@sigil-dev/grimoire 0.9.2 → 0.9.4

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 (88) hide show
  1. package/index.ts +37 -35
  2. package/package.json +9 -12
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +31 -8
  6. package/src/client/enhance.ts +102 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +529 -371
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +163 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +114 -114
  14. package/src/dev/hmr-client.ts +185 -185
  15. package/src/dev/loader.ts +47 -47
  16. package/src/dev/paths.ts +14 -14
  17. package/src/dev/runtime-bundle.ts +52 -52
  18. package/src/dev/watcher.ts +47 -46
  19. package/src/env/dynamic-private.ts +19 -19
  20. package/src/env/dynamic-public.ts +22 -22
  21. package/src/env/index.ts +25 -25
  22. package/src/env/plugin.ts +19 -19
  23. package/src/env/private.ts +5 -5
  24. package/src/env/public.ts +7 -7
  25. package/src/env/typegen.ts +61 -61
  26. package/src/headers.ts +114 -114
  27. package/src/integrations/vite.ts +73 -73
  28. package/src/logger/index.ts +4 -4
  29. package/src/logger/instance.ts +6 -6
  30. package/src/logger/logger.ts +113 -113
  31. package/src/logger/request-middleware.ts +24 -24
  32. package/src/logger/transports.ts +117 -117
  33. package/src/logger/types.ts +39 -39
  34. package/src/rendering/head.ts +47 -47
  35. package/src/rendering/hydrate.ts +146 -119
  36. package/src/rendering/index.ts +573 -372
  37. package/src/rendering/ssrPlugin.ts +69 -69
  38. package/src/routing/manifest-gen.ts +55 -42
  39. package/src/routing/router.ts +135 -109
  40. package/src/routing/scanner.ts +187 -141
  41. package/src/routing/transform-routes.ts +102 -102
  42. package/src/sentinels/error.ts +52 -52
  43. package/src/sentinels/fail.ts +41 -41
  44. package/src/sentinels/redirect.ts +35 -35
  45. package/src/server/build.ts +255 -219
  46. package/src/server/context.ts +10 -10
  47. package/src/server/cookie-utils.ts +66 -66
  48. package/src/server/coordinator.ts +364 -356
  49. package/src/server/hooks.ts +114 -114
  50. package/src/server/index.ts +677 -658
  51. package/src/server/interactive.ts +56 -56
  52. package/src/server/plugins.ts +121 -120
  53. package/src/server/worker.ts +58 -58
  54. package/src/typegen/index.ts +389 -356
  55. package/src/types.ts +8 -4
  56. package/test/client-router.test.ts +295 -35
  57. package/test/context.test.ts +52 -52
  58. package/test/env.test.ts +70 -70
  59. package/test/exports.test.ts +37 -37
  60. package/test/fail.test.ts +46 -46
  61. package/test/headers.test.ts +100 -100
  62. package/test/hydration.test.ts +119 -119
  63. package/test/middleware.test.ts +223 -223
  64. package/test/preload.ts +5 -5
  65. package/test/redirect-error.test.ts +112 -112
  66. package/test/rendering.test.ts +728 -579
  67. package/test/routing.test.ts +194 -81
  68. package/test/scanning.test.ts +254 -200
  69. package/test/scope.test.ts +195 -195
  70. package/test/server.test.ts +354 -249
  71. package/test/streaming.test.ts +242 -125
  72. package/test/transform-routes.test.ts +87 -84
  73. package/test/typegen.test.ts +697 -682
  74. package/tsconfig.json +10 -10
  75. package/.grimoire/_routes.dom.js +0 -8
  76. package/.grimoire/_routes.hydrate.js +0 -8
  77. package/.grimoire/tsconfig.generated.json +0 -11
  78. package/.grimoire/types/ambient.d.ts +0 -59
  79. package/.grimoire/types/api/hello/$types.d.ts +0 -50
  80. package/.grimoire/types/api/items/$types.d.ts +0 -50
  81. package/.grimoire/types/echo/$types.d.ts +0 -50
  82. package/.grimoire/types/env-private.d.ts +0 -5
  83. package/.grimoire/types/env-public.d.ts +0 -5
  84. package/.grimoire/types/mixed/$types.d.ts +0 -50
  85. package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
  86. package/.grimoire/types/reject/$types.d.ts +0 -50
  87. package/public/__grimoire__/hydrate.js +0 -585
  88. package/public/__grimoire__/index.js +0 -490
