@sigil-dev/grimoire 0.9.23 → 0.9.25

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