@sigil-dev/grimoire 0.9.32 → 0.10.0

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.
@@ -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