@sigil-dev/grimoire 0.7.6 → 0.8.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.
Files changed (41) hide show
  1. package/index.ts +35 -34
  2. package/package.json +8 -6
  3. package/preload.js +3 -2
  4. package/server.ts +13 -13
  5. package/src/client/head.ts +29 -29
  6. package/src/client/router.ts +120 -53
  7. package/src/dev/compile-module.ts +173 -0
  8. package/src/dev/effect-registry.ts +23 -0
  9. package/src/dev/graph.ts +114 -0
  10. package/src/dev/hmr-client.ts +158 -0
  11. package/src/dev/hmr-server.ts +187 -0
  12. package/src/dev/loader.ts +47 -0
  13. package/src/dev/paths.ts +14 -0
  14. package/src/dev/runtime-bundle.ts +49 -0
  15. package/src/dev/watcher.ts +44 -0
  16. package/src/integrations/vite.ts +73 -72
  17. package/src/rendering/hydrate.ts +102 -64
  18. package/src/rendering/index.ts +296 -199
  19. package/src/rendering/ssrPlugin.ts +67 -53
  20. package/src/routing/manifest-gen.ts +42 -39
  21. package/src/routing/router.ts +109 -106
  22. package/src/routing/scanner.ts +141 -135
  23. package/src/routing/transform-routes.ts +101 -101
  24. package/src/server/build.ts +239 -147
  25. package/src/server/coordinator.ts +306 -306
  26. package/src/server/index.ts +260 -50
  27. package/src/server/worker.ts +59 -59
  28. package/src/typegen/index.ts +356 -353
  29. package/src/types.ts +270 -269
  30. package/test/context.test.ts +52 -52
  31. package/test/hydration.test.ts +119 -119
  32. package/test/middleware.test.ts +223 -223
  33. package/test/rendering.test.ts +579 -425
  34. package/test/routing.test.ts +81 -83
  35. package/test/scanning.test.ts +200 -181
  36. package/test/scope.test.ts +24 -8
  37. package/test/server.test.ts +249 -229
  38. package/test/streaming.test.ts +125 -106
  39. package/test/transform-routes.test.ts +84 -84
  40. package/test/typegen.test.ts +35 -25
  41. package/tsconfig.json +1 -0
