@sigil-dev/grimoire 0.8.6 → 0.9.0

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.
@@ -28,6 +28,16 @@ async function renderErrorPage(
28
28
  });
29
29
  }
30
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
+
31
41
  export async function renderRoute(
32
42
  matched: MatchedRoute,
33
43
  req: Request,
@@ -36,16 +46,16 @@ export async function renderRoute(
36
46
  locals: Record<string, any> = {},
37
47
  plugins: GrimoirePlugin[] = [],
38
48
  cspNonce?: string,
39
- dev?: boolean,
40
- patchedFetch
49
+ dev?: boolean,
50
+ patchedFetch?: typeof fetch,
41
51
  ): Promise<Response> {
42
52
  return runWithContext(async () => {
43
53
  const context: LoadContext = {
44
54
  request: req,
45
55
  params: matched.params,
46
56
  url: new URL(req.url),
47
- locals,
48
- fetch: patchedFetch ?? globalThis.fetch
57
+ locals,
58
+ fetch: patchedFetch ?? globalThis.fetch,
49
59
  };
50
60
 
51
61
  initHead(cspNonce);
@@ -59,6 +69,7 @@ export async function renderRoute(
59
69
  };
60
70
  await runHook(plugins, "onRouteLoad", route, context);
61
71
 
72
+ // ── layout loading ──────────────────────────────────────────────────────
62
73
  const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
63
74
  for (const layout of matched.layouts) {
64
75
  const layoutMod = await loadModule(layout.filePath);
@@ -120,32 +131,33 @@ export async function renderRoute(
120
131
  throw e;
121
132
  }
122
133
  }
134
+
123
135
  const universalLayoutData = layoutMod.load
124
136
  ? await layoutMod.load(context)
125
137
  : undefined;
126
138
 
127
139
  const mergedLayoutData =
128
140
  universalLayoutData !== undefined
129
- ? //@ts-expect-error User provded data is always unknown.
130
- { ...universalLayoutData, ...data }
141
+ ? //@ts-expect-error user-provided data is always unknown
142
+ { ...universalLayoutData, ...data }
131
143
  : data;
132
144
 
133
145
  layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
134
146
  }
135
147
 
148
+ // ── page server load ────────────────────────────────────────────────────
136
149
  let pageData: unknown;
137
150
  if (matched.pageServer) {
138
151
  try {
139
152
  const mod = await loadModule(matched.pageServer.filePath);
140
153
  pageData = await mod.load?.(context);
141
154
  } catch (e) {
142
- if (isRedirectResult(e)) {
155
+ if (isRedirectResult(e))
143
156
  return new Response(null, {
144
157
  status: e.status,
145
158
  headers: { Location: e.location },
146
159
  });
147
- }
148
- if (isErrorResult(e)) {
160
+ if (isErrorResult(e))
149
161
  return (
150
162
  (await renderErrorPage(
151
163
  errorRoutes,
@@ -155,16 +167,18 @@ export async function renderRoute(
155
167
  e,
156
168
  )) ?? new Response(e.message, { status: e.status })
157
169
  );
158
- }
159
170
  throw e;
160
171
  }
161
172
  }
162
173
 
174
+ // ── page module ─────────────────────────────────────────────────────────
163
175
  const pageMod = await loadModule(matched.route.filePath);
176
+
164
177
  if (pageMod.canMatch) {
165
178
  try {
166
179
  const result = await pageMod.canMatch(context);
167
- if (result === false) return new Response("Not Found", { status: 404 });
180
+ if (result === false)
181
+ return new Response("Not Found", { status: 404 });
168
182
  if (isRedirectResult(result))
169
183
  return new Response(null, {
170
184
  status: result.status,
@@ -190,30 +204,119 @@ export async function renderRoute(
190
204
  }
191
205
  }
192
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) ────────────────────────────────────
193
298
  const universalData = pageMod.load
194
299
  ? await pageMod.load(context).catch((e) => {
195
- if (isRedirectResult(e)) throw e;
196
- if (isErrorResult(e)) throw e;
197
- throw e;
198
- })
300
+ if (isRedirectResult(e)) throw e;
301
+ if (isErrorResult(e)) throw e;
302
+ throw e;
303
+ })
199
304
  : undefined;
200
305
 
201
306
  const mergedData =
202
307
  universalData !== undefined
203
- ? //@ts-expect-error User provded data is always unknown.
204
- { ...universalData, ...pageData }
308
+ ? //@ts-expect-error user-provided data is always unknown
309
+ { ...universalData, ...pageData }
205
310
  : pageData;
206
311
 
207
- const pageHtml = pageMod.default({
208
- data: mergedData,
209
- params: matched.params,
210
- });
312
+ const pageHtml = await Promise.resolve(
313
+ pageMod.default({ data: mergedData, params: matched.params }),
314
+ );
211
315
 
212
- // collect head AFTER page render so <Head> calls are captured
213
316
  const headHtml = collectHead();
214
317
 
215
- // navigation request: return JSON, client handles rendering
216
- if (req.headers.get("x-grimoire-navigate") === "1") {
318
+ // ── navigation request — client handles rendering ───────────────────────
319
+ if (isNavigate) {
217
320
  return Response.json({
218
321
  data: mergedData ?? {},
219
322
  layoutData: layoutPairs.map((l) => l.data),
@@ -223,20 +326,7 @@ export async function renderRoute(
223
326
  });
224
327
  }
225
328
 
226
- const wrappedPage = `<div id="grimoire-page">${String(pageHtml)}</div>`;
227
-
228
- let bodyHtml: string = wrappedPage;
229
- for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
230
- bodyHtml = String(
231
- layoutMod.default({
232
- data,
233
- children: new SafeHtml(bodyHtml),
234
- params: matched.params,
235
- }),
236
- );
237
- }
238
-
239
- bodyHtml = `<div id="grimoire-root">${bodyHtml}</div>`;
329
+ // ── single-pass SSR stream ──────────────────────────────────────────────
240
330
  const csrfToken = randomBytes(32).toString("hex");
241
331
  const stateJson = JSON.stringify({
242
332
  params: matched.params,
@@ -244,43 +334,27 @@ export async function renderRoute(
244
334
  layoutData: layoutPairs.map((l) => l.data),
245
335
  pattern: matched.route.path,
246
336
  });
337
+
338
+ let bodyHtml = applyLayouts(String(pageHtml));
339
+
247
340
  const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
248
341
  bodyHtml = bodyHtml.replace(
249
342
  /<form([^>]*action=[^>]*)>/gi,
250
343
  `<form$1>${csrfInput}`,
251
344
  );
252
- // --- Streaming SSR ---
253
- // Send DOCTYPE + head skeleton immediately (browser starts resource fetch).
254
- // Then stream body + full head content + state as they become available.
255
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
345
+
256
346
  const stream = new ReadableStream({
257
347
  start(controller) {
258
- // 1. Document skeleton — browser starts parsing, fetches CSS/JS
259
- controller.enqueue(
260
- `<!DOCTYPE html>
261
- <html>
262
- <head>
263
- <meta charset="UTF-8" />
264
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
265
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
266
- ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`,
267
- );
348
+ controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
268
349
 
269
- // 2. Head content (captured from <Head> component calls during render)
270
350
  if (headHtml) {
271
351
  controller.enqueue(`\n${headHtml}`);
272
352
  }
273
353
 
274
354
  controller.enqueue(`\n</head>
275
355
  <body>
276
- <div id="app">`);
277
-
278
- // 3. Page body
279
- controller.enqueue(bodyHtml);
280
-
281
- // 4. State script + closing tags
282
- controller.enqueue(`</div>
283
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
356
+ <div id="app">${bodyHtml}</div>
357
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
284
358
  </body>
285
359
  </html>`);
286
360
 
@@ -291,8 +365,8 @@ export async function renderRoute(
291
365
  return new Response(stream, {
292
366
  headers: {
293
367
  "Content-Type": "text/html",
294
- "Set-Cookie": "_csrf=${csrfToken}; SameSite=Strict; Path=/",
368
+ "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
295
369
  },
296
370
  });
297
371
  });
298
- }
372
+ }