@@ -1,371 +1,529 @@
1
- import {popHydrationNodes, pushHydrationNodes} from "@sigil-dev/runtime";
2
- import {withEffectScope} from "./scope";
3
-
4
- // ── Dependency tracking ──────────────────────────────────────────────────────
5
- const routeDeps = new Map<string, Set<string>>(); // pattern → dep keys
6
- let _collectingDeps: Set<string> | null = null;
7
-
8
- /**
9
- * Call from inside a load() function to register a dependency key.
10
- * When invalidate(key) is called, any route that depends on that key
11
- * will refetch if it's the current route.
12
- */
13
- export function depends(key: string): void {
14
- _collectingDeps?.add(key);
15
- }
16
-
17
- async function refetchCurrent(): Promise<void> {
18
- if (!lastState) return;
19
- await navigate(location.pathname, true); // true = replace, no pushState
20
- }
21
-
22
- export async function invalidate(...keys: string[]): Promise<void> {
23
- const current = lastState?.pattern;
24
- if (!current) return;
25
- const deps = routeDeps.get(current);
26
- if (!deps) return;
27
- if (keys.some(k => deps.has(k))) await refetchCurrent();
28
- }
29
-
30
- export async function invalidateAll(): Promise<void> {
31
- await refetchCurrent();
32
- }
33
-
34
- let routeMap: Record<
35
- string,
36
- ((props: any) => any) & {
37
- load?: (ctx: any) => Promise<any>;
38
- loading?: () => any;
39
- error?: (props: { error: unknown }) => any;
40
- }
41
- > = {};
42
- let layoutList: { path: string; component: (props: any) => any }[] = [];
43
- let disposeCurrentPage: (() => void) | null = null;
44
- let currentPath = location.pathname;
45
-
46
- // C1: Navigation hooks
47
- let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
48
- let onNavigateCb: ((url: URL) => void) | null = null;
49
- let afterNavigateCb: ((url: URL) => void) | null = null;
50
-
51
- // // HMR
52
- // (globalThis as any).__grimoire_routes__ = routeMap;
53
- // (globalThis as any).__grimoire_current_pattern__ = currentPath;
54
- // (globalThis as any).__grimoire_navigate__ = navigate;
55
-
56
- export async function hmrRerender(): Promise<void> {
57
- if (!lastState) {
58
- location.reload();
59
- return;
60
- }
61
- disposeCurrentPage?.();
62
- pushHydrationNodes([]);
63
- let rootNode: any;
64
- disposeCurrentPage = withEffectScope(() => {
65
- rootNode = buildRouteTree(lastState!);
66
- });
67
- popHydrationNodes();
68
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
69
- }
70
-
71
- // (globalThis as any).__grimoire_rerender__ = hmrRerender;
72
-
73
- export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
74
- beforeNavigateCb = cb;
75
- }
76
-
77
- export function onNavigate(cb: (url: URL) => void): void {
78
- onNavigateCb = cb;
79
- }
80
-
81
- export function afterNavigate(cb: (url: URL) => void): void {
82
- afterNavigateCb = cb;
83
- }
84
-
85
- // C2: Scroll restoration
86
- const scrollPositions = new Map<string, number>();
87
-
88
- function saveScrollPosition(): void {
89
- scrollPositions.set(currentPath, window.scrollY);
90
- }
91
-
92
- function restoreScrollPosition(path: string): void {
93
- const saved = scrollPositions.get(path);
94
- if (saved !== undefined) {
95
- requestAnimationFrame(() => window.scrollTo(0, saved));
96
- } else {
97
- requestAnimationFrame(() => window.scrollTo(0, 0));
98
- }
99
- }
100
-
101
- // C3: Preloading
102
- let preloadTimer: Timer | null = null;
103
-
104
- function setupPreload(): void {
105
- document.addEventListener("mouseover", (e) => {
106
- const a = (e.target as Element).closest("a");
107
- if (!a) return;
108
- const href = a.getAttribute("href");
109
- if (!href) return;
110
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
111
-
112
- const preloadData = a.hasAttribute("data-sigil-preload-data");
113
- const preloadCode = a.hasAttribute("data-sigil-preload-code");
114
- if (!preloadData && !preloadCode) return;
115
-
116
- if (preloadTimer) clearTimeout(preloadTimer);
117
- preloadTimer = setTimeout(() => {
118
- if (preloadCode) {
119
- const link = document.createElement("link");
120
- link.rel = "prefetch";
121
- link.href = href;
122
- document.head.appendChild(link);
123
- }
124
- if (preloadData) {
125
- fetch(href, {
126
- headers: {"x-grimoire-navigate": "1"},
127
- priority: "low",
128
- }).catch(() => {
129
- });
130
- }
131
- }, 80);
132
- });
133
-
134
- document.addEventListener("mouseout", (e) => {
135
- const a = (e.target as Element).closest("a");
136
- if (!a) return;
137
- if (preloadTimer) clearTimeout(preloadTimer);
138
- });
139
- }
140
-
141
- let lastState: {
142
- data: any;
143
- layoutData: any[];
144
- params: any;
145
- pattern: string;
146
- } | null = null;
147
-
148
- function buildRouteTree(state: typeof lastState): any {
149
- const {data, layoutData, params, pattern} = state!;
150
- const Page = routeMap[pattern];
151
- if (!Page) throw new Error(`no component for pattern ${pattern}`);
152
-
153
- const matchedLayouts = layoutList
154
- .filter(
155
- (l) =>
156
- l.path === "/" ||
157
- pattern === l.path ||
158
- pattern.startsWith(`${l.path}/`),
159
- )
160
- .sort((a, b) => a.path.length - b.path.length);
161
-
162
- let renderFn = () => {
163
- const pageNode = Page({data, params});
164
- const pageDiv = document.createElement("div");
165
- pageDiv.id = "grimoire-page";
166
- pageDiv.appendChild(pageNode);
167
- return pageDiv;
168
- };
169
-
170
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
171
- const LayoutComponent = matchedLayouts[i].component;
172
- const innerRender = renderFn;
173
- const currentLayoutData = layoutData?.[i];
174
- renderFn = () => {
175
- const childNode = innerRender();
176
- return LayoutComponent({
177
- data: currentLayoutData,
178
- params,
179
- children: childNode,
180
- });
181
- };
182
- }
183
-
184
- return renderFn();
185
- }
186
-
187
- function matchClientPattern(pattern: string, pathname: string): boolean {
188
- // haha pp and ph
189
- const pp = pattern.split("/").filter(Boolean);
190
- const ph = pathname.split("/").filter(Boolean);
191
- let pi = 0, pj = 0;
192
- while (pi < pp.length) {
193
- if (pp[pi]!.startsWith("*")) return true;
194
- if (pj >= ph.length) return false;
195
- if (!pp[pi]!.startsWith(":") && pp[pi] !== ph[pj]) return false;
196
- pi++;
197
- pj++;
198
- }
199
- return pj === ph.length;
200
- }
201
-
202
- function findPattern(pathname: string): string | null {
203
- for (const pattern of Object.keys(routeMap)) {
204
- if (matchClientPattern(pattern, pathname)) return pattern;
205
- }
206
- return null;
207
- }
208
-
209
- export async function navigate(path: string, replace = false) {
210
- const url = new URL(path, location.origin);
211
-
212
- if (beforeNavigateCb) {
213
- const shouldProceed = beforeNavigateCb(url);
214
- if (shouldProceed === false) return;
215
- }
216
- onNavigateCb?.(url);
217
- saveScrollPosition();
218
-
219
- // load the loading immediately
220
- const destPattern = findPattern(url.pathname);
221
- const DestPage = destPattern ? routeMap[destPattern] : null;
222
- if (DestPage?.loading) {
223
- disposeCurrentPage?.();
224
- disposeCurrentPage = null;
225
- pushHydrationNodes([]);
226
- let loadingNode: any;
227
- disposeCurrentPage = withEffectScope(() => {
228
- loadingNode = (DestPage as any).loading();
229
- });
230
- popHydrationNodes();
231
- // replace only grimoire-page, keeps layout stable during transition
232
- const pageEl = document.getElementById("grimoire-page");
233
- if (pageEl) pageEl.replaceChildren(loadingNode);
234
- else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
235
- }
236
-
237
- const res = await fetch(path, {headers: {"x-grimoire-navigate": "1"}});
238
- const contentType = res.headers.get("content-type") ?? "";
239
- if (!contentType.includes("application/json")) {
240
- window.location.href = path;
241
- return;
242
- }
243
- const json = await res.json();
244
- const {data, layoutData, params, pattern, head} = json;
245
- const Page = routeMap[pattern];
246
- if (!Page) {
247
- window.location.href = path;
248
- return;
249
- }
250
-
251
- let mergedData = data;
252
- if (Page.load) {
253
- try {
254
- _collectingDeps = new Set()
255
- const clientData = await Page.load({
256
- params,
257
- url,
258
- request: new Request(url),
259
- });
260
- routeDeps.set(pattern, _collectingDeps);
261
- _collectingDeps = null;
262
- mergedData = {...clientData, ...data};
263
- } catch (e: any) {
264
- _collectingDeps = null;
265
- if (e?.location) {
266
- window.location.href = e.location;
267
- return;
268
- }
269
- console.error("[grimoire] universal load error:", e);
270
- }
271
- }
272
-
273
- // track state for HMR rerender
274
- lastState = {data: mergedData, layoutData, params, pattern};
275
- (globalThis as any).__grimoire_current_pattern__ = pattern;
276
-
277
- disposeCurrentPage?.();
278
- disposeCurrentPage = null;
279
- pushHydrationNodes([]);
280
- let rootNode: any;
281
- disposeCurrentPage = withEffectScope(() => {
282
- try {
283
- rootNode = buildRouteTree(lastState!);
284
- } catch (e) {
285
- console.error(e);
286
- }
287
- });
288
- popHydrationNodes();
289
-
290
- updateHead(head);
291
- document.title = head?.title ?? document.title;
292
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
293
- currentPath = path;
294
-
295
- history[replace ? "replaceState" : "pushState"](null, "", path);
296
- restoreScrollPosition(path);
297
- afterNavigateCb?.(url);
298
- }
299
-
300
- export function initRouter(
301
- routes: Record<
302
- string,
303
- ((props: any) => any) & { load?: (ctx: any) => Promise<any> }
304
- >,
305
- layouts: any[],
306
- initialDispose?: () => void,
307
- ) {
308
- routeMap = routes;
309
- layoutList = layouts;
310
- disposeCurrentPage = initialDispose ?? null;
311
- currentPath = location.pathname;
312
-
313
- // set initial HMR state from SSR
314
- const stateEl = document.getElementById("__grimoire_state__");
315
- if (stateEl) {
316
- const state = JSON.parse(stateEl.textContent!);
317
- lastState = {
318
- data: state.data,
319
- layoutData: state.layoutData,
320
- params: state.params,
321
- pattern: state.pattern,
322
- };
323
- (globalThis as any).__grimoire_current_pattern__ = state.pattern;
324
- (globalThis as any).__grimoire_routes__ = routeMap;
325
- (globalThis as any).__grimoire_rerender__ = hmrRerender;
326
- (globalThis as any).__grimoire_navigate__ = (path: string) =>
327
- navigate(path);
328
- }
329
-
330
- saveScrollPosition();
331
- document.addEventListener("click", handleClick);
332
- window.addEventListener("popstate", () => {
333
- if (location.pathname !== currentPath) {
334
- saveScrollPosition();
335
- currentPath = location.pathname;
336
- navigate(location.pathname);
337
- }
338
- });
339
- setupPreload();
340
- }
341
-
342
- function updateHead(headHtml: string) {
343
- document
344
- .querySelectorAll("[data-grimoire-head]")
345
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
346
- .forEach((el) => el.remove());
347
- const parsed = headHtml
348
- ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
349
- : null;
350
- const incomingTitle = parsed?.querySelector("title");
351
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
352
- document.querySelectorAll("title").forEach((el) => el.remove());
353
- document.title = incomingTitle?.textContent ?? document.title;
354
- if (parsed) {
355
- for (const el of Array.from(parsed.head.children)) {
356
- if (el.tagName === "TITLE") continue;
357
- (el as HTMLElement).dataset.grimoireHead = "1";
358
- document.head.appendChild(el);
359
- }
360
- }
361
- }
362
-
363
- function handleClick(e: MouseEvent) {
364
- const a = (e.target as Element).closest("a");
365
- if (!a) return;
366
- const href = a.getAttribute("href");
367
- if (!href) return;
368
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
369
- e.preventDefault();
370
- navigate(href);
371
- }
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
+ let currentPath = location.pathname;
58
+
59
+ // C1: Navigation hooks
60
+ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
61
+ let onNavigateCb: ((url: URL) => void) | null = null;
62
+ let afterNavigateCb: ((url: URL) => void) | null = null;
63
+
64
+ // // HMR
65
+ // (globalThis as any).__grimoire_routes__ = routeMap;
66
+ // (globalThis as any).__grimoire_current_pattern__ = currentPath;
67
+ // (globalThis as any).__grimoire_navigate__ = navigate;
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
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
87
+ }
88
+
89
+ // (globalThis as any).__grimoire_rerender__ = hmrRerender;
90
+
91
+ export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
92
+ beforeNavigateCb = cb;
93
+ }
94
+
95
+ export function onNavigate(cb: (url: URL) => void): void {
96
+ onNavigateCb = cb;
97
+ }
98
+
99
+ export function afterNavigate(cb: (url: URL) => void): void {
100
+ afterNavigateCb = cb;
101
+ }
102
+
103
+ // C2: Scroll restoration
104
+ const scrollPositions = new Map<string, number>();
105
+
106
+ function saveScrollPosition(): void {
107
+ scrollPositions.set(currentPath, window.scrollY);
108
+ }
109
+
110
+ function restoreScrollPosition(path: string): void {
111
+ const y = scrollPositions.get(path) ?? 0;
112
+ window.scrollTo(0, y);
113
+ // re-assert after layout settles (late effects/images can shift content)
114
+ requestAnimationFrame(() => window.scrollTo(0, y));
115
+ }
116
+
117
+ function scrollToTop(): void {
118
+ window.scrollTo(0, 0);
119
+ requestAnimationFrame(() => window.scrollTo(0, 0));
120
+ }
121
+
122
+ // C3: Preloading
123
+ let preloadTimer: Timer | null = null;
124
+
125
+ function setupPreload(): void {
126
+ document.addEventListener("mouseover", (e) => {
127
+ const a = (e.target as Element).closest("a");
128
+ if (!a) return;
129
+ const href = a.getAttribute("href");
130
+ if (!href) return;
131
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
132
+ if (a.getAttribute("data-sigil-preload") === "off") return;
133
+
134
+ // Only prefetch links that resolve to a known client route — external
135
+ // pages and non-page endpoints (API routes, redirects) are skipped.
136
+ try {
137
+ const url = new URL(href, location.origin);
138
+ if (!findPattern(url.pathname)) return;
139
+ } catch {
140
+ return;
141
+ }
142
+
143
+ const preloadCode = a.hasAttribute("data-sigil-preload-code");
144
+
145
+ clearTimeout(preloadTimer);
146
+ preloadTimer = setTimeout(() => {
147
+ if (preloadCode) {
148
+ const link = document.createElement("link");
149
+ link.rel = "prefetch";
150
+ link.href = href;
151
+ document.head.appendChild(link);
152
+ }
153
+ // data prefetch is the default; -code is the explicit escalation
154
+ fetch(href, {
155
+ headers: { "x-grimoire-navigate": "1" },
156
+ redirect: "manual",
157
+ priority: "low",
158
+ }).catch(() => {});
159
+ }, 80);
160
+ });
161
+
162
+ document.addEventListener("mouseout", (e) => {
163
+ const a = (e.target as Element).closest("a");
164
+ if (!a) return;
165
+ clearTimeout(preloadTimer);
166
+ });
167
+ }
168
+
169
+ let lastState: {
170
+ data: any;
171
+ layoutData: any[];
172
+ params: any;
173
+ pattern: string;
174
+ } | null = null;
175
+
176
+ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
177
+ const { data, layoutData, params, pattern } = state!;
178
+ if (!Page) throw new Error(`no component for pattern ${pattern}`);
179
+
180
+ const matchedLayouts = layoutList
181
+ .filter(
182
+ (l) =>
183
+ l.path === "/" ||
184
+ pattern === l.path ||
185
+ pattern.startsWith(`${l.path}/`),
186
+ )
187
+ .sort((a, b) => a.path.length - b.path.length);
188
+
189
+ let renderFn = () => {
190
+ const pageNode = Page({ data, params });
191
+ const pageDiv = document.createElement("div");
192
+ pageDiv.id = "grimoire-page";
193
+ pageDiv.appendChild(pageNode);
194
+ return pageDiv;
195
+ };
196
+
197
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
198
+ const LayoutComponent = matchedLayouts[i].component;
199
+ const innerRender = renderFn;
200
+ const currentLayoutData = layoutData?.[i];
201
+ renderFn = () => {
202
+ const childNode = innerRender();
203
+ return LayoutComponent({
204
+ data: currentLayoutData,
205
+ params,
206
+ children: childNode,
207
+ });
208
+ };
209
+ }
210
+
211
+ return renderFn();
212
+ }
213
+
214
+ function matchClientPattern(pattern: string, pathname: string): boolean {
215
+ // haha pp and ph
216
+ const pp = pattern.split("/").filter(Boolean);
217
+ const ph = pathname.split("/").filter(Boolean);
218
+
219
+ // Depth-first walk; optional segments (:x?) try consuming one segment
220
+ // before consuming zero, mirroring the server's matchPattern.
221
+ function walk(pi: number, pj: number): boolean {
222
+ if (pi === pp.length) return pj === ph.length;
223
+ const part = pp[pi]!;
224
+ if (part.startsWith("*")) return true;
225
+ const optional = part.startsWith(":") && part.endsWith("?");
226
+ if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
227
+ if (!optional) {
228
+ if (pj >= ph.length) return false;
229
+ if (!part.startsWith(":") && part !== ph[pj]) return false;
230
+ return walk(pi + 1, pj + 1);
231
+ }
232
+ return walk(pi + 1, pj);
233
+ }
234
+
235
+ return walk(0, 0);
236
+ }
237
+
238
+ function findPattern(pathname: string): string | null {
239
+ for (const pattern of Object.keys(routeMap)) {
240
+ if (matchClientPattern(pattern, pathname)) return pattern;
241
+ }
242
+ return null;
243
+ }
244
+
245
+ export interface NavigateOptions {
246
+ /** "push" (default) adds a history entry, "replace" swaps the current one,
247
+ * "none" leaves history untouched (popstate — the browser already moved). */
248
+ history?: "push" | "replace" | "none";
249
+ }
250
+
251
+ // monotonically increasing id — a navigation aborts silently the moment a
252
+ // newer one starts, so overlapping navigations can't commit stale responses
253
+ let navigationId = 0;
254
+
255
+ export async function navigate(
256
+ path: string,
257
+ opts: NavigateOptions | boolean = {},
258
+ ) {
259
+ // boolean back-compat: navigate(path, true) meant "replace"
260
+ const historyMode =
261
+ typeof opts === "boolean"
262
+ ? opts
263
+ ? "replace"
264
+ : "push"
265
+ : (opts.history ?? "push");
266
+ const navId = ++navigationId;
267
+ const url = new URL(path, location.origin);
268
+
269
+ if (beforeNavigateCb) {
270
+ const shouldProceed = beforeNavigateCb(url);
271
+ if (shouldProceed === false) return;
272
+ }
273
+ onNavigateCb?.(url);
274
+ saveScrollPosition();
275
+
276
+ // load the loading immediately
277
+ const destPattern = findPattern(url.pathname);
278
+ const DestPage = destPattern ? await resolveRoute(destPattern) : null;
279
+ if (navId !== navigationId) return;
280
+ if (DestPage?.loading) {
281
+ disposeCurrentPage?.();
282
+ disposeCurrentPage = null;
283
+ pushHydrationNodes([]);
284
+ let loadingNode: any;
285
+ disposeCurrentPage = withEffectScope(() => {
286
+ loadingNode = (DestPage as any).loading();
287
+ });
288
+ popHydrationNodes();
289
+ // replace only grimoire-page, keeps layout stable during transition
290
+ const pageEl = document.getElementById("grimoire-page");
291
+ if (pageEl) pageEl.replaceChildren(loadingNode);
292
+ else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
293
+ }
294
+
295
+ const res = await fetch(path, {
296
+ headers: { "x-grimoire-navigate": "1" },
297
+ redirect: "manual",
298
+ });
299
+ if (navId !== navigationId) return;
300
+ const contentType = res.headers.get("content-type") ?? "";
301
+ if (!contentType.includes("application/json")) {
302
+ window.location.href = path;
303
+ return;
304
+ }
305
+ const json = await res.json();
306
+ if (navId !== navigationId) return;
307
+ const { data, layoutData, params, pattern, head, deps } = json;
308
+ const Page = await resolveRoute(pattern);
309
+ if (navId !== navigationId) return;
310
+ if (!Page) {
311
+ window.location.href = path;
312
+ return;
313
+ }
314
+
315
+ let mergedData = data;
316
+ if (Page.load) {
317
+ try {
318
+ startCollecting();
319
+ const clientData = await Page.load({
320
+ params,
321
+ url,
322
+ request: new Request(url),
323
+ // layout loads run server-side; their data arrives in layoutData —
324
+ // parent() merges it outermost-first, mirroring the server context
325
+ parent: async () =>
326
+ Object.assign(
327
+ {},
328
+ ...(Array.isArray(layoutData) ? layoutData : []).filter(
329
+ (d) => d && typeof d === "object",
330
+ ),
331
+ ),
332
+ });
333
+ // merge server-collected keys (page/layout server loads) with
334
+ // whatever this client-side load itself registered
335
+ setDeps(pattern, [
336
+ ...(Array.isArray(deps) ? deps : []),
337
+ ...stopCollecting(),
338
+ ]);
339
+ mergedData = { ...clientData, ...data };
340
+ } catch (e: unknown) {
341
+ stopCollecting();
342
+ if (e && typeof e === "object" && "location" in e) {
343
+ window.location.href = String(
344
+ (e as { location: unknown }).location,
345
+ );
346
+ return;
347
+ }
348
+ console.error("[grimoire] universal load error:", e);
349
+ }
350
+ if (navId !== navigationId) return;
351
+ } else if (Array.isArray(deps)) {
352
+ // no client-side load to run — the server's collected depends() keys
353
+ // (from +page.server.ts / +layout.server.ts) are the whole story
354
+ setDeps(pattern, deps);
355
+ }
356
+
357
+ // track state for HMR rerender
358
+ lastState = { data: mergedData, layoutData, params, pattern };
359
+ (globalThis as any).__grimoire_current_pattern__ = pattern;
360
+
361
+ disposeCurrentPage?.();
362
+ disposeCurrentPage = null;
363
+ pushHydrationNodes([]);
364
+ let rootNode: any;
365
+ disposeCurrentPage = withEffectScope(() => {
366
+ try {
367
+ rootNode = buildRouteTree(lastState!, Page);
368
+ } catch (e) {
369
+ console.error(e);
370
+ }
371
+ });
372
+ popHydrationNodes();
373
+
374
+ updateHead(head);
375
+ // View transitions: animate the swap when the browser supports it and the
376
+ // user hasn't asked for reduced motion. The callback must stay synchronous.
377
+ const doSwap = () => {
378
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
379
+ };
380
+ const doc = document as Document & {
381
+ startViewTransition?: (cb: () => void) => unknown;
382
+ };
383
+ if (
384
+ typeof doc.startViewTransition === "function" &&
385
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches
386
+ ) {
387
+ doc.startViewTransition(doSwap);
388
+ } else {
389
+ doSwap();
390
+ }
391
+ const isRefetch = url.pathname === currentPath;
392
+ currentPath = url.pathname;
393
+
394
+ if (historyMode !== "none") {
395
+ history[historyMode === "replace" ? "replaceState" : "pushState"](
396
+ null,
397
+ "",
398
+ path,
399
+ );
400
+ }
401
+ if (url.hash) {
402
+ const target = document.getElementById(url.hash.slice(1));
403
+ if (target) requestAnimationFrame(() => target.scrollIntoView());
404
+ else scrollToTop();
405
+ } else if (historyMode === "none") {
406
+ // popstate: the browser already moved through history — restore what
407
+ // we saved for this path (back/forward semantics)
408
+ restoreScrollPosition(url.pathname);
409
+ } else if (!isRefetch) {
410
+ // fresh navigation: the new page starts at the top
411
+ scrollToTop();
412
+ }
413
+ // same-path replace (invalidate/refetch): keep the current scroll
414
+ afterNavigateCb?.(url);
415
+ }
416
+
417
+ export interface RouterExtensions {
418
+ /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
419
+ matchers?: Record<string, (value: string) => boolean>;
420
+ /** Server-collected depends() keys per route pattern (from SSR state). */
421
+ deps?: Record<string, string[]>;
422
+ }
423
+
424
+ let paramMatcherFns: Record<string, (value: string) => boolean> = {};
425
+
426
+ export function initRouter(
427
+ routes: Record<string, RouteEntry>,
428
+ layouts: any[] = [],
429
+ initialDispose?: () => void,
430
+ ext?: RouterExtensions,
431
+ ) {
432
+ paramMatcherFns = ext?.matchers ?? {};
433
+ routeMap = routes;
434
+ layoutList = layouts;
435
+ disposeCurrentPage = initialDispose ?? null;
436
+ currentPath = location.pathname;
437
+
438
+ // the app owns scroll: the browser's automatic restoration fires after
439
+ // the router's own scroll and clobbers scroll-to-top / saved positions
440
+ if ("scrollRestoration" in history) history.scrollRestoration = "manual";
441
+ // set initial HMR state from SSR
442
+ const stateEl = document.getElementById("__grimoire_state__");
443
+ if (stateEl) {
444
+ const state = JSON.parse(stateEl.textContent!);
445
+ lastState = {
446
+ data: state.data,
447
+ layoutData: state.layoutData,
448
+ params: state.params,
449
+ pattern: state.pattern,
450
+ };
451
+ if (Array.isArray(state.deps)) {
452
+ setDeps(state.pattern, state.deps);
453
+ }
454
+ (globalThis as unknown as { __grimoire_current_pattern__: string }).__grimoire_current_pattern__ =
455
+ state.pattern;
456
+ (globalThis as unknown as { __grimoire_routes__: Record<string, RouteEntry> }).__grimoire_routes__ =
457
+ routeMap;
458
+ (globalThis as unknown as { __grimoire_rerender__: () => Promise<void> }).__grimoire_rerender__ =
459
+ hmrRerender;
460
+ (globalThis as unknown as {
461
+ __grimoire_navigate__: (path: string, replace?: boolean) => void;
462
+ }).__grimoire_navigate__ = (path: string, replace?: boolean) =>
463
+ navigate(path, replace ?? false);
464
+ }
465
+
466
+ saveScrollPosition();
467
+ document.addEventListener("click", handleClick);
468
+ window.addEventListener("popstate", () => {
469
+ if (location.pathname !== currentPath) {
470
+ // the browser already moved through history — render only, never
471
+ // push/replace here or the forward stack gets clobbered
472
+ navigate(location.pathname, { history: "none" });
473
+ }
474
+ });
475
+ setupPreload();
476
+ }
477
+
478
+ function updateHead(headHtml: string) {
479
+ document
480
+ .querySelectorAll("[data-grimoire-head]")
481
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
482
+ .forEach((el) => el.remove());
483
+ const parsed = headHtml
484
+ ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
485
+ : null;
486
+ const incomingTitle = parsed?.querySelector("title");
487
+ if (incomingTitle) {
488
+ // capture before removing <title> elements — reading document.title
489
+ // after removal returns "" and would wipe the title
490
+ const prevTitle = document.title;
491
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
492
+ document.querySelectorAll("title").forEach((el) => el.remove());
493
+ document.title = incomingTitle.textContent ?? prevTitle;
494
+ }
495
+ if (parsed) {
496
+ for (const el of Array.from(parsed.head.children)) {
497
+ if (el.tagName === "TITLE") continue;
498
+ (el as HTMLElement).dataset.grimoireHead = "1";
499
+ document.head.appendChild(el);
500
+ }
501
+ }
502
+ }
503
+
504
+ function handleClick(e: MouseEvent) {
505
+ // let the browser handle modified clicks (new tab/window/download)
506
+ if (e.defaultPrevented || e.button !== 0) return;
507
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
508
+ const a = (e.target as Element).closest("a");
509
+ if (!a) return;
510
+ if (a.target && a.target !== "_self") return;
511
+ if (a.hasAttribute("download")) return;
512
+ if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
513
+ const href = a.getAttribute("href");
514
+ if (!href) return;
515
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
516
+ // Only intercept clicks for known page routes — let server routes
517
+ // (redirects, API endpoints, etc.) navigate normally so the browser
518
+ // follows the response without the extra fetch-then-redirect dance.
519
+ try {
520
+ const url = new URL(href, location.origin);
521
+ if (!findPattern(url.pathname)) return;
522
+ // same-page anchor: native behavior scrolls to it, no re-render needed
523
+ if (url.pathname === location.pathname && url.hash) return;
524
+ } catch {
525
+ return;
526
+ }
527
+ e.preventDefault();
528
+ navigate(href);
529
+ }