@sigil-dev/grimoire 0.9.2 → 0.9.3

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 (88) hide show
  1. package/index.ts +35 -35
  2. package/package.json +8 -8
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +13 -7
  6. package/src/client/enhance.ts +98 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +2 -2
  9. package/src/client/router.ts +445 -371
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +163 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +114 -114
  14. package/src/dev/hmr-client.ts +185 -185
  15. package/src/dev/loader.ts +47 -47
  16. package/src/dev/paths.ts +14 -14
  17. package/src/dev/runtime-bundle.ts +52 -52
  18. package/src/dev/watcher.ts +47 -46
  19. package/src/env/dynamic-private.ts +19 -19
  20. package/src/env/dynamic-public.ts +22 -22
  21. package/src/env/index.ts +25 -25
  22. package/src/env/plugin.ts +19 -19
  23. package/src/env/private.ts +5 -5
  24. package/src/env/public.ts +7 -7
  25. package/src/env/typegen.ts +61 -61
  26. package/src/headers.ts +114 -114
  27. package/src/integrations/vite.ts +73 -73
  28. package/src/logger/index.ts +4 -4
  29. package/src/logger/instance.ts +6 -6
  30. package/src/logger/logger.ts +113 -113
  31. package/src/logger/request-middleware.ts +24 -24
  32. package/src/logger/transports.ts +117 -117
  33. package/src/logger/types.ts +39 -39
  34. package/src/rendering/head.ts +47 -47
  35. package/src/rendering/hydrate.ts +98 -79
  36. package/src/rendering/index.ts +455 -372
  37. package/src/rendering/ssrPlugin.ts +69 -69
  38. package/src/routing/manifest-gen.ts +12 -11
  39. package/src/routing/router.ts +109 -109
  40. package/src/routing/scanner.ts +141 -141
  41. package/src/routing/transform-routes.ts +102 -102
  42. package/src/sentinels/error.ts +52 -52
  43. package/src/sentinels/fail.ts +41 -41
  44. package/src/sentinels/redirect.ts +35 -35
  45. package/src/server/build.ts +243 -219
  46. package/src/server/context.ts +10 -10
  47. package/src/server/cookie-utils.ts +66 -66
  48. package/src/server/coordinator.ts +364 -356
  49. package/src/server/hooks.ts +114 -114
  50. package/src/server/index.ts +655 -658
  51. package/src/server/interactive.ts +56 -56
  52. package/src/server/plugins.ts +121 -120
  53. package/src/server/worker.ts +58 -58
  54. package/src/typegen/index.ts +356 -356
  55. package/src/types.ts +4 -4
  56. package/test/client-router.test.ts +37 -31
  57. package/test/context.test.ts +52 -52
  58. package/test/env.test.ts +70 -70
  59. package/test/exports.test.ts +37 -37
  60. package/test/fail.test.ts +46 -46
  61. package/test/headers.test.ts +100 -100
  62. package/test/hydration.test.ts +119 -119
  63. package/test/middleware.test.ts +223 -223
  64. package/test/preload.ts +5 -5
  65. package/test/redirect-error.test.ts +112 -112
  66. package/test/rendering.test.ts +615 -579
  67. package/test/routing.test.ts +81 -81
  68. package/test/scanning.test.ts +200 -200
  69. package/test/scope.test.ts +195 -195
  70. package/test/server.test.ts +249 -249
  71. package/test/streaming.test.ts +125 -125
  72. package/test/transform-routes.test.ts +84 -84
  73. package/test/typegen.test.ts +682 -682
  74. package/tsconfig.json +10 -10
  75. package/.grimoire/_routes.dom.js +0 -8
  76. package/.grimoire/_routes.hydrate.js +0 -8
  77. package/.grimoire/tsconfig.generated.json +0 -11
  78. package/.grimoire/types/ambient.d.ts +0 -59
  79. package/.grimoire/types/api/hello/$types.d.ts +0 -50
  80. package/.grimoire/types/api/items/$types.d.ts +0 -50
  81. package/.grimoire/types/echo/$types.d.ts +0 -50
  82. package/.grimoire/types/env-private.d.ts +0 -5
  83. package/.grimoire/types/env-public.d.ts +0 -5
  84. package/.grimoire/types/mixed/$types.d.ts +0 -50
  85. package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
  86. package/.grimoire/types/reject/$types.d.ts +0 -50
  87. package/public/__grimoire__/hydrate.js +0 -585
  88. package/public/__grimoire__/index.js +0 -490
