feat: export compat types from /compat export (#2478)

This commit is contained in:
Luca Casonato
2024-06-03 14:32:38 +00:00
committed by GitHub
parent 2fb8606e9e
commit aa19b393e7
10 changed files with 186 additions and 143 deletions
+1
View File
@@ -4,3 +4,4 @@ vendor/
node_modules/
.docs/
.DS_Store
tmp-*
+4 -1
View File
@@ -4,7 +4,8 @@
"exports": {
".": "./src/mod.ts",
"./runtime": "./src/runtime/shared.ts",
"./dev": "./src/dev/mod.ts"
"./dev": "./src/dev/mod.ts",
"./compat": "./src/compat/mod.ts"
},
"lock": false,
"tasks": {
@@ -39,6 +40,7 @@
"@fresh/core": "./src/mod.ts",
"@fresh/core/dev": "./src/dev/mod.ts",
"@fresh/core/runtime": "./src/runtime/shared.ts",
"@fresh/core/compat": "./src/compat/mod.ts",
"@fresh/plugin-tailwind": "./plugin-tailwindcss/src/mod.ts",
"@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3",
"@preact/signals": "npm:@preact/signals@^1.2.3",
@@ -71,6 +73,7 @@
"twind/": "https://esm.sh/twind@0.16.19/"
},
"compilerOptions": {
"lib": ["dom", "dom.asynciterable", "deno.ns"],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
+1
View File
@@ -503,6 +503,7 @@ if (Deno.args.includes("build")) {
"@preact/signals": "npm:@preact/signals@^1.2.3",
} as Record<string, string>,
compilerOptions: {
lib: ["dom", "dom.asynciterable", "deno.ns"],
jsx: "react-jsx",
jsxImportSource: "preact",
},
+13
View File
@@ -0,0 +1,13 @@
// Compat with older Fresh versions
export {
type AppProps,
defineApp,
defineLayout,
defineRoute,
type ErrorPageProps,
type Handler,
type Handlers,
type LayoutProps,
type RouteContext,
type UnknownPageProps,
} from "./server.ts";
+25 -11
View File
@@ -1,33 +1,47 @@
import type { VNode } from "preact";
import type { FreshContext } from "../context.ts";
import type { HandlerByMethod } from "../handlers.ts";
import type { HandlerFn, RouteHandler } from "../handlers.ts";
/**
* @deprecated Use {@link FreshContext} instead
* @deprecated Use {@link PageProps} instead.
*/
export type AppProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
* @deprecated Use {@link PageProps} instead.
*/
export type LayoutProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
* @deprecated Use {@link PageProps} instead.
*/
export type UnknownPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
* @deprecated Use {@link PageProps} instead.
*/
export type ErrorPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
* @deprecated Use {@link FreshContext} instead.
*/
export type RouteContext<_T = never, S = Record<string, unknown>> =
FreshContext<S>;
/**
* @deprecated Use {@link RouteHandler} instead.
*/
// deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> =
HandlerByMethod<T, State>;
export type Handlers<T = any, State = Record<string, unknown>> = RouteHandler<
T,
State
>;
/**
* @deprecated Use {@link HandlerFn} instead.
*/
// deno-lint-ignore no-explicit-any
export type Handler<T = any, State = Record<string, unknown>> = HandlerFn<
T,
State
>;
function defineFn<State>(
fn: (
@@ -40,14 +54,14 @@ function defineFn<State>(
}
/**
* @deprecated Use {@link definePage} instead
* @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/
export const defineApp = defineFn;
/**
* @deprecated Use {@link definePage} instead
* @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/
export const defineRoute = defineFn;
/**
* @deprecated Use {@link definePage} instead
* @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/
export const defineLayout = defineFn;
-14
View File
@@ -18,17 +18,3 @@ export type { FreshContext, Island, PageProps } from "./context.ts";
export { createDefine, type Define } from "./define.ts";
export type { Method } from "./router.ts";
export { HttpError } from "./error.ts";
// Compat with older Fresh versions
export {
type AppProps,
defineApp,
defineLayout,
defineRoute,
type ErrorPageProps,
type Handlers,
type Handlers as Handler,
type LayoutProps,
type RouteContext,
type UnknownPageProps,
} from "./compat/server.ts";
+127 -107
View File
@@ -58,8 +58,22 @@ async function updateDenoJson(
interface ImportState {
core: Set<string>;
runtime: Set<string>;
compat: Set<string>;
}
const compat = new Set([
"defineApp",
"defineLayout",
"defineRoute",
"AppProps",
"ErrorPageProps",
"Handler",
"Handlers",
"LayoutProps",
"RouteContext",
"UnknownPageProps",
]);
export async function updateProject(dir: string) {
// Update config
await updateDenoJson(dir, (config) => {
@@ -72,30 +86,30 @@ export async function updateProject(dir: string) {
config.imports["@preact/signals"] =
`npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`;
delete config.imports["$fresh/"];
delete config.imports["@preact/signals-core"];
delete config.imports["preact-render-to-string"];
});
// Update routes folder
const routesDir = path.join(dir, "routes");
if (await dirExists(routesDir)) {
const project = new tsmorph.Project();
const sfs = project.addSourceFilesAtPaths(
path.join(routesDir, "**", "*.{js,jsx,ts,tsx}"),
);
await Promise.all(sfs.map(async (sourceFile) => {
try {
return await updateFile(sourceFile);
} catch (err) {
console.error(`Could not process ${sourceFile.getFilePath()}`);
throw err;
}
}));
}
const project = new tsmorph.Project();
const sfs = project.addSourceFilesAtPaths(
path.join(dir, "**", "*.{js,jsx,ts,tsx}"),
);
await Promise.all(sfs.map(async (sourceFile) => {
try {
return await updateFile(sourceFile);
} catch (err) {
console.error(`Could not process ${sourceFile.getFilePath()}`);
throw err;
}
}));
}
async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
const newImports: ImportState = {
core: new Set(),
runtime: new Set(),
compat: new Set(),
};
const text = sourceFile.getFullText()
@@ -108,92 +122,98 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
.replaceAll('/// <reference lib="deno.ns" />\n', "");
sourceFile.replaceWithText(text);
for (const [name, decl] of sourceFile.getExportedDeclarations()) {
if (name === "handler") {
const node = decl[0];
if (node.isKind(SyntaxKind.VariableDeclaration)) {
const init = node.getInitializer();
if (
init !== undefined && init.isKind(SyntaxKind.ObjectLiteralExpression)
) {
for (const property of init.getProperties()) {
if (property.isKind(SyntaxKind.MethodDeclaration)) {
const name = property.getName();
if (
name === "GET" || name === "POST" || name === "PATCH" ||
name === "PUT" || name === "DELETE"
) {
const body = property.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(property, newImports, true);
}
} else if (property.isKind(SyntaxKind.PropertyAssignment)) {
const init = property.getInitializer();
if (
init !== undefined &&
(init.isKind(SyntaxKind.ArrowFunction) ||
init.isKind(SyntaxKind.FunctionExpression))
) {
const body = init.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(init, newImports, true);
}
}
}
}
} else if (node.isKind(SyntaxKind.FunctionDeclaration)) {
const body = node.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(node, newImports, false);
}
} else if (name === "default" && decl.length > 0) {
const caller = decl[0];
if (caller.isKind(SyntaxKind.CallExpression)) {
const expr = caller.getExpression();
if (expr.isKind(SyntaxKind.Identifier)) {
const text = expr.getText();
if (
sourceFile.getFilePath().includes("/routes/") &&
!sourceFile.getDirectoryPath().includes("/(_")
) {
for (const [name, decl] of sourceFile.getExportedDeclarations()) {
if (name === "handler") {
const node = decl[0];
if (node.isKind(SyntaxKind.VariableDeclaration)) {
const init = node.getInitializer();
if (
text === "defineApp" || text === "defineLayout" ||
text === "defineRoute"
init !== undefined &&
init.isKind(SyntaxKind.ObjectLiteralExpression)
) {
const args = caller.getArguments();
if (args.length > 0) {
const first = args[0];
if (
first.isKind(SyntaxKind.ArrowFunction) ||
first.isKind(SyntaxKind.FunctionExpression)
) {
const body = first.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
for (const property of init.getProperties()) {
if (property.isKind(SyntaxKind.MethodDeclaration)) {
const name = property.getName();
if (
name === "GET" || name === "POST" || name === "PATCH" ||
name === "PUT" || name === "DELETE"
) {
const body = property.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(first, newImports, false);
maybePrependReqVar(property, newImports, true);
}
} else if (property.isKind(SyntaxKind.PropertyAssignment)) {
const init = property.getInitializer();
if (
init !== undefined &&
(init.isKind(SyntaxKind.ArrowFunction) ||
init.isKind(SyntaxKind.FunctionExpression))
) {
const body = init.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(init, newImports, true);
}
}
}
}
}
} else if (caller.isKind(SyntaxKind.FunctionDeclaration)) {
const body = caller.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
} else if (node.isKind(SyntaxKind.FunctionDeclaration)) {
const body = node.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(caller, newImports, false);
maybePrependReqVar(node, newImports, false);
}
} else if (name === "default" && decl.length > 0) {
const caller = decl[0];
if (caller.isKind(SyntaxKind.CallExpression)) {
const expr = caller.getExpression();
if (expr.isKind(SyntaxKind.Identifier)) {
const text = expr.getText();
if (
text === "defineApp" || text === "defineLayout" ||
text === "defineRoute"
) {
const args = caller.getArguments();
if (args.length > 0) {
const first = args[0];
if (
first.isKind(SyntaxKind.ArrowFunction) ||
first.isKind(SyntaxKind.FunctionExpression)
) {
const body = first.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(first, newImports, false);
}
}
}
}
} else if (caller.isKind(SyntaxKind.FunctionDeclaration)) {
const body = caller.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(caller, newImports, false);
}
}
}
}
@@ -215,8 +235,10 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
for (const n of d.getNamedImports()) {
const name = n.getName();
if (newImports.core.has(name)) {
newImports.core.delete(name);
newImports.core.delete(name);
if (compat.has(name)) {
n.remove();
newImports.compat.add(name);
}
}
if (newImports.core.size > 0) {
@@ -224,15 +246,15 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
d.addNamedImport(name);
});
}
removeEmptyImport(d);
} else if (specifier === "$fresh/runtime.ts") {
hasRuntimeImport = true;
d.setModuleSpecifier("@fresh/core/runtime");
for (const n of d.getNamedImports()) {
const name = n.getName();
if (newImports.runtime.has(name)) {
newImports.runtime.delete(name);
}
newImports.runtime.delete(name);
}
if (newImports.runtime.size > 0) {
newImports.runtime.forEach((name) => {
@@ -256,6 +278,12 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
namedImports: Array.from(newImports.core),
});
}
if (newImports.compat.size > 0) {
sourceFile.addImportDeclaration({
moduleSpecifier: "@fresh/core/compat",
namedImports: Array.from(newImports.compat),
});
}
await sourceFile.save();
await format(sourceFile.getFilePath());
@@ -436,11 +464,3 @@ function rewriteCtxMemberName(
rewriteCtxMemberName(children[0]);
}
}
async function dirExists(dir: string): Promise<boolean> {
try {
return (await Deno.stat(dir)).isDirectory;
} catch (_) {
return false;
}
}
+11 -8
View File
@@ -254,7 +254,7 @@ export const handler: Handlers = {
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "@fresh/core";
.toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = {
async GET(ctx) {
@@ -274,7 +274,7 @@ export const handler: Handlers = {
},
};`);
expect(files["/routes/foo.tsx"])
.toEqual(`import { Handlers } from "@fresh/core";
.toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = {
async GET(ctx) {},
@@ -285,7 +285,7 @@ export const handler: Handlers = {
};`);
expect(files["/routes/name.tsx"])
.toEqual(`import { Handlers } from "@fresh/core";
.toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = {
async GET(ctx) {
@@ -305,7 +305,7 @@ export const handler: Handlers = {
},
};`);
expect(files["/routes/name-unused.tsx"])
.toEqual(`import { Handlers } from "@fresh/core";
.toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = {
async GET(ctx) {},
@@ -425,7 +425,7 @@ export const handler: Handlers = {
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "@fresh/core";
.toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = {
async GET({ params, render, info, req }) {
@@ -470,21 +470,24 @@ export default defineRoute(async (req, ctx) => {
const files = await readFiles(dir);
expect(files["/routes/_app.tsx"])
.toEqual(`import { defineApp } from "@fresh/core";
.toEqual(`import { defineApp } from "@fresh/core/compat";
export default defineApp(async (ctx) => {
const req = ctx.req;
return null;
});`);
expect(files["/routes/_layout.tsx"])
.toEqual(`import { defineLayout } from "@fresh/core";
.toEqual(`import { defineLayout } from "@fresh/core/compat";
export default defineLayout(async (ctx) => {
const req = ctx.req;
return null;
});`);
expect(files["/routes/foo.tsx"])
.toEqual(`import { defineRoute } from "@fresh/core";
.toEqual(`import { defineRoute } from "@fresh/core/compat";
export default defineRoute(async (ctx) => {
const req = ctx.req;
+2
View File
@@ -13,6 +13,7 @@
"@fresh/core": "../src/mod.ts",
"@fresh/core/dev": "../src/dev/mod.ts",
"@fresh/core/runtime": "../src/runtime/shared.ts",
"@fresh/core/compat": "../src/compat/mod.ts",
"@fresh/plugin-tailwind": "../plugin-tailwindcss/src/mod.ts",
"@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3",
"@preact/signals": "npm:@preact/signals@^1.2.3",
@@ -37,6 +38,7 @@
"tailwindcss/plugin": "npm:/tailwindcss@3.4.1/plugin.js"
},
"compilerOptions": {
"lib": ["dom", "dom.asynciterable", "deno.ns"],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Handler } from "@fresh/core";
import type { Handlers } from "@fresh/core/compat";
export const handler: Handler<void> = {
export const handler: Handlers<void> = {
GET(ctx) {
const slug = ctx.params.slug;