@sigil-dev/grimoire 0.9.2 → 0.9.3
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 +35 -35
- package/package.json +8 -8
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +13 -7
- package/src/client/enhance.ts +98 -98
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +2 -2
- package/src/client/router.ts +445 -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 +98 -79
- package/src/rendering/index.ts +455 -372
- package/src/rendering/ssrPlugin.ts +69 -69
- package/src/routing/manifest-gen.ts +12 -11
- package/src/routing/router.ts +109 -109
- package/src/routing/scanner.ts +141 -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 +243 -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 +655 -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 +356 -356
- package/src/types.ts +4 -4
- package/test/client-router.test.ts +37 -31
- 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 +615 -579
- package/test/routing.test.ts +81 -81
- package/test/scanning.test.ts +200 -200
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +249 -249
- package/test/streaming.test.ts +125 -125
- package/test/transform-routes.test.ts +84 -84
- package/test/typegen.test.ts +682 -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,445 @@
|
|
|
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
|
-
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
async function refetchCurrent(): Promise<void> {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export async function invalidate(...keys: string[]): Promise<void> {
|
|
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
|
-
let
|
|
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
|
-
function
|
|
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
|
-
function
|
|
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 { 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, { history: "replace" });
|
|
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
|
+
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 = PageComponent | { __lazy: () => Promise<{ default: PageComponent }> };
|
|
42
|
+
|
|
43
|
+
let routeMap: Record<string, RouteEntry> = {};
|
|
44
|
+
const resolvedRoutes: Record<string, PageComponent> = {};
|
|
45
|
+
|
|
46
|
+
async function resolveRoute(pattern: string): Promise<PageComponent | null> {
|
|
47
|
+
const entry = routeMap[pattern];
|
|
48
|
+
if (!entry) return null;
|
|
49
|
+
// plain function: eager component or an HMR hot-swap — always wins over cache
|
|
50
|
+
if (typeof entry === "function") return entry;
|
|
51
|
+
return (resolvedRoutes[pattern] ??= (await entry.__lazy()).default);
|
|
52
|
+
}
|
|
53
|
+
let layoutList: { path: string; component: (props: any) => any }[] = [];
|
|
54
|
+
let disposeCurrentPage: (() => void) | null = null;
|
|
55
|
+
let currentPath = location.pathname;
|
|
56
|
+
|
|
57
|
+
// C1: Navigation hooks
|
|
58
|
+
let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
|
|
59
|
+
let onNavigateCb: ((url: URL) => void) | null = null;
|
|
60
|
+
let afterNavigateCb: ((url: URL) => void) | null = null;
|
|
61
|
+
|
|
62
|
+
// // HMR
|
|
63
|
+
// (globalThis as any).__grimoire_routes__ = routeMap;
|
|
64
|
+
// (globalThis as any).__grimoire_current_pattern__ = currentPath;
|
|
65
|
+
// (globalThis as any).__grimoire_navigate__ = navigate;
|
|
66
|
+
|
|
67
|
+
export async function hmrRerender(): Promise<void> {
|
|
68
|
+
if (!lastState) {
|
|
69
|
+
location.reload();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const Page = await resolveRoute(lastState.pattern);
|
|
73
|
+
if (!Page) {
|
|
74
|
+
location.reload();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
disposeCurrentPage?.();
|
|
78
|
+
pushHydrationNodes([]);
|
|
79
|
+
let rootNode: any;
|
|
80
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
81
|
+
rootNode = buildRouteTree(lastState!, Page);
|
|
82
|
+
});
|
|
83
|
+
popHydrationNodes();
|
|
84
|
+
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// (globalThis as any).__grimoire_rerender__ = hmrRerender;
|
|
88
|
+
|
|
89
|
+
export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
|
|
90
|
+
beforeNavigateCb = cb;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function onNavigate(cb: (url: URL) => void): void {
|
|
94
|
+
onNavigateCb = cb;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function afterNavigate(cb: (url: URL) => void): void {
|
|
98
|
+
afterNavigateCb = cb;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// C2: Scroll restoration
|
|
102
|
+
const scrollPositions = new Map<string, number>();
|
|
103
|
+
|
|
104
|
+
function saveScrollPosition(): void {
|
|
105
|
+
scrollPositions.set(currentPath, window.scrollY);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function restoreScrollPosition(path: string): void {
|
|
109
|
+
const saved = scrollPositions.get(path);
|
|
110
|
+
if (saved !== undefined) {
|
|
111
|
+
requestAnimationFrame(() => window.scrollTo(0, saved));
|
|
112
|
+
} else {
|
|
113
|
+
requestAnimationFrame(() => window.scrollTo(0, 0));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// C3: Preloading
|
|
118
|
+
let preloadTimer: Timer | null = null;
|
|
119
|
+
|
|
120
|
+
function setupPreload(): void {
|
|
121
|
+
document.addEventListener("mouseover", (e) => {
|
|
122
|
+
const a = (e.target as Element).closest("a");
|
|
123
|
+
if (!a) return;
|
|
124
|
+
const href = a.getAttribute("href");
|
|
125
|
+
if (!href) return;
|
|
126
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
|
|
127
|
+
|
|
128
|
+
const preloadData = a.hasAttribute("data-sigil-preload-data");
|
|
129
|
+
const preloadCode = a.hasAttribute("data-sigil-preload-code");
|
|
130
|
+
if (!preloadData && !preloadCode) return;
|
|
131
|
+
|
|
132
|
+
if (preloadTimer) clearTimeout(preloadTimer);
|
|
133
|
+
preloadTimer = setTimeout(() => {
|
|
134
|
+
if (preloadCode) {
|
|
135
|
+
const link = document.createElement("link");
|
|
136
|
+
link.rel = "prefetch";
|
|
137
|
+
link.href = href;
|
|
138
|
+
document.head.appendChild(link);
|
|
139
|
+
}
|
|
140
|
+
if (preloadData) {
|
|
141
|
+
fetch(href, {
|
|
142
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
143
|
+
redirect: "manual",
|
|
144
|
+
priority: "low",
|
|
145
|
+
}).catch(() => {});
|
|
146
|
+
}
|
|
147
|
+
}, 80);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
document.addEventListener("mouseout", (e) => {
|
|
151
|
+
const a = (e.target as Element).closest("a");
|
|
152
|
+
if (!a) return;
|
|
153
|
+
if (preloadTimer) clearTimeout(preloadTimer);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let lastState: {
|
|
158
|
+
data: any;
|
|
159
|
+
layoutData: any[];
|
|
160
|
+
params: any;
|
|
161
|
+
pattern: string;
|
|
162
|
+
} | null = null;
|
|
163
|
+
|
|
164
|
+
function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
|
|
165
|
+
const { data, layoutData, params, pattern } = state!;
|
|
166
|
+
if (!Page) throw new Error(`no component for pattern ${pattern}`);
|
|
167
|
+
|
|
168
|
+
const matchedLayouts = layoutList
|
|
169
|
+
.filter(
|
|
170
|
+
(l) =>
|
|
171
|
+
l.path === "/" ||
|
|
172
|
+
pattern === l.path ||
|
|
173
|
+
pattern.startsWith(`${l.path}/`),
|
|
174
|
+
)
|
|
175
|
+
.sort((a, b) => a.path.length - b.path.length);
|
|
176
|
+
|
|
177
|
+
let renderFn = () => {
|
|
178
|
+
const pageNode = Page({ data, params });
|
|
179
|
+
const pageDiv = document.createElement("div");
|
|
180
|
+
pageDiv.id = "grimoire-page";
|
|
181
|
+
pageDiv.appendChild(pageNode);
|
|
182
|
+
return pageDiv;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
for (let i = matchedLayouts.length - 1; i >= 0; i--) {
|
|
186
|
+
const LayoutComponent = matchedLayouts[i].component;
|
|
187
|
+
const innerRender = renderFn;
|
|
188
|
+
const currentLayoutData = layoutData?.[i];
|
|
189
|
+
renderFn = () => {
|
|
190
|
+
const childNode = innerRender();
|
|
191
|
+
return LayoutComponent({
|
|
192
|
+
data: currentLayoutData,
|
|
193
|
+
params,
|
|
194
|
+
children: childNode,
|
|
195
|
+
});
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return renderFn();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function matchClientPattern(pattern: string, pathname: string): boolean {
|
|
203
|
+
// haha pp and ph
|
|
204
|
+
const pp = pattern.split("/").filter(Boolean);
|
|
205
|
+
const ph = pathname.split("/").filter(Boolean);
|
|
206
|
+
let pi = 0,
|
|
207
|
+
pj = 0;
|
|
208
|
+
while (pi < pp.length) {
|
|
209
|
+
if (pp[pi]!.startsWith("*")) return true;
|
|
210
|
+
if (pj >= ph.length) return false;
|
|
211
|
+
if (!pp[pi]!.startsWith(":") && pp[pi] !== ph[pj]) return false;
|
|
212
|
+
pi++;
|
|
213
|
+
pj++;
|
|
214
|
+
}
|
|
215
|
+
return pj === ph.length;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function findPattern(pathname: string): string | null {
|
|
219
|
+
for (const pattern of Object.keys(routeMap)) {
|
|
220
|
+
if (matchClientPattern(pattern, pathname)) return pattern;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface NavigateOptions {
|
|
226
|
+
/** "push" (default) adds a history entry, "replace" swaps the current one,
|
|
227
|
+
* "none" leaves history untouched (popstate — the browser already moved). */
|
|
228
|
+
history?: "push" | "replace" | "none";
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// monotonically increasing id — a navigation aborts silently the moment a
|
|
232
|
+
// newer one starts, so overlapping navigations can't commit stale responses
|
|
233
|
+
let navigationId = 0;
|
|
234
|
+
|
|
235
|
+
export async function navigate(
|
|
236
|
+
path: string,
|
|
237
|
+
opts: NavigateOptions | boolean = {},
|
|
238
|
+
) {
|
|
239
|
+
// boolean back-compat: navigate(path, true) meant "replace"
|
|
240
|
+
const historyMode =
|
|
241
|
+
typeof opts === "boolean"
|
|
242
|
+
? opts
|
|
243
|
+
? "replace"
|
|
244
|
+
: "push"
|
|
245
|
+
: (opts.history ?? "push");
|
|
246
|
+
const navId = ++navigationId;
|
|
247
|
+
const url = new URL(path, location.origin);
|
|
248
|
+
|
|
249
|
+
if (beforeNavigateCb) {
|
|
250
|
+
const shouldProceed = beforeNavigateCb(url);
|
|
251
|
+
if (shouldProceed === false) return;
|
|
252
|
+
}
|
|
253
|
+
onNavigateCb?.(url);
|
|
254
|
+
saveScrollPosition();
|
|
255
|
+
|
|
256
|
+
// load the loading immediately
|
|
257
|
+
const destPattern = findPattern(url.pathname);
|
|
258
|
+
const DestPage = destPattern ? await resolveRoute(destPattern) : null;
|
|
259
|
+
if (navId !== navigationId) return;
|
|
260
|
+
if (DestPage?.loading) {
|
|
261
|
+
disposeCurrentPage?.();
|
|
262
|
+
disposeCurrentPage = null;
|
|
263
|
+
pushHydrationNodes([]);
|
|
264
|
+
let loadingNode: any;
|
|
265
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
266
|
+
loadingNode = (DestPage as any).loading();
|
|
267
|
+
});
|
|
268
|
+
popHydrationNodes();
|
|
269
|
+
// replace only grimoire-page, keeps layout stable during transition
|
|
270
|
+
const pageEl = document.getElementById("grimoire-page");
|
|
271
|
+
if (pageEl) pageEl.replaceChildren(loadingNode);
|
|
272
|
+
else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" }, redirect: "manual" });
|
|
276
|
+
if (navId !== navigationId) return;
|
|
277
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
278
|
+
if (!contentType.includes("application/json")) {
|
|
279
|
+
window.location.href = path;
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const json = await res.json();
|
|
283
|
+
if (navId !== navigationId) return;
|
|
284
|
+
const { data, layoutData, params, pattern, head } = json;
|
|
285
|
+
const Page = await resolveRoute(pattern);
|
|
286
|
+
if (navId !== navigationId) return;
|
|
287
|
+
if (!Page) {
|
|
288
|
+
window.location.href = path;
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
let mergedData = data;
|
|
293
|
+
if (Page.load) {
|
|
294
|
+
try {
|
|
295
|
+
_collectingDeps = new Set();
|
|
296
|
+
const clientData = await Page.load({
|
|
297
|
+
params,
|
|
298
|
+
url,
|
|
299
|
+
request: new Request(url),
|
|
300
|
+
});
|
|
301
|
+
routeDeps.set(pattern, _collectingDeps);
|
|
302
|
+
_collectingDeps = null;
|
|
303
|
+
mergedData = { ...clientData, ...data };
|
|
304
|
+
} catch (e: any) {
|
|
305
|
+
_collectingDeps = null;
|
|
306
|
+
if (e?.location) {
|
|
307
|
+
window.location.href = e.location;
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
console.error("[grimoire] universal load error:", e);
|
|
311
|
+
}
|
|
312
|
+
if (navId !== navigationId) return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// track state for HMR rerender
|
|
316
|
+
lastState = { data: mergedData, layoutData, params, pattern };
|
|
317
|
+
(globalThis as any).__grimoire_current_pattern__ = pattern;
|
|
318
|
+
|
|
319
|
+
disposeCurrentPage?.();
|
|
320
|
+
disposeCurrentPage = null;
|
|
321
|
+
pushHydrationNodes([]);
|
|
322
|
+
let rootNode: any;
|
|
323
|
+
disposeCurrentPage = withEffectScope(() => {
|
|
324
|
+
try {
|
|
325
|
+
rootNode = buildRouteTree(lastState!, Page);
|
|
326
|
+
} catch (e) {
|
|
327
|
+
console.error(e);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
popHydrationNodes();
|
|
331
|
+
|
|
332
|
+
updateHead(head);
|
|
333
|
+
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
334
|
+
currentPath = url.pathname;
|
|
335
|
+
|
|
336
|
+
if (historyMode !== "none") {
|
|
337
|
+
history[historyMode === "replace" ? "replaceState" : "pushState"](
|
|
338
|
+
null,
|
|
339
|
+
"",
|
|
340
|
+
path,
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
if (url.hash) {
|
|
344
|
+
const target = document.getElementById(url.hash.slice(1));
|
|
345
|
+
if (target) requestAnimationFrame(() => target.scrollIntoView());
|
|
346
|
+
else restoreScrollPosition(url.pathname);
|
|
347
|
+
} else {
|
|
348
|
+
restoreScrollPosition(url.pathname);
|
|
349
|
+
}
|
|
350
|
+
afterNavigateCb?.(url);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function initRouter(
|
|
354
|
+
routes: Record<string, RouteEntry>,
|
|
355
|
+
layouts: any[] = [],
|
|
356
|
+
initialDispose?: () => void,
|
|
357
|
+
) {
|
|
358
|
+
routeMap = routes;
|
|
359
|
+
layoutList = layouts;
|
|
360
|
+
disposeCurrentPage = initialDispose ?? null;
|
|
361
|
+
currentPath = location.pathname;
|
|
362
|
+
|
|
363
|
+
// set initial HMR state from SSR
|
|
364
|
+
const stateEl = document.getElementById("__grimoire_state__");
|
|
365
|
+
if (stateEl) {
|
|
366
|
+
const state = JSON.parse(stateEl.textContent!);
|
|
367
|
+
lastState = {
|
|
368
|
+
data: state.data,
|
|
369
|
+
layoutData: state.layoutData,
|
|
370
|
+
params: state.params,
|
|
371
|
+
pattern: state.pattern,
|
|
372
|
+
};
|
|
373
|
+
(globalThis as any).__grimoire_current_pattern__ = state.pattern;
|
|
374
|
+
(globalThis as any).__grimoire_routes__ = routeMap;
|
|
375
|
+
(globalThis as any).__grimoire_rerender__ = hmrRerender;
|
|
376
|
+
(globalThis as any).__grimoire_navigate__ = (
|
|
377
|
+
path: string,
|
|
378
|
+
replace?: boolean,
|
|
379
|
+
) => navigate(path, replace ?? false);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
saveScrollPosition();
|
|
383
|
+
document.addEventListener("click", handleClick);
|
|
384
|
+
window.addEventListener("popstate", () => {
|
|
385
|
+
if (location.pathname !== currentPath) {
|
|
386
|
+
// the browser already moved through history — render only, never
|
|
387
|
+
// push/replace here or the forward stack gets clobbered
|
|
388
|
+
navigate(location.pathname, { history: "none" });
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
setupPreload();
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function updateHead(headHtml: string) {
|
|
395
|
+
document
|
|
396
|
+
.querySelectorAll("[data-grimoire-head]")
|
|
397
|
+
//biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
|
|
398
|
+
.forEach((el) => el.remove());
|
|
399
|
+
const parsed = headHtml
|
|
400
|
+
? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
|
|
401
|
+
: null;
|
|
402
|
+
const incomingTitle = parsed?.querySelector("title");
|
|
403
|
+
if (incomingTitle) {
|
|
404
|
+
// capture before removing <title> elements — reading document.title
|
|
405
|
+
// after removal returns "" and would wipe the title
|
|
406
|
+
const prevTitle = document.title;
|
|
407
|
+
//biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
|
|
408
|
+
document.querySelectorAll("title").forEach((el) => el.remove());
|
|
409
|
+
document.title = incomingTitle.textContent ?? prevTitle;
|
|
410
|
+
}
|
|
411
|
+
if (parsed) {
|
|
412
|
+
for (const el of Array.from(parsed.head.children)) {
|
|
413
|
+
if (el.tagName === "TITLE") continue;
|
|
414
|
+
(el as HTMLElement).dataset.grimoireHead = "1";
|
|
415
|
+
document.head.appendChild(el);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function handleClick(e: MouseEvent) {
|
|
421
|
+
// let the browser handle modified clicks (new tab/window/download)
|
|
422
|
+
if (e.defaultPrevented || e.button !== 0) return;
|
|
423
|
+
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
|
424
|
+
const a = (e.target as Element).closest("a");
|
|
425
|
+
if (!a) return;
|
|
426
|
+
if (a.target && a.target !== "_self") return;
|
|
427
|
+
if (a.hasAttribute("download")) return;
|
|
428
|
+
if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
|
|
429
|
+
const href = a.getAttribute("href");
|
|
430
|
+
if (!href) return;
|
|
431
|
+
if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
|
|
432
|
+
// Only intercept clicks for known page routes — let server routes
|
|
433
|
+
// (redirects, API endpoints, etc.) navigate normally so the browser
|
|
434
|
+
// follows the response without the extra fetch-then-redirect dance.
|
|
435
|
+
try {
|
|
436
|
+
const url = new URL(href, location.origin);
|
|
437
|
+
if (!findPattern(url.pathname)) return;
|
|
438
|
+
// same-page anchor: native behavior scrolls to it, no re-render needed
|
|
439
|
+
if (url.pathname === location.pathname && url.hash) return;
|
|
440
|
+
} catch {
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
e.preventDefault();
|
|
444
|
+
navigate(href);
|
|
445
|
+
}
|