@sigil-dev/grimoire 0.9.13 → 0.9.15

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.
@@ -241,6 +241,96 @@ describe("navigate — view transitions", () => {
241
241
  });
242
242
  });
243
243
 
244
+ describe("shared-element view transitions", () => {
245
+ const nameOf = (el: Element) =>
246
+ (el as HTMLElement).style.getPropertyValue("view-transition-name");
247
+
248
+ test("elements sharing data-sigil-transition are named on both pages", async () => {
249
+ const root = document.createElement("div");
250
+ root.id = "grimoire-root";
251
+ const oldHero = document.createElement("img");
252
+ oldHero.setAttribute("data-sigil-transition", "hero-7");
253
+ const other = document.createElement("img");
254
+ other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
255
+ root.append(oldHero, other);
256
+ document.body.appendChild(root);
257
+
258
+ let newHero: Element | undefined;
259
+ const page = () => {
260
+ const main = document.createElement("main");
261
+ newHero = document.createElement("img");
262
+ newHero.setAttribute("data-sigil-transition", "hero-7");
263
+ main.appendChild(newHero);
264
+ return main;
265
+ };
266
+ const docEnv = document as unknown as {
267
+ startViewTransition?: (cb: () => void) => unknown;
268
+ };
269
+ const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] = [];
270
+ docEnv.startViewTransition = (cb: () => void) => {
271
+ const before = { oldNamed: nameOf(oldHero), otherNamed: nameOf(other), newNamed: "" };
272
+ cb();
273
+ before.newNamed = nameOf(newHero!);
274
+ seen.push(before);
275
+ return { finished: Promise.resolve() };
276
+ };
277
+ const shim = captureFetch();
278
+ try {
279
+ router.initRouter({ "/shared": page }, []);
280
+ await router.navigate("/shared");
281
+ // the old element is named when the browser snapshots, the new one
282
+ // once the swap ran; an element with no partner is left alone
283
+ expect(seen).toEqual([{ oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" }]);
284
+ await Promise.resolve();
285
+ await Promise.resolve();
286
+ expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
287
+ } finally {
288
+ delete docEnv.startViewTransition;
289
+ shim.restore();
290
+ root.remove();
291
+ }
292
+ });
293
+
294
+ test("a key used twice on a page is skipped", async () => {
295
+ const root = document.createElement("div");
296
+ root.id = "grimoire-root";
297
+ for (let i = 0; i < 2; i++) {
298
+ const el = document.createElement("div");
299
+ el.setAttribute("data-sigil-transition", "dup");
300
+ root.appendChild(el);
301
+ }
302
+ document.body.appendChild(root);
303
+ const docEnv = document as unknown as {
304
+ startViewTransition?: (cb: () => void) => unknown;
305
+ };
306
+ let named = 0;
307
+ docEnv.startViewTransition = (cb: () => void) => {
308
+ named = document.querySelectorAll('[style*="view-transition-name"]').length;
309
+ cb();
310
+ return undefined;
311
+ };
312
+ const shim = captureFetch();
313
+ try {
314
+ router.initRouter(
315
+ {
316
+ "/dup": () => {
317
+ const el = document.createElement("div");
318
+ el.setAttribute("data-sigil-transition", "dup");
319
+ return el;
320
+ },
321
+ },
322
+ [],
323
+ );
324
+ await router.navigate("/dup");
325
+ expect(named).toBe(0);
326
+ } finally {
327
+ delete docEnv.startViewTransition;
328
+ shim.restore();
329
+ root.remove();
330
+ }
331
+ });
332
+ });
333
+
244
334
  describe("hover prefetch", () => {
245
335
  // The 80ms debounce is real timer logic under test — fake timers advance
246
336
  // it deterministically instead of sleeping past it.
@@ -295,6 +385,96 @@ describe("hover prefetch", () => {
295
385
  });
296
386
  });
297
387
 
388
+ describe("prefetch reuse", () => {
389
+ test("a tap reuses the request started on touchstart", async () => {
390
+ const root = document.createElement("div");
391
+ root.id = "grimoire-root";
392
+ document.body.appendChild(root);
393
+ router.initRouter({ "/tap": () => document.createElement("main") }, []);
394
+ const shim = captureFetch();
395
+ try {
396
+ const a = document.createElement("a");
397
+ a.setAttribute("href", "/tap");
398
+ document.body.appendChild(a);
399
+ a.dispatchEvent(new Event("touchstart", { bubbles: true }));
400
+ expect(shim.calls.length).toBe(1);
401
+
402
+ await router.navigate("/tap");
403
+ // the click did not issue a second request
404
+ expect(shim.calls.length).toBe(1);
405
+ expect(root.childNodes.length).toBeGreaterThan(0);
406
+
407
+ // and a prefetch is single-use: the next visit fetches fresh data
408
+ await router.navigate("/tap");
409
+ expect(shim.calls.length).toBe(2);
410
+ } finally {
411
+ shim.restore();
412
+ root.remove();
413
+ }
414
+ });
415
+
416
+ test("a click cancels the hover prefetch it just consumed", async () => {
417
+ const root = document.createElement("div");
418
+ root.id = "grimoire-root";
419
+ document.body.appendChild(root);
420
+ router.initRouter({ "/hov": () => document.createElement("main") }, []);
421
+ const shim = captureFetch();
422
+ try {
423
+ const a = document.createElement("a");
424
+ a.setAttribute("href", "/hov");
425
+ document.body.appendChild(a);
426
+ a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
427
+ a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
428
+ await Bun.sleep(200); // past the 80ms hover delay
429
+ expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
430
+ expect(shim.calls.length).toBe(1); // its own request, not a second
431
+ } finally {
432
+ shim.restore();
433
+ root.remove();
434
+ }
435
+ });
436
+
437
+ test("a prefetch made before a cookie changed is not reused", async () => {
438
+ const root = document.createElement("div");
439
+ root.id = "grimoire-root";
440
+ document.body.appendChild(root);
441
+ router.initRouter({ "/pref": () => document.createElement("main") }, []);
442
+ const shim = captureFetch();
443
+ try {
444
+ document.cookie = "region=jp";
445
+ router.prefetch("/pref");
446
+ expect(shim.calls.length).toBe(1);
447
+ document.cookie = "region=en"; // the visitor switched server
448
+ await router.navigate("/pref");
449
+ // the held response was fetched as jp, so the click asks again
450
+ expect(shim.calls.length).toBe(2);
451
+ } finally {
452
+ document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
453
+ shim.restore();
454
+ root.remove();
455
+ }
456
+ });
457
+
458
+ test("invalidateAll never serves a prefetched response", async () => {
459
+ const root = document.createElement("div");
460
+ root.id = "grimoire-root";
461
+ document.body.appendChild(root);
462
+ window.history.pushState(null, "", "/inv");
463
+ router.initRouter({ "/inv": () => document.createElement("main") }, []);
464
+ const shim = captureFetch();
465
+ try {
466
+ await router.navigate("/inv");
467
+ router.prefetch("/inv");
468
+ const before = shim.calls.length;
469
+ await router.invalidateAll();
470
+ expect(shim.calls.length).toBe(before + 1);
471
+ } finally {
472
+ shim.restore();
473
+ root.remove();
474
+ }
475
+ });
476
+ });
477
+
298
478
  describe("popstate — query string", () => {
299
479
  // popstate fires navigate() from an event listener, so there is no promise
300
480
  // to await at the call site. afterNavigate is the router's own completion
@@ -0,0 +1,49 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { optimizeImages, EAGER_IMAGE_COUNT } from "../src/rendering/images.ts";
3
+
4
+ const imgs = (n: number, attrs = "") =>
5
+ Array.from({ length: n }, (_, i) => `<img src="/${i}.png"${attrs}>`).join("");
6
+
7
+ describe("optimizeImages", () => {
8
+ test("leaves the first images eager and defers the rest", () => {
9
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT + 2));
10
+ const tags = out.match(/<img[^>]*>/g)!;
11
+ for (const t of tags.slice(0, EAGER_IMAGE_COUNT))
12
+ expect(t).not.toContain("loading");
13
+ for (const t of tags.slice(EAGER_IMAGE_COUNT))
14
+ expect(t).toBe(`<img src="/${tags.indexOf(t)}.png" loading="lazy" decoding="async">`);
15
+ });
16
+
17
+ test("respects the author's loading and decoding", () => {
18
+ const out = optimizeImages(
19
+ imgs(EAGER_IMAGE_COUNT) + `<img src="/x.png" loading="eager" decoding="sync" />`,
20
+ );
21
+ expect(out.endsWith(`<img src="/x.png" loading="eager" decoding="sync" />`)).toBe(true);
22
+ });
23
+
24
+ test("handles self-closing tags and never touches script strings", () => {
25
+ const script = `<script>var s='<img src="q.png">'</script>`;
26
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT) + script + `<img src="/y.png" />`);
27
+ expect(out).toContain(script);
28
+ expect(out).toContain(`<img src="/y.png" loading="lazy" decoding="async" />`);
29
+ });
30
+
31
+ test("a priority image is fetched first and does not use up the eager budget", () => {
32
+ const hero = `<img src="/hero.png" data-sigil-priority>`;
33
+ const out = optimizeImages(hero + imgs(EAGER_IMAGE_COUNT + 1));
34
+ const tags = out.match(/<img[^>]*>/g)!;
35
+ expect(tags[0]).toBe(`<img src="/hero.png" data-sigil-priority fetchpriority="high">`);
36
+ // the four after it are still eager, the fifth is deferred
37
+ for (const t of tags.slice(1, 1 + EAGER_IMAGE_COUNT)) expect(t).not.toContain("loading");
38
+ expect(tags.at(-1)).toContain('loading="lazy"');
39
+ });
40
+
41
+ test("an explicit fetchpriority on a priority image is kept", () => {
42
+ const t = `<img src="/h.png" data-sigil-priority fetchpriority="low">`;
43
+ expect(optimizeImages(t)).toBe(t);
44
+ });
45
+
46
+ test("html without images is returned as is", () => {
47
+ expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
48
+ });
49
+ });
@@ -0,0 +1,48 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import {
3
+ chunksFor,
4
+ parseChunkGraph,
5
+ preloadLinks,
6
+ resetChunkGraph,
7
+ } from "../src/rendering/preload.ts";
8
+
9
+ // the shape Bun writes into hydrate.js for a split build
10
+ const SOURCE = `var x = 1;
11
+ __chunks(import.meta.url,["hy","home","cards","shared","leaf"],[["./hydrate.js",3],["./chunk-home.js",3],["./chunk-cards.js",3,4],["./chunk-shared.js"],["./chunk-leaf.js",3]],0);
12
+ var routes = {
13
+ "/": { __lazy: () => (__preload("home"), import("./chunk-home.js")) },
14
+ "/cards/:id": { __lazy: () => (__preload("cards"), import("./chunk-cards.js")) },
15
+ };`;
16
+
17
+ afterEach(() => resetChunkGraph());
18
+
19
+ describe("chunk graph", () => {
20
+ test("routes map to chunks and closures include shared imports", () => {
21
+ const g = parseChunkGraph(SOURCE)!;
22
+ expect(g.routes.get("/")).toBe("home");
23
+ expect(chunksFor(g, "/").sort()).toEqual(["chunk-home.js", "chunk-shared.js"]);
24
+ expect(chunksFor(g, "/cards/:id").sort()).toEqual([
25
+ "chunk-cards.js",
26
+ "chunk-leaf.js",
27
+ "chunk-shared.js",
28
+ ]);
29
+ });
30
+
31
+ test("hydrate.js itself is never listed, unknown routes give nothing", () => {
32
+ const g = parseChunkGraph(SOURCE)!;
33
+ expect(chunksFor(g, "/cards/:id")).not.toContain("hydrate.js");
34
+ expect(chunksFor(g, "/missing")).toEqual([]);
35
+ });
36
+
37
+ test("output without a chunk graph parses to null", () => {
38
+ expect(parseChunkGraph("console.log(1)")).toBeNull();
39
+ });
40
+ });
41
+
42
+ describe("preloadLinks", () => {
43
+ test("is empty in dev and when no build exists", () => {
44
+ expect(preloadLinks("/", "", true)).toBe("");
45
+ // cwd here has no public/__grimoire__/hydrate.js
46
+ expect(preloadLinks("/", "")).toBe("");
47
+ });
48
+ });
@@ -763,3 +763,36 @@ describe("server-side depends()", () => {
763
763
  expect(html).toContain('"deps":["user:1"]');
764
764
  });
