From 6dc1116694c5ce9d0028239029bd9260924e3018 Mon Sep 17 00:00:00 2001 From: Aaron Date: Sun, 6 Sep 2026 13:00:59 -0500 Subject: [PATCH] perf: Optimizations with AI --- benchmarks/results/index.md | 2 +- .../response-validation-latency-avg.svg | 20 +- .../results/single-hook-latency-avg.svg | 14 +- .../results/static-response-latency-avg.svg | 18 +- ...alidate-and-echo-json-body-latency-avg.svg | 20 +- ...idate-and-echo-path-params-latency-avg.svg | 16 +- ...date-and-echo-query-params-latency-avg.svg | 22 +- src/__tests__/app.test.ts | 186 +++++++- src/app.ts | 1 + .../__tests__/compile-fetch-function.test.ts | 45 +- .../__tests__/compile-route-handler.test.ts | 417 +++++++++++------- src/internal/compile-fetch-function.ts | 7 +- src/internal/compile-route-handler.ts | 271 ++++++++---- src/internal/context.ts | 45 +- src/internal/utils.ts | 117 +++-- src/types.ts | 6 + 16 files changed, 839 insertions(+), 368 deletions(-) diff --git a/benchmarks/results/index.md b/benchmarks/results/index.md index 6fe0a00..3ed2c9f 100644 --- a/benchmarks/results/index.md +++ b/benchmarks/results/index.md @@ -1,5 +1,5 @@ --- -date: 2026-09-06T17:19:38.452Z +date: 2026-09-06T17:56:54.313Z platform: darwin arch: arm64 cpu: diff --git a/benchmarks/results/response-validation-latency-avg.svg b/benchmarks/results/response-validation-latency-avg.svg index 46e419f..f447ff2 100644 --- a/benchmarks/results/response-validation-latency-avg.svg +++ b/benchmarks/results/response-validation-latency-avg.svg @@ -5,15 +5,15 @@ vanilla 🥇 - elysia v1.4.30 🥈 - hono v4.13.7 🥉 - zeta v2.2.2 - - - + zeta v2.2.2 🥈 + elysia v1.4.30 🥉 + hono v4.13.7 + + + - 381.856 μs - 503.904 μs - 634.628 μs - 781.244 μs + 362.368 μs + 427.035 μs + 526.878 μs + 666.743 μs \ No newline at end of file diff --git a/benchmarks/results/single-hook-latency-avg.svg b/benchmarks/results/single-hook-latency-avg.svg index 0b6d2a4..cf39d9e 100644 --- a/benchmarks/results/single-hook-latency-avg.svg +++ b/benchmarks/results/single-hook-latency-avg.svg @@ -4,13 +4,13 @@ Average latency, lower = better - elysia v1.4.30 🥇 - zeta v2.2.2 🥈 + zeta v2.2.2 🥇 + elysia v1.4.30 🥈 hono v4.13.7 🥉 - - + + - 495.352 μs - 804.524 μs - 968.518 μs + 406.741 μs + 517.546 μs + 999.173 μs \ No newline at end of file diff --git a/benchmarks/results/static-response-latency-avg.svg b/benchmarks/results/static-response-latency-avg.svg index 9f73eb6..ec638c5 100644 --- a/benchmarks/results/static-response-latency-avg.svg +++ b/benchmarks/results/static-response-latency-avg.svg @@ -6,14 +6,14 @@ vanilla 🥇 elysia v1.4.30 🥈 - hono v4.13.7 🥉 - zeta v2.2.2 - - - + zeta v2.2.2 🥉 + hono v4.13.7 + + + - 230.910 μs - 267.259 μs - 346.256 μs - 606.146 μs + 241.602 μs + 291.709 μs + 343.876 μs + 355.270 μs \ No newline at end of file diff --git a/benchmarks/results/validate-and-echo-json-body-latency-avg.svg b/benchmarks/results/validate-and-echo-json-body-latency-avg.svg index c020368..99d7387 100644 --- a/benchmarks/results/validate-and-echo-json-body-latency-avg.svg +++ b/benchmarks/results/validate-and-echo-json-body-latency-avg.svg @@ -5,15 +5,15 @@ vanilla 🥇 - elysia v1.4.30 🥈 - hono v4.13.7 🥉 - zeta v2.2.2 - - - + zeta v2.2.2 🥈 + elysia v1.4.30 🥉 + hono v4.13.7 + + + - 578.877 μs - 1.016 ms - 1.055 ms - 1.114 ms + 597.810 μs + 782.744 μs + 1.016 ms + 1.060 ms \ No newline at end of file diff --git a/benchmarks/results/validate-and-echo-path-params-latency-avg.svg b/benchmarks/results/validate-and-echo-path-params-latency-avg.svg index 0412156..28ed1af 100644 --- a/benchmarks/results/validate-and-echo-path-params-latency-avg.svg +++ b/benchmarks/results/validate-and-echo-path-params-latency-avg.svg @@ -4,13 +4,13 @@ Average latency, lower = better - elysia v1.4.30 🥇 - hono v4.13.7 🥈 - zeta v2.2.2 🥉 - - + zeta v2.2.2 🥇 + elysia v1.4.30 🥈 + hono v4.13.7 🥉 + + - 670.528 μs - 888.754 μs - 967.833 μs + 545.221 μs + 596.954 μs + 905.847 μs \ No newline at end of file diff --git a/benchmarks/results/validate-and-echo-query-params-latency-avg.svg b/benchmarks/results/validate-and-echo-query-params-latency-avg.svg index a347e8f..80f5fdd 100644 --- a/benchmarks/results/validate-and-echo-query-params-latency-avg.svg +++ b/benchmarks/results/validate-and-echo-query-params-latency-avg.svg @@ -4,16 +4,16 @@ Average latency, lower = better - elysia v1.4.30 🥇 - vanilla 🥈 - hono v4.13.7 🥉 - zeta v2.2.2 - - - + zeta v2.2.2 🥇 + elysia v1.4.30 🥈 + vanilla 🥉 + hono v4.13.7 + + + - 724.848 μs - 820.740 μs - 903.908 μs - 1.072 ms + 629.122 μs + 750.414 μs + 753.761 μs + 949.329 μs \ No newline at end of file diff --git a/src/__tests__/app.test.ts b/src/__tests__/app.test.ts index c8d32aa..7873196 100644 --- a/src/__tests__/app.test.ts +++ b/src/__tests__/app.test.ts @@ -25,12 +25,12 @@ describe("App", () => { { respondWith: { hello: "world" }, expectedResponse: { hello: "world" }, - expectedContentType: "application/json;charset=utf-8", + expectedContentType: "application/json", }, { respondWith: [1, 2, 3], expectedResponse: [1, 2, 3], - expectedContentType: "application/json;charset=utf-8", + expectedContentType: "application/json", }, { respondWith: "test", @@ -59,14 +59,90 @@ describe("App", () => { }, ])( "should respond with the correct content type and value for %j", - async ({ respondWith, expectedResponse }) => { + async ({ respondWith, expectedResponse, expectedContentType }) => { const app = createApp().get("/test", { responses: z.any() }, () => respondWith); + const fetch = app.build(); const client = createTestAppClient(app); + const response = await client.fetch("GET", "/test", {}); + const raw = await fetch(new Request("http://localhost/test")); expect(response).toEqual(expectedResponse); + expect(raw.headers.get("content-type")).toBe(expectedContentType); }, ); + + it.each<{ name: string; respondWith: () => any; expectedContentType: string | null }>([ + { + name: "a class instance", + respondWith: () => + new (class Point { + x = 1; + })(), + expectedContentType: "application/json", + }, + { + name: "a null-prototype object", + respondWith: () => Object.assign(Object.create(null), { x: 1 }), + expectedContentType: "application/json", + }, + { + name: "a Blob", + respondWith: () => new Blob(["a,b"], { type: "text/csv" }), + expectedContentType: "text/csv", + }, + ])( + "should fall back to full serialization for $name", + async ({ respondWith, expectedContentType }) => { + const fetch = createApp().get("/test", respondWith).build(); + + const response = await fetch(new Request("http://localhost/test")); + + expect(response.headers.get("content-type")).toBe(expectedContentType); + }, + ); + + it("should keep a status set on the context", async () => { + const fetch = createApp() + .get("/test", (ctx) => { + ctx.set.status = HttpStatus.ImATeapot; + return { teapot: true }; + }) + .build(); + + const response = await fetch(new Request("http://localhost/test")); + + expect(response.status).toBe(HttpStatus.ImATeapot); + expect(response.headers.get("content-type")).toBe("application/json"); + expect(await response.json()).toEqual({ teapot: true }); + }); + + it("should keep headers set on the context", async () => { + const fetch = createApp() + .get("/test", (ctx) => { + ctx.set.headers["X-Custom"] = "yes"; + return "body"; + }) + .build(); + + const response = await fetch(new Request("http://localhost/test")); + + expect(response.headers.get("x-custom")).toBe("yes"); + expect(response.headers.get("content-type")).toBe("text/plain"); + }); + + it("should let the handler override the content type", async () => { + const fetch = createApp() + .get("/test", (ctx) => { + ctx.set.headers["Content-Type"] = "text/csv"; + return "a,b,c"; + }) + .build(); + + const response = await fetch(new Request("http://localhost/test")); + + expect(response.headers.get("content-type")).toBe("text/csv"); + }); }); describe("Response content type meta", () => { @@ -183,6 +259,20 @@ describe("App", () => { expect(actual).toEqual({ id: 123 }); expect(typeof actual.id).toBe("number"); }); + + it("should percent-decode path parameters but leave + alone", async () => { + let actual: any; + const fetch = createApp() + .get("/test/:value", (ctx) => void (actual = ctx.params)) + .build(); + + await fetch(new Request("http://localhost/test/a%20b")); + expect(actual).toEqual({ value: "a b" }); + + // "+" only means "space" in query strings, not in path segments. + await fetch(new Request("http://localhost/test/a+b")); + expect(actual).toEqual({ value: "a+b" }); + }); }); describe("query parameters parsing", () => { @@ -254,6 +344,31 @@ describe("App", () => { expect(actual).toEqual({ text: "hello world" }); }); + + it.each<{ search: string; expected: Record }>([ + { search: "?a=1&b=2", expected: { a: "1", b: "2" } }, + { search: "?a=hello%20world", expected: { a: "hello world" } }, + { search: "?a=hello+world", expected: { a: "hello world" } }, + { search: "?a=", expected: { a: "" } }, + // Keys without a value are skipped + { search: "?a", expected: {} }, + // A trailing separator shouldn't leak into the last value + { search: "?a=1&", expected: { a: "1" } }, + // Only the first "=" separates the key from the value + { search: "?a=b=c", expected: { a: "b=c" } }, + // Last value wins for repeated keys + { search: "?a=1&a=2", expected: { a: "2" } }, + { search: "", expected: {} }, + ])("should parse the raw query string $search", async ({ search, expected }) => { + let actual: any; + const fetch = createApp() + .get("/test", (ctx) => void (actual = ctx.query)) + .build(); + + await fetch(new Request(`http://localhost/test${search}`)); + + expect(actual).toEqual(expected); + }); }); describe("any", () => { @@ -361,6 +476,71 @@ describe("App", () => { }); }); + describe("life cycle hooks", () => { + it.each(["onTransform", "onBeforeHandle", "onAfterHandle", "onMapResponse"] as const)( + "should ignore a %s hook that returns nothing", + async (hook) => { + const fetch = createApp() + [hook](() => {}) + .get("/", () => "handled") + .build(); + + const response = await fetch(new Request("http://localhost/")); + + expect(response.status).toBe(HttpStatus.Ok); + expect(await response.text()).toBe("handled"); + }, + ); + + it.each(["onTransform", "onBeforeHandle"] as const)( + "should short circuit when a %s hook returns a Response", + async (hook) => { + const handler = mock(() => "handled"); + const fetch = createApp() + [hook](() => new Response("short circuited")) + .get("/", handler) + .build(); + + const response = await fetch(new Request("http://localhost/")); + + expect(await response.text()).toBe("short circuited"); + expect(handler).not.toHaveBeenCalled(); + }, + ); + + it.each(["onAfterHandle", "onMapResponse"] as const)( + "should replace the response when a %s hook returns one", + async (hook) => { + const fetch = createApp() + [hook](() => new Response("replaced")) + .get("/", () => "handled") + .build(); + + const response = await fetch(new Request("http://localhost/")); + + expect(await response.text()).toBe("replaced"); + }, + ); + + it("should await async hooks", async () => { + const calls: string[] = []; + const fetch = createApp() + .onTransform(async () => void calls.push("transform")) + .onBeforeHandle(async () => void calls.push("beforeHandle")) + .onAfterHandle(async () => void calls.push("afterHandle")) + .get("/", async () => { + calls.push("handler"); + return "handled"; + }) + .build(); + + const response = await fetch(new Request("http://localhost/")); + + expect(await response.text()).toBe("handled"); + expect(calls).toEqual(["transform", "beforeHandle", "handler", "afterHandle"]); + }); + }); + describe("decorate", () => { it("should include the decorated value in the request handlers", async () => { const expected = "decorated value"; diff --git a/src/app.ts b/src/app.ts index fc7cfdb..dc7dea2 100644 --- a/src/app.ts +++ b/src/app.ts @@ -167,6 +167,7 @@ export function createApp< id: nextHookId(appId), applyTo: "local", callback: () => obj, + decoration: obj, }); return app; diff --git a/src/internal/__tests__/compile-fetch-function.test.ts b/src/internal/__tests__/compile-fetch-function.test.ts index 5896d16..bbdba80 100644 --- a/src/internal/__tests__/compile-fetch-function.test.ts +++ b/src/internal/__tests__/compile-fetch-function.test.ts @@ -26,8 +26,9 @@ describe("compileFetchFunction", () => { expect(actual.toString()).toMatchInlineSnapshot(` "(request) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); try { const matchedRoute = utils.getRoute(request.method, path); @@ -51,7 +52,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); }); @@ -63,7 +64,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); } @@ -85,8 +86,9 @@ describe("compileFetchFunction", () => { expect(actual.toString()).toMatchInlineSnapshot(` "(request) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); try { const onGlobalRequestRes0 = utils.hooks.onGlobalRequest[0].callback(ctx); @@ -118,7 +120,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); }); @@ -130,7 +132,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); } @@ -152,8 +154,9 @@ describe("compileFetchFunction", () => { expect(actual.toString()).toMatchInlineSnapshot(` "(request) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); let handlerReturnedPromise = false; @@ -180,7 +183,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); }).finally(() => { @@ -196,7 +199,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); } finally { @@ -225,8 +228,9 @@ describe("compileFetchFunction", () => { expect(actual.toString()).toMatchInlineSnapshot(` "(request) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); try { const matchedRoute = utils.getRoute(request.method, path); @@ -253,7 +257,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); }); @@ -268,7 +272,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); } @@ -297,8 +301,9 @@ describe("compileFetchFunction", () => { expect(actual.toString()).toMatchInlineSnapshot(` "(request, ...args) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); utils.transport.decorate(ctx, request, ...args); try { @@ -323,7 +328,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); }); @@ -335,7 +340,7 @@ describe("compileFetchFunction", () => { return ( ctx.response = Response.json( utils.serializeErrorResponse(error), - { status, headers: ctx.set.headers }, + { status, headers: ctx.set.rawHeaders }, ) ); } diff --git a/src/internal/__tests__/compile-route-handler.test.ts b/src/internal/__tests__/compile-route-handler.test.ts index 5646c23..0f8c12c 100644 --- a/src/internal/__tests__/compile-route-handler.test.ts +++ b/src/internal/__tests__/compile-route-handler.test.ts @@ -1,13 +1,13 @@ import { describe, it, expect } from "bun:test"; -import { compileRouteHandler } from "../compile-route-handler"; +import { compileRouteHandlerSource } from "../compile-route-handler"; process.env.NODE_ENV = "production"; describe("compileRouteHandler", () => { describe("when compiling a mounted fetch function", () => { it("should return a simple function", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, route: "/", @@ -16,15 +16,19 @@ describe("compileRouteHandler", () => { fetch: () => new Response(), }); - expect(actual.toString()).toMatchInlineSnapshot( - `"(request, ctx) => ctx.matchedRoute.data.fetch(request)"`, + expect(actual).toMatchInlineSnapshot( + ` + "return (request, ctx) => ctx.matchedRoute.data.fetch(request) + //#sourceURL=zeta-jit-generated://get--.js + " + `, ); }); }); describe("when compiling route handlers", () => { it("should return a simple function with context", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, route: "/", @@ -33,10 +37,17 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot( + expect(actual).toMatchInlineSnapshot( ` - "async (request, ctx) => { - ctx.response = await ctx.matchedRoute.data.handler(ctx); + "function step0(request, ctx) { + const value0 = ctx.matchedRoute.data.handler(ctx); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + ctx.response = value0; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -44,31 +55,36 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://get--.js + " `, ); }); it("should get the request body for non-GET methods", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, route: "/", @@ -77,13 +93,25 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot( + expect(actual).toMatchInlineSnapshot( ` - "async (request, ctx) => { - ctx.body = utils.smartDeserialize(request); - if (ctx.body) ctx.body = await ctx.body; - - ctx.response = await ctx.matchedRoute.data.handler(ctx); + "function step0(request, ctx) { + const value0 = utils.smartDeserialize(request); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + ctx.body = value0; + const value1 = ctx.matchedRoute.data.handler(ctx); + if (value1 != null && typeof value1.then === utils.FUNCTION) + return value1.then(resolved => step2(request, ctx, resolved)); + return step2(request, ctx, value1); + } + + function step2(request, ctx, value1) { + ctx.response = value1; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -91,31 +119,36 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://post--.js + " `, ); }); it("should include onTransform hook calls", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, hooks: { @@ -126,17 +159,27 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot(` - "async (request, ctx) => { - const onTransformRes0 = await ctx.matchedRoute.data.hooks.onTransform[0].callback(ctx); - if (onTransformRes0) - if (typeof onTransformRes0.body?.bytes === utils.FUNCTION) - return onTransformRes0; - else - for (const key of Object.keys(onTransformRes0)) - ctx[key] = onTransformRes0[key]; - - ctx.response = await ctx.matchedRoute.data.handler(ctx); + expect(actual).toMatchInlineSnapshot(` + "function step0(request, ctx) { + const value0 = ctx.matchedRoute.data.hooks.onTransform[0].callback(ctx); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + if (value0) { + if (typeof value0.body?.bytes === utils.FUNCTION) return value0; + for (const key of Object.keys(value0)) ctx[key] = value0[key]; + } + const value1 = ctx.matchedRoute.data.handler(ctx); + if (value1 != null && typeof value1.then === utils.FUNCTION) + return value1.then(resolved => step2(request, ctx, resolved)); + return step2(request, ctx, value1); + } + + function step2(request, ctx, value1) { + ctx.response = value1; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -144,30 +187,35 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://get--.js + " `); }); it("should include onBeforeHandle hook calls", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, hooks: { @@ -178,17 +226,27 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot(` - "async (request, ctx) => { - const onBeforeHandleRes0 = await ctx.matchedRoute.data.hooks.onBeforeHandle[0].callback(ctx); - if (onBeforeHandleRes0) - if (typeof onBeforeHandleRes0.body?.bytes === utils.FUNCTION) - return onBeforeHandleRes0; - else - for (const key of Object.keys(onBeforeHandleRes0)) - ctx[key] = onBeforeHandleRes0[key]; - - ctx.response = await ctx.matchedRoute.data.handler(ctx); + expect(actual).toMatchInlineSnapshot(` + "function step0(request, ctx) { + const value0 = ctx.matchedRoute.data.hooks.onBeforeHandle[0].callback(ctx); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + if (value0) { + if (typeof value0.body?.bytes === utils.FUNCTION) return value0; + for (const key of Object.keys(value0)) ctx[key] = value0[key]; + } + const value1 = ctx.matchedRoute.data.handler(ctx); + if (value1 != null && typeof value1.then === utils.FUNCTION) + return value1.then(resolved => step2(request, ctx, resolved)); + return step2(request, ctx, value1); + } + + function step2(request, ctx, value1) { + ctx.response = value1; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -196,30 +254,35 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://get--.js + " `); }); it("should include onAfterHandle hook calls", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, hooks: { @@ -230,9 +293,16 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot(` - "async (request, ctx) => { - ctx.response = await ctx.matchedRoute.data.handler(ctx); + expect(actual).toMatchInlineSnapshot(` + "function step0(request, ctx) { + const value0 = ctx.matchedRoute.data.handler(ctx); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + ctx.response = value0; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -240,35 +310,46 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - const onAfterHandleRes0 = await ctx.matchedRoute.data.hooks.onAfterHandle[0].callback(ctx); - if (onAfterHandleRes0) ctx.response = onAfterHandleRes0; - if (typeof onAfterHandleRes0.body?.bytes === utils.FUNCTION) - return onAfterHandleRes0; - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const value1 = ctx.matchedRoute.data.hooks.onAfterHandle[0].callback(ctx); + if (value1 != null && typeof value1.then === utils.FUNCTION) + return value1.then(resolved => step2(request, ctx, resolved)); + return step2(request, ctx, value1); + } + + function step2(request, ctx, value1) { + if (value1) { + ctx.response = value1; + if (typeof value1.body?.bytes === utils.FUNCTION) return value1; + } + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://get--.js + " `); }); it("should include onMapResponse hook calls", () => { - const actual = compileRouteHandler({ + const actual = compileRouteHandlerSource({ def: undefined, schemaAdapter: undefined, hooks: { @@ -279,9 +360,16 @@ describe("compileRouteHandler", () => { handler: () => 0, }); - expect(actual.toString()).toMatchInlineSnapshot(` - "async (request, ctx) => { - ctx.response = await ctx.matchedRoute.data.handler(ctx); + expect(actual).toMatchInlineSnapshot(` + "function step0(request, ctx) { + const value0 = ctx.matchedRoute.data.handler(ctx); + if (value0 != null && typeof value0.then === utils.FUNCTION) + return value0.then(resolved => step1(request, ctx, resolved)); + return step1(request, ctx, value0); + } + + function step1(request, ctx, value0) { + ctx.response = value0; if (ctx.response) { if (ctx.response[utils.IsStatusResult]) { ctx.set.status = ctx.response.status; @@ -289,30 +377,41 @@ describe("compileRouteHandler", () => { } if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; } - - const onMapResponseRes0 = await ctx.matchedRoute.data.hooks.onMapResponse[0].callback(ctx); - if (onMapResponseRes0) ctx.response = onMapResponseRes0; - if (typeof onMapResponseRes0.body?.bytes === utils.FUNCTION) - return onMapResponseRes0; - - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) + const value1 = ctx.matchedRoute.data.hooks.onMapResponse[0].callback(ctx); + if (value1 != null && typeof value1.then === utils.FUNCTION) + return value1.then(resolved => step2(request, ctx, resolved)); + return step2(request, ctx, value1); + } + + function step2(request, ctx, value1) { + if (value1) { + ctx.response = value1; + if (typeof value1.body?.bytes === utils.FUNCTION) return value1; + } + const status = ctx.set.status; + const headers = ctx.set.rawHeaders; + if (ctx.response == null) + return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers })); + if (status === 200 && headers === undefined) { + const type = typeof ctx.response; + if (type === "object") { + const ctor = ctx.response.constructor; + if (ctor === Object || ctor === Array) + return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT)); + } else if (type === "string") { + return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT)); + } } - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - }" + const contentType = serialized.contentType; + const outHeaders = ctx.set.headers; + if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType; + return (ctx.response = new Response(serialized.value, { status, headers: outHeaders })); + } + + return step0; + //#sourceURL=zeta-jit-generated://get--.js + " `); }); }); diff --git a/src/internal/compile-fetch-function.ts b/src/internal/compile-fetch-function.ts index f4902db..22b90b3 100644 --- a/src/internal/compile-fetch-function.ts +++ b/src/internal/compile-fetch-function.ts @@ -13,8 +13,9 @@ export function compileFetchFunction(options: CompileOptions): ServerSideFetch { const js = ` return (request${options.transport?.decorate ? ", ...args" : ""}) => { - const path = utils.getRawPathname(request); - const ctx = new utils.Context(request, path, utils.origin); + const url = request.url; + const path = utils.getRawPathname(url); + const ctx = new utils.Context(request, path, utils.origin, url); ${options.transport?.decorate ? `utils.transport.decorate(ctx, request, ...args);` : ""} ${onGlobalAfterResponseCount ? "let handlerReturnedPromise = false;" : ""} @@ -138,7 +139,7 @@ ${indent} : utils.HttpStatus.InternalServerError; ${indent}return ( ${indent} ctx.response = Response.json( ${indent} utils.serializeErrorResponse(error), -${indent} { status, headers: ctx.set.headers }, +${indent} { status, headers: ctx.set.rawHeaders }, ${indent} ) ${indent});`; } diff --git a/src/internal/compile-route-handler.ts b/src/internal/compile-route-handler.ts index 3637d48..860f218 100644 --- a/src/internal/compile-route-handler.ts +++ b/src/internal/compile-route-handler.ts @@ -1,6 +1,7 @@ import { getMeta } from "../meta"; import type { CompiledRouteHandler, + LifeCycleHook, LifeCycleHookName, LifeCycleHooks, MaybePromise, @@ -13,71 +14,74 @@ import { smartDeserialize, smartSerialize } from "./serialization"; import { cleanupCompiledWhitespace, IsStatusResult, + JSON_RESPONSE_INIT, + TEXT_RESPONSE_INIT, validateInputSchema, validateOutputSchema, } from "./utils"; export function compileRouteHandler(options: CompileOptions): CompiledRouteHandler { + const responseContentTypeMap = options.fetch ? undefined : getResponseContentTypeMap(options); + const js = compileRouteHandlerSource(options, responseContentTypeMap); + return new Function("utils", "responseContentTypeMap", js)(UTILS, responseContentTypeMap); +} + +/** + * Generates the source compiled by `compileRouteHandler`. Exported so tests can + * assert on the generated code. + */ +export function compileRouteHandlerSource( + options: CompileOptions, + responseContentTypeMap: Record | undefined = getResponseContentTypeMap(options), +): string { + const sourceUrl = getSourceUrl(options); if (options.fetch) { - return new Function(` - return (request, ctx) => ctx.matchedRoute.data.fetch(request) - //#sourceURL=${getSourceUrl(options)} - `)(); + return `return (request, ctx) => ctx.matchedRoute.data.fetch(request)\n//#sourceURL=${sourceUrl}\n`; } - const responseContentTypeMap = getResponseContentTypeMap(options); - - const js = ` -return async (request, ctx) => { - ${options.method === "GET" ? "" : ADD_CTX_BODY} + const chain = new HandlerChain(); -${options.hooks.onTransform?.length ? compileCtxModifierHookCall("onTransform", options.hooks.onTransform.length) : ""} + if (options.method !== "GET") { + const body = chain.split("utils.smartDeserialize(request)"); + chain.push(`ctx.body = ${body};`); + } - ${options.def?.body ? "ctx.body = utils.validateInputSchema(ctx.matchedRoute.data.def.body, ctx.body);" : ""} - ${options.def?.params ? "ctx.params = utils.validateInputSchema(ctx.matchedRoute.data.def.params, ctx.params);" : ""} - ${options.def?.query ? "ctx.query = utils.validateInputSchema(ctx.matchedRoute.data.def.query, ctx.query);" : ""} + compileCtxModifierHooks(chain, "onTransform", options.hooks.onTransform); -${options.hooks.onBeforeHandle?.length ? compileCtxModifierHookCall("onBeforeHandle", options.hooks.onBeforeHandle.length) : ""} + if (options.def?.body) + chain.push("ctx.body = utils.validateInputSchema(ctx.matchedRoute.data.def.body, ctx.body);"); + if (options.def?.params) + chain.push( + "ctx.params = utils.validateInputSchema(ctx.matchedRoute.data.def.params, ctx.params);", + ); + if (options.def?.query) + chain.push( + "ctx.query = utils.validateInputSchema(ctx.matchedRoute.data.def.query, ctx.query);", + ); - ctx.response = await ctx.matchedRoute.data.handler(ctx); - if (ctx.response) { - if (ctx.response[utils.IsStatusResult]) { - ctx.set.status = ctx.response.status; - ctx.response = ctx.response.body; - } - if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response; - } + compileCtxModifierHooks(chain, "onBeforeHandle", options.hooks.onBeforeHandle); - ${compileValidateResponse(options)} + const result = chain.split("ctx.matchedRoute.data.handler(ctx)"); + chain.push( + `ctx.response = ${result};`, + "if (ctx.response) {", + " if (ctx.response[utils.IsStatusResult]) {", + " ctx.set.status = ctx.response.status;", + " ctx.response = ctx.response.body;", + " }", + " if (typeof ctx.response?.body?.bytes === utils.FUNCTION) return ctx.response;", + "}", + ); -${options.hooks.onAfterHandle?.length ? compileResponseModifierHookCall("onAfterHandle", options.hooks.onAfterHandle.length) : ""} + const validateResponse = compileValidateResponse(options); + if (validateResponse) chain.push(validateResponse); -${options.hooks.onMapResponse?.length ? compileResponseModifierHookCall("onMapResponse", options.hooks.onMapResponse.length) : ""} + compileResponseModifierHooks(chain, "onAfterHandle", options.hooks.onAfterHandle); + compileResponseModifierHooks(chain, "onMapResponse", options.hooks.onMapResponse); - if (ctx.response == null) { - return ( - ctx.response = new Response(undefined, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) - } + chain.push(...compileSendResponse(responseContentTypeMap)); - const serialized = utils.smartSerialize(ctx.response); - if (!ctx.set.headers["Content-Type"]) ctx.set.headers["Content-Type"] = ${responseContentTypeMap ? "responseContentTypeMap[ctx.set.status] ??" : ""} serialized.contentType - return ( - ctx.response = new Response(serialized.value, { - status: ctx.set.status, - headers: ctx.set.headers, - }) - ) -} -//#sourceURL=${getSourceUrl(options)} - `; - return new Function("utils", "responseContentTypeMap", cleanupCompiledWhitespace(js))( - UTILS, - responseContentTypeMap, - ); + return cleanupCompiledWhitespace(chain.render(sourceUrl)); } // These functions are available in the generated code via the "utils" object. @@ -86,6 +90,8 @@ const UTILS = { smartSerialize, FUNCTION: "function", IsStatusResult, + JSON_RESPONSE_INIT, + TEXT_RESPONSE_INIT, validateInputSchema, validateOutputSchema, }; @@ -104,49 +110,107 @@ function getSourceUrl(options: CompileOptions) { return `zeta-jit-generated://${options.method.toLowerCase()}-${options.route.replace(/\s/gm, "").replaceAll("/", "-")}.js`; } -const ADD_CTX_BODY = ` - ctx.body = utils.smartDeserialize(request); - if (ctx.body) ctx.body = await ctx.body; -`; +/** + * Builds the source of a route handler as a chain of "steps", split at each + * point where a value might be a promise. + * + * Compiling to a single `async` function is simpler, but it forces every + * request through the promise machinery even when nothing in the pipeline is + * actually async. Instead, each possibly-async expression checks its own result + * and only defers to `.then()` when it really got a promise, so a route with a + * synchronous handler and synchronous hooks runs start-to-finish synchronously + * and returns a `Response` rather than a `Promise`. + */ +class HandlerChain { + #segments: string[][] = [[]]; -function compileCtxModifierHookCall(hook: LifeCycleHookName, hookCount: number): string { - const lines: string[] = []; + push(...lines: string[]): void { + this.#segments[this.#segments.length - 1]!.push(...lines); + } - for (let i = 0; i < hookCount; i++) { - const resultVar = `${hook}Res${i}`; - lines.push( - ` const ${resultVar} = await ctx.matchedRoute.data.hooks.${hook}[${i}].callback(ctx);`, - ` if (${resultVar})`, - ` if (typeof ${resultVar}.body?.bytes === utils.FUNCTION)`, - ` return ${resultVar};`, - ` else`, - ` for (const key of Object.keys(${resultVar}))`, - ` ctx[key] = ${resultVar}[key];`, + /** + * Ends the current step with `expr`, continuing the rest of the handler in a + * new step once the value settles. + * + * @returns The name of the variable holding the settled value. Only valid in + * code pushed after this call. + */ + split(expr: string): string { + const index = this.#segments.length - 1; + const value = `value${index}`; + const next = `step${index + 1}`; + this.push( + `const ${value} = ${expr};`, + `if (${value} != null && typeof ${value}.then === utils.FUNCTION)`, + ` return ${value}.then(resolved => ${next}(request, ctx, resolved));`, + `return ${next}(request, ctx, ${value});`, ); + this.#segments.push([]); + return value; } - return lines.join("\n"); + render(sourceUrl: string): string { + const fns = this.#segments.map((lines, i) => { + // Every step but the first receives the value the previous step split on. + const args = i === 0 ? "request, ctx" : `request, ctx, value${i - 1}`; + const body = lines.map((line) => ` ${line}`).join("\n"); + return `function step${i}(${args}) {\n${body}\n}`; + }); + return `${fns.join("\n\n")}\n\nreturn step0;\n//#sourceURL=${sourceUrl}\n`; + } } -function compileResponseModifierHookCall(hook: LifeCycleHookName, hookCount: number): string { - const lines: string[] = []; +function compileCtxModifierHooks( + chain: HandlerChain, + hook: LifeCycleHookName, + hooks: LifeCycleHook[] | undefined, +): void { + if (!hooks?.length) return; - for (let i = 0; i < hookCount; i++) { - const resultVar = `${hook}Res${i}`; - lines.push( - ` const ${resultVar} = await ctx.matchedRoute.data.hooks.${hook}[${i}].callback(ctx);`, - ` if (${resultVar}) ctx.response = ${resultVar};`, - ` if (typeof ${resultVar}.body?.bytes === utils.FUNCTION)`, - ` return ${resultVar};`, + for (let i = 0; i < hooks.length; i++) { + const path = `ctx.matchedRoute.data.hooks.${hook}[${i}]`; + + // `app.decorate` values are known at compile time, so they can be assigned + // straight onto the context - no call, no `Object.keys`, no async check. + const { decoration } = hooks[i]!; + if (decoration) { + for (const key of Object.keys(decoration)) { + chain.push(`ctx[${JSON.stringify(key)}] = ${path}.decoration[${JSON.stringify(key)}];`); + } + continue; + } + + const res = chain.split(`${path}.callback(ctx)`); + chain.push( + `if (${res}) {`, + ` if (typeof ${res}.body?.bytes === utils.FUNCTION) return ${res};`, + ` for (const key of Object.keys(${res})) ctx[key] = ${res}[key];`, + `}`, ); } +} + +function compileResponseModifierHooks( + chain: HandlerChain, + hook: LifeCycleHookName, + hooks: LifeCycleHook[] | undefined, +): void { + if (!hooks?.length) return; - return lines.join("\n"); + for (let i = 0; i < hooks.length; i++) { + const res = chain.split(`ctx.matchedRoute.data.hooks.${hook}[${i}].callback(ctx)`); + chain.push( + `if (${res}) {`, + ` ctx.response = ${res};`, + ` if (typeof ${res}.body?.bytes === utils.FUNCTION) return ${res};`, + `}`, + ); + } } -function compileValidateResponse(options: CompileOptions): string { +function compileValidateResponse(options: CompileOptions): string | undefined { // No schemas defined - if (!options.def?.responses) return ""; + if (!options.def?.responses) return; // One schema defined if ("~standard" in options.def.responses) @@ -156,6 +220,54 @@ function compileValidateResponse(options: CompileOptions): string { return "ctx.response = utils.validateOutputSchema(ctx.matchedRoute.data.def.responses[ctx.set.status], ctx.response);"; } +/** + * Turns `ctx.response` into a `Response`. + * + * When the route didn't customize the status or headers (by far the most common + * case), strings and plain JSON values skip `smartSerialize` and reuse a shared + * `ResponseInit`, which avoids re-parsing a headers object literal on every + * request. See `createContentTypeInit` - that parsing costs roughly as much as + * the rest of the request pipeline combined. + */ +function compileSendResponse(responseContentTypeMap: Record | undefined): string[] { + const lines = ["const status = ctx.set.status;", "const headers = ctx.set.rawHeaders;"]; + + // A route-specific content type means we can't let the runtime pick one. + const canFastPath = responseContentTypeMap == null; + + lines.push( + "if (ctx.response == null)", + canFastPath + ? " return (ctx.response = status === 200 && headers === undefined ? new Response() : new Response(undefined, { status, headers }));" + : " return (ctx.response = new Response(undefined, { status, headers }));", + ); + + if (canFastPath) { + lines.push( + "if (status === 200 && headers === undefined) {", + " const type = typeof ctx.response;", + ' if (type === "object") {', + " const ctor = ctx.response.constructor;", + " if (ctor === Object || ctor === Array)", + " return (ctx.response = new Response(JSON.stringify(ctx.response), utils.JSON_RESPONSE_INIT));", + ' } else if (type === "string") {', + " return (ctx.response = new Response(ctx.response, utils.TEXT_RESPONSE_INIT));", + " }", + "}", + ); + } + + lines.push( + "const serialized = utils.smartSerialize(ctx.response);", + `const contentType = ${responseContentTypeMap ? "responseContentTypeMap[status] ?? " : ""}serialized.contentType;`, + "const outHeaders = ctx.set.headers;", + 'if (contentType && !outHeaders["Content-Type"]) outHeaders["Content-Type"] = contentType;', + "return (ctx.response = new Response(serialized.value, { status, headers: outHeaders }));", + ); + + return lines; +} + function getResponseContentTypeMap(options: CompileOptions): Record | undefined { // No schemas defined if (!options.def?.responses) return; @@ -170,11 +282,14 @@ function getResponseContentTypeMap(options: CompileOptions): Record = {}; + let empty = true; for (const [status, schema] of Object.entries(options.def.responses)) { const { contentType } = getMeta(options.schemaAdapter, schema); + if (!contentType) continue; map[Number(status)] = contentType; + empty = false; } - if (Object.keys(map).length === 0) return; + if (empty) return; return map; } diff --git a/src/internal/context.ts b/src/internal/context.ts index 4c8063b..8dbf42e 100644 --- a/src/internal/context.ts +++ b/src/internal/context.ts @@ -1,17 +1,46 @@ import type { MatchedRoute } from "rou3"; import { HttpStatus } from "../status"; -import type { RouterData, StatusResult } from "../types"; +import type { RouterData, Setter as SetterType, StatusResult } from "../types"; import { getRawParams, getRawQuery, IsStatusResult } from "./utils"; +/** + * `ctx.set`, with headers created lazily. + * + * Most responses never touch `set.headers`, and knowing that lets the compiled + * route handler skip building a `ResponseInit` entirely, which is a large + * fraction of the cost of returning a response. + */ +class Setter implements SetterType { + status: number = HttpStatus.Ok; + + /** + * The headers object, or `undefined` if nothing has read or written headers + * yet. Compiled handlers read this instead of `headers` to avoid + * materializing the object. + */ + rawHeaders: Record | undefined; + + get headers(): Record { + return (this.rawHeaders ??= {}); + } + + set headers(value: Record) { + this.rawHeaders = value; + } +} + export class Context { - set = { - status: HttpStatus.Ok, - headers: {}, - }; + set: SetterType = new Setter(); matchedRoute: MatchedRoute | undefined; + // Declared up-front so the compiled handlers assigning them don't force a + // hidden class transition on every request. + response: any; + error: unknown; + body: any; + // Private storage for overwritten values #params: Record | undefined; #query: Record | undefined; @@ -20,10 +49,12 @@ export class Context { public request: Request, public path: string, public origin: string, + /** The unparsed `request.url`. Cached because it's a non-trivial getter. */ + public rawUrl: string, ) {} get url(): URL { - return new URL(this.request.url, this.origin); + return new URL(this.rawUrl, this.origin); } get params(): Record { @@ -41,7 +72,7 @@ export class Context { if (this.#query !== undefined) { return this.#query; } - return this.request.url.includes("?") ? getRawQuery(this.request) : {}; + return getRawQuery(this.rawUrl); } set query(value: Record) { diff --git a/src/internal/utils.ts b/src/internal/utils.ts index aa160d9..de2e678 100644 --- a/src/internal/utils.ts +++ b/src/internal/utils.ts @@ -4,9 +4,9 @@ import type { MatchedRoute } from "rou3"; import { HttpError } from "../errors"; import type { ErrorResponse } from "../schema"; import { HttpStatus } from "../status"; -import type { App, LifeCycleHook, MaybePromise, RouterData, StatusResult } from "../types"; +import type { RouterData } from "../types"; -export function validateSchema( +function validateSchema( schema: StandardSchemaV1, input: unknown, status: number, @@ -38,41 +38,62 @@ export const validateOutputSchema = createHttpSchemaValidator( "Output validation failed", ); -export function isApp(obj: unknown): obj is App { - return (obj as any)[Symbol.toStringTag] === "ZetaApp"; -} +// Character codes used while scanning URLs. Scanning by char code avoids +// allocating a single-character string for every character of the URL. +const CHAR_HASH = 35; // # +const CHAR_PERCENT = 37; // % +const CHAR_AMPERSAND = 38; // & +const CHAR_PLUS = 43; // + +const CHAR_EQUALS = 61; // = +const CHAR_QUESTION = 63; // ? -export function getRawPathname(request: Request): string { +export function getRawPathname(url: string): string { // Fast path for common case: http://host/path - const start = request.url.indexOf("/", 8); // Skip 'http://' or 'https://' + const start = url.indexOf("/", 8); // Skip 'http://' or 'https://' if (start === -1) return "/"; - // Find end of pathname (before ? or #) - for (let i = start + 1; i < request.url.length; i++) { - if (request.url[i] === "?" || request.url[i] === "#") { - return decodeUrlString(request.url.slice(start, i)); - } + // Find end of pathname (before ? or #), noting whether it contains any + // percent-escapes so decoding can be skipped for the (very common) case + // where there's nothing to decode. + const len = url.length; + let escaped = false; + let i = start; + for (; i < len; i++) { + const char = url.charCodeAt(i); + if (char === CHAR_QUESTION || char === CHAR_HASH) break; + if (char === CHAR_PERCENT) escaped = true; } - return decodeUrlString(request.url.slice(start)); + + const pathname = url.slice(start, i); + return escaped ? decodeURIComponent(pathname) : pathname; } -export function getRawQuery(request: Request): Record { - let index = request.url.indexOf("?"); +export function getRawQuery(url: string): Record { + const index = url.indexOf("?"); if (index === -1) return {}; const res: Record = {}; - const str = request.url; - const len = str.length; + const len = url.length; let start = index + 1; - - for (let i = start; i < len; i++) { - if (str[i] === "&" || i === len - 1) { - const end = i === len - 1 ? len : i; - const eqIndex = str.indexOf("=", start); - if (eqIndex !== -1 && eqIndex < end) { - res[str.slice(start, eqIndex)] = decodeUrlString(str.slice(eqIndex + 1, end)); + let eq = -1; + let escaped = false; + + // `i === len` acts as a trailing "&" so the last pair is flushed by the same + // code path as the rest. + for (let i = start; i <= len; i++) { + const char = i === len ? CHAR_AMPERSAND : url.charCodeAt(i); + if (char === CHAR_AMPERSAND) { + if (eq !== -1) { + const value = url.slice(eq + 1, i); + res[url.slice(start, eq)] = escaped ? decodeUrlString(value) : value; } start = i + 1; + eq = -1; + escaped = false; + } else if (char === CHAR_EQUALS) { + if (eq === -1) eq = i; + } else if (eq !== -1 && (char === CHAR_PERCENT || char === CHAR_PLUS)) { + escaped = true; } } return res; @@ -84,14 +105,14 @@ export function getRawParams(route: MatchedRoute): Record = {}; for (const key in params) { + const value = params[key]!; // Rename rou3's _ to ** to match type-system - const outKey = key === "_" ? "**" : key; - res[outKey] = decodeURIComponent(params[key]!); + res[key === "_" ? "**" : key] = value.indexOf("%") === -1 ? value : decodeURIComponent(value); } return res; } -export function getErrorStack(err: Error): string[] | undefined { +function getErrorStack(err: Error): string[] | undefined { if (process.env.NODE_ENV === "production") return; return err.stack ?.split("\n") @@ -127,25 +148,37 @@ export function serializeErrorResponse(err: unknown): ErrorResponse { }; } -export async function callCtxModifierHooks( - ctx: any, - hooks: LifeCycleHook<(ctx: any) => MaybePromise | void>>[] | undefined, -): Promise { - if (!hooks) return; - - for (const hook of hooks) { - let res = hook.callback(ctx); - if (res instanceof Promise) res = await res; - if (res instanceof Response) return res; - if (res) Object.assign(ctx, res); // TODO: Replace with manual property setting for performance? +/** + * Builds a `ResponseInit` that only sets `Content-Type`, in the cheapest form + * the runtime accepts. + * + * Building a `ResponseInit` is a surprisingly large share of the cost of + * responding - in Bun, `new Response(body, { headers: { "Content-Type": x } })` + * takes about 2.5x as long as `new Response(body)`. A bare `Response` is a + * valid `ResponseInit` (the spec reads `status`/`statusText`/`headers` off of + * whatever object it's given) and is by far the fastest of the options, since + * the runtime can copy the already-parsed header list instead of re-parsing an + * object literal. Nothing is shared with the constructed response, so a single + * template can be reused for every request. + * + * The template is probed once at startup and falls back to a plain object for + * runtimes that don't handle it. + */ +function createContentTypeInit(contentType: string): ResponseInit { + const template = new Response(null, { headers: { "Content-Type": contentType } }); + try { + const probe = new Response(null, template); + if (probe.status === 200 && probe.headers.get("Content-Type") === contentType) return template; + } catch { + // Fall through to the portable form. } + return { headers: template.headers }; } -export const IsStatusResult = Symbol("IsStatusResult"); +export const TEXT_RESPONSE_INIT: ResponseInit = createContentTypeInit("text/plain"); +export const JSON_RESPONSE_INIT: ResponseInit = createContentTypeInit("application/json"); -export function isStatusResult(result: any): result is StatusResult { - return IsStatusResult in result; -} +export const IsStatusResult = Symbol("IsStatusResult"); export function cleanupCompiledWhitespace(code: string): string { return ( diff --git a/src/types.ts b/src/types.ts index 411a583..8f71ae8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -423,6 +423,12 @@ export type LifeCycleHook = { * The function called when the hook is triggered. */ callback: TCallback; + /** + * Set by `app.decorate` to a static object of values to merge into the + * request context. When present, compiled handlers assign the keys directly + * instead of calling `callback` and iterating over its result. + */ + decoration?: Record; }; /**