@sigil-dev/grimoire 0.9.33 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/sigil.ts CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env bun
2
2
  // `sigil`, installed with grimoire: an app depends on grimoire alone and
3
3
  // still gets the command. The CLI itself lives in @sigil-dev/cli.
4
4
  import "@sigil-dev/cli/src/index.ts";
package/index.ts CHANGED
@@ -8,6 +8,8 @@ export { importConfig } from "./src/config-file";
8
8
  // "1h 30m" and friends, for every option that takes a time
9
9
  export { type Duration, ms } from "./src/duration";
10
10
  export { Head } from "./src/rendering/head";
11
+ // the part of locals the browser may see, the same on both sides
12
+ export { pageUrl, publicLocals } from "./src/locals";
11
13
  export { type Routes, route } from "./src/routing/route";
12
14
  // registerSSRPlugin is server-only — import from "@sigil-dev/grimoire/bun"
13
15
  export type { RouteFile, RouteTree } from "./src/routing/scanner";
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "module": "index.ts",
12
12
  "type": "module",
13
13
  "private": false,
14
- "version": "0.9.33",
14
+ "version": "0.10.1",
15
15
  "bin": {
16
16
  "sigil": "bin/sigil.ts"
17
17
  },
@@ -32,15 +32,16 @@
32
32
  "./adapters/bun": "./src/adapters/bun.ts",
33
33
  "./testing": "./src/testing/index.ts",
34
34
  "./testing/dom": "./src/testing/dom.ts",
35
- "./testing/server": "./src/testing/server.ts"
35
+ "./testing/server": "./src/testing/server.ts",
36
+ "./testing/server-preload": "./src/testing/server-preload.ts"
36
37
  },
37
38
  "scripts": {
38
39
  "test": "bun test"
39
40
  },
40
41
  "dependencies": {
41
- "@sigil-dev/cli": "0.9.33",
42
- "@sigil-dev/compiler": "0.9.33",
43
- "@sigil-dev/runtime": "0.9.33"
42
+ "@sigil-dev/cli": "0.10.1",
43
+ "@sigil-dev/compiler": "0.10.1",
44
+ "@sigil-dev/runtime": "0.10.1"
44
45
  },
