@teyik0/furin 0.1.0-alpha.11 → 0.1.0-alpha.13

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.
@@ -0,0 +1,1428 @@
1
+ import { log } from "evlog";
2
+ import type React from "react";
3
+ import {
4
+ createContext,
5
+ createElement,
6
+ useCallback,
7
+ useContext,
8
+ useEffect,
9
+ useLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ useState,
13
+ } from "react";
14
+ import type { RuntimeRoute } from "./client";
15
+ import type { ErrorComponent } from "./error";
16
+ import type { NotFoundComponent } from "./not-found";
17
+ import { FurinErrorBoundary, FurinNotFoundBoundary } from "./render/boundaries.tsx";
18
+ import { DefaultNotFoundScreen } from "./render/default-screens.tsx";
19
+
20
+ // ── Types ─────────────────────────────────────────────────────────────────────
21
+
22
+ /**
23
+ * Augment this interface via declaration merging in furin-env.d.ts
24
+ * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
25
+ *
26
+ * @example
27
+ * // furin-env.d.ts (auto-generated by Furin at project root)
28
+ * import "@teyik0/furin/link";
29
+ * declare module "@teyik0/furin/link" {
30
+ * interface RouteManifest {
31
+ * "/blog": { search?: { page?: number; tag?: string } };
32
+ * "/": { search?: never };
33
+ * [key: `/blog/${string}`]: { search?: never };
34
+ * }
35
+ * }
36
+ */
37
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
38
+ export interface RouteManifest {}
39
+
40
+ /**
41
+ * The valid `to` pathname union derived from the augmented RouteManifest.
42
+ * Falls back to `string` when furin-env.d.ts has not been generated yet.
43
+ * When augmented, also includes `https://` and `http://` for external links.
44
+ */
45
+ export type RouteTo = keyof RouteManifest extends never
46
+ ? string
47
+ : (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
48
+
49
+ /**
50
+ * The typed search params for a given `to` pathname.
51
+ * Falls back to a permissive record when RouteManifest is not augmented.
52
+ */
53
+ export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
54
+ ? Record<string, string | number | boolean | null | undefined>
55
+ : To extends keyof RouteManifest
56
+ ? RouteManifest[To] extends { search?: infer S }
57
+ ? S
58
+ : undefined
59
+ : undefined;
60
+
61
+ export type PreloadStrategy = false | "intent" | "viewport" | "render";
62
+
63
+ export interface LinkProps<To extends RouteTo = RouteTo>
64
+ extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
65
+ /**
66
+ * Extra props merged onto the anchor when the link is active.
67
+ * `isActive` is also passed so one function can handle both states.
68
+ * Styles and classNames from `activeProps` win over the static props.
69
+ */
70
+ activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
71
+ /** Static children or a render function receiving active state. */
72
+ children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
73
+ /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
74
+ disabled?: boolean;
75
+ /** Optional URL fragment (without the #). */
76
+ hash?: string;
77
+ /**
78
+ * Extra props merged onto the anchor when the link is NOT active.
79
+ * Styles and classNames from `inactiveProps` win over the static props.
80
+ */
81
+ inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
82
+ /** Preload strategy. Default: "intent" (preload on hover/focus). */
83
+ preload?: PreloadStrategy;
84
+ /** Delay in ms before intent preload triggers. Default: 50. */
85
+ preloadDelay?: number;
86
+ /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
87
+ preloadStaleTime?: number;
88
+ /** If true, uses history.replaceState instead of pushState (no new history entry). */
89
+ replace?: boolean;
90
+ /**
91
+ * Whether to scroll after SPA navigation. Default: true.
92
+ * - If the destination href has a `#hash`, scrolls to that element.
93
+ * - Otherwise scrolls to the top of the page.
94
+ * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
95
+ */
96
+ resetScroll?: boolean;
97
+ /** Typed search params for this route. Auto-completed from the route's query schema. */
98
+ search?: RouteSearch<To>;
99
+ to: To;
100
+ }
101
+
102
+ /**
103
+ * Builds a full href string from a pathname, optional search params, and optional hash.
104
+ * Null/undefined search values are omitted.
105
+ *
106
+ * @internal Exported for unit testing only.
107
+ */
108
+ export function buildHref(
109
+ to: string,
110
+ search?: Record<string, unknown> | null,
111
+ hash?: string
112
+ ): string {
113
+ let url = to;
114
+ if (search && Object.keys(search).length > 0) {
115
+ const params = new URLSearchParams();
116
+ for (const [k, v] of Object.entries(search)) {
117
+ if (v != null) {
118
+ params.set(k, String(v));
119
+ }
120
+ }
121
+ const qs = params.toString();
122
+ if (qs) {
123
+ url += `?${qs}`;
124
+ }
125
+ }
126
+ if (hash) {
127
+ url += `#${hash}`;
128
+ }
129
+ return url;
130
+ }
131
+
132
+ // ── Revalidation helpers ────────────────────────────────────────────────────────
133
+
134
+ /**
135
+ * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
136
+ * each path entry. Header format: `"/path1,/path2:layout,/path3"`
137
+ *
138
+ * Intended to be called from a `window.fetch` interceptor or SPA navigation
139
+ * handler so that client-side prefetch caches are busted automatically whenever
140
+ * a server-side `revalidatePath()` call is made within the same request.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const res = await fetch("/api/publish");
145
+ * applyRevalidateHeader(res.headers, (path, type) => {
146
+ * console.log("invalidate", path, type);
147
+ * });
148
+ * ```
149
+ */
150
+ export function applyRevalidateHeader(
151
+ headers: Headers,
152
+ invalidate: (path: string, type?: "page" | "layout") => void
153
+ ): void {
154
+ const headerValue = headers.get("x-furin-revalidate");
155
+ if (!headerValue) {
156
+ return;
157
+ }
158
+ for (const entry of headerValue.split(",")) {
159
+ const trimmed = entry.trim();
160
+ if (!trimmed) {
161
+ continue;
162
+ }
163
+ if (trimmed.endsWith(":layout")) {
164
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
165
+ } else {
166
+ invalidate(trimmed, "page");
167
+ }
168
+ }
169
+ }
170
+
171
+ // ── Auto-refresh helpers ───────────────────────────────────────────────────────
172
+
173
+ /**
174
+ * Returns `true` when `currentPath` is targeted by at least one invalidation entry,
175
+ * using the same matching rules as `invalidatePrefetch`:
176
+ * - `type: 'page'` — exact pathname match (query string stripped)
177
+ * - `type: 'layout'` — prefix match: the path itself OR any descendant
178
+ *
179
+ * @internal Exported for unit testing only.
180
+ */
181
+ export function shouldAutoRefreshPath(
182
+ currentPath: string,
183
+ invalidations: ReadonlyArray<{ path: string; type: "page" | "layout" }>
184
+ ): boolean {
185
+ // Strip query string for comparison — revalidatePath works on pathnames
186
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
187
+ return invalidations.some(({ path, type }) => {
188
+ if (type === "page") {
189
+ return path === normalizedCurrent;
190
+ }
191
+ // layout: match the path itself and all descendants
192
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
193
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
194
+ });
195
+ }
196
+
197
+ // ── Router context ─────────────────────────────────────────────────────────────
198
+
199
+ export interface RouterContextValue {
200
+ /**
201
+ * Sub-path prefix for static deployments (e.g. "/furin").
202
+ * Empty string when the site is served from root.
203
+ * Used by `Link` to build correct physical hrefs for the `<a>` element.
204
+ */
205
+ basePath: string;
206
+ /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
207
+ currentHref: string;
208
+ defaultPreload: PreloadStrategy;
209
+ defaultPreloadDelay: number;
210
+ defaultPreloadStaleTime: number;
211
+ /**
212
+ * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
213
+ * made on the server. Called automatically by the `window.fetch` interceptor when
214
+ * the server emits `X-Furin-Revalidate` headers.
215
+ *
216
+ * - `type: 'page'` (default) — exact URL match
217
+ * - `type: 'layout'` — prefix match (path + all nested children)
218
+ */
219
+ invalidatePrefetch: (path: string, type?: "page" | "layout") => void;
220
+ isNavigating: boolean;
221
+ navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
222
+ prefetch: (href: string, opts?: { staleTime?: number }) => void;
223
+ /**
224
+ * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
225
+ * loaders, and updates the rendered tree — without adding a history entry or
226
+ * resetting scroll (unless `resetScroll: true` is passed).
227
+ *
228
+ * Prefer this over `navigate(window.location.pathname)` after a mutation.
229
+ *
230
+ * @example
231
+ * ```tsx
232
+ * const { refresh } = useRouter();
233
+ * await apiClient.api.boards.post({ name });
234
+ * await refresh();
235
+ * ```
236
+ */
237
+ refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
238
+ }
239
+
240
+ export const RouterContext = createContext<RouterContextValue | null>(null);
241
+
242
+ /**
243
+ * Returns the current router context.
244
+ * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
245
+ */
246
+ export function useRouter(): RouterContextValue {
247
+ const ctx = useContext(RouterContext);
248
+ return (
249
+ ctx ?? {
250
+ basePath: "",
251
+ // Use the same "/" as SSR_FALLBACK_ROUTER so SSR and client render the
252
+ // same active-state when no RouterProvider is present, avoiding hydration mismatches.
253
+ currentHref: "/",
254
+ navigate: (href) => {
255
+ window.location.href = href;
256
+ return Promise.resolve();
257
+ },
258
+ prefetch: () => {
259
+ /* noop fallback */
260
+ },
261
+ invalidatePrefetch: () => {
262
+ /* noop fallback */
263
+ },
264
+ refresh: () => {
265
+ window.location.reload();
266
+ return Promise.resolve();
267
+ },
268
+ isNavigating: false,
269
+ defaultPreload: "intent",
270
+ defaultPreloadDelay: 50,
271
+ defaultPreloadStaleTime: 30_000,
272
+ }
273
+ );
274
+ }
275
+
276
+ // ── RouterProvider ─────────────────────────────────────────────────────────────
277
+
278
+ /**
279
+ * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
280
+ * version this does NOT carry the directory path — it's purely a (depth,
281
+ * fallback) pair because the client never reads files, only renders.
282
+ *
283
+ * Emitted by `generateHydrateEntry` from the scanned `segmentBoundaries`
284
+ * array: each route's entry lists ONLY the directories on its path that
285
+ * declare a convention file, so routes with no error.tsx / not-found.tsx
286
+ * anywhere carry an empty list (or omit the field entirely).
287
+ */
288
+ export interface ClientSegmentBoundary {
289
+ depth: number;
290
+ error?: ErrorComponent;
291
+ notFound?: NotFoundComponent;
292
+ }
293
+
294
+ export interface ClientRoute {
295
+ component?: React.ComponentType<Record<string, unknown>>;
296
+ load: () => Promise<{
297
+ default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
298
+ }>;
299
+ pageRoute?: RuntimeRoute;
300
+ pattern: string;
301
+ regex: RegExp;
302
+ /**
303
+ * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
304
+ * to the route-chain index used on the server side, so `buildPageElement`
305
+ * can interleave boundaries at the exact same positions that the server
306
+ * used in `buildElement` — guaranteeing hydration consistency.
307
+ */
308
+ segmentBoundaries?: ClientSegmentBoundary[];
309
+ }
310
+
311
+ /**
312
+ * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
313
+ * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
314
+ * on navigation via fetchPageState.
315
+ */
316
+ export type LoadedClientRoute = ClientRoute & {
317
+ component: React.ComponentType<Record<string, unknown>>;
318
+ pageRoute: RuntimeRoute;
319
+ };
320
+
321
+ export interface RouterProviderProps {
322
+ /**
323
+ * When `true` (default), the router automatically re-fetches the current page
324
+ * whenever a server `revalidatePath()` call targets it. The signal is the
325
+ * `X-Furin-Revalidate` header detected on any `window.fetch` response.
326
+ *
327
+ * Set to `false` to opt out and call `router.refresh()` manually instead.
328
+ */
329
+ autoRefresh: boolean;
330
+ /**
331
+ * Sub-path prefix for static deployments (e.g. "/furin").
332
+ * Must start with "/" and have no trailing slash.
333
+ * Default: "" (site served from root).
334
+ *
335
+ * When set:
336
+ * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
337
+ * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
338
+ * - `fetch` calls use the physical path `basePath + logicalHref`.
339
+ */
340
+ basePath: string;
341
+ defaultPreload: PreloadStrategy;
342
+ defaultPreloadDelay: number;
343
+ defaultPreloadStaleTime: number;
344
+ initialData: Record<string, unknown>;
345
+ /**
346
+ * Slice 10 — server-logged error digest threaded from
347
+ * `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
348
+ * `FurinErrorBoundary` so that if a client-side error escapes the
349
+ * per-segment boundaries (root layout crash, hydration mismatch, …), the
350
+ * fallback UI surfaces the id a user would find in server logs.
351
+ * Undefined when the initial SSR response was successful (no server-side
352
+ * error digest to correlate).
353
+ */
354
+ initialDigest: string | undefined;
355
+ /**
356
+ * The route matched at hydration time. `null` is a valid value ONLY when
357
+ * `initialNotFound` is also provided — it signals the initial URL didn't
358
+ * match any registered route (direct load to an unknown URL). The provider
359
+ * then mounts in a "not-found" state so the root `not-found.tsx` hydrates
360
+ * inside a live RouterContext — critical for Links in the not-found UI to
361
+ * participate in SPA navigation instead of triggering a full-page reload.
362
+ */
363
+ initialMatch: LoadedClientRoute | null;
364
+ /**
365
+ * When set, the provider boots into the inline not-found state as if a
366
+ * prior SPA navigation hit a 404. Callers set this when the server-rendered
367
+ * HTML carries `__FURIN_DATA__.__furinStatus === 404` — either because the
368
+ * loader threw `notFound()` (rare at hydration time) or, more commonly,
369
+ * because the URL didn't match any client route and `initialMatch` is
370
+ * `null`. In the unmatched-URL case the depth-0 `rootBoundaries` are used
371
+ * as the boundary chain, matching the server's `renderRootNotFound` choice.
372
+ */
373
+ initialNotFound: { data?: unknown; message?: string } | undefined;
374
+ /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
375
+ prefetchCacheSize: number;
376
+ root: RuntimeRoute | null;
377
+ routes: ClientRoute[];
378
+ }
379
+
380
+ interface RouterState {
381
+ data: Record<string, unknown>;
382
+ /** The canonical href after server-side redirects (e.g. query-default redirect). */
383
+ finalHref?: string;
384
+ /**
385
+ * The currently rendered route.
386
+ *
387
+ * `null` is a valid value ONLY when `notFound` is also set — it signals the
388
+ * initial URL didn't match any registered route (direct load to an unknown
389
+ * URL). In that case the provider renders the root `not-found.tsx` directly
390
+ * and waits for the next `navigate()` call to populate `match`. Every other
391
+ * state (including loader-triggered `notFound()` on a matched route) keeps a
392
+ * non-null `match`. Render code MUST guard on `notFound` before dereferencing.
393
+ */
394
+ match: LoadedClientRoute | null;
395
+ /**
396
+ * Slice 8 — set when the matched route's loader threw `notFound()` on the
397
+ * server (signalled via `__FURIN_DATA__.__furinStatus === 404`). Triggers
398
+ * inline rendering of the deepest segment-level not-found.tsx instead of
399
+ * the normal layout+page tree, mirroring the server's `buildNotFoundElement`.
400
+ */
401
+ notFound?: { data?: unknown; message?: string };
402
+ /**
403
+ * Explicit boundary chain to use for the not-found render.
404
+ *
405
+ * - **Set** (typically to depth-0 only) when no client-side route matched the
406
+ * navigation URL — the root `not-found.tsx` is the correct fallback and no
407
+ * page-specific segment context exists.
408
+ * - **Absent** when a matched route's loader called `notFound()`, in which
409
+ * case `match.segmentBoundaries` is used (preserves per-route not-found).
410
+ */
411
+ notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
412
+ title?: string;
413
+ }
414
+
415
+ /** @internal */
416
+ export interface CacheEntry {
417
+ createdAt: number;
418
+ promise: Promise<RouterState | null>;
419
+ staleTime: number;
420
+ }
421
+
422
+ /** @internal Exported for unit testing only. */
423
+ export function shouldRefetch(entry: CacheEntry): boolean {
424
+ return Date.now() - entry.createdAt > entry.staleTime;
425
+ }
426
+
427
+ const HASH_FRAGMENT_RE = /#.*$/;
428
+
429
+ function stripHashFromHref(href: string): string {
430
+ return href.replace(HASH_FRAGMENT_RE, "");
431
+ }
432
+
433
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
434
+ * Query strings and hashes are preserved and re-attached after normalization. */
435
+ export function normalizeHref(href: string): string {
436
+ const url = new URL(href, "http://localhost");
437
+ let pathname = url.pathname;
438
+ if (pathname !== "/") {
439
+ pathname = pathname.replace(/\/+$/g, "");
440
+ }
441
+ return pathname + url.search + url.hash;
442
+ }
443
+
444
+ /** Strips a single trailing slash from a pathname. Root `/` and empty string are preserved. */
445
+ function normalizePath(path: string): string {
446
+ if (path === "/" || path === "") {
447
+ return path;
448
+ }
449
+ return path.endsWith("/") ? path.slice(0, -1) : path;
450
+ }
451
+
452
+ // ── Slice 8 helpers — SPA 404 inline rendering ─────────────────────────────────
453
+
454
+ /**
455
+ * Classification of a fetch response during SPA navigation. Returned by the
456
+ * pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
457
+ *
458
+ * - `ok` — 2xx response with usable loader data; render normally.
459
+ * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`; the
460
+ * caller should render the not-found UI inline (no full-page reload).
461
+ * - `bail` — any other non-2xx (5xx, stale-deploy, unparseable payload…);
462
+ * the caller falls back to a full-page navigation so the browser picks up
463
+ * whatever the server wants to send (could be an error page, redirect, etc.).
464
+ *
465
+ * @internal Exported for unit testing only.
466
+ */
467
+ export type SpaResponseKind =
468
+ | { kind: "ok" }
469
+ | { kind: "not-found"; error: { data?: unknown; message?: string } }
470
+ | { kind: "bail" };
471
+
472
+ /**
473
+ * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
474
+ * already-parsed `__FURIN_DATA__` payload. The 404 signal is trusted over the
475
+ * HTTP status (guards against proxies that rewrite status but preserve body),
476
+ * while any other non-ok HTTP status triggers a bail even if the payload is
477
+ * well-formed.
478
+ *
479
+ * @internal Exported for unit testing only.
480
+ */
481
+ export function classifySpaResponse(
482
+ status: number,
483
+ data: Record<string, unknown> | null
484
+ ): SpaResponseKind {
485
+ if (!data) {
486
+ return { kind: "bail" };
487
+ }
488
+ if (((status >= 200 && status < 300) || status === 404) && data.__furinStatus === 404) {
489
+ const notFound = data.__furinNotFound as { data?: unknown; message?: string } | undefined;
490
+ return { kind: "not-found", error: notFound ?? {} };
491
+ }
492
+ if (status >= 200 && status < 300) {
493
+ return { kind: "ok" };
494
+ }
495
+ return { kind: "bail" };
496
+ }
497
+
498
+ /**
499
+ * Decides whether a native `<a>` click should be intercepted and converted
500
+ * to an SPA navigation. Returns the logical href to navigate to, or `null`
501
+ * when the browser should handle the click normally.
502
+ *
503
+ * Pure function: all external dependencies (current origin, pathname) are
504
+ * passed as parameters so tests need neither DOM globals nor mocks.
505
+ *
506
+ * @internal Exported for unit testing only.
507
+ */
508
+ export function shouldInterceptClick(
509
+ anchor: { href: string; target: string; hasAttribute(name: string): boolean },
510
+ event: { metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean },
511
+ basePath: string,
512
+ currentOrigin: string,
513
+ currentPathname: string
514
+ ): string | null {
515
+ // Respect modifier keys (new tab, etc.)
516
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
517
+ return null;
518
+ }
519
+
520
+ // Respect explicit target
521
+ if (anchor.target && anchor.target !== "_self") {
522
+ return null;
523
+ }
524
+
525
+ // Respect download attribute
526
+ if (anchor.hasAttribute("download")) {
527
+ return null;
528
+ }
529
+
530
+ const href = anchor.href;
531
+ if (!href) {
532
+ return null;
533
+ }
534
+
535
+ let url: URL;
536
+ try {
537
+ url = new URL(href, currentOrigin);
538
+ } catch {
539
+ return null;
540
+ }
541
+
542
+ // External link — let the browser handle it
543
+ if (url.origin !== currentOrigin) {
544
+ return null;
545
+ }
546
+
547
+ // Hash-only navigation on the same page — let the browser handle scrolling.
548
+ // Normalize trailing slashes so `/docs` and `/docs/` are treated as equal.
549
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
550
+ return null;
551
+ }
552
+
553
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
554
+ const normalizedBase = normalizePath(basePath);
555
+ const normalizedPathname = normalizePath(url.pathname);
556
+ if (
557
+ normalizedBase &&
558
+ normalizedPathname !== normalizedBase &&
559
+ !normalizedPathname.startsWith(`${normalizedBase}/`)
560
+ ) {
561
+ return null;
562
+ }
563
+ return logicalPath + url.search + url.hash;
564
+ }
565
+
566
+ /**
567
+ * Picks the deepest not-found component declared on the match's boundary
568
+ * chain. Mirrors the server's `route.notFound ?? root.notFound` selection:
569
+ * since `segmentBoundaries` is ordered shallow→deep, the last entry with a
570
+ * `notFound` wins. Returns undefined when no boundary on the chain declares
571
+ * a not-found convention.
572
+ *
573
+ * @internal Exported for unit testing only.
574
+ */
575
+ export function pickDeepestNotFound(
576
+ boundaries: ClientSegmentBoundary[] | undefined
577
+ ): NotFoundComponent | undefined {
578
+ if (!boundaries) {
579
+ return;
580
+ }
581
+ for (let i = boundaries.length - 1; i >= 0; i--) {
582
+ const seg = boundaries[i];
583
+ if (seg?.notFound) {
584
+ return seg.notFound;
585
+ }
586
+ }
587
+ return;
588
+ }
589
+
590
+ const DefaultClientNotFoundFallback: NotFoundComponent = ({ error }) =>
591
+ createElement(DefaultNotFoundScreen, { message: error.message });
592
+
593
+ /**
594
+ * Builds the bare not-found element rendered inline by RouterProvider on SPA
595
+ * navigation when the server signalled a 404. Matches the server's
596
+ * `buildNotFoundElement` exactly — NO layouts, NO segment boundaries, just the
597
+ * deepest user-declared `not-found.tsx` (or the built-in default). Preserving
598
+ * layouts on 404 is a deliberate non-goal for this slice: it would diverge
599
+ * from the server's current behaviour and require coordinated changes on both
600
+ * sides.
601
+ *
602
+ * Accepts the boundary chain directly (rather than a full `LoadedClientRoute`)
603
+ * so callers can pass a subset (e.g. depth-0 only for unmatched URLs) without
604
+ * fabricating a synthetic route object.
605
+ *
606
+ * @internal Exported for unit testing only.
607
+ */
608
+ export function buildNotFoundPageElement(
609
+ boundaries: ClientSegmentBoundary[] | undefined,
610
+ error: { data?: unknown; message?: string }
611
+ ): React.ReactNode {
612
+ const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
613
+ return createElement(Fallback, { error });
614
+ }
615
+
616
+ /**
617
+ * Root-level safety-net options forwarded onto the outermost
618
+ * `FurinErrorBoundary` that wraps the entire RouterProvider tree. See
619
+ * `buildRouterTree` for the full rationale.
620
+ */
621
+ export interface RootBoundaryOptions {
622
+ /**
623
+ * Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
624
+ * When the server's SSR response carried a digest (loader error or shell
625
+ * recovery) this value lets the client's fallback UI display the SAME id a
626
+ * user would find in the server logs — without having to recompute and
627
+ * potentially produce a different hash from a different error instance.
628
+ */
629
+ digest?: string;
630
+ onReset?: () => void;
631
+ resetKey?: string | number;
632
+ }
633
+
634
+ /**
635
+ * Composes the outermost tree produced by `RouterProvider`:
636
+ *
637
+ * <FurinErrorBoundary digest onReset resetKey>
638
+ * <RouterContext.Provider value={context}>
639
+ * {pageElement}
640
+ * </RouterContext.Provider>
641
+ * </FurinErrorBoundary>
642
+ *
643
+ * This top boundary is the LAST line of defence. Per-segment
644
+ * `FurinErrorBoundary`s inserted by `buildPageElement` only wrap the page
645
+ * subtree BELOW the root layout, so they cannot catch errors thrown in:
646
+ * - the root layout itself,
647
+ * - hydration mismatches (these tear the whole tree before any inner
648
+ * boundary is reached),
649
+ * - the RouterProvider / page-building scaffolding code.
650
+ *
651
+ * We deliberately omit the `fallback` prop so the boundary falls back to its
652
+ * built-in `DefaultErrorFallback` — if a user-authored fallback crashed
653
+ * during its own render, we'd still have a guaranteed-to-render UI here.
654
+ * Users who want a custom *branded* global error UI author a root-level
655
+ * `error.tsx`; that convention is already picked up by `segmentBoundaries`
656
+ * at depth 0 and sits inside this top boundary.
657
+ *
658
+ * @internal Exported for unit testing only.
659
+ */
660
+ export function buildRouterTree(
661
+ context: RouterContextValue,
662
+ pageElement: React.ReactNode,
663
+ options: RootBoundaryOptions
664
+ ): React.ReactElement {
665
+ return (
666
+ <FurinErrorBoundary {...options}>
667
+ <RouterContext.Provider value={context}>{pageElement}</RouterContext.Provider>
668
+ </FurinErrorBoundary>
669
+ );
670
+ }
671
+
672
+ /**
673
+ * Options threaded from `RouterProvider` (or a test harness) into each
674
+ * boundary that `buildPageElement` inserts:
675
+ *
676
+ * - `onReset` — invoked by `FurinErrorBoundary.reset` after it clears local
677
+ * error state. RouterProvider wires this to `refresh()` so the user's
678
+ * `reset()` prop re-runs the current route's loaders in addition to
679
+ * remounting the subtree.
680
+ * - `resetKey` — when it changes, both boundary classes clear their latched
681
+ * error. RouterProvider passes `currentHref`, so navigating between
682
+ * sibling routes that share a boundary (e.g. /blog/a → /blog/b) auto-clears
683
+ * any stuck error state even when the boundary instance persists.
684
+ */
685
+ export interface BoundaryOptions {
686
+ onReset?: () => void;
687
+ resetKey?: string | number;
688
+ }
689
+
690
+ /**
691
+ * Wraps `inner` with the client-side boundary pair declared at one depth.
692
+ * Error boundary must be OUTSIDE the not-found boundary — see the detailed
693
+ * justification in `render/element.tsx`'s `wrapInBoundaries`. The client
694
+ * mirrors the server's wrap order exactly so hydration sees an identical
695
+ * React tree.
696
+ */
697
+ function wrapPageBoundaries(
698
+ inner: React.ReactNode,
699
+ segment: ClientSegmentBoundary | undefined,
700
+ options: BoundaryOptions | undefined
701
+ ): React.ReactNode {
702
+ if (!segment) {
703
+ return inner;
704
+ }
705
+ let wrapped = inner;
706
+ if (segment.notFound) {
707
+ wrapped = (
708
+ <FurinNotFoundBoundary fallback={segment.notFound} resetKey={options?.resetKey}>
709
+ {wrapped}
710
+ </FurinNotFoundBoundary>
711
+ );
712
+ }
713
+ if (segment.error) {
714
+ wrapped = (
715
+ <FurinErrorBoundary
716
+ fallback={segment.error}
717
+ onReset={options?.onReset}
718
+ resetKey={options?.resetKey}
719
+ >
720
+ {wrapped}
721
+ </FurinErrorBoundary>
722
+ );
723
+ }
724
+ return wrapped;
725
+ }
726
+
727
+ /** @internal Exported for unit testing only. */
728
+ export function buildPageElement(
729
+ match: LoadedClientRoute,
730
+ root: RuntimeRoute | null,
731
+ data: Record<string, unknown>,
732
+ options: BoundaryOptions | undefined
733
+ ): React.ReactNode {
734
+ let element: React.ReactNode = createElement(match.component, data);
735
+
736
+ // Collect non-root layouts from the route chain (bottom-up)
737
+ const allLayouts: React.ComponentType<Record<string, unknown> & { children: React.ReactNode }>[] =
738
+ [];
739
+ let current: RuntimeRoute | undefined = match.pageRoute;
740
+ while (current) {
741
+ if (current.layout) {
742
+ allLayouts.unshift(current.layout);
743
+ }
744
+ current = current.parent;
745
+ }
746
+
747
+ // If a root layout exists, the first entry in allLayouts IS the root — skip it here
748
+ const layouts = root ? allLayouts.slice(1) : allLayouts;
749
+
750
+ // Index boundaries by depth for O(1) lookup. `layouts[i]` corresponds to
751
+ // route-chain depth `i + 1` (depth 0 = root layout, handled separately).
752
+ const byDepth = new Map<number, ClientSegmentBoundary>();
753
+ for (const segment of match.segmentBoundaries ?? []) {
754
+ byDepth.set(segment.depth, segment);
755
+ }
756
+
757
+ // Inside-out: at each layout level wrap the subtree with its same-depth
758
+ // boundary (so the boundary sits INSIDE the layout), then wrap with the
759
+ // layout itself.
760
+ for (let i = layouts.length - 1; i >= 0; i--) {
761
+ element = wrapPageBoundaries(element, byDepth.get(i + 1), options);
762
+ const Layout = layouts[i];
763
+ if (Layout) {
764
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
765
+ element = createElement(Layout, { ...data } as any, element);
766
+ }
767
+ }
768
+
769
+ // Depth 0 boundary wraps EVERYTHING below the root layout.
770
+ element = wrapPageBoundaries(element, byDepth.get(0), options);
771
+
772
+ if (root?.layout) {
773
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
774
+ element = createElement(root.layout, { ...data } as any, element);
775
+ }
776
+
777
+ return element;
778
+ }
779
+
780
+ // ── Scroll restoration helpers ─────────────────────────────────────────────────
781
+
782
+ const SCROLL_STORAGE_KEY = "__furin_scroll__";
783
+
784
+ function getHistoryKey(state: unknown): string | undefined {
785
+ return (state as { _furinKey?: string } | null)?._furinKey;
786
+ }
787
+
788
+ function generateHistoryKey(): string {
789
+ return Math.random().toString(36).slice(2, 9);
790
+ }
791
+
792
+ function saveScrollPosition(key: string): void {
793
+ try {
794
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
795
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
796
+ positions[key] = window.scrollY;
797
+ const keys = Object.keys(positions);
798
+ if (keys.length > 50) {
799
+ delete positions[keys[0] as string];
800
+ }
801
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
802
+ } catch {
803
+ // sessionStorage unavailable (private mode, quota exceeded, etc.)
804
+ }
805
+ }
806
+
807
+ // ── Path helpers ───────────────────────────────────────────────────────────────
808
+
809
+ /**
810
+ * Returns `true` when the server reports a different build-id from the one
811
+ * embedded in the initial HTML (`<meta name="furin-build-id">`). The client
812
+ * bundle is then stale and SPA navigation would mount wrong components, so
813
+ * the caller must force a full-page reload to pick up the new deploy.
814
+ */
815
+ function isStaleDeployResponse(res: Response): boolean {
816
+ const serverBuildId = res.headers.get("x-furin-build-id");
817
+ if (!serverBuildId) {
818
+ return false;
819
+ }
820
+ const metaEl =
821
+ typeof document === "undefined"
822
+ ? null
823
+ : document.querySelector<HTMLMetaElement>('meta[name="furin-build-id"]');
824
+ const clientBuildId = metaEl?.content;
825
+ return Boolean(clientBuildId && serverBuildId !== clientBuildId);
826
+ }
827
+
828
+ /**
829
+ * Parses the HTML payload of a page response into the pieces `fetchPageState`
830
+ * cares about: the document (for title), the __FURIN_DATA__ loader payload,
831
+ * and the logical `finalHref` after any server-side redirect.
832
+ */
833
+ async function parsePageResponse(
834
+ res: Response,
835
+ basePath: string
836
+ ): Promise<{ data: Record<string, unknown> | null; finalHref: string | undefined; title: string }> {
837
+ let finalHref: string | undefined;
838
+ if (res.redirected) {
839
+ const final = new URL(res.url);
840
+ finalHref = toLogical(final.pathname, basePath) + final.search;
841
+ }
842
+ const html = await res.text();
843
+ const doc = new DOMParser().parseFromString(html, "text/html");
844
+ const dataEl = doc.getElementById("__FURIN_DATA__");
845
+ const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
846
+ return { data, finalHref, title: doc.title };
847
+ }
848
+
849
+ /** Strips basePath prefix from a physical pathname, returning the logical path. */
850
+ export function toLogical(physicalPathname: string, basePath: string): string {
851
+ if (
852
+ basePath &&
853
+ physicalPathname.startsWith(basePath) &&
854
+ // Require a path boundary after the prefix so "/furin" doesn't match "/furinity/foo"
855
+ (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")
856
+ ) {
857
+ return physicalPathname.slice(basePath.length) || "/";
858
+ }
859
+ return physicalPathname;
860
+ }
861
+
862
+ export function RouterProvider({
863
+ routes,
864
+ root,
865
+ initialMatch,
866
+ initialData,
867
+ initialDigest,
868
+ initialNotFound,
869
+ autoRefresh,
870
+ basePath,
871
+ defaultPreload,
872
+ defaultPreloadDelay,
873
+ defaultPreloadStaleTime,
874
+ prefetchCacheSize,
875
+ }: RouterProviderProps): React.ReactElement {
876
+ const _autoRefresh = autoRefresh ?? true;
877
+ const _basePath = basePath ?? "";
878
+ const _defaultPreload = defaultPreload ?? "intent";
879
+ const _defaultPreloadDelay = defaultPreloadDelay ?? 50;
880
+ const _defaultPreloadStaleTime = defaultPreloadStaleTime ?? 30_000;
881
+ const _prefetchCacheSize = prefetchCacheSize ?? 50;
882
+ // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
883
+ // the provider boots into the inline not-found UI (see `initialNotFound` JSDoc).
884
+ // `notFoundBoundaries` is left undefined so the render path can fall through to
885
+ // the memoised `rootBoundaries` below (which isn't available yet at useState init).
886
+ const [state, setState] = useState<RouterState>(() => ({
887
+ match: initialMatch,
888
+ data: initialData,
889
+ notFound: initialNotFound,
890
+ }));
891
+ const [isNavigating, setIsNavigating] = useState(false);
892
+ // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
893
+ // detection works with route patterns that never include the basePath prefix.
894
+ const [currentHref, setCurrentHref] = useState<string>(() => {
895
+ if (typeof window === "undefined") {
896
+ return "/";
897
+ }
898
+ return normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
899
+ });
900
+ const prefetchCache = useRef(new Map<string, CacheEntry>());
901
+ /** Monotonic counter to discard stale navigations (race condition guard). */
902
+ const navVersion = useRef(0);
903
+ /**
904
+ * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
905
+ * This replaces the fragile double-requestAnimationFrame pattern with a render-
906
+ * synchronous scroll that fires immediately after React commits the new route.
907
+ */
908
+ const pendingScrollRef = useRef<
909
+ { type: "restore"; key: string } | { type: "reset"; href: string } | null
910
+ >(null);
911
+ /**
912
+ * Tracks the last successfully rendered match for use in the no-route 404 path.
913
+ * `null` on the initial render when the URL didn't match any route and the
914
+ * provider booted directly into the not-found state; flips to a real match as
915
+ * soon as the user navigates away via `navigate()` or the back button.
916
+ */
917
+ const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
918
+
919
+ /**
920
+ * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
921
+ * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
922
+ * handles it — the root `not-found.tsx` (depth 0) is the correct component to
923
+ * render inline instead of doing a full-page reload.
924
+ * Computed once per `routes` change; stable across navigations.
925
+ */
926
+ const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
927
+ for (const route of routes) {
928
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
929
+ if (depth0) {
930
+ return [depth0];
931
+ }
932
+ }
933
+ return;
934
+ }, [routes]);
935
+
936
+ const fetchPageState = useCallback(
937
+ async (rawLogicalHref: string): Promise<RouterState | null> => {
938
+ // Normalize trailing slashes so "/docs/routing/" matches the route
939
+ // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
940
+ // redirect to or serve URLs with a trailing slash.
941
+ const logicalHref = normalizeHref(rawLogicalHref);
942
+ try {
943
+ // Physical href: what the browser/server actually receives.
944
+ // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
945
+ const physicalHref = _basePath + logicalHref;
946
+ const url = new URL(physicalHref, window.location.origin);
947
+ // Route matching always uses the LOGICAL pathname (basePath stripped).
948
+ const logicalPathname = toLogical(url.pathname, _basePath);
949
+ const match = routes.find((r) => r.regex.test(logicalPathname));
950
+ if (!match) {
951
+ // No client-side route matched — the server will call renderRootNotFound.
952
+ // Fetch the URL so we can detect the __furinStatus: 404 signal embedded
953
+ // by renderRootNotFound and render the 404 UI inline (SPA) instead of
954
+ // forcing a jarring full-page reload.
955
+ const res = await fetch(physicalHref);
956
+ if (isStaleDeployResponse(res)) {
957
+ window.location.href = physicalHref;
958
+ return null;
959
+ }
960
+ const { data, finalHref, title } = await parsePageResponse(res, _basePath);
961
+ const kind = classifySpaResponse(res.status, data);
962
+ if (kind.kind !== "not-found") {
963
+ // Non-404 server response for an unmatched URL (e.g. 5xx) — bail to
964
+ // full-page navigation so the browser shows whatever the server sent.
965
+ return null;
966
+ }
967
+ // Strip internal signals before surfacing loader data.
968
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
969
+ return {
970
+ match: currentMatchRef.current,
971
+ data: cleanData,
972
+ title,
973
+ finalHref,
974
+ notFound: kind.error,
975
+ // Pass only depth-0 boundaries: for an unmatched URL the root
976
+ // not-found.tsx is always the right component — no page-specific
977
+ // segment context exists.
978
+ notFoundBoundaries: rootBoundaries,
979
+ };
980
+ }
981
+
982
+ // Parallelize HTML data fetch + JS chunk load for this route.
983
+ // The browser module cache makes match.load() near-instant for already-loaded pages.
984
+ const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
985
+
986
+ // Stale-deploy detection: if the server reports a different buildId, the client
987
+ // bundle is outdated and SPA navigation would mount wrong components / stale code.
988
+ // Force a full page reload to pick up the new bundle.
989
+ if (isStaleDeployResponse(res)) {
990
+ window.location.href = physicalHref;
991
+ return null;
992
+ }
993
+
994
+ // Parse the HTML payload BEFORE deciding whether to bail on !res.ok.
995
+ // Slice 8: a 404 response still carries a valid __FURIN_DATA__ with a
996
+ // `__furinStatus: 404` signal, which lets us render the not-found UI
997
+ // inline instead of doing a jarring full-page reload. Any other
998
+ // non-2xx still bails out (see `classifySpaResponse`).
999
+ const { data, finalHref, title } = await parsePageResponse(res, _basePath);
1000
+
1001
+ const kind = classifySpaResponse(res.status, data);
1002
+ if (kind.kind === "bail") {
1003
+ log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
1004
+ return null;
1005
+ }
1006
+
1007
+ const loadedMatch: LoadedClientRoute = {
1008
+ ...match,
1009
+ component: loadedMod.default.component,
1010
+ pageRoute: loadedMod.default._route,
1011
+ };
1012
+
1013
+ if (kind.kind === "not-found") {
1014
+ // Strip the server-injected signals from `data` before handing it to
1015
+ // the component — the NotFound payload is surfaced via `state.notFound`
1016
+ // instead, and leaking __furinStatus into component props would be
1017
+ // noise. The caller (RouterProvider render) ignores `data` when
1018
+ // `notFound` is set anyway, but we keep it tidy for devtools.
1019
+ const { __furinStatus, __furinNotFound, ...cleanData } = data ?? {};
1020
+ return {
1021
+ match: loadedMatch,
1022
+ data: cleanData,
1023
+ title,
1024
+ finalHref,
1025
+ notFound: kind.error,
1026
+ };
1027
+ }
1028
+
1029
+ return { match: loadedMatch, data: data ?? {}, title, finalHref };
1030
+ } catch (err: unknown) {
1031
+ log.error({ action: "navigate_failed", href: _basePath + logicalHref, error: String(err) });
1032
+ return null;
1033
+ }
1034
+ },
1035
+ [routes, _basePath, rootBoundaries]
1036
+ );
1037
+
1038
+ const invalidatePrefetch = useCallback((path: string, type: "page" | "layout" = "page") => {
1039
+ const normalizedPath = stripHashFromHref(path);
1040
+
1041
+ if (type === "page") {
1042
+ for (const key of [...prefetchCache.current.keys()]) {
1043
+ if (stripHashFromHref(key) === normalizedPath) {
1044
+ prefetchCache.current.delete(key);
1045
+ }
1046
+ }
1047
+ return;
1048
+ }
1049
+
1050
+ // layout: prefix match — evict the path itself and all nested children
1051
+ const prefix =
1052
+ normalizedPath === "/" || normalizedPath.endsWith("/")
1053
+ ? normalizedPath
1054
+ : `${normalizedPath}/`;
1055
+ for (const key of [...prefetchCache.current.keys()]) {
1056
+ const normalizedKey = stripHashFromHref(key);
1057
+ if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
1058
+ prefetchCache.current.delete(key);
1059
+ }
1060
+ }
1061
+ }, []);
1062
+
1063
+ const prefetch = useCallback(
1064
+ (href: string, opts?: { staleTime?: number }) => {
1065
+ const staleTime = opts?.staleTime ?? _defaultPreloadStaleTime;
1066
+ const existing = prefetchCache.current.get(href);
1067
+ if (existing && !shouldRefetch(existing)) {
1068
+ return;
1069
+ }
1070
+ prefetchCache.current.set(href, {
1071
+ promise: fetchPageState(href),
1072
+ createdAt: Date.now(),
1073
+ staleTime,
1074
+ });
1075
+ // Evict the oldest entry when the cap is exceeded
1076
+ if (prefetchCache.current.size > _prefetchCacheSize) {
1077
+ const oldest = prefetchCache.current.keys().next().value as string;
1078
+ prefetchCache.current.delete(oldest);
1079
+ }
1080
+ },
1081
+ [fetchPageState, _defaultPreloadStaleTime, _prefetchCacheSize]
1082
+ );
1083
+
1084
+ const navigate = useCallback(
1085
+ async (rawLogicalHref: string, opts?: { replace?: boolean; resetScroll?: boolean }) => {
1086
+ // Normalize trailing slashes so the prefetch cache key and route
1087
+ // matching stay consistent regardless of how the href was formed.
1088
+ const logicalHref = normalizeHref(rawLogicalHref);
1089
+ // logicalHref is the route-relative path (no basePath).
1090
+ // The prefetch cache is keyed by logical hrefs.
1091
+ prefetch(logicalHref);
1092
+ const myVersion = ++navVersion.current;
1093
+ setIsNavigating(true);
1094
+ try {
1095
+ const newState = await prefetchCache.current.get(logicalHref)?.promise;
1096
+ // Discard if a newer navigation was started while we were waiting
1097
+ if (navVersion.current !== myVersion) {
1098
+ return;
1099
+ }
1100
+ if (!newState) {
1101
+ log.warn({
1102
+ action: "navigate_fallback",
1103
+ href: logicalHref,
1104
+ reason: "prefetch_returned_null",
1105
+ });
1106
+ // Fall back to full-page navigation using the physical URL.
1107
+ window.location.href = _basePath + logicalHref;
1108
+ return;
1109
+ }
1110
+ currentMatchRef.current = newState.match;
1111
+ setState(newState);
1112
+ if (newState.title) {
1113
+ document.title = newState.title;
1114
+ }
1115
+ // effectiveHref is logical (finalHref from fetchPageState is also logical).
1116
+ const effectiveLogical = newState.finalHref ?? logicalHref;
1117
+ // Push the PHYSICAL path to browser history.
1118
+ const physicalEffective = _basePath + effectiveLogical;
1119
+ if (opts?.replace) {
1120
+ // Preserve the existing key — same history entry, URL just updated.
1121
+ window.history.replaceState(
1122
+ {
1123
+ ...((history.state as object) ?? {}),
1124
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
1125
+ },
1126
+ "",
1127
+ physicalEffective
1128
+ );
1129
+ } else {
1130
+ // Save current position before leaving, then push a fresh entry.
1131
+ const currentKey = getHistoryKey(history.state);
1132
+ if (currentKey) {
1133
+ saveScrollPosition(currentKey);
1134
+ }
1135
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
1136
+ }
1137
+ // Store the LOGICAL path in currentHref so Link active-state works.
1138
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
1139
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, _basePath));
1140
+ setCurrentHref(logicalPath + effectiveUrl.search);
1141
+ if (opts?.resetScroll ?? true) {
1142
+ pendingScrollRef.current = { type: "reset", href: physicalEffective };
1143
+ }
1144
+ } finally {
1145
+ // Only clear navigating flag if this is still the latest navigation
1146
+ if (navVersion.current === myVersion) {
1147
+ setIsNavigating(false);
1148
+ }
1149
+ }
1150
+ },
1151
+ [prefetch, _basePath]
1152
+ );
1153
+
1154
+ const refresh = useCallback(
1155
+ async (opts?: { resetScroll?: boolean }) => {
1156
+ // Convert the physical browser URL to a logical href before navigating.
1157
+ const logicalPath = toLogical(window.location.pathname, _basePath);
1158
+ const logicalHref = logicalPath + window.location.search;
1159
+ // Bust the cache for this exact logical page so navigate always re-fetches
1160
+ invalidatePrefetch(logicalHref, "page");
1161
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
1162
+ },
1163
+ [navigate, invalidatePrefetch, _basePath]
1164
+ );
1165
+
1166
+ // Expose refresh() to the HMR handler in _hydrate.tsx so that after a hot
1167
+ // reload of a loader-bearing route the client re-fetches fresh data instead
1168
+ // of rendering with stale initialData from the initial SSR payload.
1169
+ useEffect(() => {
1170
+ if (typeof window !== "undefined") {
1171
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
1172
+ (window as any).__FURIN_HMR_REFRESH__ = refresh;
1173
+ return () => {
1174
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
1175
+ (window as any).__FURIN_HMR_REFRESH__ = undefined;
1176
+ };
1177
+ }
1178
+ }, [refresh]);
1179
+
1180
+ const handlePopState = useCallback(() => {
1181
+ // Capture the destination key IMMEDIATELY — history.state is already the
1182
+ // destination entry when popstate fires, before any awaits. Keeping the
1183
+ // handler synchronous prevents browsers (notably Chrome) from treating the
1184
+ // event as resolved and applying their own scroll restoration prematurely.
1185
+ const destKey = getHistoryKey(history.state);
1186
+ // Convert physical browser URL to logical href for cache lookup + fetchPageState.
1187
+ // Normalize trailing slashes so "/docs/routing/" back-button navigations
1188
+ // still match the route pattern "/docs/routing".
1189
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, _basePath));
1190
+ const logicalHref = logicalPath + window.location.search;
1191
+ const myVersion = ++navVersion.current;
1192
+ setIsNavigating(true);
1193
+
1194
+ (async () => {
1195
+ try {
1196
+ // Check prefetch cache before fetching fresh (keyed by logical href)
1197
+ const cached = prefetchCache.current.get(logicalHref);
1198
+ let newState: RouterState | null;
1199
+ if (cached && !shouldRefetch(cached)) {
1200
+ newState = await cached.promise;
1201
+ } else {
1202
+ newState = await fetchPageState(logicalHref);
1203
+ }
1204
+ // Discard if a newer navigation was started while we were waiting
1205
+ if (navVersion.current !== myVersion) {
1206
+ return;
1207
+ }
1208
+ if (!newState) {
1209
+ log.warn({
1210
+ action: "popstate_fallback",
1211
+ href: logicalHref,
1212
+ reason: "fetchPageState_returned_null",
1213
+ });
1214
+ window.location.reload();
1215
+ return;
1216
+ }
1217
+ currentMatchRef.current = newState.match;
1218
+ setState(newState);
1219
+ if (newState.title) {
1220
+ document.title = newState.title;
1221
+ }
1222
+ // effectiveHref is logical (includes search); push physical to history if server redirected.
1223
+ const effectiveLogical = newState.finalHref ?? logicalHref;
1224
+ if (newState.finalHref) {
1225
+ // Preserve _furinKey so scroll restoration still works after a redirect.
1226
+ window.history.replaceState(history.state, "", _basePath + effectiveLogical);
1227
+ }
1228
+ // effectiveLogical already contains the search params — no URL round-trip needed.
1229
+ setCurrentHref(normalizeHref(effectiveLogical));
1230
+ // Queue scroll restoration for the layout effect tied to currentHref.
1231
+ if (destKey) {
1232
+ pendingScrollRef.current = { type: "restore", key: destKey };
1233
+ } else {
1234
+ window.scrollTo({ top: 0, behavior: "instant" });
1235
+ }
1236
+ } finally {
1237
+ if (navVersion.current === myVersion) {
1238
+ setIsNavigating(false);
1239
+ }
1240
+ }
1241
+ })();
1242
+ }, [fetchPageState, _basePath]);
1243
+
1244
+ // Disable native scroll restoration and assign a key to the initial history entry.
1245
+ // No cleanup: in an SPA once manual it stays manual for the app lifetime.
1246
+ useEffect(() => {
1247
+ history.scrollRestoration = "manual";
1248
+ if (!getHistoryKey(history.state)) {
1249
+ history.replaceState(
1250
+ { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
1251
+ ""
1252
+ );
1253
+ }
1254
+ }, []);
1255
+
1256
+ // Render-synchronous scroll restoration. Fires immediately after React commits
1257
+ // the new route, eliminating the race conditions inherent in double rAF.
1258
+ useLayoutEffect(() => {
1259
+ const instruction = pendingScrollRef.current;
1260
+ if (!instruction) {
1261
+ return;
1262
+ }
1263
+ pendingScrollRef.current = null;
1264
+
1265
+ if (instruction.type === "restore") {
1266
+ try {
1267
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
1268
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
1269
+ const y = positions[instruction.key] ?? 0;
1270
+ window.scrollTo({ top: y, behavior: "instant" });
1271
+ } catch {
1272
+ window.scrollTo({ top: 0, behavior: "instant" });
1273
+ }
1274
+ return;
1275
+ }
1276
+
1277
+ // instruction.type === "reset"
1278
+ const destUrl = new URL(instruction.href, window.location.origin);
1279
+ if (destUrl.hash) {
1280
+ const id = decodeURIComponent(destUrl.hash.slice(1));
1281
+ const element = document.getElementById(id);
1282
+ if (element) {
1283
+ element.scrollIntoView({ behavior: "instant", block: "start" });
1284
+ }
1285
+ } else {
1286
+ window.scrollTo({ top: 0, behavior: "instant" });
1287
+ }
1288
+ }, [currentHref]);
1289
+
1290
+ // Handle browser back/forward
1291
+ useEffect(() => {
1292
+ window.addEventListener("popstate", handlePopState);
1293
+ return () => window.removeEventListener("popstate", handlePopState);
1294
+ }, [handlePopState]);
1295
+
1296
+ // Intercept clicks on native <a> tags so that internal links (including
1297
+ // those rendered by MDX, CMS content, or third-party components) participate
1298
+ // in SPA navigation instead of triggering full-page reloads.
1299
+ useEffect(() => {
1300
+ if (typeof window === "undefined") {
1301
+ return;
1302
+ }
1303
+ const handler = (e: MouseEvent) => {
1304
+ if (e.defaultPrevented) {
1305
+ return;
1306
+ }
1307
+ const anchor = (e.target as HTMLElement).closest("a");
1308
+ if (!(anchor instanceof HTMLAnchorElement)) {
1309
+ return;
1310
+ }
1311
+ // Ignore Furin Link anchors — they handle their own navigation via
1312
+ // LinkInteractive.handleClick. This guards against double-interception
1313
+ // in dev mode where React synthetic-event defaultPrevented may not
1314
+ // propagate reliably to the native event after Bun HMR reloads.
1315
+ if (anchor.closest("a[data-furin-link]")) {
1316
+ return;
1317
+ }
1318
+ const logicalHref = shouldInterceptClick(
1319
+ anchor,
1320
+ e,
1321
+ _basePath,
1322
+ window.location.origin,
1323
+ window.location.pathname
1324
+ );
1325
+ if (logicalHref === null) {
1326
+ return;
1327
+ }
1328
+ e.preventDefault();
1329
+ navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
1330
+ };
1331
+ document.addEventListener("click", handler);
1332
+ return () => document.removeEventListener("click", handler);
1333
+ }, [navigate, _basePath]);
1334
+
1335
+ // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
1336
+ // This ensures that API routes calling revalidatePath() automatically bust the
1337
+ // client prefetch cache, even for non-navigation fetches (e.g. form submissions).
1338
+ // When autoRefresh=true (default), also re-fetches the current page if it was invalidated.
1339
+ useEffect(() => {
1340
+ if (typeof window === "undefined") {
1341
+ return;
1342
+ }
1343
+ const originalFetch = window.fetch;
1344
+ const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
1345
+ const response = await originalFetch.apply(window, args);
1346
+ const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
1347
+ applyRevalidateHeader(response.headers, (path, type = "page") => {
1348
+ invalidatePrefetch(path, type);
1349
+ invalidated.push({ path, type });
1350
+ });
1351
+ if (_autoRefresh && invalidated.length > 0) {
1352
+ const currentLogicalPath =
1353
+ normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
1354
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
1355
+ // fire-and-forget: don't block the original fetch caller
1356
+ refresh();
1357
+ }
1358
+ }
1359
+ return response;
1360
+ };
1361
+ // Copy static fetch methods (e.g. preconnect) so the patched value satisfies typeof fetch.
1362
+ Object.assign(wrapped, originalFetch);
1363
+ // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
1364
+ window.fetch = wrapped as any;
1365
+ return () => {
1366
+ window.fetch = originalFetch;
1367
+ };
1368
+ }, [invalidatePrefetch, refresh, _autoRefresh]);
1369
+
1370
+ // Slice 8 — when a prior SPA navigation hit a loader-thrown or catch-all 404,
1371
+ // render the bare not-found element (mirrors server's `buildNotFoundElement`).
1372
+ // - `notFoundBoundaries`: set when no route matched (always depth-0 / root
1373
+ // not-found.tsx, since no page-specific context applies to unknown URLs).
1374
+ // - Fallback to `match.segmentBoundaries`: set when a matched loader called
1375
+ // `notFound()` (preserves the deepest route-level not-found.tsx).
1376
+ // - Fallback to `rootBoundaries`: the initial-hydration "direct load to an
1377
+ // unknown URL" case, where `state.match` is null because no client route
1378
+ // matched the boot URL. The provider booted into not-found mode to give
1379
+ // Links in the not-found UI a live RouterContext (so "Go Home" does SPA
1380
+ // navigation, not a full reload).
1381
+ // The render path is split explicitly rather than collapsed into a ternary
1382
+ // so TypeScript can narrow `state.match` to non-null for `buildPageElement`
1383
+ // — the invariant is "`state.match` is null only when `state.notFound` is set".
1384
+ let pageElement: React.ReactNode;
1385
+ if (state.notFound || !state.match) {
1386
+ pageElement = buildNotFoundPageElement(
1387
+ state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
1388
+ state.notFound ?? {}
1389
+ );
1390
+ } else {
1391
+ pageElement = buildPageElement(state.match, root, state.data, {
1392
+ // User's `reset()` prop → clear local boundary state (handled by the
1393
+ // boundary itself) → re-run loaders for the current route so transient
1394
+ // errors (bad state, expired data) can recover without a full reload.
1395
+ onReset: refresh,
1396
+ // Auto-clear latched errors when navigating between routes that share
1397
+ // a boundary instance — otherwise the new route would render INSIDE
1398
+ // the previous route's error fallback.
1399
+ resetKey: currentHref,
1400
+ });
1401
+ }
1402
+
1403
+ // Slice 9 + 10 — wrap the entire tree in a root FurinErrorBoundary that
1404
+ // catches anything per-segment boundaries missed (root layout crash,
1405
+ // hydration mismatch, scaffolding errors). `digest` is seeded from the
1406
+ // server's __FURIN_DATA__.__furinError.digest so client fallback UIs show
1407
+ // the same id the server already logged.
1408
+ return buildRouterTree(
1409
+ {
1410
+ basePath: _basePath,
1411
+ currentHref,
1412
+ navigate,
1413
+ prefetch,
1414
+ refresh,
1415
+ invalidatePrefetch,
1416
+ isNavigating,
1417
+ defaultPreload: _defaultPreload,
1418
+ defaultPreloadDelay: _defaultPreloadDelay,
1419
+ defaultPreloadStaleTime: _defaultPreloadStaleTime,
1420
+ },
1421
+ pageElement,
1422
+ {
1423
+ digest: initialDigest,
1424
+ onReset: refresh,
1425
+ resetKey: currentHref,
1426
+ }
1427
+ );
1428
+ }