@sigil-dev/grimoire 0.3.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.
Files changed (52) hide show
  1. package/.grimoire/_routes.dom.js +4 -0
  2. package/.grimoire/_routes.hydrate.js +4 -0
  3. package/.grimoire/_routes.ts +4 -0
  4. package/.grimoire/tsconfig.generated.json +11 -0
  5. package/.grimoire/types/ambient.d.ts +6 -0
  6. package/.grimoire/types/api/hello/$types.d.ts +29 -0
  7. package/README.md +1 -0
  8. package/index.ts +22 -0
  9. package/package.json +36 -0
  10. package/public/__grimoire__/client.js +86 -0
  11. package/public/__grimoire__/hydrate.js +101 -0
  12. package/src/client-router.ts +77 -0
  13. package/src/client.ts +4 -0
  14. package/src/context.ts +10 -0
  15. package/src/cookie-utils.ts +66 -0
  16. package/src/enhance.ts +97 -0
  17. package/src/error.ts +52 -0
  18. package/src/fail.ts +41 -0
  19. package/src/head.ts +27 -0
  20. package/src/headers.ts +114 -0
  21. package/src/hooks.ts +93 -0
  22. package/src/hydrate.ts +22 -0
  23. package/src/manifest-gen.ts +26 -0
  24. package/src/plugins.ts +25 -0
  25. package/src/redirect.ts +35 -0
  26. package/src/renderer.ts +142 -0
  27. package/src/router.ts +94 -0
  28. package/src/scanner.ts +97 -0
  29. package/src/scope.ts +22 -0
  30. package/src/server.ts +318 -0
  31. package/src/ssrPlugin.ts +26 -0
  32. package/src/sync.ts +18 -0
  33. package/src/transform-routes.ts +90 -0
  34. package/src/typegen.ts +263 -0
  35. package/src/types.ts +85 -0
  36. package/src/vite-plugin.ts +72 -0
  37. package/test/context.test.ts +52 -0
  38. package/test/fail.test.ts +46 -0
  39. package/test/headers.test.ts +96 -0
  40. package/test/hydration.test.ts +119 -0
  41. package/test/middleware.test.ts +217 -0
  42. package/test/preload.ts +5 -0
  43. package/test/redirect-error.test.ts +112 -0
  44. package/test/rendering.test.ts +172 -0
  45. package/test/routing.test.ts +45 -0
  46. package/test/scanning.test.ts +55 -0
  47. package/test/scope.test.ts +164 -0
  48. package/test/server.test.ts +30 -0
  49. package/test/streaming.test.ts +132 -0
  50. package/test/transform-routes.test.ts +84 -0
  51. package/test/typegen.test.ts +652 -0
  52. package/tsconfig.json +7 -0
