@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.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.
Files changed (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
@@ -1,723 +1,804 @@
1
- import { log } from "evlog";
2
- import type React from "react";
3
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
- import { parseDeferredNdjson } from "../../shared/deferred-ndjson.ts";
5
- import { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
6
- import {
7
- generateHistoryKey,
8
- getHistoryKey,
9
- isStaleDeployResponse,
10
- SCROLL_STORAGE_KEY,
11
- saveScrollPosition,
12
- } from "./history.ts";
13
- import {
14
- applyRevalidateHeader,
15
- normalizeHref,
16
- shouldAutoRefreshPath,
17
- shouldInterceptClick,
18
- shouldRefetch,
19
- stripHashFromHref,
20
- toLogical,
21
- } from "./link-utils.ts";
22
- import {
23
- buildDataEndpoint,
24
- buildNotFoundPageElement,
25
- classifySpaResponse,
26
- detectStaticMode,
27
- parsePageResponse,
28
- } from "./spa-response.ts";
29
- import type {
30
- CacheEntry,
31
- ClientSegmentBoundary,
32
- LoadedClientRoute,
33
- RouterProviderProps,
34
- RouterState,
35
- } from "./types.ts";
36
-
37
- export function setPrefetchCacheEntry(
38
- cache: Map<string, CacheEntry>,
39
- href: string,
40
- entry: CacheEntry,
41
- maxSize: number
42
- ): void {
43
- if (cache.has(href)) {
44
- cache.delete(href);
45
- }
46
- cache.set(href, entry);
47
- if (cache.size > maxSize) {
48
- const oldest = cache.keys().next().value;
49
- if (typeof oldest === "string") {
50
- cache.delete(oldest);
51
- }
52
- }
53
- }
54
-
55
- export function RouterProvider({
56
- routes,
57
- root,
58
- initialMatch,
59
- initialData,
60
- initialDigest,
61
- initialNotFound,
62
- autoRefresh,
63
- basePath,
64
- defaultPreload,
65
- defaultPreloadDelay,
66
- defaultPreloadStaleTime,
67
- prefetchCacheSize,
68
- }: RouterProviderProps): React.ReactElement {
69
- // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
70
- // the provider boots into the inline not-found UI.
71
- const [state, setState] = useState<RouterState>(() => ({
72
- match: initialMatch,
73
- data: initialData,
74
- notFound: initialNotFound,
75
- }));
76
- const [isNavigating, setIsNavigating] = useState(false);
77
- // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
78
- // detection works with route patterns that never include the basePath prefix.
79
- const [currentHref, setCurrentHref] = useState<string>(() => {
80
- if (typeof window === "undefined") {
81
- return "/";
82
- }
83
- return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
84
- });
85
- const prefetchCache = useRef(new Map<string, CacheEntry>());
86
- /** Monotonic counter to discard stale navigations (race condition guard). */
87
- const navVersion = useRef(0);
88
- /**
89
- * AbortController for the current navigation. Cancelled when a newer
90
- * navigation starts so any in-flight `parseDeferredNdjson` releases its
91
- * pending deferred promises (resolvers reject with `AbortError`) and frees
92
- * the underlying stream reader.
93
- */
94
- const navAbortRef = useRef<AbortController | null>(null);
95
- /**
96
- * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
97
- * This replaces the fragile double-requestAnimationFrame pattern with a render-
98
- * synchronous scroll that fires immediately after React commits the new route.
99
- */
100
- const pendingScrollRef = useRef<
101
- { type: "restore"; key: string } | { type: "reset"; href: string } | null
102
- >(null);
103
- /**
104
- * Tracks the last successfully rendered match for use in the no-route 404 path.
105
- * `null` on the initial render when the URL didn't match any route and the
106
- * provider booted directly into the not-found state; flips to a real match as
107
- * soon as the user navigates away via `navigate()` or the back button.
108
- */
109
- const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
110
- /**
111
- * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
112
- * fetch URL: runtime `/_furin/data` for SSR/ISR/dev, per-route
113
- * `__furin_data.ndjson` for static exports.
114
- */
115
- const staticModeRef = useRef<boolean>(detectStaticMode());
116
-
117
- /**
118
- * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
119
- * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
120
- * handles it — the root `not-found.tsx` (depth 0) is the correct component to
121
- * render inline instead of doing a full-page reload.
122
- */
123
- const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
124
- for (const route of routes) {
125
- const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
126
- if (depth0) {
127
- return [depth0];
128
- }
129
- }
130
- return;
131
- }, [routes]);
132
-
133
- /**
134
- * Resolves the RouterState when no client-side route matched the URL. The
135
- * server's `renderRootNotFound` produced the 404 HTML; we fetch the physical
136
- * URL to detect the `__furinStatus: 404` signal and render the 404 UI inline
137
- * (rather than triggering a jarring full-page reload).
138
- */
139
- const resolveNoMatchState = useCallback(
140
- async (physicalHref: string, signal: AbortSignal | undefined): Promise<RouterState | null> => {
141
- const res = await fetch(physicalHref, { signal });
142
- if (isStaleDeployResponse(res)) {
143
- window.location.href = physicalHref;
144
- return null;
145
- }
146
- const { data, finalHref, title } = await parsePageResponse(res, basePath);
147
- const kind = classifySpaResponse(res.status, data);
148
- if (kind.kind !== "not-found") {
149
- return null;
150
- }
151
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
152
- return {
153
- match: currentMatchRef.current,
154
- data: cleanData,
155
- title,
156
- finalHref,
157
- notFound: kind.error,
158
- notFoundBoundaries: rootBoundaries,
159
- };
160
- },
161
- [basePath, rootBoundaries]
162
- );
163
-
164
- const fetchPageState = useCallback(
165
- async (
166
- rawLogicalHref: string,
167
- signal: AbortSignal | undefined
168
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
169
- ): Promise<RouterState | null> => {
170
- // Normalize trailing slashes so "/docs/routing/" matches the route
171
- // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
172
- // redirect to or serve URLs with a trailing slash.
173
- const logicalHref = normalizeHref(rawLogicalHref);
174
- try {
175
- // Physical href: what the browser/server actually receives.
176
- // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
177
- const physicalHref = basePath + logicalHref;
178
- const url = new URL(physicalHref, window.location.origin);
179
- // Route matching always uses the LOGICAL pathname (basePath stripped).
180
- const logicalPathname = toLogical(url.pathname, basePath);
181
- const match = routes.find((r) => r.regex.test(logicalPathname));
182
- if (!match) {
183
- return await resolveNoMatchState(physicalHref, signal);
184
- }
185
-
186
- // ── NDJSON data endpoint + JS chunk load (parallel) ──────────────────
187
- const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
188
- const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
189
-
190
- // Stale-deploy detection: force a full page reload to pick up the new bundle.
191
- if (isStaleDeployResponse(res)) {
192
- window.location.href = physicalHref;
193
- return null;
194
- }
195
-
196
- const body = res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() });
197
- let parsed: {
198
- syncData: Record<string, unknown>;
199
- deferredPromises: Record<string, Promise<unknown>>;
200
- };
201
- try {
202
- parsed = await parseDeferredNdjson(body, signal);
203
- } catch (parseErr) {
204
- log.warn({
205
- action: "navigate_server_error",
206
- href: physicalHref,
207
- status: res.status,
208
- error: String(parseErr),
209
- });
210
- return null;
211
- }
212
- const { syncData, deferredPromises } = parsed;
213
-
214
- // Special fields injected by the server into syncData:
215
- // __furinStatus — 404 signal
216
- // __furinNotFound — not-found payload
217
- // __furinRedirect — server-side redirect target (logical path)
218
- // __furinError — error sentinel (digest, message, status)
219
- // __furinTitle — document title resolved server-side from head()
220
- const {
221
- __furinStatus,
222
- __furinNotFound,
223
- __furinRedirect,
224
- __furinError,
225
- __furinTitle,
226
- ...cleanSyncData
227
- } = syncData as {
228
- __furinStatus?: number;
229
- __furinNotFound?: { data?: unknown; message?: string };
230
- __furinRedirect?: string;
231
- __furinError?: { digest: string; message: string; status: number };
232
- __furinTitle?: string;
233
- [key: string]: unknown;
234
- };
235
-
236
- const finalHref: string | undefined =
237
- typeof __furinRedirect === "string" ? __furinRedirect : undefined;
238
-
239
- // Merge sync data + deferred Promises.
240
- const data = { ...cleanSyncData, ...deferredPromises };
241
-
242
- const title = typeof __furinTitle === "string" ? __furinTitle : "";
243
-
244
- const loadedMatch: LoadedClientRoute = {
245
- ...match,
246
- component: loadedMod.default.component,
247
- pageRoute: loadedMod.default._route,
248
- segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries,
249
- };
250
-
251
- // Loader threw a non-redirect Response (or an Error).
252
- if (__furinError) {
253
- return {
254
- match: loadedMatch,
255
- data: {},
256
- title,
257
- finalHref,
258
- error: __furinError,
259
- };
260
- }
261
-
262
- // Non-2xx without sentinel and not 404 → opaque server error.
263
- if (!res.ok && res.status !== 404) {
264
- log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
265
- return null;
266
- }
267
-
268
- if (__furinStatus === 404) {
269
- return {
270
- match: loadedMatch,
271
- data,
272
- title,
273
- finalHref,
274
- notFound: (__furinNotFound as { data?: unknown; message?: string }) ?? {},
275
- };
276
- }
277
-
278
- // Server-side redirect: do not mount the pre-redirect route.
279
- if (finalHref) {
280
- return { match: null, data, title, finalHref };
281
- }
282
-
283
- return { match: loadedMatch, data, title, finalHref };
284
- } catch (err: unknown) {
285
- log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
286
- return null;
287
- }
288
- },
289
- [routes, basePath, resolveNoMatchState]
290
- );
291
-
292
- const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
293
- const normalizedPath = stripHashFromHref(path);
294
-
295
- if (type === "page") {
296
- for (const key of [...prefetchCache.current.keys()]) {
297
- if (stripHashFromHref(key) === normalizedPath) {
298
- prefetchCache.current.delete(key);
299
- }
300
- }
301
- return;
302
- }
303
-
304
- // layout: prefix match — evict the path itself and all nested children
305
- const prefix =
306
- normalizedPath === "/" || normalizedPath.endsWith("/")
307
- ? normalizedPath
308
- : `${normalizedPath}/`;
309
- for (const key of [...prefetchCache.current.keys()]) {
310
- const normalizedKey = stripHashFromHref(key);
311
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
312
- prefetchCache.current.delete(key);
313
- }
314
- }
315
- }, []);
316
-
317
- const prefetch = useCallback(
318
- (href: string, opts: { staleTime?: number } | undefined) => {
319
- const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
320
- const existing = prefetchCache.current.get(href);
321
- if (existing && !shouldRefetch(existing)) {
322
- return;
323
- }
324
- setPrefetchCacheEntry(
325
- prefetchCache.current,
326
- href,
327
- {
328
- promise: fetchPageState(href, undefined),
329
- createdAt: Date.now(),
330
- staleTime,
331
- },
332
- prefetchCacheSize
333
- );
334
- },
335
- [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
336
- );
337
-
338
- /** Loads the RouterState for a redirect target, respecting the nav version. */
339
- async function resolveRedirectState(
340
- redirectLogical: string,
341
- myVersion: number,
342
- signal: AbortSignal | undefined
343
- ): Promise<RouterState | null> {
344
- const cached = prefetchCache.current.get(redirectLogical);
345
- const state =
346
- cached && !shouldRefetch(cached)
347
- ? await cached.promise
348
- : await fetchPageState(redirectLogical, signal);
349
- if (navVersion.current !== myVersion) {
350
- return null;
351
- }
352
- return state;
353
- }
354
-
355
- const navigate = useCallback(
356
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — redirect follow, history management, and scroll handling require this depth
357
- async function navigateTo(
358
- rawLogicalHref: string,
359
- opts: { replace?: boolean; resetScroll?: boolean } | undefined
360
- ) {
361
- const logicalHref = normalizeHref(rawLogicalHref);
362
- const myVersion = ++navVersion.current;
363
- navAbortRef.current?.abort();
364
- const navAbort = new AbortController();
365
- navAbortRef.current = navAbort;
366
- const navSignal = navAbort.signal;
367
- setIsNavigating(true);
368
- try {
369
- const cached = prefetchCache.current.get(logicalHref);
370
- let newState =
371
- cached && !shouldRefetch(cached)
372
- ? await cached.promise
373
- : await fetchPageState(logicalHref, navSignal);
374
- if (navVersion.current !== myVersion) {
375
- return;
376
- }
377
- if (newState && (!cached || shouldRefetch(cached))) {
378
- setPrefetchCacheEntry(
379
- prefetchCache.current,
380
- logicalHref,
381
- {
382
- promise: Promise.resolve(newState),
383
- createdAt: Date.now(),
384
- staleTime: defaultPreloadStaleTime,
385
- },
386
- prefetchCacheSize
387
- );
388
- }
389
- if (!newState) {
390
- log.warn({
391
- action: "navigate_fallback",
392
- href: logicalHref,
393
- reason: "prefetch_returned_null",
394
- });
395
- window.location.href = basePath + logicalHref;
396
- return;
397
- }
398
-
399
- // Server-side redirect: replace current history entry and load target
400
- let redirectLogical: string | undefined;
401
- if (newState.finalHref && !newState.match && !newState.notFound) {
402
- redirectLogical = normalizeHref(newState.finalHref);
403
- const redirectPhysical = basePath + redirectLogical;
404
- window.history.replaceState(
405
- {
406
- ...((history.state as object) ?? {}),
407
- _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
408
- },
409
- "",
410
- redirectPhysical
411
- );
412
- setCurrentHref(redirectLogical);
413
- const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
414
- if (!redirectState) {
415
- if (navVersion.current === myVersion) {
416
- window.location.href = redirectPhysical;
417
- }
418
- return;
419
- }
420
- newState = redirectState;
421
- }
422
-
423
- currentMatchRef.current = newState.match;
424
- setState(newState);
425
- if (newState.title) {
426
- document.title = newState.title;
427
- }
428
- const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
429
- const physicalEffective = basePath + effectiveLogical;
430
- if (opts?.replace) {
431
- window.history.replaceState(
432
- {
433
- ...((history.state as object) ?? {}),
434
- _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
435
- },
436
- "",
437
- physicalEffective
438
- );
439
- } else {
440
- const currentKey = getHistoryKey(history.state);
441
- if (currentKey) {
442
- saveScrollPosition(currentKey);
443
- }
444
- window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
445
- }
446
- const effectiveUrl = new URL(physicalEffective, window.location.origin);
447
- const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
448
- setCurrentHref(logicalPath + effectiveUrl.search);
449
- if (opts?.resetScroll ?? true) {
450
- pendingScrollRef.current = { type: "reset", href: physicalEffective };
451
- }
452
- } finally {
453
- if (navVersion.current === myVersion) {
454
- setIsNavigating(false);
455
- }
456
- }
457
- },
458
- [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
459
- );
460
-
461
- const refresh = useCallback(
462
- async (opts: { resetScroll?: boolean } | undefined) => {
463
- const logicalPath = toLogical(window.location.pathname, basePath);
464
- const logicalHref = logicalPath + window.location.search;
465
- invalidatePrefetch(logicalHref, "page");
466
- await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
467
- },
468
- [navigate, invalidatePrefetch, basePath]
469
- );
470
-
471
- // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
472
- // reload of a loader-bearing route the client re-fetches fresh data instead
473
- // of rendering with stale initialData from the initial SSR payload.
474
- useEffect(() => {
475
- if (typeof window !== "undefined") {
476
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
477
- (window as any).__FURIN_HMR_REFRESH__ = refresh;
478
- return () => {
479
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
480
- (window as any).__FURIN_HMR_REFRESH__ = undefined;
481
- };
482
- }
483
- }, [refresh]);
484
-
485
- const handlePopState = useCallback(() => {
486
- const destKey = getHistoryKey(history.state);
487
- const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
488
- const logicalHref = logicalPath + window.location.search;
489
- const myVersion = ++navVersion.current;
490
- navAbortRef.current?.abort();
491
- const navAbort = new AbortController();
492
- navAbortRef.current = navAbort;
493
- const navSignal = navAbort.signal;
494
- setIsNavigating(true);
495
-
496
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: popstate handler — cache check, redirect follow, and scroll restoration require this depth
497
- (async () => {
498
- try {
499
- const cached = prefetchCache.current.get(logicalHref);
500
- let newState: RouterState | null;
501
- if (cached && !shouldRefetch(cached)) {
502
- newState = await cached.promise;
503
- } else {
504
- newState = await fetchPageState(logicalHref, navSignal);
505
- }
506
- if (navVersion.current !== myVersion) {
507
- return;
508
- }
509
- if (!newState) {
510
- log.warn({
511
- action: "popstate_fallback",
512
- href: logicalHref,
513
- reason: "fetchPageState_returned_null",
514
- });
515
- window.location.reload();
516
- return;
517
- }
518
-
519
- // Server-side redirect: replace history entry and load target
520
- let redirectLogical: string | undefined;
521
- if (newState.finalHref && !newState.match && !newState.notFound) {
522
- redirectLogical = normalizeHref(newState.finalHref);
523
- window.history.replaceState(history.state, "", basePath + redirectLogical);
524
- setCurrentHref(redirectLogical);
525
- const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
526
- if (!redirectState) {
527
- if (navVersion.current === myVersion) {
528
- window.location.reload();
529
- }
530
- return;
531
- }
532
- newState = redirectState;
533
- }
534
-
535
- currentMatchRef.current = newState.match;
536
- setState(newState);
537
- if (newState.title) {
538
- document.title = newState.title;
539
- }
540
- const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
541
- if (newState.finalHref) {
542
- window.history.replaceState(history.state, "", basePath + effectiveLogical);
543
- }
544
- setCurrentHref(normalizeHref(effectiveLogical));
545
- if (destKey) {
546
- pendingScrollRef.current = { type: "restore", key: destKey };
547
- } else {
548
- window.scrollTo({ top: 0, behavior: "instant" });
549
- }
550
- } finally {
551
- if (navVersion.current === myVersion) {
552
- setIsNavigating(false);
553
- }
554
- }
555
- })();
556
- }, [fetchPageState, basePath]);
557
-
558
- // Disable native scroll restoration and assign a key to the initial history entry.
559
- useEffect(() => {
560
- history.scrollRestoration = "manual";
561
- if (!getHistoryKey(history.state)) {
562
- history.replaceState(
563
- { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
564
- ""
565
- );
566
- }
567
- }, []);
568
-
569
- // Render-synchronous scroll restoration.
570
- useLayoutEffect(() => {
571
- const instruction = pendingScrollRef.current;
572
- if (!instruction) {
573
- return;
574
- }
575
- pendingScrollRef.current = null;
576
-
577
- if (instruction.type === "restore") {
578
- try {
579
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
580
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
581
- const y = positions[instruction.key] ?? 0;
582
- window.scrollTo({ top: y, behavior: "instant" });
583
- } catch {
584
- window.scrollTo({ top: 0, behavior: "instant" });
585
- }
586
- return;
587
- }
588
-
589
- const destUrl = new URL(instruction.href, window.location.origin);
590
- if (destUrl.hash) {
591
- const id = decodeURIComponent(destUrl.hash.slice(1));
592
- const element = document.getElementById(id);
593
- if (element) {
594
- element.scrollIntoView({ behavior: "instant", block: "start" });
595
- }
596
- } else {
597
- window.scrollTo({ top: 0, behavior: "instant" });
598
- }
599
- }, [currentHref]);
600
-
601
- // Handle browser back/forward
602
- useEffect(() => {
603
- window.addEventListener("popstate", handlePopState);
604
- return () => window.removeEventListener("popstate", handlePopState);
605
- }, [handlePopState]);
606
-
607
- // Intercept clicks on native <a> tags so that internal links (including
608
- // those rendered by MDX, CMS content, or third-party components) participate
609
- // in SPA navigation instead of triggering full-page reloads.
610
- useEffect(() => {
611
- if (typeof window === "undefined") {
612
- return;
613
- }
614
- const handler = (e: MouseEvent) => {
615
- if (e.defaultPrevented) {
616
- return;
617
- }
618
- const anchor = (e.target as HTMLElement).closest("a");
619
- if (!(anchor instanceof HTMLAnchorElement)) {
620
- return;
621
- }
622
- // Ignore Furin Link anchors — they handle their own navigation via
623
- // LinkInteractive.handleClick.
624
- if (anchor.closest("a[data-furin-link]")) {
625
- return;
626
- }
627
- const logicalHref = shouldInterceptClick(
628
- anchor,
629
- e,
630
- basePath,
631
- window.location.origin,
632
- window.location.pathname
633
- );
634
- if (logicalHref === null) {
635
- return;
636
- }
637
- e.preventDefault();
638
- navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
639
- };
640
- document.addEventListener("click", handler);
641
- return () => document.removeEventListener("click", handler);
642
- }, [navigate, basePath]);
643
-
644
- // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
645
- useEffect(() => {
646
- if (typeof window === "undefined") {
647
- return;
648
- }
649
- const originalFetch = window.fetch;
650
- const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
651
- const response = await originalFetch.apply(window, args);
652
- const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
653
- applyRevalidateHeader(response.headers, (path, type = "page") => {
654
- invalidatePrefetch(path, type);
655
- invalidated.push({ path, type });
656
- });
657
- if (autoRefresh && invalidated.length > 0) {
658
- const currentLogicalPath =
659
- normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
660
- if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
661
- // fire-and-forget: don't block the original fetch caller
662
- refresh(undefined);
663
- }
664
- }
665
- return response;
666
- };
667
- // Copy static fetch methods so the patched value satisfies typeof fetch.
668
- Object.assign(wrapped, originalFetch);
669
- // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
670
- window.fetch = wrapped as any;
671
- return () => {
672
- window.fetch = originalFetch;
673
- };
674
- }, [invalidatePrefetch, refresh, autoRefresh, basePath]);
675
-
676
- let pageElement: React.ReactNode;
677
- if (state.notFound || !state.match) {
678
- pageElement = buildNotFoundPageElement(
679
- state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
680
- state.notFound ?? {}
681
- );
682
- } else {
683
- pageElement = buildPageElement(
684
- state.match,
685
- root,
686
- state.data,
687
- {
688
- onReset: () => {
689
- refresh(undefined).catch((err: unknown) => {
690
- log.error({ action: "boundary_reset_failed", error: String(err) });
691
- });
692
- },
693
- resetKey: currentHref,
694
- },
695
- state.error
696
- );
697
- }
698
-
699
- return buildRouterTree(
700
- {
701
- basePath,
702
- currentHref,
703
- navigate,
704
- prefetch,
705
- refresh,
706
- invalidatePrefetch,
707
- isNavigating,
708
- defaultPreload,
709
- defaultPreloadDelay,
710
- defaultPreloadStaleTime,
711
- },
712
- pageElement,
713
- {
714
- digest: initialDigest,
715
- onReset: () => {
716
- refresh(undefined).catch((err: unknown) => {
717
- log.error({ action: "boundary_reset_failed", error: String(err) });
718
- });
719
- },
720
- resetKey: currentHref,
721
- }
722
- );
723
- }
1
+ import { log } from "evlog";
2
+ import type React from "react";
3
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
+ import { parseDeferredNdjson } from "../../shared/deferred-ndjson.ts";
5
+ import type { SearchParamsInput } from "../../shared/search-params.ts";
6
+ import { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
7
+ import {
8
+ generateHistoryKey,
9
+ getHistoryKey,
10
+ isStaleDeployResponse,
11
+ SCROLL_STORAGE_KEY,
12
+ saveScrollPosition,
13
+ } from "./history.ts";
14
+ import {
15
+ applyRevalidateEntries,
16
+ applyRevalidateHeader,
17
+ normalizeHref,
18
+ shouldAutoRefreshPath,
19
+ shouldInterceptClick,
20
+ shouldRefetch,
21
+ stripHashFromHref,
22
+ toLogical,
23
+ } from "./link-utils.ts";
24
+ import { createSearchStore, type SearchStore, SearchStoreContext } from "./search-store.ts";
25
+ import {
26
+ buildDataEndpoint,
27
+ buildNotFoundPageElement,
28
+ classifySpaResponse,
29
+ detectStaticMode,
30
+ parsePageResponse,
31
+ } from "./spa-response.ts";
32
+ import type {
33
+ CacheEntry,
34
+ ClientSegmentBoundary,
35
+ LoadedClientRoute,
36
+ RouterProviderProps,
37
+ RouterState,
38
+ } from "./types.ts";
39
+
40
+ const EMPTY_SEARCH: SearchParamsInput = {};
41
+
42
+ export function setPrefetchCacheEntry(
43
+ cache: Map<string, CacheEntry>,
44
+ href: string,
45
+ entry: CacheEntry,
46
+ maxSize: number
47
+ ): void {
48
+ if (cache.has(href)) {
49
+ cache.delete(href);
50
+ }
51
+ cache.set(href, entry);
52
+ if (cache.size > maxSize) {
53
+ const oldest = cache.keys().next().value;
54
+ if (typeof oldest === "string") {
55
+ cache.delete(oldest);
56
+ }
57
+ }
58
+ }
59
+
60
+ export function RouterProvider({
61
+ routes,
62
+ root,
63
+ initialMatch,
64
+ initialData,
65
+ initialDigest,
66
+ initialNotFound,
67
+ autoRefresh,
68
+ basePath,
69
+ defaultPreload,
70
+ defaultPreloadDelay,
71
+ defaultPreloadStaleTime,
72
+ prefetchCacheSize,
73
+ syncStream,
74
+ }: RouterProviderProps): React.ReactElement {
75
+ // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
76
+ // the provider boots into the inline not-found UI.
77
+ const [state, setState] = useState<RouterState>(() => ({
78
+ match: initialMatch,
79
+ data: initialData,
80
+ notFound: initialNotFound,
81
+ }));
82
+ const [isNavigating, setIsNavigating] = useState(false);
83
+ // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
84
+ // detection works with route patterns that never include the basePath prefix.
85
+ const [currentHref, setCurrentHref] = useState<string>(() => {
86
+ if (typeof window === "undefined") {
87
+ return "/";
88
+ }
89
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
90
+ });
91
+ const prefetchCache = useRef(new Map<string, CacheEntry>());
92
+ /** Monotonic counter to discard stale navigations (race condition guard). */
93
+ const navVersion = useRef(0);
94
+ /**
95
+ * AbortController for the current navigation. Cancelled when a newer
96
+ * navigation starts so any in-flight `parseDeferredNdjson` releases its
97
+ * pending deferred promises (resolvers reject with `AbortError`) and frees
98
+ * the underlying stream reader.
99
+ */
100
+ const navAbortRef = useRef<AbortController | null>(null);
101
+ /**
102
+ * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
103
+ * This replaces the fragile double-requestAnimationFrame pattern with a render-
104
+ * synchronous scroll that fires immediately after React commits the new route.
105
+ */
106
+ const pendingScrollRef = useRef<
107
+ { type: "restore"; key: string } | { type: "reset"; href: string } | null
108
+ >(null);
109
+ /**
110
+ * Tracks the last successfully rendered match for use in the no-route 404 path.
111
+ * `null` on the initial render when the URL didn't match any route and the
112
+ * provider booted directly into the not-found state; flips to a real match as
113
+ * soon as the user navigates away via `navigate()` or the back button.
114
+ */
115
+ const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
116
+ /**
117
+ * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
118
+ * fetch URL: runtime `/_furin/data` for SSR/ISR/dev, per-route
119
+ * `__furin_data.ndjson` for static exports.
120
+ */
121
+ const staticModeRef = useRef<boolean>(detectStaticMode());
122
+ const resolvedSearch = (state.data.query as SearchParamsInput | undefined) ?? EMPTY_SEARCH;
123
+ const searchStoreRef = useRef<SearchStore | null>(null);
124
+
125
+ /**
126
+ * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
127
+ * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
128
+ * handles it — the root `not-found.tsx` (depth 0) is the correct component to
129
+ * render inline instead of doing a full-page reload.
130
+ */
131
+ const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
132
+ for (const route of routes) {
133
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
134
+ if (depth0) {
135
+ return [depth0];
136
+ }
137
+ }
138
+ return;
139
+ }, [routes]);
140
+
141
+ /**
142
+ * Resolves the RouterState when no client-side route matched the URL. The
143
+ * server's `renderRootNotFound` produced the 404 HTML; we fetch the physical
144
+ * URL to detect the `__furinStatus: 404` signal and render the 404 UI inline
145
+ * (rather than triggering a jarring full-page reload).
146
+ */
147
+ const resolveNoMatchState = useCallback(
148
+ async (physicalHref: string, signal: AbortSignal | undefined): Promise<RouterState | null> => {
149
+ const res = await fetch(physicalHref, { signal });
150
+ if (isStaleDeployResponse(res)) {
151
+ window.location.href = physicalHref;
152
+ return null;
153
+ }
154
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
155
+ const kind = classifySpaResponse(res.status, data);
156
+ if (kind.kind !== "not-found") {
157
+ return null;
158
+ }
159
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
160
+ return {
161
+ match: currentMatchRef.current,
162
+ data: cleanData,
163
+ title,
164
+ finalHref,
165
+ notFound: kind.error,
166
+ notFoundBoundaries: rootBoundaries,
167
+ };
168
+ },
169
+ [basePath, rootBoundaries]
170
+ );
171
+
172
+ const fetchPageState = useCallback(
173
+ async (
174
+ rawLogicalHref: string,
175
+ signal: AbortSignal | undefined
176
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
177
+ ): Promise<RouterState | null> => {
178
+ // Normalize trailing slashes so "/docs/routing/" matches the route
179
+ // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
180
+ // redirect to or serve URLs with a trailing slash.
181
+ const logicalHref = normalizeHref(rawLogicalHref);
182
+ try {
183
+ // Physical href: what the browser/server actually receives.
184
+ // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
185
+ const physicalHref = basePath + logicalHref;
186
+ const url = new URL(physicalHref, window.location.origin);
187
+ // Route matching always uses the LOGICAL pathname (basePath stripped).
188
+ const logicalPathname = toLogical(url.pathname, basePath);
189
+ const match = routes.find((r) => r.regex.test(logicalPathname));
190
+ if (!match) {
191
+ return await resolveNoMatchState(physicalHref, signal);
192
+ }
193
+
194
+ // ── NDJSON data endpoint + JS chunk load (parallel) ──────────────────
195
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
196
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
197
+
198
+ // Stale-deploy detection: force a full page reload to pick up the new bundle.
199
+ if (isStaleDeployResponse(res)) {
200
+ window.location.href = physicalHref;
201
+ return null;
202
+ }
203
+
204
+ const body = res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() });
205
+ let parsed: {
206
+ syncData: Record<string, unknown>;
207
+ deferredPromises: Record<string, Promise<unknown>>;
208
+ };
209
+ try {
210
+ parsed = await parseDeferredNdjson(body, signal);
211
+ } catch (parseErr) {
212
+ log.warn({
213
+ action: "navigate_server_error",
214
+ href: physicalHref,
215
+ status: res.status,
216
+ error: String(parseErr),
217
+ });
218
+ return null;
219
+ }
220
+ const { syncData, deferredPromises } = parsed;
221
+
222
+ // Special fields injected by the server into syncData:
223
+ // __furinStatus — 404 signal
224
+ // __furinNotFound — not-found payload
225
+ // __furinRedirect — server-side redirect target (logical path)
226
+ // __furinError — error sentinel (digest, message, status)
227
+ // __furinTitle — document title resolved server-side from head()
228
+ const {
229
+ __furinStatus,
230
+ __furinNotFound,
231
+ __furinRedirect,
232
+ __furinError,
233
+ __furinTitle,
234
+ ...cleanSyncData
235
+ } = syncData as {
236
+ __furinStatus?: number;
237
+ __furinNotFound?: { data?: unknown; message?: string };
238
+ __furinRedirect?: string;
239
+ __furinError?: { digest: string; message: string; status: number };
240
+ __furinTitle?: string;
241
+ [key: string]: unknown;
242
+ };
243
+
244
+ const finalHref: string | undefined =
245
+ typeof __furinRedirect === "string" ? __furinRedirect : undefined;
246
+
247
+ // Merge sync data + deferred Promises.
248
+ const data = { ...cleanSyncData, ...deferredPromises };
249
+
250
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
251
+
252
+ const loadedMatch: LoadedClientRoute = {
253
+ ...match,
254
+ component: loadedMod.default.component,
255
+ pageRoute: loadedMod.default._route,
256
+ segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries,
257
+ };
258
+
259
+ // Loader threw a non-redirect Response (or an Error).
260
+ if (__furinError) {
261
+ return {
262
+ match: loadedMatch,
263
+ data: {},
264
+ title,
265
+ finalHref,
266
+ error: __furinError,
267
+ };
268
+ }
269
+
270
+ // Non-2xx without sentinel and not 404 → opaque server error.
271
+ if (!res.ok && res.status !== 404) {
272
+ log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
273
+ return null;
274
+ }
275
+
276
+ if (__furinStatus === 404) {
277
+ return {
278
+ match: loadedMatch,
279
+ data,
280
+ title,
281
+ finalHref,
282
+ notFound: (__furinNotFound as { data?: unknown; message?: string }) ?? {},
283
+ };
284
+ }
285
+
286
+ // Server-side redirect: do not mount the pre-redirect route.
287
+ if (finalHref) {
288
+ return { match: null, data, title, finalHref };
289
+ }
290
+
291
+ return { match: loadedMatch, data, title, finalHref };
292
+ } catch (err: unknown) {
293
+ log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
294
+ return null;
295
+ }
296
+ },
297
+ [routes, basePath, resolveNoMatchState]
298
+ );
299
+
300
+ const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
301
+ const normalizedPath = stripHashFromHref(path);
302
+
303
+ if (type === "page") {
304
+ for (const key of [...prefetchCache.current.keys()]) {
305
+ if (stripHashFromHref(key) === normalizedPath) {
306
+ prefetchCache.current.delete(key);
307
+ }
308
+ }
309
+ return;
310
+ }
311
+
312
+ // layout: prefix match — evict the path itself and all nested children
313
+ const prefix =
314
+ normalizedPath === "/" || normalizedPath.endsWith("/")
315
+ ? normalizedPath
316
+ : `${normalizedPath}/`;
317
+ for (const key of [...prefetchCache.current.keys()]) {
318
+ const normalizedKey = stripHashFromHref(key);
319
+ if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
320
+ prefetchCache.current.delete(key);
321
+ }
322
+ }
323
+ }, []);
324
+
325
+ const prefetch = useCallback(
326
+ (href: string, opts: { staleTime?: number } | undefined) => {
327
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
328
+ const existing = prefetchCache.current.get(href);
329
+ if (existing && !shouldRefetch(existing)) {
330
+ return;
331
+ }
332
+ setPrefetchCacheEntry(
333
+ prefetchCache.current,
334
+ href,
335
+ {
336
+ promise: fetchPageState(href, undefined),
337
+ createdAt: Date.now(),
338
+ staleTime,
339
+ },
340
+ prefetchCacheSize
341
+ );
342
+ },
343
+ [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
344
+ );
345
+
346
+ /** Loads the RouterState for a redirect target, respecting the nav version. */
347
+ async function resolveRedirectState(
348
+ redirectLogical: string,
349
+ myVersion: number,
350
+ signal: AbortSignal | undefined
351
+ ): Promise<RouterState | null> {
352
+ const cached = prefetchCache.current.get(redirectLogical);
353
+ const state =
354
+ cached && !shouldRefetch(cached)
355
+ ? await cached.promise
356
+ : await fetchPageState(redirectLogical, signal);
357
+ if (navVersion.current !== myVersion) {
358
+ return null;
359
+ }
360
+ return state;
361
+ }
362
+
363
+ const navigate = useCallback(
364
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — redirect follow, history management, and scroll handling require this depth
365
+ async function navigateTo(
366
+ rawLogicalHref: string,
367
+ opts: { replace?: boolean; resetScroll?: boolean } | undefined
368
+ ) {
369
+ const logicalHref = normalizeHref(rawLogicalHref);
370
+ const myVersion = ++navVersion.current;
371
+ navAbortRef.current?.abort();
372
+ const navAbort = new AbortController();
373
+ navAbortRef.current = navAbort;
374
+ const navSignal = navAbort.signal;
375
+ setIsNavigating(true);
376
+ try {
377
+ const cached = prefetchCache.current.get(logicalHref);
378
+ let newState =
379
+ cached && !shouldRefetch(cached)
380
+ ? await cached.promise
381
+ : await fetchPageState(logicalHref, navSignal);
382
+ if (navVersion.current !== myVersion) {
383
+ return;
384
+ }
385
+ if (newState && (!cached || shouldRefetch(cached))) {
386
+ setPrefetchCacheEntry(
387
+ prefetchCache.current,
388
+ logicalHref,
389
+ {
390
+ promise: Promise.resolve(newState),
391
+ createdAt: Date.now(),
392
+ staleTime: defaultPreloadStaleTime,
393
+ },
394
+ prefetchCacheSize
395
+ );
396
+ }
397
+ if (!newState) {
398
+ log.warn({
399
+ action: "navigate_fallback",
400
+ href: logicalHref,
401
+ reason: "prefetch_returned_null",
402
+ });
403
+ window.location.href = basePath + logicalHref;
404
+ return;
405
+ }
406
+
407
+ // Server-side redirect: replace current history entry and load target
408
+ let redirectLogical: string | undefined;
409
+ if (newState.finalHref && !newState.match && !newState.notFound) {
410
+ redirectLogical = normalizeHref(newState.finalHref);
411
+ const redirectPhysical = basePath + redirectLogical;
412
+ window.history.replaceState(
413
+ {
414
+ ...((history.state as object) ?? {}),
415
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
416
+ },
417
+ "",
418
+ redirectPhysical
419
+ );
420
+ setCurrentHref(redirectLogical);
421
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
422
+ if (!redirectState) {
423
+ if (navVersion.current === myVersion) {
424
+ window.location.href = redirectPhysical;
425
+ }
426
+ return;
427
+ }
428
+ newState = redirectState;
429
+ }
430
+
431
+ currentMatchRef.current = newState.match;
432
+ setState(newState);
433
+ if (newState.title) {
434
+ document.title = newState.title;
435
+ }
436
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
437
+ const physicalEffective = basePath + effectiveLogical;
438
+ if (opts?.replace) {
439
+ window.history.replaceState(
440
+ {
441
+ ...((history.state as object) ?? {}),
442
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
443
+ },
444
+ "",
445
+ physicalEffective
446
+ );
447
+ } else {
448
+ const currentKey = getHistoryKey(history.state);
449
+ if (currentKey) {
450
+ saveScrollPosition(currentKey);
451
+ }
452
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
453
+ }
454
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
455
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
456
+ setCurrentHref(logicalPath + effectiveUrl.search);
457
+ if (opts?.resetScroll ?? true) {
458
+ pendingScrollRef.current = { type: "reset", href: physicalEffective };
459
+ }
460
+ } finally {
461
+ if (navVersion.current === myVersion) {
462
+ setIsNavigating(false);
463
+ }
464
+ }
465
+ },
466
+ [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
467
+ );
468
+
469
+ if (searchStoreRef.current === null) {
470
+ searchStoreRef.current = createSearchStore({
471
+ currentHref,
472
+ navigate,
473
+ search: resolvedSearch,
474
+ searchRoutes: routes,
475
+ });
476
+ }
477
+ const searchStore = searchStoreRef.current;
478
+ const searchSnapshot = useMemo(
479
+ () => ({
480
+ currentHref,
481
+ navigate,
482
+ search: resolvedSearch,
483
+ searchRoutes: routes,
484
+ }),
485
+ [currentHref, navigate, resolvedSearch, routes]
486
+ );
487
+
488
+ useLayoutEffect(() => {
489
+ searchStore.setSnapshot(searchSnapshot);
490
+ searchStore.flush();
491
+ }, [searchStore, searchSnapshot]);
492
+
493
+ const refresh = useCallback(
494
+ async (opts: { resetScroll?: boolean } | undefined) => {
495
+ const logicalPath = toLogical(window.location.pathname, basePath);
496
+ const logicalHref = logicalPath + window.location.search;
497
+ invalidatePrefetch(logicalHref, "page");
498
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
499
+ },
500
+ [navigate, invalidatePrefetch, basePath]
501
+ );
502
+
503
+ // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
504
+ // reload of a loader-bearing route the client re-fetches fresh data instead
505
+ // of rendering with stale initialData from the initial SSR payload.
506
+ useEffect(() => {
507
+ if (typeof window !== "undefined") {
508
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
509
+ (window as any).__FURIN_HMR_REFRESH__ = refresh;
510
+ return () => {
511
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
512
+ (window as any).__FURIN_HMR_REFRESH__ = undefined;
513
+ };
514
+ }
515
+ }, [refresh]);
516
+
517
+ const handlePopState = useCallback(() => {
518
+ const destKey = getHistoryKey(history.state);
519
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
520
+ const logicalHref = logicalPath + window.location.search;
521
+ const myVersion = ++navVersion.current;
522
+ navAbortRef.current?.abort();
523
+ const navAbort = new AbortController();
524
+ navAbortRef.current = navAbort;
525
+ const navSignal = navAbort.signal;
526
+ setIsNavigating(true);
527
+
528
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: popstate handler — cache check, redirect follow, and scroll restoration require this depth
529
+ (async () => {
530
+ try {
531
+ const cached = prefetchCache.current.get(logicalHref);
532
+ let newState: RouterState | null;
533
+ if (cached && !shouldRefetch(cached)) {
534
+ newState = await cached.promise;
535
+ } else {
536
+ newState = await fetchPageState(logicalHref, navSignal);
537
+ }
538
+ if (navVersion.current !== myVersion) {
539
+ return;
540
+ }
541
+ if (!newState) {
542
+ log.warn({
543
+ action: "popstate_fallback",
544
+ href: logicalHref,
545
+ reason: "fetchPageState_returned_null",
546
+ });
547
+ window.location.reload();
548
+ return;
549
+ }
550
+
551
+ // Server-side redirect: replace history entry and load target
552
+ let redirectLogical: string | undefined;
553
+ if (newState.finalHref && !newState.match && !newState.notFound) {
554
+ redirectLogical = normalizeHref(newState.finalHref);
555
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
556
+ setCurrentHref(redirectLogical);
557
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
558
+ if (!redirectState) {
559
+ if (navVersion.current === myVersion) {
560
+ window.location.reload();
561
+ }
562
+ return;
563
+ }
564
+ newState = redirectState;
565
+ }
566
+
567
+ currentMatchRef.current = newState.match;
568
+ setState(newState);
569
+ if (newState.title) {
570
+ document.title = newState.title;
571
+ }
572
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
573
+ if (newState.finalHref) {
574
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
575
+ }
576
+ setCurrentHref(normalizeHref(effectiveLogical));
577
+ if (destKey) {
578
+ pendingScrollRef.current = { type: "restore", key: destKey };
579
+ } else {
580
+ window.scrollTo({ top: 0, behavior: "instant" });
581
+ }
582
+ } finally {
583
+ if (navVersion.current === myVersion) {
584
+ setIsNavigating(false);
585
+ }
586
+ }
587
+ })();
588
+ }, [fetchPageState, basePath]);
589
+
590
+ // Disable native scroll restoration and assign a key to the initial history entry.
591
+ useEffect(() => {
592
+ history.scrollRestoration = "manual";
593
+ if (!getHistoryKey(history.state)) {
594
+ history.replaceState(
595
+ { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
596
+ ""
597
+ );
598
+ }
599
+ }, []);
600
+
601
+ // Render-synchronous scroll restoration.
602
+ useLayoutEffect(() => {
603
+ const instruction = pendingScrollRef.current;
604
+ if (!instruction) {
605
+ return;
606
+ }
607
+ pendingScrollRef.current = null;
608
+
609
+ if (instruction.type === "restore") {
610
+ try {
611
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
612
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
613
+ const y = positions[instruction.key] ?? 0;
614
+ window.scrollTo({ top: y, behavior: "instant" });
615
+ } catch {
616
+ window.scrollTo({ top: 0, behavior: "instant" });
617
+ }
618
+ return;
619
+ }
620
+
621
+ const destUrl = new URL(instruction.href, window.location.origin);
622
+ if (destUrl.hash) {
623
+ const id = decodeURIComponent(destUrl.hash.slice(1));
624
+ const element = document.getElementById(id);
625
+ if (element) {
626
+ element.scrollIntoView({ behavior: "instant", block: "start" });
627
+ }
628
+ } else {
629
+ window.scrollTo({ top: 0, behavior: "instant" });
630
+ }
631
+ }, [currentHref]);
632
+
633
+ // Handle browser back/forward
634
+ useEffect(() => {
635
+ window.addEventListener("popstate", handlePopState);
636
+ return () => window.removeEventListener("popstate", handlePopState);
637
+ }, [handlePopState]);
638
+
639
+ // Intercept clicks on native <a> tags so that internal links (including
640
+ // those rendered by MDX, CMS content, or third-party components) participate
641
+ // in SPA navigation instead of triggering full-page reloads.
642
+ useEffect(() => {
643
+ if (typeof window === "undefined") {
644
+ return;
645
+ }
646
+ const handler = (e: MouseEvent) => {
647
+ if (e.defaultPrevented) {
648
+ return;
649
+ }
650
+ const anchor = (e.target as HTMLElement).closest("a");
651
+ if (!(anchor instanceof HTMLAnchorElement)) {
652
+ return;
653
+ }
654
+ // Ignore Furin Link anchors — they handle their own navigation via
655
+ // LinkInteractive.handleClick.
656
+ if (anchor.closest("a[data-furin-link]")) {
657
+ return;
658
+ }
659
+ const logicalHref = shouldInterceptClick(
660
+ anchor,
661
+ e,
662
+ basePath,
663
+ window.location.origin,
664
+ window.location.pathname
665
+ );
666
+ if (logicalHref === null) {
667
+ return;
668
+ }
669
+ e.preventDefault();
670
+ navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
671
+ };
672
+ document.addEventListener("click", handler);
673
+ return () => document.removeEventListener("click", handler);
674
+ }, [navigate, basePath]);
675
+
676
+ // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
677
+ useEffect(() => {
678
+ if (typeof window === "undefined") {
679
+ return;
680
+ }
681
+ const originalFetch = window.fetch;
682
+ const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
683
+ const response = await originalFetch.apply(window, args);
684
+ const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
685
+ applyRevalidateHeader(response.headers, (path, type) => {
686
+ const resolvedType = type ?? "page";
687
+ invalidatePrefetch(path, resolvedType);
688
+ invalidated.push({ path, type: resolvedType });
689
+ });
690
+ if (autoRefresh && invalidated.length > 0) {
691
+ const currentLogicalPath =
692
+ normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
693
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
694
+ // fire-and-forget: don't block the original fetch caller
695
+ refresh(undefined);
696
+ }
697
+ }
698
+ return response;
699
+ };
700
+ // Copy static fetch methods so the patched value satisfies typeof fetch.
701
+ Object.assign(wrapped, originalFetch);
702
+ // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
703
+ window.fetch = wrapped as any;
704
+ return () => {
705
+ window.fetch = originalFetch;
706
+ };
707
+ }, [invalidatePrefetch, refresh, autoRefresh, basePath]);
708
+
709
+ // Listen for cross-client invalidations published by furin({ sync: true }).
710
+ useEffect(() => {
711
+ if (!syncStream || typeof window === "undefined" || typeof EventSource === "undefined") {
712
+ return;
713
+ }
714
+
715
+ const streamUrl = syncStream.startsWith("/")
716
+ ? `${basePath}${syncStream}`
717
+ : `${basePath}/${syncStream}`;
718
+ const source = new EventSource(streamUrl);
719
+ const onInvalidate = (event: MessageEvent) => {
720
+ let payload: { invalidations?: string[] };
721
+ try {
722
+ payload = JSON.parse(event.data) as { invalidations?: string[] };
723
+ } catch {
724
+ log.warn({ action: "sync_invalid_event", event: "furin.invalidate" });
725
+ return;
726
+ }
727
+
728
+ const invalidations: Array<{ path: string; type: "page" | "layout" }> = [];
729
+ applyRevalidateEntries(payload.invalidations ?? [], (path, type) => {
730
+ const resolvedType = type ?? "page";
731
+ invalidatePrefetch(path, resolvedType);
732
+ invalidations.push({ path, type: resolvedType });
733
+ });
734
+
735
+ if (autoRefresh && invalidations.length > 0) {
736
+ const currentLogicalPath =
737
+ normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
738
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidations)) {
739
+ refresh(undefined);
740
+ }
741
+ }
742
+ };
743
+
744
+ source.addEventListener("furin.invalidate", onInvalidate);
745
+ return () => {
746
+ source.removeEventListener("furin.invalidate", onInvalidate);
747
+ source.close();
748
+ };
749
+ }, [syncStream, basePath, invalidatePrefetch, refresh, autoRefresh]);
750
+
751
+ let pageElement: React.ReactNode;
752
+ if (state.notFound || !state.match) {
753
+ pageElement = buildNotFoundPageElement(
754
+ state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
755
+ state.notFound ?? {}
756
+ );
757
+ } else {
758
+ pageElement = buildPageElement(
759
+ state.match,
760
+ root,
761
+ state.data,
762
+ {
763
+ onReset: () => {
764
+ refresh(undefined).catch((err: unknown) => {
765
+ log.error({ action: "boundary_reset_failed", error: String(err) });
766
+ });
767
+ },
768
+ resetKey: currentHref,
769
+ },
770
+ state.error
771
+ );
772
+ }
773
+
774
+ return (
775
+ <SearchStoreContext.Provider value={searchStore}>
776
+ {buildRouterTree(
777
+ {
778
+ basePath,
779
+ currentHref,
780
+ search: resolvedSearch,
781
+ searchRoutes: routes,
782
+ navigate,
783
+ prefetch,
784
+ refresh,
785
+ invalidatePrefetch,
786
+ isNavigating,
787
+ defaultPreload,
788
+ defaultPreloadDelay,
789
+ defaultPreloadStaleTime,
790
+ },
791
+ pageElement,
792
+ {
793
+ digest: initialDigest,
794
+ onReset: () => {
795
+ refresh(undefined).catch((err: unknown) => {
796
+ log.error({ action: "boundary_reset_failed", error: String(err) });
797
+ });
798
+ },
799
+ resetKey: currentHref,
800
+ }
801
+ )}
802
+ </SearchStoreContext.Provider>
803
+ );
804
+ }