@sigil-dev/grimoire 0.9.21 → 0.9.23
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/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +22 -10
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +871 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -749
- package/src/rendering/preload.ts +102 -101
- package/src/rendering/ssrPlugin.ts +1 -1
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +262 -262
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -44
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +211 -80
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +1 -1
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +799 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +381 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +808 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +1 -1
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/src/dev/loader.ts
CHANGED
|
@@ -1,141 +1,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 { 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 { 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
|
+
}
|
package/src/dev/resolve.ts
CHANGED
|
@@ -1,70 +1,70 @@
|
|
|
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, 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,51 +1,51 @@
|
|
|
1
|
-
import { mkdirSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { log } from "../logger/instance";
|
|
4
|
-
import { clientDir } from "../server/client-dir";
|
|
5
|
-
|
|
6
|
-
const logger = log.scope("runtime-bundle");
|
|
7
|
-
|
|
8
|
-
export async function ensureRuntimeBundle(projectRoot: string): Promise<void> {
|
|
9
|
-
const outDir = clientDir(projectRoot);
|
|
10
|
-
mkdirSync(outDir, { recursive: true });
|
|
11
|
-
|
|
12
|
-
// runtime: rebuilt on every start, since an existing file says nothing
|
|
13
|
-
// about whether @sigil-dev/runtime changed under it. It takes a few ms.
|
|
14
|
-
logger.debug("bundling runtime...");
|
|
15
|
-
const result = await Bun.build({
|
|
16
|
-
entrypoints: [
|
|
17
|
-
join(projectRoot, "node_modules/@sigil-dev/runtime/index.ts"),
|
|
18
|
-
],
|
|
19
|
-
outdir: outDir,
|
|
20
|
-
naming: "runtime.js",
|
|
21
|
-
target: "browser",
|
|
22
|
-
format: "esm",
|
|
23
|
-
minify: false,
|
|
24
|
-
});
|
|
25
|
-
if (!result.success)
|
|
26
|
-
logger.error("[sigil hmr] runtime bundle failed:", result.logs);
|
|
27
|
-
else logger.debug("[sigil hmr] runtime bundled");
|
|
28
|
-
|
|
29
|
-
// grimoire client
|
|
30
|
-
const grimClientOut = join(outDir, "grimoire-client.js");
|
|
31
|
-
const ref = Bun.file(grimClientOut);
|
|
32
|
-
if (await ref.exists()) await ref.delete();
|
|
33
|
-
await Bun.write(
|
|
34
|
-
grimClientOut,
|
|
35
|
-
`
|
|
36
|
-
// Grimoire client shim for HMR dev mode
|
|
37
|
-
export function Head({ children }) {
|
|
38
|
-
if (children instanceof Node) {
|
|
39
|
-
document.head.appendChild(children);
|
|
40
|
-
}
|
|
41
|
-
return document.createComment("head");
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export const navigate = (...args) => window.__grimoire_navigate__?.(...args);
|
|
45
|
-
export const beforeNavigate = (cb) => window.__grimoire_beforeNavigate__?.(cb);
|
|
46
|
-
export const onNavigate = (cb) => window.__grimoire_onNavigate__?.(cb);
|
|
47
|
-
export const afterNavigate = (cb) => window.__grimoire_afterNavigate__?.(cb);
|
|
48
|
-
`.trim(),
|
|
49
|
-
);
|
|
50
|
-
logger.info("grimoire client shim written");
|
|
51
|
-
}
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { log } from "../logger/instance";
|
|
4
|
+
import { clientDir } from "../server/client-dir";
|
|
5
|
+
|
|
6
|
+
const logger = log.scope("runtime-bundle");
|
|
7
|
+
|
|
8
|
+
export async function ensureRuntimeBundle(projectRoot: string): Promise<void> {
|
|
9
|
+
const outDir = clientDir(projectRoot);
|
|
10
|
+
mkdirSync(outDir, { recursive: true });
|
|
11
|
+
|
|
12
|
+
// runtime: rebuilt on every start, since an existing file says nothing
|
|
13
|
+
// about whether @sigil-dev/runtime changed under it. It takes a few ms.
|
|
14
|
+
logger.debug("bundling runtime...");
|
|
15
|
+
const result = await Bun.build({
|
|
16
|
+
entrypoints: [
|
|
17
|
+
join(projectRoot, "node_modules/@sigil-dev/runtime/index.ts"),
|
|
18
|
+
],
|
|
19
|
+
outdir: outDir,
|
|
20
|
+
naming: "runtime.js",
|
|
21
|
+
target: "browser",
|
|
22
|
+
format: "esm",
|
|
23
|
+
minify: false,
|
|
24
|
+
});
|
|
25
|
+
if (!result.success)
|
|
26
|
+
logger.error("[sigil hmr] runtime bundle failed:", result.logs);
|
|
27
|
+
else logger.debug("[sigil hmr] runtime bundled");
|
|
28
|
+
|
|
29
|
+
// grimoire client
|
|
30
|
+
const grimClientOut = join(outDir, "grimoire-client.js");
|
|
31
|
+
const ref = Bun.file(grimClientOut);
|
|
32
|
+
if (await ref.exists()) await ref.delete();
|
|
33
|
+
await Bun.write(
|
|
34
|
+
grimClientOut,
|
|
35
|
+
`
|
|
36
|
+
// Grimoire client shim for HMR dev mode
|
|
37
|
+
export function Head({ children }) {
|
|
38
|
+
if (children instanceof Node) {
|
|
39
|
+
document.head.appendChild(children);
|
|
40
|
+
}
|
|
41
|
+
return document.createComment("head");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const navigate = (...args) => window.__grimoire_navigate__?.(...args);
|
|
45
|
+
export const beforeNavigate = (cb) => window.__grimoire_beforeNavigate__?.(cb);
|
|
46
|
+
export const onNavigate = (cb) => window.__grimoire_onNavigate__?.(cb);
|
|
47
|
+
export const afterNavigate = (cb) => window.__grimoire_afterNavigate__?.(cb);
|
|
48
|
+
`.trim(),
|
|
49
|
+
);
|
|
50
|
+
logger.info("grimoire client shim written");
|
|
51
|
+
}
|
package/src/env/modules.ts
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
2
|
-
import { filterPrivate, filterPublic } from "./index";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Source for the `$env/*` modules.
|
|
6
|
-
*
|
|
7
|
-
* - `$env/static/public` and `$env/static/private`: values read when the
|
|
8
|
-
* module is built (the browser build, or server start), as `env` and as
|
|
9
|
-
* one named export per variable.
|
|
10
|
-
* - `$env/dynamic/public`: `env`, read live on the server; in the browser,
|
|
11
|
-
* the values the server rendered into the page (`__grimoire_env__`).
|
|
12
|
-
* - `$env/dynamic/private`: `env`, every variable, read live.
|
|
13
|
-
*
|
|
14
|
-
* `env` reads a missing variable as "".
|
|
15
|
-
*
|
|
16
|
-
* The private modules are server-only: importing one into browser code
|
|
17
|
-
* fails the build rather than shipping secrets.
|
|
18
|
-
*/
|
|
19
|
-
export const ENV_MODULE = /^\$env\/(static|dynamic)\/(public|private)$/;
|
|
20
|
-
|
|
21
|
-
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
22
|
-
|
|
23
|
-
function snapshot(values: Record<string, string>): string {
|
|
24
|
-
const names = Object.keys(values).filter((k) => IDENT.test(k));
|
|
25
|
-
return [
|
|
26
|
-
`export const env = ${JSON.stringify(values)};`,
|
|
27
|
-
...names.map((k) => `export const ${k} = env[${JSON.stringify(k)}];`),
|
|
28
|
-
].join("\n");
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function envModuleSource(
|
|
32
|
-
specifier: string,
|
|
33
|
-
target: "server" | "browser",
|
|
34
|
-
): string {
|
|
35
|
-
const m = ENV_MODULE.exec(specifier);
|
|
36
|
-
if (!m) throw new Error(`unknown env module ${specifier}`);
|
|
37
|
-
const [, kind, visibility] = m;
|
|
38
|
-
if (visibility === "private" && target === "browser") {
|
|
39
|
-
throw new Error(
|
|
40
|
-
`${specifier} holds server secrets and can't be imported into browser code. Import it from a .server.ts file, or use $env/${kind}/public for PUBLIC_ variables.`,
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
if (kind === "static") {
|
|
44
|
-
return snapshot(
|
|
45
|
-
visibility === "public"
|
|
46
|
-
? filterPublic(process.env)
|
|
47
|
-
: filterPrivate(process.env),
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
if (target === "browser") {
|
|
51
|
-
// like the server's: a missing PUBLIC_ variable reads as ""
|
|
52
|
-
return `const values = globalThis.__grimoire_env__ ?? {};
|
|
53
|
-
export const env = new Proxy(values, {
|
|
54
|
-
get: (t, k) => (typeof k === "string" ? (t[k] ?? "") : undefined),
|
|
55
|
-
});`;
|
|
56
|
-
}
|
|
57
|
-
const file = join(
|
|
58
|
-
import.meta.dir,
|
|
59
|
-
visibility === "public" ? "dynamic-public.ts" : "dynamic-private.ts",
|
|
60
|
-
);
|
|
61
|
-
return `export { env } from ${JSON.stringify(file)};`;
|
|
62
|
-
}
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { filterPrivate, filterPublic } from "./index";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Source for the `$env/*` modules.
|
|
6
|
+
*
|
|
7
|
+
* - `$env/static/public` and `$env/static/private`: values read when the
|
|
8
|
+
* module is built (the browser build, or server start), as `env` and as
|
|
9
|
+
* one named export per variable.
|
|
10
|
+
* - `$env/dynamic/public`: `env`, read live on the server; in the browser,
|
|
11
|
+
* the values the server rendered into the page (`__grimoire_env__`).
|
|
12
|
+
* - `$env/dynamic/private`: `env`, every variable, read live.
|
|
13
|
+
*
|
|
14
|
+
* `env` reads a missing variable as "".
|
|
15
|
+
*
|
|
16
|
+
* The private modules are server-only: importing one into browser code
|
|
17
|
+
* fails the build rather than shipping secrets.
|
|
18
|
+
*/
|
|
19
|
+
export const ENV_MODULE = /^\$env\/(static|dynamic)\/(public|private)$/;
|
|
20
|
+
|
|
21
|
+
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
22
|
+
|
|
23
|
+
function snapshot(values: Record<string, string>): string {
|
|
24
|
+
const names = Object.keys(values).filter((k) => IDENT.test(k));
|
|
25
|
+
return [
|
|
26
|
+
`export const env = ${JSON.stringify(values)};`,
|
|
27
|
+
...names.map((k) => `export const ${k} = env[${JSON.stringify(k)}];`),
|
|
28
|
+
].join("\n");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function envModuleSource(
|
|
32
|
+
specifier: string,
|
|
33
|
+
target: "server" | "browser",
|
|
34
|
+
): string {
|
|
35
|
+
const m = ENV_MODULE.exec(specifier);
|
|
36
|
+
if (!m) throw new Error(`unknown env module ${specifier}`);
|
|
37
|
+
const [, kind, visibility] = m;
|
|
38
|
+
if (visibility === "private" && target === "browser") {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`${specifier} holds server secrets and can't be imported into browser code. Import it from a .server.ts file, or use $env/${kind}/public for PUBLIC_ variables.`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (kind === "static") {
|
|
44
|
+
return snapshot(
|
|
45
|
+
visibility === "public"
|
|
46
|
+
? filterPublic(process.env)
|
|
47
|
+
: filterPrivate(process.env),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
if (target === "browser") {
|
|
51
|
+
// like the server's: a missing PUBLIC_ variable reads as ""
|
|
52
|
+
return `const values = globalThis.__grimoire_env__ ?? {};
|
|
53
|
+
export const env = new Proxy(values, {
|
|
54
|
+
get: (t, k) => (typeof k === "string" ? (t[k] ?? "") : undefined),
|
|
55
|
+
});`;
|
|
56
|
+
}
|
|
57
|
+
const file = join(
|
|
58
|
+
import.meta.dir,
|
|
59
|
+
visibility === "public" ? "dynamic-public.ts" : "dynamic-private.ts",
|
|
60
|
+
);
|
|
61
|
+
return `export { env } from ${JSON.stringify(file)};`;
|
|
62
|
+
}
|