@sigil-dev/grimoire 0.9.26 → 0.9.28

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/src/dev/loader.ts CHANGED
@@ -1,141 +1,144 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
- import { transformSync } from "@babel/core";
6
- import sigilPlugin from "@sigil-dev/compiler/babel";
7
- import {
8
- computeHash,
9
- extractStyles,
10
- serverStyleSnippet,
11
- } from "@sigil-dev/compiler/css";
12
- import { disposeModuleEffects } from "./effect-registry";
13
- import type { DevGraph } from "./graph";
14
- import { normalizePath } from "./paths";
15
- import { isSourceFile, resolveProjectImport } from "./resolve";
16
-
17
- export interface DevLoaderOptions {
18
- /** GrimoireConfig.alias — prefix → project-relative directory. */
19
- aliases?: Record<string, string>;
20
- }
21
-
22
- /**
23
- * Module loader for dev SSR.
24
- *
25
- * Bun caches every module it imports for the process lifetime, so a changed
26
- * file can only be re-executed under a fresh path. Each edited module (and
27
- * each importer of one, since the graph bumps them together) is recompiled
28
- * into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
29
- * rewritten to the versioned files of its dependencies — otherwise a
30
- * recompiled page would keep importing the cached copy of the component that
31
- * was just edited.
32
- */
33
- export function makeDevLoader(
34
- graph: DevGraph,
35
- projectRoot: string,
36
- options: DevLoaderOptions = {},
37
- ) {
38
- const cacheDir = join(projectRoot, ".grimoire/dev-cache");
39
- const aliases = options.aliases ?? {};
40
- // a previous session's cache cannot be trusted: same path, same version
41
- // number, different source
42
- rmSync(cacheDir, { recursive: true, force: true });
43
- mkdirSync(cacheDir, { recursive: true });
44
-
45
- /** Cache files this process has already written, by path. */
46
- const written = new Set<string>();
47
-
48
- const materialize = async (filePath: string): Promise<string> => {
49
- const version = graph.get(filePath)?.version ?? 0;
50
- // untouched since startup: the SSR plugin handles the source directly
51
- if (version === 0) return pathToFileURL(filePath).href;
52
-
53
- const key = createHash("md5")
54
- .update(normalizePath(filePath))
55
- .digest("hex")
56
- .slice(0, 8);
57
- const cachePath = join(cacheDir, `${key}_v${version}.js`);
58
- const href = pathToFileURL(cachePath).href;
59
- // (file, version) is immutable within a session; import cycles reach
60
- // the same deterministic path, and the outer call writes it
61
- if (written.has(cachePath)) return href;
62
- written.add(cachePath);
63
-
64
- try {
65
- const source = await Bun.file(filePath).text();
66
- // scoped <style> blocks come out before parsing (CSS braces would
67
- // read as JSX expressions); their CSS is registered for the
68
- // renderer, which puts it in <head>
69
- const styles = extractStyles(source, computeHash(filePath), filePath);
70
- const babelResult = transformSync(styles.code, {
71
- configFile: false,
72
- babelrc: false,
73
- parserOpts: { plugins: ["typescript", "jsx"] },
74
- plugins: [
75
- [
76
- sigilPlugin,
77
- {
78
- mode: "ssr",
79
- hash: styles.css ? computeHash(filePath) : undefined,
80
- },
81
- ],
82
- ],
83
- filename: filePath,
84
- });
85
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
86
- let compiled = transpiler.transformSync(babelResult?.code ?? "");
87
- if (styles.css) {
88
- compiled =
89
- serverStyleSnippet(computeHash(filePath), styles.css) + compiled;
90
- }
91
- compiled = await rewriteSpecifiers(compiled, async (specifier) => {
92
- const resolved = resolveProjectImport(
93
- specifier,
94
- filePath,
95
- projectRoot,
96
- aliases,
97
- );
98
- // externals keep their specifier: node_modules resolution walks
99
- // up from the cache dir to the project root all the same
100
- if (!resolved || !isSourceFile(resolved)) return null;
101
- return await materialize(resolved);
102
- });
103
- mkdirSync(cacheDir, { recursive: true });
104
- writeFileSync(cachePath, compiled);
105
- } catch (e) {
106
- // let the next request retry instead of importing a half-written file
107
- written.delete(cachePath);
108
- throw e;
109
- }
110
- return href;
111
- };
112
-
113
- return async function devLoadModule(filePath: string): Promise<unknown> {
114
- disposeModuleEffects(normalizePath(filePath));
115
- return import(await materialize(filePath));
116
- };
117
- }
118
-
119
- const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
120
-
121
- /** Replace every import specifier for which `resolve` returns a new one. */
122
- async function rewriteSpecifiers(
123
- code: string,
124
- resolve: (specifier: string) => Promise<string | null>,
125
- ): Promise<string> {
126
- const replacements = new Map<string, string>();
127
- for (const match of code.matchAll(SPEC_RE)) {
128
- const specifier = match[3]!;
129
- if (replacements.has(specifier)) continue;
130
- const next = await resolve(specifier);
131
- if (next) replacements.set(specifier, next);
132
- }
133
- if (replacements.size === 0) return code;
134
- return code.replace(
135
- SPEC_RE,
136
- (match, keyword: string, quote: string, specifier: string) => {
137
- const next = replacements.get(specifier);
138
- return next ? `${keyword}${quote}${next}${quote}` : match;
139
- },
140
- );
141
- }
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { transformSync } from "@babel/core";
6
+ import sigilPlugin from "@sigil-dev/compiler/babel";
7
+ import {
8
+ computeHash,
9
+ extractStyles,
10
+ serverStyleSnippet,
11
+ } from "@sigil-dev/compiler/css";
12
+ import { disposeModuleEffects } from "./effect-registry";
13
+ import type { DevGraph } from "./graph";
14
+ import { normalizePath } from "./paths";
15
+ import { absoluteAliases, isSourceFile, resolveProjectImport } from "./resolve";
16
+ import { pinRuntime } from "../server/resolver";
17
+
18
+ export interface DevLoaderOptions {
19
+ /** GrimoireConfig.alias — prefix → project-relative directory. */
20
+ aliases?: Record<string, string>;
21
+ }
22
+
23
+ /**
24
+ * Module loader for dev SSR.
25
+ *
26
+ * Bun caches every module it imports for the process lifetime, so a changed
27
+ * file can only be re-executed under a fresh path. Each edited module (and
28
+ * each importer of one, since the graph bumps them together) is recompiled
29
+ * into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
30
+ * rewritten to the versioned files of its dependencies — otherwise a
31
+ * recompiled page would keep importing the cached copy of the component that
32
+ * was just edited.
33
+ */
34
+ export function makeDevLoader(
35
+ graph: DevGraph,
36
+ projectRoot: string,
37
+ options: DevLoaderOptions = {},
38
+ ) {
39
+ const cacheDir = join(projectRoot, ".grimoire/dev-cache");
40
+ const aliases = options.aliases ?? {};
41
+ // a previous session's cache cannot be trusted: same path, same version
42
+ // number, different source
43
+ rmSync(cacheDir, { recursive: true, force: true });
44
+ mkdirSync(cacheDir, { recursive: true });
45
+
46
+ /** Cache files this process has already written, by path. */
47
+ const written = new Set<string>();
48
+
49
+ const materialize = async (filePath: string): Promise<string> => {
50
+ const version = graph.get(filePath)?.version ?? 0;
51
+ // untouched since startup: the SSR plugin handles the source directly
52
+ if (version === 0) return pathToFileURL(filePath).href;
53
+
54
+ const key = createHash("md5")
55
+ .update(normalizePath(filePath))
56
+ .digest("hex")
57
+ .slice(0, 8);
58
+ const cachePath = join(cacheDir, `${key}_v${version}.js`);
59
+ const href = pathToFileURL(cachePath).href;
60
+ // (file, version) is immutable within a session; import cycles reach
61
+ // the same deterministic path, and the outer call writes it
62
+ if (written.has(cachePath)) return href;
63
+ written.add(cachePath);
64
+
65
+ try {
66
+ const source = await Bun.file(filePath).text();
67
+ // scoped <style> blocks come out before parsing (CSS braces would
68
+ // read as JSX expressions); their CSS is registered for the
69
+ // renderer, which puts it in <head>
70
+ const styles = extractStyles(source, computeHash(filePath), filePath);
71
+ const babelResult = transformSync(styles.code, {
72
+ configFile: false,
73
+ babelrc: false,
74
+ parserOpts: { plugins: ["typescript", "jsx"] },
75
+ plugins: [
76
+ [
77
+ sigilPlugin,
78
+ {
79
+ mode: "ssr",
80
+ hash: styles.css ? computeHash(filePath) : undefined,
81
+ aliases: absoluteAliases(projectRoot, aliases),
82
+ },
83
+ ],
84
+ ],
85
+ filename: filePath,
86
+ });
87
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
88
+ let compiled = transpiler.transformSync(babelResult?.code ?? "");
89
+ if (styles.css) {
90
+ compiled =
91
+ serverStyleSnippet(computeHash(filePath), styles.css) + compiled;
92
+ }
93
+ compiled = pinRuntime(compiled);
94
+ compiled = await rewriteSpecifiers(compiled, async (specifier) => {
95
+ const resolved = resolveProjectImport(
96
+ specifier,
97
+ filePath,
98
+ projectRoot,
99
+ aliases,
100
+ );
101
+ // externals keep their specifier: node_modules resolution walks
102
+ // up from the cache dir to the project root all the same
103
+ if (!resolved || !isSourceFile(resolved)) return null;
104
+ return await materialize(resolved);
105
+ });
106
+ mkdirSync(cacheDir, { recursive: true });
107
+ writeFileSync(cachePath, compiled);
108
+ } catch (e) {
109
+ // let the next request retry instead of importing a half-written file
110
+ written.delete(cachePath);
111
+ throw e;
112
+ }
113
+ return href;
114
+ };
115
+
116
+ return async function devLoadModule(filePath: string): Promise<unknown> {
117
+ disposeModuleEffects(normalizePath(filePath));
118
+ return import(await materialize(filePath));
119
+ };
120
+ }
121
+
122
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
123
+
124
+ /** Replace every import specifier for which `resolve` returns a new one. */
125
+ async function rewriteSpecifiers(
126
+ code: string,
127
+ resolve: (specifier: string) => Promise<string | null>,
128
+ ): Promise<string> {
129
+ const replacements = new Map<string, string>();
130
+ for (const match of code.matchAll(SPEC_RE)) {
131
+ const specifier = match[3]!;
132
+ if (replacements.has(specifier)) continue;
133
+ const next = await resolve(specifier);
134
+ if (next) replacements.set(specifier, next);
135
+ }
136
+ if (replacements.size === 0) return code;
137
+ return code.replace(
138
+ SPEC_RE,
139
+ (match, keyword: string, quote: string, specifier: string) => {
140
+ const next = replacements.get(specifier);
141
+ return next ? `${keyword}${quote}${next}${quote}` : match;
142
+ },
143
+ );
144
+ }
@@ -1,70 +1,85 @@
1
- import { statSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
-
4
- const EXTS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"];
5
-
6
- function isFile(p: string): boolean {
7
- try {
8
- return statSync(p).isFile();
9
- } catch {
10
- return false;
11
- }
12
- }
13
-
14
- /** Add extensions / index files until an on-disk source file is found. */
15
- export function resolveFile(base: string): string | null {
16
- if (isFile(base)) return base;
17
- for (const ext of EXTS) if (isFile(base + ext)) return base + ext;
18
- for (const ext of EXTS) {
19
- const indexed = join(base, `index${ext}`);
20
- if (isFile(indexed)) return indexed;
21
- }
22
- return null;
23
- }
24
-
25
- /**
26
- * Resolve an import specifier to an absolute project source file.
27
- *
28
- * Returns `null` for anything outside the project's own sources — bare npm
29
- * specifiers, `$env/*` virtual modules and `@sigil-dev/*` packages. Those are
30
- * never part of the dev graph: they can't be hot-swapped, and their browser
31
- * URLs are stable.
32
- *
33
- * `aliases` mirrors `GrimoireConfig.alias` (prefix → project-relative dir).
34
- */
35
- export function resolveProjectImport(
36
- specifier: string,
37
- fromFile: string,
38
- projectRoot: string,
39
- aliases: Record<string, string> = {},
40
- ): string | null {
41
- if (specifier.startsWith("$env/")) return null;
42
- if (specifier.startsWith("@sigil-dev/")) return null;
43
-
44
- if (specifier.startsWith(".")) {
45
- return resolveFile(join(dirname(fromFile), specifier));
46
- }
47
- if (specifier === "$lib" || specifier.startsWith("$lib/")) {
48
- return resolveFile(join(projectRoot, "src/lib", specifier.slice(5)));
49
- }
50
- for (const [prefix, target] of Object.entries(aliases)) {
51
- if (specifier !== prefix && !specifier.startsWith(`${prefix}/`)) continue;
52
- const rest = specifier.slice(prefix.length);
53
- return resolveFile(join(projectRoot, target, rest));
54
- }
55
- return null;
56
- }
57
-
58
- /** Source files the dev graph tracks. */
59
- export function isSourceFile(filePath: string): boolean {
60
- return /\.[cm]?[jt]sx?$/.test(filePath);
61
- }
62
-
63
- /** Files that only ever run on the server — never sent to the browser. */
64
- export function isServerOnly(filePath: string): boolean {
65
- return (
66
- /(^|[\\/])(\+page\.server|\+layout\.server|\+server|hooks\.server)\.[cm]?[jt]s$/.test(
67
- filePath,
68
- ) || /\.server\.[cm]?[jt]sx?$/.test(filePath)
69
- );
70
- }
1
+ import { statSync } from "node:fs";
2
+ import { dirname, isAbsolute, join } from "node:path";
3
+
4
+ const EXTS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"];
5
+
6
+ function isFile(p: string): boolean {
7
+ try {
8
+ return statSync(p).isFile();
9
+ } catch {
10
+ return false;
11
+ }
12
+ }
13
+
14
+ /** Add extensions / index files until an on-disk source file is found. */
15
+ export function resolveFile(base: string): string | null {
16
+ if (isFile(base)) return base;
17
+ for (const ext of EXTS) if (isFile(base + ext)) return base + ext;
18
+ for (const ext of EXTS) {
19
+ const indexed = join(base, `index${ext}`);
20
+ if (isFile(indexed)) return indexed;
21
+ }
22
+ return null;
23
+ }
24
+
25
+ /**
26
+ * Resolve an import specifier to an absolute project source file.
27
+ *
28
+ * Returns `null` for anything outside the project's own sources — bare npm
29
+ * specifiers, `$env/*` virtual modules and `@sigil-dev/*` packages. Those are
30
+ * never part of the dev graph: they can't be hot-swapped, and their browser
31
+ * URLs are stable.
32
+ *
33
+ * `aliases` mirrors `GrimoireConfig.alias` (prefix → project-relative dir).
34
+ */
35
+ export function resolveProjectImport(
36
+ specifier: string,
37
+ fromFile: string,
38
+ projectRoot: string,
39
+ aliases: Record<string, string> = {},
40
+ ): string | null {
41
+ if (specifier.startsWith("$env/")) return null;
42
+ if (specifier.startsWith("@sigil-dev/")) return null;
43
+
44
+ if (specifier.startsWith(".")) {
45
+ return resolveFile(join(dirname(fromFile), specifier));
46
+ }
47
+ if (specifier === "$lib" || specifier.startsWith("$lib/")) {
48
+ return resolveFile(join(projectRoot, "src/lib", specifier.slice(5)));
49
+ }
50
+ for (const [prefix, target] of Object.entries(aliases)) {
51
+ if (specifier !== prefix && !specifier.startsWith(`${prefix}/`)) continue;
52
+ const rest = specifier.slice(prefix.length);
53
+ return resolveFile(join(projectRoot, target, rest));
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /** Source files the dev graph tracks. */
59
+ export function isSourceFile(filePath: string): boolean {
60
+ return /\.[cm]?[jt]sx?$/.test(filePath);
61
+ }
62
+
63
+ /** Files that only ever run on the server — never sent to the browser. */
64
+ export function isServerOnly(filePath: string): boolean {
65
+ return (
66
+ /(^|[\\/])(\+page\.server|\+layout\.server|\+server|hooks\.server)\.[cm]?[jt]s$/.test(
67
+ filePath,
68
+ ) || /\.server\.[cm]?[jt]sx?$/.test(filePath)
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Dev aliases (project-relative, as in GrimoireConfig.alias) plus `$lib`, as
74
+ * the absolute directories the compiler resolves imported state through.
75
+ */
76
+ export function absoluteAliases(
77
+ projectRoot: string,
78
+ aliases: Record<string, string> = {},
79
+ ): Record<string, string> {
80
+ const out: Record<string, string> = { $lib: join(projectRoot, "src/lib") };
81
+ for (const [prefix, target] of Object.entries(aliases)) {
82
+ out[prefix] = isAbsolute(target) ? target : join(projectRoot, target);
83
+ }
84
+ return out;
85
+ }