@sigil-dev/grimoire 0.9.26 → 0.9.27

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,914 +1,915 @@
1
- import {
2
- collectEffects,
3
- popHydrationNodes,
4
- pushHydrationNodes,
5
- } from "@sigil-dev/runtime";
6
- import { base, stripBase } from "../base";
7
- import { onSubmitEnsureCsrf } from "./csrf.ts";
8
- import {
9
- clearDeps,
10
- depends,
11
- getDeps,
12
- setDeps,
13
- startCollecting,
14
- stopCollecting,
15
- } from "./deps";
16
- import { withEffectScope } from "./scope";
17
-
18
- // re-exported for app code that imports depends() from the router module
19
- export { depends };
20
-
21
- async function refetchCurrent(): Promise<void> {
22
- if (!lastState) return;
23
- // a refetch exists because the data changed; never serve it from a prefetch
24
- prefetched.clear();
25
- await navigate(location.pathname, { history: "replace" });
26
- }
27
-
28
- export async function invalidate(...keys: string[]): Promise<void> {
29
- const current = lastState?.pattern;
30
- if (!current) return;
31
- const deps = getDeps(current);
32
- // no recorded deps → conservative refetch; otherwise only on intersection
33
- if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
34
- await refetchCurrent();
35
- }
36
- }
37
-
38
- export async function invalidateAll(): Promise<void> {
39
- await refetchCurrent();
40
- }
41
-
42
- type PageComponent = ((props: any) => any) & {
43
- load?: (ctx: any) => Promise<any>;
44
- loading?: () => any;
45
- error?: (props: { error: unknown }) => any;
46
- };
47
- /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
48
- * component functions are also accepted (tests, HMR replacements). */
49
- type RouteEntry =
50
- | PageComponent
51
- | { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
52
-
53
- let routeMap: Record<string, RouteEntry> = {};
54
- const resolvedRoutes: Record<string, PageComponent> = {};
55
-
56
- async function resolveRoute(pattern: string): Promise<PageComponent | null> {
57
- const entry = routeMap[pattern];
58
- if (!entry) return null;
59
- // plain function: eager component or an HMR hot-swap — always wins over cache
60
- if (typeof entry === "function") return entry;
61
- if (!resolvedRoutes[pattern]) {
62
- const mod = (await entry.__lazy()) as {
63
- default: PageComponent;
64
- loading?: PageComponent["loading"];
65
- };
66
- // `loading` is a named export of the page module; navigation looks
67
- // for it on the component, and never saw it before
68
- if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
69
- resolvedRoutes[pattern] = mod.default;
70
- }
71
- return resolvedRoutes[pattern];
72
- }
73
- let layoutList: { path: string; component: (props: any) => any }[] = [];
74
- let disposeCurrentPage: (() => void) | null = null;
75
- // Scroll keys and same-page refetch detection are pathname-only on purpose.
76
- // currentSearch is tracked alongside so popstate can tell "?page=2" apart
77
- // from "?page=1" without polluting either of those.
78
- let currentPath = location.pathname;
79
- let currentSearch = location.search;
80
-
81
- // C1: Navigation hooks
82
- let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
83
- let onNavigateCb: ((url: URL) => void) | null = null;
84
- let afterNavigateCb: ((url: URL) => void) | null = null;
85
-
86
- /**
87
- * Shows the page again with an enhanced form's failure as its `form` prop,
88
- * which is what a submission without JavaScript gets from the server. The
89
- * same page code then works either way.
90
- */
91
- export function showActionFailure(form: unknown): Promise<void> {
92
- if (!lastState) return Promise.resolve();
93
- lastState = { ...lastState, form };
94
- return hmrRerender();
95
- }
96
-
97
- export async function hmrRerender(): Promise<void> {
98
- if (!lastState) {
99
- location.reload();
100
- return;
101
- }
102
- const Page = await resolveRoute(lastState.pattern);
103
- if (!Page) {
104
- location.reload();
105
- return;
106
- }
107
- disposeCurrentPage?.();
108
- pushHydrationNodes([]);
109
- let rootNode: any;
110
- let flush = () => {};
111
- disposeCurrentPage = withEffectScope(() => {
112
- ({ value: rootNode, flush } = collectEffects(() =>
113
- buildRouteTree(lastState!, Page),
114
- ));
115
- });
116
- popHydrationNodes();
117
- const preserved = capturePreservedScroll();
118
- // swapping the root can shrink the document for a moment, and the browser
119
- // clamps scrollY to the shorter height; put the page back where it was
120
- const y = window.scrollY;
121
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
122
- flush();
123
- restorePreservedScroll(preserved);
124
- window.scrollTo(0, y);
125
- requestAnimationFrame(() => window.scrollTo(0, y));
126
- }
127
-
128
- /**
129
- * Dev-only surface the HMR client drives. Route entries are replaced rather
130
- * than mutated in place so a swapped module also wins for later navigations,
131
- * and the resolved-module cache is dropped with them.
132
- */
133
- export interface HmrControl {
134
- setRoute(pattern: string, entry: RouteEntry): void;
135
- setLayout(path: string, component: (props: any) => any): void;
136
- rerender(): Promise<void>;
137
- }
138
-
139
- const hmrControl: HmrControl = {
140
- setRoute(pattern, entry) {
141
- routeMap[pattern] = entry;
142
- delete resolvedRoutes[pattern];
143
- },
144
- setLayout(path: string, component: (props: any) => any) {
145
- const existing = layoutList.find((l) => l.path === path);
146
- if (existing) existing.component = component;
147
- else layoutList.push({ path, component });
148
- },
149
- rerender: hmrRerender,
150
- };
151
-
152
- export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
153
- beforeNavigateCb = cb;
154
- }
155
-
156
- export function onNavigate(cb: (url: URL) => void): void {
157
- onNavigateCb = cb;
158
- }
159
-
160
- export function afterNavigate(cb: (url: URL) => void): void {
161
- afterNavigateCb = cb;
162
- }
163
-
164
- // C2: Scroll restoration
165
- const scrollPositions = new Map<string, number>();
166
-
167
- function saveScrollPosition(): void {
168
- scrollPositions.set(currentPath, window.scrollY);
169
- }
170
-
171
- function restoreScrollPosition(path: string): void {
172
- const y = scrollPositions.get(path) ?? 0;
173
- window.scrollTo(0, y);
174
- // re-assert after layout settles (late effects/images can shift content)
175
- requestAnimationFrame(() => window.scrollTo(0, y));
176
- }
177
-
178
- function scrollToTop(): void {
179
- window.scrollTo(0, 0);
180
- requestAnimationFrame(() => window.scrollTo(0, 0));
181
- }
182
-
183
- // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
184
- // across the root swap: the router rebuilds the whole tree on navigation, so a
185
- // long independently-scrollable sidebar would otherwise snap back to the top.
186
- // The attribute value is the matching key; elements without one fall back to
187
- // their id, then to their ordinal position.
188
- const PRESERVE_ATTR = "data-sigil-scroll-preserve";
189
-
190
- function preserveKey(el: Element, ordinal: number): string {
191
- return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
192
- }
193
-
194
- function capturePreservedScroll(): Map<string, number> {
195
- const positions = new Map<string, number>();
196
- let ordinal = 0;
197
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
198
- positions.set(preserveKey(el, ordinal), el.scrollTop);
199
- ordinal++;
200
- }
201
- return positions;
202
- }
203
-
204
- function restorePreservedScroll(positions: Map<string, number>): void {
205
- if (positions.size === 0) return;
206
- let ordinal = 0;
207
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
208
- const top = positions.get(preserveKey(el, ordinal));
209
- if (top !== undefined) el.scrollTop = top;
210
- ordinal++;
211
- }
212
- }
213
-
214
- const TRANSITION_ATTR = "data-sigil-transition";
215
-
216
- /** key → the one element carrying it; keys that appear twice are dropped,
217
- * because a duplicate view-transition-name cancels the whole transition. */
218
- function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
219
- const seen = new Map<string, Element>();
220
- const dup = new Set<string>();
221
- for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
222
- const key = el.getAttribute(TRANSITION_ATTR);
223
- if (!key) continue;
224
- if (seen.has(key)) dup.add(key);
225
- else seen.set(key, el);
226
- }
227
- for (const key of dup) seen.delete(key);
228
- return seen;
229
- }
230
-
231
- /** [key, element on the current page, element on the incoming page] */
232
- function sharedTransitionKeys(
233
- incoming: unknown,
234
- ): Array<[string, Element, Element]> {
235
- const root = incoming as Partial<ParentNode> | null;
236
- if (!root || typeof root.querySelectorAll !== "function") return [];
237
- const next = uniqueTransitionEls(root as ParentNode);
238
- if (next.size === 0) return [];
239
- const prev = uniqueTransitionEls(document);
240
- const both: Array<[string, Element, Element]> = [];
241
- for (const [key, el] of next) {
242
- const old = prev.get(key);
243
- if (old) both.push([key, old, el]);
244
- }
245
- return both;
246
- }
247
-
248
- // C3: Preloading
249
- //
250
- // A prefetch keeps its in-flight Response here and navigate() consumes it.
251
- // The HTTP cache cannot do this job: the navigate JSON carries no freshness
252
- // headers and pages are commonly served `no-cache`, so a plain prefetch
253
- // warmed nothing the click could reuse.
254
- let preloadTimer: Timer | null = null;
255
- const PREFETCH_TTL_MS = 15_000;
256
- const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
257
-
258
- /**
259
- * A held response is only valid for the cookies it was requested with: apps
260
- * keep preferences (a language, a region, a theme) in cookies the server reads
261
- * per request, so a page fetched before the visitor changed one is wrong
262
- * after. Cookies the script can read are part of the key.
263
- */
264
- function prefetchKey(url: URL): string {
265
- return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
266
- }
267
-
268
- /**
269
- * A prerendered site has no server to answer `x-grimoire-navigate`, so
270
- * `adapterStatic` marks its pages and writes the same payload to
271
- * `<page>/__data.json`, which any static host serves. The path must match
272
- * `dataFileFor` in server/prerender.ts.
273
- */
274
- function navigateTarget(path: string): string {
275
- if (
276
- (globalThis as { __grimoire_static__?: unknown }).__grimoire_static__ !== 1
277
- ) {
278
- return path;
279
- }
280
- const { pathname } = new URL(path, location.origin);
281
- return `${pathname.replace(/\/+$/, "")}/__data.json`;
282
- }
283
-
284
- function navigateFetch(path: string, priority?: "low"): Promise<Response> {
285
- const target = navigateTarget(path);
286
- return fetch(target, {
287
- ...(target === path ? { headers: { "x-grimoire-navigate": "1" } } : {}),
288
- redirect: "manual",
289
- ...(priority ? { priority } : {}),
290
- });
291
- }
292
-
293
- /** The route-local href of an anchor worth prefetching, or null. */
294
- function prefetchHref(a: Element | null): string | null {
295
- if (!a) return null;
296
- const href = a.getAttribute("href");
297
- if (!href) return null;
298
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
299
- if (a.getAttribute("data-sigil-preload") === "off") return null;
300
- // Only links that resolve to a known client route — external pages and
301
- // non-page endpoints (API routes, redirects) are skipped.
302
- try {
303
- const url = new URL(href, location.origin);
304
- if (!findPattern(url.pathname)) return null;
305
- } catch {
306
- return null;
307
- }
308
- return href;
309
- }
310
-
311
- /**
312
- * Warm a navigation: load the route's code and start its data request. The
313
- * response is held for a short while so the click that follows reuses it.
314
- */
315
- export function prefetch(href: string): void {
316
- const conn = (navigator as { connection?: { saveData?: boolean } })
317
- .connection;
318
- if (conn?.saveData) return;
319
- const url = new URL(href, location.origin);
320
- // the page already on screen needs no warming
321
- if (url.pathname === location.pathname && url.search === location.search)
322
- return;
323
- const key = prefetchKey(url);
324
- const hit = prefetched.get(key);
325
- if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
326
- const pattern = findPattern(url.pathname);
327
- if (pattern) void resolveRoute(pattern).catch(() => {});
328
- const res = navigateFetch(url.pathname + url.search, "low");
329
- res.catch(() => prefetched.delete(key));
330
- prefetched.set(key, { res, at: Date.now() });
331
- }
332
-
333
- /** The held prefetch for `path` if it is still fresh; each is used once. */
334
- function takePrefetched(path: string): Promise<Response> | null {
335
- const key = prefetchKey(new URL(path, location.origin));
336
- const hit = prefetched.get(key);
337
- prefetched.delete(key);
338
- if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
339
- return hit.res;
340
- }
341
-
342
- /**
343
- * The server points `<link rel="stylesheet">` at `/style.<hash>.css`, but a
344
- * link the router renders after a navigation is built from the component's own
345
- * `/style.css`. Point it at the hashed URL too, so it hits the cached copy
346
- * instead of revalidating the plain one.
347
- */
348
- function setupStylesheetHashes(): void {
349
- const map = (globalThis as { __grimoire_css__?: Record<string, string> })
350
- .__grimoire_css__;
351
- if (!map || typeof MutationObserver === "undefined") return;
352
- const fix = (el: Element) => {
353
- if (!(el instanceof HTMLLinkElement) || el.rel !== "stylesheet") return;
354
- const hashed = map[el.getAttribute("href") ?? ""];
355
- if (hashed) el.setAttribute("href", hashed);
356
- };
357
- new MutationObserver((records) => {
358
- for (const r of records) {
359
- for (const node of r.addedNodes) {
360
- if (node.nodeType !== 1) continue;
361
- fix(node as Element);
362
- for (const l of (node as Element).querySelectorAll?.("link") ?? [])
363
- fix(l);
364
- }
365
- }
366
- }).observe(document.documentElement, { childList: true, subtree: true });
367
- }
368
-
369
- function setupPreload(): void {
370
- // Hover is a desktop signal; a short delay ignores cursors passing over.
371
- document.addEventListener("mouseover", (e) => {
372
- const a = (e.target as Element).closest("a");
373
- const href = prefetchHref(a);
374
- if (!a || !href) return;
375
- clearTimeout(preloadTimer);
376
- preloadTimer = setTimeout(() => {
377
- if (a.hasAttribute("data-sigil-preload-code")) {
378
- const link = document.createElement("link");
379
- link.rel = "prefetch";
380
- link.href = href;
381
- document.head.appendChild(link);
382
- }
383
- prefetch(href);
384
- }, 80);
385
- });
386
-
387
- document.addEventListener("mouseout", (e) => {
388
- const a = (e.target as Element).closest("a");
389
- if (!a) return;
390
- clearTimeout(preloadTimer);
391
- });
392
-
393
- // Touch has no hover, but a tap lands 100-300ms after the finger goes
394
- // down; start the request then.
395
- document.addEventListener(
396
- "touchstart",
397
- (e) => {
398
- const href = prefetchHref((e.target as Element).closest("a"));
399
- if (href) prefetch(href);
400
- },
401
- { passive: true },
402
- );
403
-
404
- // Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
405
- // into view, for navs whose next tap is predictable.
406
- if (typeof IntersectionObserver !== "undefined") {
407
- const io = new IntersectionObserver((entries) => {
408
- for (const entry of entries) {
409
- if (!entry.isIntersecting) continue;
410
- io.unobserve(entry.target);
411
- const href = prefetchHref(entry.target);
412
- if (href) prefetch(href);
413
- }
414
- });
415
- const observe = (root: ParentNode) => {
416
- for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
417
- io.observe(a);
418
- };
419
- observe(document);
420
- new MutationObserver((muts) => {
421
- for (const m of muts)
422
- for (const n of m.addedNodes)
423
- if (n instanceof Element) {
424
- if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
425
- observe(n);
426
- }
427
- }).observe(document.body, { childList: true, subtree: true });
428
- }
429
- }
430
-
431
- let lastState: {
432
- data: any;
433
- layoutData: any[];
434
- params: any;
435
- pattern: string;
436
- /** What the page's last failed action passed to fail(); cleared by navigation. */
437
- form?: unknown;
438
- } | null = null;
439
-
440
- function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
441
- const { data, layoutData, params, pattern, form } = state!;
442
- if (!Page) throw new Error(`no component for pattern ${pattern}`);
443
-
444
- const matchedLayouts = layoutList
445
- .filter(
446
- (l) =>
447
- l.path === "/" ||
448
- pattern === l.path ||
449
- pattern.startsWith(`${l.path}/`),
450
- )
451
- .sort((a, b) => a.path.length - b.path.length);
452
-
453
- let renderFn = () => {
454
- const pageNode = Page({ data, params, form });
455
- const pageDiv = document.createElement("div");
456
- pageDiv.id = "grimoire-page";
457
- pageDiv.appendChild(pageNode);
458
- return pageDiv;
459
- };
460
-
461
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
462
- const LayoutComponent = matchedLayouts[i].component;
463
- const innerRender = renderFn;
464
- const currentLayoutData = layoutData?.[i];
465
- renderFn = () => {
466
- const childNode = innerRender();
467
- return LayoutComponent({
468
- data: currentLayoutData,
469
- params,
470
- path: pattern,
471
- children: childNode,
472
- });
473
- };
474
- }
475
-
476
- return renderFn();
477
- }
478
-
479
- function matchClientPattern(pattern: string, pathname: string): boolean {
480
- // haha pp and ph
481
- const pp = pattern.split("/").filter(Boolean);
482
- const ph = pathname.split("/").filter(Boolean);
483
-
484
- // Depth-first walk; optional segments (:x?) try consuming one segment
485
- // before consuming zero, mirroring the server's matchPattern.
486
- function walk(pi: number, pj: number): boolean {
487
- if (pi === pp.length) return pj === ph.length;
488
- const part = pp[pi]!;
489
- if (part.startsWith("*")) return true;
490
- const optional = part.startsWith(":") && part.endsWith("?");
491
- if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
492
- if (!optional) {
493
- if (pj >= ph.length) return false;
494
- if (!part.startsWith(":") && part !== ph[pj]) return false;
495
- return walk(pi + 1, pj + 1);
496
- }
497
- return walk(pi + 1, pj);
498
- }
499
-
500
- return walk(0, 0);
501
- }
502
-
503
- // The one place the base is stripped. Everything else in the router handles
504
- // full browser paths (history, fetch, scroll keys, `__data.json`), and a path
505
- // outside the base matches no route, so the browser loads it as a page.
506
- function findPattern(pathname: string): string | null {
507
- const route = stripBase(pathname);
508
- if (route === null) return null;
509
- for (const pattern of Object.keys(routeMap)) {
510
- if (matchClientPattern(pattern, route)) return pattern;
511
- }
512
- return null;
513
- }
514
-
515
- /** The URL as routes and loads see it: the same on the server, which strips the base from the request. */
516
- function routeUrl(url: URL): URL {
517
- const route = new URL(url);
518
- route.pathname = stripBase(url.pathname) ?? url.pathname;
519
- return route;
520
- }
521
-
522
- export interface NavigateOptions {
523
- /** "push" (default) adds a history entry, "replace" swaps the current one,
524
- * "none" leaves history untouched (popstate — the browser already moved). */
525
- history?: "push" | "replace" | "none";
526
- }
527
-
528
- // monotonically increasing id — a navigation aborts silently the moment a
529
- // newer one starts, so overlapping navigations can't commit stale responses
530
- let navigationId = 0;
531
-
532
- export async function navigate(
533
- path: string,
534
- opts: NavigateOptions | boolean = {},
535
- ) {
536
- // boolean back-compat: navigate(path, true) meant "replace"
537
- const historyMode =
538
- typeof opts === "boolean"
539
- ? opts
540
- ? "replace"
541
- : "push"
542
- : (opts.history ?? "push");
543
- const navId = ++navigationId;
544
- const url = new URL(path, location.origin);
545
- const seen = routeUrl(url);
546
- if (
547
- base &&
548
- url.origin === location.origin &&
549
- stripBase(url.pathname) === null
550
- ) {
551
- console.warn(
552
- `[grimoire] navigate("${path}") is outside the base "${base}", so it loads as a new page and the server will not find it. Write navigate(withBase("${url.pathname}")).`,
553
- );
554
- }
555
-
556
- if (beforeNavigateCb) {
557
- const shouldProceed = beforeNavigateCb(seen);
558
- if (shouldProceed === false) return;
559
- }
560
- onNavigateCb?.(seen);
561
- saveScrollPosition();
562
- // read before the loading placeholder below collapses the page and the
563
- // browser clamps scrollY; a same-path refetch restores this value
564
- const startY = window.scrollY;
565
-
566
- // load the loading immediately
567
- const destPattern = findPattern(url.pathname);
568
- const DestPage = destPattern ? await resolveRoute(destPattern) : null;
569
- if (navId !== navigationId) return;
570
- if (DestPage?.loading) {
571
- disposeCurrentPage?.();
572
- disposeCurrentPage = null;
573
- pushHydrationNodes([]);
574
- let loadingNode: any;
575
- let flush = () => {};
576
- disposeCurrentPage = withEffectScope(() => {
577
- ({ value: loadingNode, flush } = collectEffects(() =>
578
- (DestPage as any).loading(),
579
- ));
580
- });
581
- popHydrationNodes();
582
- // replace only grimoire-page, keeps layout stable during transition
583
- const pageEl = document.getElementById("grimoire-page");
584
- if (pageEl) pageEl.replaceChildren(loadingNode);
585
- else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
586
- flush();
587
- }
588
-
589
- let res: Response;
590
- try {
591
- res = await (takePrefetched(path) ?? navigateFetch(path));
592
- } catch {
593
- // a failed prefetch must not fail the click
594
- res = await navigateFetch(path);
595
- }
596
- if (navId !== navigationId) return;
597
- const contentType = res.headers.get("content-type") ?? "";
598
- if (!contentType.includes("application/json")) {
599
- window.location.href = path;
600
- return;
601
- }
602
- const json = await res.json();
603
- if (navId !== navigationId) return;
604
- const { data, layoutData, params, pattern, head, deps } = json;
605
- const Page = await resolveRoute(pattern);
606
- if (navId !== navigationId) return;
607
- if (!Page) {
608
- window.location.href = path;
609
- return;
610
- }
611
-
612
- let mergedData = data;
613
- if (Page.load) {
614
- try {
615
- startCollecting();
616
- const clientData = await Page.load({
617
- params,
618
- url: seen,
619
- request: new Request(seen),
620
- // layout loads run server-side; their data arrives in layoutData —
621
- // parent() merges it outermost-first, mirroring the server context
622
- parent: async () =>
623
- Object.assign(
624
- {},
625
- ...(Array.isArray(layoutData) ? layoutData : []).filter(
626
- (d) => d && typeof d === "object",
627
- ),
628
- ),
629
- });
630
- // merge server-collected keys (page/layout server loads) with
631
- // whatever this client-side load itself registered
632
- setDeps(pattern, [
633
- ...(Array.isArray(deps) ? deps : []),
634
- ...stopCollecting(),
635
- ]);
636
- mergedData = { ...clientData, ...data };
637
- } catch (e: unknown) {
638
- stopCollecting();
639
- if (e && typeof e === "object" && "location" in e) {
640
- window.location.href = String((e as { location: unknown }).location);
641
- return;
642
- }
643
- console.error("[grimoire] universal load error:", e);
644
- }
645
- if (navId !== navigationId) return;
646
- } else if (Array.isArray(deps)) {
647
- // no client-side load to run — the server's collected depends() keys
648
- // (from +page.server.ts / +layout.server.ts) are the whole story
649
- setDeps(pattern, deps);
650
- }
651
-
652
- // track state for HMR rerender
653
- lastState = { data: mergedData, layoutData, params, pattern };
654
- (globalThis as any).__grimoire_current_pattern__ = pattern;
655
-
656
- disposeCurrentPage?.();
657
- disposeCurrentPage = null;
658
- pushHydrationNodes([]);
659
- let rootNode: any;
660
- // the page's effects (and use: directives) run once it is in the document
661
- let flushEffects = () => {};
662
- disposeCurrentPage = withEffectScope(() => {
663
- try {
664
- ({ value: rootNode, flush: flushEffects } = collectEffects(() =>
665
- buildRouteTree(lastState!, Page),
666
- ));
667
- } catch (e) {
668
- console.error(e);
669
- }
670
- });
671
- popHydrationNodes();
672
-
673
- updateHead(head);
674
- // isRefetch is read before currentPath moves, and captured, because
675
- // applyScroll may run after this function has returned.
676
- const isRefetch = url.pathname === currentPath;
677
-
678
- // Scroll has to be decided in the same frame the content lands. Running it
679
- // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
680
- // same-page anchor was already present and worked, while an anchor on the
681
- // incoming page did not exist yet and fell through to scrollToTop().
682
- const applyScroll = () => {
683
- if (url.hash) {
684
- const target = document.getElementById(url.hash.slice(1));
685
- if (!target) {
686
- scrollToTop();
687
- return;
688
- }
689
- target.scrollIntoView();
690
- // re-assert after layout settles (late effects/images can shift content)
691
- requestAnimationFrame(() => target.scrollIntoView());
692
- return;
693
- }
694
- if (historyMode === "none") {
695
- // popstate: the browser already moved through history — restore what
696
- // we saved for this path (back/forward semantics)
697
- restoreScrollPosition(url.pathname);
698
- return;
699
- }
700
- // fresh navigation starts at the top; a same-path replace
701
- // (invalidate/refetch) keeps the scroll it started with
702
- if (!isRefetch) {
703
- scrollToTop();
704
- return;
705
- }
706
- window.scrollTo(0, startY);
707
- requestAnimationFrame(() => window.scrollTo(0, startY));
708
- };
709
-
710
- // View transitions: animate the swap when the browser supports it and the
711
- // user hasn't asked for reduced motion. The callback must stay synchronous.
712
- const preserved = capturePreservedScroll();
713
- const doc = document as Document & {
714
- startViewTransition?: (
715
- cb: () => void,
716
- ) => { finished?: Promise<unknown>; ready?: Promise<unknown> } | undefined;
717
- };
718
- const animate =
719
- typeof doc.startViewTransition === "function" &&
720
- !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
721
- // elements the old and new page share by key morph into each other
722
- const shared = animate ? sharedTransitionKeys(rootNode) : [];
723
- const named: Element[] = [];
724
- const name = (el: Element, key: string) => {
725
- (el as HTMLElement).style.setProperty("view-transition-name", key);
726
- named.push(el);
727
- };
728
- const doSwap = () => {
729
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
730
- flushEffects();
731
- for (const [key, , next] of shared) name(next, key);
732
- restorePreservedScroll(preserved);
733
- applyScroll();
734
- };
735
- if (animate) {
736
- // the browser snapshots the old page as startViewTransition is called
737
- for (const [key, prev] of shared) name(prev, key);
738
- const transition = doc.startViewTransition?.(doSwap);
739
- const clear = () => {
740
- for (const el of named)
741
- (el as HTMLElement).style.removeProperty("view-transition-name");
742
- };
743
- Promise.resolve(transition?.finished).then(clear, clear);
744
- // a skipped transition (another navigation, a hidden tab) rejects
745
- // ready; the swap still runs, so it is not an error worth reporting
746
- transition?.ready?.catch(() => {});
747
- } else {
748
- doSwap();
749
- }
750
- currentPath = url.pathname;
751
- currentSearch = url.search;
752
-
753
- if (historyMode !== "none") {
754
- history[historyMode === "replace" ? "replaceState" : "pushState"](
755
- null,
756
- "",
757
- path,
758
- );
759
- }
760
- afterNavigateCb?.(seen);
761
- }
762
-
763
- export interface RouterExtensions {
764
- /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
765
- matchers?: Record<string, (value: string) => boolean>;
766
- /** Server-collected depends() keys per route pattern (from SSR state). */
767
- deps?: Record<string, string[]>;
768
- }
769
-
770
- let paramMatcherFns: Record<string, (value: string) => boolean> = {};
771
-
772
- export function initRouter(
773
- routes: Record<string, RouteEntry>,
774
- layouts: any[] = [],
775
- initialDispose?: () => void,
776
- ext?: RouterExtensions,
777
- ) {
778
- paramMatcherFns = ext?.matchers ?? {};
779
- routeMap = routes;
780
- layoutList = layouts;
781
- prefetched.clear();
782
- disposeCurrentPage = initialDispose ?? null;
783
- currentPath = location.pathname;
784
- currentSearch = location.search;
785
-
786
- // the app owns scroll: the browser's automatic restoration fires after
787
- // the router's own scroll and clobbers scroll-to-top / saved positions
788
- if ("scrollRestoration" in history) history.scrollRestoration = "manual";
789
- // dev HMR surface: available even without SSR state so the client can tell
790
- // a missing router apart from a missing initial payload
791
- const globals = globalThis as unknown as {
792
- __grimoire_current_pattern__?: string;
793
- __grimoire_routes__?: Record<string, RouteEntry>;
794
- __grimoire_rerender__?: () => Promise<void>;
795
- __grimoire_navigate__?: (path: string, replace?: boolean) => void;
796
- __grimoire_form__?: (form: unknown) => Promise<void>;
797
- __grimoire_hmr__?: HmrControl;
798
- };
799
- globals.__grimoire_routes__ = routeMap;
800
- globals.__grimoire_rerender__ = hmrRerender;
801
- globals.__grimoire_hmr__ = hmrControl;
802
- globals.__grimoire_form__ = showActionFailure;
803
- globals.__grimoire_navigate__ = (path, replace) =>
804
- navigate(path, replace ?? false);
805
-
806
- // initial HMR state from SSR
807
- const stateEl = document.getElementById("__grimoire_state__");
808
- if (stateEl) {
809
- const state = JSON.parse(stateEl.textContent!);
810
- lastState = {
811
- data: state.data,
812
- layoutData: state.layoutData,
813
- params: state.params,
814
- pattern: state.pattern,
815
- form: state.form,
816
- };
817
- if (Array.isArray(state.deps)) {
818
- setDeps(state.pattern, state.deps);
819
- }
820
- globals.__grimoire_current_pattern__ = state.pattern;
821
- }
822
-
823
- saveScrollPosition();
824
- document.addEventListener("click", handleClick);
825
- // forms rendered client-side have no SSR-injected _csrf input
826
- document.addEventListener("submit", onSubmitEnsureCsrf, true);
827
- window.addEventListener("popstate", () => {
828
- if (
829
- location.pathname === currentPath &&
830
- location.search === currentSearch
831
- ) {
832
- return;
833
- }
834
- // the browser already moved through history — render only, never
835
- // push/replace here or the forward stack gets clobbered.
836
- // The search has to come along: refetching the bare pathname served
837
- // unfiltered data while the address bar still showed the query.
838
- // The hash deliberately does not, so back/forward restores the saved
839
- // scroll offset instead of re-jumping to the anchor, matching the
840
- // browser's own behaviour for document history navigation.
841
- navigate(location.pathname + location.search, { history: "none" });
842
- });
843
- setupPreload();
844
- setupStylesheetHashes();
845
- }
846
-
847
- /**
848
- * Swap the page's <head> tags for the incoming page's. Server-rendered tags
849
- * sit between `<!--grimoire-head-->` markers; tags added by an earlier
850
- * navigation carry `data-grimoire-head`. Both are replaced, so the first
851
- * navigation doesn't leave the server-rendered description or icon behind
852
- * next to the new ones. With no incoming <title>, the current title stays.
853
- */
854
- function updateHead(headHtml: string) {
855
- const prevTitle = document.title;
856
- const markers = Array.from(document.head.childNodes).filter(
857
- (n): n is Comment => n.nodeType === Node.COMMENT_NODE,
858
- );
859
- const start = markers.find((c) => c.data === "grimoire-head");
860
- const end = markers.find((c) => c.data === "/grimoire-head");
861
- if (start && end) {
862
- while (start.nextSibling && start.nextSibling !== end) {
863
- start.nextSibling.remove();
864
- }
865
- }
866
- document
867
- .querySelectorAll("[data-grimoire-head]")
868
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
869
- .forEach((el) => el.remove());
870
- const parsed = headHtml
871
- ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
872
- : null;
873
- const incomingTitle = parsed?.querySelector("title");
874
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
875
- document.querySelectorAll("title").forEach((el) => el.remove());
876
- document.title = incomingTitle?.textContent ?? prevTitle;
877
- if (parsed) {
878
- for (const el of Array.from(parsed.head.children)) {
879
- if (el.tagName === "TITLE") continue;
880
- (el as HTMLElement).dataset.grimoireHead = "1";
881
- if (end) document.head.insertBefore(el, end);
882
- else document.head.appendChild(el);
883
- }
884
- }
885
- }
886
-
887
- function handleClick(e: MouseEvent) {
888
- // let the browser handle modified clicks (new tab/window/download)
889
- if (e.defaultPrevented || e.button !== 0) return;
890
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
891
- const a = (e.target as Element).closest("a");
892
- if (!a) return;
893
- if (a.target && a.target !== "_self") return;
894
- if (a.hasAttribute("download")) return;
895
- if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
896
- const href = a.getAttribute("href");
897
- if (!href) return;
898
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
899
- // Only intercept clicks for known page routes — let server routes
900
- // (redirects, API endpoints, etc.) navigate normally so the browser
901
- // follows the response without the extra fetch-then-redirect dance.
902
- try {
903
- const url = new URL(href, location.origin);
904
- if (!findPattern(url.pathname)) return;
905
- // same-page anchor: native behavior scrolls to it, no re-render needed
906
- if (url.pathname === location.pathname && url.hash) return;
907
- } catch {
908
- return;
909
- }
910
- e.preventDefault();
911
- // a pending hover prefetch would re-request what this click just consumed
912
- clearTimeout(preloadTimer);
913
- navigate(href);
914
- }
1
+ import {
2
+ collectEffects,
3
+ popHydrationNodes,
4
+ pushHydrationNodes,
5
+ __component,
6
+ } from "@sigil-dev/runtime";
7
+ import { base, stripBase } from "../base";
8
+ import { onSubmitEnsureCsrf } from "./csrf.ts";
9
+ import {
10
+ clearDeps,
11
+ depends,
12
+ getDeps,
13
+ setDeps,
14
+ startCollecting,
15
+ stopCollecting,
16
+ } from "./deps";
17
+ import { withEffectScope } from "./scope";
18
+
19
+ // re-exported for app code that imports depends() from the router module
20
+ export { depends };
21
+
22
+ async function refetchCurrent(): Promise<void> {
23
+ if (!lastState) return;
24
+ // a refetch exists because the data changed; never serve it from a prefetch
25
+ prefetched.clear();
26
+ await navigate(location.pathname, { history: "replace" });
27
+ }
28
+
29
+ export async function invalidate(...keys: string[]): Promise<void> {
30
+ const current = lastState?.pattern;
31
+ if (!current) return;
32
+ const deps = getDeps(current);
33
+ // no recorded deps → conservative refetch; otherwise only on intersection
34
+ if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
35
+ await refetchCurrent();
36
+ }
37
+ }
38
+
39
+ export async function invalidateAll(): Promise<void> {
40
+ await refetchCurrent();
41
+ }
42
+
43
+ type PageComponent = ((props: any) => any) & {
44
+ load?: (ctx: any) => Promise<any>;
45
+ loading?: () => any;
46
+ error?: (props: { error: unknown }) => any;
47
+ };
48
+ /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
49
+ * component functions are also accepted (tests, HMR replacements). */
50
+ type RouteEntry =
51
+ | PageComponent
52
+ | { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
53
+
54
+ let routeMap: Record<string, RouteEntry> = {};
55
+ const resolvedRoutes: Record<string, PageComponent> = {};
56
+
57
+ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
58
+ const entry = routeMap[pattern];
59
+ if (!entry) return null;
60
+ // plain function: eager component or an HMR hot-swap — always wins over cache
61
+ if (typeof entry === "function") return entry;
62
+ if (!resolvedRoutes[pattern]) {
63
+ const mod = (await entry.__lazy()) as {
64
+ default: PageComponent;
65
+ loading?: PageComponent["loading"];
66
+ };
67
+ // `loading` is a named export of the page module; navigation looks
68
+ // for it on the component, and never saw it before
69
+ if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
70
+ resolvedRoutes[pattern] = mod.default;
71
+ }
72
+ return resolvedRoutes[pattern];
73
+ }
74
+ let layoutList: { path: string; component: (props: any) => any }[] = [];
75
+ let disposeCurrentPage: (() => void) | null = null;
76
+ // Scroll keys and same-page refetch detection are pathname-only on purpose.
77
+ // currentSearch is tracked alongside so popstate can tell "?page=2" apart
78
+ // from "?page=1" without polluting either of those.
79
+ let currentPath = location.pathname;
80
+ let currentSearch = location.search;
81
+
82
+ // C1: Navigation hooks
83
+ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
84
+ let onNavigateCb: ((url: URL) => void) | null = null;
85
+ let afterNavigateCb: ((url: URL) => void) | null = null;
86
+
87
+ /**
88
+ * Shows the page again with an enhanced form's failure as its `form` prop,
89
+ * which is what a submission without JavaScript gets from the server. The
90
+ * same page code then works either way.
91
+ */
92
+ export function showActionFailure(form: unknown): Promise<void> {
93
+ if (!lastState) return Promise.resolve();
94
+ lastState = { ...lastState, form };
95
+ return hmrRerender();
96
+ }
97
+
98
+ export async function hmrRerender(): Promise<void> {
99
+ if (!lastState) {
100
+ location.reload();
101
+ return;
102
+ }
103
+ const Page = await resolveRoute(lastState.pattern);
104
+ if (!Page) {
105
+ location.reload();
106
+ return;
107
+ }
108
+ disposeCurrentPage?.();
109
+ pushHydrationNodes([]);
110
+ let rootNode: any;
111
+ let flush = () => {};
112
+ disposeCurrentPage = withEffectScope(() => {
113
+ ({ value: rootNode, flush } = collectEffects(() =>
114
+ buildRouteTree(lastState!, Page),
115
+ ));
116
+ });
117
+ popHydrationNodes();
118
+ const preserved = capturePreservedScroll();
119
+ // swapping the root can shrink the document for a moment, and the browser
120
+ // clamps scrollY to the shorter height; put the page back where it was
121
+ const y = window.scrollY;
122
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
123
+ flush();
124
+ restorePreservedScroll(preserved);
125
+ window.scrollTo(0, y);
126
+ requestAnimationFrame(() => window.scrollTo(0, y));
127
+ }
128
+
129
+ /**
130
+ * Dev-only surface the HMR client drives. Route entries are replaced rather
131
+ * than mutated in place so a swapped module also wins for later navigations,
132
+ * and the resolved-module cache is dropped with them.
133
+ */
134
+ export interface HmrControl {
135
+ setRoute(pattern: string, entry: RouteEntry): void;
136
+ setLayout(path: string, component: (props: any) => any): void;
137
+ rerender(): Promise<void>;
138
+ }
139
+
140
+ const hmrControl: HmrControl = {
141
+ setRoute(pattern, entry) {
142
+ routeMap[pattern] = entry;
143
+ delete resolvedRoutes[pattern];
144
+ },
145
+ setLayout(path: string, component: (props: any) => any) {
146
+ const existing = layoutList.find((l) => l.path === path);
147
+ if (existing) existing.component = component;
148
+ else layoutList.push({ path, component });
149
+ },
150
+ rerender: hmrRerender,
151
+ };
152
+
153
+ export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
154
+ beforeNavigateCb = cb;
155
+ }
156
+
157
+ export function onNavigate(cb: (url: URL) => void): void {
158
+ onNavigateCb = cb;
159
+ }
160
+
161
+ export function afterNavigate(cb: (url: URL) => void): void {
162
+ afterNavigateCb = cb;
163
+ }
164
+
165
+ // C2: Scroll restoration
166
+ const scrollPositions = new Map<string, number>();
167
+
168
+ function saveScrollPosition(): void {
169
+ scrollPositions.set(currentPath, window.scrollY);
170
+ }
171
+
172
+ function restoreScrollPosition(path: string): void {
173
+ const y = scrollPositions.get(path) ?? 0;
174
+ window.scrollTo(0, y);
175
+ // re-assert after layout settles (late effects/images can shift content)
176
+ requestAnimationFrame(() => window.scrollTo(0, y));
177
+ }
178
+
179
+ function scrollToTop(): void {
180
+ window.scrollTo(0, 0);
181
+ requestAnimationFrame(() => window.scrollTo(0, 0));
182
+ }
183
+
184
+ // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
185
+ // across the root swap: the router rebuilds the whole tree on navigation, so a
186
+ // long independently-scrollable sidebar would otherwise snap back to the top.
187
+ // The attribute value is the matching key; elements without one fall back to
188
+ // their id, then to their ordinal position.
189
+ const PRESERVE_ATTR = "data-sigil-scroll-preserve";
190
+
191
+ function preserveKey(el: Element, ordinal: number): string {
192
+ return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
193
+ }
194
+
195
+ function capturePreservedScroll(): Map<string, number> {
196
+ const positions = new Map<string, number>();
197
+ let ordinal = 0;
198
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
199
+ positions.set(preserveKey(el, ordinal), el.scrollTop);
200
+ ordinal++;
201
+ }
202
+ return positions;
203
+ }
204
+
205
+ function restorePreservedScroll(positions: Map<string, number>): void {
206
+ if (positions.size === 0) return;
207
+ let ordinal = 0;
208
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
209
+ const top = positions.get(preserveKey(el, ordinal));
210
+ if (top !== undefined) el.scrollTop = top;
211
+ ordinal++;
212
+ }
213
+ }
214
+
215
+ const TRANSITION_ATTR = "data-sigil-transition";
216
+
217
+ /** key → the one element carrying it; keys that appear twice are dropped,
218
+ * because a duplicate view-transition-name cancels the whole transition. */
219
+ function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
220
+ const seen = new Map<string, Element>();
221
+ const dup = new Set<string>();
222
+ for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
223
+ const key = el.getAttribute(TRANSITION_ATTR);
224
+ if (!key) continue;
225
+ if (seen.has(key)) dup.add(key);
226
+ else seen.set(key, el);
227
+ }
228
+ for (const key of dup) seen.delete(key);
229
+ return seen;
230
+ }
231
+
232
+ /** [key, element on the current page, element on the incoming page] */
233
+ function sharedTransitionKeys(
234
+ incoming: unknown,
235
+ ): Array<[string, Element, Element]> {
236
+ const root = incoming as Partial<ParentNode> | null;
237
+ if (!root || typeof root.querySelectorAll !== "function") return [];
238
+ const next = uniqueTransitionEls(root as ParentNode);
239
+ if (next.size === 0) return [];
240
+ const prev = uniqueTransitionEls(document);
241
+ const both: Array<[string, Element, Element]> = [];
242
+ for (const [key, el] of next) {
243
+ const old = prev.get(key);
244
+ if (old) both.push([key, old, el]);
245
+ }
246
+ return both;
247
+ }
248
+
249
+ // C3: Preloading
250
+ //
251
+ // A prefetch keeps its in-flight Response here and navigate() consumes it.
252
+ // The HTTP cache cannot do this job: the navigate JSON carries no freshness
253
+ // headers and pages are commonly served `no-cache`, so a plain prefetch
254
+ // warmed nothing the click could reuse.
255
+ let preloadTimer: Timer | null = null;
256
+ const PREFETCH_TTL_MS = 15_000;
257
+ const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
258
+
259
+ /**
260
+ * A held response is only valid for the cookies it was requested with: apps
261
+ * keep preferences (a language, a region, a theme) in cookies the server reads
262
+ * per request, so a page fetched before the visitor changed one is wrong
263
+ * after. Cookies the script can read are part of the key.
264
+ */
265
+ function prefetchKey(url: URL): string {
266
+ return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
267
+ }
268
+
269
+ /**
270
+ * A prerendered site has no server to answer `x-grimoire-navigate`, so
271
+ * `adapterStatic` marks its pages and writes the same payload to
272
+ * `<page>/__data.json`, which any static host serves. The path must match
273
+ * `dataFileFor` in server/prerender.ts.
274
+ */
275
+ function navigateTarget(path: string): string {
276
+ if (
277
+ (globalThis as { __grimoire_static__?: unknown }).__grimoire_static__ !== 1
278
+ ) {
279
+ return path;
280
+ }
281
+ const { pathname } = new URL(path, location.origin);
282
+ return `${pathname.replace(/\/+$/, "")}/__data.json`;
283
+ }
284
+
285
+ function navigateFetch(path: string, priority?: "low"): Promise<Response> {
286
+ const target = navigateTarget(path);
287
+ return fetch(target, {
288
+ ...(target === path ? { headers: { "x-grimoire-navigate": "1" } } : {}),
289
+ redirect: "manual",
290
+ ...(priority ? { priority } : {}),
291
+ });
292
+ }
293
+
294
+ /** The route-local href of an anchor worth prefetching, or null. */
295
+ function prefetchHref(a: Element | null): string | null {
296
+ if (!a) return null;
297
+ const href = a.getAttribute("href");
298
+ if (!href) return null;
299
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
300
+ if (a.getAttribute("data-sigil-preload") === "off") return null;
301
+ // Only links that resolve to a known client route — external pages and
302
+ // non-page endpoints (API routes, redirects) are skipped.
303
+ try {
304
+ const url = new URL(href, location.origin);
305
+ if (!findPattern(url.pathname)) return null;
306
+ } catch {
307
+ return null;
308
+ }
309
+ return href;
310
+ }
311
+
312
+ /**
313
+ * Warm a navigation: load the route's code and start its data request. The
314
+ * response is held for a short while so the click that follows reuses it.
315
+ */
316
+ export function prefetch(href: string): void {
317
+ const conn = (navigator as { connection?: { saveData?: boolean } })
318
+ .connection;
319
+ if (conn?.saveData) return;
320
+ const url = new URL(href, location.origin);
321
+ // the page already on screen needs no warming
322
+ if (url.pathname === location.pathname && url.search === location.search)
323
+ return;
324
+ const key = prefetchKey(url);
325
+ const hit = prefetched.get(key);
326
+ if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
327
+ const pattern = findPattern(url.pathname);
328
+ if (pattern) void resolveRoute(pattern).catch(() => {});
329
+ const res = navigateFetch(url.pathname + url.search, "low");
330
+ res.catch(() => prefetched.delete(key));
331
+ prefetched.set(key, { res, at: Date.now() });
332
+ }
333
+
334
+ /** The held prefetch for `path` if it is still fresh; each is used once. */
335
+ function takePrefetched(path: string): Promise<Response> | null {
336
+ const key = prefetchKey(new URL(path, location.origin));
337
+ const hit = prefetched.get(key);
338
+ prefetched.delete(key);
339
+ if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
340
+ return hit.res;
341
+ }
342
+
343
+ /**
344
+ * The server points `<link rel="stylesheet">` at `/style.<hash>.css`, but a
345
+ * link the router renders after a navigation is built from the component's own
346
+ * `/style.css`. Point it at the hashed URL too, so it hits the cached copy
347
+ * instead of revalidating the plain one.
348
+ */
349
+ function setupStylesheetHashes(): void {
350
+ const map = (globalThis as { __grimoire_css__?: Record<string, string> })
351
+ .__grimoire_css__;
352
+ if (!map || typeof MutationObserver === "undefined") return;
353
+ const fix = (el: Element) => {
354
+ if (!(el instanceof HTMLLinkElement) || el.rel !== "stylesheet") return;
355
+ const hashed = map[el.getAttribute("href") ?? ""];
356
+ if (hashed) el.setAttribute("href", hashed);
357
+ };
358
+ new MutationObserver((records) => {
359
+ for (const r of records) {
360
+ for (const node of r.addedNodes) {
361
+ if (node.nodeType !== 1) continue;
362
+ fix(node as Element);
363
+ for (const l of (node as Element).querySelectorAll?.("link") ?? [])
364
+ fix(l);
365
+ }
366
+ }
367
+ }).observe(document.documentElement, { childList: true, subtree: true });
368
+ }
369
+
370
+ function setupPreload(): void {
371
+ // Hover is a desktop signal; a short delay ignores cursors passing over.
372
+ document.addEventListener("mouseover", (e) => {
373
+ const a = (e.target as Element).closest("a");
374
+ const href = prefetchHref(a);
375
+ if (!a || !href) return;
376
+ clearTimeout(preloadTimer);
377
+ preloadTimer = setTimeout(() => {
378
+ if (a.hasAttribute("data-sigil-preload-code")) {
379
+ const link = document.createElement("link");
380
+ link.rel = "prefetch";
381
+ link.href = href;
382
+ document.head.appendChild(link);
383
+ }
384
+ prefetch(href);
385
+ }, 80);
386
+ });
387
+
388
+ document.addEventListener("mouseout", (e) => {
389
+ const a = (e.target as Element).closest("a");
390
+ if (!a) return;
391
+ clearTimeout(preloadTimer);
392
+ });
393
+
394
+ // Touch has no hover, but a tap lands 100-300ms after the finger goes
395
+ // down; start the request then.
396
+ document.addEventListener(
397
+ "touchstart",
398
+ (e) => {
399
+ const href = prefetchHref((e.target as Element).closest("a"));
400
+ if (href) prefetch(href);
401
+ },
402
+ { passive: true },
403
+ );
404
+
405
+ // Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
406
+ // into view, for navs whose next tap is predictable.
407
+ if (typeof IntersectionObserver !== "undefined") {
408
+ const io = new IntersectionObserver((entries) => {
409
+ for (const entry of entries) {
410
+ if (!entry.isIntersecting) continue;
411
+ io.unobserve(entry.target);
412
+ const href = prefetchHref(entry.target);
413
+ if (href) prefetch(href);
414
+ }
415
+ });
416
+ const observe = (root: ParentNode) => {
417
+ for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
418
+ io.observe(a);
419
+ };
420
+ observe(document);
421
+ new MutationObserver((muts) => {
422
+ for (const m of muts)
423
+ for (const n of m.addedNodes)
424
+ if (n instanceof Element) {
425
+ if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
426
+ observe(n);
427
+ }
428
+ }).observe(document.body, { childList: true, subtree: true });
429
+ }
430
+ }
431
+
432
+ let lastState: {
433
+ data: any;
434
+ layoutData: any[];
435
+ params: any;
436
+ pattern: string;
437
+ /** What the page's last failed action passed to fail(); cleared by navigation. */
438
+ form?: unknown;
439
+ } | null = null;
440
+
441
+ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
442
+ const { data, layoutData, params, pattern, form } = state!;
443
+ if (!Page) throw new Error(`no component for pattern ${pattern}`);
444
+
445
+ const matchedLayouts = layoutList
446
+ .filter(
447
+ (l) =>
448
+ l.path === "/" ||
449
+ pattern === l.path ||
450
+ pattern.startsWith(`${l.path}/`),
451
+ )
452
+ .sort((a, b) => a.path.length - b.path.length);
453
+
454
+ let renderFn = () => {
455
+ const pageNode = __component(Page, { data, params, form });
456
+ const pageDiv = document.createElement("div");
457
+ pageDiv.id = "grimoire-page";
458
+ pageDiv.appendChild(pageNode);
459
+ return pageDiv;
460
+ };
461
+
462
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
463
+ const LayoutComponent = matchedLayouts[i].component;
464
+ const innerRender = renderFn;
465
+ const currentLayoutData = layoutData?.[i];
466
+ renderFn = () => {
467
+ const childNode = innerRender();
468
+ return __component(LayoutComponent, {
469
+ data: currentLayoutData,
470
+ params,
471
+ path: pattern,
472
+ children: childNode,
473
+ });
474
+ };
475
+ }
476
+
477
+ return renderFn();
478
+ }
479
+
480
+ function matchClientPattern(pattern: string, pathname: string): boolean {
481
+ // haha pp and ph
482
+ const pp = pattern.split("/").filter(Boolean);
483
+ const ph = pathname.split("/").filter(Boolean);
484
+
485
+ // Depth-first walk; optional segments (:x?) try consuming one segment
486
+ // before consuming zero, mirroring the server's matchPattern.
487
+ function walk(pi: number, pj: number): boolean {
488
+ if (pi === pp.length) return pj === ph.length;
489
+ const part = pp[pi]!;
490
+ if (part.startsWith("*")) return true;
491
+ const optional = part.startsWith(":") && part.endsWith("?");
492
+ if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
493
+ if (!optional) {
494
+ if (pj >= ph.length) return false;
495
+ if (!part.startsWith(":") && part !== ph[pj]) return false;
496
+ return walk(pi + 1, pj + 1);
497
+ }
498
+ return walk(pi + 1, pj);
499
+ }
500
+
501
+ return walk(0, 0);
502
+ }
503
+
504
+ // The one place the base is stripped. Everything else in the router handles
505
+ // full browser paths (history, fetch, scroll keys, `__data.json`), and a path
506
+ // outside the base matches no route, so the browser loads it as a page.
507
+ function findPattern(pathname: string): string | null {
508
+ const route = stripBase(pathname);
509
+ if (route === null) return null;
510
+ for (const pattern of Object.keys(routeMap)) {
511
+ if (matchClientPattern(pattern, route)) return pattern;
512
+ }
513
+ return null;
514
+ }
515
+
516
+ /** The URL as routes and loads see it: the same on the server, which strips the base from the request. */
517
+ function routeUrl(url: URL): URL {
518
+ const route = new URL(url);
519
+ route.pathname = stripBase(url.pathname) ?? url.pathname;
520
+ return route;
521
+ }
522
+
523
+ export interface NavigateOptions {
524
+ /** "push" (default) adds a history entry, "replace" swaps the current one,
525
+ * "none" leaves history untouched (popstate — the browser already moved). */
526
+ history?: "push" | "replace" | "none";
527
+ }
528
+
529
+ // monotonically increasing id — a navigation aborts silently the moment a
530
+ // newer one starts, so overlapping navigations can't commit stale responses
531
+ let navigationId = 0;
532
+
533
+ export async function navigate(
534
+ path: string,
535
+ opts: NavigateOptions | boolean = {},
536
+ ) {
537
+ // boolean back-compat: navigate(path, true) meant "replace"
538
+ const historyMode =
539
+ typeof opts === "boolean"
540
+ ? opts
541
+ ? "replace"
542
+ : "push"
543
+ : (opts.history ?? "push");
544
+ const navId = ++navigationId;
545
+ const url = new URL(path, location.origin);
546
+ const seen = routeUrl(url);
547
+ if (
548
+ base &&
549
+ url.origin === location.origin &&
550
+ stripBase(url.pathname) === null
551
+ ) {
552
+ console.warn(
553
+ `[grimoire] navigate("${path}") is outside the base "${base}", so it loads as a new page and the server will not find it. Write navigate(withBase("${url.pathname}")).`,
554
+ );
555
+ }
556
+
557
+ if (beforeNavigateCb) {
558
+ const shouldProceed = beforeNavigateCb(seen);
559
+ if (shouldProceed === false) return;
560
+ }
561
+ onNavigateCb?.(seen);
562
+ saveScrollPosition();
563
+ // read before the loading placeholder below collapses the page and the
564
+ // browser clamps scrollY; a same-path refetch restores this value
565
+ const startY = window.scrollY;
566
+
567
+ // load the loading immediately
568
+ const destPattern = findPattern(url.pathname);
569
+ const DestPage = destPattern ? await resolveRoute(destPattern) : null;
570
+ if (navId !== navigationId) return;
571
+ if (DestPage?.loading) {
572
+ disposeCurrentPage?.();
573
+ disposeCurrentPage = null;
574
+ pushHydrationNodes([]);
575
+ let loadingNode: any;
576
+ let flush = () => {};
577
+ disposeCurrentPage = withEffectScope(() => {
578
+ ({ value: loadingNode, flush } = collectEffects(() =>
579
+ (DestPage as any).loading(),
580
+ ));
581
+ });
582
+ popHydrationNodes();
583
+ // replace only grimoire-page, keeps layout stable during transition
584
+ const pageEl = document.getElementById("grimoire-page");
585
+ if (pageEl) pageEl.replaceChildren(loadingNode);
586
+ else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
587
+ flush();
588
+ }
589
+
590
+ let res: Response;
591
+ try {
592
+ res = await (takePrefetched(path) ?? navigateFetch(path));
593
+ } catch {
594
+ // a failed prefetch must not fail the click
595
+ res = await navigateFetch(path);
596
+ }
597
+ if (navId !== navigationId) return;
598
+ const contentType = res.headers.get("content-type") ?? "";
599
+ if (!contentType.includes("application/json")) {
600
+ window.location.href = path;
601
+ return;
602
+ }
603
+ const json = await res.json();
604
+ if (navId !== navigationId) return;
605
+ const { data, layoutData, params, pattern, head, deps } = json;
606
+ const Page = await resolveRoute(pattern);
607
+ if (navId !== navigationId) return;
608
+ if (!Page) {
609
+ window.location.href = path;
610
+ return;
611
+ }
612
+
613
+ let mergedData = data;
614
+ if (Page.load) {
615
+ try {
616
+ startCollecting();
617
+ const clientData = await Page.load({
618
+ params,
619
+ url: seen,
620
+ request: new Request(seen),
621
+ // layout loads run server-side; their data arrives in layoutData —
622
+ // parent() merges it outermost-first, mirroring the server context
623
+ parent: async () =>
624
+ Object.assign(
625
+ {},
626
+ ...(Array.isArray(layoutData) ? layoutData : []).filter(
627
+ (d) => d && typeof d === "object",
628
+ ),
629
+ ),
630
+ });
631
+ // merge server-collected keys (page/layout server loads) with
632
+ // whatever this client-side load itself registered
633
+ setDeps(pattern, [
634
+ ...(Array.isArray(deps) ? deps : []),
635
+ ...stopCollecting(),
636
+ ]);
637
+ mergedData = { ...clientData, ...data };
638
+ } catch (e: unknown) {
639
+ stopCollecting();
640
+ if (e && typeof e === "object" && "location" in e) {
641
+ window.location.href = String((e as { location: unknown }).location);
642
+ return;
643
+ }
644
+ console.error("[grimoire] universal load error:", e);
645
+ }
646
+ if (navId !== navigationId) return;
647
+ } else if (Array.isArray(deps)) {
648
+ // no client-side load to run — the server's collected depends() keys
649
+ // (from +page.server.ts / +layout.server.ts) are the whole story
650
+ setDeps(pattern, deps);
651
+ }
652
+
653
+ // track state for HMR rerender
654
+ lastState = { data: mergedData, layoutData, params, pattern };
655
+ (globalThis as any).__grimoire_current_pattern__ = pattern;
656
+
657
+ disposeCurrentPage?.();
658
+ disposeCurrentPage = null;
659
+ pushHydrationNodes([]);
660
+ let rootNode: any;
661
+ // the page's effects (and use: directives) run once it is in the document
662
+ let flushEffects = () => {};
663
+ disposeCurrentPage = withEffectScope(() => {
664
+ try {
665
+ ({ value: rootNode, flush: flushEffects } = collectEffects(() =>
666
+ buildRouteTree(lastState!, Page),
667
+ ));
668
+ } catch (e) {
669
+ console.error(e);
670
+ }
671
+ });
672
+ popHydrationNodes();
673
+
674
+ updateHead(head);
675
+ // isRefetch is read before currentPath moves, and captured, because
676
+ // applyScroll may run after this function has returned.
677
+ const isRefetch = url.pathname === currentPath;
678
+
679
+ // Scroll has to be decided in the same frame the content lands. Running it
680
+ // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
681
+ // same-page anchor was already present and worked, while an anchor on the
682
+ // incoming page did not exist yet and fell through to scrollToTop().
683
+ const applyScroll = () => {
684
+ if (url.hash) {
685
+ const target = document.getElementById(url.hash.slice(1));
686
+ if (!target) {
687
+ scrollToTop();
688
+ return;
689
+ }
690
+ target.scrollIntoView();
691
+ // re-assert after layout settles (late effects/images can shift content)
692
+ requestAnimationFrame(() => target.scrollIntoView());
693
+ return;
694
+ }
695
+ if (historyMode === "none") {
696
+ // popstate: the browser already moved through history — restore what
697
+ // we saved for this path (back/forward semantics)
698
+ restoreScrollPosition(url.pathname);
699
+ return;
700
+ }
701
+ // fresh navigation starts at the top; a same-path replace
702
+ // (invalidate/refetch) keeps the scroll it started with
703
+ if (!isRefetch) {
704
+ scrollToTop();
705
+ return;
706
+ }
707
+ window.scrollTo(0, startY);
708
+ requestAnimationFrame(() => window.scrollTo(0, startY));
709
+ };
710
+
711
+ // View transitions: animate the swap when the browser supports it and the
712
+ // user hasn't asked for reduced motion. The callback must stay synchronous.
713
+ const preserved = capturePreservedScroll();
714
+ const doc = document as Document & {
715
+ startViewTransition?: (
716
+ cb: () => void,
717
+ ) => { finished?: Promise<unknown>; ready?: Promise<unknown> } | undefined;
718
+ };
719
+ const animate =
720
+ typeof doc.startViewTransition === "function" &&
721
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
722
+ // elements the old and new page share by key morph into each other
723
+ const shared = animate ? sharedTransitionKeys(rootNode) : [];
724
+ const named: Element[] = [];
725
+ const name = (el: Element, key: string) => {
726
+ (el as HTMLElement).style.setProperty("view-transition-name", key);
727
+ named.push(el);
728
+ };
729
+ const doSwap = () => {
730
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
731
+ flushEffects();
732
+ for (const [key, , next] of shared) name(next, key);
733
+ restorePreservedScroll(preserved);
734
+ applyScroll();
735
+ };
736
+ if (animate) {
737
+ // the browser snapshots the old page as startViewTransition is called
738
+ for (const [key, prev] of shared) name(prev, key);
739
+ const transition = doc.startViewTransition?.(doSwap);
740
+ const clear = () => {
741
+ for (const el of named)
742
+ (el as HTMLElement).style.removeProperty("view-transition-name");
743
+ };
744
+ Promise.resolve(transition?.finished).then(clear, clear);
745
+ // a skipped transition (another navigation, a hidden tab) rejects
746
+ // ready; the swap still runs, so it is not an error worth reporting
747
+ transition?.ready?.catch(() => {});
748
+ } else {
749
+ doSwap();
750
+ }
751
+ currentPath = url.pathname;
752
+ currentSearch = url.search;
753
+
754
+ if (historyMode !== "none") {
755
+ history[historyMode === "replace" ? "replaceState" : "pushState"](
756
+ null,
757
+ "",
758
+ path,
759
+ );
760
+ }
761
+ afterNavigateCb?.(seen);
762
+ }
763
+
764
+ export interface RouterExtensions {
765
+ /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
766
+ matchers?: Record<string, (value: string) => boolean>;
767
+ /** Server-collected depends() keys per route pattern (from SSR state). */
768
+ deps?: Record<string, string[]>;
769
+ }
770
+
771
+ let paramMatcherFns: Record<string, (value: string) => boolean> = {};
772
+
773
+ export function initRouter(
774
+ routes: Record<string, RouteEntry>,
775
+ layouts: any[] = [],
776
+ initialDispose?: () => void,
777
+ ext?: RouterExtensions,
778
+ ) {
779
+ paramMatcherFns = ext?.matchers ?? {};
780
+ routeMap = routes;
781
+ layoutList = layouts;
782
+ prefetched.clear();
783
+ disposeCurrentPage = initialDispose ?? null;
784
+ currentPath = location.pathname;
785
+ currentSearch = location.search;
786
+
787
+ // the app owns scroll: the browser's automatic restoration fires after
788
+ // the router's own scroll and clobbers scroll-to-top / saved positions
789
+ if ("scrollRestoration" in history) history.scrollRestoration = "manual";
790
+ // dev HMR surface: available even without SSR state so the client can tell
791
+ // a missing router apart from a missing initial payload
792
+ const globals = globalThis as unknown as {
793
+ __grimoire_current_pattern__?: string;
794
+ __grimoire_routes__?: Record<string, RouteEntry>;
795
+ __grimoire_rerender__?: () => Promise<void>;
796
+ __grimoire_navigate__?: (path: string, replace?: boolean) => void;
797
+ __grimoire_form__?: (form: unknown) => Promise<void>;
798
+ __grimoire_hmr__?: HmrControl;
799
+ };
800
+ globals.__grimoire_routes__ = routeMap;
801
+ globals.__grimoire_rerender__ = hmrRerender;
802
+ globals.__grimoire_hmr__ = hmrControl;
803
+ globals.__grimoire_form__ = showActionFailure;
804
+ globals.__grimoire_navigate__ = (path, replace) =>
805
+ navigate(path, replace ?? false);
806
+
807
+ // initial HMR state from SSR
808
+ const stateEl = document.getElementById("__grimoire_state__");
809
+ if (stateEl) {
810
+ const state = JSON.parse(stateEl.textContent!);
811
+ lastState = {
812
+ data: state.data,
813
+ layoutData: state.layoutData,
814
+ params: state.params,
815
+ pattern: state.pattern,
816
+ form: state.form,
817
+ };
818
+ if (Array.isArray(state.deps)) {
819
+ setDeps(state.pattern, state.deps);
820
+ }
821
+ globals.__grimoire_current_pattern__ = state.pattern;
822
+ }
823
+
824
+ saveScrollPosition();
825
+ document.addEventListener("click", handleClick);
826
+ // forms rendered client-side have no SSR-injected _csrf input
827
+ document.addEventListener("submit", onSubmitEnsureCsrf, true);
828
+ window.addEventListener("popstate", () => {
829
+ if (
830
+ location.pathname === currentPath &&
831
+ location.search === currentSearch
832
+ ) {
833
+ return;
834
+ }
835
+ // the browser already moved through history — render only, never
836
+ // push/replace here or the forward stack gets clobbered.
837
+ // The search has to come along: refetching the bare pathname served
838
+ // unfiltered data while the address bar still showed the query.
839
+ // The hash deliberately does not, so back/forward restores the saved
840
+ // scroll offset instead of re-jumping to the anchor, matching the
841
+ // browser's own behaviour for document history navigation.
842
+ navigate(location.pathname + location.search, { history: "none" });
843
+ });
844
+ setupPreload();
845
+ setupStylesheetHashes();
846
+ }
847
+
848
+ /**
849
+ * Swap the page's <head> tags for the incoming page's. Server-rendered tags
850
+ * sit between `<!--grimoire-head-->` markers; tags added by an earlier
851
+ * navigation carry `data-grimoire-head`. Both are replaced, so the first
852
+ * navigation doesn't leave the server-rendered description or icon behind
853
+ * next to the new ones. With no incoming <title>, the current title stays.
854
+ */
855
+ function updateHead(headHtml: string) {
856
+ const prevTitle = document.title;
857
+ const markers = Array.from(document.head.childNodes).filter(
858
+ (n): n is Comment => n.nodeType === Node.COMMENT_NODE,
859
+ );
860
+ const start = markers.find((c) => c.data === "grimoire-head");
861
+ const end = markers.find((c) => c.data === "/grimoire-head");
862
+ if (start && end) {
863
+ while (start.nextSibling && start.nextSibling !== end) {
864
+ start.nextSibling.remove();
865
+ }
866
+ }
867
+ document
868
+ .querySelectorAll("[data-grimoire-head]")
869
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
870
+ .forEach((el) => el.remove());
871
+ const parsed = headHtml
872
+ ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
873
+ : null;
874
+ const incomingTitle = parsed?.querySelector("title");
875
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
876
+ document.querySelectorAll("title").forEach((el) => el.remove());
877
+ document.title = incomingTitle?.textContent ?? prevTitle;
878
+ if (parsed) {
879
+ for (const el of Array.from(parsed.head.children)) {
880
+ if (el.tagName === "TITLE") continue;
881
+ (el as HTMLElement).dataset.grimoireHead = "1";
882
+ if (end) document.head.insertBefore(el, end);
883
+ else document.head.appendChild(el);
884
+ }
885
+ }
886
+ }
887
+
888
+ function handleClick(e: MouseEvent) {
889
+ // let the browser handle modified clicks (new tab/window/download)
890
+ if (e.defaultPrevented || e.button !== 0) return;
891
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
892
+ const a = (e.target as Element).closest("a");
893
+ if (!a) return;
894
+ if (a.target && a.target !== "_self") return;
895
+ if (a.hasAttribute("download")) return;
896
+ if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
897
+ const href = a.getAttribute("href");
898
+ if (!href) return;
899
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
900
+ // Only intercept clicks for known page routes — let server routes
901
+ // (redirects, API endpoints, etc.) navigate normally so the browser
902
+ // follows the response without the extra fetch-then-redirect dance.
903
+ try {
904
+ const url = new URL(href, location.origin);
905
+ if (!findPattern(url.pathname)) return;
906
+ // same-page anchor: native behavior scrolls to it, no re-render needed
907
+ if (url.pathname === location.pathname && url.hash) return;
908
+ } catch {
909
+ return;
910
+ }
911
+ e.preventDefault();
912
+ // a pending hover prefetch would re-request what this click just consumed
913
+ clearTimeout(preloadTimer);
914
+ navigate(href);
915
+ }