@sigil-dev/grimoire 0.9.30 → 0.9.32

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.
@@ -1,1179 +1,1181 @@
1
- import { existsSync, mkdirSync } from "node:fs";
2
- import { isAbsolute, join } from "node:path";
3
- import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
4
- import {
5
- normalizeBase,
6
- outsideBaseMessage,
7
- setBase,
8
- stripBase,
9
- withBase,
10
- } from "../base";
11
- import { getDevModule } from "../dev/compile-module.ts";
12
- import { DevGraph } from "../dev/graph.ts";
13
- import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
14
- import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
15
- import { makeDevLoader } from "../dev/loader.ts";
16
- import { normalizePath } from "../dev/paths.ts";
17
- import { crawlFrom } from "../dev/scan.ts";
18
- import { startWatcher } from "../dev/watcher.ts";
19
- import { envModuleSource } from "../env/modules";
20
- import { assertRequiredEnv } from "../env/required";
21
- import { log } from "../logger/instance.ts";
22
- import { orderPlugins } from "../plugin-order";
23
- import { renderErrorPage, renderRoute } from "../rendering";
24
- import { registerSSRPlugin } from "../rendering/ssrPlugin";
25
- import { setServerTiming } from "../rendering/timing.ts";
26
- import { matchNotFound, matchRoute } from "../routing/router";
27
- import type { RouteTree } from "../routing/scanner";
28
- import { isErrorResult } from "../sentinels/error.ts";
29
- import { isFailResult } from "../sentinels/fail.ts";
30
- import { isRedirectResult } from "../sentinels/redirect.ts";
31
- import { setServerOnlyPlugins } from "../server-only";
32
- import type { GrimoireConfig, GrimoirePlugin, WsRouteHandler } from "../types";
33
- import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
34
- import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
35
- import { buildProject, rebuildClient } from "./build";
36
- import { clientAddressOf, trackClientAddress } from "./client-address";
37
- import { CLIENT_URL, clientDir } from "./client-dir";
38
- import { createCookies } from "./cookie-utils";
39
- import type {
40
- Handle,
41
- HandleError,
42
- HandleFetch,
43
- InitFunction,
44
- RequestEvent,
45
- ResolveFunction,
46
- } from "./hooks";
47
- import { shadowedRouteMessage, shadowedRoutes } from "./plugin-routes";
48
- import {
49
- collectServices,
50
- composeHandle,
51
- runDeserializeLocals,
52
- runHook,
53
- runRequestHooks,
54
- } from "./plugins";
55
- import { contentHash, splitHashedCss } from "./public-assets";
56
- import { RESERVED_EXPORTS } from "./reserved";
57
- import { projectAliases, resolverPlugin } from "./resolver";
58
- import { applyRewriters } from "./rewrite";
59
- import { preloadModules, startWarming, type Warmer } from "./warm.ts";
60
- import { withHeaders } from "./with-headers";
61
-
62
- /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
63
- const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
64
-
65
- const logger = log.scope("server");
66
-
67
- /**
68
- * Directories to watch in dev. `src` covers components and libs that pages
69
- * import; the routes directory is added separately when it lives outside it.
70
- */
71
- function watchRoots(projectRoot: string, routesDir: string): string[] {
72
- const src = join(projectRoot, "src");
73
- const roots = existsSync(src) ? [src] : [];
74
- const key = normalizePath(routesDir);
75
- if (
76
- !roots.some(
77
- (r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
78
- )
79
- )
80
- roots.push(routesDir);
81
- return roots;
82
- }
83
-
84
- /**
85
- * ETags by file, keyed on size and modification time. Hashing the content on
86
- * every request read the whole file and ran sha256 over it for each page
87
- * view; the answer only changes when the file does.
88
- */
89
- const etags = new Map<string, { stamp: string; etag: string }>();
90
-
91
- async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
92
- const key = file.name ?? "";
93
- const stamp = `${file.size}:${file.lastModified}`;
94
- const hit = etags.get(key);
95
- if (hit && hit.stamp === stamp) return hit.etag;
96
- const etag = `"${contentHash(await file.arrayBuffer())}"`;
97
- etags.set(key, { stamp, etag });
98
- return etag;
99
- }
100
-
101
- /**
102
- * Serve a file from public/, or the client bundle from .grimoire/client for
103
- * a /__grimoire__/ path, or return null when the path is neither.
104
- *
105
- * `immutable` is sent only for a URL that changes with its content, and
106
- * `must-revalidate` with an ETag for everything else. That distinction is
107
- * the whole point: telling a browser to cache a stylesheet for a year at a
108
- * URL that never changes means a deploy which edits the CSS is invisible to
109
- * anyone already holding it — the new HTML loads, and the old stylesheet
110
- * stays. Unconditional `immutable` was the bug here, and it was worse than
111
- * no caching at all, because it looked like it was working.
112
- *
113
- * Callers must not put user input in the pathname: this joins it onto
114
- * public/ directly.
115
- */
116
- async function servePublicAsset(
117
- pathname: string,
118
- search: string,
119
- ifNoneMatch: string | null,
120
- ): Promise<Response | null> {
121
- // Reject traversal before touching the filesystem.
122
- if (pathname.includes("..") || pathname.includes("\0")) return null;
123
- const locate = (p: string) =>
124
- Bun.file(
125
- p.startsWith(CLIENT_URL)
126
- ? join(clientDir(), p.slice(CLIENT_URL.length))
127
- : join(process.cwd(), "public", p),
128
- );
129
- let file = locate(pathname);
130
- // The hash is not in the file's name on disk: /style.<hash>.css is
131
- // public/style.css. A real file with that exact name wins.
132
- let stale = false;
133
- if (!(await file.exists())) {
134
- const hashed = pathname.startsWith(CLIENT_URL)
135
- ? null
136
- : splitHashedCss(pathname);
137
- if (!hashed) return null;
138
- file = locate(hashed.plain);
139
- if (!(await file.exists())) return null;
140
- // A page rendered before a deploy still asks for the old hash. Serve
141
- // the current content, but do not let the old URL pin it for a year.
142
- stale = contentHash(await file.arrayBuffer()) !== hashed.hash;
143
- }
144
-
145
- const headers: Record<string, string> = {};
146
- // Bun sets Content-Type from the extension, but be explicit for the
147
- // cases where a wrong guess is expensive: a stylesheet served as
148
- // text/plain is refused outright by the browser.
149
- const type = file.type;
150
- if (type) headers["Content-Type"] = type;
151
-
152
- const policy = stale ? "revalidate" : cacheControlFor(pathname, search);
153
- headers["Cache-Control"] = CACHE_CONTROL[policy];
154
- if (policy === "revalidate") {
155
- // The hash of the content, so a revalidation can be answered with
156
- // 304 instead of the whole file.
157
- const etag = await etagFor(file);
158
- headers["ETag"] = etag;
159
-
160
- // Compared here rather than left to Bun: a Bun.file body does not
161
- // honour If-None-Match on its own, so without this the conditional
162
- // request would get a 200 and re-download the whole file, and
163
- // max-age=0 would cost a full transfer on every single page load.
164
- //
165
- // Weak comparison, and a match on `*`: both are what the HTTP spec
166
- // asks for here. `W/` is stripped because these are strong ETags and
167
- // a client may legitimately send the weak form of one.
168
- const current = ifNoneMatch
169
- ?.split(",")
170
- .map((v) => v.trim())
171
- .some((v) => v === "*" || v.replace(/^W\//, "") === etag);
172
- if (current) {
173
- return new Response(null, { status: 304, headers });
174
- }
175
- }
176
- // Content-Length and Last-Modified come from the File; let Bun set them.
177
- if (file.lastModified) {
178
- headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
179
- }
180
- return new Response(file, { headers });
181
- }
182
- /**
183
- * Try to load hooks.server.ts from the project root.
184
- */
185
- async function loadHooks(projectRoot: string): Promise<{
186
- handle?: Handle;
187
- init?: InitFunction;
188
- handleError?: HandleError;
189
- handleFetch?: HandleFetch;
190
- }> {
191
- const hooksPath = `${projectRoot}/hooks.server.ts`;
192
- // no hooks file is fine; a hooks file that fails to load is not, and
193
- // swallowing that silently switched off auth and every other handle
194
- if (!existsSync(hooksPath)) return {};
195
- const mod = await import(hooksPath);
196
- return {
197
- handle: mod.handle,
198
- init: mod.init,
199
- handleError: mod.handleError,
200
- handleFetch: mod.handleFetch,
201
- };
202
- }
203
-
204
- let resolverRegistered = false;
205
- function registerServerResolver(config: GrimoireConfig): void {
206
- if (resolverRegistered) return;
207
- resolverRegistered = true;
208
- bunPlugin(resolverPlugin(config, "server"));
209
- }
210
-
211
- interface _WsInternalData {
212
- params: Record<string, string>;
213
- // always present at runtime — optional only to satisfy TypeScript;
214
- // upgrade block gates on mod.websocket before calling server.upgrade()
215
- __handler?: WsRouteHandler<any>;
216
- [key: string]: unknown;
217
- }
218
-
219
- /**
220
- * Everything a server is except the socket: the request handler, the
221
- * websocket handlers and the scanned route tree.
222
- *
223
- * Split from `createServer` so something that is not a listening server can
224
- * use the real pipeline — `sigil build` prerenders by sending requests
225
- * through `fetch`, which means `hooks.server.ts`, plugins and layouts run
226
- * exactly as they will in production. `createServer` is this plus a port.
227
- */
228
- export interface GrimoireApp {
229
- /** The full request pipeline: plugins, hooks, routing, rendering. */
230
- fetch(req: Request): Promise<Response>;
231
- /** Handlers to hand to `Bun.serve({ websocket })`. */
232
- websocket: ServerWebSocketHandlers;
233
- tree: RouteTree;
234
- /** `src/params/*.ts` matchers by name, for `[param=name]` routes. */
235
- matchers: Record<string, (value: string) => boolean>;
236
- config: GrimoireConfig;
237
- plugins: GrimoirePlugin[];
238
- /** Tell the app which server it runs in, so it can upgrade websockets. */
239
- bind(server: Server<any>): void;
240
- /**
241
- * Run `onStop` and let pending after-response work finish. Begins a
242
- * process-wide shutdown (`afterResponse()` rejects afterwards), so call it
243
- * once, when the process is done with the app.
244
- */
245
- close(
246
- reason?: "shutdown" | "restart",
247
- options?: { drainMs?: number },
248
- ): Promise<void>;
249
- /** Import every route module now, so the first visitor does not pay for it. */
250
- preload(): Promise<void>;
251
- }
252
-
253
- type ServerWebSocketHandlers = {
254
- open(ws: ServerWebSocket<any>): void;
255
- message(ws: ServerWebSocket<any>, data: string | Buffer): void;
256
- close(ws: ServerWebSocket<any>, code: number, reason?: string): void;
257
- drain(ws: ServerWebSocket<any>): void;
258
- };
259
-
260
- export async function createApp(
261
- config: GrimoireConfig = {},
262
- ): Promise<GrimoireApp> {
263
- // `after`/`before` decide the order, not the list; a config that did not
264
- // come through importConfig (a test, a script) is ordered here too.
265
- if (config.plugins)
266
- config = { ...config, plugins: orderPlugins(config.plugins) };
267
- setServerOnlyPlugins(config.plugins ?? []);
268
-
269
- // run config hooks
270
- let finalConfig = config;
271
- const earlyPlugins = config.plugins ?? [];
272
- for (const plugin of earlyPlugins) {
273
- finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
274
- }
275
-
276
- // Last word on `dev`: a plugin's config hook runs above and could have set
277
- // it. The worker does the same for the same reason.
278
- if (finalConfig._forceProduction)
279
- finalConfig = { ...finalConfig, dev: false };
280
-
281
- // Before the build, which can take a minute: a missing variable is the
282
- // cheapest thing to find out about and the most annoying to learn late.
283
- assertRequiredEnv(finalConfig);
284
-
285
- // A base that would 404 every asset is a startup error, not a mystery.
286
- const appBase = normalizeBase(finalConfig.base);
287
- setBase(appBase);
288
-
289
- const {
290
- port = 3000,
291
- host = "localhost",
292
- plugins = [],
293
- dev = false,
294
- routes = "src/routes",
295
- cspNonce,
296
- //biome-ignore lint: not implemented yet
297
- devEditor = "code",
298
- _skipBuild = false,
299
- } = finalConfig;
300
-
301
- let tree: any;
302
- if (!config._skipBuild) {
303
- const { result, tree: _tree } = await buildProject(finalConfig, plugins);
304
- if (!result.success) throw new Error("Grimoire: build failed");
305
- tree = _tree;
306
- } else {
307
- // worker — build already done by loom, just scan routes
308
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
309
- const { scanRoutes } = await import("../routing/scanner");
310
- tree = await scanRoutes(routesDir, process.cwd());
311
- }
312
-
313
- // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
314
- // WHAT ARE WE DOINGGGGGGGGG
315
- // $lib and config.alias in every server module, and the $env/* modules
316
- registerSSRPlugin(plugins, projectAliases(finalConfig));
317
- registerServerResolver(finalConfig);
318
-
319
- // Set by bind(); the handlers below only use it once a request arrives.
320
- let server: Server<any> | undefined;
321
-
322
- const graph = new DevGraph();
323
- const hmr = dev ? new HmrServer() : null;
324
-
325
- const aliases = finalConfig.alias ?? {};
326
- setServerTiming(finalConfig.serverTiming ?? dev);
327
-
328
- if (dev) {
329
- const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
330
- await ensureRuntimeBundle(process.cwd());
331
-
332
- // clean dev-modules cache from previous session
333
- const { rmSync, mkdirSync } = await import("node:fs");
334
- const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
335
- try {
336
- rmSync(devModulesDir, { recursive: true, force: true });
337
- } catch {}
338
- mkdirSync(devModulesDir, { recursive: true });
339
-
340
- const scanCtx = { graph, projectRoot: process.cwd(), aliases };
341
- const entryFiles = () => {
342
- const all = [
343
- ...tree.routes,
344
- ...tree.layouts,
345
- ...tree.servers,
346
- ...tree.errors,
347
- ];
348
- for (const rf of all) {
349
- graph.getOrCreate(rf.filePath, rf.filePath);
350
- graph.markRoute(rf.filePath, rf);
351
- }
352
- return all.map((rf) => rf.filePath);
353
- };
354
-
355
- // crawl the whole import graph, not just each route's direct imports:
356
- // an edit is traced back to the routes that render it through however
357
- // many component hops lie between
358
- await crawlFrom(entryFiles(), scanCtx);
359
-
360
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
361
-
362
- // one rebuild at a time; saves that land during a build fold into one
363
- // follow-up pass instead of queueing a Bun.build each
364
- let rebuilding: Promise<void> | null = null;
365
- let rebuildQueued = false;
366
- const runRebuild = (): Promise<void> => {
367
- if (rebuilding) {
368
- rebuildQueued = true;
369
- return rebuilding;
370
- }
371
- rebuilding = (async () => {
372
- do {
373
- rebuildQueued = false;
374
- const { result, tree: rescanned } = await rebuildClient(
375
- finalConfig,
376
- plugins,
377
- );
378
- if (!result.success) {
379
- logger.error("client rebuild failed:", result.errors.join("\n"));
380
- break;
381
- }
382
- // adopt the rescanned tree so routes added since startup match
383
- tree = rescanned;
384
- await crawlFrom(entryFiles(), scanCtx);
385
- } while (rebuildQueued);
386
- })().finally(() => {
387
- rebuilding = null;
388
- });
389
- return rebuilding;
390
- };
391
-
392
- const devCtx: DevContext = {
393
- graph,
394
- hmr: hmr!,
395
- projectRoot: process.cwd(),
396
- aliases,
397
- entries: entryFiles,
398
- rebuild: runRebuild,
399
- scheduleRebuild: () => {
400
- runRebuild().catch((e: unknown) =>
401
- logger.error("client rebuild failed:", e),
402
- );
403
- },
404
- };
405
-
406
- startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
407
- handleChange(f, devCtx),
408
- );
409
- }
410
-
411
- const loader = dev
412
- ? makeDevLoader(graph, process.cwd(), { aliases })
413
- : (p: string) => import(p);
414
-
415
- // [param=matcher] validation — load src/params/*.ts once at startup
416
- const paramMatcherFns: Record<string, (value: string) => boolean> = {};
417
- for (const pm of tree.paramMatcherFiles ?? []) {
418
- try {
419
- const mod = await loader(pm.filePath);
420
- if (typeof mod.match === "function") {
421
- paramMatcherFns[pm.name] = mod.match;
422
- }
423
- } catch (e) {
424
- logger.warn(`failed to load param matcher "${pm.name}":`, e);
425
- }
426
- }
427
- for (const s of shadowedRoutes(plugins, tree, paramMatcherFns)) {
428
- logger.warn(shadowedRouteMessage(s));
429
- }
430
-
431
- // Load hooks.server.ts
432
- const {
433
- handle: appHandle,
434
- init: hooksInit,
435
- handleError: hooksHandleError,
436
- handleFetch: hooksHandleFetch,
437
- } = await loadHooks(process.cwd());
438
-
439
- const hooksHandle = composeHandle(plugins, appHandle);
440
-
441
- // Resolved once at startup, not per request: services() may open a pool,
442
- // and the object is immutable for the process lifetime, so building it
443
- // inside handleRequest would open a connection per visitor.
444
- //
445
- // Before init(), so hooks.server.ts can use what plugins opened — a
446
- // database for a warm-up query or a migration check is the usual case,
447
- // and running init first meant it could only fail.
448
- // The same hook the coordinator fires, for every process that serves
449
- // requests. It used to run only in the coordinator, so `sigil dev` and a
450
- // single-process `sigil start` never gave plugins their moment to look at
451
- // each other.
452
- await runHook(plugins, "onPluginsResolved", {
453
- mode: dev ? "development" : "production",
454
- plugins: new Map(plugins.map((p) => [p.name, p])),
455
- logger: log.scope("plugins"),
456
- });
457
-
458
- const services = await collectServices(plugins);
459
-
460
- // Run init hook if present
461
- await hooksInit?.();
462
-
463
- // onRouteRender forces the whole response to be buffered into a string,
464
- // which silently disables streaming for every route a plugin touches. That
465
- // is a real cost and an invisible one, so say it once at boot rather than
466
- // letting someone discover it as "streaming stopped working".
467
- for (const p of plugins) {
468
- if (p.onRouteRender) {
469
- logger.warn(
470
- `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. Use rewriteHtml(rewriter) to change the HTML while it streams, or onRequest to change headers.`,
471
- );
472
- }
473
- }
474
-
475
- async function handleRequest(req: Request) {
476
- // Only the coordinator is trusted to say who the user is. A server that
477
- // answers the public directly ignores the header, so nobody can send
478
- // their own `locals` to it.
479
- const rawLocals = finalConfig._behindCoordinator
480
- ? req.headers.get("X-Grimoire-Locals")
481
- : null;
482
- const locals: App.Locals = rawLocals
483
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
484
- : {};
485
- // Plugin services sit under the request's own locals: what the app
486
- // set (a session, a user) always wins over what a plugin declared,
487
- // so a plugin cannot clobber auth by defining a common key.
488
- for (const [key, value] of Object.entries(services)) {
489
- if (!(key in locals)) locals[key] = value;
490
- }
491
- const url = new URL(req.url);
492
-
493
- if (dev && url.pathname === "/__grimoire__/hmr") {
494
- //@ts-expect-error holy shut up
495
- if (server?.upgrade(req, { data: { __hmrClient: true } })) {
496
- return undefined as unknown as Response;
497
- }
498
- return new Response("Upgrade Required", { status: 426 });
499
- }
500
- if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
501
- return new Response(HMR_CLIENT_SOURCE, {
502
- headers: { "Content-Type": "application/javascript" },
503
- });
504
- }
505
- if (dev && url.pathname === "/__grimoire__/open") {
506
- const file = url.searchParams.get("file") ?? "";
507
- const line = url.searchParams.get("line") ?? "1";
508
- const col = url.searchParams.get("col") ?? "1";
509
- const editor = finalConfig.devEditor ?? "code";
510
- //@ts-expect-error Bun spawn has werird types just shut up
511
- Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
512
- return new Response(null, { status: 204 });
513
- }
514
- if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
515
- const depName = decodeURIComponent(
516
- url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
517
- );
518
-
519
- // grimoire shim
520
- if (depName.includes("@sigil-dev__grimoire")) {
521
- return Response.redirect("/__grimoire__/grimoire-client.js", 302);
522
- }
523
-
524
- // convert URL-safe name back to package name
525
- // @codex__shared → @codex/shared
526
- const pkgName = depName.startsWith("@")
527
- ? depName.replace("__", "/")
528
- : depName;
529
-
530
- const depsDir = join(process.cwd(), ".grimoire/deps");
531
- mkdirSync(depsDir, { recursive: true });
532
- const outFile = join(depsDir, `${depName}.js`);
533
-
534
- if (!(await Bun.file(outFile).exists())) {
535
- logger.debug("bundling dep:", pkgName);
536
- try {
537
- const entry = Bun.resolveSync(pkgName, process.cwd());
538
- const result = await Bun.build({
539
- entrypoints: [entry],
540
- outdir: depsDir,
541
- naming: `${depName}.js`,
542
- target: "browser",
543
- format: "esm",
544
- minify: false,
545
- external: ["@sigil-dev/runtime"],
546
- });
547
- if (!result.success) {
548
- logger.error("dep bundle failed:", pkgName, result.logs);
549
- return new Response(
550
- `throw new Error("failed to bundle dep: ${pkgName}")`,
551
- { headers: { "Content-Type": "application/javascript" } },
552
- );
553
- }
554
- logger.debug("bundled dep:", pkgName);
555
- } catch (e: any) {
556
- return new Response(
557
- `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
558
- { headers: { "Content-Type": "application/javascript" } },
559
- );
560
- }
561
- }
562
-
563
- return new Response(Bun.file(outFile), {
564
- headers: {
565
- "Content-Type": "application/javascript",
566
- "Cache-Control": "no-store",
567
- },
568
- });
569
- }
570
-
571
- if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
572
- const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
573
- let js: string;
574
- try {
575
- js = envModuleSource(specifier, "browser");
576
- } catch (e: unknown) {
577
- const message = e instanceof Error ? e.message : String(e);
578
- js = `throw new Error(${JSON.stringify(message)})`;
579
- }
580
- return new Response(js, {
581
- headers: {
582
- "Content-Type": "application/javascript",
583
- "Cache-Control": "no-store",
584
- },
585
- });
586
- }
587
-
588
- if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
589
- const clientPath = decodeURIComponent(
590
- url.pathname.slice("/__grimoire__/m/".length),
591
- );
592
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
593
- try {
594
- // compiled at the module's current graph version, which is what
595
- // the `?v=` in the URL was derived from
596
- const { js } = await getDevModule(absPath, {
597
- projectRoot: process.cwd(),
598
- aliases,
599
- graph,
600
- });
601
- return new Response(js, {
602
- headers: {
603
- "Content-Type": "application/javascript",
604
- "Cache-Control": "no-store",
605
- },
606
- });
607
- } catch (e: unknown) {
608
- const message = e instanceof Error ? e.message : String(e);
609
- return new Response(`throw new Error(${JSON.stringify(message)})`, {
610
- headers: { "Content-Type": "application/javascript" },
611
- });
612
- }
613
- }
614
-
615
- // Static files are served BEFORE the plugin pipeline. A CSS file or
616
- // an image has nothing to do with a plugin's onRequest hook, and
617
- // running them through it costs a hook round-trip plus a stat on
618
- // every asset request.
619
- //
620
- // Caching rule, decided per asset by servePublicAsset: the document
621
- // is never cached, a content-addressed URL is immutable, and
622
- // anything else revalidates against an ETag.
623
- const staticAsset = await servePublicAsset(
624
- url.pathname,
625
- url.search,
626
- req.headers.get("if-none-match"),
627
- );
628
- if (staticAsset) return staticAsset;
629
-
630
- return runRequestHooks(plugins, req, async () => {
631
- const HTTP_METHODS = [
632
- "GET",
633
- "POST",
634
- "PUT",
635
- "PATCH",
636
- "DELETE",
637
- "HEAD",
638
- "OPTIONS",
639
- ] as const;
640
-
641
- // Build event BEFORE matching — handle() runs pre-match like SvelteKit
642
- trackClientAddress(req, server);
643
- const cookieHeader = req.headers.get("cookie") ?? "";
644
- const cookies = createCookies(cookieHeader);
645
- const setHeadersMap: Record<string, string> = {};
646
-
647
- const event: RequestEvent = {
648
- request: req,
649
- url,
650
- params: {},
651
- locals,
652
- cookies,
653
- route: { id: "" },
654
- fetch: globalThis.fetch,
655
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
656
- getClientAddress: () => clientAddressOf(req),
657
- };
658
-
659
- if (hooksHandleFetch) {
660
- event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
661
- const r = new Request(reqInfo, init);
662
- return Promise.resolve(
663
- hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
664
- );
665
- };
666
- }
667
- const patchedFetch: typeof fetch = (input, init) => {
668
- const resolved =
669
- typeof input === "string" && input.startsWith("/")
670
- ? new URL(input, url.origin).toString()
671
- : input;
672
- return globalThis.fetch(resolved as any, init);
673
- };
674
- const resolve: ResolveFunction = async (evt) => {
675
- // matching happens here — after handle() has run
676
- let matched = matchRoute(tree, evt.url, paramMatcherFns);
677
- if (!matched) {
678
- // the nearest +error.tsx inside the layouts that cover the
679
- // address, like a page whose load throws error(404)
680
- return renderRoute(
681
- matchNotFound(tree, evt.url),
682
- evt.request,
683
- tree.errors,
684
- loader,
685
- evt.locals,
686
- plugins,
687
- cspNonce,
688
- dev,
689
- patchedFetch,
690
- );
691
- }
692
-
693
- // patch event with match results so handle() epilogue can read them
694
- evt.params = matched.params;
695
- evt.route = { id: matched.route.path };
696
-
697
- // API routes (+server.ts)
698
- if (matched.route.type === "server") {
699
- const mod = await loader(matched.route.filePath);
700
-
701
- const isWsUpgrade =
702
- evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
703
- if (isWsUpgrade && mod.websocket) {
704
- let extraData: Record<string, unknown> = {};
705
- if (mod.upgrade) {
706
- try {
707
- const result = await mod.upgrade({
708
- request: evt.request,
709
- params: matched.params,
710
- url: evt.url,
711
- locals: evt.locals,
712
- });
713
- if (result && typeof result === "object") extraData = result;
714
- } catch {
715
- return new Response("Upgrade Required", { status: 426 });
716
- }
717
- }
718
- const wsData: _WsInternalData = {
719
- params: matched.params,
720
- __handler: mod.websocket,
721
- ...extraData,
722
- };
723
- //@ts-expect-error i dont know what you are talking about please
724
- if (server?.upgrade(req, { data: wsData })) {
725
- return undefined as unknown as Response;
726
- }
727
- return new Response("Upgrade Required", { status: 426 });
728
- }
729
-
730
- const handler = mod[evt.request.method];
731
- if (handler) {
732
- try {
733
- return await handler({
734
- request: evt.request,
735
- params: matched.params,
736
- url: evt.url,
737
- locals: evt.locals,
738
- fetch: patchedFetch,
739
- cookies,
740
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
741
- getClientAddress: () => clientAddressOf(evt.request),
742
- });
743
- } catch (e) {
744
- // `throw redirect(303, "/login")` works here as in an action
745
- if (isRedirectResult(e)) {
746
- return new Response(null, {
747
- status: e.status,
748
- headers: { Location: e.location },
749
- });
750
- }
751
- throw e;
752
- }
753
- }
754
- // no handler for this method: a page at the same URL (say a
755
- // chat page next to its WebSocket endpoint) takes the request
756
- const page = matchRoute(
757
- { ...tree, servers: [] },
758
- evt.url,
759
- paramMatcherFns,
760
- );
761
- if (!page) {
762
- return new Response("Method Not Allowed", { status: 405 });
763
- }
764
- matched = page;
765
- evt.params = page.params;
766
- evt.route = { id: page.route.path };
767
- }
768
-
769
- // form actions (+page.server.ts)
770
- if (
771
- matched.pageServer &&
772
- HTTP_METHODS.includes(evt.request.method as any)
773
- ) {
774
- const mod = await loader(matched.pageServer.filePath);
775
-
776
- // named actions: ?/create dispatches export `create`. Only for
777
- // non-GET requests: a GET must never run an action, or any link
778
- // or <img> on another site could trigger one with the visitor's
779
- // cookies and no CSRF check (GET skips it)
780
- const isRead =
781
- evt.request.method === "GET" || evt.request.method === "HEAD";
782
- const actionName = isRead
783
- ? undefined
784
- : [...evt.url.searchParams.keys()]
785
- .find((k) => k.startsWith("/"))
786
- ?.slice(1);
787
- // every other function export is callable by name, but the
788
- // module's own hooks are not actions
789
- const reserved =
790
- actionName !== undefined && RESERVED_EXPORTS.has(actionName);
791
- // reads render the page; an exported GET is not an action either
792
- const handler =
793
- reserved || isRead
794
- ? undefined
795
- : actionName
796
- ? mod[actionName]
797
- : mod[evt.request.method];
798
- if (actionName && typeof handler !== "function") {
799
- return new Response("Not Found", { status: 404 });
800
- }
801
-
802
- if (mod.csrf !== false && !isRead) {
803
- const cookieToken = cookies.get("_csrf");
804
- const formData = await evt.request
805
- .clone()
806
- .formData()
807
- .catch(() => null);
808
- const bodyToken = formData?.get("_csrf");
809
- if (!cookieToken || cookieToken !== String(bodyToken)) {
810
- return new Response("Forbidden", { status: 403 });
811
- }
812
- }
813
- // enhance() submits with fetch, which follows a 303 on its own
814
- // and can't read where it went; it asks for the outcome as JSON
815
- // instead and navigates itself
816
- const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
817
- if (handler) {
818
- let result: any;
819
- try {
820
- result = await handler({
821
- request: evt.request,
822
- params: matched.params,
823
- url: evt.url,
824
- locals: evt.locals,
825
- fetch: patchedFetch,
826
- cookies,
827
- getClientAddress: () => clientAddressOf(evt.request),
828
- });
829
- } catch (e) {
830
- // A thrown Response is the reply, like a returned one: it
831
- // used to fall through to the 500 path and be swallowed.
832
- if (e instanceof Response) return e;
833
- if (isRedirectResult(e)) {
834
- if (enhanced) {
835
- return Response.json({
836
- type: "redirect",
837
- status: e.status,
838
- location: e.location,
839
- });
840
- }
841
- return new Response(null, {
842
- status: e.status,
843
- headers: { Location: e.location },
844
- });
845
- }
846
- if (isErrorResult(e)) {
847
- const isApi =
848
- enhanced ||
849
- evt.request.headers
850
- .get("accept")
851
- ?.includes("application/json");
852
- if (isApi) {
853
- return Response.json(
854
- { error: true, status: e.status, message: e.message },
855
- { status: e.status },
856
- );
857
- }
858
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
859
- // no layoutPairs here: layout data comes from the load
860
- // pipeline in renderRoute, which a form action bypasses —
861
- // wrapping layouts without their data would crash them
862
- return (
863
- (await renderErrorPage(
864
- tree.errors,
865
- evt.url.pathname,
866
- e.status,
867
- e.message,
868
- e,
869
- loader,
870
- { params: matched.params, nonceAttr, dev },
871
- )) ??
872
- new Response(e.message, { status: e.status, headers: TEXT })
873
- );
874
- }
875
- throw e;
876
- }
877
-
878
- if (result instanceof Response) return result;
879
-
880
- if (isFailResult(result)) {
881
- if (enhanced) {
882
- return Response.json(
883
- { fail: true, status: result.status, data: result.data },
884
- { status: result.status },
885
- );
886
- }
887
- // a plain form post (no JavaScript): show the page again,
888
- // with the failure as its `form` prop
889
- return renderRoute(
890
- matched,
891
- evt.request,
892
- tree.errors,
893
- loader,
894
- evt.locals,
895
- plugins,
896
- cspNonce,
897
- dev,
898
- patchedFetch,
899
- { status: result.status, data: result.data },
900
- );
901
- }
902
-
903
- const redirectTo =
904
- result?.redirect ??
905
- evt.request.headers.get("referer") ??
906
- withBase("/");
907
- if (enhanced) {
908
- return Response.json({
909
- type: "success",
910
- location: redirectTo,
911
- data: result ?? null,
912
- });
913
- }
914
- return new Response(null, {
915
- status: 303,
916
- headers: { Location: redirectTo },
917
- });
918
- }
919
- if (!actionName && !isRead) {
920
- return new Response("Method Not Allowed", { status: 405 });
921
- }
922
- }
923
-
924
- // page routes
925
- const response = await renderRoute(
926
- matched,
927
- evt.request,
928
- tree.errors,
929
- loader,
930
- evt.locals,
931
- plugins,
932
- cspNonce,
933
- dev,
934
- patchedFetch,
935
- );
936
-
937
- if (evt.request.headers.get("x-grimoire-navigate") === "1") {
938
- return response;
939
- }
940
-
941
- // Streaming-safe rewrites first, then the buffered legacy hook.
942
- const rewritten = await applyRewriters(response, plugins, {
943
- route: matched.route,
944
- request: evt.request,
945
- params: matched.params,
946
- data: undefined,
947
- });
948
- const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
949
- if (!hasRenderPlugins) return rewritten;
950
- let html = await rewritten.text();
951
- for (const plugin of plugins) {
952
- html =
953
- (await plugin.onRouteRender?.(html, {
954
- route: matched.route,
955
- request: evt.request,
956
- params: matched.params,
957
- data: undefined,
958
- })) ?? html;
959
- }
960
- // Carry the original headers over. Rebuilding with a fixed set
961
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
962
- // plugin silently broke form actions and cache correctness.
963
- const headers = new Headers(rewritten.headers);
964
- headers.set("Content-Type", "text/html");
965
- return new Response(html, {
966
- status: rewritten.status,
967
- statusText: rewritten.statusText,
968
- headers,
969
- });
970
- };
971
-
972
- let response: Response;
973
- try {
974
- if (!hooksHandle) {
975
- response = await resolve(event);
976
- } else {
977
- response = await hooksHandle({ event, resolve });
978
- }
979
- } catch (err) {
980
- logger.error(
981
- `${event.request.method} ${event.url.pathname} failed:`,
982
- err,
983
- );
984
- await hooksHandleError?.({
985
- error: err,
986
- event,
987
- status: 500,
988
- message: "Internal Server Error",
989
- });
990
- // an unexpected error gets the nearest +error.tsx too, with a
991
- // generic message: details stay in the log
992
- try {
993
- const page = await renderErrorPage(
994
- tree.errors,
995
- event.url.pathname,
996
- 500,
997
- "Internal Server Error",
998
- process.env.NODE_ENV === "production" ? null : err,
999
- loader,
1000
- { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
1001
- );
1002
- if (page) return page;
1003
- } catch (pageErr) {
1004
- logger.error("+error.tsx failed while rendering an error:", pageErr);
1005
- }
1006
- const errorHtmlPath = `${process.cwd()}/error.html`;
1007
- try {
1008
- const errorFile = Bun.file(errorHtmlPath);
1009
- if (await errorFile.exists()) {
1010
- return new Response(errorFile, {
1011
- status: 500,
1012
- headers: { "Content-Type": "text/html" },
1013
- });
1014
- }
1015
- } catch {}
1016
- const message =
1017
- process.env.NODE_ENV === "production"
1018
- ? "Internal Server Error"
1019
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
1020
- return new Response(message, { status: 500, headers: TEXT });
1021
- }
1022
-
1023
- const setCookieHeaders = cookies.toHeaders();
1024
- if (
1025
- !response ||
1026
- (setCookieHeaders.length === 0 &&
1027
- Object.keys(setHeadersMap).length === 0)
1028
- ) {
1029
- return response;
1030
- }
1031
- return withHeaders(
1032
- response,
1033
- Object.entries(setHeadersMap),
1034
- setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
1035
- );
1036
- });
1037
- }
1038
-
1039
- const websocket: ServerWebSocketHandlers = {
1040
- open(ws: ServerWebSocket<any>) {
1041
- if (ws.data.__hmrClient) {
1042
- hmr?.addClient(ws);
1043
- return;
1044
- }
1045
- (ws.data as _WsInternalData).__handler?.open?.(ws);
1046
- },
1047
- message(ws: ServerWebSocket<any>, data: string | Buffer) {
1048
- if (ws.data.__hmrClient) return;
1049
- (ws.data as _WsInternalData).__handler?.message?.(ws, data);
1050
- },
1051
- close(ws: ServerWebSocket<any>, code: number, reason?: string) {
1052
- if (ws.data.__hmrClient) {
1053
- hmr?.removeClient(ws);
1054
- return;
1055
- }
1056
- (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
1057
- },
1058
- drain(ws: ServerWebSocket<any>) {
1059
- if (ws.data.__hmrClient) return;
1060
- (ws.data as _WsInternalData).__handler?.drain?.(ws);
1061
- },
1062
- };
1063
-
1064
- // Wrapping is what makes afterResponse() mean "after the response",
1065
- // including for streaming responses: the tasks fire when the body
1066
- // finishes, not when the handler returns.
1067
- const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
1068
-
1069
- // Under a base, the request is stripped to a route path once, here, so
1070
- // nothing past this point has to know about it.
1071
- const fetchUnderBase = (req: Request): Promise<Response> | Response => {
1072
- if (!appBase) return fetchHandler(req);
1073
- const url = new URL(req.url);
1074
- if (url.pathname === appBase) {
1075
- return new Response(null, {
1076
- status: 308,
1077
- headers: { Location: `${appBase}/${url.search}` },
1078
- });
1079
- }
1080
- const route = stripBase(url.pathname, appBase);
1081
- if (route === null) {
1082
- // dev modules import each other root-relative
1083
- if (dev && url.pathname.startsWith("/__grimoire__/")) {
1084
- return fetchHandler(req);
1085
- }
1086
- return new Response(outsideBaseMessage(url.pathname, appBase, dev), {
1087
- status: 404,
1088
- headers: { "Content-Type": "text/plain" },
1089
- });
1090
- }
1091
- url.pathname = route;
1092
- return fetchHandler(new Request(url, req));
1093
- };
1094
-
1095
- const preload = async () => {
1096
- if (dev || finalConfig.warm?.preload === false) return;
1097
- const files = [
1098
- ...tree.routes,
1099
- ...tree.layouts,
1100
- ...tree.servers,
1101
- ...tree.errors,
1102
- ].map((rf: { filePath: string }) => rf.filePath);
1103
- const t0 = performance.now();
1104
- const loaded = await preloadModules(files, loader, (msg, err) =>
1105
- logger.warn(msg, err),
1106
- );
1107
- logger.info(
1108
- `preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
1109
- );
1110
- };
1111
-
1112
- return {
1113
- fetch: fetchUnderBase,
1114
- websocket,
1115
- tree,
1116
- matchers: paramMatcherFns,
1117
- config: finalConfig,
1118
- plugins,
1119
- bind(s) {
1120
- server = s;
1121
- },
1122
- preload,
1123
- async close(reason = "shutdown", options) {
1124
- await runHook(plugins, "onStop", reason);
1125
- // Drain before stopping, so a task already registered for a response
1126
- // that has been sent gets to finish rather than being killed with the
1127
- // process. Bounded: a hung task must not block a deploy forever.
1128
- await drainAfterResponse(options?.drainMs);
1129
- },
1130
- };
1131
- }
1132
-
1133
- export async function createServer(config: GrimoireConfig = {}) {
1134
- const app = await createApp(config);
1135
- const { plugins, config: finalConfig } = app;
1136
- const { port = 3000, host = "localhost", dev = false } = finalConfig;
1137
-
1138
- // Before the port opens, so the first visitor never pays for compiling a
1139
- // route: a worker only reports ready once this has finished.
1140
- await app.preload();
1141
-
1142
- const server = Bun.serve({
1143
- port,
1144
- hostname: host,
1145
- fetch: app.fetch,
1146
- websocket: app.websocket,
1147
- });
1148
- app.bind(server);
1149
-
1150
- const warmConfig = finalConfig.warm;
1151
- let warmer: Warmer | null = null;
1152
- if (!dev && warmConfig?.paths?.length) {
1153
- warmer = startWarming({
1154
- paths: warmConfig.paths,
1155
- every: warmConfig.every,
1156
- origin: `http://${host}:${server.port}`,
1157
- headers: finalConfig._warmHeaders,
1158
- handle: async (req) => app.fetch(req),
1159
- log: (msg) => logger.info(msg),
1160
- });
1161
- }
1162
-
1163
- let stopping = false;
1164
- const handleShutdown = async () => {
1165
- if (stopping) return;
1166
- stopping = true;
1167
- warmer?.stop();
1168
- await app.close("shutdown");
1169
- // stop(true), not stop(): the graceful form waits for open connections,
1170
- // and a dev HMR websocket never closes on its own, so shutdown hangs.
1171
- server.stop(true);
1172
- process.exit(0);
1173
- };
1174
- process.on("SIGINT", handleShutdown);
1175
- process.on("SIGTERM", handleShutdown);
1176
-
1177
- await runHook(plugins, "onStart", server);
1178
- return server;
1179
- }
1
+ import { existsSync, mkdirSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
4
+ import {
5
+ normalizeBase,
6
+ outsideBaseMessage,
7
+ setBase,
8
+ stripBase,
9
+ withBase,
10
+ } from "../base";
11
+ import { getDevModule } from "../dev/compile-module.ts";
12
+ import { DevGraph } from "../dev/graph.ts";
13
+ import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
14
+ import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
15
+ import { makeDevLoader } from "../dev/loader.ts";
16
+ import { normalizePath } from "../dev/paths.ts";
17
+ import { crawlFrom } from "../dev/scan.ts";
18
+ import { startWatcher } from "../dev/watcher.ts";
19
+ import { envModuleSource } from "../env/modules";
20
+ import { assertRequiredEnv } from "../env/required";
21
+ import { log } from "../logger/instance.ts";
22
+ import { orderPlugins } from "../plugin-order";
23
+ import { renderErrorPage, renderRoute } from "../rendering";
24
+ import { registerSSRPlugin } from "../rendering/ssrPlugin";
25
+ import { setServerTiming } from "../rendering/timing.ts";
26
+ import { matchNotFound, matchRoute } from "../routing/router";
27
+ import type { RouteTree } from "../routing/scanner";
28
+ import { isErrorResult } from "../sentinels/error.ts";
29
+ import { isFailResult } from "../sentinels/fail.ts";
30
+ import { isRedirectResult } from "../sentinels/redirect.ts";
31
+ import { setServerOnlyPlugins } from "../server-only";
32
+ import type { GrimoireConfig, GrimoirePlugin, WsRouteHandler } from "../types";
33
+ import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
34
+ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
35
+ import { buildProject, rebuildClient } from "./build";
36
+ import { clientAddressOf, trackClientAddress } from "./client-address";
37
+ import { CLIENT_URL, clientDir } from "./client-dir";
38
+ import { createCookies } from "./cookie-utils";
39
+ import type {
40
+ Handle,
41
+ HandleError,
42
+ HandleFetch,
43
+ InitFunction,
44
+ RequestEvent,
45
+ ResolveFunction,
46
+ } from "./hooks";
47
+ import { shadowedRouteMessage, shadowedRoutes } from "./plugin-routes";
48
+ import {
49
+ collectServices,
50
+ composeHandle,
51
+ runDeserializeLocals,
52
+ runHook,
53
+ runRequestHooks,
54
+ } from "./plugins";
55
+ import { contentHash, splitHashedCss } from "./public-assets";
56
+ import { RESERVED_EXPORTS } from "./reserved";
57
+ import { projectAliases, resolverPlugin } from "./resolver";
58
+ import { applyRewriters } from "./rewrite";
59
+ import { preloadModules, startWarming, type Warmer } from "./warm.ts";
60
+ import { withHeaders } from "./with-headers";
61
+
62
+ /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
63
+ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
64
+
65
+ const logger = log.scope("server");
66
+
67
+ /**
68
+ * Directories to watch in dev. `src` covers components and libs that pages
69
+ * import; the routes directory is added separately when it lives outside it.
70
+ */
71
+ function watchRoots(projectRoot: string, routesDir: string): string[] {
72
+ const src = join(projectRoot, "src");
73
+ const roots = existsSync(src) ? [src] : [];
74
+ const key = normalizePath(routesDir);
75
+ if (
76
+ !roots.some(
77
+ (r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
78
+ )
79
+ )
80
+ roots.push(routesDir);
81
+ return roots;
82
+ }
83
+
84
+ /**
85
+ * ETags by file, keyed on size and modification time. Hashing the content on
86
+ * every request read the whole file and ran sha256 over it for each page
87
+ * view; the answer only changes when the file does.
88
+ */
89
+ const etags = new Map<string, { stamp: string; etag: string }>();
90
+
91
+ async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
92
+ const key = file.name ?? "";
93
+ const stamp = `${file.size}:${file.lastModified}`;
94
+ const hit = etags.get(key);
95
+ if (hit && hit.stamp === stamp) return hit.etag;
96
+ const etag = `"${contentHash(await file.arrayBuffer())}"`;
97
+ etags.set(key, { stamp, etag });
98
+ return etag;
99
+ }
100
+
101
+ /**
102
+ * Serve a file from public/, or the client bundle from .grimoire/client for
103
+ * a /__grimoire__/ path, or return null when the path is neither.
104
+ *
105
+ * `immutable` is sent only for a URL that changes with its content, and
106
+ * `must-revalidate` with an ETag for everything else. That distinction is
107
+ * the whole point: telling a browser to cache a stylesheet for a year at a
108
+ * URL that never changes means a deploy which edits the CSS is invisible to
109
+ * anyone already holding it — the new HTML loads, and the old stylesheet
110
+ * stays. Unconditional `immutable` was the bug here, and it was worse than
111
+ * no caching at all, because it looked like it was working.
112
+ *
113
+ * Callers must not put user input in the pathname: this joins it onto
114
+ * public/ directly.
115
+ */
116
+ async function servePublicAsset(
117
+ pathname: string,
118
+ search: string,
119
+ ifNoneMatch: string | null,
120
+ ): Promise<Response | null> {
121
+ // Reject traversal before touching the filesystem.
122
+ if (pathname.includes("..") || pathname.includes("\0")) return null;
123
+ const locate = (p: string) =>
124
+ Bun.file(
125
+ p.startsWith(CLIENT_URL)
126
+ ? join(clientDir(), p.slice(CLIENT_URL.length))
127
+ : join(process.cwd(), "public", p),
128
+ );
129
+ let file = locate(pathname);
130
+ // The hash is not in the file's name on disk: /style.<hash>.css is
131
+ // public/style.css. A real file with that exact name wins.
132
+ let stale = false;
133
+ if (!(await file.exists())) {
134
+ const hashed = pathname.startsWith(CLIENT_URL)
135
+ ? null
136
+ : splitHashedCss(pathname);
137
+ if (!hashed) return null;
138
+ file = locate(hashed.plain);
139
+ if (!(await file.exists())) return null;
140
+ // A page rendered before a deploy still asks for the old hash. Serve
141
+ // the current content, but do not let the old URL pin it for a year.
142
+ stale = contentHash(await file.arrayBuffer()) !== hashed.hash;
143
+ }
144
+
145
+ const headers: Record<string, string> = {};
146
+ // Bun sets Content-Type from the extension, but be explicit for the
147
+ // cases where a wrong guess is expensive: a stylesheet served as
148
+ // text/plain is refused outright by the browser.
149
+ const type = file.type;
150
+ if (type) headers["Content-Type"] = type;
151
+
152
+ const policy = stale ? "revalidate" : cacheControlFor(pathname, search);
153
+ headers["Cache-Control"] = CACHE_CONTROL[policy];
154
+ if (policy === "revalidate") {
155
+ // The hash of the content, so a revalidation can be answered with
156
+ // 304 instead of the whole file.
157
+ const etag = await etagFor(file);
158
+ headers["ETag"] = etag;
159
+
160
+ // Compared here rather than left to Bun: a Bun.file body does not
161
+ // honour If-None-Match on its own, so without this the conditional
162
+ // request would get a 200 and re-download the whole file, and
163
+ // max-age=0 would cost a full transfer on every single page load.
164
+ //
165
+ // Weak comparison, and a match on `*`: both are what the HTTP spec
166
+ // asks for here. `W/` is stripped because these are strong ETags and
167
+ // a client may legitimately send the weak form of one.
168
+ const current = ifNoneMatch
169
+ ?.split(",")
170
+ .map((v) => v.trim())
171
+ .some((v) => v === "*" || v.replace(/^W\//, "") === etag);
172
+ if (current) {
173
+ return new Response(null, { status: 304, headers });
174
+ }
175
+ }
176
+ // Content-Length and Last-Modified come from the File; let Bun set them.
177
+ if (file.lastModified) {
178
+ headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
179
+ }
180
+ return new Response(file, { headers });
181
+ }
182
+ /**
183
+ * Try to load hooks.server.ts from the project root.
184
+ */
185
+ async function loadHooks(projectRoot: string): Promise<{
186
+ handle?: Handle;
187
+ init?: InitFunction;
188
+ handleError?: HandleError;
189
+ handleFetch?: HandleFetch;
190
+ }> {
191
+ const hooksPath = `${projectRoot}/hooks.server.ts`;
192
+ // no hooks file is fine; a hooks file that fails to load is not, and
193
+ // swallowing that silently switched off auth and every other handle
194
+ if (!existsSync(hooksPath)) return {};
195
+ const mod = await import(hooksPath);
196
+ return {
197
+ handle: mod.handle,
198
+ init: mod.init,
199
+ handleError: mod.handleError,
200
+ handleFetch: mod.handleFetch,
201
+ };
202
+ }
203
+
204
+ let resolverRegistered = false;
205
+ function registerServerResolver(config: GrimoireConfig): void {
206
+ if (resolverRegistered) return;
207
+ resolverRegistered = true;
208
+ bunPlugin(resolverPlugin(config, "server"));
209
+ }
210
+
211
+ interface _WsInternalData {
212
+ params: Record<string, string>;
213
+ // always present at runtime — optional only to satisfy TypeScript;
214
+ // upgrade block gates on mod.websocket before calling server.upgrade()
215
+ __handler?: WsRouteHandler<any>;
216
+ [key: string]: unknown;
217
+ }
218
+
219
+ /**
220
+ * Everything a server is except the socket: the request handler, the
221
+ * websocket handlers and the scanned route tree.
222
+ *
223
+ * Split from `createServer` so something that is not a listening server can
224
+ * use the real pipeline — `sigil build` prerenders by sending requests
225
+ * through `fetch`, which means `hooks.server.ts`, plugins and layouts run
226
+ * exactly as they will in production. `createServer` is this plus a port.
227
+ */
228
+ export interface GrimoireApp {
229
+ /** The full request pipeline: plugins, hooks, routing, rendering. */
230
+ fetch(req: Request): Promise<Response>;
231
+ /** Handlers to hand to `Bun.serve({ websocket })`. */
232
+ websocket: ServerWebSocketHandlers;
233
+ tree: RouteTree;
234
+ /** `src/params/*.ts` matchers by name, for `[param=name]` routes. */
235
+ matchers: Record<string, (value: string) => boolean>;
236
+ config: GrimoireConfig;
237
+ plugins: GrimoirePlugin[];
238
+ /** Tell the app which server it runs in, so it can upgrade websockets. */
239
+ bind(server: Server<any>): void;
240
+ /**
241
+ * Run `onStop` and let pending after-response work finish. Begins a
242
+ * process-wide shutdown (`afterResponse()` rejects afterwards), so call it
243
+ * once, when the process is done with the app.
244
+ */
245
+ close(
246
+ reason?: "shutdown" | "restart",
247
+ options?: { drainMs?: number },
248
+ ): Promise<void>;
249
+ /** Import every route module now, so the first visitor does not pay for it. */
250
+ preload(): Promise<void>;
251
+ }
252
+
253
+ type ServerWebSocketHandlers = {
254
+ open(ws: ServerWebSocket<any>): void;
255
+ message(ws: ServerWebSocket<any>, data: string | Buffer): void;
256
+ close(ws: ServerWebSocket<any>, code: number, reason?: string): void;
257
+ drain(ws: ServerWebSocket<any>): void;
258
+ };
259
+
260
+ export async function createApp(
261
+ config: GrimoireConfig = {},
262
+ ): Promise<GrimoireApp> {
263
+ // `after`/`before` decide the order, not the list; a config that did not
264
+ // come through importConfig (a test, a script) is ordered here too.
265
+ if (config.plugins)
266
+ config = { ...config, plugins: orderPlugins(config.plugins) };
267
+ setServerOnlyPlugins(config.plugins ?? []);
268
+
269
+ // run config hooks
270
+ let finalConfig = config;
271
+ const earlyPlugins = config.plugins ?? [];
272
+ for (const plugin of earlyPlugins) {
273
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
274
+ }
275
+
276
+ // Last word on `dev`: a plugin's config hook runs above and could have set
277
+ // it. The worker does the same for the same reason.
278
+ if (finalConfig._forceProduction)
279
+ finalConfig = { ...finalConfig, dev: false };
280
+
281
+ // Before the build, which can take a minute: a missing variable is the
282
+ // cheapest thing to find out about and the most annoying to learn late.
283
+ assertRequiredEnv(finalConfig);
284
+
285
+ // A base that would 404 every asset is a startup error, not a mystery.
286
+ const appBase = normalizeBase(finalConfig.base);
287
+ setBase(appBase);
288
+
289
+ const {
290
+ port = 3000,
291
+ host = "localhost",
292
+ plugins = [],
293
+ dev = false,
294
+ routes = "src/routes",
295
+ cspNonce,
296
+ //biome-ignore lint: not implemented yet
297
+ devEditor = "code",
298
+ _skipBuild = false,
299
+ } = finalConfig;
300
+
301
+ let tree: any;
302
+ if (!config._skipBuild) {
303
+ const { result, tree: _tree } = await buildProject(finalConfig, plugins);
304
+ if (!result.success) throw new Error("Grimoire: build failed");
305
+ tree = _tree;
306
+ } else {
307
+ // worker — build already done by loom, just scan routes
308
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
309
+ const { scanRoutes } = await import("../routing/scanner");
310
+ tree = await scanRoutes(routesDir, process.cwd());
311
+ }
312
+
313
+ // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
314
+ // WHAT ARE WE DOINGGGGGGGGG
315
+ // $lib and config.alias in every server module, and the $env/* modules
316
+ registerSSRPlugin(plugins, projectAliases(finalConfig));
317
+ registerServerResolver(finalConfig);
318
+
319
+ // Set by bind(); the handlers below only use it once a request arrives.
320
+ let server: Server<any> | undefined;
321
+
322
+ const graph = new DevGraph();
323
+ const hmr = dev ? new HmrServer() : null;
324
+
325
+ const aliases = finalConfig.alias ?? {};
326
+ setServerTiming(finalConfig.serverTiming ?? dev);
327
+
328
+ if (dev) {
329
+ const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
330
+ await ensureRuntimeBundle(process.cwd());
331
+
332
+ // clean dev-modules cache from previous session
333
+ const { rmSync, mkdirSync } = await import("node:fs");
334
+ const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
335
+ try {
336
+ rmSync(devModulesDir, { recursive: true, force: true });
337
+ } catch {}
338
+ mkdirSync(devModulesDir, { recursive: true });
339
+
340
+ const scanCtx = { graph, projectRoot: process.cwd(), aliases };
341
+ const entryFiles = () => {
342
+ const all = [
343
+ ...tree.routes,
344
+ ...tree.layouts,
345
+ ...tree.servers,
346
+ ...tree.errors,
347
+ ];
348
+ for (const rf of all) {
349
+ graph.getOrCreate(rf.filePath, rf.filePath);
350
+ graph.markRoute(rf.filePath, rf);
351
+ }
352
+ return all.map((rf) => rf.filePath);
353
+ };
354
+
355
+ // crawl the whole import graph, not just each route's direct imports:
356
+ // an edit is traced back to the routes that render it through however
357
+ // many component hops lie between
358
+ await crawlFrom(entryFiles(), scanCtx);
359
+
360
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
361
+
362
+ // one rebuild at a time; saves that land during a build fold into one
363
+ // follow-up pass instead of queueing a Bun.build each
364
+ let rebuilding: Promise<void> | null = null;
365
+ let rebuildQueued = false;
366
+ const runRebuild = (): Promise<void> => {
367
+ if (rebuilding) {
368
+ rebuildQueued = true;
369
+ return rebuilding;
370
+ }
371
+ rebuilding = (async () => {
372
+ do {
373
+ rebuildQueued = false;
374
+ const { result, tree: rescanned } = await rebuildClient(
375
+ finalConfig,
376
+ plugins,
377
+ );
378
+ if (!result.success) {
379
+ logger.error("client rebuild failed:", result.errors.join("\n"));
380
+ break;
381
+ }
382
+ // adopt the rescanned tree so routes added since startup match
383
+ tree = rescanned;
384
+ await crawlFrom(entryFiles(), scanCtx);
385
+ } while (rebuildQueued);
386
+ })().finally(() => {
387
+ rebuilding = null;
388
+ });
389
+ return rebuilding;
390
+ };
391
+
392
+ const devCtx: DevContext = {
393
+ graph,
394
+ hmr: hmr!,
395
+ projectRoot: process.cwd(),
396
+ aliases,
397
+ entries: entryFiles,
398
+ rebuild: runRebuild,
399
+ scheduleRebuild: () => {
400
+ runRebuild().catch((e: unknown) =>
401
+ logger.error("client rebuild failed:", e),
402
+ );
403
+ },
404
+ };
405
+
406
+ startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
407
+ handleChange(f, devCtx),
408
+ );
409
+ }
410
+
411
+ const loader = dev
412
+ ? makeDevLoader(graph, process.cwd(), { aliases })
413
+ : (p: string) => import(p);
414
+
415
+ // [param=matcher] validation — load src/params/*.ts once at startup
416
+ const paramMatcherFns: Record<string, (value: string) => boolean> = {};
417
+ for (const pm of tree.paramMatcherFiles ?? []) {
418
+ try {
419
+ const mod = await loader(pm.filePath);
420
+ if (typeof mod.match === "function") {
421
+ paramMatcherFns[pm.name] = mod.match;
422
+ }
423
+ } catch (e) {
424
+ logger.warn(`failed to load param matcher "${pm.name}":`, e);
425
+ }
426
+ }
427
+ for (const s of shadowedRoutes(plugins, tree, paramMatcherFns)) {
428
+ logger.warn(shadowedRouteMessage(s));
429
+ }
430
+
431
+ // Load hooks.server.ts
432
+ const {
433
+ handle: appHandle,
434
+ init: hooksInit,
435
+ handleError: hooksHandleError,
436
+ handleFetch: hooksHandleFetch,
437
+ } = await loadHooks(process.cwd());
438
+
439
+ const hooksHandle = composeHandle(plugins, appHandle);
440
+
441
+ // Resolved once at startup, not per request: services() may open a pool,
442
+ // and the object is immutable for the process lifetime, so building it
443
+ // inside handleRequest would open a connection per visitor.
444
+ //
445
+ // Before init(), so hooks.server.ts can use what plugins opened — a
446
+ // database for a warm-up query or a migration check is the usual case,
447
+ // and running init first meant it could only fail.
448
+ // The same hook the coordinator fires, for every process that serves
449
+ // requests. It used to run only in the coordinator, so `sigil dev` and a
450
+ // single-process `sigil start` never gave plugins their moment to look at
451
+ // each other.
452
+ await runHook(plugins, "onPluginsResolved", {
453
+ mode: dev ? "development" : "production",
454
+ plugins: new Map(plugins.map((p) => [p.name, p])),
455
+ logger: log.scope("plugins"),
456
+ });
457
+
458
+ const services = await collectServices(plugins);
459
+
460
+ // Run init hook if present
461
+ await hooksInit?.();
462
+
463
+ // onRouteRender forces the whole response to be buffered into a string,
464
+ // which silently disables streaming for every route a plugin touches. That
465
+ // is a real cost and an invisible one, so say it once at boot rather than
466
+ // letting someone discover it as "streaming stopped working".
467
+ for (const p of plugins) {
468
+ if (p.onRouteRender) {
469
+ logger.warn(
470
+ `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. Use rewriteHtml(rewriter) to change the HTML while it streams, or onRequest to change headers.`,
471
+ );
472
+ }
473
+ }
474
+
475
+ async function handleRequest(req: Request) {
476
+ // Only the coordinator is trusted to say who the user is. A server that
477
+ // answers the public directly ignores the header, so nobody can send
478
+ // their own `locals` to it.
479
+ const rawLocals = finalConfig._behindCoordinator
480
+ ? req.headers.get("X-Grimoire-Locals")
481
+ : null;
482
+ const locals: App.Locals = rawLocals
483
+ ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
484
+ : {};
485
+ // Plugin services sit under the request's own locals: what the app
486
+ // set (a session, a user) always wins over what a plugin declared,
487
+ // so a plugin cannot clobber auth by defining a common key.
488
+ for (const [key, value] of Object.entries(services)) {
489
+ if (!(key in locals)) locals[key] = value;
490
+ }
491
+ const url = new URL(req.url);
492
+
493
+ if (dev && url.pathname === "/__grimoire__/hmr") {
494
+ //@ts-expect-error holy shut up
495
+ if (server?.upgrade(req, { data: { __hmrClient: true } })) {
496
+ return undefined as unknown as Response;
497
+ }
498
+ return new Response("Upgrade Required", { status: 426 });
499
+ }
500
+ if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
501
+ return new Response(HMR_CLIENT_SOURCE, {
502
+ headers: { "Content-Type": "application/javascript" },
503
+ });
504
+ }
505
+ if (dev && url.pathname === "/__grimoire__/open") {
506
+ const file = url.searchParams.get("file") ?? "";
507
+ const line = url.searchParams.get("line") ?? "1";
508
+ const col = url.searchParams.get("col") ?? "1";
509
+ const editor = finalConfig.devEditor ?? "code";
510
+ //@ts-expect-error Bun spawn has werird types just shut up
511
+ Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
512
+ return new Response(null, { status: 204 });
513
+ }
514
+ if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
515
+ const depName = decodeURIComponent(
516
+ url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
517
+ );
518
+
519
+ // grimoire shim
520
+ if (depName.includes("@sigil-dev__grimoire")) {
521
+ return Response.redirect("/__grimoire__/grimoire-client.js", 302);
522
+ }
523
+
524
+ // convert URL-safe name back to package name
525
+ // @codex__shared → @codex/shared
526
+ const pkgName = depName.startsWith("@")
527
+ ? depName.replace("__", "/")
528
+ : depName;
529
+
530
+ const depsDir = join(process.cwd(), ".grimoire/deps");
531
+ mkdirSync(depsDir, { recursive: true });
532
+ const outFile = join(depsDir, `${depName}.js`);
533
+
534
+ if (!(await Bun.file(outFile).exists())) {
535
+ logger.debug("bundling dep:", pkgName);
536
+ try {
537
+ const entry = Bun.resolveSync(pkgName, process.cwd());
538
+ const result = await Bun.build({
539
+ entrypoints: [entry],
540
+ outdir: depsDir,
541
+ naming: `${depName}.js`,
542
+ target: "browser",
543
+ format: "esm",
544
+ minify: false,
545
+ external: ["@sigil-dev/runtime"],
546
+ });
547
+ if (!result.success) {
548
+ logger.error("dep bundle failed:", pkgName, result.logs);
549
+ return new Response(
550
+ `throw new Error("failed to bundle dep: ${pkgName}")`,
551
+ { headers: { "Content-Type": "application/javascript" } },
552
+ );
553
+ }
554
+ logger.debug("bundled dep:", pkgName);
555
+ } catch (e: any) {
556
+ return new Response(
557
+ `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
558
+ { headers: { "Content-Type": "application/javascript" } },
559
+ );
560
+ }
561
+ }
562
+
563
+ return new Response(Bun.file(outFile), {
564
+ headers: {
565
+ "Content-Type": "application/javascript",
566
+ "Cache-Control": "no-store",
567
+ },
568
+ });
569
+ }
570
+
571
+ if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
572
+ const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
573
+ let js: string;
574
+ try {
575
+ js = envModuleSource(specifier, "browser");
576
+ } catch (e: unknown) {
577
+ const message = e instanceof Error ? e.message : String(e);
578
+ js = `throw new Error(${JSON.stringify(message)})`;
579
+ }
580
+ return new Response(js, {
581
+ headers: {
582
+ "Content-Type": "application/javascript",
583
+ "Cache-Control": "no-store",
584
+ },
585
+ });
586
+ }
587
+
588
+ if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
589
+ const clientPath = decodeURIComponent(
590
+ url.pathname.slice("/__grimoire__/m/".length),
591
+ );
592
+ const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
593
+ try {
594
+ // compiled at the module's current graph version, which is what
595
+ // the `?v=` in the URL was derived from
596
+ const { js } = await getDevModule(absPath, {
597
+ projectRoot: process.cwd(),
598
+ aliases,
599
+ graph,
600
+ });
601
+ return new Response(js, {
602
+ headers: {
603
+ "Content-Type": "application/javascript",
604
+ "Cache-Control": "no-store",
605
+ },
606
+ });
607
+ } catch (e: unknown) {
608
+ const message = e instanceof Error ? e.message : String(e);
609
+ return new Response(`throw new Error(${JSON.stringify(message)})`, {
610
+ headers: { "Content-Type": "application/javascript" },
611
+ });
612
+ }
613
+ }
614
+
615
+ // Static files are served BEFORE the plugin pipeline. A CSS file or
616
+ // an image has nothing to do with a plugin's onRequest hook, and
617
+ // running them through it costs a hook round-trip plus a stat on
618
+ // every asset request.
619
+ //
620
+ // Caching rule, decided per asset by servePublicAsset: the document
621
+ // is never cached, a content-addressed URL is immutable, and
622
+ // anything else revalidates against an ETag.
623
+ const staticAsset = await servePublicAsset(
624
+ url.pathname,
625
+ url.search,
626
+ req.headers.get("if-none-match"),
627
+ );
628
+ if (staticAsset) return staticAsset;
629
+
630
+ return runRequestHooks(plugins, req, async () => {
631
+ const HTTP_METHODS = [
632
+ "GET",
633
+ "POST",
634
+ "PUT",
635
+ "PATCH",
636
+ "DELETE",
637
+ "HEAD",
638
+ "OPTIONS",
639
+ ] as const;
640
+
641
+ // Build event BEFORE matching — handle() runs pre-match like SvelteKit
642
+ trackClientAddress(req, server);
643
+ const cookieHeader = req.headers.get("cookie") ?? "";
644
+ const cookies = createCookies(cookieHeader);
645
+ const setHeadersMap: Record<string, string> = {};
646
+
647
+ const event: RequestEvent = {
648
+ request: req,
649
+ url,
650
+ params: {},
651
+ locals,
652
+ cookies,
653
+ route: { id: "" },
654
+ fetch: globalThis.fetch,
655
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
656
+ getClientAddress: () => clientAddressOf(req),
657
+ };
658
+
659
+ if (hooksHandleFetch) {
660
+ event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
661
+ const r = new Request(reqInfo, init);
662
+ return Promise.resolve(
663
+ hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
664
+ );
665
+ };
666
+ }
667
+ const patchedFetch: typeof fetch = (input, init) => {
668
+ const resolved =
669
+ typeof input === "string" && input.startsWith("/")
670
+ ? new URL(input, url.origin).toString()
671
+ : input;
672
+ return globalThis.fetch(resolved as any, init);
673
+ };
674
+ const resolve: ResolveFunction = async (evt) => {
675
+ // matching happens here — after handle() has run
676
+ let matched = matchRoute(tree, evt.url, paramMatcherFns);
677
+ if (!matched) {
678
+ // the nearest +error.tsx inside the layouts that cover the
679
+ // address, like a page whose load throws error(404)
680
+ return renderRoute(
681
+ matchNotFound(tree, evt.url),
682
+ evt.request,
683
+ tree.errors,
684
+ loader,
685
+ evt.locals,
686
+ plugins,
687
+ cspNonce,
688
+ dev,
689
+ patchedFetch,
690
+ );
691
+ }
692
+
693
+ // patch event with match results so handle() epilogue can read them
694
+ evt.params = matched.params;
695
+ evt.route = { id: matched.route.path };
696
+
697
+ // API routes (+server.ts)
698
+ if (matched.route.type === "server") {
699
+ const mod = await loader(matched.route.filePath);
700
+
701
+ const isWsUpgrade =
702
+ evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
703
+ if (isWsUpgrade && mod.websocket) {
704
+ let extraData: Record<string, unknown> = {};
705
+ if (mod.upgrade) {
706
+ try {
707
+ const result = await mod.upgrade({
708
+ request: evt.request,
709
+ params: matched.params,
710
+ url: evt.url,
711
+ locals: evt.locals,
712
+ });
713
+ if (result && typeof result === "object") extraData = result;
714
+ } catch {
715
+ return new Response("Upgrade Required", { status: 426 });
716
+ }
717
+ }
718
+ const wsData: _WsInternalData = {
719
+ params: matched.params,
720
+ __handler: mod.websocket,
721
+ ...extraData,
722
+ };
723
+ //@ts-expect-error i dont know what you are talking about please
724
+ if (server?.upgrade(req, { data: wsData })) {
725
+ return undefined as unknown as Response;
726
+ }
727
+ return new Response("Upgrade Required", { status: 426 });
728
+ }
729
+
730
+ const handler = mod[evt.request.method];
731
+ if (handler) {
732
+ try {
733
+ return await handler({
734
+ request: evt.request,
735
+ params: matched.params,
736
+ url: evt.url,
737
+ locals: evt.locals,
738
+ fetch: patchedFetch,
739
+ cookies,
740
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
741
+ getClientAddress: () => clientAddressOf(evt.request),
742
+ });
743
+ } catch (e) {
744
+ // `throw redirect(303, "/login")` works here as in an action
745
+ if (isRedirectResult(e)) {
746
+ return new Response(null, {
747
+ status: e.status,
748
+ headers: { Location: e.location },
749
+ });
750
+ }
751
+ throw e;
752
+ }
753
+ }
754
+ // no handler for this method: a page at the same URL (say a
755
+ // chat page next to its WebSocket endpoint) takes the request
756
+ const page = matchRoute(
757
+ { ...tree, servers: [] },
758
+ evt.url,
759
+ paramMatcherFns,
760
+ );
761
+ if (!page) {
762
+ return new Response("Method Not Allowed", { status: 405 });
763
+ }
764
+ matched = page;
765
+ evt.params = page.params;
766
+ evt.route = { id: page.route.path };
767
+ }
768
+
769
+ // form actions (+page.server.ts)
770
+ if (
771
+ matched.pageServer &&
772
+ HTTP_METHODS.includes(evt.request.method as any)
773
+ ) {
774
+ const mod = await loader(matched.pageServer.filePath);
775
+
776
+ // named actions: ?/create dispatches export `create`. Only for
777
+ // non-GET requests: a GET must never run an action, or any link
778
+ // or <img> on another site could trigger one with the visitor's
779
+ // cookies and no CSRF check (GET skips it)
780
+ const isRead =
781
+ evt.request.method === "GET" || evt.request.method === "HEAD";
782
+ const actionName = isRead
783
+ ? undefined
784
+ : [...evt.url.searchParams.keys()]
785
+ .find((k) => k.startsWith("/"))
786
+ ?.slice(1);
787
+ // every other function export is callable by name, but the
788
+ // module's own hooks are not actions
789
+ const reserved =
790
+ actionName !== undefined && RESERVED_EXPORTS.has(actionName);
791
+ // reads render the page; an exported GET is not an action either
792
+ const handler =
793
+ reserved || isRead
794
+ ? undefined
795
+ : actionName
796
+ ? mod[actionName]
797
+ : mod[evt.request.method];
798
+ if (actionName && typeof handler !== "function") {
799
+ return new Response("Not Found", { status: 404 });
800
+ }
801
+
802
+ if (mod.csrf !== false && !isRead) {
803
+ const cookieToken = cookies.get("_csrf");
804
+ const formData = await evt.request
805
+ .clone()
806
+ .formData()
807
+ .catch(() => null);
808
+ const bodyToken = formData?.get("_csrf");
809
+ if (!cookieToken || cookieToken !== String(bodyToken)) {
810
+ return new Response("Forbidden", { status: 403 });
811
+ }
812
+ }
813
+ // enhance() submits with fetch, which follows a 303 on its own
814
+ // and can't read where it went; it asks for the outcome as JSON
815
+ // instead and navigates itself
816
+ const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
817
+ if (handler) {
818
+ let result: any;
819
+ try {
820
+ result = await handler({
821
+ request: evt.request,
822
+ params: matched.params,
823
+ url: evt.url,
824
+ locals: evt.locals,
825
+ fetch: patchedFetch,
826
+ cookies,
827
+ getClientAddress: () => clientAddressOf(evt.request),
828
+ });
829
+ } catch (e) {
830
+ // A thrown Response is the reply, like a returned one: it
831
+ // used to fall through to the 500 path and be swallowed.
832
+ if (e instanceof Response) return e;
833
+ if (isRedirectResult(e)) {
834
+ if (enhanced) {
835
+ return Response.json({
836
+ type: "redirect",
837
+ status: e.status,
838
+ location: e.location,
839
+ });
840
+ }
841
+ return new Response(null, {
842
+ status: e.status,
843
+ headers: { Location: e.location },
844
+ });
845
+ }
846
+ if (isErrorResult(e)) {
847
+ const isApi =
848
+ enhanced ||
849
+ evt.request.headers
850
+ .get("accept")
851
+ ?.includes("application/json");
852
+ if (isApi) {
853
+ return Response.json(
854
+ { error: true, status: e.status, message: e.message },
855
+ { status: e.status },
856
+ );
857
+ }
858
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
859
+ // no layoutPairs here: layout data comes from the load
860
+ // pipeline in renderRoute, which a form action bypasses —
861
+ // wrapping layouts without their data would crash them
862
+ return (
863
+ (await renderErrorPage(
864
+ tree.errors,
865
+ evt.url.pathname,
866
+ e.status,
867
+ e.message,
868
+ e,
869
+ loader,
870
+ { params: matched.params, nonceAttr, dev },
871
+ )) ??
872
+ new Response(e.message, { status: e.status, headers: TEXT })
873
+ );
874
+ }
875
+ throw e;
876
+ }
877
+
878
+ if (result instanceof Response) return result;
879
+
880
+ if (isFailResult(result)) {
881
+ if (enhanced) {
882
+ return Response.json(
883
+ { fail: true, status: result.status, data: result.data },
884
+ { status: result.status },
885
+ );
886
+ }
887
+ // a plain form post (no JavaScript): show the page again,
888
+ // with the failure as its `form` prop
889
+ return renderRoute(
890
+ matched,
891
+ evt.request,
892
+ tree.errors,
893
+ loader,
894
+ evt.locals,
895
+ plugins,
896
+ cspNonce,
897
+ dev,
898
+ patchedFetch,
899
+ { status: result.status, data: result.data },
900
+ );
901
+ }
902
+
903
+ const redirectTo =
904
+ result?.redirect ??
905
+ evt.request.headers.get("referer") ??
906
+ withBase("/");
907
+ if (enhanced) {
908
+ return Response.json({
909
+ type: "success",
910
+ location: redirectTo,
911
+ data: result ?? null,
912
+ });
913
+ }
914
+ return new Response(null, {
915
+ status: 303,
916
+ headers: { Location: redirectTo },
917
+ });
918
+ }
919
+ if (!actionName && !isRead) {
920
+ return new Response("Method Not Allowed", { status: 405 });
921
+ }
922
+ }
923
+
924
+ // page routes
925
+ const response = await renderRoute(
926
+ matched,
927
+ evt.request,
928
+ tree.errors,
929
+ loader,
930
+ evt.locals,
931
+ plugins,
932
+ cspNonce,
933
+ dev,
934
+ patchedFetch,
935
+ );
936
+
937
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
938
+ return response;
939
+ }
940
+
941
+ // Streaming-safe rewrites first, then the buffered legacy hook.
942
+ const rewritten = await applyRewriters(response, plugins, {
943
+ route: matched.route,
944
+ request: evt.request,
945
+ params: matched.params,
946
+ data: undefined,
947
+ });
948
+ const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
949
+ if (!hasRenderPlugins) return rewritten;
950
+ let html = await rewritten.text();
951
+ for (const plugin of plugins) {
952
+ html =
953
+ (await plugin.onRouteRender?.(html, {
954
+ route: matched.route,
955
+ request: evt.request,
956
+ params: matched.params,
957
+ data: undefined,
958
+ })) ?? html;
959
+ }
960
+ // Carry the original headers over. Rebuilding with a fixed set
961
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
962
+ // plugin silently broke form actions and cache correctness.
963
+ const headers = new Headers(rewritten.headers);
964
+ headers.set("Content-Type", "text/html");
965
+ return new Response(html, {
966
+ status: rewritten.status,
967
+ statusText: rewritten.statusText,
968
+ headers,
969
+ });
970
+ };
971
+
972
+ let response: Response;
973
+ try {
974
+ if (!hooksHandle) {
975
+ response = await resolve(event);
976
+ } else {
977
+ response = await hooksHandle({ event, resolve });
978
+ }
979
+ } catch (err) {
980
+ logger.error(
981
+ `${event.request.method} ${event.url.pathname} failed:`,
982
+ err,
983
+ );
984
+ await hooksHandleError?.({
985
+ error: err,
986
+ event,
987
+ status: 500,
988
+ message: "Internal Server Error",
989
+ });
990
+ // an unexpected error gets the nearest +error.tsx too, with a
991
+ // generic message: details stay in the log
992
+ try {
993
+ const page = await renderErrorPage(
994
+ tree.errors,
995
+ event.url.pathname,
996
+ 500,
997
+ "Internal Server Error",
998
+ process.env.NODE_ENV === "production" ? null : err,
999
+ loader,
1000
+ { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
1001
+ );
1002
+ if (page) return page;
1003
+ } catch (pageErr) {
1004
+ logger.error("+error.tsx failed while rendering an error:", pageErr);
1005
+ }
1006
+ const errorHtmlPath = `${process.cwd()}/error.html`;
1007
+ try {
1008
+ const errorFile = Bun.file(errorHtmlPath);
1009
+ if (await errorFile.exists()) {
1010
+ return new Response(errorFile, {
1011
+ status: 500,
1012
+ headers: { "Content-Type": "text/html" },
1013
+ });
1014
+ }
1015
+ } catch {}
1016
+ const message =
1017
+ process.env.NODE_ENV === "production"
1018
+ ? "Internal Server Error"
1019
+ : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
1020
+ return new Response(message, { status: 500, headers: TEXT });
1021
+ }
1022
+
1023
+ const setCookieHeaders = cookies.toHeaders();
1024
+ if (
1025
+ !response ||
1026
+ (setCookieHeaders.length === 0 &&
1027
+ Object.keys(setHeadersMap).length === 0)
1028
+ ) {
1029
+ return response;
1030
+ }
1031
+ return withHeaders(
1032
+ response,
1033
+ Object.entries(setHeadersMap),
1034
+ setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
1035
+ );
1036
+ });
1037
+ }
1038
+
1039
+ const websocket: ServerWebSocketHandlers = {
1040
+ open(ws: ServerWebSocket<any>) {
1041
+ if (ws.data.__hmrClient) {
1042
+ hmr?.addClient(ws);
1043
+ return;
1044
+ }
1045
+ (ws.data as _WsInternalData).__handler?.open?.(ws);
1046
+ },
1047
+ message(ws: ServerWebSocket<any>, data: string | Buffer) {
1048
+ if (ws.data.__hmrClient) return;
1049
+ (ws.data as _WsInternalData).__handler?.message?.(ws, data);
1050
+ },
1051
+ close(ws: ServerWebSocket<any>, code: number, reason?: string) {
1052
+ if (ws.data.__hmrClient) {
1053
+ hmr?.removeClient(ws);
1054
+ return;
1055
+ }
1056
+ (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
1057
+ },
1058
+ drain(ws: ServerWebSocket<any>) {
1059
+ if (ws.data.__hmrClient) return;
1060
+ (ws.data as _WsInternalData).__handler?.drain?.(ws);
1061
+ },
1062
+ };
1063
+
1064
+ // Wrapping is what makes afterResponse() mean "after the response",
1065
+ // including for streaming responses: the tasks fire when the body
1066
+ // finishes, not when the handler returns.
1067
+ const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
1068
+
1069
+ // Under a base, the request is stripped to a route path once, here, so
1070
+ // nothing past this point has to know about it.
1071
+ const fetchUnderBase = (req: Request): Promise<Response> | Response => {
1072
+ if (!appBase) return fetchHandler(req);
1073
+ const url = new URL(req.url);
1074
+ if (url.pathname === appBase) {
1075
+ return new Response(null, {
1076
+ status: 308,
1077
+ headers: { Location: `${appBase}/${url.search}` },
1078
+ });
1079
+ }
1080
+ const route = stripBase(url.pathname, appBase);
1081
+ if (route === null) {
1082
+ // dev modules import each other root-relative
1083
+ if (dev && url.pathname.startsWith("/__grimoire__/")) {
1084
+ return fetchHandler(req);
1085
+ }
1086
+ return new Response(outsideBaseMessage(url.pathname, appBase, dev), {
1087
+ status: 404,
1088
+ headers: { "Content-Type": "text/plain" },
1089
+ });
1090
+ }
1091
+ url.pathname = route;
1092
+ return fetchHandler(new Request(url, req));
1093
+ };
1094
+
1095
+ const preload = async () => {
1096
+ if (dev || finalConfig.warm?.preload === false) return;
1097
+ const files = [
1098
+ ...tree.routes,
1099
+ ...tree.layouts,
1100
+ ...tree.servers,
1101
+ ...tree.errors,
1102
+ ].map((rf: { filePath: string }) => rf.filePath);
1103
+ const t0 = performance.now();
1104
+ const loaded = await preloadModules(files, loader, (msg, err) =>
1105
+ logger.warn(msg, err),
1106
+ );
1107
+ logger.info(
1108
+ `preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
1109
+ );
1110
+ };
1111
+
1112
+ return {
1113
+ fetch: fetchUnderBase,
1114
+ websocket,
1115
+ tree,
1116
+ matchers: paramMatcherFns,
1117
+ config: finalConfig,
1118
+ plugins,
1119
+ bind(s) {
1120
+ server = s;
1121
+ },
1122
+ preload,
1123
+ async close(reason = "shutdown", options) {
1124
+ await runHook(plugins, "onStop", reason);
1125
+ // Drain before stopping, so a task already registered for a response
1126
+ // that has been sent gets to finish rather than being killed with the
1127
+ // process. Bounded: a hung task must not block a deploy forever.
1128
+ await drainAfterResponse(options?.drainMs);
1129
+ },
1130
+ };
1131
+ }
1132
+
1133
+ export async function createServer(config: GrimoireConfig = {}) {
1134
+ const app = await createApp(config);
1135
+ const { plugins, config: finalConfig } = app;
1136
+ const { port = 3000, host = "localhost", dev = false } = finalConfig;
1137
+
1138
+ // Before the port opens, so the first visitor never pays for compiling a
1139
+ // route: a worker only reports ready once this has finished.
1140
+ await app.preload();
1141
+
1142
+ const server = Bun.serve({
1143
+ port,
1144
+ hostname: host,
1145
+ idleTimeout: finalConfig.idleTimeout,
1146
+ maxRequestBodySize: finalConfig.maxRequestBodySize,
1147
+ fetch: app.fetch,
1148
+ websocket: app.websocket,
1149
+ });
1150
+ app.bind(server);
1151
+
1152
+ const warmConfig = finalConfig.warm;
1153
+ let warmer: Warmer | null = null;
1154
+ if (!dev && warmConfig?.paths?.length) {
1155
+ warmer = startWarming({
1156
+ paths: warmConfig.paths,
1157
+ every: warmConfig.every,
1158
+ origin: `http://${host}:${server.port}`,
1159
+ headers: finalConfig._warmHeaders,
1160
+ handle: async (req) => app.fetch(req),
1161
+ log: (msg) => logger.info(msg),
1162
+ });
1163
+ }
1164
+
1165
+ let stopping = false;
1166
+ const handleShutdown = async () => {
1167
+ if (stopping) return;
1168
+ stopping = true;
1169
+ warmer?.stop();
1170
+ await app.close("shutdown");
1171
+ // stop(true), not stop(): the graceful form waits for open connections,
1172
+ // and a dev HMR websocket never closes on its own, so shutdown hangs.
1173
+ server.stop(true);
1174
+ process.exit(0);
1175
+ };
1176
+ process.on("SIGINT", handleShutdown);
1177
+ process.on("SIGTERM", handleShutdown);
1178
+
1179
+ await runHook(plugins, "onStart", server);
1180
+ return server;
1181
+ }