@@ -0,0 +1,55 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { filePathToRoutePath } from "../src/scanner";
3
+
4
+ describe("File scanning", () => {
5
+ test("index.tsx → /", () => {
6
+ expect(filePathToRoutePath("/app/routes/index.tsx", "/app/routes")).toEqual(
7
+ { pattern: "/", params: [] },
8
+ );
9
+ });
10
+
11
+ test("about.tsx → /about", () => {
12
+ expect(filePathToRoutePath("/app/routes/about.tsx", "/app/routes")).toEqual(
13
+ { pattern: "/about", params: [] },
14
+ );
15
+ });
16
+
17
+ test("[slug].tsx → /:slug", () => {
18
+ expect(
19
+ filePathToRoutePath("/app/routes/[slug].tsx", "/app/routes"),
20
+ ).toEqual({ pattern: "/:slug", params: ["slug"] });
21
+ });
22
+
23
+ test("blog/+page.tsx → /blog", () => {
24
+ expect(
25
+ filePathToRoutePath("/app/routes/blog/+page.tsx", "/app/routes"),
26
+ ).toEqual({ pattern: "/blog", params: [] });
27
+ });
28
+
29
+ test("blog/[slug]/+page.tsx → /blog/:slug", () => {
30
+ expect(
31
+ filePathToRoutePath("/app/routes/blog/[slug]/+page.tsx", "/app/routes"),
32
+ ).toEqual({ pattern: "/blog/:slug", params: ["slug"] });
33
+ });
34
+
35
+ test("blog/[slug]/+page.server.ts → /blog/:slug", () => {
36
+ expect(
37
+ filePathToRoutePath(
38
+ "/app/routes/blog/[slug]/+page.server.ts",
39
+ "/app/routes",
40
+ ),
41
+ ).toEqual({ pattern: "/blog/:slug", params: ["slug"] });
42
+ });
43
+
44
+ test("+layout.tsx → /", () => {
45
+ expect(
46
+ filePathToRoutePath("/app/routes/+layout.tsx", "/app/routes"),
47
+ ).toEqual({ pattern: "/", params: [] });
48
+ });
49
+
50
+ test("nested +layout.tsx → /blog", () => {
51
+ expect(
52
+ filePathToRoutePath("/app/routes/blog/+layout.tsx", "/app/routes"),
53
+ ).toEqual({ pattern: "/blog", params: [] });
54
+ });
55
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Tests for the effect-scope mechanism used by the router to prevent effect
3
+ * accumulation across client-side navigations.
4
+ *
5
+ * Two invariants must hold forever:
6
+ * 1. Effects created during a page mount stop running when the page is disposed.
7
+ * 2. __nodes is reset to [] before each SPA navigation so the new page gets
8
+ * a fresh empty pool instead of recycling stale DOM nodes.
9
+ */
10
+ import { describe, expect, test } from "bun:test";
11
+ import { createEffect, createSignal, withEffectScope as runtimeScope } from "@sigil-dev/runtime";
12
+ import { withEffectScope } from "../src/scope.ts";
13
+
14
+ describe("grimoire withEffectScope", () => {
15
+ test("effects inside scope stop after dispose", () => {
16
+ const count = createSignal(0);
17
+ let runs = 0;
18
+ const dispose = withEffectScope(() => {
19
+ createEffect(() => {
20
+ count();
21
+ runs++;
22
+ });
23
+ });
24
+
25
+ count.set(1);
26
+ expect(runs).toBe(2); // initial + one update
27
+
28
+ dispose();
29
+
30
+ count.set(2);
31
+ expect(runs).toBe(2); // stopped — dispose cut the subscription
32
+ });
33
+
34
+ test("simulates two page navigations — only latest page's effects run", () => {
35
+ const count = createSignal(0);
36
+ let pageARuns = 0;
37
+ let pageBRuns = 0;
38
+
39
+ // Mount page A
40
+ let disposeCurrentPage = withEffectScope(() => {
41
+ createEffect(() => { count(); pageARuns++; });
42
+ });
43
+ count.set(1);
44
+ expect(pageARuns).toBe(2);
45
+ expect(pageBRuns).toBe(0);
46
+
47
+ // Navigate to page B — dispose A first
48
+ disposeCurrentPage();
49
+ disposeCurrentPage = withEffectScope(() => {
50
+ createEffect(() => { count(); pageBRuns++; });
51
+ });
52
+
53
+ count.set(2);
54
+ expect(pageARuns).toBe(2); // A's effect is gone
55
+ expect(pageBRuns).toBe(2); // B initial + update
56
+
57
+ // Navigate away from B — dispose B
58
+ disposeCurrentPage();
59
+ count.set(3);
60
+ expect(pageARuns).toBe(2);
61
+ expect(pageBRuns).toBe(2); // B's effect is gone too
62
+ });
63
+
64
+ test("three navigations: each page's effects are independent", () => {
65
+ const signal = createSignal("a");
66
+ const log: string[] = [];
67
+
68
+ const mountPage = (label: string) =>
69
+ withEffectScope(() => {
70
+ createEffect(() => {
71
+ log.push(`${label}:${signal()}`);
72
+ });
73
+ });
74
+
75
+ const disposeA = mountPage("A");
76
+ const disposeB = mountPage("B");
77
+
78
+ signal.set("b");
79
+ expect(log).toEqual(["A:a", "B:a", "A:b", "B:b"]);
80
+
81
+ disposeA();
82
+ signal.set("c");
83
+ expect(log).toEqual(["A:a", "B:a", "A:b", "B:b", "B:c"]); // only B ran
84
+
85
+ disposeB();
86
+ signal.set("d");
87
+ expect(log).toEqual(["A:a", "B:a", "A:b", "B:b", "B:c"]); // neither ran
88
+ });
89
+
90
+ test("grimoire scope uses same globalThis channel as runtime scope", () => {
91
+ // Both must route through the same global so that createEffect
92
+ // in page components (compiled by sigil, imports @sigil-dev/runtime)
93
+ // is captured by grimoire's router scope.
94
+ const count = createSignal(0);
95
+ let runs = 0;
96
+
97
+ // grimoire's local withEffectScope wraps a createEffect from @sigil-dev/runtime
98
+ const dispose = withEffectScope(() => {
99
+ createEffect(() => { count(); runs++; });
100
+ });
101
+
102
+ count.set(1);
103
+ expect(runs).toBe(2);
104
+
105
+ dispose();
106
+ count.set(2);
107
+ expect(runs).toBe(2); // runtime's createEffect was captured by grimoire's scope ✓
108
+ });
109
+
110
+ test("runtime's withEffectScope and grimoire's are interchangeable", () => {
111
+ // The runtime exports its own withEffectScope for user code.
112
+ // Both implementations must work the same way via the globalThis channel.
113
+ const count = createSignal(0);
114
+ let runs = 0;
115
+
116
+ const dispose = runtimeScope(() => {
117
+ createEffect(() => { count(); runs++; });
118
+ });
119
+
120
+ count.set(1);
121
+ expect(runs).toBe(2);
122
+ dispose();
123
+ count.set(2);
124
+ expect(runs).toBe(2);
125
+ });
126
+ });
127
+
128
+ describe("__nodes pool reset on SPA navigation", () => {
129
+ test("navigate sets __nodes to [] before calling Page()", () => {
130
+ // Simulate exactly what client-router.ts's navigate() does:
131
+ // dispose old effects → set __nodes = [] → call Page() → replaceChildren(node)
132
+ // We only care that Page() sees an empty pool.
133
+ let nodesAtCallTime: unknown = "not set";
134
+
135
+ const mockPage = () => {
136
+ nodesAtCallTime = (globalThis as any).__nodes;
137
+ return document.createElement("div"); // satisfy replaceChildren
138
+ };
139
+
140
+ // Mimic the three lines in navigate() that matter
141
+ ;(globalThis as any).__nodes = ["stale", "dom", "nodes"]; // leftover from previous page
142
+ (globalThis as any).__nodes = []; // the reset
143
+ mockPage();
144
+
145
+ expect(nodesAtCallTime).toEqual([]);
146
+ });
147
+
148
+ test("Page() called during SSR hydration sees real DOM nodes, not empty pool", () => {
149
+ // Contrast: hydrate.ts sets __nodes to Array.from(slot.childNodes) before calling Page()
150
+ const fakeSlotChild = document.createElement("div");
151
+ let nodesAtCallTime: unknown = "not set";
152
+
153
+ const mockPage = () => {
154
+ nodesAtCallTime = (globalThis as any).__nodes;
155
+ };
156
+
157
+ ;(globalThis as any).__nodes = [fakeSlotChild]; // hydrate.ts sets real nodes
158
+ mockPage();
159
+
160
+ expect(Array.isArray(nodesAtCallTime)).toBe(true);
161
+ expect((nodesAtCallTime as unknown[]).length).toBe(1);
162
+ expect((nodesAtCallTime as unknown[])[0]).toBe(fakeSlotChild);
163
+ });
164
+ });
@@ -0,0 +1,30 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, writeFile } from "fs/promises"; // ← promises not fs
3
+ import { tmpdir } from "os";
4
+ import { join } from "path";
5
+ import { createServer } from "../src/server";
6
+
7
+ let tmpDir: string;
8
+
9
+ beforeAll(async () => {
10
+ tmpDir = join(tmpdir(), `grimoire-server-${Date.now()}`);
11
+ await mkdir(join(tmpDir, "api", "hello"), { recursive: true });
12
+ await writeFile(
13
+ join(tmpDir, "api", "hello", "+server.ts"),
14
+ `
15
+ export async function GET({ request }) {
16
+ return Response.json({ message: 'hello' });
17
+ }
18
+ `,
19
+ );
20
+ });
21
+
22
+ describe("Server", () => {
23
+ test("serves GET api route", async () => {
24
+ const server = await createServer({ port: 3004, routes: tmpDir });
25
+ const res = await fetch("http://localhost:3004/api/hello");
26
+ const data = await res.json();
27
+ expect(data.message).toBe("hello");
28
+ server.stop();
29
+ });
30
+ });
@@ -0,0 +1,132 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { renderRoute } from "../src/renderer";
3
+
4
+ describe("Streaming SSR", () => {
5
+ test("returns a ReadableStream response", async () => {
6
+ const matched = {
7
+ route: {
8
+ path: "/",
9
+ params: {},
10
+ filePath: "data:text/javascript,export default (p) => '<div>hello</div>'",
11
+ },
12
+ params: {},
13
+ } as any;
14
+
15
+ const res = await renderRoute(matched, new Request("http://localhost/"));
16
+ expect(res.body).toBeInstanceOf(ReadableStream);
17
+ });
18
+
19
+ test("stream contains full HTML document", async () => {
20
+ const matched = {
21
+ route: {
22
+ path: "/test",
23
+ params: {},
24
+ filePath:
25
+ "data:text/javascript,export default (p) => '<p>streaming works</p>'",
26
+ },
27
+ params: {},
28
+ } as any;
29
+
30
+ const res = await renderRoute(matched, new Request("http://localhost/test"));
31
+ const html = await res.text();
32
+
33
+ expect(html).toContain("<!DOCTYPE html>");
34
+ expect(html).toContain('<meta charset="UTF-8" />');
35
+ expect(html).toContain("streaming works");
36
+ expect(html).toContain("</html>");
37
+ expect(html).toContain("__grimoire_state__");
38
+ });
39
+
40
+ test("stream includes state JSON with route pattern", async () => {
41
+ const matched = {
42
+ route: {
43
+ path: "/spells/:id",
44
+ params: {},
45
+ filePath:
46
+ "data:text/javascript,export default (p) => '<div>spell</div>'",
47
+ },
48
+ params: { id: "fireball" },
49
+ } as any;
50
+
51
+ const res = await renderRoute(
52
+ matched,
53
+ new Request("http://localhost/spells/fireball"),
54
+ );
55
+ const html = await res.text();
56
+
57
+ expect(html).toContain('"pattern":"/spells/:id"');
58
+ expect(html).toContain('"id":"fireball"');
59
+ });
60
+
61
+ test("head script tag comes before head content", async () => {
62
+ const matched = {
63
+ route: {
64
+ path: "/head-test",
65
+ params: {},
66
+ filePath:
67
+ "data:text/javascript,export default (p) => '<div>head</div>'",
68
+ },
69
+ params: {},
70
+ } as any;
71
+
72
+ const res = await renderRoute(matched, new Request("http://localhost/head-test"));
73
+ const html = await res.text();
74
+
75
+ const hydrateScript = html.indexOf("hydrate.js");
76
+ const headClosing = html.indexOf("</head>");
77
+ // hydrate.js should be in <head>
78
+ expect(hydrateScript).toBeGreaterThan(-1);
79
+ expect(hydrateScript).toBeLessThan(headClosing);
80
+ });
81
+
82
+ test("stream chunks arrive incrementally", async () => {
83
+ const matched = {
84
+ route: {
85
+ path: "/chunked",
86
+ params: {},
87
+ filePath:
88
+ "data:text/javascript,export default (p) => '<div>chunked</div>'",
89
+ },
90
+ params: {},
91
+ } as any;
92
+
93
+ const res = await renderRoute(matched, new Request("http://localhost/chunked"));
94
+ const reader = res.body!.getReader();
95
+ const chunks: string[] = [];
96
+
97
+ while (true) {
98
+ const { done, value } = await reader.read();
99
+ if (done) break;
100
+ // Bun ReadableStream returns Uint8Array
101
+ chunks.push(typeof value === "string" ? value : new TextDecoder().decode(value.buffer));
102
+ }
103
+
104
+ // Should have multiple chunks (at least DOCTYPE + body)
105
+ expect(chunks.length).toBeGreaterThan(1);
106
+ // First chunk should start with DOCTYPE
107
+ expect(chunks[0]).toContain("<!DOCTYPE html>");
108
+ // Last chunk should close the document
109
+ expect(chunks[chunks.length - 1]).toContain("</html>");
110
+ });
111
+
112
+ test("navigation request returns JSON not stream", async () => {
113
+ const matched = {
114
+ route: {
115
+ path: "/nav",
116
+ params: {},
117
+ filePath:
118
+ "data:text/javascript,export default (p) => '<div>nav</div>'",
119
+ },
120
+ params: {},
121
+ } as any;
122
+
123
+ const req = new Request("http://localhost/nav", {
124
+ headers: { "x-grimoire-navigate": "1" },
125
+ });
126
+ const res = await renderRoute(matched, req);
127
+ const json = await res.json();
128
+
129
+ expect(json.pattern).toBe("/nav");
130
+ expect(json.data).toBeDefined();
131
+ });
132
+ });
@@ -0,0 +1,84 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "fs/promises";
3
+ import { tmpdir } from "os";
4
+ import { join } from "path";
5
+ import type { RouteFile } from "../src/scanner";
6
+ import { transformRoutes } from "../src/transform-routes";
7
+
8
+ describe("transformRoutes", () => {
9
+ test("pre-transforms TypeScript TSX routes to unique JavaScript files", async () => {
10
+ const root = await mkdtemp(join(tmpdir(), "grimoire-transform-"));
11
+ try {
12
+ const routesDir = join(root, "src", "routes");
13
+ const spellDir = join(routesDir, "spells", "[id]");
14
+ const otherDir = join(routesDir, "other");
15
+ const outDir = join(root, ".grimoire", "compiled");
16
+ await mkdir(spellDir, { recursive: true });
17
+ await mkdir(otherDir, { recursive: true });
18
+ await mkdir(outDir, { recursive: true });
19
+
20
+ const spellRoute = join(spellDir, "+page.tsx");
21
+ const otherRoute = join(otherDir, "+page.tsx");
22
+ const spellData = join(spellDir, "data.ts");
23
+ await writeFile(
24
+ spellData,
25
+ `
26
+ export const SPELLS = { fire: "Fire" } as const;
27
+ `,
28
+ );
29
+ await writeFile(
30
+ spellRoute,
31
+ `
32
+ import { SPELLS } from "./data";
33
+ type PageProps = { params: { id: keyof typeof SPELLS } };
34
+
35
+ export default function Page({ params }: PageProps) {
36
+ const n: number = 1;
37
+ return <h1>{SPELLS[params.id] ?? n}</h1>;
38
+ }
39
+ `,
40
+ );
41
+ await writeFile(
42
+ otherRoute,
43
+ `
44
+ export default function Other({ count }: { count: number }) {
45
+ return <p>{count}</p>;
46
+ }
47
+ `,
48
+ );
49
+
50
+ const routes: RouteFile[] = [
51
+ route(spellRoute, "/spells/:id"),
52
+ route(otherRoute, "/other"),
53
+ ];
54
+ const files = await transformRoutes(routes, outDir, "dom");
55
+
56
+ const spellOut = files.get(spellRoute);
57
+ const otherOut = files.get(otherRoute);
58
+ expect(spellOut).not.toEqual(otherOut);
59
+ expect(spellOut).toContain(".dom.js");
60
+ expect(otherOut).toContain(".dom.js");
61
+
62
+ const code = await readFile(spellOut!, "utf8");
63
+ expect(code).toContain("export default function Page");
64
+ expect(code).toContain(
65
+ spellData.replace(/\.ts$/, "").replace(/\\/g, "\\\\"),
66
+ );
67
+ expect(code).not.toContain(": number");
68
+ expect(code).not.toContain("keyof typeof");
69
+ expect(code).not.toContain("as const");
70
+ } finally {
71
+ await rm(root, { recursive: true, force: true });
72
+ }
73
+ });
74
+ });
75
+
76
+ function route(filePath: string, path: string): RouteFile {
77
+ return {
78
+ path,
79
+ filePath,
80
+ clientPath: filePath,
81
+ type: "page",
82
+ paramNames: [],
83
+ };
84
+ }