@sigil-dev/grimoire 0.9.4 → 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.
Files changed (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +42 -20
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +10 -6
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +295 -298
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,163 +1,215 @@
1
- import { existsSync } from "node:fs";
2
- import { dirname, join, relative } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
-
5
- const RUNTIME_URL = "/__grimoire__/runtime.js";
6
- const MODULES_BASE = "/__grimoire__/m/";
7
- const DEPS_BASE = "/__grimoire__/dep/";
8
- /**
9
- * Rewrite a single import specifier to a browser-servable URL.
10
- * project-relative → /__grimoire__/m/...
11
- * @sigil-dev/runtime → /__grimoire__/runtime.js
12
- * bare npm → /__grimoire__/dep/...
13
- * relative → /__grimoire__/m/... (resolved)
14
- */
15
- function rewriteSpecifier(
16
- specifier: string,
17
- fromFile: string,
18
- projectRoot: string,
19
- ): string {
20
- if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
21
- // if (specifier.startsWith("@sigil-dev/")) return RUNTIME_URL; // all sigil packages
22
-
23
- // relative import — resolve to absolute, then make a module URL
24
- if (specifier.startsWith(".")) {
25
- const resolved = join(dirname(fromFile), specifier);
26
- for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
27
- const candidate = resolved.endsWith(ext) ? resolved : resolved + ext;
28
- if (existsSync(candidate)) {
29
- const rel = relative(projectRoot, candidate).replace(/\\/g, "/");
30
- return `${MODULES_BASE}${rel}.js`;
31
- }
32
- }
33
- // already has extension
34
- const rel = relative(projectRoot, resolved).replace(/\\/g, "/");
35
- return `${MODULES_BASE}${rel}.js`;
36
- }
37
-
38
- // $lib alias
39
- if (specifier.startsWith("$lib/")) {
40
- const rel = specifier.replace("$lib/", "src/lib/");
41
- // try common extensions
42
- for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
43
- const candidate = join(projectRoot, rel + ext);
44
- if (existsSync(candidate)) {
45
- return `${MODULES_BASE}${rel}${ext}.js`;
46
- }
47
- }
48
- return `${MODULES_BASE}${rel}.ts.js`; // fallback
49
- }
50
-
51
- // $env — keep as-is, these are virtual modules handled elsewhere
52
- if (specifier.startsWith("$env/")) return specifier;
53
-
54
- // bare npm specifier → dep bundle
55
- const pkgName = specifier.startsWith("@")
56
- ? specifier.split("/").slice(0, 2).join("/")
57
- : specifier.split("/")[0];
58
- return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
59
- }
60
-
61
- /**
62
- * Rewrite all import/export from specifiers in compiled JS output.
63
- * Works on the static pattern `from "..."` — sufficient for Babel output.
64
- */
65
- function rewriteImports(
66
- code: string,
67
- filePath: string,
68
- projectRoot: string,
69
- ): string {
70
- return code.replace(
71
- /(from\s+|import\s+)(["'])([^"']+)\2/g,
72
- (_match, keyword, quote, specifier) => {
73
- const rewritten = rewriteSpecifier(specifier, filePath, projectRoot);
74
- return `${keyword}${quote}${rewritten}${quote}`;
75
- },
76
- );
77
- }
78
-
79
- export interface CompileResult {
80
- js: string;
81
- css: string | null;
82
- cssHash: string;
83
- }
84
-
85
- export async function compileForBrowser(
86
- filePath: string,
87
- projectRoot: string,
88
- ): Promise<CompileResult> {
89
- const source = await Bun.file(filePath).text();
90
-
91
- // extract scoped CSS
92
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/i;
93
- const { computeHash, scopeCSS } = await import(
94
- pathToFileURL(
95
- join(
96
- projectRoot,
97
- "node_modules/@sigil-dev/compiler/src/babel/util/css.ts",
98
- ),
99
- ).href
100
- );
101
- const cssHash = computeHash(filePath);
102
- const styleMatch = source.match(STYLE_RE);
103
- const css = styleMatch ? scopeCSS(styleMatch[1].trim(), cssHash) : null;
104
- const sourceNoStyle = source.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
105
-
106
- // Babel transform — dom mode
107
- const { transformSync } = await import("@babel/core");
108
- const sigilPlugin = (await import("@sigil-dev/compiler/babel")).default;
109
- const { createHash } = await import("node:crypto");
110
- const hash = createHash("md5").update(filePath).digest("hex").slice(0, 8);
111
-
112
- const babelResult = transformSync(sourceNoStyle, {
113
- configFile: false,
114
- babelrc: false,
115
- parserOpts: { plugins: ["typescript", "jsx"] },
116
- plugins: [[sigilPlugin, { mode: "dom", hash, dev: true }]],
117
- filename: filePath,
118
- });
119
- // strip TypeScript types
120
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
121
- let js = transpiler.transformSync(babelResult?.code ?? "");
122
-
123
- const runtimeSpecifiers = [
124
- "createSignal",
125
- "createRawSignal",
126
- "createEffect",
127
- "createMemo",
128
- "reconcile",
129
- "claim",
130
- "claimText",
131
- "claimComment",
132
- "hydrateKeyedList",
133
- "insert",
134
- "getHydrationNodes",
135
- "pushHydrationNodes",
136
- "popHydrationNodes",
137
- "snapshot",
138
- "tracking",
139
- "createEffectPre",
140
- "createInspectEffect",
141
- "withEffectScope",
142
- ].join(", ");
143
-
144
- js = js.replace(
145
- /import\s*\{[^}]+\}\s*from\s*["']@sigil-dev\/runtime["'];?/,
146
- `import { ${runtimeSpecifiers} } from "@sigil-dev/runtime";`,
147
- );
148
-
149
- // inject scoped CSS at runtime
150
- if (css) {
151
- js = `if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
152
- const __s = document.createElement('style');
153
- __s.id = 'sigil-${hash}';
154
- __s.textContent = ${JSON.stringify(css)};
155
- document.head.appendChild(__s);
156
- }\n${js}`;
157
- }
158
-
159
- // rewrite imports to browser-servable URLs
160
- js = rewriteImports(js, filePath, projectRoot);
161
-
162
- return { js, css, cssHash };
163
- }
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 { computeHash, scopeCSS } from "@sigil-dev/compiler/css";
7
+ import type { DevGraph } from "./graph";
8
+ import { normalizePath } from "./paths";
9
+ import { resolveProjectImport } from "./resolve";
10
+
11
+ const RUNTIME_URL = "/__grimoire__/runtime.js";
12
+ const MODULES_BASE = "/__grimoire__/m/";
13
+ const DEPS_BASE = "/__grimoire__/dep/";
14
+
15
+ export interface BrowserCompileContext {
16
+ projectRoot: string;
17
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
18
+ aliases: Record<string, string>;
19
+ /** Supplies the version each dependency URL is stamped with. */
20
+ graph?: DevGraph;
21
+ }
22
+
23
+ /** `/__grimoire__/m/src/lib/Card.tsx.js?v=3` for a project module. */
24
+ function moduleUrl(absPath: string, ctx: BrowserCompileContext): string {
25
+ const rel = relative(ctx.projectRoot, absPath).replace(/\\/g, "/");
26
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
27
+ return `${MODULES_BASE}${rel}.js?v=${version}`;
28
+ }
29
+
30
+ /**
31
+ * Rewrite one import specifier to a browser-servable URL.
32
+ *
33
+ * Project modules carry their graph version in the query string: the browser
34
+ * caches ES modules by URL forever, so an edited component is only re-fetched
35
+ * when the importing module's own text points at a new URL.
36
+ */
37
+ function rewriteSpecifier(
38
+ specifier: string,
39
+ fromFile: string,
40
+ ctx: BrowserCompileContext,
41
+ ): string {
42
+ if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
43
+ if (specifier.startsWith("$env/")) return specifier;
44
+
45
+ const resolved = resolveProjectImport(
46
+ specifier,
47
+ fromFile,
48
+ ctx.projectRoot,
49
+ ctx.aliases,
50
+ );
51
+ if (resolved) return moduleUrl(resolved, ctx);
52
+
53
+ // unresolvable relative import (missing file) — keep a module URL so the
54
+ // browser reports the 404 against a path the developer recognises
55
+ if (specifier.startsWith(".") || specifier.startsWith("$lib/")) {
56
+ const rel = specifier.startsWith("$lib/")
57
+ ? specifier.replace("$lib/", "src/lib/")
58
+ : relative(ctx.projectRoot, join(fromFile, "..", specifier)).replace(
59
+ /\\/g,
60
+ "/",
61
+ );
62
+ return `${MODULES_BASE}${rel}.js`;
63
+ }
64
+
65
+ const pkgName = specifier.startsWith("@")
66
+ ? specifier.split("/").slice(0, 2).join("/")
67
+ : specifier.split("/")[0];
68
+ return `${DEPS_BASE}${pkgName!.replace("/", "__")}.js`;
69
+ }
70
+
71
+ /** Rewrite static `from "…"` / `import "…"` and dynamic `import("…")`. */
72
+ function rewriteImports(
73
+ code: string,
74
+ filePath: string,
75
+ ctx: BrowserCompileContext,
76
+ ): string {
77
+ return code
78
+ .replace(
79
+ /(from\s+|import\s+)(["'])([^"']+)\2/g,
80
+ (_m, keyword: string, quote: string, specifier: string) =>
81
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
82
+ )
83
+ .replace(
84
+ /(import\s*\(\s*)(["'])([^"']+)\2/g,
85
+ (_m, keyword: string, quote: string, specifier: string) =>
86
+ `${keyword}${quote}${rewriteSpecifier(specifier, filePath, ctx)}${quote}`,
87
+ );
88
+ }
89
+
90
+ export interface CompileResult {
91
+ js: string;
92
+ css: string | null;
93
+ cssHash: string;
94
+ }
95
+
96
+ const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/i;
97
+
98
+ const RUNTIME_SPECIFIERS = [
99
+ "createSignal",
100
+ "createRawSignal",
101
+ "createEffect",
102
+ "createMemo",
103
+ "reconcile",
104
+ "claim",
105
+ "claimText",
106
+ "claimComment",
107
+ "hydrateKeyedList",
108
+ "insert",
109
+ "getHydrationNodes",
110
+ "pushHydrationNodes",
111
+ "popHydrationNodes",
112
+ "snapshot",
113
+ "tracking",
114
+ "createEffectPre",
115
+ "createInspectEffect",
116
+ "withEffectScope",
117
+ ].join(", ");
118
+
119
+ export async function compileForBrowser(
120
+ filePath: string,
121
+ ctx: BrowserCompileContext,
122
+ ): Promise<CompileResult> {
123
+ const source = await Bun.file(filePath).text();
124
+
125
+ // the scope hash must be the compiler's own: a swapped module whose
126
+ // elements carry a different class than the emitted CSS loses its styles
127
+ const hash = computeHash(filePath);
128
+ const styleBody = source.match(STYLE_RE)?.[1]?.trim();
129
+ const css = styleBody ? scopeCSS(styleBody, hash) : null;
130
+ const sourceNoStyle = source.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
131
+
132
+ // dom mode: swapped modules always re-render from scratch, they never
133
+ // claim server-rendered nodes
134
+ const babelResult = transformSync(sourceNoStyle, {
135
+ configFile: false,
136
+ babelrc: false,
137
+ parserOpts: { plugins: ["typescript", "jsx"] },
138
+ plugins: [[sigilPlugin, { mode: "dom", hash, dev: true }]],
139
+ filename: filePath,
140
+ });
141
+ // strip TypeScript types
142
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
143
+ let js = transpiler.transformSync(babelResult?.code ?? "");
144
+
145
+ js = js.replace(
146
+ /import\s*\{[^}]+\}\s*from\s*["']@sigil-dev\/runtime["'];?/,
147
+ `import { ${RUNTIME_SPECIFIERS} } from "@sigil-dev/runtime";`,
148
+ );
149
+
150
+ // inject scoped CSS at runtime
151
+ if (css) {
152
+ js = `if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
153
+ const __s = document.createElement('style');
154
+ __s.id = 'sigil-${hash}';
155
+ __s.textContent = ${JSON.stringify(css)};
156
+ document.head.appendChild(__s);
157
+ }\n${js}`;
158
+ }
159
+
160
+ js = rewriteImports(js, filePath, ctx);
161
+
162
+ return { js, css, cssHash: hash };
163
+ }
164
+
165
+ const cacheName = (absPath: string, version: number): string => {
166
+ // hashed so one flat cache dir holds every module, path separators and all
167
+ const hash = createHash("md5")
168
+ .update(normalizePath(absPath))
169
+ .digest("hex")
170
+ .slice(0, 8);
171
+ return `${hash}_v${version}.js`;
172
+ };
173
+
174
+ /**
175
+ * Compile a module for the browser at its current graph version, memoised on
176
+ * disk. The version comes from the graph, not the request URL: a client may
177
+ * ask for a stale `?v=`, and serving anything but current code would
178
+ * reintroduce the mismatch HMR exists to avoid.
179
+ */
180
+ export async function getDevModule(
181
+ absPath: string,
182
+ ctx: BrowserCompileContext,
183
+ ): Promise<CompileResult> {
184
+ const version = ctx.graph?.get(absPath)?.version ?? 0;
185
+ const cachePath = join(
186
+ ctx.projectRoot,
187
+ ".grimoire/dev-modules",
188
+ cacheName(absPath, version),
189
+ );
190
+
191
+ const cached = Bun.file(cachePath);
192
+ if (await cached.exists()) {
193
+ return { js: await cached.text(), css: null, cssHash: "" };
194
+ }
195
+
196
+ const result = await compileForBrowser(absPath, ctx);
197
+ cacheDevModule(absPath, version, ctx.projectRoot, result.js);
198
+ return result;
199
+ }
200
+
201
+ /**
202
+ * Store already-compiled output for a version. Used by the HMR pipeline, which
203
+ * must compile the edited source *before* bumping the version — a failed
204
+ * compile has to leave the previous version live.
205
+ */
206
+ export function cacheDevModule(
207
+ absPath: string,
208
+ version: number,
209
+ projectRoot: string,
210
+ js: string,
211
+ ): void {
212
+ const dir = join(projectRoot, ".grimoire/dev-modules");
213
+ mkdirSync(dir, { recursive: true });
214
+ writeFileSync(join(dir, cacheName(absPath, version)), js);
215
+ }
@@ -1,23 +1,23 @@
1
- import { normalizePath } from "./paths";
2
-
3
- const registry = new Map<string, (() => void)[]>();
4
-
5
- export function registerModuleEffect(
6
- filePath: string,
7
- dispose: () => void,
8
- ): void {
9
- const key = normalizePath(filePath);
10
- let list = registry.get(key);
11
- if (!list) registry.set(key, (list = []));
12
- list.push(dispose);
13
- }
14
-
15
- export function disposeModuleEffects(filePath: string): void {
16
- const key = normalizePath(filePath);
17
- for (const d of registry.get(key) ?? []) {
18
- try {
19
- d();
20
- } catch {}
21
- }
22
- registry.delete(key);
23
- }
1
+ import { normalizePath } from "./paths";
2
+
3
+ const registry = new Map<string, (() => void)[]>();
4
+
5
+ export function registerModuleEffect(
6
+ filePath: string,
7
+ dispose: () => void,
8
+ ): void {
9
+ const key = normalizePath(filePath);
10
+ let list = registry.get(key);
11
+ if (!list) registry.set(key, (list = []));
12
+ list.push(dispose);
13
+ }
14
+
15
+ export function disposeModuleEffects(filePath: string): void {
16
+ const key = normalizePath(filePath);
17
+ for (const d of registry.get(key) ?? []) {
18
+ try {
19
+ d();
20
+ } catch {}
21
+ }
22
+ registry.delete(key);
23
+ }
package/src/dev/graph.ts CHANGED
@@ -1,114 +1,109 @@
1
- import type { RouteFile } from "../routing/scanner";
2
- import { normalizePath } from "./paths";
3
-
4
- export interface SpecRef {
5
- start: number;
6
- end: number;
7
- target: string; // normalizePath key or dep name
8
- kind: "project" | "dep" | "runtime";
9
- }
10
-
11
- export interface ModNode {
12
- key: string;
13
- displayPath: string;
14
- importers: Set<string>;
15
- imports: Set<string>;
16
- version: number;
17
- compiled: {
18
- js: string;
19
- css: string | null;
20
- cssHash: string;
21
- specifiers: SpecRef[];
22
- } | null;
23
- isRoute: RouteFile | null;
24
- lastSubstituted: Map<string, number>;
25
- }
26
-
27
- export class DevGraph {
28
- private nodes = new Map<string, ModNode>();
29
-
30
- get(key: string): ModNode | undefined {
31
- return this.nodes.get(normalizePath(key));
32
- }
33
-
34
- getOrCreate(filePath: string, displayPath?: string): ModNode {
35
- const key = normalizePath(filePath);
36
- if (!this.nodes.has(key)) {
37
- this.nodes.set(key, {
38
- key,
39
- displayPath: displayPath ?? filePath,
40
- importers: new Set(),
41
- imports: new Set(),
42
- version: 0,
43
- compiled: null,
44
- isRoute: null,
45
- lastSubstituted: new Map(),
46
- });
47
- }
48
- return this.nodes.get(key)!;
49
- }
50
-
51
- addEdge(importerPath: string, importedPath: string): void {
52
- const a = normalizePath(importerPath);
53
- const b = normalizePath(importedPath);
54
- this.getOrCreate(a).imports.add(b);
55
- this.getOrCreate(b).importers.add(a);
56
- }
57
-
58
- /** DFS for cycles in the subgraph reachable from key via forward edges */
59
- hasCycle(key: string): boolean {
60
- const k = normalizePath(key);
61
- const visited = new Set<string>();
62
- const stack = new Set<string>();
63
- const dfs = (node: string): boolean => {
64
- if (stack.has(node)) return true;
65
- if (visited.has(node)) return false;
66
- visited.add(node);
67
- stack.add(node);
68
- for (const imp of this.nodes.get(node)?.imports ?? []) {
69
- if (dfs(imp)) return true;
70
- }
71
- stack.delete(node);
72
- return false;
73
- };
74
- return dfs(k);
75
- }
76
-
77
- /** Walk importers up to routes. Returns affected RouteFiles. */
78
- affectedRoutes(changedKey: string): RouteFile[] {
79
- const key = normalizePath(changedKey);
80
- const seen = new Set<string>([key]);
81
- const queue = [key];
82
- const hits: RouteFile[] = [];
83
- while (queue.length) {
84
- const f = queue.pop()!;
85
- const node = this.nodes.get(f);
86
- if (!node) continue;
87
- if (node.isRoute) {
88
- hits.push(node.isRoute);
89
- continue;
90
- }
91
- for (const importer of node.importers) {
92
- if (!seen.has(importer)) {
93
- seen.add(importer);
94
- queue.push(importer);
95
- }
96
- }
97
- }
98
- return hits;
99
- }
100
-
101
- markRoute(filePath: string, route: RouteFile): void {
102
- this.getOrCreate(filePath).isRoute = route;
103
- }
104
-
105
- bump(filePath: string): number {
106
- const node = this.getOrCreate(filePath);
107
- node.version++;
108
- return node.version;
109
- }
110
-
111
- all(): IterableIterator<ModNode> {
112
- return this.nodes.values();
113
- }
114
- }
1
+ import type { RouteFile } from "../routing/scanner";
2
+ import { normalizePath } from "./paths";
3
+
4
+ export interface ModNode {
5
+ key: string;
6
+ displayPath: string;
7
+ importers: Set<string>;
8
+ imports: Set<string>;
9
+ /** Bumped on every edit to this module or to anything it imports. */
10
+ version: number;
11
+ isRoute: RouteFile | null;
12
+ }
13
+
14
+ export class DevGraph {
15
+ private nodes = new Map<string, ModNode>();
16
+
17
+ get(key: string): ModNode | undefined {
18
+ return this.nodes.get(normalizePath(key));
19
+ }
20
+
21
+ getOrCreate(filePath: string, displayPath?: string): ModNode {
22
+ const key = normalizePath(filePath);
23
+ if (!this.nodes.has(key)) {
24
+ this.nodes.set(key, {
25
+ key,
26
+ displayPath: displayPath ?? filePath,
27
+ importers: new Set(),
28
+ imports: new Set(),
29
+ version: 0,
30
+ isRoute: null,
31
+ });
32
+ }
33
+ return this.nodes.get(key)!;
34
+ }
35
+
36
+ /**
37
+ * Replace an importer's outgoing edges, dropping back-links that no longer
38
+ * apply. Called on every rescan so deleted imports stop propagating
39
+ * invalidation.
40
+ */
41
+ setImports(importerPath: string, importedPaths: string[]): void {
42
+ const key = normalizePath(importerPath);
43
+ const node = this.getOrCreate(importerPath);
44
+ const next = new Set(importedPaths.map(normalizePath));
45
+ for (const stale of node.imports) {
46
+ if (!next.has(stale)) this.nodes.get(stale)?.importers.delete(key);
47
+ }
48
+ node.imports = next;
49
+ for (const target of next) this.getOrCreate(target).importers.add(key);
50
+ }
51
+
52
+ /**
53
+ * Bump the changed module and every transitive importer, so both the SSR
54
+ * loader and the browser's module cache are forced to refetch every module
55
+ * on the path from a route down to the edit. Returns the bumped keys.
56
+ */
57
+ invalidate(changedKey: string): string[] {
58
+ const seen = new Set<string>();
59
+ const queue = [normalizePath(changedKey)];
60
+ while (queue.length) {
61
+ const key = queue.pop()!;
62
+ if (seen.has(key)) continue;
63
+ seen.add(key);
64
+ for (const importer of this.nodes.get(key)?.importers ?? []) {
65
+ if (!seen.has(importer)) queue.push(importer);
66
+ }
67
+ }
68
+ for (const key of seen) this.bump(key);
69
+ return [...seen];
70
+ }
71
+
72
+ /** Walk importers up to routes. Returns affected RouteFiles. */
73
+ affectedRoutes(changedKey: string): RouteFile[] {
74
+ const key = normalizePath(changedKey);
75
+ const seen = new Set<string>([key]);
76
+ const queue = [key];
77
+ const hits: RouteFile[] = [];
78
+ while (queue.length) {
79
+ const f = queue.pop()!;
80
+ const node = this.nodes.get(f);
81
+ if (!node) continue;
82
+ if (node.isRoute) {
83
+ hits.push(node.isRoute);
84
+ continue;
85
+ }
86
+ for (const importer of node.importers) {
87
+ if (!seen.has(importer)) {
88
+ seen.add(importer);
89
+ queue.push(importer);
90
+ }
91
+ }
92
+ }
93
+ return hits;
94
+ }
95
+
96
+ markRoute(filePath: string, route: RouteFile): void {
97
+ this.getOrCreate(filePath).isRoute = route;
98
+ }
99
+
100
+ bump(filePath: string): number {
101
+ const node = this.getOrCreate(filePath);
102
+ node.version++;
103
+ return node.version;
104
+ }
105
+
106
+ all(): IterableIterator<ModNode> {
107
+ return this.nodes.values();
108
+ }
109
+ }