@sigil-dev/grimoire 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/index.ts +35 -35
  2. package/package.json +8 -8
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +13 -7
  6. package/src/client/enhance.ts +98 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +2 -2
  9. package/src/client/router.ts +445 -371
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +163 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +114 -114
  14. package/src/dev/hmr-client.ts +185 -185
  15. package/src/dev/loader.ts +47 -47
  16. package/src/dev/paths.ts +14 -14
  17. package/src/dev/runtime-bundle.ts +52 -52
  18. package/src/dev/watcher.ts +47 -46
  19. package/src/env/dynamic-private.ts +19 -19
  20. package/src/env/dynamic-public.ts +22 -22
  21. package/src/env/index.ts +25 -25
  22. package/src/env/plugin.ts +19 -19
  23. package/src/env/private.ts +5 -5
  24. package/src/env/public.ts +7 -7
  25. package/src/env/typegen.ts +61 -61
  26. package/src/headers.ts +114 -114
  27. package/src/integrations/vite.ts +73 -73
  28. package/src/logger/index.ts +4 -4
  29. package/src/logger/instance.ts +6 -6
  30. package/src/logger/logger.ts +113 -113
  31. package/src/logger/request-middleware.ts +24 -24
  32. package/src/logger/transports.ts +117 -117
  33. package/src/logger/types.ts +39 -39
  34. package/src/rendering/head.ts +47 -47
  35. package/src/rendering/hydrate.ts +98 -79
  36. package/src/rendering/index.ts +455 -372
  37. package/src/rendering/ssrPlugin.ts +69 -69
  38. package/src/routing/manifest-gen.ts +12 -11
  39. package/src/routing/router.ts +109 -109
  40. package/src/routing/scanner.ts +141 -141
  41. package/src/routing/transform-routes.ts +102 -102
  42. package/src/sentinels/error.ts +52 -52
  43. package/src/sentinels/fail.ts +41 -41
  44. package/src/sentinels/redirect.ts +35 -35
  45. package/src/server/build.ts +243 -219
  46. package/src/server/context.ts +10 -10
  47. package/src/server/cookie-utils.ts +66 -66
  48. package/src/server/coordinator.ts +364 -356
  49. package/src/server/hooks.ts +114 -114
  50. package/src/server/index.ts +655 -658
  51. package/src/server/interactive.ts +56 -56
  52. package/src/server/plugins.ts +121 -120
  53. package/src/server/worker.ts +58 -58
  54. package/src/typegen/index.ts +356 -356
  55. package/src/types.ts +4 -4
  56. package/test/client-router.test.ts +37 -31
  57. package/test/context.test.ts +52 -52
  58. package/test/env.test.ts +70 -70
  59. package/test/exports.test.ts +37 -37
  60. package/test/fail.test.ts +46 -46
  61. package/test/headers.test.ts +100 -100
  62. package/test/hydration.test.ts +119 -119
  63. package/test/middleware.test.ts +223 -223
  64. package/test/preload.ts +5 -5
  65. package/test/redirect-error.test.ts +112 -112
  66. package/test/rendering.test.ts +615 -579
  67. package/test/routing.test.ts +81 -81
  68. package/test/scanning.test.ts +200 -200
  69. package/test/scope.test.ts +195 -195
  70. package/test/server.test.ts +249 -249
  71. package/test/streaming.test.ts +125 -125
  72. package/test/transform-routes.test.ts +84 -84
  73. package/test/typegen.test.ts +682 -682
  74. package/tsconfig.json +10 -10
  75. package/.grimoire/_routes.dom.js +0 -8
  76. package/.grimoire/_routes.hydrate.js +0 -8
  77. package/.grimoire/tsconfig.generated.json +0 -11
  78. package/.grimoire/types/ambient.d.ts +0 -59
  79. package/.grimoire/types/api/hello/$types.d.ts +0 -50
  80. package/.grimoire/types/api/items/$types.d.ts +0 -50
  81. package/.grimoire/types/echo/$types.d.ts +0 -50
  82. package/.grimoire/types/env-private.d.ts +0 -5
  83. package/.grimoire/types/env-public.d.ts +0 -5
  84. package/.grimoire/types/mixed/$types.d.ts +0 -50
  85. package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
  86. package/.grimoire/types/reject/$types.d.ts +0 -50
  87. package/public/__grimoire__/hydrate.js +0 -585
  88. package/public/__grimoire__/index.js +0 -490
