@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.
@@ -1,854 +1,904 @@
1
- import { beforeEach, describe, expect, test, vi } from "bun:test";
2
- import type { Document, History, Location, Window } from "happy-dom";
3
- import {
4
- clearDeps,
5
- depends,
6
- hasDep,
7
- setDeps,
8
- startCollecting,
9
- stopCollecting,
10
- } from "../src/client/deps.ts";
11
-
12
- // test/preload.ts installs happy-dom globals at runtime; this package's
13
- // compiler options have no DOM lib, so declare the shapes we rely on.
14
- declare global {
15
- // biome-ignore-all lint/style/noVar: ambient global declarations require var
16
- var window: Window;
17
- var document: Document;
18
- var location: Location;
19
- var history: History;
20
- var MouseEvent: Window["MouseEvent"];
21
- var Event: Window["Event"];
22
- var requestAnimationFrame: Window["requestAnimationFrame"];
23
- }
24
-
25
- // router.ts reads `location` at module load — DOM globals must exist first.
26
- // Dynamic import is required because the module under test captures location
27
- // during evaluation, which static-hoisted imports would race. The default
28
- // about:blank URL has origin "null", which breaks new URL(href, origin) —
29
- // point the window at a real origin first.
30
- window.location.href = "http://localhost/";
31
- const globalEnv = globalThis as typeof globalThis & {
32
- location: Location;
33
- history: History;
34
- requestAnimationFrame: Window["requestAnimationFrame"];
35
- };
36
- globalEnv.location = window.location;
37
- globalEnv.history = window.history;
38
- globalEnv.requestAnimationFrame = window.requestAnimationFrame.bind(window);
39
- const router = await import("../src/client/router.ts");
40
-
41
- function jsonResponse(pattern: string): Response {
42
- return new Response(
43
- JSON.stringify({
44
- data: {},
45
- layoutData: [],
46
- params: {},
47
- pattern,
48
- head: "",
49
- }),
50
- { headers: { "content-type": "application/json" } },
51
- );
52
- }
53
-
54
- function captureFetch(): {
55
- calls: Array<{ input: string; init?: RequestInit }>;
56
- restore: () => void;
57
- } {
58
- const calls: Array<{ input: string; init?: RequestInit }> = [];
59
- const original = globalThis.fetch;
60
- // test shim over the global — precise fetch typing is impossible here.
61
- // Echoes the requested pathname as the route pattern, mirroring renderRoute.
62
- globalThis.fetch = (async (
63
- input: string,
64
- init?: RequestInit,
65
- ): Promise<Response> => {
66
- calls.push({ input, init });
67
- const pattern = new URL(input, "http://localhost").pathname;
68
- return jsonResponse(pattern);
69
- }) as unknown as typeof fetch;
70
- return {
71
- calls,
72
- restore: () => {
73
- globalThis.fetch = original;
74
- },
75
- };
76
- }
77
-
78
- describe("depends", () => {
79
- test("no-op outside collection", () => {
80
- depends("posts");
81
- expect(hasDep("/", "posts")).toBe(false);
82
- });
83
-
84
- test("registers key during collection", () => {
85
- startCollecting();
86
- depends("posts");
87
- stopCollecting("/");
88
- expect(hasDep("/", "posts")).toBe(true);
89
- });
90
-
91
- test("multiple keys", () => {
92
- startCollecting();
93
- depends("posts");
94
- depends("tags");
95
- stopCollecting("/");
96
- expect(hasDep("/", "posts")).toBe(true);
97
- expect(hasDep("/", "tags")).toBe(true);
98
- });
99
-
100
- test("cleared on next collection", () => {
101
- startCollecting();
102
- depends("posts");
103
- stopCollecting("/");
104
- startCollecting();
105
- depends("comments");
106
- stopCollecting("/");
107
- expect(hasDep("/", "posts")).toBe(false);
108
- expect(hasDep("/", "comments")).toBe(true);
109
- });
110
- });
111
- describe("navigate — head", () => {
112
- test("server-rendered head tags are replaced, not kept beside the new ones", async () => {
113
- const root = document.createElement("div");
114
- root.id = "grimoire-root";
115
- document.body.appendChild(root);
116
- document.head.innerHTML =
117
- '<meta charset="UTF-8"><!--grimoire-head--><title>Old</title><meta name="description" content="old"><!--/grimoire-head-->';
118
- const g = globalThis as { DOMParser?: unknown };
119
- g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
120
- const original = globalThis.fetch;
121
- globalThis.fetch = (async () =>
122
- new Response(
123
- JSON.stringify({
124
- data: {},
125
- layoutData: [],
126
- params: {},
127
- pattern: "/",
128
- head: '<title>New</title><meta name="description" content="new">',
129
- }),
130
- { headers: { "content-type": "application/json" } },
131
- )) as unknown as typeof fetch;
132
- try {
133
- router.initRouter({ "/": () => document.createElement("main") }, []);
134
- await router.navigate("/");
135
- const descriptions = [
136
- ...document.head.querySelectorAll('meta[name="description"]'),
137
- ].map((m) => m.getAttribute("content"));
138
- expect(descriptions).toEqual(["new"]);
139
- expect(document.title).toBe("New");
140
- expect(document.head.querySelectorAll("meta[charset]").length).toBe(1);
141
- // a second navigation replaces the tags the first one added
142
- await router.navigate("/");
143
- expect(
144
- document.head.querySelectorAll('meta[name="description"]').length,
145
- ).toBe(1);
146
- } finally {
147
- globalThis.fetch = original;
148
- root.remove();
149
- document.head.innerHTML = "";
150
- }
151
- });
152
- });
153
-
154
- describe("navigate — loading export", () => {
155
- test("a lazy page module's loading export shows while data loads", async () => {
156
- // other files' tests may leave a page host behind
157
- for (const id of ["grimoire-root", "grimoire-page"])
158
- document.getElementById(id)?.remove();
159
- const root = document.createElement("div");
160
- root.id = "grimoire-root";
161
- const page = document.createElement("div");
162
- page.id = "grimoire-page";
163
- root.appendChild(page);
164
- document.body.appendChild(root);
165
- let release!: () => void;
166
- const gate = new Promise<void>((r) => (release = r));
167
- const original = globalThis.fetch;
168
- globalThis.fetch = (async () => {
169
- await gate;
170
- return jsonResponse("/slow");
171
- }) as unknown as typeof fetch;
172
- try {
173
- const Page = () => {
174
- const el = document.createElement("p");
175
- el.textContent = "page";
176
- return el;
177
- };
178
- const loading = () => {
179
- const el = document.createElement("p");
180
- el.textContent = "loading";
181
- return el;
182
- };
183
- router.initRouter(
184
- { "/slow": { __lazy: async () => ({ default: Page, loading }) } },
185
- [],
186
- );
187
- const done = router.navigate("/slow");
188
- for (let i = 0; i < 20 && !root.textContent?.includes("loading"); i++)
189
- await new Promise((r) => setTimeout(r, 5));
190
- expect(root.textContent).toContain("loading");
191
- release();
192
- await done;
193
- expect(root.textContent).toContain("page");
194
- } finally {
195
- globalThis.fetch = original;
196
- root.remove();
197
- }
198
- });
199
- });
200
-
201
- describe("navigate — a route chunk that fails to load", () => {
202
- // After a rebuild or a deploy, an open tab's bundle still names the old
203
- // chunks, and those are gone. The import rejects; the router must load the
204
- // page from the server instead of dying on an unhandled rejection.
205
- test("falls back to a full page load", async () => {
206
- const root = document.createElement("div");
207
- root.id = "grimoire-root";
208
- document.body.appendChild(root);
209
- const fetchShim = captureFetch();
210
- const href = location.href;
211
- try {
212
- router.initRouter(
213
- {
214
- "/gone": {
215
- __lazy: async () => {
216
- throw new TypeError(
217
- "error loading dynamically imported module: /__grimoire__/chunk-old.js",
218
- );
219
- },
220
- },
221
- },
222
- [],
223
- );
224
- await router.navigate("/gone");
225
- expect(location.pathname).toBe("/gone");
226
- } finally {
227
- fetchShim.restore();
228
- root.remove();
229
- location.href = href;
230
- }
231
- });
232
- });
233
-
234
- describe("navigate — view transitions", () => {
235
- test("falls back to direct swap when startViewTransition is missing", async () => {
236
- const root = document.createElement("div");
237
- root.id = "grimoire-root";
238
- document.body.appendChild(root);
239
- const fetchShim = captureFetch();
240
- try {
241
- router.initRouter({ "/": () => document.createElement("main") }, []);
242
- await router.navigate("/");
243
- expect(root.childNodes.length).toBeGreaterThan(0);
244
- } finally {
245
- fetchShim.restore();
246
- root.remove();
247
- }
248
- });
249
-
250
- test("routes the swap through startViewTransition when available", async () => {
251
- const root = document.createElement("div");
252
- root.id = "grimoire-root";
253
- document.body.appendChild(root);
254
- let vtCalled = false;
255
- const docEnv = document as Document & {
256
- startViewTransition?: (cb: () => void) => unknown;
257
- };
258
- docEnv.startViewTransition = (cb: () => void) => {
259
- vtCalled = true;
260
- cb();
261
- return undefined;
262
- };
263
- const fetchShim = captureFetch();
264
- try {
265
- router.initRouter({ "/vt": () => document.createElement("main") }, []);
266
- await router.navigate("/vt");
267
- expect(vtCalled).toBe(true);
268
- expect(root.childNodes.length).toBeGreaterThan(0);
269
- } finally {
270
- delete docEnv.startViewTransition;
271
- fetchShim.restore();
272
- root.remove();
273
- }
274
- });
275
- });
276
-
277
- describe("shared-element view transitions", () => {
278
- const nameOf = (el: Element) =>
279
- (el as HTMLElement).style.getPropertyValue("view-transition-name");
280
-
281
- test("elements sharing data-sigil-transition are named on both pages", async () => {
282
- const root = document.createElement("div");
283
- root.id = "grimoire-root";
284
- const oldHero = document.createElement("img");
285
- oldHero.setAttribute("data-sigil-transition", "hero-7");
286
- const other = document.createElement("img");
287
- other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
288
- root.append(oldHero, other);
289
- document.body.appendChild(root);
290
-
291
- let newHero: Element | undefined;
292
- const page = () => {
293
- const main = document.createElement("main");
294
- newHero = document.createElement("img");
295
- newHero.setAttribute("data-sigil-transition", "hero-7");
296
- main.appendChild(newHero);
297
- return main;
298
- };
299
- const docEnv = document as unknown as {
300
- startViewTransition?: (cb: () => void) => unknown;
301
- };
302
- const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] =
303
- [];
304
- docEnv.startViewTransition = (cb: () => void) => {
305
- const before = {
306
- oldNamed: nameOf(oldHero),
307
- otherNamed: nameOf(other),
308
- newNamed: "",
309
- };
310
- cb();
311
- before.newNamed = nameOf(newHero!);
312
- seen.push(before);
313
- return { finished: Promise.resolve() };
314
- };
315
- const shim = captureFetch();
316
- try {
317
- router.initRouter({ "/shared": page }, []);
318
- await router.navigate("/shared");
319
- // the old element is named when the browser snapshots, the new one
320
- // once the swap ran; an element with no partner is left alone
321
- expect(seen).toEqual([
322
- { oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" },
323
- ]);
324
- await Promise.resolve();
325
- await Promise.resolve();
326
- expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
327
- } finally {
328
- delete docEnv.startViewTransition;
329
- shim.restore();
330
- root.remove();
331
- }
332
- });
333
-
334
- test("a key used twice on a page is skipped", async () => {
335
- const root = document.createElement("div");
336
- root.id = "grimoire-root";
337
- for (let i = 0; i < 2; i++) {
338
- const el = document.createElement("div");
339
- el.setAttribute("data-sigil-transition", "dup");
340
- root.appendChild(el);
341
- }
342
- document.body.appendChild(root);
343
- const docEnv = document as unknown as {
344
- startViewTransition?: (cb: () => void) => unknown;
345
- };
346
- let named = 0;
347
- docEnv.startViewTransition = (cb: () => void) => {
348
- named = document.querySelectorAll(
349
- '[style*="view-transition-name"]',
350
- ).length;
351
- cb();
352
- return undefined;
353
- };
354
- const shim = captureFetch();
355
- try {
356
- router.initRouter(
357
- {
358
- "/dup": () => {
359
- const el = document.createElement("div");
360
- el.setAttribute("data-sigil-transition", "dup");
361
- return el;
362
- },
363
- },
364
- [],
365
- );
366
- await router.navigate("/dup");
367
- expect(named).toBe(0);
368
- } finally {
369
- delete docEnv.startViewTransition;
370
- shim.restore();
371
- root.remove();
372
- }
373
- });
374
- });
375
-
376
- describe("hover prefetch", () => {
377
- // The 80ms debounce is real timer logic under test — fake timers advance
378
- // it deterministically instead of sleeping past it.
379
- test("plain internal link prefetches route data; preload=off skips", () => {
380
- vi.useFakeTimers();
381
- router.initRouter(
382
- {
383
- "/": () => document.createElement("div"),
384
- "/off": () => document.createElement("div"),
385
- },
386
- [],
387
- );
388
- const fetchShim = captureFetch();
389
- try {
390
- const plain = document.createElement("a");
391
- plain.setAttribute("href", "/");
392
- document.body.appendChild(plain);
393
- plain.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
394
- vi.advanceTimersByTime(80);
395
- expect(fetchShim.calls.length).toBe(1);
396
- expect(fetchShim.calls[0]?.init?.headers).toEqual({
397
- "x-grimoire-navigate": "1",
398
- });
399
-
400
- const optedOut = document.createElement("a");
401
- optedOut.setAttribute("href", "/off");
402
- optedOut.setAttribute("data-sigil-preload", "off");
403
- document.body.appendChild(optedOut);
404
- optedOut.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
405
- vi.advanceTimersByTime(80);
406
- expect(fetchShim.calls.length).toBe(1); // unchanged
407
- } finally {
408
- vi.useRealTimers();
409
- fetchShim.restore();
410
- }
411
- });
412
-
413
- test("external links are never prefetched", () => {
414
- vi.useFakeTimers();
415
- const fetchShim = captureFetch();
416
- try {
417
- const ext = document.createElement("a");
418
- ext.setAttribute("href", "https://example.com/page");
419
- document.body.appendChild(ext);
420
- ext.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
421
- vi.advanceTimersByTime(80);
422
- expect(fetchShim.calls.length).toBe(0);
423
- } finally {
424
- vi.useRealTimers();
425
- fetchShim.restore();
426
- }
427
- });
428
- });
429
-
430
- describe("prefetch reuse", () => {
431
- test("a tap reuses the request started on touchstart", async () => {
432
- const root = document.createElement("div");
433
- root.id = "grimoire-root";
434
- document.body.appendChild(root);
435
- router.initRouter({ "/tap": () => document.createElement("main") }, []);
436
- const shim = captureFetch();
437
- try {
438
- const a = document.createElement("a");
439
- a.setAttribute("href", "/tap");
440
- document.body.appendChild(a);
441
- a.dispatchEvent(new Event("touchstart", { bubbles: true }));
442
- expect(shim.calls.length).toBe(1);
443
-
444
- await router.navigate("/tap");
445
- // the click did not issue a second request
446
- expect(shim.calls.length).toBe(1);
447
- expect(root.childNodes.length).toBeGreaterThan(0);
448
-
449
- // and a prefetch is single-use: the next visit fetches fresh data
450
- await router.navigate("/tap");
451
- expect(shim.calls.length).toBe(2);
452
- } finally {
453
- shim.restore();
454
- root.remove();
455
- }
456
- });
457
-
458
- test("a click cancels the hover prefetch it just consumed", async () => {
459
- const root = document.createElement("div");
460
- root.id = "grimoire-root";
461
- document.body.appendChild(root);
462
- router.initRouter({ "/hov": () => document.createElement("main") }, []);
463
- const shim = captureFetch();
464
- try {
465
- const a = document.createElement("a");
466
- a.setAttribute("href", "/hov");
467
- document.body.appendChild(a);
468
- a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
469
- a.dispatchEvent(
470
- new MouseEvent("click", { bubbles: true, cancelable: true }),
471
- );
472
- await Bun.sleep(200); // past the 80ms hover delay
473
- expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
474
- expect(shim.calls.length).toBe(1); // its own request, not a second
475
- } finally {
476
- shim.restore();
477
- root.remove();
478
- }
479
- });
480
-
481
- test("a prefetch made before a cookie changed is not reused", async () => {
482
- const root = document.createElement("div");
483
- root.id = "grimoire-root";
484
- document.body.appendChild(root);
485
- router.initRouter({ "/pref": () => document.createElement("main") }, []);
486
- const shim = captureFetch();
487
- try {
488
- document.cookie = "region=jp";
489
- router.prefetch("/pref");
490
- expect(shim.calls.length).toBe(1);
491
- document.cookie = "region=en"; // the visitor switched server
492
- await router.navigate("/pref");
493
- // the held response was fetched as jp, so the click asks again
494
- expect(shim.calls.length).toBe(2);
495
- } finally {
496
- document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
497
- shim.restore();
498
- root.remove();
499
- }
500
- });
501
-
502
- test("invalidateAll never serves a prefetched response", async () => {
503
- const root = document.createElement("div");
504
- root.id = "grimoire-root";
505
- document.body.appendChild(root);
506
- window.history.pushState(null, "", "/inv");
507
- router.initRouter({ "/inv": () => document.createElement("main") }, []);
508
- const shim = captureFetch();
509
- try {
510
- await router.navigate("/inv");
511
- router.prefetch("/inv");
512
- const before = shim.calls.length;
513
- await router.invalidateAll();
514
- expect(shim.calls.length).toBe(before + 1);
515
- } finally {
516
- shim.restore();
517
- root.remove();
518
- }
519
- });
520
- });
521
-
522
- describe("popstate — query string", () => {
523
- // popstate fires navigate() from an event listener, so there is no promise
524
- // to await at the call site. afterNavigate is the router's own completion
525
- // signal; a fixed sleep would be both slower and racy.
526
- function onNavigated(): Promise<void> {
527
- const { promise, resolve } = Promise.withResolvers<void>();
528
- router.afterNavigate(() => resolve());
529
- return promise;
530
- }
531
-
532
- // Back used to refetch the bare pathname, so a query-driven page rendered
533
- // unfiltered data while the address bar still showed the query.
534
- test("back to a query URL refetches with the query intact", async () => {
535
- const root = document.createElement("div");
536
- root.id = "grimoire-root";
537
- document.body.appendChild(root);
538
- window.history.pushState(null, "", "/");
539
- router.initRouter(
540
- {
541
- "/list": () => document.createElement("div"),
542
- "/other": () => document.createElement("div"),
543
- },
544
- [],
545
- );
546
- const shim = captureFetch();
547
- try {
548
- await router.navigate("/list?q=fireball&page=2");
549
- await router.navigate("/other");
550
- shim.calls.length = 0;
551
-
552
- // the browser moves history itself, then fires popstate
553
- const navigated = onNavigated();
554
- window.history.pushState(null, "", "/list?q=fireball&page=2");
555
- window.dispatchEvent(new Event("popstate"));
556
- await navigated;
557
-
558
- expect(shim.calls.map((c) => c.input)).toEqual([
559
- "/list?q=fireball&page=2",
560
- ]);
561
- } finally {
562
- router.afterNavigate(() => {});
563
- shim.restore();
564
- root.remove();
565
- }
566
- });
567
-
568
- test("a popstate that only changes the query still refetches", async () => {
569
- const root = document.createElement("div");
570
- root.id = "grimoire-root";
571
- document.body.appendChild(root);
572
- window.history.pushState(null, "", "/");
573
- router.initRouter({ "/list": () => document.createElement("div") }, []);
574
- const shim = captureFetch();
575
- try {
576
- await router.navigate("/list?page=2");
577
- shim.calls.length = 0;
578
-
579
- const navigated = onNavigated();
580
- window.history.pushState(null, "", "/list?page=1");
581
- window.dispatchEvent(new Event("popstate"));
582
- await navigated;
583
-
584
- expect(shim.calls.map((c) => c.input)).toEqual(["/list?page=1"]);
585
- } finally {
586
- router.afterNavigate(() => {});
587
- shim.restore();
588
- root.remove();
589
- }
590
- });
591
- });
592
-
593
- describe("enhance — named action URLs", () => {
594
- test("action starting with ?/ submits to the current pathname", async () => {
595
- // earlier navigate() tests moved history — reset to a clean path
596
- window.history.pushState(null, "", "/");
597
- const { enhance } = await import("../src/client/enhance.ts");
598
- const calls: string[] = [];
599
- const original = globalThis.fetch;
600
- globalThis.fetch = (async (input: string) => {
601
- calls.push(input);
602
- return new Response(null, { status: 303, headers: { location: "/" } });
603
- }) as unknown as typeof fetch;
604
-
605
- const form = document.createElement("form");
606
- document.body.appendChild(form);
607
- const cleanup = enhance(form, { action: "?/create" });
608
- try {
609
- form.dispatchEvent(
610
- new Event("submit", { bubbles: true, cancelable: true }),
611
- );
612
- await new Promise((r) => setTimeout(r, 0));
613
- expect(calls).toEqual([`${window.location.pathname}?/create`]);
614
- } finally {
615
- cleanup();
616
- form.remove();
617
- globalThis.fetch = original;
618
- }
619
- });
620
- });
621
-
622
- describe("enhance — outcomes", () => {
623
- async function submit(
624
- reply: Response,
625
- options: Record<string, unknown> = {},
626
- submitter?: HTMLButtonElement,
627
- ) {
628
- window.history.pushState(null, "", "/books");
629
- const { enhance } = await import("../src/client/enhance.ts");
630
- const sent: { headers: Headers; body: FormData }[] = [];
631
- const navigations: [string, boolean | undefined][] = [];
632
- const g = globalThis as Record<string, unknown>;
633
- const originalFetch = globalThis.fetch;
634
- const originalNavigate = g.__grimoire_navigate__;
635
- globalThis.fetch = (async (_input: string, init: RequestInit) => {
636
- sent.push({
637
- headers: new Headers(init.headers),
638
- body: init.body as FormData,
639
- });
640
- return reply;
641
- }) as unknown as typeof fetch;
642
- g.__grimoire_navigate__ = (path: string, replace?: boolean) =>
643
- navigations.push([path, replace]);
644
-
645
- const form = document.createElement("form");
646
- form.setAttribute("action", "?/toggle");
647
- const input = document.createElement("input");
648
- input.setAttribute("name", "id");
649
- input.setAttribute("value", "7");
650
- form.appendChild(input);
651
- if (submitter) form.appendChild(submitter);
652
- document.body.appendChild(form);
653
- const cleanup = enhance(form, options);
654
- try {
655
- const event = new Event("submit", { bubbles: true, cancelable: true });
656
- if (submitter)
657
- Object.defineProperty(event, "submitter", { value: submitter });
658
- form.dispatchEvent(event);
659
- await new Promise((r) => setTimeout(r, 0));
660
- return { sent, navigations };
661
- } finally {
662
- cleanup();
663
- form.remove();
664
- globalThis.fetch = originalFetch;
665
- g.__grimoire_navigate__ = originalNavigate;
666
- }
667
- }
668
-
669
- test("success on the same page re-runs its loads in place", async () => {
670
- const seen: unknown[] = [];
671
- const { sent, navigations } = await submit(
672
- Response.json({
673
- type: "success",
674
- location: "http://localhost/books",
675
- data: { ok: 1 },
676
- }),
677
- { onSuccess: (r: unknown) => seen.push(r) },
678
- );
679
- expect(sent[0]!.headers.get("x-grimoire-form")).toBe("1");
680
- expect(seen).toEqual([
681
- { redirect: "http://localhost/books", data: { ok: 1 } },
682
- ]);
683
- // replace: no new history entry for the same page
684
- expect(navigations).toEqual([["/books", true]]);
685
- });
686
-
687
- test("a redirect elsewhere pushes a new entry", async () => {
688
- const { navigations } = await submit(
689
- Response.json({ type: "redirect", status: 303, location: "/books/7" }),
690
- );
691
- expect(navigations).toEqual([["/books/7", false]]);
692
- });
693
-
694
- test("fail() data goes to onFail, and nothing navigates", async () => {
695
- const failed: unknown[] = [];
696
- const { navigations } = await submit(
697
- Response.json(
698
- { fail: true, status: 400, data: { problem: "x" } },
699
- { status: 400 },
700
- ),
701
- { onFail: (d: unknown) => failed.push(d) },
702
- );
703
- expect(failed).toEqual([{ problem: "x" }]);
704
- expect(navigations).toEqual([]);
705
- });
706
-
707
- test("the submitting button's name=value is sent", async () => {
708
- const button = document.createElement("button");
709
- button.name = "read";
710
- button.value = "1";
711
- const { sent } = await submit(
712
- Response.json({ type: "success", location: "/books", data: null }),
713
- {},
714
- button,
715
- );
716
- expect(sent[0]!.body.get("read")).toBe("1");
717
- });
718
- });
719
-
720
- describe("Page.load — parent()", () => {
721
- test("parent() merges layoutData entries outermost-first", async () => {
722
- let seenParent: Record<string, unknown> | undefined;
723
- const PageWithLoad = Object.assign(() => document.createElement("div"), {
724
- load: async (ctx: { parent: () => Promise<Record<string, unknown>> }) => {
725
- seenParent = await ctx.parent();
726
- return {};
727
- },
728
- });
729
-
730
- const original = globalThis.fetch;
731
- globalThis.fetch = (async (input: string) => {
732
- const pattern = new URL(input, "http://localhost").pathname;
733
- return new Response(
734
- JSON.stringify({
735
- data: {},
736
- layoutData: [{ a: 1 }, { b: 2 }],
737
- params: {},
738
- pattern,
739
- head: "",
740
- }),
741
- { headers: { "content-type": "application/json" } },
742
- );
743
- }) as unknown as typeof fetch;
744
-
745
- try {
746
- router.initRouter({ "/pl": PageWithLoad }, []);
747
- await router.navigate("/pl");
748
- expect(seenParent).toEqual({ a: 1, b: 2 });
749
- } finally {
750
- globalThis.fetch = original;
751
- }
752
- });
753
- });
754
-
755
- describe("invalidate", () => {
756
- test("refetches only on key intersection; empty deps always refetch", async () => {
757
- router.initRouter({ "/": () => document.createElement("div") }, []);
758
- const shim = captureFetch();
759
- try {
760
- await router.navigate("/"); // establishes lastState.pattern = "/"
761
-
762
- setDeps("/", ["user:1"]);
763
- shim.calls.length = 0;
764
- await router.invalidate("other");
765
- expect(shim.calls.length).toBe(0); // no intersection → skip
766
-
767
- await router.invalidate("user:1");
768
- expect(shim.calls.length).toBe(1); // intersect → refetch
769
-
770
- clearDeps("/");
771
- await router.invalidate("anything");
772
- expect(shim.calls.length).toBe(2); // no deps → conservative refetch
773
- } finally {
774
- shim.restore();
775
- clearDeps("/");
776
- }
777
- });
778
- });
779
-
780
- describe("invalidate keeps the query string", () => {
781
- test("a filtered page reloads with its filters", async () => {
782
- const root = document.createElement("div");
783
- root.id = "grimoire-root";
784
- document.body.appendChild(root);
785
- router.initRouter({ "/search": () => document.createElement("main") }, []);
786
- const shim = captureFetch();
787
- try {
788
- await router.navigate("/search?q=dune&page=2");
789
- shim.calls.length = 0;
790
- await router.invalidateAll();
791
- expect(shim.calls.length).toBe(1);
792
- expect(shim.calls[0]!.input).toContain("q=dune");
793
- expect(shim.calls[0]!.input).toContain("page=2");
794
- } finally {
795
- shim.restore();
796
- root.remove();
797
- }
798
- });
799
- });
800
-
801
- describe("navigate — under a base", () => {
802
- test("fetches and records the full path, but routes and loads see the route path", async () => {
803
- const { setBase } = await import("../src/base.ts");
804
- const root = document.createElement("div");
805
- root.id = "grimoire-root";
806
- document.body.appendChild(root);
807
- const g = globalThis as { DOMParser?: unknown };
808
- g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
809
- const original = globalThis.fetch;
810
- const requested: string[] = [];
811
- globalThis.fetch = (async (input: string) => {
812
- requested.push(input);
813
- return jsonResponse("/about");
814
- }) as unknown as typeof fetch;
815
- const seen: string[] = [];
816
- const warn = console.warn;
817
- const warned: string[] = [];
818
- console.warn = (m: string) => warned.push(m);
819
- setBase("/repo");
820
- try {
821
- const About = Object.assign(() => document.createElement("main"), {
822
- load: async ({ url }: { url: URL }) => {
823
- seen.push(url.pathname);
824
- return {};
825
- },
826
- });
827
- router.initRouter({ "/about": About }, []);
828
- router.onNavigate((url) => seen.push(`cb:${url.pathname}`));
829
- await router.navigate("/repo/about?x=1");
830
- expect(requested).toEqual(["/repo/about?x=1"]);
831
- expect(location.pathname).toBe("/repo/about");
832
- expect(seen).toContain("/about");
833
- expect(seen).toContain("cb:/about");
834
- expect(warned).toEqual([]);
835
-
836
- // the base alone is the root route, with or without the slash
837
- router.initRouter({ "/": () => document.createElement("main") }, []);
838
- await router.navigate("/repo");
839
- expect(requested.at(-1)).toBe("/repo");
840
-
841
- // outside the base: not a route, and the mistake is named
842
- requested.length = 0;
843
- const href = location.href;
844
- await router.navigate("/about").catch(() => {});
845
- expect(warned.join("\n")).toContain('withBase("/about")');
846
- location.href = href;
847
- } finally {
848
- setBase("");
849
- console.warn = warn;
850
- globalThis.fetch = original;
851
- root.remove();
852
- }
853
- });
854
- });
1
+ import { beforeEach, describe, expect, test, vi } from "bun:test";
2
+ import type { Document, History, Location, Window } from "happy-dom";
3
+ import {
4
+ clearDeps,
5
+ depends,
6
+ hasDep,
7
+ setDeps,
8
+ startCollecting,
9
+ stopCollecting,
10
+ } from "../src/client/deps.ts";
11
+
12
+ // test/preload.ts installs happy-dom globals at runtime; this package's
13
+ // compiler options have no DOM lib, so declare the shapes we rely on.
14
+ declare global {
15
+ // biome-ignore-all lint/style/noVar: ambient global declarations require var
16
+ var window: Window;
17
+ var document: Document;
18
+ var location: Location;
19
+ var history: History;
20
+ var MouseEvent: Window["MouseEvent"];
21
+ var Event: Window["Event"];
22
+ var requestAnimationFrame: Window["requestAnimationFrame"];
23
+ }
24
+
25
+ // router.ts reads `location` at module load — DOM globals must exist first.
26
+ // Dynamic import is required because the module under test captures location
27
+ // during evaluation, which static-hoisted imports would race. The default
28
+ // about:blank URL has origin "null", which breaks new URL(href, origin) —
29
+ // point the window at a real origin first.
30
+ window.location.href = "http://localhost/";
31
+ const globalEnv = globalThis as typeof globalThis & {
32
+ location: Location;
33
+ history: History;
34
+ requestAnimationFrame: Window["requestAnimationFrame"];
35
+ };
36
+ globalEnv.location = window.location;
37
+ globalEnv.history = window.history;
38
+ globalEnv.requestAnimationFrame = window.requestAnimationFrame.bind(window);
39
+ const router = await import("../src/client/router.ts");
40
+
41
+ function jsonResponse(pattern: string): Response {
42
+ return new Response(
43
+ JSON.stringify({
44
+ data: {},
45
+ layoutData: [],
46
+ params: {},
47
+ pattern,
48
+ head: "",
49
+ }),
50
+ { headers: { "content-type": "application/json" } },
51
+ );
52
+ }
53
+
54
+ function captureFetch(): {
55
+ calls: Array<{ input: string; init?: RequestInit }>;
56
+ restore: () => void;
57
+ } {
58
+ const calls: Array<{ input: string; init?: RequestInit }> = [];
59
+ const original = globalThis.fetch;
60
+ // test shim over the global — precise fetch typing is impossible here.
61
+ // Echoes the requested pathname as the route pattern, mirroring renderRoute.
62
+ globalThis.fetch = (async (
63
+ input: string,
64
+ init?: RequestInit,
65
+ ): Promise<Response> => {
66
+ calls.push({ input, init });
67
+ const pattern = new URL(input, "http://localhost").pathname;
68
+ return jsonResponse(pattern);
69
+ }) as unknown as typeof fetch;
70
+ return {
71
+ calls,
72
+ restore: () => {
73
+ globalThis.fetch = original;
74
+ },
75
+ };
76
+ }
77
+
78
+ describe("depends", () => {
79
+ test("no-op outside collection", () => {
80
+ depends("posts");
81
+ expect(hasDep("/", "posts")).toBe(false);
82
+ });
83
+
84
+ test("registers key during collection", () => {
85
+ startCollecting();
86
+ depends("posts");
87
+ stopCollecting("/");
88
+ expect(hasDep("/", "posts")).toBe(true);
89
+ });
90
+
91
+ test("multiple keys", () => {
92
+ startCollecting();
93
+ depends("posts");
94
+ depends("tags");
95
+ stopCollecting("/");
96
+ expect(hasDep("/", "posts")).toBe(true);
97
+ expect(hasDep("/", "tags")).toBe(true);
98
+ });
99
+
100
+ test("cleared on next collection", () => {
101
+ startCollecting();
102
+ depends("posts");
103
+ stopCollecting("/");
104
+ startCollecting();
105
+ depends("comments");
106
+ stopCollecting("/");
107
+ expect(hasDep("/", "posts")).toBe(false);
108
+ expect(hasDep("/", "comments")).toBe(true);
109
+ });
110
+ });
111
+ describe("navigate — head", () => {
112
+ test("server-rendered head tags are replaced, not kept beside the new ones", async () => {
113
+ const root = document.createElement("div");
114
+ root.id = "grimoire-root";
115
+ document.body.appendChild(root);
116
+ document.head.innerHTML =
117
+ '<meta charset="UTF-8"><!--grimoire-head--><title>Old</title><meta name="description" content="old"><!--/grimoire-head-->';
118
+ const g = globalThis as { DOMParser?: unknown };
119
+ g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
120
+ const original = globalThis.fetch;
121
+ globalThis.fetch = (async () =>
122
+ new Response(
123
+ JSON.stringify({
124
+ data: {},
125
+ layoutData: [],
126
+ params: {},
127
+ pattern: "/",
128
+ head: '<title>New</title><meta name="description" content="new">',
129
+ }),
130
+ { headers: { "content-type": "application/json" } },
131
+ )) as unknown as typeof fetch;
132
+ try {
133
+ router.initRouter({ "/": () => document.createElement("main") }, []);
134
+ await router.navigate("/");
135
+ const descriptions = [
136
+ ...document.head.querySelectorAll('meta[name="description"]'),
137
+ ].map((m) => m.getAttribute("content"));
138
+ expect(descriptions).toEqual(["new"]);
139
+ expect(document.title).toBe("New");
140
+ expect(document.head.querySelectorAll("meta[charset]").length).toBe(1);
141
+ // a second navigation replaces the tags the first one added
142
+ await router.navigate("/");
143
+ expect(
144
+ document.head.querySelectorAll('meta[name="description"]').length,
145
+ ).toBe(1);
146
+ } finally {
147
+ globalThis.fetch = original;
148
+ root.remove();
149
+ document.head.innerHTML = "";
150
+ }
151
+ });
152
+ });
153
+
154
+ describe("navigate — loading export", () => {
155
+ test("a lazy page module's loading export shows while data loads", async () => {
156
+ // other files' tests may leave a page host behind
157
+ for (const id of ["grimoire-root", "grimoire-page"])
158
+ document.getElementById(id)?.remove();
159
+ const root = document.createElement("div");
160
+ root.id = "grimoire-root";
161
+ const page = document.createElement("div");
162
+ page.id = "grimoire-page";
163
+ root.appendChild(page);
164
+ document.body.appendChild(root);
165
+ let release!: () => void;
166
+ const gate = new Promise<void>((r) => (release = r));
167
+ const original = globalThis.fetch;
168
+ globalThis.fetch = (async () => {
169
+ await gate;
170
+ return jsonResponse("/slow");
171
+ }) as unknown as typeof fetch;
172
+ try {
173
+ const Page = () => {
174
+ const el = document.createElement("p");
175
+ el.textContent = "page";
176
+ return el;
177
+ };
178
+ const loading = () => {
179
+ const el = document.createElement("p");
180
+ el.textContent = "loading";
181
+ return el;
182
+ };
183
+ router.initRouter(
184
+ { "/slow": { __lazy: async () => ({ default: Page, loading }) } },
185
+ [],
186
+ );
187
+ const done = router.navigate("/slow");
188
+ for (let i = 0; i < 20 && !root.textContent?.includes("loading"); i++)
189
+ await new Promise((r) => setTimeout(r, 5));
190
+ expect(root.textContent).toContain("loading");
191
+ release();
192
+ await done;
193
+ expect(root.textContent).toContain("page");
194
+ } finally {
195
+ globalThis.fetch = original;
196
+ root.remove();
197
+ }
198
+ });
199
+ });
200
+
201
+ describe("navigate — a route chunk that fails to load", () => {
202
+ // After a rebuild or a deploy, an open tab's bundle still names the old
203
+ // chunks, and those are gone. The import rejects; the router must load the
204
+ // page from the server instead of dying on an unhandled rejection.
205
+ test("falls back to a full page load", async () => {
206
+ const root = document.createElement("div");
207
+ root.id = "grimoire-root";
208
+ document.body.appendChild(root);
209
+ const fetchShim = captureFetch();
210
+ const href = location.href;
211
+ try {
212
+ router.initRouter(
213
+ {
214
+ "/gone": {
215
+ __lazy: async () => {
216
+ throw new TypeError(
217
+ "error loading dynamically imported module: /__grimoire__/chunk-old.js",
218
+ );
219
+ },
220
+ },
221
+ },
222
+ [],
223
+ );
224
+ await router.navigate("/gone");
225
+ expect(location.pathname).toBe("/gone");
226
+ } finally {
227
+ fetchShim.restore();
228
+ root.remove();
229
+ location.href = href;
230
+ }
231
+ });
232
+ });
233
+
234
+ describe("navigate — view transitions", () => {
235
+ test("falls back to direct swap when startViewTransition is missing", async () => {
236
+ const root = document.createElement("div");
237
+ root.id = "grimoire-root";
238
+ document.body.appendChild(root);
239
+ const fetchShim = captureFetch();
240
+ try {
241
+ router.initRouter({ "/": () => document.createElement("main") }, []);
242
+ await router.navigate("/");
243
+ expect(root.childNodes.length).toBeGreaterThan(0);
244
+ } finally {
245
+ fetchShim.restore();
246
+ root.remove();
247
+ }
248
+ });
249
+
250
+ test("routes the swap through startViewTransition when available", async () => {
251
+ const root = document.createElement("div");
252
+ root.id = "grimoire-root";
253
+ document.body.appendChild(root);
254
+ let vtCalled = false;
255
+ const docEnv = document as Document & {
256
+ startViewTransition?: (cb: () => void) => unknown;
257
+ };
258
+ docEnv.startViewTransition = (cb: () => void) => {
259
+ vtCalled = true;
260
+ cb();
261
+ return undefined;
262
+ };
263
+ const fetchShim = captureFetch();
264
+ try {
265
+ router.initRouter({ "/vt": () => document.createElement("main") }, []);
266
+ await router.navigate("/vt");
267
+ expect(vtCalled).toBe(true);
268
+ expect(root.childNodes.length).toBeGreaterThan(0);
269
+ } finally {
270
+ delete docEnv.startViewTransition;
271
+ fetchShim.restore();
272
+ root.remove();
273
+ }
274
+ });
275
+ });
276
+
277
+ describe("shared-element view transitions", () => {
278
+ const nameOf = (el: Element) =>
279
+ (el as HTMLElement).style.getPropertyValue("view-transition-name");
280
+
281
+ test("elements sharing data-sigil-transition are named on both pages", async () => {
282
+ const root = document.createElement("div");
283
+ root.id = "grimoire-root";
284
+ const oldHero = document.createElement("img");
285
+ oldHero.setAttribute("data-sigil-transition", "hero-7");
286
+ const other = document.createElement("img");
287
+ other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
288
+ root.append(oldHero, other);
289
+ document.body.appendChild(root);
290
+
291
+ let newHero: Element | undefined;
292
+ const page = () => {
293
+ const main = document.createElement("main");
294
+ newHero = document.createElement("img");
295
+ newHero.setAttribute("data-sigil-transition", "hero-7");
296
+ main.appendChild(newHero);
297
+ return main;
298
+ };
299
+ const docEnv = document as unknown as {
300
+ startViewTransition?: (cb: () => void) => unknown;
301
+ };
302
+ const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] =
303
+ [];
304
+ docEnv.startViewTransition = (cb: () => void) => {
305
+ const before = {
306
+ oldNamed: nameOf(oldHero),
307
+ otherNamed: nameOf(other),
308
+ newNamed: "",
309
+ };
310
+ cb();
311
+ before.newNamed = nameOf(newHero!);
312
+ seen.push(before);
313
+ return { finished: Promise.resolve() };
314
+ };
315
+ const shim = captureFetch();
316
+ try {
317
+ router.initRouter({ "/shared": page }, []);
318
+ await router.navigate("/shared");
319
+ // the old element is named when the browser snapshots, the new one
320
+ // once the swap ran; an element with no partner is left alone
321
+ expect(seen).toEqual([
322
+ { oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" },
323
+ ]);
324
+ await Promise.resolve();
325
+ await Promise.resolve();
326
+ expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
327
+ } finally {
328
+ delete docEnv.startViewTransition;
329
+ shim.restore();
330
+ root.remove();
331
+ }
332
+ });
333
+
334
+ test("a key used twice on a page is skipped", async () => {
335
+ const root = document.createElement("div");
336
+ root.id = "grimoire-root";
337
+ for (let i = 0; i < 2; i++) {
338
+ const el = document.createElement("div");
339
+ el.setAttribute("data-sigil-transition", "dup");
340
+ root.appendChild(el);
341
+ }
342
+ document.body.appendChild(root);
343
+ const docEnv = document as unknown as {
344
+ startViewTransition?: (cb: () => void) => unknown;
345
+ };
346
+ let named = 0;
347
+ docEnv.startViewTransition = (cb: () => void) => {
348
+ named = document.querySelectorAll(
349
+ '[style*="view-transition-name"]',
350
+ ).length;
351
+ cb();
352
+ return undefined;
353
+ };
354
+ const shim = captureFetch();
355
+ try {
356
+ router.initRouter(
357
+ {
358
+ "/dup": () => {
359
+ const el = document.createElement("div");
360
+ el.setAttribute("data-sigil-transition", "dup");
361
+ return el;
362
+ },
363
+ },
364
+ [],
365
+ );
366
+ await router.navigate("/dup");
367
+ expect(named).toBe(0);
368
+ } finally {
369
+ delete docEnv.startViewTransition;
370
+ shim.restore();
371
+ root.remove();
372
+ }
373
+ });
374
+ });
375
+
376
+ describe("hover prefetch", () => {
377
+ // The 80ms debounce is real timer logic under test — fake timers advance
378
+ // it deterministically instead of sleeping past it.
379
+ test("plain internal link prefetches route data; preload=off skips", () => {
380
+ vi.useFakeTimers();
381
+ router.initRouter(
382
+ {
383
+ "/": () => document.createElement("div"),
384
+ "/off": () => document.createElement("div"),
385
+ },
386
+ [],
387
+ );
388
+ const fetchShim = captureFetch();
389
+ try {
390
+ const plain = document.createElement("a");
391
+ plain.setAttribute("href", "/");
392
+ document.body.appendChild(plain);
393
+ plain.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
394
+ vi.advanceTimersByTime(80);
395
+ expect(fetchShim.calls.length).toBe(1);
396
+ expect(fetchShim.calls[0]?.init?.headers).toEqual({
397
+ "x-grimoire-navigate": "1",
398
+ });
399
+
400
+ const optedOut = document.createElement("a");
401
+ optedOut.setAttribute("href", "/off");
402
+ optedOut.setAttribute("data-sigil-preload", "off");
403
+ document.body.appendChild(optedOut);
404
+ optedOut.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
405
+ vi.advanceTimersByTime(80);
406
+ expect(fetchShim.calls.length).toBe(1); // unchanged
407
+ } finally {
408
+ vi.useRealTimers();
409
+ fetchShim.restore();
410
+ }
411
+ });
412
+
413
+ test("external links are never prefetched", () => {
414
+ vi.useFakeTimers();
415
+ const fetchShim = captureFetch();
416
+ try {
417
+ const ext = document.createElement("a");
418
+ ext.setAttribute("href", "https://example.com/page");
419
+ document.body.appendChild(ext);
420
+ ext.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
421
+ vi.advanceTimersByTime(80);
422
+ expect(fetchShim.calls.length).toBe(0);
423
+ } finally {
424
+ vi.useRealTimers();
425
+ fetchShim.restore();
426
+ }
427
+ });
428
+
429
+ // a GET like /auth/github starts a sign-in: warming it would overwrite
430
+ // the state cookie of the sign-in the click starts
431
+ test("rel=external, download and target=_blank links are never prefetched", () => {
432
+ vi.useFakeTimers();
433
+ router.initRouter({ "/:a/:b": () => document.createElement("div") }, []);
434
+ const fetchShim = captureFetch();
435
+ try {
436
+ for (const [attr, value] of [
437
+ ["rel", "external"],
438
+ ["download", ""],
439
+ ["target", "_blank"],
440
+ ] as const) {
441
+ const a = document.createElement("a");
442
+ a.setAttribute("href", "/auth/github");
443
+ a.setAttribute(attr, value);
444
+ document.body.appendChild(a);
445
+ a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
446
+ vi.advanceTimersByTime(80);
447
+ }
448
+ expect(fetchShim.calls.length).toBe(0);
449
+ } finally {
450
+ vi.useRealTimers();
451
+ fetchShim.restore();
452
+ }
453
+ });
454
+
455
+ test("a click cancels a pending hover prefetch, even one the router leaves to the browser", () => {
456
+ vi.useFakeTimers();
457
+ router.initRouter({ "/:a/:b": () => document.createElement("div") }, []);
458
+ const fetchShim = captureFetch();
459
+ try {
460
+ const page = document.createElement("a");
461
+ page.setAttribute("href", "/some/page");
462
+ document.body.appendChild(page);
463
+ page.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
464
+ vi.advanceTimersByTime(40);
465
+ // some other handler (or the app) takes the click: the router steps
466
+ // aside, and the pending prefetch must still be dropped
467
+ const takeIt = (e: Event) => e.preventDefault();
468
+ document.addEventListener("click", takeIt, { capture: true });
469
+ page.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
470
+ document.removeEventListener("click", takeIt, { capture: true });
471
+ vi.advanceTimersByTime(80);
472
+ expect(fetchShim.calls.length).toBe(0);
473
+ } finally {
474
+ vi.useRealTimers();
475
+ fetchShim.restore();
476
+ }
477
+ });
478
+ });
479
+
480
+ describe("prefetch reuse", () => {
481
+ test("a tap reuses the request started on touchstart", async () => {
482
+ const root = document.createElement("div");
483
+ root.id = "grimoire-root";
484
+ document.body.appendChild(root);
485
+ router.initRouter({ "/tap": () => document.createElement("main") }, []);
486
+ const shim = captureFetch();
487
+ try {
488
+ const a = document.createElement("a");
489
+ a.setAttribute("href", "/tap");
490
+ document.body.appendChild(a);
491
+ a.dispatchEvent(new Event("touchstart", { bubbles: true }));
492
+ expect(shim.calls.length).toBe(1);
493
+
494
+ await router.navigate("/tap");
495
+ // the click did not issue a second request
496
+ expect(shim.calls.length).toBe(1);
497
+ expect(root.childNodes.length).toBeGreaterThan(0);
498
+
499
+ // and a prefetch is single-use: the next visit fetches fresh data
500
+ await router.navigate("/tap");
501
+ expect(shim.calls.length).toBe(2);
502
+ } finally {
503
+ shim.restore();
504
+ root.remove();
505
+ }
506
+ });
507
+
508
+ test("a click cancels the hover prefetch it just consumed", async () => {
509
+ const root = document.createElement("div");
510
+ root.id = "grimoire-root";
511
+ document.body.appendChild(root);
512
+ router.initRouter({ "/hov": () => document.createElement("main") }, []);
513
+ const shim = captureFetch();
514
+ try {
515
+ const a = document.createElement("a");
516
+ a.setAttribute("href", "/hov");
517
+ document.body.appendChild(a);
518
+ a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
519
+ a.dispatchEvent(
520
+ new MouseEvent("click", { bubbles: true, cancelable: true }),
521
+ );
522
+ await Bun.sleep(200); // past the 80ms hover delay
523
+ expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
524
+ expect(shim.calls.length).toBe(1); // its own request, not a second
525
+ } finally {
526
+ shim.restore();
527
+ root.remove();
528
+ }
529
+ });
530
+
531
+ test("a prefetch made before a cookie changed is not reused", async () => {
532
+ const root = document.createElement("div");
533
+ root.id = "grimoire-root";
534
+ document.body.appendChild(root);
535
+ router.initRouter({ "/pref": () => document.createElement("main") }, []);
536
+ const shim = captureFetch();
537
+ try {
538
+ document.cookie = "region=jp";
539
+ router.prefetch("/pref");
540
+ expect(shim.calls.length).toBe(1);
541
+ document.cookie = "region=en"; // the visitor switched server
542
+ await router.navigate("/pref");
543
+ // the held response was fetched as jp, so the click asks again
544
+ expect(shim.calls.length).toBe(2);
545
+ } finally {
546
+ document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
547
+ shim.restore();
548
+ root.remove();
549
+ }
550
+ });
551
+
552
+ test("invalidateAll never serves a prefetched response", async () => {
553
+ const root = document.createElement("div");
554
+ root.id = "grimoire-root";
555
+ document.body.appendChild(root);
556
+ window.history.pushState(null, "", "/inv");
557
+ router.initRouter({ "/inv": () => document.createElement("main") }, []);
558
+ const shim = captureFetch();
559
+ try {
560
+ await router.navigate("/inv");
561
+ router.prefetch("/inv");
562
+ const before = shim.calls.length;
563
+ await router.invalidateAll();
564
+ expect(shim.calls.length).toBe(before + 1);
565
+ } finally {
566
+ shim.restore();
567
+ root.remove();
568
+ }
569
+ });
570
+ });
571
+
572
+ describe("popstate — query string", () => {
573
+ // popstate fires navigate() from an event listener, so there is no promise
574
+ // to await at the call site. afterNavigate is the router's own completion
575
+ // signal; a fixed sleep would be both slower and racy.
576
+ function onNavigated(): Promise<void> {
577
+ const { promise, resolve } = Promise.withResolvers<void>();
578
+ router.afterNavigate(() => resolve());
579
+ return promise;
580
+ }
581
+
582
+ // Back used to refetch the bare pathname, so a query-driven page rendered
583
+ // unfiltered data while the address bar still showed the query.
584
+ test("back to a query URL refetches with the query intact", async () => {
585
+ const root = document.createElement("div");
586
+ root.id = "grimoire-root";
587
+ document.body.appendChild(root);
588
+ window.history.pushState(null, "", "/");
589
+ router.initRouter(
590
+ {
591
+ "/list": () => document.createElement("div"),
592
+ "/other": () => document.createElement("div"),
593
+ },
594
+ [],
595
+ );
596
+ const shim = captureFetch();
597
+ try {
598
+ await router.navigate("/list?q=fireball&page=2");
599
+ await router.navigate("/other");
600
+ shim.calls.length = 0;
601
+
602
+ // the browser moves history itself, then fires popstate
603
+ const navigated = onNavigated();
604
+ window.history.pushState(null, "", "/list?q=fireball&page=2");
605
+ window.dispatchEvent(new Event("popstate"));
606
+ await navigated;
607
+
608
+ expect(shim.calls.map((c) => c.input)).toEqual([
609
+ "/list?q=fireball&page=2",
610
+ ]);
611
+ } finally {
612
+ router.afterNavigate(() => {});
613
+ shim.restore();
614
+ root.remove();
615
+ }
616
+ });
617
+
618
+ test("a popstate that only changes the query still refetches", async () => {
619
+ const root = document.createElement("div");
620
+ root.id = "grimoire-root";
621
+ document.body.appendChild(root);
622
+ window.history.pushState(null, "", "/");
623
+ router.initRouter({ "/list": () => document.createElement("div") }, []);
624
+ const shim = captureFetch();
625
+ try {
626
+ await router.navigate("/list?page=2");
627
+ shim.calls.length = 0;
628
+
629
+ const navigated = onNavigated();
630
+ window.history.pushState(null, "", "/list?page=1");
631
+ window.dispatchEvent(new Event("popstate"));
632
+ await navigated;
633
+
634
+ expect(shim.calls.map((c) => c.input)).toEqual(["/list?page=1"]);
635
+ } finally {
636
+ router.afterNavigate(() => {});
637
+ shim.restore();
638
+ root.remove();
639
+ }
640
+ });
641
+ });
642
+
643
+ describe("enhance — named action URLs", () => {
644
+ test("action starting with ?/ submits to the current pathname", async () => {
645
+ // earlier navigate() tests moved history — reset to a clean path
646
+ window.history.pushState(null, "", "/");
647
+ const { enhance } = await import("../src/client/enhance.ts");
648
+ const calls: string[] = [];
649
+ const original = globalThis.fetch;
650
+ globalThis.fetch = (async (input: string) => {
651
+ calls.push(input);
652
+ return new Response(null, { status: 303, headers: { location: "/" } });
653
+ }) as unknown as typeof fetch;
654
+
655
+ const form = document.createElement("form");
656
+ document.body.appendChild(form);
657
+ const cleanup = enhance(form, { action: "?/create" });
658
+ try {
659
+ form.dispatchEvent(
660
+ new Event("submit", { bubbles: true, cancelable: true }),
661
+ );
662
+ await new Promise((r) => setTimeout(r, 0));
663
+ expect(calls).toEqual([`${window.location.pathname}?/create`]);
664
+ } finally {
665
+ cleanup();
666
+ form.remove();
667
+ globalThis.fetch = original;
668
+ }
669
+ });
670
+ });
671
+
672
+ describe("enhance — outcomes", () => {
673
+ async function submit(
674
+ reply: Response,
675
+ options: Record<string, unknown> = {},
676
+ submitter?: HTMLButtonElement,
677
+ ) {
678
+ window.history.pushState(null, "", "/books");
679
+ const { enhance } = await import("../src/client/enhance.ts");
680
+ const sent: { headers: Headers; body: FormData }[] = [];
681
+ const navigations: [string, boolean | undefined][] = [];
682
+ const g = globalThis as Record<string, unknown>;
683
+ const originalFetch = globalThis.fetch;
684
+ const originalNavigate = g.__grimoire_navigate__;
685
+ globalThis.fetch = (async (_input: string, init: RequestInit) => {
686
+ sent.push({
687
+ headers: new Headers(init.headers),
688
+ body: init.body as FormData,
689
+ });
690
+ return reply;
691
+ }) as unknown as typeof fetch;
692
+ g.__grimoire_navigate__ = (path: string, replace?: boolean) =>
693
+ navigations.push([path, replace]);
694
+
695
+ const form = document.createElement("form");
696
+ form.setAttribute("action", "?/toggle");
697
+ const input = document.createElement("input");
698
+ input.setAttribute("name", "id");
699
+ input.setAttribute("value", "7");
700
+ form.appendChild(input);
701
+ if (submitter) form.appendChild(submitter);
702
+ document.body.appendChild(form);
703
+ const cleanup = enhance(form, options);
704
+ try {
705
+ const event = new Event("submit", { bubbles: true, cancelable: true });
706
+ if (submitter)
707
+ Object.defineProperty(event, "submitter", { value: submitter });
708
+ form.dispatchEvent(event);
709
+ await new Promise((r) => setTimeout(r, 0));
710
+ return { sent, navigations };
711
+ } finally {
712
+ cleanup();
713
+ form.remove();
714
+ globalThis.fetch = originalFetch;
715
+ g.__grimoire_navigate__ = originalNavigate;
716
+ }
717
+ }
718
+
719
+ test("success on the same page re-runs its loads in place", async () => {
720
+ const seen: unknown[] = [];
721
+ const { sent, navigations } = await submit(
722
+ Response.json({
723
+ type: "success",
724
+ location: "http://localhost/books",
725
+ data: { ok: 1 },
726
+ }),
727
+ { onSuccess: (r: unknown) => seen.push(r) },
728
+ );
729
+ expect(sent[0]!.headers.get("x-grimoire-form")).toBe("1");
730
+ expect(seen).toEqual([
731
+ { redirect: "http://localhost/books", data: { ok: 1 } },
732
+ ]);
733
+ // replace: no new history entry for the same page
734
+ expect(navigations).toEqual([["/books", true]]);
735
+ });
736
+
737
+ test("a redirect elsewhere pushes a new entry", async () => {
738
+ const { navigations } = await submit(
739
+ Response.json({ type: "redirect", status: 303, location: "/books/7" }),
740
+ );
741
+ expect(navigations).toEqual([["/books/7", false]]);
742
+ });
743
+
744
+ test("fail() data goes to onFail, and nothing navigates", async () => {
745
+ const failed: unknown[] = [];
746
+ const { navigations } = await submit(
747
+ Response.json(
748
+ { fail: true, status: 400, data: { problem: "x" } },
749
+ { status: 400 },
750
+ ),
751
+ { onFail: (d: unknown) => failed.push(d) },
752
+ );
753
+ expect(failed).toEqual([{ problem: "x" }]);
754
+ expect(navigations).toEqual([]);
755
+ });
756
+
757
+ test("the submitting button's name=value is sent", async () => {
758
+ const button = document.createElement("button");
759
+ button.name = "read";
760
+ button.value = "1";
761
+ const { sent } = await submit(
762
+ Response.json({ type: "success", location: "/books", data: null }),
763
+ {},
764
+ button,
765
+ );
766
+ expect(sent[0]!.body.get("read")).toBe("1");
767
+ });
768
+ });
769
+
770
+ describe("Page.load — parent()", () => {
771
+ test("parent() merges layoutData entries outermost-first", async () => {
772
+ let seenParent: Record<string, unknown> | undefined;
773
+ const PageWithLoad = Object.assign(() => document.createElement("div"), {
774
+ load: async (ctx: { parent: () => Promise<Record<string, unknown>> }) => {
775
+ seenParent = await ctx.parent();
776
+ return {};
777
+ },
778
+ });
779
+
780
+ const original = globalThis.fetch;
781
+ globalThis.fetch = (async (input: string) => {
782
+ const pattern = new URL(input, "http://localhost").pathname;
783
+ return new Response(
784
+ JSON.stringify({
785
+ data: {},
786
+ layoutData: [{ a: 1 }, { b: 2 }],
787
+ params: {},
788
+ pattern,
789
+ head: "",
790
+ }),
791
+ { headers: { "content-type": "application/json" } },
792
+ );
793
+ }) as unknown as typeof fetch;
794
+
795
+ try {
796
+ router.initRouter({ "/pl": PageWithLoad }, []);
797
+ await router.navigate("/pl");
798
+ expect(seenParent).toEqual({ a: 1, b: 2 });
799
+ } finally {
800
+ globalThis.fetch = original;
801
+ }
802
+ });
803
+ });
804
+
805
+ describe("invalidate", () => {
806
+ test("refetches only on key intersection; empty deps always refetch", async () => {
807
+ router.initRouter({ "/": () => document.createElement("div") }, []);
808
+ const shim = captureFetch();
809
+ try {
810
+ await router.navigate("/"); // establishes lastState.pattern = "/"
811
+
812
+ setDeps("/", ["user:1"]);
813
+ shim.calls.length = 0;
814
+ await router.invalidate("other");
815
+ expect(shim.calls.length).toBe(0); // no intersection → skip
816
+
817
+ await router.invalidate("user:1");
818
+ expect(shim.calls.length).toBe(1); // intersect → refetch
819
+
820
+ clearDeps("/");
821
+ await router.invalidate("anything");
822
+ expect(shim.calls.length).toBe(2); // no deps → conservative refetch
823
+ } finally {
824
+ shim.restore();
825
+ clearDeps("/");
826
+ }
827
+ });
828
+ });
829
+
830
+ describe("invalidate keeps the query string", () => {
831
+ test("a filtered page reloads with its filters", async () => {
832
+ const root = document.createElement("div");
833
+ root.id = "grimoire-root";
834
+ document.body.appendChild(root);
835
+ router.initRouter({ "/search": () => document.createElement("main") }, []);
836
+ const shim = captureFetch();
837
+ try {
838
+ await router.navigate("/search?q=dune&page=2");
839
+ shim.calls.length = 0;
840
+ await router.invalidateAll();
841
+ expect(shim.calls.length).toBe(1);
842
+ expect(shim.calls[0]!.input).toContain("q=dune");
843
+ expect(shim.calls[0]!.input).toContain("page=2");
844
+ } finally {
845
+ shim.restore();
846
+ root.remove();
847
+ }
848
+ });
849
+ });
850
+
851
+ describe("navigate — under a base", () => {
852
+ test("fetches and records the full path, but routes and loads see the route path", async () => {
853
+ const { setBase } = await import("../src/base.ts");
854
+ const root = document.createElement("div");
855
+ root.id = "grimoire-root";
856
+ document.body.appendChild(root);
857
+ const g = globalThis as { DOMParser?: unknown };
858
+ g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
859
+ const original = globalThis.fetch;
860
+ const requested: string[] = [];
861
+ globalThis.fetch = (async (input: string) => {
862
+ requested.push(input);
863
+ return jsonResponse("/about");
864
+ }) as unknown as typeof fetch;
865
+ const seen: string[] = [];
866
+ const warn = console.warn;
867
+ const warned: string[] = [];
868
+ console.warn = (m: string) => warned.push(m);
869
+ setBase("/repo");
870
+ try {
871
+ const About = Object.assign(() => document.createElement("main"), {
872
+ load: async ({ url }: { url: URL }) => {
873
+ seen.push(url.pathname);
874
+ return {};
875
+ },
876
+ });
877
+ router.initRouter({ "/about": About }, []);
878
+ router.onNavigate((url) => seen.push(`cb:${url.pathname}`));
879
+ await router.navigate("/repo/about?x=1");
880
+ expect(requested).toEqual(["/repo/about?x=1"]);
881
+ expect(location.pathname).toBe("/repo/about");
882
+ expect(seen).toContain("/about");
883
+ expect(seen).toContain("cb:/about");
884
+ expect(warned).toEqual([]);
885
+
886
+ // the base alone is the root route, with or without the slash
887
+ router.initRouter({ "/": () => document.createElement("main") }, []);
888
+ await router.navigate("/repo");
889
+ expect(requested.at(-1)).toBe("/repo");
890
+
891
+ // outside the base: not a route, and the mistake is named
892
+ requested.length = 0;
893
+ const href = location.href;
894
+ await router.navigate("/about").catch(() => {});
895
+ expect(warned.join("\n")).toContain('withBase("/about")');
896
+ location.href = href;
897
+ } finally {
898
+ setBase("");
899
+ console.warn = warn;
900
+ globalThis.fetch = original;
901
+ root.remove();
902
+ }
903
+ });
904
+ });