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.
This commit is contained in:
Marvin Hagemeister
2025-07-25 14:33:28 +02:00
committed by GitHub
parent 097fb6b27c
commit 3ad3e6ecf3
24 changed files with 529 additions and 133 deletions
+99
View File
@@ -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(<h1>About me</h1>));
```
## `.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
+26 -20
View File
@@ -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 () => {
+25 -17
View File
@@ -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<State> {
/**
* Add one or more middlewares at the top or the specified path.
*/
use(...middleware: MiddlewareFn<State>[]): this;
use(path: string, ...middleware: MiddlewareFn<State>[]): this;
use(...middleware: MaybeLazyMiddleware<State>[]): this;
use(path: string, ...middleware: MaybeLazyMiddleware<State>[]): this;
use(
pathOrMiddleware: string | MiddlewareFn<State>,
...middlewares: MiddlewareFn<State>[]
pathOrMiddleware: string | MaybeLazyMiddleware<State>,
...middlewares: MaybeLazyMiddleware<State>[]
): this {
let pattern: string;
let fns: MiddlewareFn<State>[];
let fns: MaybeLazyMiddleware<State>[];
if (typeof pathOrMiddleware === "string") {
pattern = pathOrMiddleware;
fns = middlewares!;
@@ -234,50 +238,54 @@ export class App<State> {
return this;
}
route(path: string, route: Route<State>): this {
this.#commands.push(newRouteCmd(path, route, false));
route(
path: string,
route: MaybeLazy<Route<State>>,
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<State>[]): this {
get(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): 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<State>[]): this {
post(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): 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<State>[]): this {
patch(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): 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<State>[]): this {
put(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): 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<State>[]): this {
delete(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): 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<State>[]): this {
head(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("HEAD", path, middlewares, false));
return this;
}
@@ -285,7 +293,7 @@ export class App<State> {
/**
* Add middlewares for all HTTP verbs at the specified path.
*/
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
all(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("ALL", path, middlewares, false));
return this;
}
@@ -359,7 +367,7 @@ export class App<State> {
}
}
const router = new UrlPatternRouter<MiddlewareFn<State>>();
const router = new UrlPatternRouter<MaybeLazyMiddleware<State>>();
const { rootMiddlewares } = applyCommands(
router,
+61
View File
@@ -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");
});
+81 -30
View File
@@ -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<Response> => {
throw new HttpError(404);
@@ -100,12 +101,12 @@ export function newLayoutCmd<State>(
export interface MiddlewareCmd<State> {
type: CommandType.Middleware;
pattern: string;
fns: MiddlewareFn<State>[];
fns: MaybeLazyMiddleware<State>[];
includeLastSegment: boolean;
}
export function newMiddlewareCmd<State>(
pattern: string,
fns: MiddlewareFn<State>[],
fns: MaybeLazyMiddleware<State>[],
includeLastSegment: boolean,
): MiddlewareCmd<State> {
return { type: CommandType.Middleware, pattern, fns, includeLastSegment };
@@ -129,29 +130,48 @@ export function newNotFoundCmd<State>(
export interface RouteCommand<State> {
type: CommandType.Route;
pattern: string;
route: Route<State>;
route: MaybeLazy<Route<State>>;
config: RouteConfig | undefined;
includeLastSegment: boolean;
}
export function newRouteCmd<State>(
pattern: string,
route: Route<State>,
route: MaybeLazy<Route<State>>,
config: RouteConfig | undefined,
includeLastSegment: boolean,
): RouteCommand<State> {
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<State> {
type: CommandType.Handler;
pattern: string;
method: Method | "ALL";
fns: MiddlewareFn<State>[];
fns: MaybeLazy<MiddlewareFn<State>>[];
includeLastSegment: boolean;
}
export function newHandlerCmd<State>(
method: Method | "ALL",
pattern: string,
fns: MiddlewareFn<State>[],
fns: MaybeLazy<MiddlewareFn<State>>[],
includeLastSegment: boolean,
): HandlerCommand<State> {
return {
@@ -181,10 +201,10 @@ export type Command<State> =
| FsRouteCommand<State>;
export function applyCommands<State>(
router: Router<MiddlewareFn<State>>,
router: Router<MaybeLazyMiddleware<State>>,
commands: Command<State>[],
basePath: string,
): { rootMiddlewares: MiddlewareFn<State>[] } {
): { rootMiddlewares: MaybeLazyMiddleware<State>[] } {
const root = newSegment<State>("", null);
applyCommandsInner(root, router, commands, basePath);
@@ -194,7 +214,7 @@ export function applyCommands<State>(
function applyCommandsInner<State>(
root: Segment<State>,
router: Router<MiddlewareFn<State>>,
router: Router<MaybeLazyMiddleware<State>>,
commands: Command<State>[],
basePath: string,
) {
@@ -241,7 +261,7 @@ function applyCommandsInner<State>(
break;
}
case CommandType.Route: {
const { pattern, route } = cmd;
const { pattern, route, config } = cmd;
const segment = getOrCreateSegment(
root,
pattern,
@@ -249,24 +269,55 @@ function applyCommandsInner<State>(
);
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<State>;
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;
-1
View File
@@ -110,7 +110,6 @@ export class Context<State> {
#buildCache: BuildCache<State>;
// FIXME: remove after switching to <Slot />
Component!: FunctionComponent;
static {
+3 -1
View File
@@ -133,7 +133,9 @@ export interface Define<State> {
*
* @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type.
*/
middleware<M extends Middleware<State>>(middleware: M): typeof middleware;
middleware<M extends Middleware<State> | Middleware<State>[]>(
middleware: M,
): typeof middleware;
}
/**
+17 -3
View File
@@ -27,7 +27,9 @@ export interface IslandModChunk {
browser: string | null;
}
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod">;
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod"> & {
lazy: boolean;
};
export interface FsRoute<State> {
id: string;
@@ -195,7 +197,9 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
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")
}
+6
View File
@@ -17,6 +17,12 @@ function testTransformer(files: Record<string, string>, 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);
}
+23 -2
View File
@@ -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<State>(
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<State>(
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<State>(
}
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,
);
+2
View File
@@ -9,6 +9,7 @@ export interface FsAdapter {
isDirectory(path: string | URL): Promise<boolean>;
mkdirp(dir: string): Promise<void>;
readFile(path: string | URL): Promise<Uint8Array>;
readTextFile(path: string | URL): Promise<string>;
}
export const fsAdapter: FsAdapter = {
@@ -33,4 +34,5 @@ export const fsAdapter: FsAdapter = {
}
},
readFile: Deno.readFile,
readTextFile: Deno.readTextFile,
};
+79 -34
View File
@@ -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<State> {
config?: RouteConfig;
@@ -26,12 +27,13 @@ export interface FreshFsMod<State> {
}
export interface FsRouteFile<State> {
id: string; // FIXME remove?
id: string;
filePath: string;
mod: FreshFsMod<State>;
mod: MaybeLazy<FreshFsMod<State>>;
pattern: string;
type: CommandType;
routePattern: string;
overrideConfig: RouteConfig | undefined;
}
// deno-lint-ignore no-explicit-any
@@ -62,23 +64,14 @@ export function fsItemsToCommands<State>(
const commands: Command<State>[] = [];
for (let i = 0; i < items.length; i++) {
const { filePath, type, mod, pattern, routePattern } = items[i];
if (!isFreshFile<State>(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<State>
| MiddlewareFn<State>[]
@@ -88,7 +81,7 @@ export function fsItemsToCommands<State>(
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<State>(
middlewares = [middlewares];
}
commands.push(
newMiddlewareCmd(pattern, middlewares, true),
);
commands.push(newMiddlewareCmd(pattern, middlewares, true));
continue;
}
case CommandType.Layout: {
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
if (handlers !== null) {
warnInvalidRoute("Layout does not support handlers");
}
@@ -112,6 +104,7 @@ export function fsItemsToCommands<State>(
continue;
}
case CommandType.Error: {
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
commands.push(newErrorCmd(
pattern,
{
@@ -125,6 +118,7 @@ export function fsItemsToCommands<State>(
continue;
}
case CommandType.NotFound: {
const { handlers, mod } = validateFsMod<State>(filePath, rawMod);
commands.push(newNotFoundCmd({
config: mod.config,
component: mod.default,
@@ -134,25 +128,35 @@ export function fsItemsToCommands<State>(
continue;
}
case CommandType.App: {
const { mod } = validateFsMod<State>(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<State>(
filePath: string,
mod: unknown,
): {
handlers: RouteHandler<unknown, State> | HandlerFn<unknown, State>[] | null;
mod: FreshFsMod<State>;
} {
if (!isFreshFile<State>(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<State>(
filePath: string,
rawMod: FreshFsMod<State>,
routePattern: string,
): Route<State> {
const { handlers, mod } = validateFsMod<State>(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,
};
}
+1 -1
View File
@@ -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),
);
});
+21 -7
View File
@@ -71,32 +71,46 @@ import type { Define as _Define } from "../define.ts";
* app.use(redirectMiddleware);
* ```
*/
export type MiddlewareFn<State> = (
export type Middleware<State> = (
ctx: Context<State>,
) => Response | Promise<Response>;
/**
* A single middleware function, or an array of middleware functions. For
* further information, see {@link MiddlewareFn}.
* @deprecated Use {@linkcode Middleware} instead.
*/
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
export type MiddlewareFn<State> = Middleware<State>;
/**
* A lazy {@linkcode Middleware}
*/
export type MaybeLazyMiddleware<State> = (
ctx: Context<State>,
) => Response | Promise<Response | MiddlewareFn<State>>;
export function runMiddlewares<State>(
middlewares: MiddlewareFn<State>[],
middlewares: MaybeLazyMiddleware<State>[],
ctx: Context<State>,
): Promise<Response> {
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;
+40
View File
@@ -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<MiddlewareFn<State>> = async () => {
called++;
return (ctx) => {
ctx.state.text += "_lazy";
return ctx.next();
};
};
const middlewares: MaybeLazy<MiddlewareFn<State>>[] = [
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);
});
+1 -1
View File
@@ -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";
+4 -4
View File
@@ -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<State> =
export interface Segment<State> {
pattern: string;
middlewares: MiddlewareFn<State>[];
middlewares: MaybeLazyMiddleware<State>[];
layout: {
component: RouteComponent<State>;
config: LayoutConfig | null;
@@ -74,8 +74,8 @@ export function getOrCreateSegment<State>(
export function segmentToMiddlewares<State>(
segment: Segment<State>,
): MiddlewareFn<State>[] {
const result: MiddlewareFn<State>[] = [];
): MaybeLazyMiddleware<State>[] {
const result: MaybeLazyMiddleware<State>[] = [];
const stack: Segment<State>[] = [];
let current: Segment<State> | null = segment;
+5 -2
View File
@@ -103,13 +103,12 @@ export function createFakeFs(files: Record<string, unknown>): 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<string, unknown>): FsAdapter {
async mkdirp(_dir: string) {
},
readFile: Deno.readFile,
// deno-lint-ignore require-await
async readTextFile(path) {
return String(files[String(path)]);
},
};
}
+18
View File
@@ -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<State> {
handler?: RouteHandler<unknown, State>;
}
/**
* Lazily construct items like middlewares, handlers, etc by wrapping them
* in a function.
*/
export type Lazy<T> = () => Promise<T>;
/**
* Return T or lazy version of T
*/
export type MaybeLazy<T> = T | Lazy<T>;
// TODO: Uncomment once JSR supports global types
// declare global {
// namespace preact.createElement.JSX {
+5
View File
@@ -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<T>(value: MaybeLazy<T>): value is Lazy<T> {
return typeof value === "function";
}
-1
View File
@@ -76,7 +76,6 @@ Deno.test({
fn: async () => {
const app = testApp()
.get("/partial", (ctx) => {
// FIXME: Add outer document
return ctx.render(
<Doc>
<Partial name="foo">
+1 -1
View File
@@ -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" },
+1 -8
View File
@@ -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();
+10
View File
@@ -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 };