@sigil-dev/grimoire 0.9.20 → 0.9.22

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -114
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -745
  28. package/src/rendering/preload.ts +101 -95
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -194
  35. package/src/server/asset-cache.ts +57 -55
  36. package/src/server/build.ts +262 -249
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -0
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1022
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -0
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -113
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -69
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,211 +1,211 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { join, relative } from "node:path";
4
- import { transformSync } from "@babel/core";
5
- import sigilPlugin from "@sigil-dev/compiler/babel";
6
- import {
7
- clientStyleSnippet,
8
- computeHash,
9
- extractStyles,
10
- } from "@sigil-dev/compiler/css";
11
- import type { DevGraph } from "./graph";
12
- import { normalizePath } from "./paths";
13
- import { resolveProjectImport } from "./resolve";
14
-
15
- const RUNTIME_URL = "/__grimoire__/runtime.js";
16
- const MODULES_BASE = "/__grimoire__/m/";
17
- const DEPS_BASE = "/__grimoire__/dep/";
18
-
19
- export interface BrowserCompileContext {
20
- projectRoot: string;
21
- /** GrimoireConfig.alias — prefix → project-relative directory. */
22
- aliases: Record<string, string>;
23
- /** Supplies the version each dependency URL is stamped with. */
24
- graph?: DevGraph;
25
- }
26
-
27
- /** `/__grimoire__/m/src/lib/Card.tsx.js?v=3` for a project module. */
28
- function moduleUrl(absPath: string, ctx: BrowserCompileContext): string {
29
- const rel = relative(ctx.projectRoot, absPath).replace(/\\/g, "/");
30
- const version = ctx.graph?.get(absPath)?.version ?? 0;
31
- return `${MODULES_BASE}${rel}.js?v=${version}`;
32
- }
33
-
34
- /**
35
- * Rewrite one import specifier to a browser-servable URL.
36
- *
37
- * Project modules carry their graph version in the query string: the browser
38
- * caches ES modules by URL forever, so an edited component is only re-fetched
39
- * when the importing module's own text points at a new URL.
40
- */
41
- function rewriteSpecifier(
42
- specifier: string,
43
- fromFile: string,
44
- ctx: BrowserCompileContext,
45
- ): string {
46
- if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
47
- if (specifier.startsWith("$env/"))
48
- return `/__grimoire__/env/${specifier.slice("$env/".length)}.js`;
49
-
50
- const resolved = resolveProjectImport(
51
- specifier,
52
- fromFile,
53
- ctx.projectRoot,
54
- ctx.aliases,
55
- );
56
- if (resolved) return moduleUrl(resolved, ctx);
57
-
58
- // unresolvable relative import (missing file) — keep a module URL so the
59
- // browser reports the 404 against a path the developer recognises
60
- if (specifier.startsWith(".") || specifier.startsWith("$lib/")) {
61
- const rel = specifier.startsWith("$lib/")
62
- ? specifier.replace("$lib/", "src/lib/")
63
- : relative(ctx.projectRoot, join(fromFile, "..", specifier)).replace(
64
- /\\/g,
65
- "/",
66
- );
67
- return `${MODULES_BASE}${rel}.js`;
68
- }
69
-
70
- const pkgName = specifier.startsWith("@")
71
- ? specifier.split("/").slice(0, 2).join("/")
72
- : specifier.split("/")[0];
73
- return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
74
- }
75
-
76
- /** Rewrite static `from "…"` / `import "…"` and dynamic `import("…")`. */
77
- function rewriteImports(
78
- code: string,
79
- filePath: string,
80
- ctx: BrowserCompileContext,
81
- ): string {
82
- return code
83
- .replace(
84
- /(from\s+|import\s+)(["'])([^"']+)\2/g,
85
- (_m, keyword: string, quote: string, specifier: string) =>
86
- `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
87
- )
88
- .replace(
89
- /(import\s*\(\s*)(["'])([^"']+)\2/g,
90
- (_m, keyword: string, quote: string, specifier: string) =>
91
- `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
92
- );
93
- }
94
-
95
- export interface CompileResult {
96
- js: string;
97
- css: string | null;
98
- cssHash: string;
99
- }
100
-
101
- const RUNTIME_SPECIFIERS = [
102
- "createSignal",
103
- "createRawSignal",
104
- "createEffect",
105
- "createMemo",
106
- "reconcile",
107
- "claim",
108
- "claimText",
109
- "claimComment",
110
- "hydrateKeyedList",
111
- "insert",
112
- "getHydrationNodes",
113
- "pushHydrationNodes",
114
- "popHydrationNodes",
115
- "snapshot",
116
- "tracking",
117
- "createEffectPre",
118
- "createInspectEffect",
119
- "withEffectScope",
120
- ].join(", ");
121
-
122
- export async function compileForBrowser(
123
- filePath: string,
124
- ctx: BrowserCompileContext,
125
- ): Promise<CompileResult> {
126
- const source = await Bun.file(filePath).text();
127
-
128
- // the scope hash must be the compiler's own: a swapped module whose
129
- // elements carry a different class than the emitted CSS loses its styles
130
- const hash = computeHash(filePath);
131
- const { code: sourceNoStyle, css } = extractStyles(source, hash, filePath);
132
-
133
- // dom mode: swapped modules always re-render from scratch, they never
134
- // claim server-rendered nodes
135
- const babelResult = transformSync(sourceNoStyle, {
136
- configFile: false,
137
- babelrc: false,
138
- parserOpts: { plugins: ["typescript", "jsx"] },
139
- plugins: [
140
- [sigilPlugin, { mode: "dom", hash: css ? hash : undefined, dev: true }],
141
- ],
142
- filename: filePath,
143
- });
144
- // strip TypeScript types
145
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
146
- let js = transpiler.transformSync(babelResult?.code ?? "");
147
-
148
- js = js.replace(
149
- /import\s*\{[^}]+\}\s*from\s*["']@sigil-dev\/runtime["'];?/,
150
- `import { ${RUNTIME_SPECIFIERS} } from "@sigil-dev/runtime";`,
151
- );
152
-
153
- // inject scoped CSS at runtime
154
- if (css) js = clientStyleSnippet(hash, css) + js;
155
-
156
- js = rewriteImports(js, filePath, ctx);
157
-
158
- return { js, css, cssHash: hash };
159
- }
160
-
161
- const cacheName = (absPath: string, version: number): string => {
162
- // hashed so one flat cache dir holds every module, path separators and all
163
- const hash = createHash("md5")
164
- .update(normalizePath(absPath))
165
- .digest("hex")
166
- .slice(0, 8);
167
- return `${hash}_v${version}.js`;
168
- };
169
-
170
- /**
171
- * Compile a module for the browser at its current graph version, memoised on
172
- * disk. The version comes from the graph, not the request URL: a client may
173
- * ask for a stale `?v=`, and serving anything but current code would
174
- * reintroduce the mismatch HMR exists to avoid.
175
- */
176
- export async function getDevModule(
177
- absPath: string,
178
- ctx: BrowserCompileContext,
179
- ): Promise<CompileResult> {
180
- const version = ctx.graph?.get(absPath)?.version ?? 0;
181
- const cachePath = join(
182
- ctx.projectRoot,
183
- ".grimoire/dev-modules",
184
- cacheName(absPath, version),
185
- );
186
-
187
- const cached = Bun.file(cachePath);
188
- if (await cached.exists()) {
189
- return { js: await cached.text(), css: null, cssHash: "" };
190
- }
191
-
192
- const result = await compileForBrowser(absPath, ctx);
193
- cacheDevModule(absPath, version, ctx.projectRoot, result.js);
194
- return result;
195
- }
196
-
197
- /**
198
- * Store already-compiled output for a version. Used by the HMR pipeline, which
199
- * must compile the edited source *before* bumping the version — a failed
200
- * compile has to leave the previous version live.
201
- */
202
- export function cacheDevModule(
203
- absPath: string,
204
- version: number,
205
- projectRoot: string,
206
- js: string,
207
- ): void {
208
- const dir = join(projectRoot, ".grimoire/dev-modules");
209
- mkdirSync(dir, { recursive: true });
210
- writeFileSync(join(dir, cacheName(absPath, version)), js);
211
- }
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ import { transformSync } from "@babel/core";
5
+ import sigilPlugin from "@sigil-dev/compiler/babel";
6
+ import {
7
+ clientStyleSnippet,
8
+ computeHash,
9
+ extractStyles,
10
+ } from "@sigil-dev/compiler/css";
11
+ import type { DevGraph } from "./graph";
12
+ import { normalizePath } from "./paths";
13
+ import { resolveProjectImport } from "./resolve";
14
+
15
+ const RUNTIME_URL = "/__grimoire__/runtime.js";
16
+ const MODULES_BASE = "/__grimoire__/m/";
17
+ const DEPS_BASE = "/__grimoire__/dep/";
18
+
19
+ export interface BrowserCompileContext {
20
+ projectRoot: string;
21
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
22
+ aliases: Record<string, string>;
23
+ /** Supplies the version each dependency URL is stamped with. */
24
+ graph?: DevGraph;
25
+ }
26
+
27
+ /** `/__grimoire__/m/src/lib/Card.tsx.js?v=3` for a project module. */
28
+ function moduleUrl(absPath: string, ctx: BrowserCompileContext): string {
29
+ const rel = relative(ctx.projectRoot, absPath).replace(/\\/g, "/");
30
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
31
+ return `${MODULES_BASE}${rel}.js?v=${version}`;
32
+ }
33
+
34
+ /**
35
+ * Rewrite one import specifier to a browser-servable URL.
36
+ *
37
+ * Project modules carry their graph version in the query string: the browser
38
+ * caches ES modules by URL forever, so an edited component is only re-fetched
39
+ * when the importing module's own text points at a new URL.
40
+ */
41
+ function rewriteSpecifier(
42
+ specifier: string,
43
+ fromFile: string,
44
+ ctx: BrowserCompileContext,
45
+ ): string {
46
+ if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
47
+ if (specifier.startsWith("$env/"))
48
+ return `/__grimoire__/env/${specifier.slice("$env/".length)}.js`;
49
+
50
+ const resolved = resolveProjectImport(
51
+ specifier,
52
+ fromFile,
53
+ ctx.projectRoot,
54
+ ctx.aliases,
55
+ );
56
+ if (resolved) return moduleUrl(resolved, ctx);
57
+
58
+ // unresolvable relative import (missing file) — keep a module URL so the
59
+ // browser reports the 404 against a path the developer recognises
60
+ if (specifier.startsWith(".") || specifier.startsWith("$lib/")) {
61
+ const rel = specifier.startsWith("$lib/")
62
+ ? specifier.replace("$lib/", "src/lib/")
63
+ : relative(ctx.projectRoot, join(fromFile, "..", specifier)).replace(
64
+ /\\/g,
65
+ "/",
66
+ );
67
+ return `${MODULES_BASE}${rel}.js`;
68
+ }
69
+
70
+ const pkgName = specifier.startsWith("@")
71
+ ? specifier.split("/").slice(0, 2).join("/")
72
+ : specifier.split("/")[0];
73
+ return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
74
+ }
75
+
76
+ /** Rewrite static `from "…"` / `import "…"` and dynamic `import("…")`. */
77
+ function rewriteImports(
78
+ code: string,
79
+ filePath: string,
80
+ ctx: BrowserCompileContext,
81
+ ): string {
82
+ return code
83
+ .replace(
84
+ /(from\s+|import\s+)(["'])([^"']+)\2/g,
85
+ (_m, keyword: string, quote: string, specifier: string) =>
86
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
87
+ )
88
+ .replace(
89
+ /(import\s*\(\s*)(["'])([^"']+)\2/g,
90
+ (_m, keyword: string, quote: string, specifier: string) =>
91
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
92
+ );
93
+ }
94
+
95
+ export interface CompileResult {
96
+ js: string;
97
+ css: string | null;
98
+ cssHash: string;
99
+ }
100
+
101
+ const RUNTIME_SPECIFIERS = [
102
+ "createSignal",
103
+ "createRawSignal",
104
+ "createEffect",
105
+ "createMemo",
106
+ "reconcile",
107
+ "claim",
108
+ "claimText",
109
+ "claimComment",
110
+ "hydrateKeyedList",
111
+ "insert",
112
+ "getHydrationNodes",
113
+ "pushHydrationNodes",
114
+ "popHydrationNodes",
115
+ "snapshot",
116
+ "tracking",
117
+ "createEffectPre",
118
+ "createInspectEffect",
119
+ "withEffectScope",
120
+ ].join(", ");
121
+
122
+ export async function compileForBrowser(
123
+ filePath: string,
124
+ ctx: BrowserCompileContext,
125
+ ): Promise<CompileResult> {
126
+ const source = await Bun.file(filePath).text();
127
+
128
+ // the scope hash must be the compiler's own: a swapped module whose
129
+ // elements carry a different class than the emitted CSS loses its styles
130
+ const hash = computeHash(filePath);
131
+ const { code: sourceNoStyle, css } = extractStyles(source, hash, filePath);
132
+
133
+ // dom mode: swapped modules always re-render from scratch, they never
134
+ // claim server-rendered nodes
135
+ const babelResult = transformSync(sourceNoStyle, {
136
+ configFile: false,
137
+ babelrc: false,
138
+ parserOpts: { plugins: ["typescript", "jsx"] },
139
+ plugins: [
140
+ [sigilPlugin, { mode: "dom", hash: css ? hash : undefined, dev: true }],
141
+ ],
142
+ filename: filePath,
143
+ });
144
+ // strip TypeScript types
145
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
146
+ let js = transpiler.transformSync(babelResult?.code ?? "");
147
+
148
+ js = js.replace(
149
+ /import\s*\{[^}]+\}\s*from\s*["']@sigil-dev\/runtime["'];?/,
150
+ `import { ${RUNTIME_SPECIFIERS} } from "@sigil-dev/runtime";`,
151
+ );
152
+
153
+ // inject scoped CSS at runtime
154
+ if (css) js = clientStyleSnippet(hash, css) + js;
155
+
156
+ js = rewriteImports(js, filePath, ctx);
157
+
158
+ return { js, css, cssHash: hash };
159
+ }
160
+
161
+ const cacheName = (absPath: string, version: number): string => {
162
+ // hashed so one flat cache dir holds every module, path separators and all
163
+ const hash = createHash("md5")
164
+ .update(normalizePath(absPath))
165
+ .digest("hex")
166
+ .slice(0, 8);
167
+ return `${hash}_v${version}.js`;
168
+ };
169
+
170
+ /**
171
+ * Compile a module for the browser at its current graph version, memoised on
172
+ * disk. The version comes from the graph, not the request URL: a client may
173
+ * ask for a stale `?v=`, and serving anything but current code would
174
+ * reintroduce the mismatch HMR exists to avoid.
175
+ */
176
+ export async function getDevModule(
177
+ absPath: string,
178
+ ctx: BrowserCompileContext,
179
+ ): Promise<CompileResult> {
180
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
181
+ const cachePath = join(
182
+ ctx.projectRoot,
183
+ ".grimoire/dev-modules",
184
+ cacheName(absPath, version),
185
+ );
186
+
187
+ const cached = Bun.file(cachePath);
188
+ if (await cached.exists()) {
189
+ return { js: await cached.text(), css: null, cssHash: "" };
190
+ }
191
+
192
+ const result = await compileForBrowser(absPath, ctx);
193
+ cacheDevModule(absPath, version, ctx.projectRoot, result.js);
194
+ return result;
195
+ }
196
+
197
+ /**
198
+ * Store already-compiled output for a version. Used by the HMR pipeline, which
199
+ * must compile the edited source *before* bumping the version — a failed
200
+ * compile has to leave the previous version live.
201
+ */
202
+ export function cacheDevModule(
203
+ absPath: string,
204
+ version: number,
205
+ projectRoot: string,
206
+ js: string,
207
+ ): void {
208
+ const dir = join(projectRoot, ".grimoire/dev-modules");
209
+ mkdirSync(dir, { recursive: true });
210
+ writeFileSync(join(dir, cacheName(absPath, version)), js);
211
+ }