@sigil-dev/grimoire 0.9.29 → 0.9.30

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