@@ -1,199 +1,296 @@
1
- import { SafeHtml } from "@sigil-dev/runtime";
2
- import { findClosestError, type MatchedRoute } from "../routing/router";
3
- import type { RouteFile } from "../routing/scanner";
4
- import { isErrorResult } from "../sentinels/error.ts";
5
- import { isRedirectResult } from "../sentinels/redirect.ts";
6
- import { runWithContext } from "../server/context";
7
- import { runHook } from "../server/plugins";
8
- import type { GrimoirePlugin, LoadContext, Route } from "../types";
9
- import { collectHead, initHead } from "./head";
10
-
11
- export type ModuleLoader = (path: string) => Promise<any>;
12
-
13
- async function renderErrorPage(
14
- errorRoutes: RouteFile[],
15
- pathname: string,
16
- status: number,
17
- message: string,
18
- ): Promise<Response | null> {
19
- const errorPage = findClosestError(errorRoutes, pathname);
20
- if (!errorPage) return null;
21
- const mod = await import(errorPage.filePath);
22
- const html = mod.default({ status, message });
23
- return new Response(html, {
24
- status,
25
- headers: { "Content-Type": "text/html" },
26
- });
27
- }
28
-
29
- export async function renderRoute(
30
- matched: MatchedRoute,
31
- req: Request,
32
- errorRoutes: RouteFile[] = [],
33
- loadModule: ModuleLoader = (path) => import(path),
34
- locals: Record<string, any> = {},
35
- plugins: GrimoirePlugin[] = [],
36
- cspNonce?: string,
37
- ): Promise<Response> {
38
- return runWithContext(async () => {
39
- const context: LoadContext = {
40
- request: req,
41
- params: matched.params,
42
- url: new URL(req.url),
43
- locals,
44
- };
45
-
46
- initHead(cspNonce);
47
-
48
- const route: Route = {
49
- path: matched.route.path,
50
- params: matched.params,
51
- filePath: matched.route.filePath,
52
- loadPath: matched.pageServer?.filePath,
53
- layoutPath: matched.layouts.at(-1)?.filePath,
54
- };
55
- await runHook(plugins, "onRouteLoad", route, context);
56
-
57
- const layoutPairs: { layout: RouteFile; data: unknown }[] = [];
58
- for (const layout of matched.layouts) {
59
- const layoutServer = matched.layoutServers.find(
60
- (ls) => ls.path === layout.path,
61
- );
62
- let data: unknown;
63
- if (layoutServer) {
64
- try {
65
- const mod = await import(layoutServer.filePath);
66
- data = await mod.load?.(context);
67
- } catch (e) {
68
- if (isRedirectResult(e))
69
- return new Response(null, {
70
- status: e.status,
71
- headers: { Location: e.location },
72
- });
73
- if (isErrorResult(e))
74
- return (
75
- (await renderErrorPage(
76
- errorRoutes,
77
- context.url.pathname,
78
- e.status,
79
- e.message,
80
- )) ?? new Response(e.message, { status: e.status })
81
- );
82
- throw e;
83
- }
84
- }
85
- layoutPairs.push({ layout, data });
86
- }
87
-
88
- let pageData: unknown;
89
- if (matched.pageServer) {
90
- try {
91
- const mod = await import(matched.pageServer.filePath);
92
- pageData = await mod.load?.(context);
93
- } catch (e) {
94
- if (isRedirectResult(e)) {
95
- return new Response(null, {
96
- status: e.status,
97
- headers: { Location: e.location },
98
- });
99
- }
100
- if (isErrorResult(e)) {
101
- return (
102
- (await renderErrorPage(
103
- errorRoutes,
104
- context.url.pathname,
105
- e.status,
106
- e.message,
107
- )) ?? new Response(e.message, { status: e.status })
108
- );
109
- }
110
- throw e;
111
- }
112
- }
113
-
114
- const pageMod = await import(matched.route.filePath);
115
- const pageHtml = pageMod.default({
116
- data: pageData,
117
- params: matched.params,
118
- });
119
-
120
- // collect head AFTER page render so <Head> calls are captured
121
- const headHtml = collectHead();
122
-
123
- // navigation request: return JSON, client handles rendering
124
- if (req.headers.get("x-grimoire-navigate") === "1") {
125
- return Response.json({
126
- data: pageData ?? {},
127
- layoutData: layoutPairs.map((l) => l.data),
128
- params: matched.params,
129
- pattern: matched.route.path,
130
- head: headHtml,
131
- });
132
- }
133
-
134
- const wrappedPage = `<div id="grimoire-page">${String(pageHtml)}</div>`;
135
-
136
- let bodyHtml: string = wrappedPage;
137
- for (const { layout, data } of [...layoutPairs].reverse()) {
138
- const layoutMod = await import(layout.filePath);
139
- bodyHtml = String(
140
- layoutMod.default({
141
- data,
142
- children: new SafeHtml(bodyHtml),
143
- params: matched.params,
144
- }),
145
- );
146
- }
147
-
148
- bodyHtml = `<div id="grimoire-root">${bodyHtml}</div>`;
149
-
150
- const stateJson = JSON.stringify({
151
- params: matched.params,
152
- data: pageData,
153
- layoutData: layoutPairs.map((l) => l.data),
154
- pattern: matched.route.path,
155
- });
156
-
157
- // --- Streaming SSR ---
158
- // Send DOCTYPE + head skeleton immediately (browser starts resource fetch).
159
- // Then stream body + full head content + state as they become available.
160
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
161
- const stream = new ReadableStream({
162
- start(controller) {
163
- // 1. Document skeleton — browser starts parsing, fetches CSS/JS
164
- controller.enqueue(
165
- `<!DOCTYPE html>
166
- <html>
167
- <head>
168
- <meta charset="UTF-8" />
169
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
170
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>`,
171
- );
172
-
173
- // 2. Head content (captured from <Head> component calls during render)
174
- if (headHtml) {
175
- controller.enqueue(`\n${headHtml}`);
176
- }
177
-
178
- controller.enqueue(`\n</head>
179
- <body>
180
- <div id="app">`);
181
-
182
- // 3. Page body
183
- controller.enqueue(bodyHtml);
184
-
185
- // 4. State script + closing tags
186
- controller.enqueue(`</div>
187
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
188
- </body>
189
- </html>`);
190
-
191
- controller.close();
192
- },
193
- });
194
-
195
- return new Response(stream, {
196
- headers: { "Content-Type": "text/html" },
197
- });
198
- });
199
- }
1
+ import { SafeHtml } from "@sigil-dev/runtime";
2
+ import { randomBytes } from "crypto";
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
+ export async function renderRoute(
32
+ matched: MatchedRoute,
33
+ req: Request,
34
+ errorRoutes: RouteFile[] = [],
35
+ loadModule: ModuleLoader = (path) => import(path),
36
+ locals: Record<string, any> = {},
37
+ plugins: GrimoirePlugin[] = [],
38
+ cspNonce?: string,
39
+ dev?: boolean,
40
+ ): Promise<Response> {
41
+ return runWithContext(async () => {
42
+ const context: LoadContext = {
43
+ request: req,
44
+ params: matched.params,
45
+ url: new URL(req.url),
46
+ locals,
47
+ };
48
+
49
+ initHead(cspNonce);
50
+
51
+ const route: Route = {
52
+ path: matched.route.path,
53
+ params: matched.params,
54
+ filePath: matched.route.filePath,
55
+ loadPath: matched.pageServer?.filePath,
56
+ layoutPath: matched.layouts.at(-1)?.filePath,
57
+ };
58
+ await runHook(plugins, "onRouteLoad", route, context);
59
+
60
+ const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
61
+ for (const layout of matched.layouts) {
62
+ const layoutMod = await loadModule(layout.filePath);
63
+
64
+ if (layoutMod.canMatch) {
65
+ try {
66
+ const result = await layoutMod.canMatch(context);
67
+ if (result === false)
68
+ return new Response("Not Found", { status: 404 });
69
+ if (isRedirectResult(result))
70
+ return new Response(null, {
71
+ status: result.status,
72
+ headers: { Location: result.location },
73
+ });
74
+ } catch (e) {
75
+ if (isRedirectResult(e))
76
+ return new Response(null, {
77
+ status: e.status,
78
+ headers: { Location: e.location },
79
+ });
80
+ if (isErrorResult(e))
81
+ return (
82
+ (await renderErrorPage(
83
+ errorRoutes,
84
+ context.url.pathname,
85
+ e.status,
86
+ e.message,
87
+ e,
88
+ )) ?? new Response(e.message, { status: e.status })
89
+ );
90
+ throw e;
91
+ }
92
+ }
93
+
94
+ const layoutServer = matched.layoutServers.find(
95
+ (ls) => ls.path === layout.path,
96
+ );
97
+ let data: unknown;
98
+ if (layoutServer) {
99
+ try {
100
+ const mod = await loadModule(layoutServer.filePath);
101
+ data = await mod.load?.(context);
102
+ } catch (e) {
103
+ if (isRedirectResult(e))
104
+ return new Response(null, {
105
+ status: e.status,
106
+ headers: { Location: e.location },
107
+ });
108
+ if (isErrorResult(e))
109
+ return (
110
+ (await renderErrorPage(
111
+ errorRoutes,
112
+ context.url.pathname,
113
+ e.status,
114
+ e.message,
115
+ e,
116
+ )) ?? new Response(e.message, { status: e.status })
117
+ );
118
+ throw e;
119
+ }
120
+ }
121
+ const universalLayoutData = layoutMod.load
122
+ ? await layoutMod.load(context)
123
+ : undefined;
124
+
125
+ const mergedLayoutData =
126
+ universalLayoutData !== undefined
127
+ ? //@ts-expect-error User provded data is always unknown.
128
+ { ...universalLayoutData, ...data }
129
+ : data;
130
+
131
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
132
+ }
133
+
134
+ let pageData: unknown;
135
+ if (matched.pageServer) {
136
+ try {
137
+ const mod = await loadModule(matched.pageServer.filePath);
138
+ pageData = await mod.load?.(context);
139
+ } catch (e) {
140
+ if (isRedirectResult(e)) {
141
+ return new Response(null, {
142
+ status: e.status,
143
+ headers: { Location: e.location },
144
+ });
145
+ }
146
+ if (isErrorResult(e)) {
147
+ return (
148
+ (await renderErrorPage(
149
+ errorRoutes,
150
+ context.url.pathname,
151
+ e.status,
152
+ e.message,
153
+ e,
154
+ )) ?? new Response(e.message, { status: e.status })
155
+ );
156
+ }
157
+ throw e;
158
+ }
159
+ }
160
+
161
+ const pageMod = await loadModule(matched.route.filePath);
162
+ if (pageMod.canMatch) {
163
+ try {
164
+ const result = await pageMod.canMatch(context);
165
+ if (result === false) return new Response("Not Found", { status: 404 });
166
+ if (isRedirectResult(result))
167
+ return new Response(null, {
168
+ status: result.status,
169
+ headers: { Location: result.location },
170
+ });
171
+ } catch (e) {
172
+ if (isRedirectResult(e))
173
+ return new Response(null, {
174
+ status: e.status,
175
+ headers: { Location: e.location },
176
+ });
177
+ if (isErrorResult(e))
178
+ return (
179
+ (await renderErrorPage(
180
+ errorRoutes,
181
+ context.url.pathname,
182
+ e.status,
183
+ e.message,
184
+ e,
185
+ )) ?? new Response(e.message, { status: e.status })
186
+ );
187
+ throw e;
188
+ }
189
+ }
190
+
191
+ const universalData = pageMod.load
192
+ ? await pageMod.load(context).catch((e) => {
193
+ if (isRedirectResult(e)) throw e;
194
+ if (isErrorResult(e)) throw e;
195
+ throw e;
196
+ })
197
+ : undefined;
198
+
199
+ const mergedData =
200
+ universalData !== undefined
201
+ ? //@ts-expect-error User provded data is always unknown.
202
+ { ...universalData, ...pageData }
203
+ : pageData;
204
+
205
+ const pageHtml = pageMod.default({
206
+ data: mergedData,
207
+ params: matched.params,
208
+ });
209
+
210
+ // collect head AFTER page render so <Head> calls are captured
211
+ const headHtml = collectHead();
212
+
213
+ // navigation request: return JSON, client handles rendering
214
+ if (req.headers.get("x-grimoire-navigate") === "1") {
215
+ return Response.json({
216
+ data: mergedData ?? {},
217
+ layoutData: layoutPairs.map((l) => l.data),
218
+ params: matched.params,
219
+ pattern: matched.route.path,
220
+ head: headHtml,
221
+ });
222
+ }
223
+
224
+ const wrappedPage = `<div id="grimoire-page">${String(pageHtml)}</div>`;
225
+
226
+ let bodyHtml: string = wrappedPage;
227
+ for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
228
+ bodyHtml = String(
229
+ layoutMod.default({
230
+ data,
231
+ children: new SafeHtml(bodyHtml),
232
+ params: matched.params,
233
+ }),
234
+ );
235
+ }
236
+
237
+ bodyHtml = `<div id="grimoire-root">${bodyHtml}</div>`;
238
+ const csrfToken = randomBytes(32).toString("hex");
239
+ const stateJson = JSON.stringify({
240
+ params: matched.params,
241
+ data: mergedData,
242
+ layoutData: layoutPairs.map((l) => l.data),
243
+ pattern: matched.route.path,
244
+ });
245
+ const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
246
+ bodyHtml = bodyHtml.replace(
247
+ /<form([^>]*action=[^>]*)>/gi,
248
+ `<form$1>${csrfInput}`,
249
+ );
250
+ // --- Streaming SSR ---
251
+ // Send DOCTYPE + head skeleton immediately (browser starts resource fetch).
252
+ // Then stream body + full head content + state as they become available.
253
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
254
+ const stream = new ReadableStream({
255
+ start(controller) {
256
+ // 1. Document skeleton — browser starts parsing, fetches CSS/JS
257
+ controller.enqueue(
258
+ `<!DOCTYPE html>
259
+ <html>
260
+ <head>
261
+ <meta charset="UTF-8" />
262
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
263
+ <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
264
+ ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`,
265
+ );
266
+
267
+ // 2. Head content (captured from <Head> component calls during render)
268
+ if (headHtml) {
269
+ controller.enqueue(`\n${headHtml}`);
270
+ }
271
+
272
+ controller.enqueue(`\n</head>
273
+ <body>
274
+ <div id="app">`);
275
+
276
+ // 3. Page body
277
+ controller.enqueue(bodyHtml);
278
+
279
+ // 4. State script + closing tags
280
+ controller.enqueue(`</div>
281
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
282
+ </body>
283
+ </html>`);
284
+
285
+ controller.close();
286
+ },
287
+ });
288
+
289
+ return new Response(stream, {
290
+ headers: {
291
+ "Content-Type": "text/html",
292
+ "Set-Cookie": "_csrf=${csrfToken}; SameSite=Strict; Path=/",
293
+ },
294
+ });
295
+ });
296
+ }
@@ -1,53 +1,67 @@
1
- import { transformSync } from "@babel/core";
2
- import sigilPlugin from "@sigil-dev/compiler/babel";
3
- import { createHash } from "node:crypto";
4
- import type { GrimoirePlugin } from "../types";
5
-
6
- let registered = false;
7
-
8
- export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
9
- if (registered) return;
10
- registered = true;
11
-
12
- Bun.plugin({
13
- name: "sigil-ssr",
14
- setup(build) {
15
- // loader: "ts" not "tsx" — Babel already consumed the JSX,
16
- // Bun only needs to strip remaining TypeScript types
17
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
18
-
19
- build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
20
- const source = await Bun.file(path).text();
21
-
22
- // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
23
- // Still must return { contents, loader } — never return undefined from onLoad.
24
- if (path.includes("node_modules") || path.includes(".grimoire")) {
25
- return { contents: transpiler.transformSync(source), loader: "js" as const };
26
- }
27
-
28
- if (process.env.SIGIL_VERBOSE) {
29
- console.log("[sigil-ssr] XFORM:", path);
30
- }
31
- const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
32
- const result = transformSync(source, {
33
- configFile: false,
34
- babelrc: false,
35
- parserOpts: {
36
- plugins: ["typescript", "jsx"],
37
- },
38
- plugins: [[sigilPlugin, { mode: "ssr", hash }]],
39
- filename: path,
40
- });
41
-
42
- let contents = transpiler.transformSync(result?.code ?? "");
43
-
44
- for (const plugin of plugins) {
45
- if (plugin.transform)
46
- contents = (await plugin.transform(contents, path)) ?? contents;
47
- }
48
-
49
- return { contents, loader: "js" as const };
50
- });
51
- },
52
- });
53
- }
1
+ import { createHash } from "node:crypto";
2
+ import { transformSync } from "@babel/core";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import type { GrimoirePlugin } from "../types";
5
+
6
+ let registered = false;
7
+
8
+ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
9
+ if (registered) return;
10
+ registered = true;
11
+
12
+ Bun.plugin({
13
+ name: "sigil-ssr",
14
+
15
+ setup(build) {
16
+ // loader: "ts" not "tsx" Babel already consumed the JSX,
17
+ // Bun only needs to strip remaining TypeScript types
18
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
19
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
20
+ try {
21
+ const resolved = Bun.resolveSync(args.path, process.cwd());
22
+ return { path: resolved.replaceAll("\\", "/") };
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ });
27
+
28
+ build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
29
+ if (path.includes("index.tsx"))
30
+ console.log("[ssr-plugin] onLoad:", path);
31
+ const source = await Bun.file(path).text();
32
+
33
+ // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
34
+ // Still must return { contents, loader } — never return undefined from onLoad.
35
+ if (path.includes("node_modules") || path.includes(".grimoire")) {
36
+ return {
37
+ contents: transpiler.transformSync(source),
38
+ loader: "js" as const,
39
+ };
40
+ }
41
+
42
+ if (process.env.SIGIL_VERBOSE) {
43
+ console.log("[sigil-ssr] XFORM:", path);
44
+ }
45
+ const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
46
+ const result = transformSync(source, {
47
+ configFile: false,
48
+ babelrc: false,
49
+ parserOpts: {
50
+ plugins: ["typescript", "jsx"],
51
+ },
52
+ plugins: [[sigilPlugin, { mode: "ssr", hash }]],
53
+ filename: path,
54
+ });
55
+
56
+ let contents = transpiler.transformSync(result?.code ?? "");
57
+
58
+ for (const plugin of plugins) {
59
+ if (plugin.transform)
60
+ contents = (await plugin.transform(contents, path)) ?? contents;
61
+ }
62
+
63
+ return { contents, loader: "js" as const };
64
+ });
65
+ },
66
+ });
67
+ }