45
46
  "peerDependencies": {
46
47
  "typescript": "^5",
package/server.ts CHANGED
@@ -18,5 +18,6 @@ export {
18
18
  runWorkerSpawn,
19
19
  } from "./src/server/plugins";
20
20
  export { projectAliases } from "./src/server/resolver";
21
+ export { getRequestEvent } from "./src/server/request-event.ts";
21
22
  export type { TypegenConfig } from "./src/typegen";
22
- export { generateTypes } from "./src/typegen";
23
+ export { generateTypes, writeTsConfig } from "./src/typegen";
@@ -15,7 +15,7 @@ export const CSRF_FIELD = "_csrf";
15
15
 
16
16
  function cookieToken(): string | null {
17
17
  const m = /(?:^|;\s*)_csrf=([^;]+)/.exec(document.cookie);
18
- return m ? decodeURIComponent(m[1]) : null;
18
+ return m?.[1] ? decodeURIComponent(m[1]) : null;
19
19
  }
20
20
 
21
21
  export function ensureCsrf(form: HTMLFormElement): void {
@@ -5,6 +5,7 @@ import {
5
5
  pushHydrationNodes,
6
6
  } from "@sigil-dev/runtime";
7
7
  import { base, stripBase } from "../base";
8
+ import { setPublicLocalsSource } from "../locals";
8
9
  import { onSubmitEnsureCsrf } from "./csrf.ts";
9
10
  import {
10
11
  clearDeps,
@@ -88,8 +89,10 @@ let disposeCurrentPage: (() => void) | null = null;
88
89
  // Scroll keys and same-page refetch detection are pathname-only on purpose.
89
90
  // currentSearch is tracked alongside so popstate can tell "?page=2" apart
90
91
  // from "?page=1" without polluting either of those.
91
- let currentPath = location.pathname;
92
- let currentSearch = location.search;
92
+ // importing this on the server (a component that calls invalidate() renders
93
+ // there too) must not touch the browser's globals
94
+ let currentPath = typeof location === "undefined" ? "" : location.pathname;
95
+ let currentSearch = typeof location === "undefined" ? "" : location.search;
93
96
 
94
97
  // C1: Navigation hooks
95
98
  let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
@@ -264,7 +267,7 @@ function sharedTransitionKeys(
264
267
  // The HTTP cache cannot do this job: the navigate JSON carries no freshness
265
268
  // headers and pages are commonly served `no-cache`, so a plain prefetch
266
269
  // warmed nothing the click could reuse.
267
- let preloadTimer: Timer | null = null;
270
+ let preloadTimer: ReturnType<typeof setTimeout> | undefined;
268
271
  const PREFETCH_TTL_MS = 15_000;
269
272
  const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
270
273
 
@@ -478,7 +481,7 @@ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
478
481
  };
479
482
 
480
483
  for (let i = matchedLayouts.length - 1; i >= 0; i--) {
481
- const LayoutComponent = matchedLayouts[i].component;
484
+ const LayoutComponent = matchedLayouts[i]!.component;
482
485
  const innerRender = renderFn;
483
486
  const currentLayoutData = layoutData?.[i];
484
487
  renderFn = () => {
@@ -621,6 +624,8 @@ export async function navigate(
621
624
  const json = await res.json();
622
625
  if (navId !== navigationId) return;
623
626
  const { data, layoutData, params, pattern, head, deps } = json;
627
+ // the new page's publicLocals() (a sign-in or a changed setting shows up here)
628
+ setPublicLocalsSource(() => json.publicLocals);
624
629
  const Page = await resolveRoute(pattern);
625
630
  if (navId !== navigationId) return;
626
631
  if (!Page) {
package/src/locals.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What of the request's locals the browser may see, the same object on both
3
+ * sides: on the server, what hooks.server.ts's `publicLocals(locals)` made
4
+ * for the request being served; in the browser, the copy the page was sent
5
+ * (refreshed on every client navigation). Undefined outside a request, or
6
+ * when hooks.server.ts has no `publicLocals`.
7
+ *
8
+ * ```ts
9
+ * // hooks.server.ts
10
+ * export const publicLocals = (locals: App.Locals) => ({ timeZone: locals.prefs.timeZone });
11
+ *
12
+ * // anywhere, server or browser
13
+ * import { publicLocals } from "@sigil-dev/grimoire";
14
+ * const zone = publicLocals()?.timeZone ?? "UTC";
15
+ * ```
16
+ *
17
+ * Everything in it is sent to the browser: never put a session, a token or
18
+ * anything private there. Server code that needs all of locals uses
19
+ * getRequestEvent() from "@sigil-dev/grimoire/server".
20
+ */
21
+ export function publicLocals<T = App.PublicLocals>(): T | undefined {
22
+ const source = (globalThis as Record<string, unknown>)[KEY];
23
+ return typeof source === "function" ? (source() as T | undefined) : undefined;
24
+ }
25
+
26
+ // a global rather than module state: the server side (request-event.ts) and
27
+ // the browser side (hydrate, router) set it from bundles that never import
28
+ // each other, and this module must stay free of node:async_hooks
29
+ const KEY = "__grimoire_public_locals__";
30
+
31
+ /** @internal Where publicLocals() reads from: the request scope, or the page's state. */
32
+ export function setPublicLocalsSource(source: () => unknown): void {
33
+ (globalThis as Record<string, unknown>)[KEY] = source;
34
+ }
35
+
36
+ const URL_KEY = "__grimoire_page_url__";
37
+
38
+ /**
39
+ * The address of the page being rendered: the request's on the server, the
40
+ * window's in the browser. For code that runs on both sides and needs an
41
+ * absolute URL or the current path (metadata, share links).
42
+ */
43
+ export function pageUrl(): URL | undefined {
44
+ if (typeof location !== "undefined" && typeof document !== "undefined") return new URL(location.href);
45
+ const source = (globalThis as Record<string, unknown>)[URL_KEY];
46
+ return typeof source === "function" ? (source() as URL | undefined) : undefined;
47
+ }
48
+
49
+ /** @internal The server's source for pageUrl(): the current request. */
50
+ export function setPageUrlSource(source: () => URL | undefined): void {
51
+ (globalThis as Record<string, unknown>)[URL_KEY] = source;
52
+ }
@@ -17,6 +17,7 @@ import {
17
17
  } from "../client/router";
18
18
  import { initRouter } from "../client/router.ts";
19
19
  import { withEffectScope } from "../client/scope.ts";
20
+ import { setPublicLocalsSource } from "../locals";
20
21
  import { Head } from "./head";
21
22
 
22
23
  // expose for HMR module shim
@@ -38,6 +39,8 @@ async function hydrate(): Promise<(() => void) | undefined> {
38
39
  if (!stateEl) return undefined;
39
40
 
40
41
  const state = JSON.parse(stateEl.textContent!);
42
+ // publicLocals() in the browser: what the server sent with this page
43
+ setPublicLocalsSource(() => state.publicLocals);
41
44
  const Page = await resolveInitialPage(state.pattern);
42
45
  if (!Page) return undefined;
43
46
  const slot = document.getElementById("grimoire-root");
@@ -16,6 +16,7 @@ import type { GrimoirePlugin, LoadContext, Route } from "../types";
16
16
  import { collectHead, initHead } from "./head";
17
17
  import { optimizeImages } from "./images.ts";
18
18
  import { preloadLinks } from "./preload.ts";
19
+ import { publicLocalsNow } from "../server/request-event.ts";
19
20
  import { createTimer } from "./timing.ts";
20
21
 
21
22
  /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
@@ -605,6 +606,7 @@ export async function renderRoute(
605
606
  params: matched.params,
606
607
  data: mergedData,
607
608
  layoutData: layoutPairs.map((l) => l.data),
609
+ publicLocals: publicLocalsNow(),
608
610
  pattern: matched.route.path,
609
611
  deps: [...collectedDeps],
610
612
  form: actionFailure?.data,
@@ -705,6 +707,7 @@ export async function renderRoute(
705
707
  {
706
708
  data: mergedData ?? {},
707
709
  layoutData: layoutPairs.map((l) => l.data),
710
+ publicLocals: publicLocalsNow(),
708
711
  params: matched.params,
709
712
  pattern: matched.route.path,
710
713
  head: headHtml,
@@ -720,6 +723,7 @@ export async function renderRoute(
720
723
  params: matched.params,
721
724
  data: mergedData,
722
725
  layoutData: layoutPairs.map((l) => l.data),
726
+ publicLocals: publicLocalsNow(),
723
727
  pattern: matched.route.path,
724
728
  deps: [...collectedDeps],
725
729
  form: actionFailure?.data,
@@ -35,8 +35,8 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
35
35
  let ids: string[];
36
36
  let raw: Array<Array<string | number>>;
37
37
  try {
38
- ids = JSON.parse(call[1]);
39
- raw = JSON.parse(call[2]);
38
+ ids = JSON.parse(call[1]!);
39
+ raw = JSON.parse(call[2]!);
40
40
  } catch {
41
41
  return null;
42
42
  }
@@ -46,14 +46,14 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
46
46
  if (typeof file !== "string") return;
47
47
  nodes.set(id, {
48
48
  file,
49
- deps: deps.map((d) => ids[Number(d)]).filter(Boolean),
49
+ deps: deps.map((d) => ids[Number(d)]).filter((d): d is string => !!d),
50
50
  });
51
51
  });
52
52
  const routes = new Map<string, string>();
53
53
  for (const m of source.matchAll(
54
54
  /^\s*("(?:[^"\\]|\\.)*"):\s*\{\s*__lazy:\s*\(\)\s*=>\s*\(__preload\("([^"]+)"\)/gm,
55
55
  )) {
56
- routes.set(JSON.parse(m[1]), m[2]);
56
+ routes.set(JSON.parse(m[1]!), m[2]!);
57
57
  }
58
58
  return { routes, nodes };
59
59
  }
@@ -1,107 +1,114 @@
1
- import { transformSync } from "@babel/core";
2
- import type { ParserPlugin } from "@babel/parser";
3
- import sigilPlugin from "@sigil-dev/compiler/babel";
4
- import {
5
- computeHash,
6
- extractStyles,
7
- serverStyleSnippet,
8
- } from "@sigil-dev/compiler/css";
9
- import { log } from "../logger/instance";
10
- import { pinRuntime, rewriteAliases } from "../server/resolver";
11
- import type { GrimoirePlugin } from "../types";
12
-
13
- const logger = log.scope("scope");
14
- let registered = false;
15
-
16
- /**
17
- * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
18
- * to file paths in every compiled module: Bun's runtime plugins can't
19
- * resolve them for static imports.
20
- */
21
- export function registerSSRPlugin(
22
- plugins: GrimoirePlugin[] = [],
23
- aliases: Record<string, string> = {},
24
- ) {
25
- if (registered) return;
26
- registered = true;
27
-
28
- Bun.plugin({
29
- name: "sigil-ssr",
30
-
31
- setup(build) {
32
- // loader: "ts" not "tsx" — Babel already consumed the JSX,
33
- // Bun only needs to strip remaining TypeScript types
34
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
35
- build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
36
- try {
37
- const resolved = Bun.resolveSync(args.path, process.cwd());
38
- return { path: resolved.replaceAll("\\", "/") };
39
- } catch {
40
- return undefined;
41
- }
42
- });
43
-
44
- build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
45
- if (path.includes("index.tsx"))
46
- logger.debug("[ssr-plugin] onLoad:", path);
47
- const source = await Bun.file(path).text();
48
-
49
- // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
50
- // Still must return { contents, loader } — never return undefined from onLoad.
51
- if (path.includes("node_modules") || path.includes(".grimoire")) {
52
- return {
53
- contents: transpiler.transformSync(source),
54
- loader: "js" as const,
55
- };
56
- }
57
-
58
- if (process.env.SIGIL_VERBOSE) {
59
- logger.debug("[sigil-ssr] XFORM:", path);
60
- }
61
- // must match the client build, or scoped classes differ per side;
62
- // files without a <style> block get no scope class at all. The
63
- // CSS is registered for the renderer, which puts it in <head>.
64
- const styles = extractStyles(source, computeHash(path), path);
65
- const hash = styles.css ? computeHash(path) : undefined;
66
- const sourceNoStyle = styles.code;
67
- const result = transformSync(sourceNoStyle, {
68
- configFile: false,
69
- babelrc: false,
70
- parserOpts: {
71
- // The jsx plugin goes on .tsx files only.
72
- //
73
- // With it enabled everywhere, Babel parses `<R>(x: R) => x`
74
- // as the opening of a JSX element and fails with
75
- // "Unexpected token `>`". So a generic arrow function in a
76
- // plain .ts file — completely ordinary TypeScript — could
77
- // not be compiled. Found while writing the Drizzle adapter
78
- // recipe, where `transaction: <R>(db, fn) => ...` is the
79
- // form that removes an `as any`.
80
- //
81
- // A .tsx file is genuinely ambiguous (`<R>(x) => x` is
82
- // JSX there), so .tsx keeps both and users write `<R,>`.
83
- plugins: path.endsWith(".tsx")
84
- ? (["typescript", "jsx"] as ParserPlugin[])
85
- : (["typescript"] as ParserPlugin[]),
86
- },
87
- plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
88
- filename: path,
89
- });
90
-
91
- let contents = pinRuntime(
92
- rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
93
- );
94
- if (styles.css && hash) {
95
- contents = serverStyleSnippet(hash, styles.css) + contents;
96
- }
97
-
98
- for (const plugin of plugins) {
99
- if (plugin.transform)
100
- contents = (await plugin.transform(contents, path)) ?? contents;
101
- }
102
-
103
- return { contents, loader: "js" as const };
104
- });
105
- },
106
- });
107
- }
1
+ import { transformSync } from "@babel/core";
2
+ import type { ParserPlugin } from "@babel/parser";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import {
5
+ computeHash,
6
+ extractStyles,
7
+ serverStyleSnippet,
8
+ } from "@sigil-dev/compiler/css";
9
+ import { log } from "../logger/instance";
10
+ import { pinRuntime, rewriteAliases } from "../server/resolver";
11
+ import type { GrimoirePlugin } from "../types";
12
+
13
+ const logger = log.scope("scope");
14
+ let registered = false;
15
+ let current: { plugins: GrimoirePlugin[]; aliases: Record<string, string> } = { plugins: [], aliases: {} };
16
+
17
+ /**
18
+ * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
19
+ * to file paths in every compiled module: Bun's runtime plugins can't
20
+ * resolve them for static imports.
21
+ */
22
+ export function registerSSRPlugin(
23
+ plugins: GrimoirePlugin[] = [],
24
+ aliases: Record<string, string> = {},
25
+ ) {
26
+ // Registered once (Bun keeps every plugin), but a later call brings the
27
+ // app's real plugins and aliases: `sigil test` registers early with the
28
+ // defaults, so a test's own imports compile with Sigil's JSX, and the app
29
+ // fills in the rest when it starts.
30
+ current = { plugins, aliases };
31
+ if (registered) return;
32
+ registered = true;
33
+
34
+ Bun.plugin({
35
+ name: "sigil-ssr",
36
+
37
+ setup(build) {
38
+ // loader: "ts" not "tsx" — Babel already consumed the JSX,
39
+ // Bun only needs to strip remaining TypeScript types
40
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
41
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
42
+ try {
43
+ const resolved = Bun.resolveSync(args.path, process.cwd());
44
+ return { path: resolved.replaceAll("\\", "/") };
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ });
49
+
50
+ build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
51
+ const { plugins, aliases } = current;
52
+ if (path.includes("index.tsx"))
53
+ logger.debug("[ssr-plugin] onLoad:", path);
54
+ const source = await Bun.file(path).text();
55
+
56
+ // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
57
+ // Still must return { contents, loader } — never return undefined from onLoad.
58
+ if (path.includes("node_modules") || path.includes(".grimoire")) {
59
+ return {
60
+ contents: transpiler.transformSync(source),
61
+ loader: "js" as const,
62
+ };
63
+ }
64
+
65
+ if (process.env.SIGIL_VERBOSE) {
66
+ logger.debug("[sigil-ssr] XFORM:", path);
67
+ }
68
+ // must match the client build, or scoped classes differ per side;
69
+ // files without a <style> block get no scope class at all. The
70
+ // CSS is registered for the renderer, which puts it in <head>.
71
+ const styles = extractStyles(source, computeHash(path), path);
72
+ const hash = styles.css ? computeHash(path) : undefined;
73
+ const sourceNoStyle = styles.code;
74
+ const result = transformSync(sourceNoStyle, {
75
+ configFile: false,
76
+ babelrc: false,
77
+ parserOpts: {
78
+ // The jsx plugin goes on .tsx files only.
79
+ //
80
+ // With it enabled everywhere, Babel parses `<R>(x: R) => x`
81
+ // as the opening of a JSX element and fails with
82
+ // "Unexpected token `>`". So a generic arrow function in a
83
+ // plain .ts file — completely ordinary TypeScript — could
84
+ // not be compiled. Found while writing the Drizzle adapter
85
+ // recipe, where `transaction: <R>(db, fn) => ...` is the
86
+ // form that removes an `as any`.
87
+ //
88
+ // A .tsx file is genuinely ambiguous (`<R>(x) => x` is
89
+ // JSX there), so .tsx keeps both and users write `<R,>`.
90
+ plugins: path.endsWith(".tsx")
91
+ ? (["typescript", "jsx"] as ParserPlugin[])
92
+ : (["typescript"] as ParserPlugin[]),
93
+ },
94
+ plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
95
+ filename: path,
96
+ });
97
+
98
+ let contents = pinRuntime(
99
+ rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
100
+ );
101
+ if (styles.css && hash) {
102
+ contents = serverStyleSnippet(hash, styles.css) + contents;
103
+ }
104
+
105
+ for (const plugin of plugins) {
106
+ if (plugin.transform)
107
+ contents = (await plugin.transform(contents, path)) ?? contents;
108
+ }
109
+
110
+ return { contents, loader: "js" as const };
111
+ });
112
+ },
113
+ });
114
+ }
@@ -28,7 +28,7 @@ export function createTimer(): Timer {
28
28
  marks.push([name, now - last]);
29
29
  last = now;
30
30
  },
31
- headers() {
31
+ headers(): Record<string, string> {
32
32
  if (!enabled || marks.length === 0) return {};
33
33
  return {
34
34
  "Server-Timing": marks
@@ -102,6 +102,26 @@ export function filePathToRoutePath(
102
102
 
103
103
  const TEST_FILE = /[._](test|spec)\.[jt]sx?$/;
104
104
 
105
+ /** How loosely a pattern segment matches: fixed text, a param, an optional one, the rest. */
106
+ const segmentRank = (seg: string) =>
107
+ seg.startsWith("*") ? 3 : seg.endsWith("?") ? 2 : seg.startsWith(":") ? 1 : 0;
108
+
109
+ /**
110
+ * Between routes that score the same, the one that is more specific earlier
111
+ * in the path goes first: /wiki/_history/*page before /wiki/*page, though
112
+ * both have one rest param. Without this, ties fell to the order the
113
+ * filesystem listed the folders in, which differs between machines.
114
+ */
115
+ export function byShape(a: string, b: string): number {
116
+ const as = a.split("/").filter(Boolean);
117
+ const bs = b.split("/").filter(Boolean);
118
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
119
+ const d = segmentRank(as[i]!) - segmentRank(bs[i]!);
120
+ if (d) return d;
121
+ }
122
+ return bs.length - as.length || (a < b ? -1 : a > b ? 1 : 0);
123
+ }
124
+
105
125
  export async function scanRoutes(
106
126
  routesDir: string,
107
127
  viteRoot: string = routesDir,
@@ -170,8 +190,10 @@ export async function scanRoutes(
170
190
  r.paramNames.length * 2 +
171
191
  r.optionalParamNames.length +
172
192
  r.restParamNames.length * 1000;
173
- routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
174
- servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
193
+ const byScore = (a: RouteFile, b: RouteFile) =>
194
+ scoreRoute(a) - scoreRoute(b) || byShape(a.path, b.path);
195
+ routes.sort(byScore);
196
+ servers.sort(byScore);
175
197
 
176
198
  assertNoDuplicatePaths(
177
199
  routes.filter((r) => r.type === "page" || r.type === "simple"),
@@ -51,7 +51,7 @@ async function waitForWorkers(
51
51
 
52
52
  function roundRobin(workers: WorkerDescriptor[]): WorkerDescriptor {
53
53
  const idx = roundRobinCounter++ % workers.length;
54
- return workers[idx];
54
+ return workers[idx]!;
55
55
  }
56
56
  let roundRobinCounter = 0;
57
57
 
@@ -63,7 +63,7 @@ function consistentHash(
63
63
  let hash = 0;
64
64
  for (let i = 0; i < key.length; i++)
65
65
  hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
66
- return workers[hash % workers.length];
66
+ return workers[hash % workers.length]!;
67
67
  }
68
68
 
69
69
  function defaultRoute(
@@ -86,7 +86,7 @@ function defaultRoute(
86
86
  (w) => w.mode === "frontend" || w.mode === "full",
87
87
  );
88
88
  if (frontend.length) return roundRobin(frontend);
89
- return workers[0];
89
+ return workers[0]!;
90
90
  }
91
91
 
92
92
  export interface ScaleSpec {
@@ -226,7 +226,7 @@ export async function startCoordinator(options: CoordinatorOptions) {
226
226
  index: i + 1,
227
227
  globalIndex: globalIndex++,
228
228
  internalUrl: `http://127.0.0.1:${workerPort}`,
229
- routes: slices[mode] ?? slices.full,
229
+ routes: slices[mode] ?? slices.full ?? [],
230
230
  };
231
231
 
232
232
  const publicEnvVars: Record<string, string> = {};
@@ -311,7 +311,8 @@ export async function startCoordinator(options: CoordinatorOptions) {
311
311
  return new Response("Upgrade Required", { status: 426 });
312
312
  }
313
313
 
314
- const locals: App.Locals = {};
314
+ // filled in by the plugins' handles before anything reads it
315
+ const locals = {} as App.Locals;
315
316
  const descriptors = liveWorkers.map((w) => w.descriptor);
316
317
  const chosen =
317
318
  (await runRouteRequest(plugins, req, descriptors, tree)) ??
@@ -54,6 +54,7 @@ import {
54
54
  } from "./plugins";
55
55
  import { contentHash, splitHashedCss } from "./public-assets";
56
56
  import { RESERVED_EXPORTS } from "./reserved";
57
+ import { runWithEvent, setPublicLocals } from "./request-event.ts";
57
58
  import { projectAliases, resolverPlugin } from "./resolver";
58
59
  import { applyRewriters } from "./rewrite";
59
60
  import { preloadModules, startWarming, type Warmer } from "./warm.ts";
@@ -187,6 +188,7 @@ async function loadHooks(projectRoot: string): Promise<{
187
188
  init?: InitFunction;
188
189
  handleError?: HandleError;
189
190
  handleFetch?: HandleFetch;
191
+ publicLocals?: (locals: App.Locals) => unknown;
190
192
  }> {
191
193
  const hooksPath = `${projectRoot}/hooks.server.ts`;
192
194
  // no hooks file is fine; a hooks file that fails to load is not, and
@@ -198,6 +200,7 @@ async function loadHooks(projectRoot: string): Promise<{
198
200
  init: mod.init,
199
201
  handleError: mod.handleError,
200
202
  handleFetch: mod.handleFetch,
203
+ publicLocals: typeof mod.publicLocals === "function" ? mod.publicLocals : undefined,
201
204
  };
202
205
  }
203
206
 
@@ -434,7 +437,9 @@ export async function createApp(
434
437
  init: hooksInit,
435
438
  handleError: hooksHandleError,
436
439
  handleFetch: hooksHandleFetch,
440
+ publicLocals: hooksPublicLocals,
437
441
  } = await loadHooks(process.cwd());
442
+ setPublicLocals(hooksPublicLocals);
438
443
 
439
444
  const hooksHandle = composeHandle(plugins, appHandle);
440
445
 
@@ -479,14 +484,13 @@ export async function createApp(
479
484
  const rawLocals = finalConfig._behindCoordinator
480
485
  ? req.headers.get("X-Grimoire-Locals")
481
486
  : null;
482
- const locals: App.Locals = rawLocals
483
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
484
- : {};
487
+ // filled in by the plugins' handles before anything reads it
488
+ const locals = (rawLocals ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {}) : {}) as App.Locals;
485
489
  // Plugin services sit under the request's own locals: what the app
486
490
  // set (a session, a user) always wins over what a plugin declared,
487
491
  // so a plugin cannot clobber auth by defining a common key.
488
492
  for (const [key, value] of Object.entries(services)) {
489
- if (!(key in locals)) locals[key] = value;
493
+ if (!(key in locals)) (locals as unknown as Record<string, unknown>)[key] = value;
490
494
  }
491
495
  const url = new URL(req.url);
492
496
 
@@ -639,7 +643,7 @@ export async function createApp(
639
643
  ] as const;
640
644
 
641
645
  // Build event BEFORE matching — handle() runs pre-match like SvelteKit
642
- trackClientAddress(req, server);
646
+ trackClientAddress(req, server ?? null);
643
647
  const cookieHeader = req.headers.get("cookie") ?? "";
644
648
  const cookies = createCookies(cookieHeader);
645
649
  const setHeadersMap: Record<string, string> = {};
@@ -664,13 +668,13 @@ export async function createApp(
664
668
  );
665
669
  };
666
670
  }
667
- const patchedFetch: typeof fetch = (input, init) => {
671
+ const patchedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
668
672
  const resolved =
669
673
  typeof input === "string" && input.startsWith("/")
670
674
  ? new URL(input, url.origin).toString()
671
675
  : input;
672
676
  return globalThis.fetch(resolved as any, init);
673
- };
677
+ }) as typeof fetch;
674
678
  const resolve: ResolveFunction = async (evt) => {
675
679
  // matching happens here — after handle() has run
676
680
  let matched = matchRoute(tree, evt.url, paramMatcherFns);
@@ -737,7 +741,7 @@ export async function createApp(
737
741
  locals: evt.locals,
738
742
  fetch: patchedFetch,
739
743
  cookies,
740
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
744
+ setHeaders: (headers: Record<string, string>) => Object.assign(setHeadersMap, headers),
741
745
  getClientAddress: () => clientAddressOf(evt.request),
742
746
  });
743
747
  } catch (e) {
@@ -748,6 +752,24 @@ export async function createApp(
748
752
  headers: { Location: e.location },
749
753
  });
750
754
  }
755
+ // so do a thrown Response and `throw error(404, "…")`: a helper the
756
+ // endpoint shares with pages (a "load the repo or 404" one, say) must
757
+ // not turn its 404 into a 500 here
758
+ if (e instanceof Response) return e;
759
+ if (isErrorResult(e)) {
760
+ const json = evt.request.headers
761
+ .get("accept")
762
+ ?.includes("application/json");
763
+ return json
764
+ ? Response.json(
765
+ { error: true, status: e.status, message: e.message },
766
+ { status: e.status },
767
+ )
768
+ : new Response(`${e.message}\n`, {
769
+ status: e.status,
770
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
771
+ });
772
+ }
751
773
  throw e;
752
774
  }
753
775
  }
@@ -971,11 +993,11 @@ export async function createApp(
971
993
 
972
994
  let response: Response;
973
995
  try {
974
- if (!hooksHandle) {
975
- response = await resolve(event);
976
- } else {
977
- response = await hooksHandle({ event, resolve });
978
- }
996
+ // getRequestEvent() and publicLocals() see this request from here on,
997
+ // through handle, loads, actions, endpoints and rendering
998
+ response = await runWithEvent(event, () =>
999
+ hooksHandle ? hooksHandle({ event, resolve }) : resolve(event),
1000
+ );
979
1001
  } catch (err) {
980
1002
  logger.error(
981
1003
  `${event.request.method} ${event.url.pathname} failed:`,
@@ -1110,7 +1132,7 @@ export async function createApp(
1110
1132
  };
1111
1133
 
1112
1134
  return {
1113
- fetch: fetchUnderBase,
1135
+ fetch: async (req: Request) => fetchUnderBase(req),
1114
1136
  websocket,
1115
1137
  tree,
1116
1138
  matchers: paramMatcherFns,
@@ -101,9 +101,7 @@ export async function runWorkerSpawn(
101
101
  const merged: WorkerEnv = { env: {} };
102
102
  for (const plugin of plugins) {
103
103
  const result = await plugin.onWorkerSpawn?.(worker);
104
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
105
104
  if (result?.env) Object.assign(merged.env!, result.env);
106
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
107
105
  if (result?.name) merged.name = result.name;
108
106
  }
109
107
  return merged;
@@ -0,0 +1,53 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { RequestEvent } from "./hooks.ts";
3
+ import { setPageUrlSource, setPublicLocalsSource } from "../locals.ts";
4
+
5
+ /**
6
+ * The request being served, for code that runs during it but isn't handed
7
+ * the event: a helper three calls deep, a formatter shared with the browser.
8
+ * Set around hooks.server.ts's handle(), so handle, loads, actions,
9
+ * endpoints and rendering all see it, and so does anything they await.
10
+ */
11
+ const store = new AsyncLocalStorage<RequestEvent>();
12
+
13
+ /**
14
+ * The current request's event, or undefined outside one (startup, a job,
15
+ * a script, a test calling a function directly). Server only.
16
+ *
17
+ * ```ts
18
+ * import { getRequestEvent } from "@sigil-dev/grimoire/server";
19
+ * const user = getRequestEvent()?.locals.user;
20
+ * ```
21
+ */
22
+ export function getRequestEvent(): RequestEvent | undefined {
23
+ return store.getStore();
24
+ }
25
+
26
+ /** Runs `fn` with `event` as the current request. */
27
+ export function runWithEvent<T>(event: RequestEvent, fn: () => T): T {
28
+ return store.run(event, fn);
29
+ }
30
+
31
+ type PublicLocalsFn = (locals: App.Locals) => unknown;
32
+ let toPublic: PublicLocalsFn | undefined;
33
+ const computed = new WeakMap<RequestEvent, unknown>();
34
+
35
+ /** hooks.server.ts's `publicLocals`, which says what of locals the browser may see. */
36
+ export function setPublicLocals(fn: PublicLocalsFn | undefined): void {
37
+ toPublic = fn;
38
+ }
39
+
40
+ /**
41
+ * This request's public locals: what hooks.server.ts's `publicLocals(locals)`
42
+ * returned, once per request. Undefined without that export or a request.
43
+ * Sent to the browser with the page, so `publicLocals()` reads the same there.
44
+ */
45
+ export function publicLocalsNow(): unknown {
46
+ const event = store.getStore();
47
+ if (!event || !toPublic) return undefined;
48
+ if (!computed.has(event)) computed.set(event, toPublic(event.locals));
49
+ return computed.get(event);
50
+ }
51
+
52
+ setPublicLocalsSource(publicLocalsNow);
53
+ setPageUrlSource(() => store.getStore()?.url);
@@ -161,7 +161,7 @@ export function context(options: ContextOptions = {}) {
161
161
  request,
162
162
  url,
163
163
  params: options.params ?? {},
164
- locals: (options.locals ?? {}) as App.Locals,
164
+ locals: (options.locals ?? {}) as unknown as App.Locals,
165
165
  cookies,
166
166
  fetch: options.fetch ?? globalThis.fetch,
167
167
  parent: async () => options.parent ?? {},
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Preloaded by `sigil test` for `*.server.test.ts` files.
3
+ *
4
+ * Bun compiles a test file's static imports before any of its code runs, so
5
+ * server code a test imports directly (a module that renders a mail
6
+ * template, say) would be compiled before `createTestApp()` sets up Sigil's
7
+ * compiler, and its `.tsx` would get React's JSX. Registering the compiler
8
+ * here, first, means it compiles the same as when the app loads it. The app
9
+ * adds its plugins and aliases when it starts.
10
+ */
11
+ import { registerSSRPlugin } from "../rendering/ssrPlugin";
12
+ import { projectAliases } from "../server/resolver";
13
+
14
+ registerSSRPlugin([], projectAliases({}));
@@ -433,14 +433,31 @@ function generateAmbient(): string {
433
433
  export function generateLocals(outDir: string, configFile: string): string {
434
434
  let path = toImportPath(outDir, configFile);
435
435
  if (!path.startsWith(".")) path = `./${path}`;
436
+ // publicLocals() is typed from what hooks.server.ts's publicLocals returns
437
+ const hooksFile = join(dirname(configFile), "hooks.server.ts");
438
+ const hasPublic =
439
+ existsSync(hooksFile) &&
440
+ /export\s+(?:const|function|async\s+function|let)\s+publicLocals\b/.test(
441
+ readFileSync(hooksFile, "utf8"),
442
+ );
443
+ let hooksPath = toImportPath(outDir, hooksFile);
444
+ if (!hooksPath.startsWith(".")) hooksPath = `./${hooksPath}`;
436
445
  return [
437
446
  "// Auto-generated by @sigil-dev/grimoire — do not edit",
438
447
  'import type { PluginLocals } from "@sigil-dev/grimoire";',
439
448
  `import type config from "${path}";`,
449
+ ...(hasPublic
450
+ ? [`import type { publicLocals as _publicLocals } from "${hooksPath}";`]
451
+ : []),
440
452
  "",
441
453
  "declare global {",
442
454
  " namespace App {",
443
455
  " interface Locals extends PluginLocals<typeof config> {}",
456
+ ...(hasPublic
457
+ ? [
458
+ " interface PublicLocals extends Awaited<ReturnType<typeof _publicLocals>> {}",
459
+ ]
460
+ : []),
444
461
  " }",
445
462
  "}",
446
463
  "",
@@ -489,6 +506,24 @@ function runtimeEntry(): string | undefined {
489
506
  }
490
507
  }
491
508
 
509
+ /**
510
+ * Only .grimoire/tsconfig.generated.json, with these aliases: what the CLI
511
+ * writes in a fresh checkout so the config can load, before the full
512
+ * generateTypes (which needs the loaded config) can run.
513
+ */
514
+ export function writeTsConfig(
515
+ projectRoot: string,
516
+ aliases: Record<string, string>,
517
+ ): void {
518
+ const grimoireDir = join(projectRoot, ".grimoire");
519
+ mkdirSync(grimoireDir, { recursive: true });
520
+ writeFileSync(
521
+ join(grimoireDir, "tsconfig.generated.json"),
522
+ generateTsConfig(aliases, grimoireDir),
523
+ "utf-8",
524
+ );
525
+ }
526
+
492
527
  function generateTsConfig(
493
528
  aliases: Record<string, string>,
494
529
  grimoireDir: string,
package/src/types.ts CHANGED
@@ -29,6 +29,8 @@ declare global {
29
29
  namespace App {
30
30
  // augment in your own project via src/app.d.ts
31
31
  interface Locals {}
32
+ /** What hooks.server.ts's `publicLocals` returns: read with publicLocals(), server and browser. */
33
+ interface PublicLocals {}
32
34
  interface Error {
33
35
  message: string;
34
36
  status?: number;
@@ -0,0 +1,73 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { publicLocals } from "../src/locals";
6
+ import { createApp } from "../src/server";
7
+ import { getRequestEvent, setPublicLocals } from "../src/server/request-event";
8
+ import type { GrimoirePlugin } from "../src/types";
9
+
10
+ /**
11
+ * getRequestEvent(): the request being served, for code that isn't handed the
12
+ * event. publicLocals(): what hooks.server.ts's publicLocals returns for it,
13
+ * which the page state carries to the browser.
14
+ */
15
+
16
+ let dir: string;
17
+ const SRC = join(import.meta.dir, "..", "src");
18
+
19
+ beforeAll(async () => {
20
+ dir = join(tmpdir(), `grimoire-event-${Date.now()}`);
21
+ await mkdir(join(dir, "who"), { recursive: true });
22
+ // a helper deep in the app: no event passed in
23
+ await writeFile(
24
+ join(dir, "helper.ts"),
25
+ `import { getRequestEvent } from ${JSON.stringify(join(SRC, "server/request-event.ts"))};
26
+ import { publicLocals } from ${JSON.stringify(join(SRC, "locals.ts"))};
27
+ export async function whoIsAsking() {
28
+ await new Promise((r) => setTimeout(r, 5)); // across an await too
29
+ const e = getRequestEvent();
30
+ return { path: e?.url.pathname ?? null, user: e?.locals.user ?? null, pub: publicLocals() ?? null };
31
+ }`,
32
+ );
33
+ await writeFile(
34
+ join(dir, "who", "+server.ts"),
35
+ `import { whoIsAsking } from "../helper.ts";
36
+ export async function GET() { return Response.json(await whoIsAsking()); }`,
37
+ );
38
+ });
39
+
40
+ afterAll(() => {
41
+ setPublicLocals(undefined);
42
+ return rm(dir, { recursive: true, force: true });
43
+ });
44
+
45
+ const signIn: GrimoirePlugin = {
46
+ name: "sign-in",
47
+ handle: async ({ event, resolve }) => {
48
+ (event.locals as Record<string, unknown>).user = event.url.searchParams.get("as");
49
+ (event.locals as Record<string, unknown>).zone = "Europe/Belgrade";
50
+ return resolve(event);
51
+ },
52
+ };
53
+
54
+ describe("getRequestEvent and publicLocals", () => {
55
+ test("outside a request: nothing", () => {
56
+ expect(getRequestEvent()).toBeUndefined();
57
+ expect(publicLocals()).toBeUndefined();
58
+ });
59
+
60
+ test("a helper sees the request it runs in, and only that one", async () => {
61
+ const app = await createApp({ routes: dir, _skipBuild: true, plugins: [signIn] });
62
+ // what loading hooks.server.ts's `publicLocals` export does (there's none in this cwd)
63
+ setPublicLocals((l) => ({ zone: (l as Record<string, unknown>).zone }));
64
+ const [a, b] = await Promise.all([
65
+ app.fetch(new Request("http://localhost/who?as=ann")).then((r) => r.json()),
66
+ app.fetch(new Request("http://localhost/who?as=bob")).then((r) => r.json()),
67
+ ]);
68
+ expect(a).toEqual({ path: "/who", user: "ann", pub: { zone: "Europe/Belgrade" } });
69
+ expect(b).toEqual({ path: "/who", user: "bob", pub: { zone: "Europe/Belgrade" } });
70
+ // and the scope ends with the request
71
+ expect(getRequestEvent()).toBeUndefined();
72
+ });
73
+ });
@@ -0,0 +1,12 @@
1
+ import { expect, test } from "bun:test";
2
+ import { join } from "node:path";
3
+
4
+ // A component that calls invalidate() is rendered on the server too, so the
5
+ // router module gets imported there, where there's no `location`. A process
6
+ // of its own: this test run has a DOM, and may have imported the router already.
7
+ test("the client router can be imported where there's no browser", () => {
8
+ const router = join(import.meta.dir, "../src/client/router.ts");
9
+ const p = Bun.spawnSync([process.execPath, "-e", `const m = await import(${JSON.stringify(router)}); if (typeof location !== "undefined") throw new Error("has a browser"); console.log(typeof m.invalidateAll)`], { stdout: "pipe", stderr: "pipe" });
10
+ expect(p.stderr.toString()).toBe("");
11
+ expect(p.stdout.toString().trim()).toBe("function");
12
+ });
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
2
  import { mkdir, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { filePathToRoutePath, scanRoutes } from "../src/routing/scanner";
5
+ import { byShape, filePathToRoutePath, scanRoutes } from "../src/routing/scanner";
6
6
 
7
7
  describe("File scanning", () => {
8
8
  test("index.tsx → /", () => {
@@ -367,3 +367,28 @@ describe("Duplicate route detection", () => {
367
367
  );
368
368
  });
369
369
  });
370
+
371
+ describe("Routes that score the same", () => {
372
+ test("the more specific one first, whatever order the folders are listed in", async () => {
373
+ // a rest param under a fixed folder vs a rest param right away: both
374
+ // score one rest param, and used to fall to readdir order
375
+ const root = join(tmpdir(), `grimoire-ties-${Date.now()}`);
376
+ const dirs = ["wiki/[...page]", "wiki/_history/[...page]", "wiki/_edit/[...page]", "wiki/_raw/[...path]"];
377
+ for (const d of dirs) {
378
+ await mkdir(join(root, d), { recursive: true });
379
+ await writeFile(join(root, d, "+page.tsx"), "export default () => null");
380
+ }
381
+ const tree = await scanRoutes(root);
382
+ const order = tree.routes.map((r) => r.path);
383
+ expect(order.indexOf("/wiki/*page")).toBe(order.length - 1);
384
+ expect(order.slice(0, 3).sort()).toEqual(["/wiki/_edit/*page", "/wiki/_history/*page", "/wiki/_raw/*path"]);
385
+ await rm(root, { recursive: true });
386
+ });
387
+
388
+ test("byShape: fixed text before params before the rest, segment by segment", () => {
389
+ expect(byShape("/a/_x/*p", "/a/*p")).toBeLessThan(0);
390
+ expect(byShape("/:o/:r/b", "/:o/:r/:x")).toBeLessThan(0);
391
+ expect(byShape("/a/:x?", "/a/:x")).toBeGreaterThan(0);
392
+ expect(byShape("/a/b", "/a/b")).toBe(0);
393
+ });
394
+ });
@@ -19,6 +19,7 @@ import {
19
19
  tick,
20
20
  } from "@sigil-dev/runtime";
21
21
  import { withEffectScope } from "../src/client/scope.ts";
22
+ import { Window } from "happy-dom";
22
23
 
23
24
  describe("grimoire withEffectScope", () => {
24
25
  test("effects inside scope stop after dispose", async () => {
@@ -157,6 +158,10 @@ describe("grimoire withEffectScope", () => {
157
158
  });
158
159
  });
159
160
 
161
+ // these two only need elements to put in the pool: a DOM of their own, so they
162
+ // run the same from the repo root (whose preload has one) and from here
163
+ const doc = (globalThis as { document?: Document }).document ?? (new Window().document as unknown as Document);
164
+
160
165
  describe("__nodes pool reset on SPA navigation", () => {
161
166
  test("navigate sets __nodes to [] before calling Page()", () => {
162
167
  // Simulate exactly what router.ts's navigate() does:
@@ -166,7 +171,7 @@ describe("__nodes pool reset on SPA navigation", () => {
166
171
 
167
172
  const mockPage = () => {
168
173
  nodesAtCallTime = (globalThis as any).__nodes;
169
- return document.createElement("div"); // satisfy replaceChildren
174
+ return doc.createElement("div"); // satisfy replaceChildren
170
175
  };
171
176
  // Mimic the three lines in navigate() that matter
172
177
  (globalThis as any).__nodes = ["stale", "dom", "nodes"]; // leftover from previous page
@@ -178,7 +183,7 @@ describe("__nodes pool reset on SPA navigation", () => {
178
183
 
179
184
  test("Page() called during SSR hydration sees real DOM nodes, not empty pool", () => {
180
185
  // Contrast: hydrate.ts sets __nodes to Array.from(slot.childNodes) before calling Page()
181
- const fakeSlotChild = document.createElement("div");
186
+ const fakeSlotChild = doc.createElement("div");
182
187
  let nodesAtCallTime: unknown = "not set";
183
188
 
184
189
  const mockPage = () => {
@@ -23,6 +23,7 @@ beforeAll(async () => {
23
23
  await mkdir(join(tmpDir, "api", "hello"), { recursive: true });
24
24
  await mkdir(join(tmpDir, "api", "items"), { recursive: true });
25
25
  await mkdir(join(tmpDir, "api", "away"), { recursive: true });
26
+ await mkdir(join(tmpDir, "api", "gone"), { recursive: true });
26
27
 
27
28
  await writeFile(
28
29
  join(tmpDir, "api", "hello", "+server.ts"),
@@ -40,6 +41,17 @@ beforeAll(async () => {
40
41
  }`,
41
42
  );
42
43
 
44
+ // what error(404, "No such thing") throws, and a thrown Response
45
+ await writeFile(
46
+ join(tmpDir, "api", "gone", "+server.ts"),
47
+ `export async function GET() {
48
+ throw { __error: true, status: 404, message: "No such thing" };
49
+ }
50
+ export async function POST() {
51
+ throw new Response("I'm a teapot", { status: 418 });
52
+ }`,
53
+ );
54
+
43
55
  // what redirect(303, "/login") throws
44
56
  await writeFile(
45
57
  join(tmpDir, "api", "away", "+server.ts"),
@@ -107,6 +119,24 @@ describe("Server — API routes (+server.ts)", () => {
107
119
  server.stop();
108
120
  });
109
121
 
122
+ test("a thrown error() keeps its status, as text or JSON; a thrown Response is the reply", async () => {
123
+ const server = await createServer({
124
+ port: 3004,
125
+ routes: tmpDir,
126
+ _skipBuild: true,
127
+ });
128
+ let res = await fetch("http://localhost:3004/api/gone");
129
+ expect(res.status).toBe(404);
130
+ expect(await res.text()).toBe("No such thing\n");
131
+ res = await fetch("http://localhost:3004/api/gone", { headers: { Accept: "application/json" } });
132
+ expect(res.status).toBe(404);
133
+ expect(await res.json()).toEqual({ error: true, status: 404, message: "No such thing" });
134
+ res = await fetch("http://localhost:3004/api/gone", { method: "POST" });
135
+ expect(res.status).toBe(418);
136
+ expect(await res.text()).toBe("I'm a teapot");
137
+ server.stop();
138
+ });
139
+
110
140
  test("maxRequestBodySize caps request bodies", async () => {
111
141
  const server = await createServer({
112
142
  port: 3004,
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { execFileSync } from "node:child_process";
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
3
4
  import { existsSync, readdirSync, readFileSync } from "node:fs";
4
5
  import { dirname, join, normalize, relative } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
@@ -103,31 +104,27 @@ function reachable(dir: string, entries: string[]): Set<string> {
103
104
  return seen;
104
105
  }
105
106
 
106
- function packedFiles(dir: string): Set<string> {
107
- const out = execFileSync(
108
- "npm",
109
- ["pack", "--dry-run", "--json", "--ignore-scripts"],
110
- {
111
- cwd: dir,
112
- encoding: "utf8",
113
- stdio: ["ignore", "pipe", "ignore"],
114
- },
115
- );
116
- const [report] = JSON.parse(out) as Array<{ files: Array<{ path: string }> }>;
107
+ // npm pack takes seconds a package; they run side by side so the whole
108
+ // workspace fits the timeout on a slow machine too
109
+ async function packedFiles(dir: string): Promise<Set<string>> {
110
+ const { stdout } = await promisify(execFile)("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
111
+ const [report] = JSON.parse(stdout) as Array<{ files: Array<{ path: string }> }>;
117
112
  return new Set(report!.files.map((f) => normalize(join(dir, f.path))));
118
113
  }
119
114
 
120
115
  describe("workspace files", () => {
121
- test("every file an entry point imports is in the tarball", () => {
116
+ test("every file an entry point imports is in the tarball", async () => {
122
117
  const missing: string[] = [];
123
- for (const { dir, manifest } of shipped()) {
118
+ const packages = shipped();
119
+ const packs = await Promise.all(packages.map(({ dir }) => packedFiles(dir)));
120
+ for (const [i, { dir, manifest }] of packages.entries()) {
124
121
  const entries = [
125
122
  ...(manifest.module ? [manifest.module] : []),
126
123
  ...(manifest.main ? [manifest.main] : []),
127
124
  ...exportTargets(manifest.bin),
128
125
  ...exportTargets(manifest.exports),
129
126
  ];
130
- const packed = packedFiles(dir);
127
+ const packed = packs[i]!;
131
128
  for (const file of reachable(dir, entries)) {
132
129
  if (!packed.has(file)) {
133
130
  missing.push(
@@ -137,7 +134,7 @@ describe("workspace files", () => {
137
134
  }
138
135
  }
139
136
  expect(missing).toEqual([]);
140
- }, 60_000);
137
+ }, 120_000);
141
138
 
142
139
  test("no relative import points at a file that does not exist", () => {
143
140
  // A type-only import of a missing file still runs, because Bun erases
@@ -95,20 +95,14 @@ describe("workspace versions", () => {
95
95
  expect(mismatches).toEqual([]);
96
96
  });
97
97
 
98
- test("every shipped package is at the same version", () => {
99
- // Two packages at different versions means a `workspace:*` between
100
- // them resolves to whichever one the lockfile saw, which is how a
101
- // packed dependency ends up pointing at a version nothing claims.
102
- const distinct = [
103
- ...new Set(shipped().map(({ manifest }) => manifest.version)),
104
- ];
105
- expect(
106
- distinct.length === 1
107
- ? []
108
- : [
109
- `packages sit at ${distinct.join(", ")} — a release moves them together`,
110
- ],
111
- ).toEqual([]);
98
+ test("core is at one version", () => {
99
+ // Core pins core exactly, so two core packages at different versions
100
+ // means a `workspace:*` between them resolves to whichever one the
101
+ // lockfile saw, which is how a packed dependency ends up pointing at a
102
+ // version nothing claims. Plugins version on their own (scripts/release-plan.ts).
103
+ const CORE = ["runtime", "compiler", "grimoire", "cli", "types"];
104
+ const distinct = [...new Set(shipped().filter(({ dir }) => CORE.includes(dir)).map(({ manifest }) => manifest.version))];
105
+ expect(distinct.length === 1 ? [] : [`core packages sit at ${distinct.join(", ")}; a release moves them together`]).toEqual([]);
112
106
  });
113
107
 
114
108
  test("the release version is not already published with other content", async () => {
@@ -120,7 +114,7 @@ describe("workspace versions", () => {
120
114
  //
121
115
  // So a version is only safe to depend on once it is published *with*
122
116
  // this content. Until then a consumer resolves to the older tarball.
123
- const version = shipped()[0]?.manifest.version;
117
+ const version = shipped().find(({ dir }) => dir === "grimoire")?.manifest.version;
124
118
  if (!version) return;
125
119
 
126
120
  // Registry access is best-effort: a suite that needs the network to