@sigil-dev/grimoire 0.9.13 → 0.9.14
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.
- package/.grimoire/_routes.ts +4 -0
- package/package.json +3 -3
- package/public/__grimoire__/client.js +55 -0
- package/public/__grimoire__/hydrate.js +63 -0
- package/src/client/router.ts +113 -28
- package/src/rendering/images.ts +34 -0
- package/src/rendering/index.ts +2 -1
- package/src/server/asset-cache.ts +4 -0
- package/src/server/index.ts +20 -3
- package/test/asset-cache-policy.test.ts +13 -0
- package/test/client-router.test.ts +48 -0
- package/test/images.test.ts +34 -0
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"module": "index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
7
|
-
"version": "0.9.
|
|
7
|
+
"version": "0.9.14",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.ts",
|
|
10
10
|
"./server": "./server.ts",
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"test": "bun test"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@sigil-dev/compiler": "0.9.
|
|
27
|
-
"@sigil-dev/runtime": "0.9.
|
|
26
|
+
"@sigil-dev/compiler": "0.9.14",
|
|
27
|
+
"@sigil-dev/runtime": "0.9.14",
|
|
28
28
|
"vite": "^8.0.16"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// .grimoire/_routes.ts
|
|
2
|
+
var routes = {};
|
|
3
|
+
|
|
4
|
+
// src/client-router.ts
|
|
5
|
+
var routeMap = {};
|
|
6
|
+
async function navigate(path) {
|
|
7
|
+
const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
|
|
8
|
+
const json = await res.json();
|
|
9
|
+
console.log("navigate response:", json);
|
|
10
|
+
const { data, params, pattern, head } = json;
|
|
11
|
+
const Page = routeMap[pattern];
|
|
12
|
+
if (!Page) {
|
|
13
|
+
window.location.href = path;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const node = Page({ ...data, params });
|
|
17
|
+
const slot = document.getElementById("grimoire-page");
|
|
18
|
+
if (!slot)
|
|
19
|
+
return;
|
|
20
|
+
slot.replaceChildren(node);
|
|
21
|
+
updateHead(head);
|
|
22
|
+
history.pushState({}, "", path);
|
|
23
|
+
window.scrollTo(0, 0);
|
|
24
|
+
}
|
|
25
|
+
function initRouter(routes2) {
|
|
26
|
+
routeMap = routes2;
|
|
27
|
+
document.addEventListener("click", handleClick);
|
|
28
|
+
window.addEventListener("popstate", () => navigate(location.pathname));
|
|
29
|
+
}
|
|
30
|
+
function updateHead(headHtml) {
|
|
31
|
+
document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
|
|
32
|
+
if (!headHtml)
|
|
33
|
+
return;
|
|
34
|
+
const tmp = document.createElement("head");
|
|
35
|
+
tmp.innerHTML = headHtml;
|
|
36
|
+
for (const el of Array.from(tmp.children)) {
|
|
37
|
+
el.dataset.grimoireHead = "1";
|
|
38
|
+
document.head.appendChild(el);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function handleClick(e) {
|
|
42
|
+
const a = e.target.closest("a");
|
|
43
|
+
if (!a)
|
|
44
|
+
return;
|
|
45
|
+
const href = a.getAttribute("href");
|
|
46
|
+
if (!href)
|
|
47
|
+
return;
|
|
48
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
|
|
49
|
+
return;
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
navigate(href);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/client.ts
|
|
55
|
+
initRouter(routes);
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// .grimoire/_routes.ts
|
|
2
|
+
var routes = {};
|
|
3
|
+
|
|
4
|
+
// src/client-router.ts
|
|
5
|
+
var routeMap = {};
|
|
6
|
+
async function navigate(path) {
|
|
7
|
+
const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" } });
|
|
8
|
+
const json = await res.json();
|
|
9
|
+
console.log("navigate response:", json);
|
|
10
|
+
const { data, params, pattern, head } = json;
|
|
11
|
+
const Page = routeMap[pattern];
|
|
12
|
+
if (!Page) {
|
|
13
|
+
window.location.href = path;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const node = Page({ ...data, params });
|
|
17
|
+
const slot = document.getElementById("grimoire-page");
|
|
18
|
+
if (!slot)
|
|
19
|
+
return;
|
|
20
|
+
slot.replaceChildren(node);
|
|
21
|
+
updateHead(head);
|
|
22
|
+
history.pushState({}, "", path);
|
|
23
|
+
window.scrollTo(0, 0);
|
|
24
|
+
}
|
|
25
|
+
function initRouter(routes2) {
|
|
26
|
+
routeMap = routes2;
|
|
27
|
+
document.addEventListener("click", handleClick);
|
|
28
|
+
window.addEventListener("popstate", () => navigate(location.pathname));
|
|
29
|
+
}
|
|
30
|
+
function updateHead(headHtml) {
|
|
31
|
+
document.querySelectorAll("[data-grimoire-head]").forEach((el) => el.remove());
|
|
32
|
+
if (!headHtml)
|
|
33
|
+
return;
|
|
34
|
+
const tmp = document.createElement("head");
|
|
35
|
+
tmp.innerHTML = headHtml;
|
|
36
|
+
for (const el of Array.from(tmp.children)) {
|
|
37
|
+
el.dataset.grimoireHead = "1";
|
|
38
|
+
document.head.appendChild(el);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function handleClick(e) {
|
|
42
|
+
const a = e.target.closest("a");
|
|
43
|
+
if (!a)
|
|
44
|
+
return;
|
|
45
|
+
const href = a.getAttribute("href");
|
|
46
|
+
if (!href)
|
|
47
|
+
return;
|
|
48
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href))
|
|
49
|
+
return;
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
navigate(href);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/hydrate.ts
|
|
55
|
+
var stateEl = document.getElementById("__grimoire_state__");
|
|
56
|
+
if (stateEl) {
|
|
57
|
+
const state = JSON.parse(stateEl.textContent);
|
|
58
|
+
const Page = routes[state.pattern];
|
|
59
|
+
if (Page) {
|
|
60
|
+
Page({ ...state.data, params: state.params });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
initRouter(routes);
|
package/src/client/router.ts
CHANGED
|
@@ -15,6 +15,8 @@ export { depends };
|
|
|
15
15
|
|
|
16
16
|
async function refetchCurrent(): Promise<void> {
|
|
17
17
|
if (!lastState) return;
|
|
18
|
+
// a refetch exists because the data changed; never serve it from a prefetch
|
|
19
|
+
prefetched.clear();
|
|
18
20
|
await navigate(location.pathname, { history: "replace" });
|
|
19
21
|
}
|
|
20
22
|
|
|
@@ -185,42 +187,84 @@ function restorePreservedScroll(positions: Map<string, number>): void {
|
|
|
185
187
|
}
|
|
186
188
|
|
|
187
189
|
// C3: Preloading
|
|
190
|
+
//
|
|
191
|
+
// A prefetch keeps its in-flight Response here and navigate() consumes it.
|
|
192
|
+
// The HTTP cache cannot do this job: the navigate JSON carries no freshness
|
|
193
|
+
// headers and pages are commonly served `no-cache`, so a plain prefetch
|
|
194
|
+
// warmed nothing the click could reuse.
|
|
188
195
|
let preloadTimer: Timer | null = null;
|
|
196
|
+
const PREFETCH_TTL_MS = 15_000;
|
|
197
|
+
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
189
198
|
|
|
190
|
-
function
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (a.getAttribute("data-sigil-preload") === "off") return;
|
|
199
|
+
function navigateFetch(path: string, priority?: "low"): Promise<Response> {
|
|
200
|
+
return fetch(path, {
|
|
201
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
202
|
+
redirect: "manual",
|
|
203
|
+
...(priority ? { priority } : {}),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
198
206
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
+
/** The route-local href of an anchor worth prefetching, or null. */
|
|
208
|
+
function prefetchHref(a: Element | null): string | null {
|
|
209
|
+
if (!a) return null;
|
|
210
|
+
const href = a.getAttribute("href");
|
|
211
|
+
if (!href) return null;
|
|
212
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
|
|
213
|
+
if (a.getAttribute("data-sigil-preload") === "off") return null;
|
|
214
|
+
// Only links that resolve to a known client route — external pages and
|
|
215
|
+
// non-page endpoints (API routes, redirects) are skipped.
|
|
216
|
+
try {
|
|
217
|
+
const url = new URL(href, location.origin);
|
|
218
|
+
if (!findPattern(url.pathname)) return null;
|
|
219
|
+
} catch {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
return href;
|
|
223
|
+
}
|
|
207
224
|
|
|
208
|
-
|
|
225
|
+
/**
|
|
226
|
+
* Warm a navigation: load the route's code and start its data request. The
|
|
227
|
+
* response is held for a short while so the click that follows reuses it.
|
|
228
|
+
*/
|
|
229
|
+
export function prefetch(href: string): void {
|
|
230
|
+
const conn = (navigator as { connection?: { saveData?: boolean } }).connection;
|
|
231
|
+
if (conn?.saveData) return;
|
|
232
|
+
const url = new URL(href, location.origin);
|
|
233
|
+
const key = url.pathname + url.search;
|
|
234
|
+
const hit = prefetched.get(key);
|
|
235
|
+
if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
|
|
236
|
+
const pattern = findPattern(url.pathname);
|
|
237
|
+
if (pattern) void resolveRoute(pattern).catch(() => {});
|
|
238
|
+
const res = navigateFetch(key, "low");
|
|
239
|
+
res.catch(() => prefetched.delete(key));
|
|
240
|
+
prefetched.set(key, { res, at: Date.now() });
|
|
241
|
+
}
|
|
209
242
|
|
|
243
|
+
/** The held prefetch for `path` if it is still fresh; each is used once. */
|
|
244
|
+
function takePrefetched(path: string): Promise<Response> | null {
|
|
245
|
+
const url = new URL(path, location.origin);
|
|
246
|
+
const key = url.pathname + url.search;
|
|
247
|
+
const hit = prefetched.get(key);
|
|
248
|
+
prefetched.delete(key);
|
|
249
|
+
if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
|
|
250
|
+
return hit.res;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function setupPreload(): void {
|
|
254
|
+
// Hover is a desktop signal; a short delay ignores cursors passing over.
|
|
255
|
+
document.addEventListener("mouseover", (e) => {
|
|
256
|
+
const a = (e.target as Element).closest("a");
|
|
257
|
+
const href = prefetchHref(a);
|
|
258
|
+
if (!a || !href) return;
|
|
210
259
|
clearTimeout(preloadTimer);
|
|
211
260
|
preloadTimer = setTimeout(() => {
|
|
212
|
-
if (
|
|
261
|
+
if (a.hasAttribute("data-sigil-preload-code")) {
|
|
213
262
|
const link = document.createElement("link");
|
|
214
263
|
link.rel = "prefetch";
|
|
215
264
|
link.href = href;
|
|
216
265
|
document.head.appendChild(link);
|
|
217
266
|
}
|
|
218
|
-
|
|
219
|
-
fetch(href, {
|
|
220
|
-
headers: { "x-grimoire-navigate": "1" },
|
|
221
|
-
redirect: "manual",
|
|
222
|
-
priority: "low",
|
|
223
|
-
}).catch(() => {});
|
|
267
|
+
prefetch(href);
|
|
224
268
|
}, 80);
|
|
225
269
|
});
|
|
226
270
|
|
|
@@ -229,6 +273,43 @@ function setupPreload(): void {
|
|
|
229
273
|
if (!a) return;
|
|
230
274
|
clearTimeout(preloadTimer);
|
|
231
275
|
});
|
|
276
|
+
|
|
277
|
+
// Touch has no hover, but a tap lands 100-300ms after the finger goes
|
|
278
|
+
// down; start the request then.
|
|
279
|
+
document.addEventListener(
|
|
280
|
+
"touchstart",
|
|
281
|
+
(e) => {
|
|
282
|
+
const href = prefetchHref((e.target as Element).closest("a"));
|
|
283
|
+
if (href) prefetch(href);
|
|
284
|
+
},
|
|
285
|
+
{ passive: true },
|
|
286
|
+
);
|
|
287
|
+
|
|
288
|
+
// Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
|
|
289
|
+
// into view, for navs whose next tap is predictable.
|
|
290
|
+
if (typeof IntersectionObserver !== "undefined") {
|
|
291
|
+
const io = new IntersectionObserver((entries) => {
|
|
292
|
+
for (const entry of entries) {
|
|
293
|
+
if (!entry.isIntersecting) continue;
|
|
294
|
+
io.unobserve(entry.target);
|
|
295
|
+
const href = prefetchHref(entry.target);
|
|
296
|
+
if (href) prefetch(href);
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
const observe = (root: ParentNode) => {
|
|
300
|
+
for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
|
|
301
|
+
io.observe(a);
|
|
302
|
+
};
|
|
303
|
+
observe(document);
|
|
304
|
+
new MutationObserver((muts) => {
|
|
305
|
+
for (const m of muts)
|
|
306
|
+
for (const n of m.addedNodes)
|
|
307
|
+
if (n instanceof Element) {
|
|
308
|
+
if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
|
|
309
|
+
observe(n);
|
|
310
|
+
}
|
|
311
|
+
}).observe(document.body, { childList: true, subtree: true });
|
|
312
|
+
}
|
|
232
313
|
}
|
|
233
314
|
|
|
234
315
|
let lastState: {
|
|
@@ -358,10 +439,13 @@ export async function navigate(
|
|
|
358
439
|
else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
|
|
359
440
|
}
|
|
360
441
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
}
|
|
442
|
+
let res: Response;
|
|
443
|
+
try {
|
|
444
|
+
res = await (takePrefetched(path) ?? navigateFetch(path));
|
|
445
|
+
} catch {
|
|
446
|
+
// a failed prefetch must not fail the click
|
|
447
|
+
res = await navigateFetch(path);
|
|
448
|
+
}
|
|
365
449
|
if (navId !== navigationId) return;
|
|
366
450
|
const contentType = res.headers.get("content-type") ?? "";
|
|
367
451
|
if (!contentType.includes("application/json")) {
|
|
@@ -517,6 +601,7 @@ export function initRouter(
|
|
|
517
601
|
paramMatcherFns = ext?.matchers ?? {};
|
|
518
602
|
routeMap = routes;
|
|
519
603
|
layoutList = layouts;
|
|
604
|
+
prefetched.clear();
|
|
520
605
|
disposeCurrentPage = initialDispose ?? null;
|
|
521
606
|
currentPath = location.pathname;
|
|
522
607
|
currentSearch = location.search;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default image loading for server-rendered pages.
|
|
3
|
+
*
|
|
4
|
+
* The first few images are left alone: they are what the visitor sees first
|
|
5
|
+
* and lazy-loading them would delay the largest paint. Every later `<img>`
|
|
6
|
+
* gets `loading="lazy"` and `decoding="async"` so a long grid of thumbnails
|
|
7
|
+
* does not compete with the stylesheet and scripts for the first seconds of
|
|
8
|
+
* bandwidth. An author's own `loading` / `decoding` always wins.
|
|
9
|
+
*/
|
|
10
|
+
export const EAGER_IMAGE_COUNT = 4;
|
|
11
|
+
|
|
12
|
+
const IMG_TAG = /<img\b[^>]*>/gi;
|
|
13
|
+
// inline scripts and styles may contain "<img" inside strings
|
|
14
|
+
const RAW_BLOCK = /<(script|style|template)\b[\s\S]*?<\/\1>/gi;
|
|
15
|
+
|
|
16
|
+
export function optimizeImages(html: string): string {
|
|
17
|
+
if (!html.includes("<img")) return html;
|
|
18
|
+
let seen = 0;
|
|
19
|
+
const tag = (t: string) => {
|
|
20
|
+
if (seen++ < EAGER_IMAGE_COUNT) return t;
|
|
21
|
+
let extra = "";
|
|
22
|
+
if (!/\sloading\s*=/i.test(t)) extra += ' loading="lazy"';
|
|
23
|
+
if (!/\sdecoding\s*=/i.test(t)) extra += ' decoding="async"';
|
|
24
|
+
// attributes go before the tag's own trailing space and `/>`
|
|
25
|
+
return extra ? t.replace(/(\s*\/?>)$/, `${extra}$1`) : t;
|
|
26
|
+
};
|
|
27
|
+
let out = "";
|
|
28
|
+
let last = 0;
|
|
29
|
+
for (const m of html.matchAll(RAW_BLOCK)) {
|
|
30
|
+
out += html.slice(last, m.index).replace(IMG_TAG, tag) + m[0];
|
|
31
|
+
last = m.index + m[0].length;
|
|
32
|
+
}
|
|
33
|
+
return out + html.slice(last).replace(IMG_TAG, tag);
|
|
34
|
+
}
|
package/src/rendering/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { optimizeImages } from "./images.ts";
|
|
2
3
|
import { SafeHtml } from "@sigil-dev/runtime";
|
|
3
4
|
import { startCollecting, stopCollecting } from "../client/deps";
|
|
4
5
|
import { filterPublic } from "../env/index";
|
|
@@ -668,7 +669,7 @@ export async function renderRoute(
|
|
|
668
669
|
form: actionFailure?.data,
|
|
669
670
|
});
|
|
670
671
|
|
|
671
|
-
bodyHtml = injectCsrf(bodyHtml, csrfToken);
|
|
672
|
+
bodyHtml = optimizeImages(injectCsrf(bodyHtml, csrfToken));
|
|
672
673
|
|
|
673
674
|
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
674
675
|
const styles = scopedStyles(bodyHtml, nonceAttr);
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
export function isContentAddressed(pathname: string, search: string): boolean {
|
|
21
21
|
// /style.a1b2c3d4.css — a hash inserted before the extension.
|
|
22
22
|
if (/\.[0-9a-f]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
|
|
23
|
+
// /__grimoire__/chunk-jp4kgm87.js — the name the bundler gives a shared
|
|
24
|
+
// chunk: "chunk-" and a hash of the contents. Anchored on the prefix, since
|
|
25
|
+
// a bare "8+ letters before the extension" would also match hero-background.png.
|
|
26
|
+
if (/(^|\/)chunk-[a-z0-9]{8,}\.[a-z0-9]+$/i.test(pathname)) return true;
|
|
23
27
|
// A non-empty version query, e.g. /style.css?v=3. Deliberately does not
|
|
24
28
|
// treat `?` with an empty value as addressed: /style.css? is the same
|
|
25
29
|
// URL and would cache forever without ever changing.
|
package/src/server/index.ts
CHANGED
|
@@ -66,6 +66,25 @@ function watchRoots(projectRoot: string, routesDir: string): string[] {
|
|
|
66
66
|
return roots;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* ETags by file, keyed on size and modification time. Hashing the content on
|
|
71
|
+
* every request read the whole file and ran sha256 over it for each page
|
|
72
|
+
* view; the answer only changes when the file does.
|
|
73
|
+
*/
|
|
74
|
+
const etags = new Map<string, { stamp: string; etag: string }>();
|
|
75
|
+
|
|
76
|
+
async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
|
|
77
|
+
const key = file.name ?? "";
|
|
78
|
+
const stamp = `${file.size}:${file.lastModified}`;
|
|
79
|
+
const hit = etags.get(key);
|
|
80
|
+
if (hit && hit.stamp === stamp) return hit.etag;
|
|
81
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
82
|
+
hasher.update(await file.arrayBuffer());
|
|
83
|
+
const etag = `"${hasher.digest("hex").slice(0, 16)}"`;
|
|
84
|
+
etags.set(key, { stamp, etag });
|
|
85
|
+
return etag;
|
|
86
|
+
}
|
|
87
|
+
|
|
69
88
|
/**
|
|
70
89
|
* Serve a file from public/, or return null when the path is not one.
|
|
71
90
|
*
|
|
@@ -102,9 +121,7 @@ async function servePublicAsset(
|
|
|
102
121
|
if (policy === "revalidate") {
|
|
103
122
|
// The hash of the content, so a revalidation can be answered with
|
|
104
123
|
// 304 instead of the whole file.
|
|
105
|
-
const
|
|
106
|
-
hasher.update(await file.arrayBuffer());
|
|
107
|
-
const etag = `"${hasher.digest("hex").slice(0, 16)}"`;
|
|
124
|
+
const etag = await etagFor(file);
|
|
108
125
|
headers["ETag"] = etag;
|
|
109
126
|
|
|
110
127
|
// Compared here rather than left to Bun: a Bun.file body does not
|
|
@@ -23,6 +23,19 @@ describe("isContentAddressed", () => {
|
|
|
23
23
|
expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
|
|
24
24
|
});
|
|
25
25
|
|
|
26
|
+
test("a bundler chunk name counts", () => {
|
|
27
|
+
// Shared chunks are named for their contents, and every page load
|
|
28
|
+
// fetches them. Without this they revalidated each time.
|
|
29
|
+
expect(isContentAddressed("/__grimoire__/chunk-jp4kgm87.js", "")).toBe(true);
|
|
30
|
+
expect(cacheControlFor("/__grimoire__/chunk-1pk15q3t.js", "")).toBe("immutable");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("chunk- must be the whole stem, not a lookalike", () => {
|
|
34
|
+
expect(isContentAddressed("/chunk-list.js", "")).toBe(false);
|
|
35
|
+
expect(isContentAddressed("/img/hero-background.png", "")).toBe(false);
|
|
36
|
+
expect(isContentAddressed("/notchunk-abcdef12.js", "")).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
|
|
26
39
|
test("a bare filename does not count", () => {
|
|
27
40
|
// The bug this policy exists to prevent: a year-long cache at a URL
|
|
28
41
|
// that never changes, so an edited stylesheet is never seen.
|
|
@@ -295,6 +295,54 @@ describe("hover prefetch", () => {
|
|
|
295
295
|
});
|
|
296
296
|
});
|
|
297
297
|
|
|
298
|
+
describe("prefetch reuse", () => {
|
|
299
|
+
test("a tap reuses the request started on touchstart", async () => {
|
|
300
|
+
const root = document.createElement("div");
|
|
301
|
+
root.id = "grimoire-root";
|
|
302
|
+
document.body.appendChild(root);
|
|
303
|
+
router.initRouter({ "/tap": () => document.createElement("main") }, []);
|
|
304
|
+
const shim = captureFetch();
|
|
305
|
+
try {
|
|
306
|
+
const a = document.createElement("a");
|
|
307
|
+
a.setAttribute("href", "/tap");
|
|
308
|
+
document.body.appendChild(a);
|
|
309
|
+
a.dispatchEvent(new Event("touchstart", { bubbles: true }));
|
|
310
|
+
expect(shim.calls.length).toBe(1);
|
|
311
|
+
|
|
312
|
+
await router.navigate("/tap");
|
|
313
|
+
// the click did not issue a second request
|
|
314
|
+
expect(shim.calls.length).toBe(1);
|
|
315
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
316
|
+
|
|
317
|
+
// and a prefetch is single-use: the next visit fetches fresh data
|
|
318
|
+
await router.navigate("/tap");
|
|
319
|
+
expect(shim.calls.length).toBe(2);
|
|
320
|
+
} finally {
|
|
321
|
+
shim.restore();
|
|
322
|
+
root.remove();
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
test("invalidateAll never serves a prefetched response", async () => {
|
|
327
|
+
const root = document.createElement("div");
|
|
328
|
+
root.id = "grimoire-root";
|
|
329
|
+
document.body.appendChild(root);
|
|
330
|
+
window.history.pushState(null, "", "/inv");
|
|
331
|
+
router.initRouter({ "/inv": () => document.createElement("main") }, []);
|
|
332
|
+
const shim = captureFetch();
|
|
333
|
+
try {
|
|
334
|
+
await router.navigate("/inv");
|
|
335
|
+
router.prefetch("/inv");
|
|
336
|
+
const before = shim.calls.length;
|
|
337
|
+
await router.invalidateAll();
|
|
338
|
+
expect(shim.calls.length).toBe(before + 1);
|
|
339
|
+
} finally {
|
|
340
|
+
shim.restore();
|
|
341
|
+
root.remove();
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
|
|
298
346
|
describe("popstate — query string", () => {
|
|
299
347
|
// popstate fires navigate() from an event listener, so there is no promise
|
|
300
348
|
// to await at the call site. afterNavigate is the router's own completion
|
|
@@ -0,0 +1,34 @@
|
|
|
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("html without images is returned as is", () => {
|
|
32
|
+
expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
|
|
33
|
+
});
|
|
34
|
+
});
|