@sigil-dev/grimoire 0.9.6 → 0.9.7

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,619 +1,622 @@
1
- import { popHydrationNodes, pushHydrationNodes } from "@sigil-dev/runtime";
2
- import {
3
- clearDeps,
4
- depends,
5
- getDeps,
6
- setDeps,
7
- startCollecting,
8
- stopCollecting,
9
- } from "./deps";
10
- import { withEffectScope } from "./scope";
11
-
12
- // re-exported for app code that imports depends() from the router module
13
- export { depends };
14
-
15
- async function refetchCurrent(): Promise<void> {
16
- if (!lastState) return;
17
- await navigate(location.pathname, { history: "replace" });
18
- }
19
-
20
- export async function invalidate(...keys: string[]): Promise<void> {
21
- const current = lastState?.pattern;
22
- if (!current) return;
23
- const deps = getDeps(current);
24
- // no recorded deps → conservative refetch; otherwise only on intersection
25
- if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
26
- await refetchCurrent();
27
- }
28
- }
29
-
30
- export async function invalidateAll(): Promise<void> {
31
- await refetchCurrent();
32
- }
33
-
34
- type PageComponent = ((props: any) => any) & {
35
- load?: (ctx: any) => Promise<any>;
36
- loading?: () => any;
37
- error?: (props: { error: unknown }) => any;
38
- };
39
- /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
40
- * component functions are also accepted (tests, HMR replacements). */
41
- type RouteEntry =
42
- | PageComponent
43
- | { __lazy: () => Promise<{ default: PageComponent }> };
44
-
45
- let routeMap: Record<string, RouteEntry> = {};
46
- const resolvedRoutes: Record<string, PageComponent> = {};
47
-
48
- async function resolveRoute(pattern: string): Promise<PageComponent | null> {
49
- const entry = routeMap[pattern];
50
- if (!entry) return null;
51
- // plain function: eager component or an HMR hot-swap — always wins over cache
52
- if (typeof entry === "function") return entry;
53
- return (resolvedRoutes[pattern] ??= (await entry.__lazy()).default);
54
- }
55
- let layoutList: { path: string; component: (props: any) => any }[] = [];
56
- let disposeCurrentPage: (() => void) | null = null;
57
- // Scroll keys and same-page refetch detection are pathname-only on purpose.
58
- // currentSearch is tracked alongside so popstate can tell "?page=2" apart
59
- // from "?page=1" without polluting either of those.
60
- let currentPath = location.pathname;
61
- let currentSearch = location.search;
62
-
63
- // C1: Navigation hooks
64
- let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
65
- let onNavigateCb: ((url: URL) => void) | null = null;
66
- let afterNavigateCb: ((url: URL) => void) | null = null;
67
-
68
- export async function hmrRerender(): Promise<void> {
69
- if (!lastState) {
70
- location.reload();
71
- return;
72
- }
73
- const Page = await resolveRoute(lastState.pattern);
74
- if (!Page) {
75
- location.reload();
76
- return;
77
- }
78
- disposeCurrentPage?.();
79
- pushHydrationNodes([]);
80
- let rootNode: any;
81
- disposeCurrentPage = withEffectScope(() => {
82
- rootNode = buildRouteTree(lastState!, Page);
83
- });
84
- popHydrationNodes();
85
- const preserved = capturePreservedScroll();
86
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
87
- restorePreservedScroll(preserved);
88
- }
89
-
90
- /**
91
- * Dev-only surface the HMR client drives. Route entries are replaced rather
92
- * than mutated in place so a swapped module also wins for later navigations,
93
- * and the resolved-module cache is dropped with them.
94
- */
95
- export interface HmrControl {
96
- setRoute(pattern: string, entry: RouteEntry): void;
97
- setLayout(path: string, component: (props: any) => any): void;
98
- rerender(): Promise<void>;
99
- }
100
-
101
- const hmrControl: HmrControl = {
102
- setRoute(pattern, entry) {
103
- routeMap[pattern] = entry;
104
- delete resolvedRoutes[pattern];
105
- },
106
- setLayout(path: string, component: (props: any) => any) {
107
- const existing = layoutList.find((l) => l.path === path);
108
- if (existing) existing.component = component;
109
- else layoutList.push({ path, component });
110
- },
111
- rerender: hmrRerender,
112
- };
113
-
114
- export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
115
- beforeNavigateCb = cb;
116
- }
117
-
118
- export function onNavigate(cb: (url: URL) => void): void {
119
- onNavigateCb = cb;
120
- }
121
-
122
- export function afterNavigate(cb: (url: URL) => void): void {
123
- afterNavigateCb = cb;
124
- }
125
-
126
- // C2: Scroll restoration
127
- const scrollPositions = new Map<string, number>();
128
-
129
- function saveScrollPosition(): void {
130
- scrollPositions.set(currentPath, window.scrollY);
131
- }
132
-
133
- function restoreScrollPosition(path: string): void {
134
- const y = scrollPositions.get(path) ?? 0;
135
- window.scrollTo(0, y);
136
- // re-assert after layout settles (late effects/images can shift content)
137
- requestAnimationFrame(() => window.scrollTo(0, y));
138
- }
139
-
140
- function scrollToTop(): void {
141
- window.scrollTo(0, 0);
142
- requestAnimationFrame(() => window.scrollTo(0, 0));
143
- }
144
-
145
- // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
146
- // across the root swap: the router rebuilds the whole tree on navigation, so a
147
- // long independently-scrollable sidebar would otherwise snap back to the top.
148
- // The attribute value is the matching key; elements without one fall back to
149
- // their id, then to their ordinal position.
150
- const PRESERVE_ATTR = "data-sigil-scroll-preserve";
151
-
152
- function preserveKey(el: Element, ordinal: number): string {
153
- return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
154
- }
155
-
156
- function capturePreservedScroll(): Map<string, number> {
157
- const positions = new Map<string, number>();
158
- let ordinal = 0;
159
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
160
- positions.set(preserveKey(el, ordinal), el.scrollTop);
161
- ordinal++;
162
- }
163
- return positions;
164
- }
165
-
166
- function restorePreservedScroll(positions: Map<string, number>): void {
167
- if (positions.size === 0) return;
168
- let ordinal = 0;
169
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
170
- const top = positions.get(preserveKey(el, ordinal));
171
- if (top !== undefined) el.scrollTop = top;
172
- ordinal++;
173
- }
174
- }
175
-
176
- // C3: Preloading
177
- let preloadTimer: Timer | null = null;
178
-
179
- function setupPreload(): void {
180
- document.addEventListener("mouseover", (e) => {
181
- const a = (e.target as Element).closest("a");
182
- if (!a) return;
183
- const href = a.getAttribute("href");
184
- if (!href) return;
185
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
186
- if (a.getAttribute("data-sigil-preload") === "off") return;
187
-
188
- // Only prefetch links that resolve to a known client route — external
189
- // pages and non-page endpoints (API routes, redirects) are skipped.
190
- try {
191
- const url = new URL(href, location.origin);
192
- if (!findPattern(url.pathname)) return;
193
- } catch {
194
- return;
195
- }
196
-
197
- const preloadCode = a.hasAttribute("data-sigil-preload-code");
198
-
199
- clearTimeout(preloadTimer);
200
- preloadTimer = setTimeout(() => {
201
- if (preloadCode) {
202
- const link = document.createElement("link");
203
- link.rel = "prefetch";
204
- link.href = href;
205
- document.head.appendChild(link);
206
- }
207
- // data prefetch is the default; -code is the explicit escalation
208
- fetch(href, {
209
- headers: { "x-grimoire-navigate": "1" },
210
- redirect: "manual",
211
- priority: "low",
212
- }).catch(() => {});
213
- }, 80);
214
- });
215
-
216
- document.addEventListener("mouseout", (e) => {
217
- const a = (e.target as Element).closest("a");
218
- if (!a) return;
219
- clearTimeout(preloadTimer);
220
- });
221
- }
222
-
223
- let lastState: {
224
- data: any;
225
- layoutData: any[];
226
- params: any;
227
- pattern: string;
228
- } | null = null;
229
-
230
- function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
231
- const { data, layoutData, params, pattern } = state!;
232
- if (!Page) throw new Error(`no component for pattern ${pattern}`);
233
-
234
- const matchedLayouts = layoutList
235
- .filter(
236
- (l) =>
237
- l.path === "/" ||
238
- pattern === l.path ||
239
- pattern.startsWith(`${l.path}/`),
240
- )
241
- .sort((a, b) => a.path.length - b.path.length);
242
-
243
- let renderFn = () => {
244
- const pageNode = Page({ data, params });
245
- const pageDiv = document.createElement("div");
246
- pageDiv.id = "grimoire-page";
247
- pageDiv.appendChild(pageNode);
248
- return pageDiv;
249
- };
250
-
251
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
252
- const LayoutComponent = matchedLayouts[i].component;
253
- const innerRender = renderFn;
254
- const currentLayoutData = layoutData?.[i];
255
- renderFn = () => {
256
- const childNode = innerRender();
257
- return LayoutComponent({
258
- data: currentLayoutData,
259
- params,
260
- path: pattern,
261
- children: childNode,
262
- });
263
- };
264
- }
265
-
266
- return renderFn();
267
- }
268
-
269
- function matchClientPattern(pattern: string, pathname: string): boolean {
270
- // haha pp and ph
271
- const pp = pattern.split("/").filter(Boolean);
272
- const ph = pathname.split("/").filter(Boolean);
273
-
274
- // Depth-first walk; optional segments (:x?) try consuming one segment
275
- // before consuming zero, mirroring the server's matchPattern.
276
- function walk(pi: number, pj: number): boolean {
277
- if (pi === pp.length) return pj === ph.length;
278
- const part = pp[pi]!;
279
- if (part.startsWith("*")) return true;
280
- const optional = part.startsWith(":") && part.endsWith("?");
281
- if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
282
- if (!optional) {
283
- if (pj >= ph.length) return false;
284
- if (!part.startsWith(":") && part !== ph[pj]) return false;
285
- return walk(pi + 1, pj + 1);
286
- }
287
- return walk(pi + 1, pj);
288
- }
289
-
290
- return walk(0, 0);
291
- }
292
-
293
- function findPattern(pathname: string): string | null {
294
- for (const pattern of Object.keys(routeMap)) {
295
- if (matchClientPattern(pattern, pathname)) return pattern;
296
- }
297
- return null;
298
- }
299
-
300
- export interface NavigateOptions {
301
- /** "push" (default) adds a history entry, "replace" swaps the current one,
302
- * "none" leaves history untouched (popstate — the browser already moved). */
303
- history?: "push" | "replace" | "none";
304
- }
305
-
306
- // monotonically increasing id — a navigation aborts silently the moment a
307
- // newer one starts, so overlapping navigations can't commit stale responses
308
- let navigationId = 0;
309
-
310
- export async function navigate(
311
- path: string,
312
- opts: NavigateOptions | boolean = {},
313
- ) {
314
- // boolean back-compat: navigate(path, true) meant "replace"
315
- const historyMode =
316
- typeof opts === "boolean"
317
- ? opts
318
- ? "replace"
319
- : "push"
320
- : (opts.history ?? "push");
321
- const navId = ++navigationId;
322
- const url = new URL(path, location.origin);
323
-
324
- if (beforeNavigateCb) {
325
- const shouldProceed = beforeNavigateCb(url);
326
- if (shouldProceed === false) return;
327
- }
328
- onNavigateCb?.(url);
329
- saveScrollPosition();
330
-
331
- // load the loading immediately
332
- const destPattern = findPattern(url.pathname);
333
- const DestPage = destPattern ? await resolveRoute(destPattern) : null;
334
- if (navId !== navigationId) return;
335
- if (DestPage?.loading) {
336
- disposeCurrentPage?.();
337
- disposeCurrentPage = null;
338
- pushHydrationNodes([]);
339
- let loadingNode: any;
340
- disposeCurrentPage = withEffectScope(() => {
341
- loadingNode = (DestPage as any).loading();
342
- });
343
- popHydrationNodes();
344
- // replace only grimoire-page, keeps layout stable during transition
345
- const pageEl = document.getElementById("grimoire-page");
346
- if (pageEl) pageEl.replaceChildren(loadingNode);
347
- else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
348
- }
349
-
350
- const res = await fetch(path, {
351
- headers: { "x-grimoire-navigate": "1" },
352
- redirect: "manual",
353
- });
354
- if (navId !== navigationId) return;
355
- const contentType = res.headers.get("content-type") ?? "";
356
- if (!contentType.includes("application/json")) {
357
- window.location.href = path;
358
- return;
359
- }
360
- const json = await res.json();
361
- if (navId !== navigationId) return;
362
- const { data, layoutData, params, pattern, head, deps } = json;
363
- const Page = await resolveRoute(pattern);
364
- if (navId !== navigationId) return;
365
- if (!Page) {
366
- window.location.href = path;
367
- return;
368
- }
369
-
370
- let mergedData = data;
371
- if (Page.load) {
372
- try {
373
- startCollecting();
374
- const clientData = await Page.load({
375
- params,
376
- url,
377
- request: new Request(url),
378
- // layout loads run server-side; their data arrives in layoutData —
379
- // parent() merges it outermost-first, mirroring the server context
380
- parent: async () =>
381
- Object.assign(
382
- {},
383
- ...(Array.isArray(layoutData) ? layoutData : []).filter(
384
- (d) => d && typeof d === "object",
385
- ),
386
- ),
387
- });
388
- // merge server-collected keys (page/layout server loads) with
389
- // whatever this client-side load itself registered
390
- setDeps(pattern, [
391
- ...(Array.isArray(deps) ? deps : []),
392
- ...stopCollecting(),
393
- ]);
394
- mergedData = { ...clientData, ...data };
395
- } catch (e: unknown) {
396
- stopCollecting();
397
- if (e && typeof e === "object" && "location" in e) {
398
- window.location.href = String((e as { location: unknown }).location);
399
- return;
400
- }
401
- console.error("[grimoire] universal load error:", e);
402
- }
403
- if (navId !== navigationId) return;
404
- } else if (Array.isArray(deps)) {
405
- // no client-side load to run — the server's collected depends() keys
406
- // (from +page.server.ts / +layout.server.ts) are the whole story
407
- setDeps(pattern, deps);
408
- }
409
-
410
- // track state for HMR rerender
411
- lastState = { data: mergedData, layoutData, params, pattern };
412
- (globalThis as any).__grimoire_current_pattern__ = pattern;
413
-
414
- disposeCurrentPage?.();
415
- disposeCurrentPage = null;
416
- pushHydrationNodes([]);
417
- let rootNode: any;
418
- disposeCurrentPage = withEffectScope(() => {
419
- try {
420
- rootNode = buildRouteTree(lastState!, Page);
421
- } catch (e) {
422
- console.error(e);
423
- }
424
- });
425
- popHydrationNodes();
426
-
427
- updateHead(head);
428
- // isRefetch is read before currentPath moves, and captured, because
429
- // applyScroll may run after this function has returned.
430
- const isRefetch = url.pathname === currentPath;
431
-
432
- // Scroll has to be decided in the same frame the content lands. Running it
433
- // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
434
- // same-page anchor was already present and worked, while an anchor on the
435
- // incoming page did not exist yet and fell through to scrollToTop().
436
- const applyScroll = () => {
437
- if (url.hash) {
438
- const target = document.getElementById(url.hash.slice(1));
439
- if (!target) {
440
- scrollToTop();
441
- return;
442
- }
443
- target.scrollIntoView();
444
- // re-assert after layout settles (late effects/images can shift content)
445
- requestAnimationFrame(() => target.scrollIntoView());
446
- return;
447
- }
448
- if (historyMode === "none") {
449
- // popstate: the browser already moved through history — restore what
450
- // we saved for this path (back/forward semantics)
451
- restoreScrollPosition(url.pathname);
452
- return;
453
- }
454
- // fresh navigation starts at the top; a same-path replace
455
- // (invalidate/refetch) keeps the current scroll
456
- if (!isRefetch) scrollToTop();
457
- };
458
-
459
- // View transitions: animate the swap when the browser supports it and the
460
- // user hasn't asked for reduced motion. The callback must stay synchronous.
461
- const preserved = capturePreservedScroll();
462
- const doSwap = () => {
463
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
464
- restorePreservedScroll(preserved);
465
- applyScroll();
466
- };
467
- const doc = document as Document & {
468
- startViewTransition?: (cb: () => void) => unknown;
469
- };
470
- if (
471
- typeof doc.startViewTransition === "function" &&
472
- !window.matchMedia("(prefers-reduced-motion: reduce)").matches
473
- ) {
474
- doc.startViewTransition(doSwap);
475
- } else {
476
- doSwap();
477
- }
478
- currentPath = url.pathname;
479
- currentSearch = url.search;
480
-
481
- if (historyMode !== "none") {
482
- history[historyMode === "replace" ? "replaceState" : "pushState"](
483
- null,
484
- "",
485
- path,
486
- );
487
- }
488
- afterNavigateCb?.(url);
489
- }
490
-
491
- export interface RouterExtensions {
492
- /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
493
- matchers?: Record<string, (value: string) => boolean>;
494
- /** Server-collected depends() keys per route pattern (from SSR state). */
495
- deps?: Record<string, string[]>;
496
- }
497
-
498
- let paramMatcherFns: Record<string, (value: string) => boolean> = {};
499
-
500
- export function initRouter(
501
- routes: Record<string, RouteEntry>,
502
- layouts: any[] = [],
503
- initialDispose?: () => void,
504
- ext?: RouterExtensions,
505
- ) {
506
- paramMatcherFns = ext?.matchers ?? {};
507
- routeMap = routes;
508
- layoutList = layouts;
509
- disposeCurrentPage = initialDispose ?? null;
510
- currentPath = location.pathname;
511
- currentSearch = location.search;
512
-
513
- // the app owns scroll: the browser's automatic restoration fires after
514
- // the router's own scroll and clobbers scroll-to-top / saved positions
515
- if ("scrollRestoration" in history) history.scrollRestoration = "manual";
516
- // dev HMR surface: available even without SSR state so the client can tell
517
- // a missing router apart from a missing initial payload
518
- const globals = globalThis as unknown as {
519
- __grimoire_current_pattern__?: string;
520
- __grimoire_routes__?: Record<string, RouteEntry>;
521
- __grimoire_rerender__?: () => Promise<void>;
522
- __grimoire_navigate__?: (path: string, replace?: boolean) => void;
523
- __grimoire_hmr__?: HmrControl;
524
- };
525
- globals.__grimoire_routes__ = routeMap;
526
- globals.__grimoire_rerender__ = hmrRerender;
527
- globals.__grimoire_hmr__ = hmrControl;
528
- globals.__grimoire_navigate__ = (path, replace) =>
529
- navigate(path, replace ?? false);
530
-
531
- // initial HMR state from SSR
532
- const stateEl = document.getElementById("__grimoire_state__");
533
- if (stateEl) {
534
- const state = JSON.parse(stateEl.textContent!);
535
- lastState = {
536
- data: state.data,
537
- layoutData: state.layoutData,
538
- params: state.params,
539
- pattern: state.pattern,
540
- };
541
- if (Array.isArray(state.deps)) {
542
- setDeps(state.pattern, state.deps);
543
- }
544
- globals.__grimoire_current_pattern__ = state.pattern;
545
- }
546
-
547
- saveScrollPosition();
548
- document.addEventListener("click", handleClick);
549
- window.addEventListener("popstate", () => {
550
- if (
551
- location.pathname === currentPath &&
552
- location.search === currentSearch
553
- ) {
554
- return;
555
- }
556
- // the browser already moved through history — render only, never
557
- // push/replace here or the forward stack gets clobbered.
558
- // The search has to come along: refetching the bare pathname served
559
- // unfiltered data while the address bar still showed the query.
560
- // The hash deliberately does not, so back/forward restores the saved
561
- // scroll offset instead of re-jumping to the anchor, matching the
562
- // browser's own behaviour for document history navigation.
563
- navigate(location.pathname + location.search, { history: "none" });
564
- });
565
- setupPreload();
566
- }
567
-
568
- function updateHead(headHtml: string) {
569
- document
570
- .querySelectorAll("[data-grimoire-head]")
571
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
572
- .forEach((el) => el.remove());
573
- const parsed = headHtml
574
- ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
575
- : null;
576
- const incomingTitle = parsed?.querySelector("title");
577
- if (incomingTitle) {
578
- // capture before removing <title> elements — reading document.title
579
- // after removal returns "" and would wipe the title
580
- const prevTitle = document.title;
581
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
582
- document.querySelectorAll("title").forEach((el) => el.remove());
583
- document.title = incomingTitle.textContent ?? prevTitle;
584
- }
585
- if (parsed) {
586
- for (const el of Array.from(parsed.head.children)) {
587
- if (el.tagName === "TITLE") continue;
588
- (el as HTMLElement).dataset.grimoireHead = "1";
589
- document.head.appendChild(el);
590
- }
591
- }
592
- }
593
-
594
- function handleClick(e: MouseEvent) {
595
- // let the browser handle modified clicks (new tab/window/download)
596
- if (e.defaultPrevented || e.button !== 0) return;
597
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
598
- const a = (e.target as Element).closest("a");
599
- if (!a) return;
600
- if (a.target && a.target !== "_self") return;
601
- if (a.hasAttribute("download")) return;
602
- if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
603
- const href = a.getAttribute("href");
604
- if (!href) return;
605
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
606
- // Only intercept clicks for known page routes — let server routes
607
- // (redirects, API endpoints, etc.) navigate normally so the browser
608
- // follows the response without the extra fetch-then-redirect dance.
609
- try {
610
- const url = new URL(href, location.origin);
611
- if (!findPattern(url.pathname)) return;
612
- // same-page anchor: native behavior scrolls to it, no re-render needed
613
- if (url.pathname === location.pathname && url.hash) return;
614
- } catch {
615
- return;
616
- }
617
- e.preventDefault();
618
- navigate(href);
619
- }
1
+ import { popHydrationNodes, pushHydrationNodes } from "@sigil-dev/runtime";
2
+ import { onSubmitEnsureCsrf } from "./csrf.ts";
3
+ import {
4
+ clearDeps,
5
+ depends,
6
+ getDeps,
7
+ setDeps,
8
+ startCollecting,
9
+ stopCollecting,
10
+ } from "./deps";
11
+ import { withEffectScope } from "./scope";
12
+
13
+ // re-exported for app code that imports depends() from the router module
14
+ export { depends };
15
+
16
+ async function refetchCurrent(): Promise<void> {
17
+ if (!lastState) return;
18
+ await navigate(location.pathname, { history: "replace" });
19
+ }
20
+
21
+ export async function invalidate(...keys: string[]): Promise<void> {
22
+ const current = lastState?.pattern;
23
+ if (!current) return;
24
+ const deps = getDeps(current);
25
+ // no recorded deps → conservative refetch; otherwise only on intersection
26
+ if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
27
+ await refetchCurrent();
28
+ }
29
+ }
30
+
31
+ export async function invalidateAll(): Promise<void> {
32
+ await refetchCurrent();
33
+ }
34
+
35
+ type PageComponent = ((props: any) => any) & {
36
+ load?: (ctx: any) => Promise<any>;
37
+ loading?: () => any;
38
+ error?: (props: { error: unknown }) => any;
39
+ };
40
+ /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
41
+ * component functions are also accepted (tests, HMR replacements). */
42
+ type RouteEntry =
43
+ | PageComponent
44
+ | { __lazy: () => Promise<{ default: PageComponent }> };
45
+
46
+ let routeMap: Record<string, RouteEntry> = {};
47
+ const resolvedRoutes: Record<string, PageComponent> = {};
48
+
49
+ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
50
+ const entry = routeMap[pattern];
51
+ if (!entry) return null;
52
+ // plain function: eager component or an HMR hot-swap — always wins over cache
53
+ if (typeof entry === "function") return entry;
54
+ return (resolvedRoutes[pattern] ??= (await entry.__lazy()).default);
55
+ }
56
+ let layoutList: { path: string; component: (props: any) => any }[] = [];
57
+ let disposeCurrentPage: (() => void) | null = null;
58
+ // Scroll keys and same-page refetch detection are pathname-only on purpose.
59
+ // currentSearch is tracked alongside so popstate can tell "?page=2" apart
60
+ // from "?page=1" without polluting either of those.
61
+ let currentPath = location.pathname;
62
+ let currentSearch = location.search;
63
+
64
+ // C1: Navigation hooks
65
+ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
66
+ let onNavigateCb: ((url: URL) => void) | null = null;
67
+ let afterNavigateCb: ((url: URL) => void) | null = null;
68
+
69
+ export async function hmrRerender(): Promise<void> {
70
+ if (!lastState) {
71
+ location.reload();
72
+ return;
73
+ }
74
+ const Page = await resolveRoute(lastState.pattern);
75
+ if (!Page) {
76
+ location.reload();
77
+ return;
78
+ }
79
+ disposeCurrentPage?.();
80
+ pushHydrationNodes([]);
81
+ let rootNode: any;
82
+ disposeCurrentPage = withEffectScope(() => {
83
+ rootNode = buildRouteTree(lastState!, Page);
84
+ });
85
+ popHydrationNodes();
86
+ const preserved = capturePreservedScroll();
87
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
88
+ restorePreservedScroll(preserved);
89
+ }
90
+
91
+ /**
92
+ * Dev-only surface the HMR client drives. Route entries are replaced rather
93
+ * than mutated in place so a swapped module also wins for later navigations,
94
+ * and the resolved-module cache is dropped with them.
95
+ */
96
+ export interface HmrControl {
97
+ setRoute(pattern: string, entry: RouteEntry): void;
98
+ setLayout(path: string, component: (props: any) => any): void;
99
+ rerender(): Promise<void>;
100
+ }
101
+
102
+ const hmrControl: HmrControl = {
103
+ setRoute(pattern, entry) {
104
+ routeMap[pattern] = entry;
105
+ delete resolvedRoutes[pattern];
106
+ },
107
+ setLayout(path: string, component: (props: any) => any) {
108
+ const existing = layoutList.find((l) => l.path === path);
109
+ if (existing) existing.component = component;
110
+ else layoutList.push({ path, component });
111
+ },
112
+ rerender: hmrRerender,
113
+ };
114
+
115
+ export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
116
+ beforeNavigateCb = cb;
117
+ }
118
+
119
+ export function onNavigate(cb: (url: URL) => void): void {
120
+ onNavigateCb = cb;
121
+ }
122
+
123
+ export function afterNavigate(cb: (url: URL) => void): void {
124
+ afterNavigateCb = cb;
125
+ }
126
+
127
+ // C2: Scroll restoration
128
+ const scrollPositions = new Map<string, number>();
129
+
130
+ function saveScrollPosition(): void {
131
+ scrollPositions.set(currentPath, window.scrollY);
132
+ }
133
+
134
+ function restoreScrollPosition(path: string): void {
135
+ const y = scrollPositions.get(path) ?? 0;
136
+ window.scrollTo(0, y);
137
+ // re-assert after layout settles (late effects/images can shift content)
138
+ requestAnimationFrame(() => window.scrollTo(0, y));
139
+ }
140
+
141
+ function scrollToTop(): void {
142
+ window.scrollTo(0, 0);
143
+ requestAnimationFrame(() => window.scrollTo(0, 0));
144
+ }
145
+
146
+ // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
147
+ // across the root swap: the router rebuilds the whole tree on navigation, so a
148
+ // long independently-scrollable sidebar would otherwise snap back to the top.
149
+ // The attribute value is the matching key; elements without one fall back to
150
+ // their id, then to their ordinal position.
151
+ const PRESERVE_ATTR = "data-sigil-scroll-preserve";
152
+
153
+ function preserveKey(el: Element, ordinal: number): string {
154
+ return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
155
+ }
156
+
157
+ function capturePreservedScroll(): Map<string, number> {
158
+ const positions = new Map<string, number>();
159
+ let ordinal = 0;
160
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
161
+ positions.set(preserveKey(el, ordinal), el.scrollTop);
162
+ ordinal++;
163
+ }
164
+ return positions;
165
+ }
166
+
167
+ function restorePreservedScroll(positions: Map<string, number>): void {
168
+ if (positions.size === 0) return;
169
+ let ordinal = 0;
170
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
171
+ const top = positions.get(preserveKey(el, ordinal));
172
+ if (top !== undefined) el.scrollTop = top;
173
+ ordinal++;
174
+ }
175
+ }
176
+
177
+ // C3: Preloading
178
+ let preloadTimer: Timer | null = null;
179
+
180
+ function setupPreload(): void {
181
+ document.addEventListener("mouseover", (e) => {
182
+ const a = (e.target as Element).closest("a");
183
+ if (!a) return;
184
+ const href = a.getAttribute("href");
185
+ if (!href) return;
186
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
187
+ if (a.getAttribute("data-sigil-preload") === "off") return;
188
+
189
+ // Only prefetch links that resolve to a known client route — external
190
+ // pages and non-page endpoints (API routes, redirects) are skipped.
191
+ try {
192
+ const url = new URL(href, location.origin);
193
+ if (!findPattern(url.pathname)) return;
194
+ } catch {
195
+ return;
196
+ }
197
+
198
+ const preloadCode = a.hasAttribute("data-sigil-preload-code");
199
+
200
+ clearTimeout(preloadTimer);
201
+ preloadTimer = setTimeout(() => {
202
+ if (preloadCode) {
203
+ const link = document.createElement("link");
204
+ link.rel = "prefetch";
205
+ link.href = href;
206
+ document.head.appendChild(link);
207
+ }
208
+ // data prefetch is the default; -code is the explicit escalation
209
+ fetch(href, {
210
+ headers: { "x-grimoire-navigate": "1" },
211
+ redirect: "manual",
212
+ priority: "low",
213
+ }).catch(() => {});
214
+ }, 80);
215
+ });
216
+
217
+ document.addEventListener("mouseout", (e) => {
218
+ const a = (e.target as Element).closest("a");
219
+ if (!a) return;
220
+ clearTimeout(preloadTimer);
221
+ });
222
+ }
223
+
224
+ let lastState: {
225
+ data: any;
226
+ layoutData: any[];
227
+ params: any;
228
+ pattern: string;
229
+ } | null = null;
230
+
231
+ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
232
+ const { data, layoutData, params, pattern } = state!;
233
+ if (!Page) throw new Error(`no component for pattern ${pattern}`);
234
+
235
+ const matchedLayouts = layoutList
236
+ .filter(
237
+ (l) =>
238
+ l.path === "/" ||
239
+ pattern === l.path ||
240
+ pattern.startsWith(`${l.path}/`),
241
+ )
242
+ .sort((a, b) => a.path.length - b.path.length);
243
+
244
+ let renderFn = () => {
245
+ const pageNode = Page({ data, params });
246
+ const pageDiv = document.createElement("div");
247
+ pageDiv.id = "grimoire-page";
248
+ pageDiv.appendChild(pageNode);
249
+ return pageDiv;
250
+ };
251
+
252
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
253
+ const LayoutComponent = matchedLayouts[i].component;
254
+ const innerRender = renderFn;
255
+ const currentLayoutData = layoutData?.[i];
256
+ renderFn = () => {
257
+ const childNode = innerRender();
258
+ return LayoutComponent({
259
+ data: currentLayoutData,
260
+ params,
261
+ path: pattern,
262
+ children: childNode,
263
+ });
264
+ };
265
+ }
266
+
267
+ return renderFn();
268
+ }
269
+
270
+ function matchClientPattern(pattern: string, pathname: string): boolean {
271
+ // haha pp and ph
272
+ const pp = pattern.split("/").filter(Boolean);
273
+ const ph = pathname.split("/").filter(Boolean);
274
+
275
+ // Depth-first walk; optional segments (:x?) try consuming one segment
276
+ // before consuming zero, mirroring the server's matchPattern.
277
+ function walk(pi: number, pj: number): boolean {
278
+ if (pi === pp.length) return pj === ph.length;
279
+ const part = pp[pi]!;
280
+ if (part.startsWith("*")) return true;
281
+ const optional = part.startsWith(":") && part.endsWith("?");
282
+ if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
283
+ if (!optional) {
284
+ if (pj >= ph.length) return false;
285
+ if (!part.startsWith(":") && part !== ph[pj]) return false;
286
+ return walk(pi + 1, pj + 1);
287
+ }
288
+ return walk(pi + 1, pj);
289
+ }
290
+
291
+ return walk(0, 0);
292
+ }
293
+
294
+ function findPattern(pathname: string): string | null {
295
+ for (const pattern of Object.keys(routeMap)) {
296
+ if (matchClientPattern(pattern, pathname)) return pattern;
297
+ }
298
+ return null;
299
+ }
300
+
301
+ export interface NavigateOptions {
302
+ /** "push" (default) adds a history entry, "replace" swaps the current one,
303
+ * "none" leaves history untouched (popstate — the browser already moved). */
304
+ history?: "push" | "replace" | "none";
305
+ }
306
+
307
+ // monotonically increasing id — a navigation aborts silently the moment a
308
+ // newer one starts, so overlapping navigations can't commit stale responses
309
+ let navigationId = 0;
310
+
311
+ export async function navigate(
312
+ path: string,
313
+ opts: NavigateOptions | boolean = {},
314
+ ) {
315
+ // boolean back-compat: navigate(path, true) meant "replace"
316
+ const historyMode =
317
+ typeof opts === "boolean"
318
+ ? opts
319
+ ? "replace"
320
+ : "push"
321
+ : (opts.history ?? "push");
322
+ const navId = ++navigationId;
323
+ const url = new URL(path, location.origin);
324
+
325
+ if (beforeNavigateCb) {
326
+ const shouldProceed = beforeNavigateCb(url);
327
+ if (shouldProceed === false) return;
328
+ }
329
+ onNavigateCb?.(url);
330
+ saveScrollPosition();
331
+
332
+ // load the loading immediately
333
+ const destPattern = findPattern(url.pathname);
334
+ const DestPage = destPattern ? await resolveRoute(destPattern) : null;
335
+ if (navId !== navigationId) return;
336
+ if (DestPage?.loading) {
337
+ disposeCurrentPage?.();
338
+ disposeCurrentPage = null;
339
+ pushHydrationNodes([]);
340
+ let loadingNode: any;
341
+ disposeCurrentPage = withEffectScope(() => {
342
+ loadingNode = (DestPage as any).loading();
343
+ });
344
+ popHydrationNodes();
345
+ // replace only grimoire-page, keeps layout stable during transition
346
+ const pageEl = document.getElementById("grimoire-page");
347
+ if (pageEl) pageEl.replaceChildren(loadingNode);
348
+ else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
349
+ }
350
+
351
+ const res = await fetch(path, {
352
+ headers: { "x-grimoire-navigate": "1" },
353
+ redirect: "manual",
354
+ });
355
+ if (navId !== navigationId) return;
356
+ const contentType = res.headers.get("content-type") ?? "";
357
+ if (!contentType.includes("application/json")) {
358
+ window.location.href = path;
359
+ return;
360
+ }
361
+ const json = await res.json();
362
+ if (navId !== navigationId) return;
363
+ const { data, layoutData, params, pattern, head, deps } = json;
364
+ const Page = await resolveRoute(pattern);
365
+ if (navId !== navigationId) return;
366
+ if (!Page) {
367
+ window.location.href = path;
368
+ return;
369
+ }
370
+
371
+ let mergedData = data;
372
+ if (Page.load) {
373
+ try {
374
+ startCollecting();
375
+ const clientData = await Page.load({
376
+ params,
377
+ url,
378
+ request: new Request(url),
379
+ // layout loads run server-side; their data arrives in layoutData —
380
+ // parent() merges it outermost-first, mirroring the server context
381
+ parent: async () =>
382
+ Object.assign(
383
+ {},
384
+ ...(Array.isArray(layoutData) ? layoutData : []).filter(
385
+ (d) => d && typeof d === "object",
386
+ ),
387
+ ),
388
+ });
389
+ // merge server-collected keys (page/layout server loads) with
390
+ // whatever this client-side load itself registered
391
+ setDeps(pattern, [
392
+ ...(Array.isArray(deps) ? deps : []),
393
+ ...stopCollecting(),
394
+ ]);
395
+ mergedData = { ...clientData, ...data };
396
+ } catch (e: unknown) {
397
+ stopCollecting();
398
+ if (e && typeof e === "object" && "location" in e) {
399
+ window.location.href = String((e as { location: unknown }).location);
400
+ return;
401
+ }
402
+ console.error("[grimoire] universal load error:", e);
403
+ }
404
+ if (navId !== navigationId) return;
405
+ } else if (Array.isArray(deps)) {
406
+ // no client-side load to run — the server's collected depends() keys
407
+ // (from +page.server.ts / +layout.server.ts) are the whole story
408
+ setDeps(pattern, deps);
409
+ }
410
+
411
+ // track state for HMR rerender
412
+ lastState = { data: mergedData, layoutData, params, pattern };
413
+ (globalThis as any).__grimoire_current_pattern__ = pattern;
414
+
415
+ disposeCurrentPage?.();
416
+ disposeCurrentPage = null;
417
+ pushHydrationNodes([]);
418
+ let rootNode: any;
419
+ disposeCurrentPage = withEffectScope(() => {
420
+ try {
421
+ rootNode = buildRouteTree(lastState!, Page);
422
+ } catch (e) {
423
+ console.error(e);
424
+ }
425
+ });
426
+ popHydrationNodes();
427
+
428
+ updateHead(head);
429
+ // isRefetch is read before currentPath moves, and captured, because
430
+ // applyScroll may run after this function has returned.
431
+ const isRefetch = url.pathname === currentPath;
432
+
433
+ // Scroll has to be decided in the same frame the content lands. Running it
434
+ // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
435
+ // same-page anchor was already present and worked, while an anchor on the
436
+ // incoming page did not exist yet and fell through to scrollToTop().
437
+ const applyScroll = () => {
438
+ if (url.hash) {
439
+ const target = document.getElementById(url.hash.slice(1));
440
+ if (!target) {
441
+ scrollToTop();
442
+ return;
443
+ }
444
+ target.scrollIntoView();
445
+ // re-assert after layout settles (late effects/images can shift content)
446
+ requestAnimationFrame(() => target.scrollIntoView());
447
+ return;
448
+ }
449
+ if (historyMode === "none") {
450
+ // popstate: the browser already moved through history — restore what
451
+ // we saved for this path (back/forward semantics)
452
+ restoreScrollPosition(url.pathname);
453
+ return;
454
+ }
455
+ // fresh navigation starts at the top; a same-path replace
456
+ // (invalidate/refetch) keeps the current scroll
457
+ if (!isRefetch) scrollToTop();
458
+ };
459
+
460
+ // View transitions: animate the swap when the browser supports it and the
461
+ // user hasn't asked for reduced motion. The callback must stay synchronous.
462
+ const preserved = capturePreservedScroll();
463
+ const doSwap = () => {
464
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
465
+ restorePreservedScroll(preserved);
466
+ applyScroll();
467
+ };
468
+ const doc = document as Document & {
469
+ startViewTransition?: (cb: () => void) => unknown;
470
+ };
471
+ if (
472
+ typeof doc.startViewTransition === "function" &&
473
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches
474
+ ) {
475
+ doc.startViewTransition(doSwap);
476
+ } else {
477
+ doSwap();
478
+ }
479
+ currentPath = url.pathname;
480
+ currentSearch = url.search;
481
+
482
+ if (historyMode !== "none") {
483
+ history[historyMode === "replace" ? "replaceState" : "pushState"](
484
+ null,
485
+ "",
486
+ path,
487
+ );
488
+ }
489
+ afterNavigateCb?.(url);
490
+ }
491
+
492
+ export interface RouterExtensions {
493
+ /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
494
+ matchers?: Record<string, (value: string) => boolean>;
495
+ /** Server-collected depends() keys per route pattern (from SSR state). */
496
+ deps?: Record<string, string[]>;
497
+ }
498
+
499
+ let paramMatcherFns: Record<string, (value: string) => boolean> = {};
500
+
501
+ export function initRouter(
502
+ routes: Record<string, RouteEntry>,
503
+ layouts: any[] = [],
504
+ initialDispose?: () => void,
505
+ ext?: RouterExtensions,
506
+ ) {
507
+ paramMatcherFns = ext?.matchers ?? {};
508
+ routeMap = routes;
509
+ layoutList = layouts;
510
+ disposeCurrentPage = initialDispose ?? null;
511
+ currentPath = location.pathname;
512
+ currentSearch = location.search;
513
+
514
+ // the app owns scroll: the browser's automatic restoration fires after
515
+ // the router's own scroll and clobbers scroll-to-top / saved positions
516
+ if ("scrollRestoration" in history) history.scrollRestoration = "manual";
517
+ // dev HMR surface: available even without SSR state so the client can tell
518
+ // a missing router apart from a missing initial payload
519
+ const globals = globalThis as unknown as {
520
+ __grimoire_current_pattern__?: string;
521
+ __grimoire_routes__?: Record<string, RouteEntry>;
522
+ __grimoire_rerender__?: () => Promise<void>;
523
+ __grimoire_navigate__?: (path: string, replace?: boolean) => void;
524
+ __grimoire_hmr__?: HmrControl;
525
+ };
526
+ globals.__grimoire_routes__ = routeMap;
527
+ globals.__grimoire_rerender__ = hmrRerender;
528
+ globals.__grimoire_hmr__ = hmrControl;
529
+ globals.__grimoire_navigate__ = (path, replace) =>
530
+ navigate(path, replace ?? false);
531
+
532
+ // initial HMR state from SSR
533
+ const stateEl = document.getElementById("__grimoire_state__");
534
+ if (stateEl) {
535
+ const state = JSON.parse(stateEl.textContent!);
536
+ lastState = {
537
+ data: state.data,
538
+ layoutData: state.layoutData,
539
+ params: state.params,
540
+ pattern: state.pattern,
541
+ };
542
+ if (Array.isArray(state.deps)) {
543
+ setDeps(state.pattern, state.deps);
544
+ }
545
+ globals.__grimoire_current_pattern__ = state.pattern;
546
+ }
547
+
548
+ saveScrollPosition();
549
+ document.addEventListener("click", handleClick);
550
+ // forms rendered client-side have no SSR-injected _csrf input
551
+ document.addEventListener("submit", onSubmitEnsureCsrf, true);
552
+ window.addEventListener("popstate", () => {
553
+ if (
554
+ location.pathname === currentPath &&
555
+ location.search === currentSearch
556
+ ) {
557
+ return;
558
+ }
559
+ // the browser already moved through history — render only, never
560
+ // push/replace here or the forward stack gets clobbered.
561
+ // The search has to come along: refetching the bare pathname served
562
+ // unfiltered data while the address bar still showed the query.
563
+ // The hash deliberately does not, so back/forward restores the saved
564
+ // scroll offset instead of re-jumping to the anchor, matching the
565
+ // browser's own behaviour for document history navigation.
566
+ navigate(location.pathname + location.search, { history: "none" });
567
+ });
568
+ setupPreload();
569
+ }
570
+
571
+ function updateHead(headHtml: string) {
572
+ document
573
+ .querySelectorAll("[data-grimoire-head]")
574
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
575
+ .forEach((el) => el.remove());
576
+ const parsed = headHtml
577
+ ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
578
+ : null;
579
+ const incomingTitle = parsed?.querySelector("title");
580
+ if (incomingTitle) {
581
+ // capture before removing <title> elements — reading document.title
582
+ // after removal returns "" and would wipe the title
583
+ const prevTitle = document.title;
584
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
585
+ document.querySelectorAll("title").forEach((el) => el.remove());
586
+ document.title = incomingTitle.textContent ?? prevTitle;
587
+ }
588
+ if (parsed) {
589
+ for (const el of Array.from(parsed.head.children)) {
590
+ if (el.tagName === "TITLE") continue;
591
+ (el as HTMLElement).dataset.grimoireHead = "1";
592
+ document.head.appendChild(el);
593
+ }
594
+ }
595
+ }
596
+
597
+ function handleClick(e: MouseEvent) {
598
+ // let the browser handle modified clicks (new tab/window/download)
599
+ if (e.defaultPrevented || e.button !== 0) return;
600
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
601
+ const a = (e.target as Element).closest("a");
602
+ if (!a) return;
603
+ if (a.target && a.target !== "_self") return;
604
+ if (a.hasAttribute("download")) return;
605
+ if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
606
+ const href = a.getAttribute("href");
607
+ if (!href) return;
608
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
609
+ // Only intercept clicks for known page routes — let server routes
610
+ // (redirects, API endpoints, etc.) navigate normally so the browser
611
+ // follows the response without the extra fetch-then-redirect dance.
612
+ try {
613
+ const url = new URL(href, location.origin);
614
+ if (!findPattern(url.pathname)) return;
615
+ // same-page anchor: native behavior scrolls to it, no re-render needed
616
+ if (url.pathname === location.pathname && url.hash) return;
617
+ } catch {
618
+ return;
619
+ }
620
+ e.preventDefault();
621
+ navigate(href);
622
+ }