@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.
- package/index.ts +37 -37
- package/package.json +3 -3
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +36 -36
- package/src/client/enhance.ts +102 -102
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +5 -5
- package/src/client/router.ts +42 -20
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +215 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +109 -114
- package/src/dev/hmr-client.ts +202 -185
- package/src/dev/hmr-server.ts +261 -187
- package/src/dev/loader.ts +120 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/resolve.ts +70 -0
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/scan.ts +78 -0
- package/src/dev/watcher.ts +69 -47
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +52 -47
- package/src/rendering/hydrate.ts +16 -3
- package/src/rendering/index.ts +10 -6
- package/src/rendering/ssrPlugin.ts +78 -69
- package/src/routing/manifest-gen.ts +55 -55
- package/src/routing/router.ts +135 -135
- package/src/routing/scanner.ts +196 -187
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +250 -255
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +364 -364
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +711 -677
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -121
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +389 -389
- package/src/types.ts +286 -286
- package/test/client-router.test.ts +295 -298
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +90 -90
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hmr.test.ts +426 -0
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +719 -728
- package/test/routing.test.ts +197 -194
- package/test/scanning.test.ts +314 -254
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +360 -354
- package/test/streaming.test.ts +242 -242
- package/test/transform-routes.test.ts +87 -87
- package/test/typegen.test.ts +697 -697
- package/tsconfig.json +10 -10
package/src/dev/hmr-server.ts
CHANGED
|
@@ -1,187 +1,261 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
private
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
if (
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import type { ServerWebSocket } from "bun";
|
|
3
|
+
import { log } from "../logger/instance";
|
|
4
|
+
import { cacheDevModule, compileForBrowser } from "./compile-module";
|
|
5
|
+
import type { DevGraph } from "./graph";
|
|
6
|
+
import { normalizePath } from "./paths";
|
|
7
|
+
import { isServerOnly, isSourceFile } from "./resolve";
|
|
8
|
+
import { crawlFrom } from "./scan";
|
|
9
|
+
import { safeRead } from "./watcher";
|
|
10
|
+
|
|
11
|
+
const logger = log.scope("hmr");
|
|
12
|
+
|
|
13
|
+
export class HmrServer {
|
|
14
|
+
private clients = new Set<ServerWebSocket<unknown>>();
|
|
15
|
+
private v = 0;
|
|
16
|
+
get clientCount() {
|
|
17
|
+
return this.clients.size;
|
|
18
|
+
}
|
|
19
|
+
addClient(ws: ServerWebSocket<unknown>) {
|
|
20
|
+
this.clients.add(ws);
|
|
21
|
+
ws.send(JSON.stringify({ type: "connected" }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
removeClient(ws: ServerWebSocket<unknown>) {
|
|
25
|
+
this.clients.delete(ws);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
send(msg: object) {
|
|
29
|
+
const s = JSON.stringify(msg);
|
|
30
|
+
for (const c of this.clients) c.send(s);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
batch(payloads: object[]) {
|
|
34
|
+
this.send({ type: "batch", payloads, v: ++this.v });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
reload() {
|
|
38
|
+
logger.info("sending reload to", this.clients.size, "clients");
|
|
39
|
+
this.batch([{ kind: "reload" }]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
error(message: string, loc?: { file: string; line: number; col: number }) {
|
|
43
|
+
this.send({ type: "error", message, loc });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface ErrorLoc {
|
|
48
|
+
file: string;
|
|
49
|
+
line: number;
|
|
50
|
+
col: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function extractLoc(e: unknown, filePath: string): ErrorLoc | undefined {
|
|
54
|
+
// Babel errors carry loc.line / loc.column
|
|
55
|
+
if (e && typeof e === "object" && "loc" in e) {
|
|
56
|
+
const loc = e.loc;
|
|
57
|
+
if (loc && typeof loc === "object" && "line" in loc) {
|
|
58
|
+
const line = Number(loc.line);
|
|
59
|
+
const col = "column" in loc ? Number(loc.column) : 0;
|
|
60
|
+
if (Number.isFinite(line))
|
|
61
|
+
return { file: filePath, line, col: Number.isFinite(col) ? col : 0 };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// fallback: parse a trailing "file:line:col" out of the message
|
|
65
|
+
const m = errorMessage(e).match(/:(\d+):(\d+)$/);
|
|
66
|
+
return m
|
|
67
|
+
? { file: filePath, line: Number(m[1]), col: Number(m[2]) }
|
|
68
|
+
: undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function errorMessage(e: unknown): string {
|
|
72
|
+
if (e instanceof Error) return e.message;
|
|
73
|
+
if (e && typeof e === "object" && "message" in e) return String(e.message);
|
|
74
|
+
return String(e);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface DevContext {
|
|
78
|
+
graph: DevGraph;
|
|
79
|
+
hmr: HmrServer;
|
|
80
|
+
projectRoot: string;
|
|
81
|
+
/** GrimoireConfig.alias — prefix → project-relative directory. */
|
|
82
|
+
aliases: Record<string, string>;
|
|
83
|
+
/** Route/layout/server files the graph is crawled from. */
|
|
84
|
+
entries: () => string[];
|
|
85
|
+
/**
|
|
86
|
+
* Rescan routes and rebuild the client bundles. Awaited before a full
|
|
87
|
+
* reload: `hydrate.js` is built once at startup, so reloading without a
|
|
88
|
+
* rebuild would serve the browser the code from before the edit.
|
|
89
|
+
*/
|
|
90
|
+
rebuild: () => Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Same rebuild, off the critical path. Runs after a hot swap so that a
|
|
93
|
+
* later manual refresh — which loads the prebuilt bundle, not the swapped
|
|
94
|
+
* modules — shows the same code the running page already has.
|
|
95
|
+
*/
|
|
96
|
+
scheduleRebuild: () => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `src/lib/Card.tsx` → the `/__grimoire__/m/` path the client imports. */
|
|
100
|
+
const clientModulePath = (filePath: string, projectRoot: string): string =>
|
|
101
|
+
`${relative(projectRoot, filePath).replace(/\\/g, "/")}.js`;
|
|
102
|
+
|
|
103
|
+
interface RouteEntryPayload {
|
|
104
|
+
pattern: string;
|
|
105
|
+
modUrl: string;
|
|
106
|
+
version: number;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface LayoutEntryPayload {
|
|
110
|
+
path: string;
|
|
111
|
+
modUrl: string;
|
|
112
|
+
version: number;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Does an edit to this file change what a `load` returns? Route modules own
|
|
117
|
+
* their data loaders, so a swap alone would re-render the new component
|
|
118
|
+
* against data produced by the old loader.
|
|
119
|
+
*/
|
|
120
|
+
function affectsData(filePath: string, source: string): boolean {
|
|
121
|
+
if (isServerOnly(filePath)) return true;
|
|
122
|
+
return /\bexport\s+(async\s+)?(function\s+load\b|const\s+load\b|const\s+actions\b|function\s+canMatch\b|const\s+canMatch\b)/.test(
|
|
123
|
+
source,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function fullReload(ctx: DevContext): Promise<void> {
|
|
128
|
+
await ctx.rebuild();
|
|
129
|
+
ctx.hmr.reload();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function handleChange(
|
|
133
|
+
filePath: string,
|
|
134
|
+
ctx: DevContext,
|
|
135
|
+
): Promise<void> {
|
|
136
|
+
const { graph, hmr, projectRoot } = ctx;
|
|
137
|
+
const key = normalizePath(filePath);
|
|
138
|
+
|
|
139
|
+
if (!isSourceFile(filePath)) {
|
|
140
|
+
logger.info("non-source change, reloading:", filePath);
|
|
141
|
+
await fullReload(ctx);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const source = await safeRead(filePath);
|
|
146
|
+
if (source === null) {
|
|
147
|
+
// deleted or unreadable — the module graph can't be trusted any more
|
|
148
|
+
await fullReload(ctx);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (!graph.get(key)) {
|
|
153
|
+
// a brand-new file, or one that just became imported: recrawl from the
|
|
154
|
+
// route entries before giving up on a targeted update
|
|
155
|
+
await crawlFrom(ctx.entries(), {
|
|
156
|
+
graph,
|
|
157
|
+
projectRoot,
|
|
158
|
+
aliases: ctx.aliases,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
if (!graph.get(key)) {
|
|
162
|
+
logger.info("file outside the route graph, reloading:", filePath);
|
|
163
|
+
await fullReload(ctx);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// the edit may have added imports — pick them up before propagating
|
|
168
|
+
await crawlFrom([filePath], { graph, projectRoot, aliases: ctx.aliases });
|
|
169
|
+
|
|
170
|
+
const isClient = !isServerOnly(filePath);
|
|
171
|
+
let css: { hash: string; text: string } | null = null;
|
|
172
|
+
let compiled: string | null = null;
|
|
173
|
+
|
|
174
|
+
if (isClient) {
|
|
175
|
+
// compile the edited source before bumping anything: on a syntax error
|
|
176
|
+
// the overlay goes up and every previous version stays live, in the
|
|
177
|
+
// browser and in SSR alike. Never read the cache here — the whole point
|
|
178
|
+
// is to see what the developer just typed.
|
|
179
|
+
try {
|
|
180
|
+
const result = await compileForBrowser(filePath, {
|
|
181
|
+
projectRoot,
|
|
182
|
+
aliases: ctx.aliases,
|
|
183
|
+
graph,
|
|
184
|
+
});
|
|
185
|
+
compiled = result.js;
|
|
186
|
+
if (result.css) css = { hash: result.cssHash, text: result.css };
|
|
187
|
+
} catch (e: unknown) {
|
|
188
|
+
const message = errorMessage(e);
|
|
189
|
+
logger.error("compile error:", message);
|
|
190
|
+
hmr.error(message, extractLoc(e, filePath));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// bump this module and every importer up to the routes, invalidating the
|
|
196
|
+
// SSR loader's cache and every stamped browser URL along the way
|
|
197
|
+
graph.invalidate(key);
|
|
198
|
+
if (compiled !== null) {
|
|
199
|
+
// dep versions are untouched by the bump, so the output just compiled
|
|
200
|
+
// is exactly what this new version should serve
|
|
201
|
+
cacheDevModule(
|
|
202
|
+
filePath,
|
|
203
|
+
graph.get(key)?.version ?? 0,
|
|
204
|
+
projectRoot,
|
|
205
|
+
compiled,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const affected = graph.affectedRoutes(key);
|
|
210
|
+
if (affected.length === 0) {
|
|
211
|
+
logger.info("no route reaches this module, reloading:", filePath);
|
|
212
|
+
await fullReload(ctx);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const routeEntries: RouteEntryPayload[] = [];
|
|
217
|
+
const layoutEntries: LayoutEntryPayload[] = [];
|
|
218
|
+
let serverTouched = false;
|
|
219
|
+
let needsReload = false;
|
|
220
|
+
|
|
221
|
+
for (const route of affected) {
|
|
222
|
+
const modUrl = clientModulePath(route.filePath, projectRoot);
|
|
223
|
+
const version = graph.get(route.filePath)?.version ?? 0;
|
|
224
|
+
if (route.type === "page" || route.type === "simple") {
|
|
225
|
+
routeEntries.push({ pattern: route.path, modUrl, version });
|
|
226
|
+
} else if (route.type === "layout") {
|
|
227
|
+
layoutEntries.push({ path: route.path, modUrl, version });
|
|
228
|
+
} else if (route.type === "error") {
|
|
229
|
+
// error pages are never in the client route table — only a document
|
|
230
|
+
// request re-renders one
|
|
231
|
+
needsReload = true;
|
|
232
|
+
} else {
|
|
233
|
+
// +page.server / +layout.server / +server: nothing the client can
|
|
234
|
+
// swap, but the data behind the current page just changed
|
|
235
|
+
serverTouched = true;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (needsReload) {
|
|
240
|
+
await fullReload(ctx);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const payloads: object[] = [];
|
|
245
|
+
if (css) payloads.push({ kind: "css", ...css });
|
|
246
|
+
if (routeEntries.length)
|
|
247
|
+
payloads.push({ kind: "routes", entries: routeEntries });
|
|
248
|
+
if (layoutEntries.length)
|
|
249
|
+
payloads.push({ kind: "layouts", entries: layoutEntries });
|
|
250
|
+
if (serverTouched || affectsData(filePath, source))
|
|
251
|
+
payloads.push({ kind: "invalidate" });
|
|
252
|
+
|
|
253
|
+
const summary = affected.map((r) => `${r.type} ${r.path}`).join(", ");
|
|
254
|
+
logger.info(
|
|
255
|
+
`changed ${relative(projectRoot, filePath).replace(/\\/g, "/")} → ${summary}`,
|
|
256
|
+
);
|
|
257
|
+
hmr.batch(payloads);
|
|
258
|
+
// the prebuilt bundles still hold pre-edit code; refresh them so a manual
|
|
259
|
+
// reload agrees with the hot-swapped page
|
|
260
|
+
ctx.scheduleRebuild();
|
|
261
|
+
}
|
package/src/dev/loader.ts
CHANGED
|
@@ -1,47 +1,120 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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 { disposeModuleEffects } from "./effect-registry";
|
|
8
|
+
import type { DevGraph } from "./graph";
|
|
9
|
+
import { normalizePath } from "./paths";
|
|
10
|
+
import { isSourceFile, resolveProjectImport } from "./resolve";
|
|
11
|
+
|
|
12
|
+
export interface DevLoaderOptions {
|
|
13
|
+
/** GrimoireConfig.alias — prefix → project-relative directory. */
|
|
14
|
+
aliases?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Module loader for dev SSR.
|
|
19
|
+
*
|
|
20
|
+
* Bun caches every module it imports for the process lifetime, so a changed
|
|
21
|
+
* file can only be re-executed under a fresh path. Each edited module (and
|
|
22
|
+
* each importer of one, since the graph bumps them together) is recompiled
|
|
23
|
+
* into `.grimoire/dev-cache/<hash>_v<version>.js`, and its own imports are
|
|
24
|
+
* rewritten to the versioned files of its dependencies — otherwise a
|
|
25
|
+
* recompiled page would keep importing the cached copy of the component that
|
|
26
|
+
* was just edited.
|
|
27
|
+
*/
|
|
28
|
+
export function makeDevLoader(
|
|
29
|
+
graph: DevGraph,
|
|
30
|
+
projectRoot: string,
|
|
31
|
+
options: DevLoaderOptions = {},
|
|
32
|
+
) {
|
|
33
|
+
const cacheDir = join(projectRoot, ".grimoire/dev-cache");
|
|
34
|
+
const aliases = options.aliases ?? {};
|
|
35
|
+
// a previous session's cache cannot be trusted: same path, same version
|
|
36
|
+
// number, different source
|
|
37
|
+
rmSync(cacheDir, { recursive: true, force: true });
|
|
38
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
39
|
+
|
|
40
|
+
/** Cache files this process has already written, by path. */
|
|
41
|
+
const written = new Set<string>();
|
|
42
|
+
|
|
43
|
+
const materialize = async (filePath: string): Promise<string> => {
|
|
44
|
+
const version = graph.get(filePath)?.version ?? 0;
|
|
45
|
+
// untouched since startup: the SSR plugin handles the source directly
|
|
46
|
+
if (version === 0) return pathToFileURL(filePath).href;
|
|
47
|
+
|
|
48
|
+
const hash = createHash("md5")
|
|
49
|
+
.update(normalizePath(filePath))
|
|
50
|
+
.digest("hex")
|
|
51
|
+
.slice(0, 8);
|
|
52
|
+
const cachePath = join(cacheDir, `${hash}_v${version}.js`);
|
|
53
|
+
const href = pathToFileURL(cachePath).href;
|
|
54
|
+
// (file, version) is immutable within a session; import cycles reach
|
|
55
|
+
// the same deterministic path, and the outer call writes it
|
|
56
|
+
if (written.has(cachePath)) return href;
|
|
57
|
+
written.add(cachePath);
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const source = await Bun.file(filePath).text();
|
|
61
|
+
const babelResult = transformSync(source, {
|
|
62
|
+
configFile: false,
|
|
63
|
+
babelrc: false,
|
|
64
|
+
parserOpts: { plugins: ["typescript", "jsx"] },
|
|
65
|
+
plugins: [[sigilPlugin, { mode: "ssr", hash }]],
|
|
66
|
+
filename: filePath,
|
|
67
|
+
});
|
|
68
|
+
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
69
|
+
let compiled = transpiler.transformSync(babelResult?.code ?? "");
|
|
70
|
+
compiled = await rewriteSpecifiers(compiled, async (specifier) => {
|
|
71
|
+
const resolved = resolveProjectImport(
|
|
72
|
+
specifier,
|
|
73
|
+
filePath,
|
|
74
|
+
projectRoot,
|
|
75
|
+
aliases,
|
|
76
|
+
);
|
|
77
|
+
// externals keep their specifier: node_modules resolution walks
|
|
78
|
+
// up from the cache dir to the project root all the same
|
|
79
|
+
if (!resolved || !isSourceFile(resolved)) return null;
|
|
80
|
+
return await materialize(resolved);
|
|
81
|
+
});
|
|
82
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
83
|
+
writeFileSync(cachePath, compiled);
|
|
84
|
+
} catch (e) {
|
|
85
|
+
// let the next request retry instead of importing a half-written file
|
|
86
|
+
written.delete(cachePath);
|
|
87
|
+
throw e;
|
|
88
|
+
}
|
|
89
|
+
return href;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return async function devLoadModule(filePath: string): Promise<unknown> {
|
|
93
|
+
disposeModuleEffects(normalizePath(filePath));
|
|
94
|
+
return import(await materialize(filePath));
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
|
|
99
|
+
|
|
100
|
+
/** Replace every import specifier for which `resolve` returns a new one. */
|
|
101
|
+
async function rewriteSpecifiers(
|
|
102
|
+
code: string,
|
|
103
|
+
resolve: (specifier: string) => Promise<string | null>,
|
|
104
|
+
): Promise<string> {
|
|
105
|
+
const replacements = new Map<string, string>();
|
|
106
|
+
for (const match of code.matchAll(SPEC_RE)) {
|
|
107
|
+
const specifier = match[3]!;
|
|
108
|
+
if (replacements.has(specifier)) continue;
|
|
109
|
+
const next = await resolve(specifier);
|
|
110
|
+
if (next) replacements.set(specifier, next);
|
|
111
|
+
}
|
|
112
|
+
if (replacements.size === 0) return code;
|
|
113
|
+
return code.replace(
|
|
114
|
+
SPEC_RE,
|
|
115
|
+
(match, keyword: string, quote: string, specifier: string) => {
|
|
116
|
+
const next = replacements.get(specifier);
|
|
117
|
+
return next ? `${keyword}${quote}${next}${quote}` : match;
|
|
118
|
+
},
|
|
119
|
+
);
|
|
120
|
+
}
|
package/src/dev/paths.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { resolve } from "node:path";
|
|
2
|
-
|
|
3
|
-
export function normalizePath(p: string) {
|
|
4
|
-
let n = resolve(p).replace(/\\/g, "/");
|
|
5
|
-
if (process.platform === "win32") n = n.toLowerCase();
|
|
6
|
-
return n;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function keyFromUrl(pathname: string, prefix: string) {
|
|
10
|
-
// __grimoire__/m/src/lib/Example.tsx.js -> src/lib/Example.tsx
|
|
11
|
-
return decodeURIComponent(pathname.slice(prefix.length))
|
|
12
|
-
.replace(/\.js(\?.*)?$/, "")
|
|
13
|
-
.replace(/\\/g, "");
|
|
14
|
-
}
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
|
|
3
|
+
export function normalizePath(p: string) {
|
|
4
|
+
let n = resolve(p).replace(/\\/g, "/");
|
|
5
|
+
if (process.platform === "win32") n = n.toLowerCase();
|
|
6
|
+
return n;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function keyFromUrl(pathname: string, prefix: string) {
|
|
10
|
+
// __grimoire__/m/src/lib/Example.tsx.js -> src/lib/Example.tsx
|
|
11
|
+
return decodeURIComponent(pathname.slice(prefix.length))
|
|
12
|
+
.replace(/\.js(\?.*)?$/, "")
|
|
13
|
+
.replace(/\\/g, "");
|
|
14
|
+
}
|