From 3ad3e6ecf36cd5e800546cb75bbd4a4ca004d3d9 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Fri, 25 Jul 2025 14:33:28 +0200 Subject: [PATCH] feat: support lazily loading routes/handlers (#3131) We can improve cold start times by only loading route modules when the particular pattern matches. This PR introduces the concept of lazy middlewares, routes and handlers to do that. --- docs/canary/concepts/app.md | 99 +++++++++++++++++++++++++++ init/src/init_test.ts | 46 +++++++------ src/app.ts | 42 +++++++----- src/app_test.tsx | 61 +++++++++++++++++ src/commands.ts | 111 ++++++++++++++++++++++-------- src/context.ts | 1 - src/define.ts | 4 +- src/dev/dev_build_cache.ts | 20 +++++- src/dev/file_transformer_test.ts | 6 ++ src/dev/fs_crawl.ts | 25 ++++++- src/fs.ts | 2 + src/fs_routes.ts | 113 +++++++++++++++++++++---------- src/fs_routes_test.tsx | 2 +- src/middlewares/mod.ts | 28 ++++++-- src/middlewares/mod_test.ts | 40 +++++++++++ src/mod.ts | 2 +- src/segments.ts | 8 +-- src/test_utils.ts | 7 +- src/types.ts | 18 +++++ src/utils.ts | 5 ++ tests/partials_test.tsx | 1 - www/components/CodeBlock.tsx | 2 +- www/utils/markdown.ts | 9 +-- www/utils/prism.ts | 10 +++ 24 files changed, 529 insertions(+), 133 deletions(-) create mode 100644 www/utils/prism.ts diff --git a/docs/canary/concepts/app.md b/docs/canary/concepts/app.md index 99805b62..f8ab8683 100644 --- a/docs/canary/concepts/app.md +++ b/docs/canary/concepts/app.md @@ -17,6 +17,23 @@ const app = new App() app.listen(); ``` +All items are applied from top to bottom. This means that when you defined a +middleware _after_ a `.get()` handler, it won't be included. + +```ts +const app = new App() + .use((ctx) => { + // Will be called for all middlewares + return ctx.next(); + }) + .get("/", () => new Response("hello")) + .use((ctx) => { + // Will only be called for `/about + return ctx.next(); + }) + .get("/about", (ctx) => ctx.render(

About me

)); +``` + ## `.use()` Add one or more [middlewares](/docs/canary/concepts/middleware). Middlewares are @@ -42,6 +59,15 @@ Adding middlewares at a specific path: app.use("/foo/bar", middleware); ``` +Middlewares can also be instantiated lazily: + +```ts +app.use("/foo/bar", async () => { + const mod = await import("./path/to/my/middleware.ts"); + return mod.default; +}); +``` + ## `.get()` Respond to a `GET` request with the specified middlewares. @@ -60,6 +86,15 @@ app.get("/about", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.get("/about", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + ## `.post()` Respond to a `POST` request with the specified middlewares. @@ -80,6 +115,15 @@ app.post("/api/user/:id", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.post("/api/user/:id", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + ## `.put()` Respond to a `PUT` request with the specified middlewares. @@ -100,6 +144,15 @@ app.put("/api/user/:id", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.put("/api/user/:id", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + ## `.delete()` Respond to a `DELETE` request with the specified middlewares. @@ -120,6 +173,15 @@ app.delete("/api/user/:id", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.delete("/api/user/:id", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + ## `.head()` Respond to a `HEAD` request with the specified middlewares. @@ -138,6 +200,15 @@ app.head("/api/user/:id", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.head("/api/user/:id", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + ## `.all()` Respond to a request for all HTTP verbs with the specified middlewares. @@ -156,6 +227,34 @@ app.all("/api/foo", middleware1, middleware2, async (ctx) => { }); ``` +You can also pass lazy middlewares: + +```ts +app.all("/api/foo", async () => { + const mod = await import("./middleware-or-handler.ts"); + return mod.default; +}); +``` + +## `.fsRoute()` + +Injects all file-based routes, middlewares, layouts and error pages to the app +instance. + +```ts +app.fsRoutes(); +``` + +You can optionally pass a path where they should be mounted. + +```ts +app.fsRoutes("/foo/bar"); +``` + +> [info]: If possible, routes are lazily loaded. Routes that set a route config +> and set `routeOverride` in particular, are never lazily loaded as Fresh would +> need to load the file to get the route pattern. + ## `.route()` TODO diff --git a/init/src/init_test.ts b/init/src/init_test.ts index fa28c4f6..a5260756 100644 --- a/init/src/init_test.ts +++ b/init/src/init_test.ts @@ -165,27 +165,33 @@ Deno.test( }, ); -Deno.test("init - can start dev server", async () => { - await using tmp = await withTmpDir(); - const dir = tmp.dir; - using _promptStub = stubPrompt("."); - using _confirmStub = stubConfirm(); - await initProject(dir, [], {}); - await expectProjectFile(dir, "main.ts"); - await expectProjectFile(dir, "dev.ts"); +Deno.test({ + // TODO: For some reason this test is flaky in GitHub CI. It works when + // testing locally on windows though. Not sure what's going on. + ignore: Deno.build.os === "windows" && Deno.env.get("CI") !== undefined, + name: "init - can start dev server", + fn: async () => { + await using tmp = await withTmpDir(); + const dir = tmp.dir; + using _promptStub = stubPrompt("."); + using _confirmStub = stubConfirm(); + await initProject(dir, [], {}); + await expectProjectFile(dir, "main.ts"); + await expectProjectFile(dir, "dev.ts"); - await patchProject(dir); - await withChildProcessServer( - dir, - ["task", "dev"], - async (address) => { - await withBrowser(async (page) => { - await page.goto(address); - await page.locator("#decrement").click(); - await waitForText(page, "button + p", "2"); - }); - }, - ); + await patchProject(dir); + await withChildProcessServer( + dir, + ["task", "dev"], + async (address) => { + await withBrowser(async (page) => { + await page.goto(address); + await page.locator("#decrement").click(); + await waitForText(page, "button + p", "2"); + }); + }, + ); + }, }); Deno.test("init - can start built project", async () => { diff --git a/src/app.ts b/src/app.ts index 803ee404..0c0365f2 100644 --- a/src/app.ts +++ b/src/app.ts @@ -2,13 +2,17 @@ import { trace } from "@opentelemetry/api"; import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts"; import * as colors from "@std/fmt/colors"; -import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts"; +import { + type MaybeLazyMiddleware, + type MiddlewareFn, + runMiddlewares, +} from "./middlewares/mod.ts"; import { Context } from "./context.ts"; import { mergePath, type Method, UrlPatternRouter } from "./router.ts"; import type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; import type { BuildCache } from "./build_cache.ts"; import { HttpError } from "./error.ts"; -import type { LayoutConfig, Route } from "./types.ts"; +import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts"; import type { RouteComponent } from "./segments.ts"; import { applyCommands, @@ -182,14 +186,14 @@ export class App { /** * Add one or more middlewares at the top or the specified path. */ - use(...middleware: MiddlewareFn[]): this; - use(path: string, ...middleware: MiddlewareFn[]): this; + use(...middleware: MaybeLazyMiddleware[]): this; + use(path: string, ...middleware: MaybeLazyMiddleware[]): this; use( - pathOrMiddleware: string | MiddlewareFn, - ...middlewares: MiddlewareFn[] + pathOrMiddleware: string | MaybeLazyMiddleware, + ...middlewares: MaybeLazyMiddleware[] ): this { let pattern: string; - let fns: MiddlewareFn[]; + let fns: MaybeLazyMiddleware[]; if (typeof pathOrMiddleware === "string") { pattern = pathOrMiddleware; fns = middlewares!; @@ -234,50 +238,54 @@ export class App { return this; } - route(path: string, route: Route): this { - this.#commands.push(newRouteCmd(path, route, false)); + route( + path: string, + route: MaybeLazy>, + config?: RouteConfig, + ): this { + this.#commands.push(newRouteCmd(path, route, config, false)); return this; } /** * Add middlewares for GET requests at the specified path. */ - get(path: string, ...middlewares: MiddlewareFn[]): this { + get(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("GET", path, middlewares, false)); return this; } /** * Add middlewares for POST requests at the specified path. */ - post(path: string, ...middlewares: MiddlewareFn[]): this { + post(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("POST", path, middlewares, false)); return this; } /** * Add middlewares for PATCH requests at the specified path. */ - patch(path: string, ...middlewares: MiddlewareFn[]): this { + patch(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("PATCH", path, middlewares, false)); return this; } /** * Add middlewares for PUT requests at the specified path. */ - put(path: string, ...middlewares: MiddlewareFn[]): this { + put(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("PUT", path, middlewares, false)); return this; } /** * Add middlewares for DELETE requests at the specified path. */ - delete(path: string, ...middlewares: MiddlewareFn[]): this { + delete(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("DELETE", path, middlewares, false)); return this; } /** * Add middlewares for HEAD requests at the specified path. */ - head(path: string, ...middlewares: MiddlewareFn[]): this { + head(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("HEAD", path, middlewares, false)); return this; } @@ -285,7 +293,7 @@ export class App { /** * Add middlewares for all HTTP verbs at the specified path. */ - all(path: string, ...middlewares: MiddlewareFn[]): this { + all(path: string, ...middlewares: MaybeLazy>[]): this { this.#commands.push(newHandlerCmd("ALL", path, middlewares, false)); return this; } @@ -359,7 +367,7 @@ export class App { } } - const router = new UrlPatternRouter>(); + const router = new UrlPatternRouter>(); const { rootMiddlewares } = applyCommands( router, diff --git a/src/app_test.tsx b/src/app_test.tsx index f496fef4..7539a465 100644 --- a/src/app_test.tsx +++ b/src/app_test.tsx @@ -616,3 +616,64 @@ Deno.test("App - .route() with basePath", async () => { expect(await res.text()).toEqual("ok"); expect(res.status).toEqual(200); }); + +Deno.test("App - .use() - lazy", async () => { + const app = new App<{ text: string }>() + // deno-lint-ignore require-await + .use(async () => { + return (ctx) => { + ctx.state.text = "ok"; + return ctx.next(); + }; + }) + .get("/", (ctx) => new Response(ctx.state.text)); + + const server = new FakeServer(app.handler()); + + const res = await server.get("/"); + expect(await res.text()).toEqual("ok"); +}); + +Deno.test("App - .route() - lazy", async () => { + const app = new App() + // deno-lint-ignore require-await + .route("/", async () => { + return { handler: () => new Response("ok") }; + }); + + const server = new FakeServer(app.handler()); + + const res = await server.get("/"); + expect(await res.text()).toEqual("ok"); +}); + +Deno.test("App - .get/post/patch/put/delete/head/all() - lazy", async () => { + const app = new App() + .get("/", () => Promise.resolve(() => new Response("ok"))) + .post("/", () => Promise.resolve(() => new Response("ok"))) + .patch("/", () => Promise.resolve(() => new Response("ok"))) + .delete("/", () => Promise.resolve(() => new Response("ok"))) + .put("/", () => Promise.resolve(() => new Response("ok"))) + .head("/", () => Promise.resolve(() => new Response("ok"))) + .all("/", () => Promise.resolve(() => new Response("ok"))); + + const server = new FakeServer(app.handler()); + + let res = await server.get("/"); + expect(await res.text()).toEqual("ok"); + + res = await server.post("/"); + expect(await res.text()).toEqual("ok"); + + res = await server.put("/"); + expect(await res.text()).toEqual("ok"); + + res = await server.patch("/"); + expect(await res.text()).toEqual("ok"); + + res = await server.delete("/"); + expect(await res.text()).toEqual("ok"); + + res = await server.head("/"); + expect(await res.text()).toEqual("ok"); +}); diff --git a/src/commands.ts b/src/commands.ts index e66fb6ce..0b245ba8 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1,6 +1,6 @@ import { HttpError } from "./error.ts"; import { isHandlerByMethod, type PageResponse } from "./handlers.ts"; -import type { MiddlewareFn } from "./middlewares/mod.ts"; +import type { MaybeLazyMiddleware, MiddlewareFn } from "./middlewares/mod.ts"; import { mergePath, type Method, type Router } from "./router.ts"; import { getOrCreateSegment, @@ -10,7 +10,8 @@ import { type Segment, segmentToMiddlewares, } from "./segments.ts"; -import type { LayoutConfig, Route } from "./types.ts"; +import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts"; +import { isLazy } from "./utils.ts"; export const DEFAULT_NOT_FOUND = (): Promise => { throw new HttpError(404); @@ -100,12 +101,12 @@ export function newLayoutCmd( export interface MiddlewareCmd { type: CommandType.Middleware; pattern: string; - fns: MiddlewareFn[]; + fns: MaybeLazyMiddleware[]; includeLastSegment: boolean; } export function newMiddlewareCmd( pattern: string, - fns: MiddlewareFn[], + fns: MaybeLazyMiddleware[], includeLastSegment: boolean, ): MiddlewareCmd { return { type: CommandType.Middleware, pattern, fns, includeLastSegment }; @@ -129,29 +130,48 @@ export function newNotFoundCmd( export interface RouteCommand { type: CommandType.Route; pattern: string; - route: Route; + route: MaybeLazy>; + config: RouteConfig | undefined; includeLastSegment: boolean; } export function newRouteCmd( pattern: string, - route: Route, + route: MaybeLazy>, + config: RouteConfig | undefined, includeLastSegment: boolean, ): RouteCommand { - ensureHandler(route); - return { type: CommandType.Route, pattern, route, includeLastSegment }; + let normalized; + if (isLazy(route)) { + normalized = async () => { + const result = await route(); + ensureHandler(result); + return result; + }; + } else { + ensureHandler(route); + normalized = route; + } + + return { + type: CommandType.Route, + pattern, + route: normalized, + config, + includeLastSegment, + }; } export interface HandlerCommand { type: CommandType.Handler; pattern: string; method: Method | "ALL"; - fns: MiddlewareFn[]; + fns: MaybeLazy>[]; includeLastSegment: boolean; } export function newHandlerCmd( method: Method | "ALL", pattern: string, - fns: MiddlewareFn[], + fns: MaybeLazy>[], includeLastSegment: boolean, ): HandlerCommand { return { @@ -181,10 +201,10 @@ export type Command = | FsRouteCommand; export function applyCommands( - router: Router>, + router: Router>, commands: Command[], basePath: string, -): { rootMiddlewares: MiddlewareFn[] } { +): { rootMiddlewares: MaybeLazyMiddleware[] } { const root = newSegment("", null); applyCommandsInner(root, router, commands, basePath); @@ -194,7 +214,7 @@ export function applyCommands( function applyCommandsInner( root: Segment, - router: Router>, + router: Router>, commands: Command[], basePath: string, ) { @@ -241,7 +261,7 @@ function applyCommandsInner( break; } case CommandType.Route: { - const { pattern, route } = cmd; + const { pattern, route, config } = cmd; const segment = getOrCreateSegment( root, pattern, @@ -249,24 +269,55 @@ function applyCommandsInner( ); const fns = segmentToMiddlewares(segment); - fns.push((ctx) => renderRoute(ctx, route)); + if (isLazy(route)) { + const routePath = mergePath( + basePath, + config?.routeOverride ?? pattern, + ); - const routePath = mergePath( - basePath, - route.config?.routeOverride ?? pattern, - ); + let def: Route; + fns.push(async (ctx) => { + if (def === undefined) { + def = await route(); + } - if (typeof route.handler === "function") { - router.add("GET", routePath, fns); - router.add("DELETE", routePath, fns); - router.add("HEAD", routePath, fns); - router.add("OPTIONS", routePath, fns); - router.add("PATCH", routePath, fns); - router.add("POST", routePath, fns); - router.add("PUT", routePath, fns); - } else if (isHandlerByMethod(route.handler!)) { - for (const method of Object.keys(route.handler)) { - router.add(method as Method, routePath, fns); + return renderRoute(ctx, def); + }); + + if (config === undefined || config.methods === "ALL") { + router.add("GET", routePath, fns); + router.add("DELETE", routePath, fns); + router.add("HEAD", routePath, fns); + router.add("OPTIONS", routePath, fns); + router.add("PATCH", routePath, fns); + router.add("POST", routePath, fns); + router.add("PUT", routePath, fns); + } else if (Array.isArray(config.methods)) { + for (let i = 0; i < config.methods.length; i++) { + const method = config.methods[i]; + router.add(method, routePath, fns); + } + } + } else { + fns.push((ctx) => renderRoute(ctx, route)); + + const routePath = mergePath( + basePath, + route.config?.routeOverride ?? pattern, + ); + + if (typeof route.handler === "function") { + router.add("GET", routePath, fns); + router.add("DELETE", routePath, fns); + router.add("HEAD", routePath, fns); + router.add("OPTIONS", routePath, fns); + router.add("PATCH", routePath, fns); + router.add("POST", routePath, fns); + router.add("PUT", routePath, fns); + } else if (isHandlerByMethod(route.handler!)) { + for (const method of Object.keys(route.handler)) { + router.add(method as Method, routePath, fns); + } } } break; diff --git a/src/context.ts b/src/context.ts index 469e083f..7d6d5490 100644 --- a/src/context.ts +++ b/src/context.ts @@ -110,7 +110,6 @@ export class Context { #buildCache: BuildCache; - // FIXME: remove after switching to Component!: FunctionComponent; static { diff --git a/src/define.ts b/src/define.ts index 5199cc23..fbb0bb79 100644 --- a/src/define.ts +++ b/src/define.ts @@ -133,7 +133,9 @@ export interface Define { * * @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type. */ - middleware>(middleware: M): typeof middleware; + middleware | Middleware[]>( + middleware: M, + ): typeof middleware; } /** diff --git a/src/dev/dev_build_cache.ts b/src/dev/dev_build_cache.ts index 01d4d273..8dd7db43 100644 --- a/src/dev/dev_build_cache.ts +++ b/src/dev/dev_build_cache.ts @@ -27,7 +27,9 @@ export interface IslandModChunk { browser: string | null; } -export type FsRouteFileNoMod = Omit, "mod">; +export type FsRouteFileNoMod = Omit, "mod"> & { + lazy: boolean; +}; export interface FsRoute { id: string; @@ -195,7 +197,9 @@ export class MemoryBuildCache implements DevBuildCache { const fileUrl = path.toFileUrl(file.filePath); return { ...file, - mod: await import(fileUrl.href), + mod: file.lazy + ? () => import(fileUrl.href) + : await import(fileUrl.href), }; })); this.#commands = fsItemsToCommands(files); @@ -368,9 +372,11 @@ ${ ${ this.#fsRoutes.files .map((item, i) => { + if (item.lazy) return null; const spec = pathToSpec(path.relative(outDir, item.filePath)); return `import * as fsRoute_${i} from "${spec}"`; }) + .filter(Boolean) .join("\n") } @@ -408,7 +414,15 @@ ${ const type = JSON.stringify(item.type); const routePattern = JSON.stringify(item.routePattern); - return ` { id: ${id}, mod: fsRoute_${i}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`; + let mod = ""; + if (item.lazy) { + const spec = pathToSpec(path.relative(outDir, item.filePath)); + mod = `() => import(${JSON.stringify(spec)})`; + } else { + mod = `fsRoute_${i}`; + } + + return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`; }) .join("\n") } diff --git a/src/dev/file_transformer_test.ts b/src/dev/file_transformer_test.ts index b5bb424e..a86150e6 100644 --- a/src/dev/file_transformer_test.ts +++ b/src/dev/file_transformer_test.ts @@ -17,6 +17,12 @@ function testTransformer(files: Record, root = "/") { const buf = new TextEncoder().encode(content); return Promise.resolve(buf); }, + readTextFile: (file) => { + if (file instanceof URL) throw new Error("Not supported"); + // deno-lint-ignore no-explicit-any + const content = (files as any)[file]; + return Promise.resolve(content); + }, }; return new FileTransformer(mockFs, root); } diff --git a/src/dev/fs_crawl.ts b/src/dev/fs_crawl.ts index 64769a96..dab12f67 100644 --- a/src/dev/fs_crawl.ts +++ b/src/dev/fs_crawl.ts @@ -5,6 +5,7 @@ import * as path from "@std/path"; import { pathToPattern } from "../router.ts"; import { CommandType } from "../commands.ts"; import { sortRoutePaths } from "../fs_routes.ts"; +import type { RouteConfig } from "../types.ts"; const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/; @@ -18,7 +19,7 @@ export async function crawlRouteDir( await walkDir( fs, routeDir, - (entry) => { + async (entry) => { // A `(_islands)` path segment is a local island folder. // Any route path segment wrapped in `(_...)` is ignored // during route collection. @@ -30,10 +31,12 @@ export async function crawlRouteDir( return; } + let lazy = false; const relative = path.relative(routeDir, entry.path); const url = new URL(relative, "http://localhost/"); const id = url.pathname.slice(0, url.pathname.lastIndexOf(".")); + let overrideConfig: RouteConfig | undefined; let pattern = "*"; let routePattern = pattern; let type = CommandType.Route; @@ -71,9 +74,27 @@ export async function crawlRouteDir( } routePattern = pathToPattern(id.slice(1)); + + const code = await fs.readTextFile(entry.path); + lazy = !code.includes("routeOverride"); + + // TODO: We could do an AST parse here to detect the + // kind of handler that's used to get a more accurate + // list of methods this route supports. + overrideConfig = { + methods: "ALL", + }; } - files.push({ id, filePath: entry.path, type, pattern, routePattern }); + files.push({ + id, + filePath: entry.path, + type, + pattern, + routePattern, + lazy, + overrideConfig, + }); }, ignore, ); diff --git a/src/fs.ts b/src/fs.ts index 51a48ea4..0ece27f2 100644 --- a/src/fs.ts +++ b/src/fs.ts @@ -9,6 +9,7 @@ export interface FsAdapter { isDirectory(path: string | URL): Promise; mkdirp(dir: string): Promise; readFile(path: string | URL): Promise; + readTextFile(path: string | URL): Promise; } export const fsAdapter: FsAdapter = { @@ -33,4 +34,5 @@ export const fsAdapter: FsAdapter = { } }, readFile: Deno.readFile, + readTextFile: Deno.readTextFile, }; diff --git a/src/fs_routes.ts b/src/fs_routes.ts index 8f4fc439..e166886d 100644 --- a/src/fs_routes.ts +++ b/src/fs_routes.ts @@ -1,5 +1,5 @@ import type { AnyComponent } from "preact"; -import type { RouteConfig } from "./types.ts"; +import type { MaybeLazy, Route, RouteConfig } from "./types.ts"; import type { HandlerByMethod, RouteHandler } from "./handlers.ts"; import type { MiddlewareFn } from "./middlewares/mod.ts"; import type { AsyncAnyComponent } from "./render.ts"; @@ -15,6 +15,7 @@ import { newNotFoundCmd, newRouteCmd, } from "./commands.ts"; +import { isLazy } from "./utils.ts"; export interface FreshFsMod { config?: RouteConfig; @@ -26,12 +27,13 @@ export interface FreshFsMod { } export interface FsRouteFile { - id: string; // FIXME remove? + id: string; filePath: string; - mod: FreshFsMod; + mod: MaybeLazy>; pattern: string; type: CommandType; routePattern: string; + overrideConfig: RouteConfig | undefined; } // deno-lint-ignore no-explicit-any @@ -62,23 +64,14 @@ export function fsItemsToCommands( const commands: Command[] = []; for (let i = 0; i < items.length; i++) { - const { filePath, type, mod, pattern, routePattern } = items[i]; - - if (!isFreshFile(mod)) { - throw new Error( - `Expected a route, middleware, layout or error template, but couldn't find relevant exports in: ${filePath}`, - ); - } - - const handlers = mod.handlers ?? mod.handler ?? null; - if (typeof handlers === "function" && handlers.length > 1) { - throw new Error( - `Handlers must only have one argument but found more than one. Check the function signature in: ${filePath}`, - ); - } + const item = items[i]; + const { filePath, type, mod: rawMod, pattern, routePattern } = item; switch (type) { case CommandType.Middleware: { + if (isLazy(rawMod)) continue; + const { handlers, mod } = validateFsMod(filePath, rawMod); + let middlewares = (handlers ?? mod.default) as unknown as | MiddlewareFn | MiddlewareFn[] @@ -88,7 +81,7 @@ export function fsItemsToCommands( if (isHandlerByMethod(middlewares)) { warnInvalidRoute( - "Middleware does not support object handlers with GET, POST, etc.", + `Middleware does not support object handlers with GET, POST, etc. in ${filePath}`, ); continue; } @@ -97,12 +90,11 @@ export function fsItemsToCommands( middlewares = [middlewares]; } - commands.push( - newMiddlewareCmd(pattern, middlewares, true), - ); + commands.push(newMiddlewareCmd(pattern, middlewares, true)); continue; } case CommandType.Layout: { + const { handlers, mod } = validateFsMod(filePath, rawMod); if (handlers !== null) { warnInvalidRoute("Layout does not support handlers"); } @@ -112,6 +104,7 @@ export function fsItemsToCommands( continue; } case CommandType.Error: { + const { handlers, mod } = validateFsMod(filePath, rawMod); commands.push(newErrorCmd( pattern, { @@ -125,6 +118,7 @@ export function fsItemsToCommands( continue; } case CommandType.NotFound: { + const { handlers, mod } = validateFsMod(filePath, rawMod); commands.push(newNotFoundCmd({ config: mod.config, component: mod.default, @@ -134,25 +128,35 @@ export function fsItemsToCommands( continue; } case CommandType.App: { + const { mod } = validateFsMod(filePath, rawMod); if (mod.default === undefined) continue; commands.push(newAppCmd(mod.default)); continue; } case CommandType.Route: { - commands.push(newRouteCmd( - pattern, - { - config: { - ...mod.config, - routeOverride: mod.config?.routeOverride ?? routePattern, - }, - // deno-lint-ignore no-explicit-any - handler: (handlers as any) ?? undefined, - component: mod.default, - }, - false, - )); + let normalized; + // Merge configs + let config: RouteConfig = {}; + if (isLazy(rawMod)) { + normalized = async () => { + const result = await rawMod(); + return normalizeRoute(filePath, result, routePattern); + }; + + config.methods = item.overrideConfig?.methods ?? "ALL"; + config.routeOverride = item.overrideConfig?.routeOverride ?? + routePattern; + } else { + normalized = normalizeRoute(filePath, rawMod, routePattern); + if (rawMod.config) { + config = rawMod.config; + } + } + + commands.push( + newRouteCmd(pattern, normalized, config, false), + ); continue; } case CommandType.Handler: @@ -279,3 +283,44 @@ function getRoutePathScore(char: string, s: string, i: number): number { return 2; } + +export function validateFsMod( + filePath: string, + mod: unknown, +): { + handlers: RouteHandler | HandlerFn[] | null; + mod: FreshFsMod; +} { + if (!isFreshFile(mod)) { + throw new Error( + `Expected a route, middleware, layout or error template, but couldn't find relevant exports in: ${filePath}`, + ); + } + + const handlers = mod.handlers ?? mod.handler ?? null; + if (typeof handlers === "function" && handlers.length > 1) { + throw new Error( + `Handlers must only have one argument but found more than one. Check the function signature in: ${filePath}`, + ); + } + + return { handlers, mod }; +} + +function normalizeRoute( + filePath: string, + rawMod: FreshFsMod, + routePattern: string, +): Route { + const { handlers, mod } = validateFsMod(filePath, rawMod); + + return { + config: { + ...mod.config, + routeOverride: mod.config?.routeOverride ?? routePattern, + }, + // deno-lint-ignore no-explicit-any + handler: (handlers as any) ?? undefined, + component: mod.default, + }; +} diff --git a/src/fs_routes_test.tsx b/src/fs_routes_test.tsx index fca05eed..b76c14c8 100644 --- a/src/fs_routes_test.tsx +++ b/src/fs_routes_test.tsx @@ -1480,7 +1480,7 @@ Deno.test("fsRoutes - warn on _middleware with object handler", async () => { expect(warnSpy.fake).toHaveBeenCalledTimes(1); expect(warnSpy.fake).toHaveBeenLastCalledWith( - "🍋 %c[WARNING] Unsupported route config: Middleware does not support object handlers with GET, POST, etc.", + "🍋 %c[WARNING] Unsupported route config: Middleware does not support object handlers with GET, POST, etc. in routes/_middleware.ts", expect.any(String), ); }); diff --git a/src/middlewares/mod.ts b/src/middlewares/mod.ts index ca0b8f7a..fcbf3ded 100644 --- a/src/middlewares/mod.ts +++ b/src/middlewares/mod.ts @@ -71,32 +71,46 @@ import type { Define as _Define } from "../define.ts"; * app.use(redirectMiddleware); * ``` */ -export type MiddlewareFn = ( +export type Middleware = ( ctx: Context, ) => Response | Promise; /** - * A single middleware function, or an array of middleware functions. For - * further information, see {@link MiddlewareFn}. + * @deprecated Use {@linkcode Middleware} instead. */ -export type Middleware = MiddlewareFn | MiddlewareFn[]; +export type MiddlewareFn = Middleware; + +/** + * A lazy {@linkcode Middleware} + */ +export type MaybeLazyMiddleware = ( + ctx: Context, +) => Response | Promise>; export function runMiddlewares( - middlewares: MiddlewareFn[], + middlewares: MaybeLazyMiddleware[], ctx: Context, ): Promise { let fn = ctx.next; let i = middlewares.length; while (i--) { const local = fn; - const next = middlewares[i]; + let next = middlewares[i]; + const idx = i; fn = async () => { const internals = getInternals(ctx); const { app: prevApp, layouts: prevLayouts } = internals; ctx.next = local; try { - return await next(ctx); + const result = await next(ctx); + if (typeof result === "function") { + middlewares[idx] = result; + next = result; + return await result(ctx); + } + + return result; } catch (err) { ctx.error = err; throw err; diff --git a/src/middlewares/mod_test.ts b/src/middlewares/mod_test.ts index de2f8962..6bf86cb4 100644 --- a/src/middlewares/mod_test.ts +++ b/src/middlewares/mod_test.ts @@ -2,6 +2,7 @@ import { runMiddlewares } from "./mod.ts"; import { expect } from "@std/expect"; import { serveMiddleware } from "../test_utils.ts"; import type { MiddlewareFn } from "./mod.ts"; +import type { Lazy, MaybeLazy } from "../types.ts"; Deno.test("runMiddleware", async () => { const middlewares: MiddlewareFn<{ text: string }>[] = [ @@ -137,3 +138,42 @@ Deno.test("runMiddleware - throws errors", async () => { expect(thrownB).toBeInstanceOf(Error); expect(thrownC).toBeInstanceOf(Error); }); + +Deno.test("runMiddleware - lazy middlewares", async () => { + type State = { text: string }; + + let called = 0; + // deno-lint-ignore require-await + const lazy: Lazy> = async () => { + called++; + return (ctx) => { + ctx.state.text += "_lazy"; + return ctx.next(); + }; + }; + + const middlewares: MaybeLazy>[] = [ + async (ctx) => { + ctx.state.text = "A"; + return await ctx.next(); + }, + lazy, + (ctx) => { + ctx.state.text += "_B"; + return new Response(ctx.state.text); + }, + ]; + + const server = serveMiddleware<{ text: string }>((ctx) => + runMiddlewares(middlewares, ctx) + ); + + let res = await server.get("/"); + expect(await res.text()).toEqual("A_lazy_B"); + expect(called).toEqual(1); + + // Lazy middlewares should only be initialized ones + res = await server.get("/"); + expect(await res.text()).toEqual("A_lazy_B"); + expect(called).toEqual(1); +}); diff --git a/src/mod.ts b/src/mod.ts index 8038435d..092bcdd2 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -8,7 +8,7 @@ export { type RouteData, type RouteHandler, } from "./handlers.ts"; -export type { LayoutConfig, RouteConfig } from "./types.ts"; +export type { LayoutConfig, Lazy, MaybeLazy, RouteConfig } from "./types.ts"; export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; export { cors, type CORSOptions } from "./middlewares/cors.ts"; diff --git a/src/segments.ts b/src/segments.ts index 10d2ccdd..46c7673f 100644 --- a/src/segments.ts +++ b/src/segments.ts @@ -1,5 +1,5 @@ import type { AnyComponent } from "preact"; -import type { MiddlewareFn } from "./middlewares/mod.ts"; +import type { MaybeLazyMiddleware, MiddlewareFn } from "./middlewares/mod.ts"; import { type Method, patternToSegments } from "./router.ts"; import type { LayoutConfig, Route } from "./types.ts"; import { type Context, getInternals } from "./context.ts"; @@ -18,7 +18,7 @@ export type RouteComponent = export interface Segment { pattern: string; - middlewares: MiddlewareFn[]; + middlewares: MaybeLazyMiddleware[]; layout: { component: RouteComponent; config: LayoutConfig | null; @@ -74,8 +74,8 @@ export function getOrCreateSegment( export function segmentToMiddlewares( segment: Segment, -): MiddlewareFn[] { - const result: MiddlewareFn[] = []; +): MaybeLazyMiddleware[] { + const result: MaybeLazyMiddleware[] = []; const stack: Segment[] = []; let current: Segment | null = segment; diff --git a/src/test_utils.ts b/src/test_utils.ts index 6a17f776..fa408dc1 100644 --- a/src/test_utils.ts +++ b/src/test_utils.ts @@ -103,13 +103,12 @@ export function createFakeFs(files: Record): FsAdapter { return { cwd: () => ".", async *walk(_root) { - // FIXME: ignore for (const file of Object.keys(files)) { const entry: WalkEntry = { isDirectory: false, isFile: true, isSymlink: false, - name: file, // FIXME? + name: file, path: file, }; yield entry; @@ -122,6 +121,10 @@ export function createFakeFs(files: Record): FsAdapter { async mkdirp(_dir: string) { }, readFile: Deno.readFile, + // deno-lint-ignore require-await + async readTextFile(path) { + return String(files[String(path)]); + }, }; } diff --git a/src/types.ts b/src/types.ts index 8410f4a5..a9d229e4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,5 @@ import type { RouteHandler } from "./handlers.ts"; +import type { Method } from "./router.ts"; import type { RouteComponent } from "./segments.ts"; export interface RouteConfig { @@ -29,6 +30,12 @@ export interface RouteConfig { * Default: `false` */ skipAppWrapper?: boolean; + /** + * Which method to use when loading this route lazily. This is only used + * for lazy routes. + * Default: `ALL` + */ + methods?: "ALL" | Method[]; } export interface LayoutConfig { @@ -51,6 +58,17 @@ export interface Route { handler?: RouteHandler; } +/** + * Lazily construct items like middlewares, handlers, etc by wrapping them + * in a function. + */ +export type Lazy = () => Promise; + +/** + * Return T or lazy version of T + */ +export type MaybeLazy = T | Lazy; + // TODO: Uncomment once JSR supports global types // declare global { // namespace preact.createElement.JSX { diff --git a/src/utils.ts b/src/utils.ts index 5105da7f..0c98e60a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,5 @@ import * as path from "@std/path"; +import type { Lazy, MaybeLazy } from "./types.ts"; export function assertInDir( filePath: string, @@ -68,3 +69,7 @@ const PATH_TO_SPEC = /[\\/]+/g; export function pathToSpec(str: string): string { return str.replaceAll(PATH_TO_SPEC, "/"); } + +export function isLazy(value: MaybeLazy): value is Lazy { + return typeof value === "function"; +} diff --git a/tests/partials_test.tsx b/tests/partials_test.tsx index eb70545c..2e8770c6 100644 --- a/tests/partials_test.tsx +++ b/tests/partials_test.tsx @@ -76,7 +76,6 @@ Deno.test({ fn: async () => { const app = testApp() .get("/partial", (ctx) => { - // FIXME: Add outer document return ctx.render( diff --git a/www/components/CodeBlock.tsx b/www/components/CodeBlock.tsx index b070d013..9e6354da 100644 --- a/www/components/CodeBlock.tsx +++ b/www/components/CodeBlock.tsx @@ -1,4 +1,4 @@ -import Prism from "prismjs"; +import { Prism } from "../utils/prism.ts"; export function CodeBlock( { code, lang }: { code: string; lang: "js" | "ts" | "jsx" | "md" | "bash" }, diff --git a/www/utils/markdown.ts b/www/utils/markdown.ts index 72230e97..2af3367a 100644 --- a/www/utils/markdown.ts +++ b/www/utils/markdown.ts @@ -1,11 +1,3 @@ -import Prism from "prismjs"; -import "prismjs/components/prism-jsx.js"; -import "prismjs/components/prism-typescript.js"; -import "prismjs/components/prism-tsx.js"; -import "prismjs/components/prism-diff.js"; -import "prismjs/components/prism-json.js"; -import "prismjs/components/prism-bash.js"; -import "prismjs/components/prism-yaml.js"; import denoJson from "../../deno.json" with { type: "json" }; export { extractYaml as frontMatter } from "@std/front-matter"; @@ -14,6 +6,7 @@ import * as Marked from "marked"; import { escape as escapeHtml } from "@std/html"; import { mangle } from "marked-mangle"; import GitHubSlugger from "github-slugger"; +import { Prism } from "./prism.ts"; const slugger = new GitHubSlugger(); diff --git a/www/utils/prism.ts b/www/utils/prism.ts new file mode 100644 index 00000000..67065003 --- /dev/null +++ b/www/utils/prism.ts @@ -0,0 +1,10 @@ +import Prism from "prismjs"; +import "prismjs/components/prism-jsx.js"; +import "prismjs/components/prism-typescript.js"; +import "prismjs/components/prism-tsx.js"; +import "prismjs/components/prism-diff.js"; +import "prismjs/components/prism-json.js"; +import "prismjs/components/prism-bash.js"; +import "prismjs/components/prism-yaml.js"; + +export { Prism };