@@ -1,682 +1,682 @@
1
- import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
- import { existsSync } from "node:fs";
3
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join, sep } from "node:path";
6
- import type { RouteFile } from "../src/routing/scanner";
7
- import { scanRoutes } from "../src/routing/scanner";
8
- import {
9
- buildParams,
10
- generateTypes,
11
- groupByDirectory,
12
- toImportPath,
13
- } from "../src/typegen";
14
-
15
- // ---------------------------------------------------------------------------
16
- // toImportPath
17
- // ---------------------------------------------------------------------------
18
-
19
- describe("toImportPath", () => {
20
- test(".ts extension becomes .js", () => {
21
- const result = toImportPath("/a/b", "/a/b/c/file.ts");
22
- expect(result).toBe("c/file.js");
23
- });
24
-
25
- test(".tsx extension becomes .js", () => {
26
- const result = toImportPath("/a/b", "/a/b/c/file.tsx");
27
- expect(result).toBe("c/file.js");
28
- });
29
-
30
- test("produces ../ prefixes for parent directories", () => {
31
- const result = toImportPath(
32
- "/project/.grimoire/types/src/routes/blog/[slug]",
33
- "/project/src/routes/blog/[slug]/+page.server.ts",
34
- );
35
- // From .grimoire/types/src/routes/blog/[slug] up 6 levels to /project/, then down
36
- expect(result).toBe(
37
- "../../../../../../src/routes/blog/[slug]/+page.server.js",
38
- );
39
- });
40
-
41
- test("never contains backslashes regardless of platform separator", () => {
42
- // Construct paths using the OS separator to exercise the replace logic
43
- // from: C:\project\.grimoire\types\src\routes (4 levels below C:\project)
44
- // to: C:\project\src\routes\+page.server.ts
45
- // → 4 "../" to escape back to C:\project, then down to src/routes/file
46
- const from = ["C:", "project", ".grimoire", "types", "src", "routes"].join(
47
- sep,
48
- );
49
- const to = ["C:", "project", "src", "routes", "+page.server.ts"].join(sep);
50
- const result = toImportPath(from, to);
51
- expect(result).not.toContain("\\");
52
- expect(result).toBe("../../../../src/routes/+page.server.js");
53
- });
54
-
55
- test("sibling file produces just the filename", () => {
56
- const result = toImportPath("/a/b/c", "/a/b/c/file.ts");
57
- expect(result).toBe("file.js");
58
- });
59
- });
60
-
61
- // ---------------------------------------------------------------------------
62
- // buildParams
63
- // ---------------------------------------------------------------------------
64
-
65
- describe("buildParams", () => {
66
- test("empty array returns {}", () => {
67
- expect(buildParams([])).toBe("{}");
68
- });
69
-
70
- test("single param", () => {
71
- expect(buildParams(["id"])).toBe("{\n id: string;\n}");
72
- });
73
-
74
- test("multiple params", () => {
75
- expect(buildParams(["org", "repo"])).toBe(
76
- "{\n org: string;\n repo: string;\n}",
77
- );
78
- });
79
-
80
- test("produces valid TypeScript type syntax", () => {
81
- const result = buildParams(["slug"]);
82
- expect(result).toContain("slug: string;");
83
- });
84
- });
85
-
86
- // ---------------------------------------------------------------------------
87
- // groupByDirectory
88
- // ---------------------------------------------------------------------------
89
-
90
- function makeRouteFile(
91
- overrides: Partial<RouteFile> & { filePath: string; type: RouteFile["type"] },
92
- ): RouteFile {
93
- return {
94
- path: "/",
95
- clientPath: "/src/routes/+page.tsx",
96
- paramNames: [],
97
- restParamNames: [],
98
- ...overrides,
99
- };
100
- }
101
-
102
- describe("groupByDirectory", () => {
103
- test("simple files are excluded", () => {
104
- const tree = {
105
- routes: [
106
- makeRouteFile({ filePath: "/app/routes/index.tsx", type: "simple" }),
107
- makeRouteFile({ filePath: "/app/routes/about.tsx", type: "simple" }),
108
- ],
109
- layouts: [],
110
- servers: [],
111
- errors: [],
112
- };
113
- const groups = groupByDirectory(tree);
114
- expect(groups.size).toBe(0);
115
- });
116
-
117
- test("+page.tsx and +page.server.ts in the same directory form one group", () => {
118
- const tree = {
119
- routes: [
120
- makeRouteFile({
121
- filePath: "/app/routes/blog/[slug]/+page.tsx",
122
- type: "page",
123
- paramNames: ["slug"],
124
- }),
125
- makeRouteFile({
126
- filePath: "/app/routes/blog/[slug]/+page.server.ts",
127
- type: "pageServer",
128
- paramNames: ["slug"],
129
- }),
130
- ],
131
- layouts: [],
132
- servers: [],
133
- errors: [],
134
- };
135
- const groups = groupByDirectory(tree);
136
- expect(groups.size).toBe(1);
137
- const group = groups.get("/app/routes/blog/[slug]")!;
138
- expect(group).toBeDefined();
139
- expect(group.page?.filePath).toBe("/app/routes/blog/[slug]/+page.tsx");
140
- expect(group.pageServer?.filePath).toBe(
141
- "/app/routes/blog/[slug]/+page.server.ts",
142
- );
143
- });
144
-
145
- test("+layout files go into their own group separate from +page files", () => {
146
- const tree = {
147
- routes: [
148
- makeRouteFile({ filePath: "/app/routes/+page.tsx", type: "page" }),
149
- ],
150
- layouts: [
151
- makeRouteFile({ filePath: "/app/routes/+layout.tsx", type: "layout" }),
152
- ],
153
- servers: [],
154
- errors: [],
155
- };
156
- const groups = groupByDirectory(tree);
157
- expect(groups.size).toBe(1);
158
- const group = groups.get("/app/routes")!;
159
- expect(group.page).toBeDefined();
160
- expect(group.layout).toBeDefined();
161
- });
162
-
163
- test("+server.ts creates a group with server field set", () => {
164
- const tree = {
165
- routes: [],
166
- layouts: [],
167
- servers: [
168
- makeRouteFile({
169
- filePath: "/app/routes/api/hello/+server.ts",
170
- type: "server",
171
- }),
172
- ],
173
- errors: [],
174
- };
175
- const groups = groupByDirectory(tree);
176
- expect(groups.size).toBe(1);
177
- expect(groups.get("/app/routes/api/hello")!.server).toBeDefined();
178
- });
179
-
180
- test("+error.tsx creates a group with error field set", () => {
181
- const tree = {
182
- routes: [],
183
- layouts: [],
184
- servers: [],
185
- errors: [
186
- makeRouteFile({
187
- filePath: "/app/routes/+error.tsx",
188
- type: "error",
189
- }),
190
- ],
191
- };
192
- const groups = groupByDirectory(tree);
193
- expect(groups.size).toBe(1);
194
- expect(groups.get("/app/routes")!.error).toBeDefined();
195
- });
196
-
197
- test("paramNames taken from the file with most params", () => {
198
- const tree = {
199
- routes: [
200
- makeRouteFile({
201
- filePath: "/app/routes/[org]/[repo]/+page.tsx",
202
- type: "page",
203
- paramNames: ["org", "repo"],
204
- }),
205
- makeRouteFile({
206
- filePath: "/app/routes/[org]/[repo]/+page.server.ts",
207
- type: "pageServer",
208
- paramNames: ["org", "repo"],
209
- }),
210
- ],
211
- layouts: [],
212
- servers: [],
213
- errors: [],
214
- };
215
- const groups = groupByDirectory(tree);
216
- const group = groups.values().next().value!;
217
- expect(group.paramNames).toEqual(["org", "repo"]);
218
- });
219
-
220
- test("simple files mixed with +page files: only +page files contribute to groups", () => {
221
- const tree = {
222
- routes: [
223
- makeRouteFile({ filePath: "/app/routes/about.tsx", type: "simple" }),
224
- makeRouteFile({
225
- filePath: "/app/routes/blog/+page.tsx",
226
- type: "page",
227
- }),
228
- ],
229
- layouts: [],
230
- servers: [],
231
- errors: [],
232
- };
233
- const groups = groupByDirectory(tree);
234
- expect(groups.size).toBe(1);
235
- expect(groups.has("/app/routes/blog")).toBe(true);
236
- expect(groups.has("/app/routes")).toBe(false);
237
- });
238
- });
239
-
240
- // ---------------------------------------------------------------------------
241
- // generateTypes — integration (file system)
242
- // ---------------------------------------------------------------------------
243
-
244
- let tmpDir: string;
245
-
246
- beforeAll(async () => {
247
- tmpDir = join(tmpdir(), `grimoire-typegen-${Date.now()}`);
248
- await mkdir(join(tmpDir, "src", "routes", "blog", "[slug]"), {
249
- recursive: true,
250
- });
251
- await mkdir(join(tmpDir, "src", "routes", "api", "posts"), {
252
- recursive: true,
253
- });
254
-
255
- // Layout at root
256
- await writeFile(
257
- join(tmpDir, "src", "routes", "+layout.tsx"),
258
- "export default () => null;",
259
- );
260
-
261
- // Page-only route (no server)
262
- await writeFile(
263
- join(tmpDir, "src", "routes", "blog", "+page.tsx"),
264
- "export default () => null;",
265
- );
266
-
267
- // Route with +page.server.ts that has a load function
268
- await writeFile(
269
- join(tmpDir, "src", "routes", "blog", "[slug]", "+page.tsx"),
270
- "export default () => null;",
271
- );
272
- await writeFile(
273
- join(tmpDir, "src", "routes", "blog", "[slug]", "+page.server.ts"),
274
- `export async function load({ params }: { params: { slug: string } }) {
275
- return { post: { title: "Hello", views: 42 } };
276
- }
277
- export async function DELETE({ request }: { request: Request }) {
278
- return {};
279
- }`,
280
- );
281
-
282
- // Route with +layout.server.ts
283
- await writeFile(
284
- join(tmpDir, "src", "routes", "blog", "+layout.server.ts"),
285
- `export async function load() { return { nav: ["Home", "Blog"] }; }`,
286
- );
287
-
288
- // API route (+server.ts)
289
- await writeFile(
290
- join(tmpDir, "src", "routes", "api", "posts", "+server.ts"),
291
- `export async function GET() { return Response.json([]); }
292
- export async function POST() { return Response.json({}); }`,
293
- );
294
-
295
- // Error page
296
- await writeFile(
297
- join(tmpDir, "src", "routes", "+error.tsx"),
298
- "export default () => null;",
299
- );
300
-
301
- // Simple file (should be ignored)
302
- await writeFile(
303
- join(tmpDir, "src", "routes", "about.tsx"),
304
- "export default () => null;",
305
- );
306
-
307
- // Rest (catch-all) param route
308
- await mkdir(join(tmpDir, "src", "routes", "files", "[...path]"), {
309
- recursive: true,
310
- });
311
- await writeFile(
312
- join(tmpDir, "src", "routes", "files", "[...path]", "+server.ts"),
313
- `export async function GET() { return new Response("ok"); }`,
314
- );
315
- });
316
-
317
- afterAll(async () => {
318
- await rm(tmpDir, { recursive: true, force: true });
319
- });
320
-
321
- async function runGenerate() {
322
- const routesDir = join(tmpDir, "src", "routes");
323
- const tree = await scanRoutes(routesDir, tmpDir);
324
- await generateTypes(tree, {
325
- projectRoot: tmpDir,
326
- routesDir,
327
- outDir: join(tmpDir, ".grimoire", "types"),
328
- });
329
- }
330
-
331
- async function readGenerated(routeRelPath: string) {
332
- const p = join(tmpDir, ".grimoire", "types", routeRelPath, "$types.d.ts");
333
- return readFile(p, "utf-8");
334
- }
335
-
336
- describe("generateTypes — output structure", () => {
337
- test("creates ambient.d.ts with App.Locals namespace", async () => {
338
- await runGenerate();
339
- const ambient = await readFile(
340
- join(tmpDir, ".grimoire", "types", "ambient.d.ts"),
341
- "utf-8",
342
- );
343
- expect(ambient).toContain("declare namespace App");
344
- expect(ambient).toContain("interface Locals");
345
- });
346
-
347
- test("creates tsconfig.generated.json with rootDirs", async () => {
348
- const config = JSON.parse(
349
- await readFile(
350
- join(tmpDir, ".grimoire", "tsconfig.generated.json"),
351
- "utf-8",
352
- ),
353
- );
354
- expect(config.compilerOptions.rootDirs).toContain("..");
355
- expect(config.compilerOptions.rootDirs).toContain("./types");
356
- });
357
-
358
- test("generates $types.d.ts for each route directory with + files", async () => {
359
- expect(
360
- existsSync(
361
- join(tmpDir, ".grimoire", "types", "src", "routes", "$types.d.ts"),
362
- ),
363
- ).toBe(true);
364
- expect(
365
- existsSync(
366
- join(
367
- tmpDir,
368
- ".grimoire",
369
- "types",
370
- "src",
371
- "routes",
372
- "blog",
373
- "$types.d.ts",
374
- ),
375
- ),
376
- ).toBe(true);
377
- expect(
378
- existsSync(
379
- join(
380
- tmpDir,
381
- ".grimoire",
382
- "types",
383
- "src",
384
- "routes",
385
- "blog",
386
- "[slug]",
387
- "$types.d.ts",
388
- ),
389
- ),
390
- ).toBe(true);
391
- });
392
-
393
- test("does NOT generate $types.d.ts for simple (non-+ convention) files", async () => {
394
- // about.tsx is a simple file in src/routes/ — there's no $types for it
395
- // (src/routes/ does get $types from +layout.tsx, but it's not created for about.tsx alone)
396
- // Confirm that about/ directory itself has no $types
397
- expect(
398
- existsSync(
399
- join(
400
- tmpDir,
401
- ".grimoire",
402
- "types",
403
- "src",
404
- "routes",
405
- "about",
406
- "$types.d.ts",
407
- ),
408
- ),
409
- ).toBe(false);
410
- });
411
- });
412
-
413
- describe("generateTypes — route without +page.server.ts", () => {
414
- test("PageData = Record<string, never>", async () => {
415
- const content = await readGenerated("src/routes/blog");
416
- expect(content).toContain("export type PageData = Record<string, never>;");
417
- });
418
-
419
- test("PageServerLoad = never", async () => {
420
- const content = await readGenerated("src/routes/blog");
421
- expect(content).toContain("export type PageServerLoad = never;");
422
- });
423
-
424
- test("Actions = Record<string, never>", async () => {
425
- const content = await readGenerated("src/routes/blog");
426
- expect(content).toContain("export type Actions = Record<string, never>;");
427
- });
428
-
429
- test("PageProps contains data and params", async () => {
430
- const content = await readGenerated("src/routes/blog");
431
- expect(content).toContain(
432
- "export type PageProps = { data: PageData; params: Params };",
433
- );
434
- });
435
- });
436
-
437
- describe("generateTypes — route with +page.server.ts", () => {
438
- test("uses typeof import() for the server module", async () => {
439
- const content = await readGenerated("src/routes/blog/[slug]");
440
- expect(content).toMatch(/type _PS = typeof import\("/);
441
- });
442
-
443
- test("import path ends with .js", async () => {
444
- const content = await readGenerated("src/routes/blog/[slug]");
445
- const match = content.match(/typeof import\("([^"]+)"\)/);
446
- expect(match?.[1]).toMatch(/\.js$/);
447
- });
448
-
449
- test("import path contains only forward slashes", async () => {
450
- const content = await readGenerated("src/routes/blog/[slug]");
451
- const match = content.match(/typeof import\("([^"]+)"\)/);
452
- expect(match?.[1]).not.toContain("\\");
453
- });
454
-
455
- test("PageData inferred from load() via ReturnType", async () => {
456
- const content = await readGenerated("src/routes/blog/[slug]");
457
- expect(content).toContain(
458
- 'export type PageData = "load" extends keyof _PS',
459
- );
460
- expect(content).toContain('Awaited<ReturnType<_PS["load"]>>');
461
- });
462
-
463
- test("PageProps = { data: PageData; params: Params }", async () => {
464
- const content = await readGenerated("src/routes/blog/[slug]");
465
- expect(content).toContain(
466
- "export type PageProps = { data: PageData; params: Params };",
467
- );
468
- });
469
-
470
- test("Actions excludes load and default from keys", async () => {
471
- const content = await readGenerated("src/routes/blog/[slug]");
472
- expect(content).toContain(
473
- 'type _ActionKeys = Exclude<keyof _PS, "load" | "default">;',
474
- );
475
- });
476
-
477
- test("Params has slug typed as string", async () => {
478
- const content = await readGenerated("src/routes/blog/[slug]");
479
- expect(content).toContain("slug: string;");
480
- });
481
- });
482
-
483
- describe("generateTypes — +layout.server.ts", () => {
484
- test("LayoutData inferred from load() via typeof import", async () => {
485
- const content = await readGenerated("src/routes/blog");
486
- expect(content).toMatch(/type _LS = typeof import\("/);
487
- expect(content).toContain(
488
- 'export type LayoutData = "load" extends keyof _LS',
489
- );
490
- expect(content).toContain('Awaited<ReturnType<_LS["load"]>>');
491
- });
492
-
493
- test("LayoutProps includes children", async () => {
494
- const content = await readGenerated("src/routes/blog");
495
- expect(content).toContain("children?: unknown");
496
- });
497
- });
498
-
499
- describe("generateTypes — +server.ts (API route)", () => {
500
- test("generates ServerHandlers type", async () => {
501
- const content = await readGenerated("src/routes/api/posts");
502
- expect(content).toContain("export type ServerHandlers");
503
- });
504
-
505
- test("uses typeof import() for server module", async () => {
506
- const content = await readGenerated("src/routes/api/posts");
507
- expect(content).toMatch(/type _SRV = typeof import\("/);
508
- });
509
-
510
- test("extracts HTTP method keys", async () => {
511
- const content = await readGenerated("src/routes/api/posts");
512
- expect(content).toContain("_HttpMethods");
513
- expect(content).toContain("_ServerKeys");
514
- });
515
- });
516
-
517
- describe("generateTypes — +error.tsx", () => {
518
- test("generates ErrorProps type", async () => {
519
- const content = await readGenerated("src/routes");
520
- expect(content).toContain(
521
- "export type ErrorProps = { status: number; message: string; error: unknown; route: string };",
522
- );
523
- });
524
- });
525
-
526
- describe("generateTypes — rest (catch-all) params", () => {
527
- test("Params includes rest param name as string", async () => {
528
- const content = await readGenerated("src/routes/files/[...path]");
529
- expect(content).toContain("path: string;");
530
- expect(content).toMatch(/export type Params = \{\s+path: string;\s+\};/);
531
- });
532
- });
533
-
534
- // This behavior no lnger exists
535
- // describe("generateTypes — clears stale output", () => {
536
- // test("removes files from a deleted route on re-run", async () => {
537
- // // First run already happened in beforeAll via runGenerate()
538
- // // Write a stale file manually
539
- // const staleDir = join(
540
- // tmpDir,
541
- // ".grimoire",
542
- // "types",
543
- // "src",
544
- // "routes",
545
- // "old-route",
546
- // );
547
- // await mkdir(staleDir, { recursive: true });
548
- // await writeFile(join(staleDir, "$types.d.ts"), "// stale");
549
-
550
- // // Re-run
551
- // await runGenerate();
552
-
553
- // // Stale file should be gone
554
- // expect(existsSync(join(staleDir, "$types.d.ts"))).toBe(false);
555
- // });
556
- // });
557
-
558
- // ---------------------------------------------------------------------------
559
- // tsc integration — proves the generated types actually type-check
560
- // ---------------------------------------------------------------------------
561
-
562
- describe("tsc integration", () => {
563
- let tscDir: string;
564
-
565
- beforeAll(async () => {
566
- tscDir = join(tmpdir(), `grimoire-tsc-${Date.now()}`);
567
- const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
568
- await mkdir(routeDir, { recursive: true });
569
-
570
- // Minimal +page.server.ts whose return type flows through to PageProps
571
- await writeFile(
572
- join(routeDir, "+page.server.ts"),
573
- `export async function load({ params }: { params: { slug: string } }) {
574
- return { post: { title: "Hello", views: 42 } };
575
- }`,
576
- );
577
-
578
- // File that uses the generated types — must live in the route dir for ./$types to resolve
579
- await writeFile(
580
- join(routeDir, "check.ts"),
581
- `import type { PageProps } from "./$types";
582
- declare const props: PageProps;
583
- const _title: string = props.data.post.title;
584
- const _views: number = props.data.post.views;
585
- const _slug: string = props.params.slug;
586
- export {};`,
587
- );
588
-
589
- // tsconfig for this mini-project
590
- await writeFile(
591
- join(tscDir, "tsconfig.json"),
592
- JSON.stringify(
593
- {
594
- extends: "./.grimoire/tsconfig.generated.json",
595
- compilerOptions: {
596
- target: "ESNext",
597
- module: "ESNext",
598
- moduleResolution: "bundler",
599
- strict: true,
600
- skipLibCheck: true,
601
- noEmit: true,
602
- },
603
- include: ["src", ".grimoire/types"],
604
- },
605
- null,
606
- 2,
607
- ),
608
- );
609
-
610
- // Generate types
611
- const routesDir = join(tscDir, "src", "routes");
612
- const tree = await scanRoutes(routesDir, tscDir);
613
- await generateTypes(tree, {
614
- projectRoot: tscDir,
615
- routesDir,
616
- outDir: join(tscDir, ".grimoire", "types"),
617
- });
618
- });
619
-
620
- afterAll(async () => {
621
- await rm(tscDir, { recursive: true, force: true });
622
- });
623
-
624
- function runTsc(cwd: string) {
625
- const proc = Bun.spawnSync(
626
- [
627
- process.execPath,
628
- "x",
629
- "--bun",
630
- "@typescript/native-preview",
631
- "--noEmit",
632
- "--project",
633
- "tsconfig.json",
634
- ],
635
- { cwd },
636
- );
637
- return proc;
638
- }
639
-
640
- test("check.ts with correct types passes tsc", () => {
641
- const result = runTsc(tscDir);
642
- // Ignore bun package-download messages; only care about exit code
643
- expect(result.exitCode).toBe(0);
644
- });
645
-
646
- test("accessing a non-existent property fails tsc", async () => {
647
- // Add a file with a wrong property access
648
- const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
649
- await writeFile(
650
- join(routeDir, "bad.ts"),
651
- `import type { PageProps } from "./$types";
652
- declare const props: PageProps;
653
- const _bad = props.post.bogus;
654
- export {};`,
655
- );
656
-
657
- const result = runTsc(tscDir);
658
- expect(result.exitCode).not.toBe(0);
659
-
660
- // Clean up so subsequent test runs are clean
661
- const { unlink } = await import("node:fs/promises");
662
- await unlink(join(routeDir, "bad.ts"));
663
- });
664
-
665
- test("params properties are typed as string", async () => {
666
- // Assigning params.slug to a number should fail
667
- const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
668
- await writeFile(
669
- join(routeDir, "wrong-param-type.ts"),
670
- `import type { PageProps } from "./$types";
671
- declare const props: PageProps;
672
- const _n: number = props.params.slug;
673
- export {};`,
674
- );
675
-
676
- const result = runTsc(tscDir);
677
- expect(result.exitCode).not.toBe(0);
678
-
679
- const { unlink } = await import("node:fs/promises");
680
- await unlink(join(routeDir, "wrong-param-type.ts"));
681
- });
682
- });
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join, sep } from "node:path";
6
+ import type { RouteFile } from "../src/routing/scanner";
7
+ import { scanRoutes } from "../src/routing/scanner";
8
+ import {
9
+ buildParams,
10
+ generateTypes,
11
+ groupByDirectory,
12
+ toImportPath,
13
+ } from "../src/typegen";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // toImportPath
17
+ // ---------------------------------------------------------------------------
18
+
19
+ describe("toImportPath", () => {
20
+ test(".ts extension becomes .js", () => {
21
+ const result = toImportPath("/a/b", "/a/b/c/file.ts");
22
+ expect(result).toBe("c/file.js");
23
+ });
24
+
25
+ test(".tsx extension becomes .js", () => {
26
+ const result = toImportPath("/a/b", "/a/b/c/file.tsx");
27
+ expect(result).toBe("c/file.js");
28
+ });
29
+
30
+ test("produces ../ prefixes for parent directories", () => {
31
+ const result = toImportPath(
32
+ "/project/.grimoire/types/src/routes/blog/[slug]",
33
+ "/project/src/routes/blog/[slug]/+page.server.ts",
34
+ );
35
+ // From .grimoire/types/src/routes/blog/[slug] up 6 levels to /project/, then down
36
+ expect(result).toBe(
37
+ "../../../../../../src/routes/blog/[slug]/+page.server.js",
38
+ );
39
+ });
40
+
41
+ test("never contains backslashes regardless of platform separator", () => {
42
+ // Construct paths using the OS separator to exercise the replace logic
43
+ // from: C:\project\.grimoire\types\src\routes (4 levels below C:\project)
44
+ // to: C:\project\src\routes\+page.server.ts
45
+ // → 4 "../" to escape back to C:\project, then down to src/routes/file
46
+ const from = ["C:", "project", ".grimoire", "types", "src", "routes"].join(
47
+ sep,
48
+ );
49
+ const to = ["C:", "project", "src", "routes", "+page.server.ts"].join(sep);
50
+ const result = toImportPath(from, to);
51
+ expect(result).not.toContain("\\");
52
+ expect(result).toBe("../../../../src/routes/+page.server.js");
53
+ });
54
+
55
+ test("sibling file produces just the filename", () => {
56
+ const result = toImportPath("/a/b/c", "/a/b/c/file.ts");
57
+ expect(result).toBe("file.js");
58
+ });
59
+ });
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // buildParams
63
+ // ---------------------------------------------------------------------------
64
+
65
+ describe("buildParams", () => {
66
+ test("empty array returns {}", () => {
67
+ expect(buildParams([])).toBe("{}");
68
+ });
69
+
70
+ test("single param", () => {
71
+ expect(buildParams(["id"])).toBe("{\n id: string;\n}");
72
+ });
73
+
74
+ test("multiple params", () => {
75
+ expect(buildParams(["org", "repo"])).toBe(
76
+ "{\n org: string;\n repo: string;\n}",
77
+ );
78
+ });
79
+
80
+ test("produces valid TypeScript type syntax", () => {
81
+ const result = buildParams(["slug"]);
82
+ expect(result).toContain("slug: string;");
83
+ });
84
+ });
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // groupByDirectory
88
+ // ---------------------------------------------------------------------------
89
+
90
+ function makeRouteFile(
91
+ overrides: Partial<RouteFile> & { filePath: string; type: RouteFile["type"] },
92
+ ): RouteFile {
93
+ return {
94
+ path: "/",
95
+ clientPath: "/src/routes/+page.tsx",
96
+ paramNames: [],
97
+ restParamNames: [],
98
+ ...overrides,
99
+ };
100
+ }
101
+
102
+ describe("groupByDirectory", () => {
103
+ test("simple files are excluded", () => {
104
+ const tree = {
105
+ routes: [
106
+ makeRouteFile({ filePath: "/app/routes/index.tsx", type: "simple" }),
107
+ makeRouteFile({ filePath: "/app/routes/about.tsx", type: "simple" }),
108
+ ],
109
+ layouts: [],
110
+ servers: [],
111
+ errors: [],
112
+ };
113
+ const groups = groupByDirectory(tree);
114
+ expect(groups.size).toBe(0);
115
+ });
116
+
117
+ test("+page.tsx and +page.server.ts in the same directory form one group", () => {
118
+ const tree = {
119
+ routes: [
120
+ makeRouteFile({
121
+ filePath: "/app/routes/blog/[slug]/+page.tsx",
122
+ type: "page",
123
+ paramNames: ["slug"],
124
+ }),
125
+ makeRouteFile({
126
+ filePath: "/app/routes/blog/[slug]/+page.server.ts",
127
+ type: "pageServer",
128
+ paramNames: ["slug"],
129
+ }),
130
+ ],
131
+ layouts: [],
132
+ servers: [],
133
+ errors: [],
134
+ };
135
+ const groups = groupByDirectory(tree);
136
+ expect(groups.size).toBe(1);
137
+ const group = groups.get("/app/routes/blog/[slug]")!;
138
+ expect(group).toBeDefined();
139
+ expect(group.page?.filePath).toBe("/app/routes/blog/[slug]/+page.tsx");
140
+ expect(group.pageServer?.filePath).toBe(
141
+ "/app/routes/blog/[slug]/+page.server.ts",
142
+ );
143
+ });
144
+
145
+ test("+layout files go into their own group separate from +page files", () => {
146
+ const tree = {
147
+ routes: [
148
+ makeRouteFile({ filePath: "/app/routes/+page.tsx", type: "page" }),
149
+ ],
150
+ layouts: [
151
+ makeRouteFile({ filePath: "/app/routes/+layout.tsx", type: "layout" }),
152
+ ],
153
+ servers: [],
154
+ errors: [],
155
+ };
156
+ const groups = groupByDirectory(tree);
157
+ expect(groups.size).toBe(1);
158
+ const group = groups.get("/app/routes")!;
159
+ expect(group.page).toBeDefined();
160
+ expect(group.layout).toBeDefined();
161
+ });
162
+
163
+ test("+server.ts creates a group with server field set", () => {
164
+ const tree = {
165
+ routes: [],
166
+ layouts: [],
167
+ servers: [
168
+ makeRouteFile({
169
+ filePath: "/app/routes/api/hello/+server.ts",
170
+ type: "server",
171
+ }),
172
+ ],
173
+ errors: [],
174
+ };
175
+ const groups = groupByDirectory(tree);
176
+ expect(groups.size).toBe(1);
177
+ expect(groups.get("/app/routes/api/hello")!.server).toBeDefined();
178
+ });
179
+
180
+ test("+error.tsx creates a group with error field set", () => {
181
+ const tree = {
182
+ routes: [],
183
+ layouts: [],
184
+ servers: [],
185
+ errors: [
186
+ makeRouteFile({
187
+ filePath: "/app/routes/+error.tsx",
188
+ type: "error",
189
+ }),
190
+ ],
191
+ };
192
+ const groups = groupByDirectory(tree);
193
+ expect(groups.size).toBe(1);
194
+ expect(groups.get("/app/routes")!.error).toBeDefined();
195
+ });
196
+
197
+ test("paramNames taken from the file with most params", () => {
198
+ const tree = {
199
+ routes: [
200
+ makeRouteFile({
201
+ filePath: "/app/routes/[org]/[repo]/+page.tsx",
202
+ type: "page",
203
+ paramNames: ["org", "repo"],
204
+ }),
205
+ makeRouteFile({
206
+ filePath: "/app/routes/[org]/[repo]/+page.server.ts",
207
+ type: "pageServer",
208
+ paramNames: ["org", "repo"],
209
+ }),
210
+ ],
211
+ layouts: [],
212
+ servers: [],
213
+ errors: [],
214
+ };
215
+ const groups = groupByDirectory(tree);
216
+ const group = groups.values().next().value!;
217
+ expect(group.paramNames).toEqual(["org", "repo"]);
218
+ });
219
+
220
+ test("simple files mixed with +page files: only +page files contribute to groups", () => {
221
+ const tree = {
222
+ routes: [
223
+ makeRouteFile({ filePath: "/app/routes/about.tsx", type: "simple" }),
224
+ makeRouteFile({
225
+ filePath: "/app/routes/blog/+page.tsx",
226
+ type: "page",
227
+ }),
228
+ ],
229
+ layouts: [],
230
+ servers: [],
231
+ errors: [],
232
+ };
233
+ const groups = groupByDirectory(tree);
234
+ expect(groups.size).toBe(1);
235
+ expect(groups.has("/app/routes/blog")).toBe(true);
236
+ expect(groups.has("/app/routes")).toBe(false);
237
+ });
238
+ });
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // generateTypes — integration (file system)
242
+ // ---------------------------------------------------------------------------
243
+
244
+ let tmpDir: string;
245
+
246
+ beforeAll(async () => {
247
+ tmpDir = join(tmpdir(), `grimoire-typegen-${Date.now()}`);
248
+ await mkdir(join(tmpDir, "src", "routes", "blog", "[slug]"), {
249
+ recursive: true,
250
+ });
251
+ await mkdir(join(tmpDir, "src", "routes", "api", "posts"), {
252
+ recursive: true,
253
+ });
254
+
255
+ // Layout at root
256
+ await writeFile(
257
+ join(tmpDir, "src", "routes", "+layout.tsx"),
258
+ "export default () => null;",
259
+ );
260
+
261
+ // Page-only route (no server)
262
+ await writeFile(
263
+ join(tmpDir, "src", "routes", "blog", "+page.tsx"),
264
+ "export default () => null;",
265
+ );
266
+
267
+ // Route with +page.server.ts that has a load function
268
+ await writeFile(
269
+ join(tmpDir, "src", "routes", "blog", "[slug]", "+page.tsx"),
270
+ "export default () => null;",
271
+ );
272
+ await writeFile(
273
+ join(tmpDir, "src", "routes", "blog", "[slug]", "+page.server.ts"),
274
+ `export async function load({ params }: { params: { slug: string } }) {
275
+ return { post: { title: "Hello", views: 42 } };
276
+ }
277
+ export async function DELETE({ request }: { request: Request }) {
278
+ return {};
279
+ }`,
280
+ );
281
+
282
+ // Route with +layout.server.ts
283
+ await writeFile(
284
+ join(tmpDir, "src", "routes", "blog", "+layout.server.ts"),
285
+ `export async function load() { return { nav: ["Home", "Blog"] }; }`,
286
+ );
287
+
288
+ // API route (+server.ts)
289
+ await writeFile(
290
+ join(tmpDir, "src", "routes", "api", "posts", "+server.ts"),
291
+ `export async function GET() { return Response.json([]); }
292
+ export async function POST() { return Response.json({}); }`,
293
+ );
294
+
295
+ // Error page
296
+ await writeFile(
297
+ join(tmpDir, "src", "routes", "+error.tsx"),
298
+ "export default () => null;",
299
+ );
300
+
301
+ // Simple file (should be ignored)
302
+ await writeFile(
303
+ join(tmpDir, "src", "routes", "about.tsx"),
304
+ "export default () => null;",
305
+ );
306
+
307
+ // Rest (catch-all) param route
308
+ await mkdir(join(tmpDir, "src", "routes", "files", "[...path]"), {
309
+ recursive: true,
310
+ });
311
+ await writeFile(
312
+ join(tmpDir, "src", "routes", "files", "[...path]", "+server.ts"),
313
+ `export async function GET() { return new Response("ok"); }`,
314
+ );
315
+ });
316
+
317
+ afterAll(async () => {
318
+ await rm(tmpDir, { recursive: true, force: true });
319
+ });
320
+
321
+ async function runGenerate() {
322
+ const routesDir = join(tmpDir, "src", "routes");
323
+ const tree = await scanRoutes(routesDir, tmpDir);
324
+ await generateTypes(tree, {
325
+ projectRoot: tmpDir,
326
+ routesDir,
327
+ outDir: join(tmpDir, ".grimoire", "types"),
328
+ });
329
+ }
330
+
331
+ async function readGenerated(routeRelPath: string) {
332
+ const p = join(tmpDir, ".grimoire", "types", routeRelPath, "$types.d.ts");
333
+ return readFile(p, "utf-8");
334
+ }
335
+
336
+ describe("generateTypes — output structure", () => {
337
+ test("creates ambient.d.ts with App.Locals namespace", async () => {
338
+ await runGenerate();
339
+ const ambient = await readFile(
340
+ join(tmpDir, ".grimoire", "types", "ambient.d.ts"),
341
+ "utf-8",
342
+ );
343
+ expect(ambient).toContain("declare namespace App");
344
+ expect(ambient).toContain("interface Locals");
345
+ });
346
+
347
+ test("creates tsconfig.generated.json with rootDirs", async () => {
348
+ const config = JSON.parse(
349
+ await readFile(
350
+ join(tmpDir, ".grimoire", "tsconfig.generated.json"),
351
+ "utf-8",
352
+ ),
353
+ );
354
+ expect(config.compilerOptions.rootDirs).toContain("..");
355
+ expect(config.compilerOptions.rootDirs).toContain("./types");
356
+ });
357
+
358
+ test("generates $types.d.ts for each route directory with + files", async () => {
359
+ expect(
360
+ existsSync(
361
+ join(tmpDir, ".grimoire", "types", "src", "routes", "$types.d.ts"),
362
+ ),
363
+ ).toBe(true);
364
+ expect(
365
+ existsSync(
366
+ join(
367
+ tmpDir,
368
+ ".grimoire",
369
+ "types",
370
+ "src",
371
+ "routes",
372
+ "blog",
373
+ "$types.d.ts",
374
+ ),
375
+ ),
376
+ ).toBe(true);
377
+ expect(
378
+ existsSync(
379
+ join(
380
+ tmpDir,
381
+ ".grimoire",
382
+ "types",
383
+ "src",
384
+ "routes",
385
+ "blog",
386
+ "[slug]",
387
+ "$types.d.ts",
388
+ ),
389
+ ),
390
+ ).toBe(true);
391
+ });
392
+
393
+ test("does NOT generate $types.d.ts for simple (non-+ convention) files", async () => {
394
+ // about.tsx is a simple file in src/routes/ — there's no $types for it
395
+ // (src/routes/ does get $types from +layout.tsx, but it's not created for about.tsx alone)
396
+ // Confirm that about/ directory itself has no $types
397
+ expect(
398
+ existsSync(
399
+ join(
400
+ tmpDir,
401
+ ".grimoire",
402
+ "types",
403
+ "src",
404
+ "routes",
405
+ "about",
406
+ "$types.d.ts",
407
+ ),
408
+ ),
409
+ ).toBe(false);
410
+ });
411
+ });
412
+
413
+ describe("generateTypes — route without +page.server.ts", () => {
414
+ test("PageData = Record<string, never>", async () => {
415
+ const content = await readGenerated("src/routes/blog");
416
+ expect(content).toContain("export type PageData = Record<string, never>;");
417
+ });
418
+
419
+ test("PageServerLoad = never", async () => {
420
+ const content = await readGenerated("src/routes/blog");
421
+ expect(content).toContain("export type PageServerLoad = never;");
422
+ });
423
+
424
+ test("Actions = Record<string, never>", async () => {
425
+ const content = await readGenerated("src/routes/blog");
426
+ expect(content).toContain("export type Actions = Record<string, never>;");
427
+ });
428
+
429
+ test("PageProps contains data and params", async () => {
430
+ const content = await readGenerated("src/routes/blog");
431
+ expect(content).toContain(
432
+ "export type PageProps = { data: PageData; params: Params };",
433
+ );
434
+ });
435
+ });
436
+
437
+ describe("generateTypes — route with +page.server.ts", () => {
438
+ test("uses typeof import() for the server module", async () => {
439
+ const content = await readGenerated("src/routes/blog/[slug]");
440
+ expect(content).toMatch(/type _PS = typeof import\("/);
441
+ });
442
+
443
+ test("import path ends with .js", async () => {
444
+ const content = await readGenerated("src/routes/blog/[slug]");
445
+ const match = content.match(/typeof import\("([^"]+)"\)/);
446
+ expect(match?.[1]).toMatch(/\.js$/);
447
+ });
448
+
449
+ test("import path contains only forward slashes", async () => {
450
+ const content = await readGenerated("src/routes/blog/[slug]");
451
+ const match = content.match(/typeof import\("([^"]+)"\)/);
452
+ expect(match?.[1]).not.toContain("\\");
453
+ });
454
+
455
+ test("PageData inferred from load() via ReturnType", async () => {
456
+ const content = await readGenerated("src/routes/blog/[slug]");
457
+ expect(content).toContain(
458
+ 'export type PageData = "load" extends keyof _PS',
459
+ );
460
+ expect(content).toContain('Awaited<ReturnType<_PS["load"]>>');
461
+ });
462
+
463
+ test("PageProps = { data: PageData; params: Params }", async () => {
464
+ const content = await readGenerated("src/routes/blog/[slug]");
465
+ expect(content).toContain(
466
+ "export type PageProps = { data: PageData; params: Params };",
467
+ );
468
+ });
469
+
470
+ test("Actions excludes load and default from keys", async () => {
471
+ const content = await readGenerated("src/routes/blog/[slug]");
472
+ expect(content).toContain(
473
+ 'type _ActionKeys = Exclude<keyof _PS, "load" | "default">;',
474
+ );
475
+ });
476
+
477
+ test("Params has slug typed as string", async () => {
478
+ const content = await readGenerated("src/routes/blog/[slug]");
479
+ expect(content).toContain("slug: string;");
480
+ });
481
+ });
482
+
483
+ describe("generateTypes — +layout.server.ts", () => {
484
+ test("LayoutData inferred from load() via typeof import", async () => {
485
+ const content = await readGenerated("src/routes/blog");
486
+ expect(content).toMatch(/type _LS = typeof import\("/);
487
+ expect(content).toContain(
488
+ 'export type LayoutData = "load" extends keyof _LS',
489
+ );
490
+ expect(content).toContain('Awaited<ReturnType<_LS["load"]>>');
491
+ });
492
+
493
+ test("LayoutProps includes children", async () => {
494
+ const content = await readGenerated("src/routes/blog");
495
+ expect(content).toContain("children?: unknown");
496
+ });
497
+ });
498
+
499
+ describe("generateTypes — +server.ts (API route)", () => {
500
+ test("generates ServerHandlers type", async () => {
501
+ const content = await readGenerated("src/routes/api/posts");
502
+ expect(content).toContain("export type ServerHandlers");
503
+ });
504
+
505
+ test("uses typeof import() for server module", async () => {
506
+ const content = await readGenerated("src/routes/api/posts");
507
+ expect(content).toMatch(/type _SRV = typeof import\("/);
508
+ });
509
+
510
+ test("extracts HTTP method keys", async () => {
511
+ const content = await readGenerated("src/routes/api/posts");
512
+ expect(content).toContain("_HttpMethods");
513
+ expect(content).toContain("_ServerKeys");
514
+ });
515
+ });
516
+
517
+ describe("generateTypes — +error.tsx", () => {
518
+ test("generates ErrorProps type", async () => {
519
+ const content = await readGenerated("src/routes");
520
+ expect(content).toContain(
521
+ "export type ErrorProps = { status: number; message: string; error: unknown; route: string };",
522
+ );
523
+ });
524
+ });
525
+
526
+ describe("generateTypes — rest (catch-all) params", () => {
527
+ test("Params includes rest param name as string", async () => {
528
+ const content = await readGenerated("src/routes/files/[...path]");
529
+ expect(content).toContain("path: string;");
530
+ expect(content).toMatch(/export type Params = \{\s+path: string;\s+\};/);
531
+ });
532
+ });
533
+
534
+ // This behavior no lnger exists
535
+ // describe("generateTypes — clears stale output", () => {
536
+ // test("removes files from a deleted route on re-run", async () => {
537
+ // // First run already happened in beforeAll via runGenerate()
538
+ // // Write a stale file manually
539
+ // const staleDir = join(
540
+ // tmpDir,
541
+ // ".grimoire",
542
+ // "types",
543
+ // "src",
544
+ // "routes",
545
+ // "old-route",
546
+ // );
547
+ // await mkdir(staleDir, { recursive: true });
548
+ // await writeFile(join(staleDir, "$types.d.ts"), "// stale");
549
+
550
+ // // Re-run
551
+ // await runGenerate();
552
+
553
+ // // Stale file should be gone
554
+ // expect(existsSync(join(staleDir, "$types.d.ts"))).toBe(false);
555
+ // });
556
+ // });
557
+
558
+ // ---------------------------------------------------------------------------
559
+ // tsc integration — proves the generated types actually type-check
560
+ // ---------------------------------------------------------------------------
561
+
562
+ describe("tsc integration", () => {
563
+ let tscDir: string;
564
+
565
+ beforeAll(async () => {
566
+ tscDir = join(tmpdir(), `grimoire-tsc-${Date.now()}`);
567
+ const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
568
+ await mkdir(routeDir, { recursive: true });
569
+
570
+ // Minimal +page.server.ts whose return type flows through to PageProps
571
+ await writeFile(
572
+ join(routeDir, "+page.server.ts"),
573
+ `export async function load({ params }: { params: { slug: string } }) {
574
+ return { post: { title: "Hello", views: 42 } };
575
+ }`,
576
+ );
577
+
578
+ // File that uses the generated types — must live in the route dir for ./$types to resolve
579
+ await writeFile(
580
+ join(routeDir, "check.ts"),
581
+ `import type { PageProps } from "./$types";
582
+ declare const props: PageProps;
583
+ const _title: string = props.data.post.title;
584
+ const _views: number = props.data.post.views;
585
+ const _slug: string = props.params.slug;
586
+ export {};`,
587
+ );
588
+
589
+ // tsconfig for this mini-project
590
+ await writeFile(
591
+ join(tscDir, "tsconfig.json"),
592
+ JSON.stringify(
593
+ {
594
+ extends: "./.grimoire/tsconfig.generated.json",
595
+ compilerOptions: {
596
+ target: "ESNext",
597
+ module: "ESNext",
598
+ moduleResolution: "bundler",
599
+ strict: true,
600
+ skipLibCheck: true,
601
+ noEmit: true,
602
+ },
603
+ include: ["src", ".grimoire/types"],
604
+ },
605
+ null,
606
+ 2,
607
+ ),
608
+ );
609
+
610
+ // Generate types
611
+ const routesDir = join(tscDir, "src", "routes");
612
+ const tree = await scanRoutes(routesDir, tscDir);
613
+ await generateTypes(tree, {
614
+ projectRoot: tscDir,
615
+ routesDir,
616
+ outDir: join(tscDir, ".grimoire", "types"),
617
+ });
618
+ });
619
+
620
+ afterAll(async () => {
621
+ await rm(tscDir, { recursive: true, force: true });
622
+ });
623
+
624
+ function runTsc(cwd: string) {
625
+ const proc = Bun.spawnSync(
626
+ [
627
+ process.execPath,
628
+ "x",
629
+ "--bun",
630
+ "@typescript/native-preview",
631
+ "--noEmit",
632
+ "--project",
633
+ "tsconfig.json",
634
+ ],
635
+ { cwd },
636
+ );
637
+ return proc;
638
+ }
639
+
640
+ test("check.ts with correct types passes tsc", () => {
641
+ const result = runTsc(tscDir);
642
+ // Ignore bun package-download messages; only care about exit code
643
+ expect(result.exitCode).toBe(0);
644
+ });
645
+
646
+ test("accessing a non-existent property fails tsc", async () => {
647
+ // Add a file with a wrong property access
648
+ const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
649
+ await writeFile(
650
+ join(routeDir, "bad.ts"),
651
+ `import type { PageProps } from "./$types";
652
+ declare const props: PageProps;
653
+ const _bad = props.post.bogus;
654
+ export {};`,
655
+ );
656
+
657
+ const result = runTsc(tscDir);
658
+ expect(result.exitCode).not.toBe(0);
659
+
660
+ // Clean up so subsequent test runs are clean
661
+ const { unlink } = await import("node:fs/promises");
662
+ await unlink(join(routeDir, "bad.ts"));
663
+ });
664
+
665
+ test("params properties are typed as string", async () => {
666
+ // Assigning params.slug to a number should fail
667
+ const routeDir = join(tscDir, "src", "routes", "blog", "[slug]");
668
+ await writeFile(
669
+ join(routeDir, "wrong-param-type.ts"),
670
+ `import type { PageProps } from "./$types";
671
+ declare const props: PageProps;
672
+ const _n: number = props.params.slug;
673
+ export {};`,
674
+ );
675
+
676
+ const result = runTsc(tscDir);
677
+ expect(result.exitCode).not.toBe(0);
678
+
679
+ const { unlink } = await import("node:fs/promises");
680
+ await unlink(join(routeDir, "wrong-param-type.ts"));
681
+ });
682
+ });