@@ -1,372 +1,455 @@
1
- import { randomBytes } from "node:crypto";
2
- import { SafeHtml } from "@sigil-dev/runtime";
3
- import { findClosestError, type MatchedRoute } from "../routing/router";
4
- import type { RouteFile } from "../routing/scanner";
5
- import { isErrorResult } from "../sentinels/error.ts";
6
- import { isRedirectResult } from "../sentinels/redirect.ts";
7
- import { runWithContext } from "../server/context";
8
- import { runHook } from "../server/plugins";
9
- import type { GrimoirePlugin, LoadContext, Route } from "../types";
10
- import { collectHead, initHead } from "./head";
11
-
12
- export type ModuleLoader = (path: string) => Promise<any>;
13
-
14
- async function renderErrorPage(
15
- errorRoutes: RouteFile[],
16
- pathname: string,
17
- status: number,
18
- message: string,
19
- error?: unknown,
20
- ): Promise<Response | null> {
21
- const errorPage = findClosestError(errorRoutes, pathname);
22
- if (!errorPage) return null;
23
- const mod = await import(errorPage.filePath);
24
- const html = mod.default({ status, message, error, route: pathname });
25
- return new Response(html, {
26
- status,
27
- headers: { "Content-Type": "text/html" },
28
- });
29
- }
30
-
31
- function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
32
- return `<!DOCTYPE html>
33
- <html>
34
- <head>
35
- <meta charset="UTF-8" />
36
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
37
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
38
- ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
39
- }
40
-
41
- export async function renderRoute(
42
- matched: MatchedRoute,
43
- req: Request,
44
- errorRoutes: RouteFile[] = [],
45
- loadModule: ModuleLoader = (path) => import(path),
46
- locals: Record<string, any> = {},
47
- plugins: GrimoirePlugin[] = [],
48
- cspNonce?: string,
49
- dev?: boolean,
50
- patchedFetch?: typeof fetch,
51
- ): Promise<Response> {
52
- return runWithContext(async () => {
53
- const context: LoadContext = {
54
- request: req,
55
- params: matched.params,
56
- url: new URL(req.url),
57
- locals,
58
- fetch: patchedFetch ?? globalThis.fetch,
59
- };
60
-
61
- initHead(cspNonce);
62
-
63
- const route: Route = {
64
- path: matched.route.path,
65
- params: matched.params,
66
- filePath: matched.route.filePath,
67
- loadPath: matched.pageServer?.filePath,
68
- layoutPath: matched.layouts.at(-1)?.filePath,
69
- };
70
- await runHook(plugins, "onRouteLoad", route, context);
71
-
72
- // ── layout loading ──────────────────────────────────────────────────────
73
- const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
74
- for (const layout of matched.layouts) {
75
- const layoutMod = await loadModule(layout.filePath);
76
-
77
- if (layoutMod.canMatch) {
78
- try {
79
- const result = await layoutMod.canMatch(context);
80
- if (result === false)
81
- return new Response("Not Found", { status: 404 });
82
- if (isRedirectResult(result))
83
- return new Response(null, {
84
- status: result.status,
85
- headers: { Location: result.location },
86
- });
87
- } catch (e) {
88
- if (isRedirectResult(e))
89
- return new Response(null, {
90
- status: e.status,
91
- headers: { Location: e.location },
92
- });
93
- if (isErrorResult(e))
94
- return (
95
- (await renderErrorPage(
96
- errorRoutes,
97
- context.url.pathname,
98
- e.status,
99
- e.message,
100
- e,
101
- )) ?? new Response(e.message, { status: e.status })
102
- );
103
- throw e;
104
- }
105
- }
106
-
107
- const layoutServer = matched.layoutServers.find(
108
- (ls) => ls.path === layout.path,
109
- );
110
- let data: unknown;
111
- if (layoutServer) {
112
- try {
113
- const mod = await loadModule(layoutServer.filePath);
114
- data = await mod.load?.(context);
115
- } catch (e) {
116
- if (isRedirectResult(e))
117
- return new Response(null, {
118
- status: e.status,
119
- headers: { Location: e.location },
120
- });
121
- if (isErrorResult(e))
122
- return (
123
- (await renderErrorPage(
124
- errorRoutes,
125
- context.url.pathname,
126
- e.status,
127
- e.message,
128
- e,
129
- )) ?? new Response(e.message, { status: e.status })
130
- );
131
- throw e;
132
- }
133
- }
134
-
135
- const universalLayoutData = layoutMod.load
136
- ? await layoutMod.load(context)
137
- : undefined;
138
-
139
- const mergedLayoutData =
140
- universalLayoutData !== undefined
141
- ? //@ts-expect-error user-provided data is always unknown
142
- { ...universalLayoutData, ...data }
143
- : data;
144
-
145
- layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
146
- }
147
-
148
- // ── page server load ────────────────────────────────────────────────────
149
- let pageData: unknown;
150
- if (matched.pageServer) {
151
- try {
152
- const mod = await loadModule(matched.pageServer.filePath);
153
- pageData = await mod.load?.(context);
154
- } catch (e) {
155
- if (isRedirectResult(e))
156
- return new Response(null, {
157
- status: e.status,
158
- headers: { Location: e.location },
159
- });
160
- if (isErrorResult(e))
161
- return (
162
- (await renderErrorPage(
163
- errorRoutes,
164
- context.url.pathname,
165
- e.status,
166
- e.message,
167
- e,
168
- )) ?? new Response(e.message, { status: e.status })
169
- );
170
- throw e;
171
- }
172
- }
173
-
174
- // ── page module ─────────────────────────────────────────────────────────
175
- const pageMod = await loadModule(matched.route.filePath);
176
-
177
- if (pageMod.canMatch) {
178
- try {
179
- const result = await pageMod.canMatch(context);
180
- if (result === false)
181
- return new Response("Not Found", { status: 404 });
182
- if (isRedirectResult(result))
183
- return new Response(null, {
184
- status: result.status,
185
- headers: { Location: result.location },
186
- });
187
- } catch (e) {
188
- if (isRedirectResult(e))
189
- return new Response(null, {
190
- status: e.status,
191
- headers: { Location: e.location },
192
- });
193
- if (isErrorResult(e))
194
- return (
195
- (await renderErrorPage(
196
- errorRoutes,
197
- context.url.pathname,
198
- e.status,
199
- e.message,
200
- e,
201
- )) ?? new Response(e.message, { status: e.status })
202
- );
203
- throw e;
204
- }
205
- }
206
-
207
- const isNavigate = req.headers.get("x-grimoire-navigate") === "1";
208
- const hasLoading = typeof pageMod.loading === "function";
209
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
210
-
211
- // helper: wrap page html in layout tree
212
- function applyLayouts(pageHtml: string): string {
213
- let bodyHtml = `<div id="grimoire-page">${pageHtml}</div>`;
214
- for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
215
- bodyHtml = String(
216
- layoutMod.default({
217
- data,
218
- children: new SafeHtml(bodyHtml),
219
- params: matched.params,
220
- }),
221
- );
222
- }
223
- return `<div id="grimoire-root">${bodyHtml}</div>`;
224
- }
225
-
226
- // ── two-pass streaming (loading export present) ─────────────────────────
227
- if (hasLoading && !isNavigate) {
228
- const uid = Math.random().toString(36).slice(2);
229
- const loadingHtml = String(pageMod.loading());
230
- const loadingBody = applyLayouts(
231
- `<div id="ab-${uid}">${loadingHtml}</div>`,
232
- );
233
-
234
- const stream = new ReadableStream({
235
- async start(controller) {
236
- // 1. skeleton + loading shell — browser paints immediately
237
- controller.enqueue(
238
- `${buildHtmlSkeleton(nonceAttr, dev)}
239
- </head>
240
- <body>
241
- <div id="app">${loadingBody}`,
242
- );
243
-
244
- // 2. run universal load while browser renders shell
245
- const universalData = pageMod.load
246
- ? await pageMod.load(context).catch((e: unknown) => {
247
- if (isRedirectResult(e)) throw e;
248
- if (isErrorResult(e)) throw e;
249
- throw e;
250
- })
251
- : undefined;
252
-
253
- const mergedData =
254
- universalData !== undefined
255
- ? //@ts-expect-error user-provided data is always unknown
256
- { ...universalData, ...pageData }
257
- : pageData;
258
-
259
- // 3. render real page + collect head
260
- const pageHtml = await Promise.resolve(
261
- pageMod.default({ data: mergedData, params: matched.params }),
262
- );
263
- const headHtml = collectHead();
264
- const stateJson = JSON.stringify({
265
- params: matched.params,
266
- data: mergedData,
267
- layoutData: layoutPairs.map((l) => l.data),
268
- pattern: matched.route.path,
269
- });
270
-
271
- // 4. inject late head tags
272
- if (headHtml) {
273
- controller.enqueue(
274
- `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
275
- );
276
- }
277
-
278
- // 5. swap shell with real content
279
- controller.enqueue(
280
- `<template id="ab-${uid}-r">${String(pageHtml)}</template>
281
- <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
282
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
283
- </div>
284
- </body>
285
- </html>`,
286
- );
287
-
288
- controller.close();
289
- },
290
- });
291
-
292
- return new Response(stream, {
293
- headers: { "Content-Type": "text/html" },
294
- });
295
- }
296
-
297
- // ── single-pass (no loading export) ────────────────────────────────────
298
- const universalData = pageMod.load
299
- ? await pageMod.load(context).catch((e) => {
300
- if (isRedirectResult(e)) throw e;
301
- if (isErrorResult(e)) throw e;
302
- throw e;
303
- })
304
- : undefined;
305
-
306
- const mergedData =
307
- universalData !== undefined
308
- ? //@ts-expect-error user-provided data is always unknown
309
- { ...universalData, ...pageData }
310
- : pageData;
311
-
312
- const pageHtml = await Promise.resolve(
313
- pageMod.default({ data: mergedData, params: matched.params }),
314
- );
315
-
316
- const headHtml = collectHead();
317
-
318
- // ── navigation request — client handles rendering ───────────────────────
319
- if (isNavigate) {
320
- return Response.json({
321
- data: mergedData ?? {},
322
- layoutData: layoutPairs.map((l) => l.data),
323
- params: matched.params,
324
- pattern: matched.route.path,
325
- head: headHtml,
326
- });
327
- }
328
-
329
- // ── single-pass SSR stream ──────────────────────────────────────────────
330
- const csrfToken = randomBytes(32).toString("hex");
331
- const stateJson = JSON.stringify({
332
- params: matched.params,
333
- data: mergedData,
334
- layoutData: layoutPairs.map((l) => l.data),
335
- pattern: matched.route.path,
336
- });
337
-
338
- let bodyHtml = applyLayouts(String(pageHtml));
339
-
340
- const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
341
- bodyHtml = bodyHtml.replace(
342
- /<form([^>]*action=[^>]*)>/gi,
343
- `<form$1>${csrfInput}`,
344
- );
345
-
346
- const stream = new ReadableStream({
347
- start(controller) {
348
- controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
349
-
350
- if (headHtml) {
351
- controller.enqueue(`\n${headHtml}`);
352
- }
353
-
354
- controller.enqueue(`\n</head>
355
- <body>
356
- <div id="app">${bodyHtml}</div>
357
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
358
- </body>
359
- </html>`);
360
-
361
- controller.close();
362
- },
363
- });
364
-
365
- return new Response(stream, {
366
- headers: {
367
- "Content-Type": "text/html",
368
- "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
369
- },
370
- });
371
- });
372
- }
1
+ import { randomBytes } from "node:crypto";
2
+ import { SafeHtml } from "@sigil-dev/runtime";
3
+ import { findClosestError, type MatchedRoute } from "../routing/router";
4
+ import type { RouteFile } from "../routing/scanner";
5
+ import { isErrorResult } from "../sentinels/error.ts";
6
+ import { isRedirectResult } from "../sentinels/redirect.ts";
7
+ import { runWithContext } from "../server/context";
8
+ import { runHook } from "../server/plugins";
9
+ import type { GrimoirePlugin, LoadContext, Route } from "../types";
10
+ import { collectHead, initHead } from "./head";
11
+
12
+ export type ModuleLoader = (path: string) => Promise<any>;
13
+
14
+ type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
15
+
16
+ function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
17
+ return `<!DOCTYPE html>
18
+ <html>
19
+ <head>
20
+ <meta charset="UTF-8" />
21
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
22
+ <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
23
+ ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
24
+ }
25
+
26
+ /**
27
+ * Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
28
+ * be emitted in <head>, where they are render-blocking. Components declare
29
+ * stylesheets inline in JSX (usually in a layout), which lands them in the
30
+ * body — the browser paints the unstyled document before body CSS applies,
31
+ * causing a white flash on every full-document load. The body originals are
32
+ * left in place so hydration can still claim them; the head copy shares the
33
+ * same URL, so the browser only fetches once.
34
+ */
35
+ function hoistStylesheets(bodyHtml: string): string {
36
+ const links = new Set<string>();
37
+ for (const m of bodyHtml.matchAll(
38
+ /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
39
+ )) {
40
+ links.add(m[0]);
41
+ }
42
+ return [...links].join("\n ");
43
+ }
44
+
45
+ /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
46
+ function applyLayoutTree(
47
+ innerHtml: string,
48
+ layoutPairs: LayoutPair[],
49
+ params: Record<string, string>,
50
+ innerId = "grimoire-page",
51
+ ): string {
52
+ let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
53
+ for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
54
+ bodyHtml = String(
55
+ layoutMod.default({
56
+ data,
57
+ children: new SafeHtml(bodyHtml),
58
+ params,
59
+ }),
60
+ );
61
+ }
62
+ return `<div id="grimoire-root">${bodyHtml}</div>`;
63
+ }
64
+
65
+ /**
66
+ * Render a +error.tsx page as a full HTML document (doctype, hydration
67
+ * script, and any parent layouts that had already loaded successfully),
68
+ * instead of a bare fragment. No __grimoire_state__ script is emitted —
69
+ * error pages aren't part of the client route table, so hydrate.js
70
+ * simply skips client hydration for them (SSR-only, which is correct
71
+ * since there's no client-side error route to hydrate against).
72
+ */
73
+ export async function renderErrorPage(
74
+ errorRoutes: RouteFile[],
75
+ pathname: string,
76
+ status: number,
77
+ message: string,
78
+ error: unknown,
79
+ loadModule: ModuleLoader,
80
+ opts: {
81
+ layoutPairs?: LayoutPair[];
82
+ params?: Record<string, string>;
83
+ nonceAttr?: string;
84
+ dev?: boolean;
85
+ } = {},
86
+ ): Promise<Response | null> {
87
+ const errorPage = findClosestError(errorRoutes, pathname);
88
+ if (!errorPage) return null;
89
+ const mod = await loadModule(errorPage.filePath);
90
+
91
+ const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
92
+
93
+ // own context so <Head> used by the error page (or wrapping layouts)
94
+ // is collected fresh, independent of whatever the failed page pushed
95
+ return runWithContext(async () => {
96
+ const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
97
+ initHead(nonce);
98
+
99
+ const errorHtml = String(
100
+ mod.default({ status, message, error, route: pathname }),
101
+ );
102
+ const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
103
+ const headHtml = collectHead();
104
+ const hoistedCss = hoistStylesheets(bodyHtml);
105
+
106
+ const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
107
+ </head>
108
+ <body>
109
+ <div id="app">${bodyHtml}</div>
110
+ </body>
111
+ </html>`;
112
+
113
+ return new Response(html, {
114
+ status,
115
+ headers: { "Content-Type": "text/html" },
116
+ });
117
+ });
118
+ }
119
+
120
+ export async function renderRoute(
121
+ matched: MatchedRoute,
122
+ req: Request,
123
+ errorRoutes: RouteFile[] = [],
124
+ loadModule: ModuleLoader = (path) => import(path),
125
+ locals: Record<string, any> = {},
126
+ plugins: GrimoirePlugin[] = [],
127
+ cspNonce?: string,
128
+ dev?: boolean,
129
+ patchedFetch?: typeof fetch,
130
+ ): Promise<Response> {
131
+ return runWithContext(async () => {
132
+ const context: LoadContext = {
133
+ request: req,
134
+ params: matched.params,
135
+ url: new URL(req.url),
136
+ locals,
137
+ fetch: patchedFetch ?? globalThis.fetch,
138
+ };
139
+
140
+ initHead(cspNonce);
141
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
142
+
143
+ const route: Route = {
144
+ path: matched.route.path,
145
+ params: matched.params,
146
+ filePath: matched.route.filePath,
147
+ loadPath: matched.pageServer?.filePath,
148
+ layoutPath: matched.layouts.at(-1)?.filePath,
149
+ };
150
+ await runHook(plugins, "onRouteLoad", route, context);
151
+
152
+ // ── layout loading ──────────────────────────────────────────────────────
153
+ const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
154
+ for (const layout of matched.layouts) {
155
+ const layoutMod = await loadModule(layout.filePath);
156
+
157
+ if (layoutMod.canMatch) {
158
+ try {
159
+ const result = await layoutMod.canMatch(context);
160
+ if (result === false)
161
+ return new Response("Not Found", { status: 404 });
162
+ if (isRedirectResult(result))
163
+ return new Response(null, {
164
+ status: result.status,
165
+ headers: { Location: result.location },
166
+ });
167
+ } catch (e) {
168
+ if (isRedirectResult(e))
169
+ return new Response(null, {
170
+ status: e.status,
171
+ headers: { Location: e.location },
172
+ });
173
+ if (isErrorResult(e))
174
+ return (
175
+ (await renderErrorPage(
176
+ errorRoutes,
177
+ context.url.pathname,
178
+ e.status,
179
+ e.message,
180
+ e,
181
+ loadModule,
182
+ { layoutPairs, params: matched.params, nonceAttr, dev },
183
+ )) ?? new Response(e.message, { status: e.status })
184
+ );
185
+ throw e;
186
+ }
187
+ }
188
+
189
+ const layoutServer = matched.layoutServers.find(
190
+ (ls) => ls.path === layout.path,
191
+ );
192
+ let data: unknown;
193
+ if (layoutServer) {
194
+ try {
195
+ const mod = await loadModule(layoutServer.filePath);
196
+ data = await mod.load?.(context);
197
+ } catch (e) {
198
+ if (isRedirectResult(e))
199
+ return new Response(null, {
200
+ status: e.status,
201
+ headers: { Location: e.location },
202
+ });
203
+ if (isErrorResult(e))
204
+ return (
205
+ (await renderErrorPage(
206
+ errorRoutes,
207
+ context.url.pathname,
208
+ e.status,
209
+ e.message,
210
+ e,
211
+ loadModule,
212
+ { layoutPairs, params: matched.params, nonceAttr, dev },
213
+ )) ?? new Response(e.message, { status: e.status })
214
+ );
215
+ throw e;
216
+ }
217
+ }
218
+
219
+ const universalLayoutData = layoutMod.load
220
+ ? await layoutMod.load(context)
221
+ : undefined;
222
+
223
+ const mergedLayoutData =
224
+ universalLayoutData !== undefined
225
+ ? //@ts-expect-error user-provided data is always unknown
226
+ { ...universalLayoutData, ...data }
227
+ : data;
228
+
229
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
230
+ }
231
+
232
+ // ── page server load ────────────────────────────────────────────────────
233
+ let pageData: unknown;
234
+ if (matched.pageServer) {
235
+ try {
236
+ const mod = await loadModule(matched.pageServer.filePath);
237
+ pageData = await mod.load?.(context);
238
+ } catch (e) {
239
+ if (isRedirectResult(e))
240
+ return new Response(null, {
241
+ status: e.status,
242
+ headers: { Location: e.location },
243
+ });
244
+ if (isErrorResult(e))
245
+ return (
246
+ (await renderErrorPage(
247
+ errorRoutes,
248
+ context.url.pathname,
249
+ e.status,
250
+ e.message,
251
+ e,
252
+ loadModule,
253
+ { layoutPairs, params: matched.params, nonceAttr, dev },
254
+ )) ?? new Response(e.message, { status: e.status })
255
+ );
256
+ throw e;
257
+ }
258
+ }
259
+
260
+ // ── page module ─────────────────────────────────────────────────────────
261
+ const pageMod = await loadModule(matched.route.filePath);
262
+
263
+ if (pageMod.canMatch) {
264
+ try {
265
+ const result = await pageMod.canMatch(context);
266
+ if (result === false) return new Response("Not Found", { status: 404 });
267
+ if (isRedirectResult(result))
268
+ return new Response(null, {
269
+ status: result.status,
270
+ headers: { Location: result.location },
271
+ });
272
+ } catch (e) {
273
+ if (isRedirectResult(e))
274
+ return new Response(null, {
275
+ status: e.status,
276
+ headers: { Location: e.location },
277
+ });
278
+ if (isErrorResult(e))
279
+ return (
280
+ (await renderErrorPage(
281
+ errorRoutes,
282
+ context.url.pathname,
283
+ e.status,
284
+ e.message,
285
+ e,
286
+ loadModule,
287
+ { layoutPairs, params: matched.params, nonceAttr, dev },
288
+ )) ?? new Response(e.message, { status: e.status })
289
+ );
290
+ throw e;
291
+ }
292
+ }
293
+
294
+ const isNavigate = req.headers.get("x-grimoire-navigate") === "1";
295
+ const hasLoading = typeof pageMod.loading === "function";
296
+
297
+ // helper: wrap page html in layout tree
298
+ function applyLayouts(pageHtml: string): string {
299
+ return applyLayoutTree(pageHtml, layoutPairs, matched.params);
300
+ }
301
+
302
+ // ── two-pass streaming (loading export present) ─────────────────────────
303
+ if (hasLoading && !isNavigate) {
304
+ const uid = Math.random().toString(36).slice(2);
305
+ const loadingHtml = String(pageMod.loading());
306
+ const loadingBody = applyLayouts(
307
+ `<div id="ab-${uid}">${loadingHtml}</div>`,
308
+ );
309
+ // layout stylesheets are in the loading shell — hoist before first flush
310
+ const hoistedCss = hoistStylesheets(loadingBody);
311
+
312
+ const stream = new ReadableStream({
313
+ async start(controller) {
314
+ // 1. skeleton + loading shell — browser paints immediately
315
+ controller.enqueue(
316
+ `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
317
+ </head>
318
+ <body>
319
+ <div id="app">${loadingBody}`,
320
+ );
321
+
322
+ // 2. run universal load while browser renders shell
323
+ const universalData = pageMod.load
324
+ ? await pageMod.load(context).catch((e: unknown) => {
325
+ if (isRedirectResult(e)) throw e;
326
+ if (isErrorResult(e)) throw e;
327
+ throw e;
328
+ })
329
+ : undefined;
330
+
331
+ const mergedData =
332
+ universalData !== undefined
333
+ ? //@ts-expect-error user-provided data is always unknown
334
+ { ...universalData, ...pageData }
335
+ : pageData;
336
+
337
+ // 3. render real page + collect head
338
+ const pageHtml = await Promise.resolve(
339
+ pageMod.default({ data: mergedData, params: matched.params }),
340
+ );
341
+ const headHtml = collectHead();
342
+ const stateJson = JSON.stringify({
343
+ params: matched.params,
344
+ data: mergedData,
345
+ layoutData: layoutPairs.map((l) => l.data),
346
+ pattern: matched.route.path,
347
+ });
348
+
349
+ // 4. inject late head tags
350
+ if (headHtml) {
351
+ controller.enqueue(
352
+ `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
353
+ );
354
+ }
355
+
356
+ // 5. swap shell with real content
357
+ controller.enqueue(
358
+ `<template id="ab-${uid}-r">${String(pageHtml)}</template>
359
+ <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
360
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
361
+ </div>
362
+ </body>
363
+ </html>`,
364
+ );
365
+
366
+ controller.close();
367
+ },
368
+ });
369
+
370
+ return new Response(stream, {
371
+ headers: { "Content-Type": "text/html" },
372
+ });
373
+ }
374
+
375
+ // ── single-pass (no loading export) ────────────────────────────────────
376
+ const universalData = pageMod.load
377
+ ? await pageMod.load(context).catch((e) => {
378
+ if (isRedirectResult(e)) throw e;
379
+ if (isErrorResult(e)) throw e;
380
+ throw e;
381
+ })
382
+ : undefined;
383
+
384
+ const mergedData =
385
+ universalData !== undefined
386
+ ? //@ts-expect-error user-provided data is always unknown
387
+ { ...universalData, ...pageData }
388
+ : pageData;
389
+
390
+ const pageHtml = await Promise.resolve(
391
+ pageMod.default({ data: mergedData, params: matched.params }),
392
+ );
393
+
394
+ const headHtml = collectHead();
395
+
396
+ // ── navigation request — client handles rendering ───────────────────────
397
+ if (isNavigate) {
398
+ return Response.json({
399
+ data: mergedData ?? {},
400
+ layoutData: layoutPairs.map((l) => l.data),
401
+ params: matched.params,
402
+ pattern: matched.route.path,
403
+ head: headHtml,
404
+ });
405
+ }
406
+
407
+ // ── single-pass SSR stream ──────────────────────────────────────────────
408
+ const csrfToken = randomBytes(32).toString("hex");
409
+ const stateJson = JSON.stringify({
410
+ params: matched.params,
411
+ data: mergedData,
412
+ layoutData: layoutPairs.map((l) => l.data),
413
+ pattern: matched.route.path,
414
+ });
415
+
416
+ let bodyHtml = applyLayouts(String(pageHtml));
417
+
418
+ const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
419
+ bodyHtml = bodyHtml.replace(
420
+ /<form([^>]*action=[^>]*)>/gi,
421
+ `<form$1>${csrfInput}`,
422
+ );
423
+
424
+ const hoistedCss = hoistStylesheets(bodyHtml);
425
+
426
+ const stream = new ReadableStream({
427
+ start(controller) {
428
+ controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
429
+
430
+ if (hoistedCss) {
431
+ controller.enqueue(`\n ${hoistedCss}`);
432
+ }
433
+ if (headHtml) {
434
+ controller.enqueue(`\n${headHtml}`);
435
+ }
436
+
437
+ controller.enqueue(`\n</head>
438
+ <body>
439
+ <div id="app">${bodyHtml}</div>
440
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
441
+ </body>
442
+ </html>`);
443
+
444
+ controller.close();
445
+ },
446
+ });
447
+
448
+ return new Response(stream, {
449
+ headers: {
450
+ "Content-Type": "text/html",
451
+ "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
452
+ },
453
+ });
454
+ });
455
+ }