@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.
- package/index.ts +37 -35
- package/package.json +9 -12
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +31 -8
- package/src/client/enhance.ts +102 -98
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +5 -5
- package/src/client/router.ts +529 -371
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +163 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +114 -114
- package/src/dev/hmr-client.ts +185 -185
- package/src/dev/loader.ts +47 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/watcher.ts +47 -46
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +47 -47
- package/src/rendering/hydrate.ts +146 -119
- package/src/rendering/index.ts +573 -372
- package/src/rendering/ssrPlugin.ts +69 -69
- package/src/routing/manifest-gen.ts +55 -42
- package/src/routing/router.ts +135 -109
- package/src/routing/scanner.ts +187 -141
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +255 -219
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +364 -356
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +677 -658
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -120
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +389 -356
- package/src/types.ts +8 -4
- package/test/client-router.test.ts +295 -35
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +70 -70
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +728 -579
- package/test/routing.test.ts +194 -81
- package/test/scanning.test.ts +254 -200
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +354 -249
- package/test/streaming.test.ts +242 -125
- package/test/transform-routes.test.ts +87 -84
- package/test/typegen.test.ts +697 -682
- package/tsconfig.json +10 -10
- package/.grimoire/_routes.dom.js +0 -8
- package/.grimoire/_routes.hydrate.js +0 -8
- package/.grimoire/tsconfig.generated.json +0 -11
- package/.grimoire/types/ambient.d.ts +0 -59
- package/.grimoire/types/api/hello/$types.d.ts +0 -50
- package/.grimoire/types/api/items/$types.d.ts +0 -50
- package/.grimoire/types/echo/$types.d.ts +0 -50
- package/.grimoire/types/env-private.d.ts +0 -5
- package/.grimoire/types/env-public.d.ts +0 -5
- package/.grimoire/types/mixed/$types.d.ts +0 -50
- package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
- package/.grimoire/types/reject/$types.d.ts +0 -50
- package/public/__grimoire__/hydrate.js +0 -585
- package/public/__grimoire__/index.js +0 -490
package/src/client/router.ts
CHANGED
|
@@ -1,371 +1,529 @@
|
|
|
1
|
-
import {popHydrationNodes, pushHydrationNodes} from "@sigil-dev/runtime";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function invalidateAll(): Promise<void> {
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
//
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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
|
+
}
|