765
765
  });
766
+
767
+ describe("Server-Timing", () => {
768
+ async function render(path: string, headers: Record<string, string> = {}) {
769
+ const tree = await scanRoutes(tmpDir);
770
+ const matched = matchRoute(tree, new URL(`http://localhost${path}`));
771
+ return renderRoute(
772
+ matched!,
773
+ new Request(`http://localhost${path}`, { headers }),
774
+ );
775
+ }
776
+
777
+ test("page responses report load and render when enabled", async () => {
778
+ const { setServerTiming } = await import("../src/rendering/timing.ts");
779
+ setServerTiming(true);
780
+ try {
781
+ const res = await render("/blog");
782
+ expect(res.headers.get("server-timing")).toMatch(
783
+ /^load;dur=[\d.]+, render;dur=[\d.]+$/,
784
+ );
785
+ const nav = await render("/blog", { "x-grimoire-navigate": "1" });
786
+ expect(nav.headers.get("server-timing")).toMatch(
787
+ /^load;dur=[\d.]+, render;dur=[\d.]+, deferred;dur=[\d.]+$/,
788
+ );
789
+ } finally {
790
+ setServerTiming(false);
791
+ }
792
+ });
793
+
794
+ test("nothing is sent when disabled", async () => {
795
+ const res = await render("/blog");
796
+ expect(res.headers.get("server-timing")).toBeNull();
797
+ });
798
+ });
@@ -0,0 +1,96 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { preloadModules, startWarming } from "../src/server/warm.ts";
3
+
4
+ describe("preloadModules", () => {
5
+ test("imports each file once and reports failures without throwing", async () => {
6
+ const seen: string[] = [];
7
+ const warnings: string[] = [];
8
+ const loaded = await preloadModules(
9
+ ["/a.tsx", "/b.tsx", "/a.tsx", "/bad.tsx"],
10
+ async (f) => {
11
+ seen.push(f);
12
+ if (f === "/bad.tsx") throw new Error("boom");
13
+ },
14
+ (msg) => warnings.push(msg),
15
+ );
16
+ expect(loaded).toBe(2);
17
+ expect(seen.sort()).toEqual(["/a.tsx", "/b.tsx", "/bad.tsx"]);
18
+ expect(warnings).toEqual(["could not preload /bad.tsx:"]);
19
+ });
20
+ });
21
+
22
+ describe("startWarming", () => {
23
+ test("requests paths in order, with the given headers, and drains bodies", async () => {
24
+ const calls: Array<{ path: string; header: string | null }> = [];
25
+ let drained = 0;
26
+ const warmer = startWarming({
27
+ paths: ["/one", "/two"],
28
+ origin: "http://127.0.0.1:1234",
29
+ headers: { "x-grimoire-internal": "s3cret" },
30
+ handle: async (req) => {
31
+ calls.push({
32
+ path: new URL(req.url).pathname,
33
+ header: req.headers.get("x-grimoire-internal"),
34
+ });
35
+ const stream = new ReadableStream({
36
+ pull(c) {
37
+ drained++;
38
+ c.enqueue(new TextEncoder().encode("x"));
39
+ c.close();
40
+ },
41
+ });
42
+ return new Response(stream);
43
+ },
44
+ log: () => {},
45
+ });
46
+ await warmer.firstPass;
47
+ warmer.stop();
48
+ expect(calls).toEqual([
49
+ { path: "/one", header: "s3cret" },
50
+ { path: "/two", header: "s3cret" },
51
+ ]);
52
+ expect(drained).toBe(2);
53
+ });
54
+
55
+ test("a failing path is logged and does not stop the rest", async () => {
56
+ const logs: string[] = [];
57
+ const paths: string[] = [];
58
+ const warmer = startWarming({
59
+ paths: ["/bad", "/good"],
60
+ origin: "http://x",
61
+ handle: async (req) => {
62
+ const p = new URL(req.url).pathname;
63
+ paths.push(p);
64
+ if (p === "/bad") throw new Error("nope");
65
+ return new Response("ok");
66
+ },
67
+ log: (m) => logs.push(m),
68
+ });
69
+ await warmer.firstPass;
70
+ warmer.stop();
71
+ expect(paths).toEqual(["/bad", "/good"]);
72
+ expect(logs[0]).toContain("/bad failed: nope");
73
+ expect(logs[1]).toContain("warmed /good (200)");
74
+ });
75
+
76
+ test("every repeats the pass until stopped", async () => {
77
+ let n = 0;
78
+ const warmer = startWarming({
79
+ paths: ["/p"],
80
+ every: 20,
81
+ origin: "http://x",
82
+ handle: async () => {
83
+ n++;
84
+ return new Response("ok");
85
+ },
86
+ log: () => {},
87
+ });
88
+ await warmer.firstPass;
89
+ await Bun.sleep(90);
90
+ warmer.stop();
91
+ const seen = n;
92
+ expect(seen).toBeGreaterThanOrEqual(3);
93
+ await Bun.sleep(60);
94
+ expect(n).toBe(seen);
95
+ });
96
+ });