@sigil-dev/grimoire 0.9.3 → 0.9.5
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.
- package/index.ts +37 -35
- package/package.json +9 -12
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +36 -19
- package/src/client/enhance.ts +102 -98
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +2 -2
- package/src/client/router.ts +174 -68
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +215 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +109 -114
- package/src/dev/hmr-client.ts +202 -185
- package/src/dev/hmr-server.ts +261 -187
- package/src/dev/loader.ts +120 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/resolve.ts +70 -0
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/scan.ts +78 -0
- package/src/dev/watcher.ts +69 -47
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +52 -47
- package/src/rendering/hydrate.ts +159 -138
- package/src/rendering/index.ts +140 -18
- package/src/rendering/ssrPlugin.ts +78 -69
- package/src/routing/manifest-gen.ts +13 -1
- package/src/routing/router.ts +135 -109
- package/src/routing/scanner.ts +196 -141
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +250 -243
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +364 -364
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +711 -655
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -121
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +389 -356
- package/src/types.ts +286 -282
- package/test/client-router.test.ts +295 -44
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +90 -90
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hmr.test.ts +426 -0
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +719 -615
- package/test/routing.test.ts +197 -81
- package/test/scanning.test.ts +314 -200
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +360 -249
- package/test/streaming.test.ts +242 -125
- package/test/transform-routes.test.ts +87 -84
- package/test/typegen.test.ts +697 -682
- package/tsconfig.json +10 -10
package/src/rendering/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { SafeHtml } from "@sigil-dev/runtime";
|
|
3
|
+
import { startCollecting, stopCollecting } from "../client/deps";
|
|
3
4
|
import { findClosestError, type MatchedRoute } from "../routing/router";
|
|
4
5
|
import type { RouteFile } from "../routing/scanner";
|
|
5
6
|
import { isErrorResult } from "../sentinels/error.ts";
|
|
@@ -13,6 +14,60 @@ export type ModuleLoader = (path: string) => Promise<any>;
|
|
|
13
14
|
|
|
14
15
|
type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
|
|
15
16
|
|
|
17
|
+
/** Placeholder for a top-level server-load promise still in flight. SSR text
|
|
18
|
+
* interpolation renders it as an empty string via the normal String(v) path. */
|
|
19
|
+
class DeferredMarker {
|
|
20
|
+
constructor(
|
|
21
|
+
public uid: string,
|
|
22
|
+
public key: string,
|
|
23
|
+
) {}
|
|
24
|
+
toString() {
|
|
25
|
+
return "";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Serialize the hydration state payload for embedding inside a
|
|
33
|
+
* `<script type="application/json">` tag. Escapes every `<` so a data value
|
|
34
|
+
* like `"</script><script>alert(1)</script>"` cannot close the state script
|
|
35
|
+
* early and inject markup. JSON.parse reads `\u003c` back as `<`.
|
|
36
|
+
* DeferredMarkers serialize to `{ __deferred: uid }`.
|
|
37
|
+
*/
|
|
38
|
+
const safeStateJson = (value: unknown): string =>
|
|
39
|
+
JSON.stringify(value, (_k, v) =>
|
|
40
|
+
v instanceof DeferredMarker ? { __deferred: v.uid } : v,
|
|
41
|
+
).replace(/</g, "\\u003c");
|
|
42
|
+
|
|
43
|
+
/** Replace every own top-level promise property with a marker and record the
|
|
44
|
+
* promise for late flush. Nested promises are awaited by the load itself. */
|
|
45
|
+
function extractDeferred(
|
|
46
|
+
data: unknown,
|
|
47
|
+
deferred: DeferredEntry[],
|
|
48
|
+
counter: { n: number },
|
|
49
|
+
): void {
|
|
50
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return;
|
|
51
|
+
const record = data as Record<string, unknown>;
|
|
52
|
+
for (const key of Object.keys(record)) {
|
|
53
|
+
const value = record[key];
|
|
54
|
+
if (value instanceof Promise) {
|
|
55
|
+
const uid = `gd-${counter.n++}`;
|
|
56
|
+
record[key] = new DeferredMarker(uid, key);
|
|
57
|
+
deferred.push({ promise: value, key, uid });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Template + patch script for one settled deferred value. */
|
|
63
|
+
function deferredChunk(key: string, value: unknown, error: boolean): string {
|
|
64
|
+
const keyJson = JSON.stringify(key);
|
|
65
|
+
// The value rides inline (safeStateJson escapes `<`, so the script cannot
|
|
66
|
+
// be broken out of). No DOM lookups: trailing chunks arrive after </html>,
|
|
67
|
+
// where element timing is unreliable across parsers.
|
|
68
|
+
return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
|
|
69
|
+
}
|
|
70
|
+
|
|
16
71
|
function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
|
|
17
72
|
return `<!DOCTYPE html>
|
|
18
73
|
<html>
|
|
@@ -47,6 +102,7 @@ function applyLayoutTree(
|
|
|
47
102
|
innerHtml: string,
|
|
48
103
|
layoutPairs: LayoutPair[],
|
|
49
104
|
params: Record<string, string>,
|
|
105
|
+
pattern?: string,
|
|
50
106
|
innerId = "grimoire-page",
|
|
51
107
|
): string {
|
|
52
108
|
let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
|
|
@@ -56,6 +112,7 @@ function applyLayoutTree(
|
|
|
56
112
|
data,
|
|
57
113
|
children: new SafeHtml(bodyHtml),
|
|
58
114
|
params,
|
|
115
|
+
path: pattern,
|
|
59
116
|
}),
|
|
60
117
|
);
|
|
61
118
|
}
|
|
@@ -135,11 +192,30 @@ export async function renderRoute(
|
|
|
135
192
|
url: new URL(req.url),
|
|
136
193
|
locals,
|
|
137
194
|
fetch: patchedFetch ?? globalThis.fetch,
|
|
195
|
+
// no layouts have loaded yet — parent() is empty until the loop runs
|
|
196
|
+
parent: async () => ({}),
|
|
138
197
|
};
|
|
139
198
|
|
|
140
199
|
initHead(cspNonce);
|
|
141
200
|
const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
|
|
142
201
|
|
|
202
|
+
// ── layout loading ──────────────────────────────────────────────────────
|
|
203
|
+
const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
|
|
204
|
+
const parentData: Record<string, unknown> = {};
|
|
205
|
+
// depends() keys gathered across every server-executed load
|
|
206
|
+
const collectedDeps = new Set<string>();
|
|
207
|
+
// top-level load promises flushed late (deferred streaming)
|
|
208
|
+
const deferred: DeferredEntry[] = [];
|
|
209
|
+
const deferredCounter = { n: 0 };
|
|
210
|
+
const collectDeps = async (run: () => unknown): Promise<unknown> => {
|
|
211
|
+
startCollecting();
|
|
212
|
+
try {
|
|
213
|
+
return await run();
|
|
214
|
+
} finally {
|
|
215
|
+
for (const key of stopCollecting()) collectedDeps.add(key);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
143
219
|
const route: Route = {
|
|
144
220
|
path: matched.route.path,
|
|
145
221
|
params: matched.params,
|
|
@@ -149,9 +225,10 @@ export async function renderRoute(
|
|
|
149
225
|
};
|
|
150
226
|
await runHook(plugins, "onRouteLoad", route, context);
|
|
151
227
|
|
|
152
|
-
// ── layout loading ──────────────────────────────────────────────────────
|
|
153
|
-
const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
|
|
154
228
|
for (const layout of matched.layouts) {
|
|
229
|
+
// loads in this layout see everything accumulated so far
|
|
230
|
+
context.parent = async () => ({ ...parentData });
|
|
231
|
+
|
|
155
232
|
const layoutMod = await loadModule(layout.filePath);
|
|
156
233
|
|
|
157
234
|
if (layoutMod.canMatch) {
|
|
@@ -193,7 +270,7 @@ export async function renderRoute(
|
|
|
193
270
|
if (layoutServer) {
|
|
194
271
|
try {
|
|
195
272
|
const mod = await loadModule(layoutServer.filePath);
|
|
196
|
-
data = await mod.load?.(context);
|
|
273
|
+
data = await collectDeps(() => mod.load?.(context));
|
|
197
274
|
} catch (e) {
|
|
198
275
|
if (isRedirectResult(e))
|
|
199
276
|
return new Response(null, {
|
|
@@ -217,7 +294,7 @@ export async function renderRoute(
|
|
|
217
294
|
}
|
|
218
295
|
|
|
219
296
|
const universalLayoutData = layoutMod.load
|
|
220
|
-
? await layoutMod.load(context)
|
|
297
|
+
? await collectDeps(() => layoutMod.load(context))
|
|
221
298
|
: undefined;
|
|
222
299
|
|
|
223
300
|
const mergedLayoutData =
|
|
@@ -227,14 +304,21 @@ export async function renderRoute(
|
|
|
227
304
|
: data;
|
|
228
305
|
|
|
229
306
|
layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
|
|
307
|
+
extractDeferred(mergedLayoutData, deferred, deferredCounter);
|
|
308
|
+
if (mergedLayoutData && typeof mergedLayoutData === "object") {
|
|
309
|
+
Object.assign(parentData, mergedLayoutData);
|
|
310
|
+
}
|
|
230
311
|
}
|
|
231
312
|
|
|
313
|
+
// page loads see every layout's data merged
|
|
314
|
+
context.parent = async () => ({ ...parentData });
|
|
315
|
+
|
|
232
316
|
// ── page server load ────────────────────────────────────────────────────
|
|
233
317
|
let pageData: unknown;
|
|
234
318
|
if (matched.pageServer) {
|
|
235
319
|
try {
|
|
236
320
|
const mod = await loadModule(matched.pageServer.filePath);
|
|
237
|
-
pageData = await mod.load?.(context);
|
|
321
|
+
pageData = await collectDeps(() => mod.load?.(context));
|
|
238
322
|
} catch (e) {
|
|
239
323
|
if (isRedirectResult(e))
|
|
240
324
|
return new Response(null, {
|
|
@@ -296,7 +380,7 @@ export async function renderRoute(
|
|
|
296
380
|
|
|
297
381
|
// helper: wrap page html in layout tree
|
|
298
382
|
function applyLayouts(pageHtml: string): string {
|
|
299
|
-
return applyLayoutTree(pageHtml, layoutPairs, matched.params);
|
|
383
|
+
return applyLayoutTree(pageHtml, layoutPairs, matched.params, matched.route.path);
|
|
300
384
|
}
|
|
301
385
|
|
|
302
386
|
// ── two-pass streaming (loading export present) ─────────────────────────
|
|
@@ -321,11 +405,13 @@ export async function renderRoute(
|
|
|
321
405
|
|
|
322
406
|
// 2. run universal load while browser renders shell
|
|
323
407
|
const universalData = pageMod.load
|
|
324
|
-
? await pageMod.load(context).catch(
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
408
|
+
? await collectDeps(() => pageMod.load(context)).catch(
|
|
409
|
+
(e: unknown) => {
|
|
410
|
+
if (isRedirectResult(e)) throw e;
|
|
411
|
+
if (isErrorResult(e)) throw e;
|
|
412
|
+
throw e;
|
|
413
|
+
},
|
|
414
|
+
)
|
|
329
415
|
: undefined;
|
|
330
416
|
|
|
331
417
|
const mergedData =
|
|
@@ -333,17 +419,19 @@ export async function renderRoute(
|
|
|
333
419
|
? //@ts-expect-error user-provided data is always unknown
|
|
334
420
|
{ ...universalData, ...pageData }
|
|
335
421
|
: pageData;
|
|
422
|
+
extractDeferred(mergedData, deferred, deferredCounter);
|
|
336
423
|
|
|
337
424
|
// 3. render real page + collect head
|
|
338
425
|
const pageHtml = await Promise.resolve(
|
|
339
426
|
pageMod.default({ data: mergedData, params: matched.params }),
|
|
340
427
|
);
|
|
341
428
|
const headHtml = collectHead();
|
|
342
|
-
const stateJson =
|
|
429
|
+
const stateJson = safeStateJson({
|
|
343
430
|
params: matched.params,
|
|
344
431
|
data: mergedData,
|
|
345
432
|
layoutData: layoutPairs.map((l) => l.data),
|
|
346
433
|
pattern: matched.route.path,
|
|
434
|
+
deps: [...collectedDeps],
|
|
347
435
|
});
|
|
348
436
|
|
|
349
437
|
// 4. inject late head tags
|
|
@@ -363,6 +451,16 @@ export async function renderRoute(
|
|
|
363
451
|
</html>`,
|
|
364
452
|
);
|
|
365
453
|
|
|
454
|
+
// 6. flush deferred values in order as they settle
|
|
455
|
+
for (const d of deferred) {
|
|
456
|
+
try {
|
|
457
|
+
const value = await d.promise;
|
|
458
|
+
controller.enqueue(deferredChunk(d.key, value, false));
|
|
459
|
+
} catch {
|
|
460
|
+
controller.enqueue(deferredChunk(d.key, null, true));
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
366
464
|
controller.close();
|
|
367
465
|
},
|
|
368
466
|
});
|
|
@@ -374,7 +472,7 @@ export async function renderRoute(
|
|
|
374
472
|
|
|
375
473
|
// ── single-pass (no loading export) ────────────────────────────────────
|
|
376
474
|
const universalData = pageMod.load
|
|
377
|
-
? await pageMod.load(context).catch((e) => {
|
|
475
|
+
? await collectDeps(() => pageMod.load(context)).catch((e) => {
|
|
378
476
|
if (isRedirectResult(e)) throw e;
|
|
379
477
|
if (isErrorResult(e)) throw e;
|
|
380
478
|
throw e;
|
|
@@ -386,35 +484,49 @@ export async function renderRoute(
|
|
|
386
484
|
? //@ts-expect-error user-provided data is always unknown
|
|
387
485
|
{ ...universalData, ...pageData }
|
|
388
486
|
: pageData;
|
|
487
|
+
extractDeferred(mergedData, deferred, deferredCounter);
|
|
389
488
|
|
|
390
489
|
const pageHtml = await Promise.resolve(
|
|
391
490
|
pageMod.default({ data: mergedData, params: matched.params }),
|
|
392
491
|
);
|
|
393
492
|
|
|
493
|
+
// layouts must render before collectHead(): a <Head> call inside a
|
|
494
|
+
// layout component (a common place for site-wide <title>/meta
|
|
495
|
+
// defaults) only registers once the layout itself has run, so
|
|
496
|
+
// collecting too early silently drops it
|
|
497
|
+
let bodyHtml = applyLayouts(String(pageHtml));
|
|
498
|
+
|
|
394
499
|
const headHtml = collectHead();
|
|
395
500
|
|
|
396
|
-
// ── navigation request — client handles rendering ───────────────────────
|
|
397
501
|
if (isNavigate) {
|
|
502
|
+
// no stream to flush into — resolve everything before responding
|
|
503
|
+
for (const d of deferred) {
|
|
504
|
+
try {
|
|
505
|
+
(mergedData as Record<string, unknown>)[d.key] = await d.promise;
|
|
506
|
+
} catch {
|
|
507
|
+
(mergedData as Record<string, unknown>)[d.key] = null;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
398
510
|
return Response.json({
|
|
399
511
|
data: mergedData ?? {},
|
|
400
512
|
layoutData: layoutPairs.map((l) => l.data),
|
|
401
513
|
params: matched.params,
|
|
402
514
|
pattern: matched.route.path,
|
|
403
515
|
head: headHtml,
|
|
516
|
+
deps: [...collectedDeps],
|
|
404
517
|
});
|
|
405
518
|
}
|
|
406
519
|
|
|
407
520
|
// ── single-pass SSR stream ──────────────────────────────────────────────
|
|
408
521
|
const csrfToken = randomBytes(32).toString("hex");
|
|
409
|
-
const stateJson =
|
|
522
|
+
const stateJson = safeStateJson({
|
|
410
523
|
params: matched.params,
|
|
411
524
|
data: mergedData,
|
|
412
525
|
layoutData: layoutPairs.map((l) => l.data),
|
|
413
526
|
pattern: matched.route.path,
|
|
527
|
+
deps: [...collectedDeps],
|
|
414
528
|
});
|
|
415
529
|
|
|
416
|
-
let bodyHtml = applyLayouts(String(pageHtml));
|
|
417
|
-
|
|
418
530
|
const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
|
|
419
531
|
bodyHtml = bodyHtml.replace(
|
|
420
532
|
/<form([^>]*action=[^>]*)>/gi,
|
|
@@ -424,7 +536,7 @@ export async function renderRoute(
|
|
|
424
536
|
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
425
537
|
|
|
426
538
|
const stream = new ReadableStream({
|
|
427
|
-
start(controller) {
|
|
539
|
+
async start(controller) {
|
|
428
540
|
controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
|
|
429
541
|
|
|
430
542
|
if (hoistedCss) {
|
|
@@ -441,6 +553,16 @@ export async function renderRoute(
|
|
|
441
553
|
</body>
|
|
442
554
|
</html>`);
|
|
443
555
|
|
|
556
|
+
// flush deferred values in order as they settle
|
|
557
|
+
for (const d of deferred) {
|
|
558
|
+
try {
|
|
559
|
+
const value = await d.promise;
|
|
560
|
+
controller.enqueue(deferredChunk(d.key, value, false));
|
|
561
|
+
} catch {
|
|
562
|
+
controller.enqueue(deferredChunk(d.key, null, true));
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
444
566
|
controller.close();
|
|
445
567
|
},
|
|
446
568
|
});
|
|
@@ -1,69 +1,78 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { transformSync } from "@babel/core";
|
|
3
|
-
import sigilPlugin from "@sigil-dev/compiler/babel";
|
|
4
|
-
import { log } from "../logger/instance";
|
|
5
|
-
import type { GrimoirePlugin } from "../types";
|
|
6
|
-
|
|
7
|
-
const logger = log.scope("scope");
|
|
8
|
-
let registered = false;
|
|
9
|
-
|
|
10
|
-
export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
|
|
11
|
-
if (registered) return;
|
|
12
|
-
registered = true;
|
|
13
|
-
|
|
14
|
-
Bun.plugin({
|
|
15
|
-
name: "sigil-ssr",
|
|
16
|
-
|
|
17
|
-
setup(build) {
|
|
18
|
-
// loader: "ts" not "tsx" — Babel already consumed the JSX,
|
|
19
|
-
// Bun only needs to strip remaining TypeScript types
|
|
20
|
-
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
21
|
-
build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
|
|
22
|
-
try {
|
|
23
|
-
const resolved = Bun.resolveSync(args.path, process.cwd());
|
|
24
|
-
return { path: resolved.replaceAll("\\", "/") };
|
|
25
|
-
} catch {
|
|
26
|
-
return undefined;
|
|
27
|
-
}
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
31
|
-
if (path.includes("index.tsx"))
|
|
32
|
-
logger.debug("[ssr-plugin] onLoad:", path);
|
|
33
|
-
const source = await Bun.file(path).text();
|
|
34
|
-
|
|
35
|
-
// node_modules and .grimoire files are plain TypeScript (no sigil JSX).
|
|
36
|
-
// Still must return { contents, loader } — never return undefined from onLoad.
|
|
37
|
-
if (path.includes("node_modules") || path.includes(".grimoire")) {
|
|
38
|
-
return {
|
|
39
|
-
contents: transpiler.transformSync(source),
|
|
40
|
-
loader: "js" as const,
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if (process.env.SIGIL_VERBOSE) {
|
|
45
|
-
logger.debug("[sigil-ssr] XFORM:", path);
|
|
46
|
-
}
|
|
47
|
-
const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { transformSync } from "@babel/core";
|
|
3
|
+
import sigilPlugin from "@sigil-dev/compiler/babel";
|
|
4
|
+
import { log } from "../logger/instance";
|
|
5
|
+
import type { GrimoirePlugin } from "../types";
|
|
6
|
+
|
|
7
|
+
const logger = log.scope("scope");
|
|
8
|
+
let registered = false;
|
|
9
|
+
|
|
10
|
+
export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
|
|
11
|
+
if (registered) return;
|
|
12
|
+
registered = true;
|
|
13
|
+
|
|
14
|
+
Bun.plugin({
|
|
15
|
+
name: "sigil-ssr",
|
|
16
|
+
|
|
17
|
+
setup(build) {
|
|
18
|
+
// loader: "ts" not "tsx" — Babel already consumed the JSX,
|
|
19
|
+
// Bun only needs to strip remaining TypeScript types
|
|
20
|
+
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
21
|
+
build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
|
|
22
|
+
try {
|
|
23
|
+
const resolved = Bun.resolveSync(args.path, process.cwd());
|
|
24
|
+
return { path: resolved.replaceAll("\\", "/") };
|
|
25
|
+
} catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
31
|
+
if (path.includes("index.tsx"))
|
|
32
|
+
logger.debug("[ssr-plugin] onLoad:", path);
|
|
33
|
+
const source = await Bun.file(path).text();
|
|
34
|
+
|
|
35
|
+
// node_modules and .grimoire files are plain TypeScript (no sigil JSX).
|
|
36
|
+
// Still must return { contents, loader } — never return undefined from onLoad.
|
|
37
|
+
if (path.includes("node_modules") || path.includes(".grimoire")) {
|
|
38
|
+
return {
|
|
39
|
+
contents: transpiler.transformSync(source),
|
|
40
|
+
loader: "js" as const,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (process.env.SIGIL_VERBOSE) {
|
|
45
|
+
logger.debug("[sigil-ssr] XFORM:", path);
|
|
46
|
+
}
|
|
47
|
+
const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
|
|
48
|
+
// scoped <style> blocks never render server-side (SSR mode never
|
|
49
|
+
// injects the CSS — see bun-plugin.ts's mode !== "ssr" guard), but
|
|
50
|
+
// their raw CSS text still needs stripping or the JSX parser treats
|
|
51
|
+
// a bare `{` in a declaration like `position: sticky;` as the start
|
|
52
|
+
// of an embedded expression and throws
|
|
53
|
+
const sourceNoStyle = source.replace(
|
|
54
|
+
/<style[^>]*>[\s\S]*?<\/style>/gi,
|
|
55
|
+
"",
|
|
56
|
+
);
|
|
57
|
+
const result = transformSync(sourceNoStyle, {
|
|
58
|
+
configFile: false,
|
|
59
|
+
babelrc: false,
|
|
60
|
+
parserOpts: {
|
|
61
|
+
plugins: ["typescript", "jsx"],
|
|
62
|
+
},
|
|
63
|
+
plugins: [[sigilPlugin, { mode: "ssr", hash }]],
|
|
64
|
+
filename: path,
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
let contents = transpiler.transformSync(result?.code ?? "");
|
|
68
|
+
|
|
69
|
+
for (const plugin of plugins) {
|
|
70
|
+
if (plugin.transform)
|
|
71
|
+
contents = (await plugin.transform(contents, path)) ?? contents;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return { contents, loader: "js" as const };
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
@@ -15,6 +15,7 @@ import type { RouteFile } from "./scanner";
|
|
|
15
15
|
export function generateManifest(
|
|
16
16
|
routes: RouteFile[],
|
|
17
17
|
fileMap?: Map<string, string>,
|
|
18
|
+
paramMatcherFiles: { name: string; filePath: string }[] = [],
|
|
18
19
|
): string {
|
|
19
20
|
const pages = routes.filter((r) => r.type === "page" || r.type === "simple");
|
|
20
21
|
const layouts = routes.filter((r) => r.type === "layout");
|
|
@@ -26,6 +27,17 @@ export function generateManifest(
|
|
|
26
27
|
})
|
|
27
28
|
.join("\n");
|
|
28
29
|
|
|
30
|
+
// param matchers are eager: the client router validates on every match
|
|
31
|
+
const matcherImports = paramMatcherFiles
|
|
32
|
+
.map(
|
|
33
|
+
(pm) =>
|
|
34
|
+
`import * as __param_${pm.name} from ${JSON.stringify(pm.filePath)};`,
|
|
35
|
+
)
|
|
36
|
+
.join("\n");
|
|
37
|
+
const matcherRecord = `export const matchers = {\n${paramMatcherFiles
|
|
38
|
+
.map((pm) => ` ${JSON.stringify(pm.name)}: __param_${pm.name}.match,`)
|
|
39
|
+
.join("\n")}\n};`;
|
|
40
|
+
|
|
29
41
|
const map = pages
|
|
30
42
|
.map((r) => {
|
|
31
43
|
const path = fileMap?.get(r.filePath) ?? r.filePath;
|
|
@@ -39,5 +51,5 @@ export function generateManifest(
|
|
|
39
51
|
)
|
|
40
52
|
.join("\n");
|
|
41
53
|
|
|
42
|
-
return `${layoutImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n`;
|
|
54
|
+
return `${layoutImports}\n${matcherImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n${matcherRecord}\n`;
|
|
43
55
|
}
|