@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.
- 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 +180 -36
- package/src/rendering/images.ts +43 -0
- package/src/rendering/index.ts +15 -4
- package/src/rendering/preload.ts +94 -0
- package/src/rendering/timing.ts +40 -0
- package/src/server/asset-cache.ts +4 -0
- package/src/server/cached.ts +114 -0
- package/src/server/index.ts +61 -7
- package/src/server/warm.ts +91 -0
- package/src/server/worker.ts +1 -0
- package/src/types.ts +14 -0
- package/test/asset-cache-policy.test.ts +13 -0
- package/test/cached.test.ts +126 -0
- package/test/client-router.test.ts +180 -0
- package/test/images.test.ts +49 -0
- package/test/preload.test.ts +48 -0
- package/test/rendering.test.ts +33 -0
- package/test/warm.test.ts +96 -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.15",
|
|
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.15",
|
|
27
|
+
"@sigil-dev/runtime": "0.9.15",
|
|
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
|
|
|
@@ -184,43 +186,128 @@ function restorePreservedScroll(positions: Map<string, number>): void {
|
|
|
184
186
|
}
|
|
185
187
|
}
|
|
186
188
|
|
|
189
|
+
const TRANSITION_ATTR = "data-sigil-transition";
|
|
190
|
+
|
|
191
|
+
/** key → the one element carrying it; keys that appear twice are dropped,
|
|
192
|
+
* because a duplicate view-transition-name cancels the whole transition. */
|
|
193
|
+
function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
|
|
194
|
+
const seen = new Map<string, Element>();
|
|
195
|
+
const dup = new Set<string>();
|
|
196
|
+
for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
|
|
197
|
+
const key = el.getAttribute(TRANSITION_ATTR);
|
|
198
|
+
if (!key) continue;
|
|
199
|
+
if (seen.has(key)) dup.add(key);
|
|
200
|
+
else seen.set(key, el);
|
|
201
|
+
}
|
|
202
|
+
for (const key of dup) seen.delete(key);
|
|
203
|
+
return seen;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** [key, element on the current page, element on the incoming page] */
|
|
207
|
+
function sharedTransitionKeys(incoming: unknown): Array<[string, Element, Element]> {
|
|
208
|
+
const root = incoming as Partial<ParentNode> | null;
|
|
209
|
+
if (!root || typeof root.querySelectorAll !== "function") return [];
|
|
210
|
+
const next = uniqueTransitionEls(root as ParentNode);
|
|
211
|
+
if (next.size === 0) return [];
|
|
212
|
+
const prev = uniqueTransitionEls(document);
|
|
213
|
+
const both: Array<[string, Element, Element]> = [];
|
|
214
|
+
for (const [key, el] of next) {
|
|
215
|
+
const old = prev.get(key);
|
|
216
|
+
if (old) both.push([key, old, el]);
|
|
217
|
+
}
|
|
218
|
+
return both;
|
|
219
|
+
}
|
|
220
|
+
|
|
187
221
|
// C3: Preloading
|
|
222
|
+
//
|
|
223
|
+
// A prefetch keeps its in-flight Response here and navigate() consumes it.
|
|
224
|
+
// The HTTP cache cannot do this job: the navigate JSON carries no freshness
|
|
225
|
+
// headers and pages are commonly served `no-cache`, so a plain prefetch
|
|
226
|
+
// warmed nothing the click could reuse.
|
|
188
227
|
let preloadTimer: Timer | null = null;
|
|
228
|
+
const PREFETCH_TTL_MS = 15_000;
|
|
229
|
+
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
189
230
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
231
|
+
/**
|
|
232
|
+
* A held response is only valid for the cookies it was requested with: apps
|
|
233
|
+
* keep preferences (a language, a region, a theme) in cookies the server reads
|
|
234
|
+
* per request, so a page fetched before the visitor changed one is wrong
|
|
235
|
+
* after. Cookies the script can read are part of the key.
|
|
236
|
+
*/
|
|
237
|
+
function prefetchKey(url: URL): string {
|
|
238
|
+
return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
|
|
239
|
+
}
|
|
198
240
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
241
|
+
function navigateFetch(path: string, priority?: "low"): Promise<Response> {
|
|
242
|
+
return fetch(path, {
|
|
243
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
244
|
+
redirect: "manual",
|
|
245
|
+
...(priority ? { priority } : {}),
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The route-local href of an anchor worth prefetching, or null. */
|
|
250
|
+
function prefetchHref(a: Element | null): string | null {
|
|
251
|
+
if (!a) return null;
|
|
252
|
+
const href = a.getAttribute("href");
|
|
253
|
+
if (!href) return null;
|
|
254
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
|
|
255
|
+
if (a.getAttribute("data-sigil-preload") === "off") return null;
|
|
256
|
+
// Only links that resolve to a known client route — external pages and
|
|
257
|
+
// non-page endpoints (API routes, redirects) are skipped.
|
|
258
|
+
try {
|
|
259
|
+
const url = new URL(href, location.origin);
|
|
260
|
+
if (!findPattern(url.pathname)) return null;
|
|
261
|
+
} catch {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
return href;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Warm a navigation: load the route's code and start its data request. The
|
|
269
|
+
* response is held for a short while so the click that follows reuses it.
|
|
270
|
+
*/
|
|
271
|
+
export function prefetch(href: string): void {
|
|
272
|
+
const conn = (navigator as { connection?: { saveData?: boolean } }).connection;
|
|
273
|
+
if (conn?.saveData) return;
|
|
274
|
+
const url = new URL(href, location.origin);
|
|
275
|
+
// the page already on screen needs no warming
|
|
276
|
+
if (url.pathname === location.pathname && url.search === location.search) return;
|
|
277
|
+
const key = prefetchKey(url);
|
|
278
|
+
const hit = prefetched.get(key);
|
|
279
|
+
if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
|
|
280
|
+
const pattern = findPattern(url.pathname);
|
|
281
|
+
if (pattern) void resolveRoute(pattern).catch(() => {});
|
|
282
|
+
const res = navigateFetch(url.pathname + url.search, "low");
|
|
283
|
+
res.catch(() => prefetched.delete(key));
|
|
284
|
+
prefetched.set(key, { res, at: Date.now() });
|
|
285
|
+
}
|
|
207
286
|
|
|
208
|
-
|
|
287
|
+
/** The held prefetch for `path` if it is still fresh; each is used once. */
|
|
288
|
+
function takePrefetched(path: string): Promise<Response> | null {
|
|
289
|
+
const key = prefetchKey(new URL(path, location.origin));
|
|
290
|
+
const hit = prefetched.get(key);
|
|
291
|
+
prefetched.delete(key);
|
|
292
|
+
if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
|
|
293
|
+
return hit.res;
|
|
294
|
+
}
|
|
209
295
|
|
|
296
|
+
function setupPreload(): void {
|
|
297
|
+
// Hover is a desktop signal; a short delay ignores cursors passing over.
|
|
298
|
+
document.addEventListener("mouseover", (e) => {
|
|
299
|
+
const a = (e.target as Element).closest("a");
|
|
300
|
+
const href = prefetchHref(a);
|
|
301
|
+
if (!a || !href) return;
|
|
210
302
|
clearTimeout(preloadTimer);
|
|
211
303
|
preloadTimer = setTimeout(() => {
|
|
212
|
-
if (
|
|
304
|
+
if (a.hasAttribute("data-sigil-preload-code")) {
|
|
213
305
|
const link = document.createElement("link");
|
|
214
306
|
link.rel = "prefetch";
|
|
215
307
|
link.href = href;
|
|
216
308
|
document.head.appendChild(link);
|
|
217
309
|
}
|
|
218
|
-
|
|
219
|
-
fetch(href, {
|
|
220
|
-
headers: { "x-grimoire-navigate": "1" },
|
|
221
|
-
redirect: "manual",
|
|
222
|
-
priority: "low",
|
|
223
|
-
}).catch(() => {});
|
|
310
|
+
prefetch(href);
|
|
224
311
|
}, 80);
|
|
225
312
|
});
|
|
226
313
|
|
|
@@ -229,6 +316,43 @@ function setupPreload(): void {
|
|
|
229
316
|
if (!a) return;
|
|
230
317
|
clearTimeout(preloadTimer);
|
|
231
318
|
});
|
|
319
|
+
|
|
320
|
+
// Touch has no hover, but a tap lands 100-300ms after the finger goes
|
|
321
|
+
// down; start the request then.
|
|
322
|
+
document.addEventListener(
|
|
323
|
+
"touchstart",
|
|
324
|
+
(e) => {
|
|
325
|
+
const href = prefetchHref((e.target as Element).closest("a"));
|
|
326
|
+
if (href) prefetch(href);
|
|
327
|
+
},
|
|
328
|
+
{ passive: true },
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
// Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
|
|
332
|
+
// into view, for navs whose next tap is predictable.
|
|
333
|
+
if (typeof IntersectionObserver !== "undefined") {
|
|
334
|
+
const io = new IntersectionObserver((entries) => {
|
|
335
|
+
for (const entry of entries) {
|
|
336
|
+
if (!entry.isIntersecting) continue;
|
|
337
|
+
io.unobserve(entry.target);
|
|
338
|
+
const href = prefetchHref(entry.target);
|
|
339
|
+
if (href) prefetch(href);
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
const observe = (root: ParentNode) => {
|
|
343
|
+
for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
|
|
344
|
+
io.observe(a);
|
|
345
|
+
};
|
|
346
|
+
observe(document);
|
|
347
|
+
new MutationObserver((muts) => {
|
|
348
|
+
for (const m of muts)
|
|
349
|
+
for (const n of m.addedNodes)
|
|
350
|
+
if (n instanceof Element) {
|
|
351
|
+
if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
|
|
352
|
+
observe(n);
|
|
353
|
+
}
|
|
354
|
+
}).observe(document.body, { childList: true, subtree: true });
|
|
355
|
+
}
|
|
232
356
|
}
|
|
233
357
|
|
|
234
358
|
let lastState: {
|
|
@@ -358,10 +482,13 @@ export async function navigate(
|
|
|
358
482
|
else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
|
|
359
483
|
}
|
|
360
484
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
}
|
|
485
|
+
let res: Response;
|
|
486
|
+
try {
|
|
487
|
+
res = await (takePrefetched(path) ?? navigateFetch(path));
|
|
488
|
+
} catch {
|
|
489
|
+
// a failed prefetch must not fail the click
|
|
490
|
+
res = await navigateFetch(path);
|
|
491
|
+
}
|
|
365
492
|
if (navId !== navigationId) return;
|
|
366
493
|
const contentType = res.headers.get("content-type") ?? "";
|
|
367
494
|
if (!contentType.includes("application/json")) {
|
|
@@ -470,19 +597,33 @@ export async function navigate(
|
|
|
470
597
|
// View transitions: animate the swap when the browser supports it and the
|
|
471
598
|
// user hasn't asked for reduced motion. The callback must stay synchronous.
|
|
472
599
|
const preserved = capturePreservedScroll();
|
|
600
|
+
const doc = document as Document & {
|
|
601
|
+
startViewTransition?: (cb: () => void) => { finished?: Promise<unknown> } | undefined;
|
|
602
|
+
};
|
|
603
|
+
const animate =
|
|
604
|
+
typeof doc.startViewTransition === "function" &&
|
|
605
|
+
!window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
606
|
+
// elements the old and new page share by key morph into each other
|
|
607
|
+
const shared = animate ? sharedTransitionKeys(rootNode) : [];
|
|
608
|
+
const named: Element[] = [];
|
|
609
|
+
const name = (el: Element, key: string) => {
|
|
610
|
+
(el as HTMLElement).style.setProperty("view-transition-name", key);
|
|
611
|
+
named.push(el);
|
|
612
|
+
};
|
|
473
613
|
const doSwap = () => {
|
|
474
614
|
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
615
|
+
for (const [key, , next] of shared) name(next, key);
|
|
475
616
|
restorePreservedScroll(preserved);
|
|
476
617
|
applyScroll();
|
|
477
618
|
};
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
619
|
+
if (animate) {
|
|
620
|
+
// the browser snapshots the old page as startViewTransition is called
|
|
621
|
+
for (const [key, prev] of shared) name(prev, key);
|
|
622
|
+
const transition = doc.startViewTransition?.(doSwap);
|
|
623
|
+
const clear = () => {
|
|
624
|
+
for (const el of named) (el as HTMLElement).style.removeProperty("view-transition-name");
|
|
625
|
+
};
|
|
626
|
+
Promise.resolve(transition?.finished).then(clear, clear);
|
|
486
627
|
} else {
|
|
487
628
|
doSwap();
|
|
488
629
|
}
|
|
@@ -517,6 +658,7 @@ export function initRouter(
|
|
|
517
658
|
paramMatcherFns = ext?.matchers ?? {};
|
|
518
659
|
routeMap = routes;
|
|
519
660
|
layoutList = layouts;
|
|
661
|
+
prefetched.clear();
|
|
520
662
|
disposeCurrentPage = initialDispose ?? null;
|
|
521
663
|
currentPath = location.pathname;
|
|
522
664
|
currentSearch = location.search;
|
|
@@ -642,5 +784,7 @@ function handleClick(e: MouseEvent) {
|
|
|
642
784
|
return;
|
|
643
785
|
}
|
|
644
786
|
e.preventDefault();
|
|
787
|
+
// a pending hover prefetch would re-request what this click just consumed
|
|
788
|
+
clearTimeout(preloadTimer);
|
|
645
789
|
navigate(href);
|
|
646
790
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
* `data-sigil-priority` marks the image that should paint first (the hero,
|
|
11
|
+
* the likely largest paint): it stays eager and is fetched at high priority,
|
|
12
|
+
* and does not count toward the eager budget above.
|
|
13
|
+
*/
|
|
14
|
+
export const EAGER_IMAGE_COUNT = 4;
|
|
15
|
+
|
|
16
|
+
const IMG_TAG = /<img\b[^>]*>/gi;
|
|
17
|
+
// inline scripts and styles may contain "<img" inside strings
|
|
18
|
+
const RAW_BLOCK = /<(script|style|template)\b[\s\S]*?<\/\1>/gi;
|
|
19
|
+
|
|
20
|
+
export function optimizeImages(html: string): string {
|
|
21
|
+
if (!html.includes("<img")) return html;
|
|
22
|
+
let seen = 0;
|
|
23
|
+
const tag = (t: string) => {
|
|
24
|
+
if (/\sdata-sigil-priority\b/i.test(t)) {
|
|
25
|
+
return /\sfetchpriority\s*=/i.test(t)
|
|
26
|
+
? t
|
|
27
|
+
: t.replace(/(\s*\/?>)$/, ' fetchpriority="high"$1');
|
|
28
|
+
}
|
|
29
|
+
if (seen++ < EAGER_IMAGE_COUNT) return t;
|
|
30
|
+
let extra = "";
|
|
31
|
+
if (!/\sloading\s*=/i.test(t)) extra += ' loading="lazy"';
|
|
32
|
+
if (!/\sdecoding\s*=/i.test(t)) extra += ' decoding="async"';
|
|
33
|
+
// attributes go before the tag's own trailing space and `/>`
|
|
34
|
+
return extra ? t.replace(/(\s*\/?>)$/, `${extra}$1`) : t;
|
|
35
|
+
};
|
|
36
|
+
let out = "";
|
|
37
|
+
let last = 0;
|
|
38
|
+
for (const m of html.matchAll(RAW_BLOCK)) {
|
|
39
|
+
out += html.slice(last, m.index).replace(IMG_TAG, tag) + m[0];
|
|
40
|
+
last = m.index + m[0].length;
|
|
41
|
+
}
|
|
42
|
+
return out + html.slice(last).replace(IMG_TAG, tag);
|
|
43
|
+
}
|
package/src/rendering/index.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { preloadLinks } from "./preload.ts";
|
|
3
|
+
import { createTimer } from "./timing.ts";
|
|
4
|
+
import { optimizeImages } from "./images.ts";
|
|
2
5
|
import { SafeHtml } from "@sigil-dev/runtime";
|
|
3
6
|
import { startCollecting, stopCollecting } from "../client/deps";
|
|
4
7
|
import { filterPublic } from "../env/index";
|
|
@@ -288,6 +291,7 @@ export async function renderRoute(
|
|
|
288
291
|
parent: async () => ({}),
|
|
289
292
|
};
|
|
290
293
|
|
|
294
|
+
const timer = createTimer();
|
|
291
295
|
initHead(cspNonce);
|
|
292
296
|
const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
|
|
293
297
|
|
|
@@ -509,7 +513,7 @@ export async function renderRoute(
|
|
|
509
513
|
async start(controller) {
|
|
510
514
|
// 1. skeleton + loading shell — browser paints immediately
|
|
511
515
|
controller.enqueue(
|
|
512
|
-
`${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
|
|
516
|
+
`${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
|
|
513
517
|
</head>
|
|
514
518
|
<body>
|
|
515
519
|
<div id="app">${loadingBody}`,
|
|
@@ -613,6 +617,7 @@ export async function renderRoute(
|
|
|
613
617
|
: pageData;
|
|
614
618
|
extractDeferred(mergedData, deferred, deferredCounter);
|
|
615
619
|
|
|
620
|
+
timer.mark("load");
|
|
616
621
|
const pageHtml = await Promise.resolve(
|
|
617
622
|
pageMod.default({
|
|
618
623
|
data: renderable(mergedData),
|
|
@@ -626,6 +631,7 @@ export async function renderRoute(
|
|
|
626
631
|
// defaults) only registers once the layout itself has run, so
|
|
627
632
|
// collecting too early silently drops it
|
|
628
633
|
let bodyHtml = applyLayouts(String(pageHtml));
|
|
634
|
+
timer.mark("render");
|
|
629
635
|
|
|
630
636
|
const headHtml = collectHead();
|
|
631
637
|
|
|
@@ -644,6 +650,7 @@ export async function renderRoute(
|
|
|
644
650
|
// raw state payloads rendering as the page after a back navigation.
|
|
645
651
|
// Deliberately still cacheable: hover-prefetch exists to warm this
|
|
646
652
|
// entry, and Vary already keeps document requests from matching it.
|
|
653
|
+
timer.mark("deferred");
|
|
647
654
|
return Response.json(
|
|
648
655
|
{
|
|
649
656
|
data: mergedData ?? {},
|
|
@@ -653,7 +660,7 @@ export async function renderRoute(
|
|
|
653
660
|
head: headHtml,
|
|
654
661
|
deps: [...collectedDeps],
|
|
655
662
|
},
|
|
656
|
-
{ headers: { Vary: NAVIGATE_HEADER } },
|
|
663
|
+
{ headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
|
|
657
664
|
);
|
|
658
665
|
}
|
|
659
666
|
|
|
@@ -668,14 +675,17 @@ export async function renderRoute(
|
|
|
668
675
|
form: actionFailure?.data,
|
|
669
676
|
});
|
|
670
677
|
|
|
671
|
-
bodyHtml = injectCsrf(bodyHtml, csrfToken);
|
|
678
|
+
bodyHtml = optimizeImages(injectCsrf(bodyHtml, csrfToken));
|
|
672
679
|
|
|
673
680
|
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
674
681
|
const styles = scopedStyles(bodyHtml, nonceAttr);
|
|
675
682
|
|
|
676
683
|
const stream = new ReadableStream({
|
|
677
684
|
async start(controller) {
|
|
678
|
-
controller.enqueue(
|
|
685
|
+
controller.enqueue(
|
|
686
|
+
buildHtmlSkeleton(nonceAttr, dev) +
|
|
687
|
+
preloadLinks(matched.route.path, nonceAttr, dev),
|
|
688
|
+
);
|
|
679
689
|
|
|
680
690
|
if (hoistedCss) {
|
|
681
691
|
controller.enqueue(`\n ${hoistedCss}`);
|
|
@@ -712,6 +722,7 @@ export async function renderRoute(
|
|
|
712
722
|
"Content-Type": "text/html",
|
|
713
723
|
"Set-Cookie": csrfCookie(csrfToken),
|
|
714
724
|
Vary: NAVIGATE_HEADER,
|
|
725
|
+
...timer.headers(),
|
|
715
726
|
},
|
|
716
727
|
});
|
|
717
728
|
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<link rel="modulepreload">` for the chunks a route needs.
|
|
3
|
+
*
|
|
4
|
+
* The client bundle loads a route's code with a lazy `import()`, which only
|
|
5
|
+
* starts once hydrate.js has downloaded and run: HTML, then hydrate.js, then
|
|
6
|
+
* the route chunk, then whatever that chunk imports. Naming those chunks in
|
|
7
|
+
* the HTML lets the browser fetch them alongside hydrate.js instead of behind
|
|
8
|
+
* it.
|
|
9
|
+
*
|
|
10
|
+
* The chunk graph is read back out of the built hydrate.js (the bundler
|
|
11
|
+
* writes it there for its own preloading), so no build step has to cooperate.
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
|
|
16
|
+
interface ChunkGraph {
|
|
17
|
+
/** route pattern → chunk id */
|
|
18
|
+
routes: Map<string, string>;
|
|
19
|
+
/** chunk id → [file, ...ids it imports] */
|
|
20
|
+
nodes: Map<string, { file: string; deps: string[] }>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const BASE = "/__grimoire__/";
|
|
24
|
+
let graph: ChunkGraph | null | undefined;
|
|
25
|
+
|
|
26
|
+
export function parseChunkGraph(source: string): ChunkGraph | null {
|
|
27
|
+
const call = /^__chunks\(import\.meta\.url,(\[.*?\]),(\[\[.*?\]\]),(\d+)\)/m.exec(
|
|
28
|
+
source,
|
|
29
|
+
);
|
|
30
|
+
if (!call) return null;
|
|
31
|
+
let ids: string[];
|
|
32
|
+
let raw: Array<Array<string | number>>;
|
|
33
|
+
try {
|
|
34
|
+
ids = JSON.parse(call[1]);
|
|
35
|
+
raw = JSON.parse(call[2]);
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const nodes: ChunkGraph["nodes"] = new Map();
|
|
40
|
+
ids.forEach((id, i) => {
|
|
41
|
+
const [file, ...deps] = raw[i] ?? [];
|
|
42
|
+
if (typeof file !== "string") return;
|
|
43
|
+
nodes.set(id, { file, deps: deps.map((d) => ids[Number(d)]).filter(Boolean) });
|
|
44
|
+
});
|
|
45
|
+
const routes = new Map<string, string>();
|
|
46
|
+
for (const m of source.matchAll(
|
|
47
|
+
/^\s*("(?:[^"\\]|\\.)*"):\s*\{\s*__lazy:\s*\(\)\s*=>\s*\(__preload\("([^"]+)"\)/gm,
|
|
48
|
+
)) {
|
|
49
|
+
routes.set(JSON.parse(m[1]), m[2]);
|
|
50
|
+
}
|
|
51
|
+
return { routes, nodes };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function load(): ChunkGraph | null {
|
|
55
|
+
if (graph !== undefined) return graph;
|
|
56
|
+
const file = join(process.cwd(), "public", "__grimoire__", "hydrate.js");
|
|
57
|
+
graph = existsSync(file) ? parseChunkGraph(readFileSync(file, "utf-8")) : null;
|
|
58
|
+
return graph;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Files (relative to /__grimoire__/) the route's chunk needs, closure included. */
|
|
62
|
+
export function chunksFor(g: ChunkGraph, pattern: string): string[] {
|
|
63
|
+
const start = g.routes.get(pattern);
|
|
64
|
+
if (!start) return [];
|
|
65
|
+
const seen = new Set<string>();
|
|
66
|
+
const stack = [start];
|
|
67
|
+
const files: string[] = [];
|
|
68
|
+
while (stack.length) {
|
|
69
|
+
const id = stack.pop() as string;
|
|
70
|
+
if (seen.has(id)) continue;
|
|
71
|
+
seen.add(id);
|
|
72
|
+
const node = g.nodes.get(id);
|
|
73
|
+
if (!node) continue;
|
|
74
|
+
// hydrate.js itself is already a <script> in the head
|
|
75
|
+
if (!/(^|\/)hydrate\.js$/.test(node.file)) files.push(node.file.replace(/^\.\//, ""));
|
|
76
|
+
stack.push(...node.deps);
|
|
77
|
+
}
|
|
78
|
+
return files;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The preload tags for a route, or "" in dev / when there is no built graph. */
|
|
82
|
+
export function preloadLinks(pattern: string, nonceAttr: string, dev?: boolean): string {
|
|
83
|
+
if (dev) return "";
|
|
84
|
+
const g = load();
|
|
85
|
+
if (!g) return "";
|
|
86
|
+
return chunksFor(g, pattern)
|
|
87
|
+
.map((f) => `\n <link rel="modulepreload" href="${BASE}${f}" crossorigin${nonceAttr}>`)
|
|
88
|
+
.join("");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** For tests: forget the cached graph. */
|
|
92
|
+
export function resetChunkGraph(): void {
|
|
93
|
+
graph = undefined;
|
|
94
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Server-Timing` for route renders, so the browser's network panel shows
|
|
3
|
+
* where a slow page spent its time (`load` = layout and page server loads,
|
|
4
|
+
* `render` = components to HTML) without any extra tooling.
|
|
5
|
+
*
|
|
6
|
+
* On in dev; in production only when `serverTiming: true`, since durations are
|
|
7
|
+
* visible to every visitor.
|
|
8
|
+
*/
|
|
9
|
+
let enabled = false;
|
|
10
|
+
|
|
11
|
+
export function setServerTiming(on: boolean): void {
|
|
12
|
+
enabled = on;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface Timer {
|
|
16
|
+
/** Close the phase that has been running since the last mark. */
|
|
17
|
+
mark(name: string): void;
|
|
18
|
+
/** `{ "Server-Timing": ... }`, or nothing when disabled or no marks. */
|
|
19
|
+
headers(): Record<string, string>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createTimer(): Timer {
|
|
23
|
+
const marks: Array<[string, number]> = [];
|
|
24
|
+
let last = performance.now();
|
|
25
|
+
return {
|
|
26
|
+
mark(name) {
|
|
27
|
+
const now = performance.now();
|
|
28
|
+
marks.push([name, now - last]);
|
|
29
|
+
last = now;
|
|
30
|
+
},
|
|
31
|
+
headers() {
|
|
32
|
+
if (!enabled || marks.length === 0) return {};
|
|
33
|
+
return {
|
|
34
|
+
"Server-Timing": marks
|
|
35
|
+
.map(([n, d]) => `${n};dur=${d.toFixed(1)}`)
|
|
36
|
+
.join(", "),
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|