@timber-js/app 0.2.0-alpha.142 → 0.2.0-alpha.143
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +8 -0
- package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
- package/dist/client/browser-entry/index.d.ts +1 -2
- package/dist/client/browser-entry/index.d.ts.map +1 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/internal.js +2 -99
- package/dist/client/internal.js.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/rsc-fetch.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +8 -8
- package/src/cli.ts +0 -0
- package/src/client/browser-entry/action-dispatch.ts +1 -12
- package/src/client/browser-entry/index.ts +2 -42
- package/src/client/browser-entry/router-init.ts +1 -24
- package/src/client/router.ts +2 -30
- package/src/client/rsc-fetch.ts +2 -2
- package/dist/client/stale-reload.d.ts +0 -59
- package/dist/client/stale-reload.d.ts.map +0 -1
- package/src/client/stale-reload.ts +0 -156
package/LICENSE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
DONTFUCKINGUSE LICENSE
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Daniel Saewitz
|
|
4
|
+
|
|
5
|
+
This software may not be used, copied, modified, merged, published,
|
|
6
|
+
distributed, sublicensed, or sold by anyone other than the copyright holder.
|
|
7
|
+
|
|
8
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action-dispatch.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/action-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;
|
|
1
|
+
{"version":3,"file":"action-dispatch.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/action-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,wBAAgB,kBAAkB,IAAI,IAAI,CA4FzC"}
|
|
@@ -21,8 +21,7 @@
|
|
|
21
21
|
* 5. hydrateApp() — hydrateRoot or deferred createRoot
|
|
22
22
|
* 6. setupPostHydration() — history stack, popstate, scroll
|
|
23
23
|
* 7. setupHmr() — dev-only HMR wiring
|
|
24
|
-
* 8.
|
|
25
|
-
* 9. timber-ready signal — E2E test readiness indicator
|
|
24
|
+
* 8. timber-ready signal — E2E test readiness indicator
|
|
26
25
|
*
|
|
27
26
|
* Design docs: 18-build-system.md §"Entry Files", 19-client-navigation.md
|
|
28
27
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAQH,OAAO,uCAAuC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-init.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/router-init.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"router-init.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/router-init.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAOnE,OAAO,EAGL,KAAK,uBAAuB,EAC7B,MAAM,sBAAsB,CAAC;AAG9B,MAAM,WAAW,iBAAiB;IAChC,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,cAAc,CAAC;IACvB,gBAAgB,EAAE,uBAAuB,GAAG,IAAI,CAAC;CAClD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CAyJhF"}
|
package/dist/client/internal.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { t as __exportAll } from "../index.js";
|
|
2
1
|
import { t as bindUseQueryStates } from "../_chunks/use-query-states-CbeQmext.js";
|
|
3
2
|
import { c as cachedSearchParams, i as _setCachedSearch, n as getSsrData, r as setSsrData, s as cachedSearch, t as clearSsrData } from "../_chunks/ssr-data-BOWsq18U.js";
|
|
4
3
|
import { a as setNavigationState, i as getNavigationState, o as useNavigationContext, r as NavigationProvider, t as setCurrentParams } from "../_chunks/use-segment-params-D1CzlgBo.js";
|
|
@@ -289,7 +288,7 @@ var RedirectError = class extends Error {
|
|
|
289
288
|
};
|
|
290
289
|
/**
|
|
291
290
|
* Thrown when the server signals a version skew (X-Timber-Reload header).
|
|
292
|
-
* Caught in navigate() to trigger a full page reload
|
|
291
|
+
* Caught in navigate() to trigger a full page reload.
|
|
293
292
|
* See TIM-446.
|
|
294
293
|
*/
|
|
295
294
|
var VersionSkewError = class extends Error {
|
|
@@ -431,86 +430,6 @@ async function fetchRscPayload(url, deps, stateTree, currentUrl, signal) {
|
|
|
431
430
|
};
|
|
432
431
|
}
|
|
433
432
|
//#endregion
|
|
434
|
-
//#region src/client/stale-reload.ts
|
|
435
|
-
var stale_reload_exports = /* @__PURE__ */ __exportAll({
|
|
436
|
-
isStaleClientReference: () => isStaleClientReference,
|
|
437
|
-
triggerStaleReload: () => triggerStaleReload
|
|
438
|
-
});
|
|
439
|
-
/**
|
|
440
|
-
* Stale Client Reference Reload
|
|
441
|
-
*
|
|
442
|
-
* When a new deployment ships updated bundles, clients running stale
|
|
443
|
-
* JavaScript may encounter "Could not find the module" errors during
|
|
444
|
-
* RSC Flight stream decoding. This happens because the RSC payload
|
|
445
|
-
* references module IDs from the new bundle that don't exist in the
|
|
446
|
-
* old client bundle.
|
|
447
|
-
*
|
|
448
|
-
* This module detects these specific errors and triggers a full page
|
|
449
|
-
* reload so the browser fetches the new bundle. A sessionStorage flag
|
|
450
|
-
* guards against infinite reload loops.
|
|
451
|
-
*
|
|
452
|
-
* See: LOCAL-332
|
|
453
|
-
*/
|
|
454
|
-
var RELOAD_FLAG_KEY = "__timber_stale_reload";
|
|
455
|
-
/**
|
|
456
|
-
* In-memory fallback counter for environments where sessionStorage is
|
|
457
|
-
* unavailable (private browsing, storage full, extension interference).
|
|
458
|
-
* Incremented each time triggerStaleReload() falls into the catch path.
|
|
459
|
-
* If the counter exceeds 0 on a subsequent call, the reload is suppressed
|
|
460
|
-
* to prevent an infinite loop. Resets naturally on page load (module
|
|
461
|
-
* re-evaluates) and can be manually reset via clearStaleReloadFlag().
|
|
462
|
-
*/
|
|
463
|
-
var memoryReloadCount = 0;
|
|
464
|
-
/**
|
|
465
|
-
* Check if an error is a stale client reference error from React's
|
|
466
|
-
* Flight client. These errors have the message pattern:
|
|
467
|
-
* "Could not find the module \"<id>\""
|
|
468
|
-
*
|
|
469
|
-
* This is thrown by react-server-dom-webpack's client when the RSC
|
|
470
|
-
* payload references a module ID that doesn't exist in the client's
|
|
471
|
-
* module map — typically because the server has been redeployed with
|
|
472
|
-
* new bundle hashes while the client is still running old JavaScript.
|
|
473
|
-
*/
|
|
474
|
-
function isStaleClientReference(error) {
|
|
475
|
-
if (!(error instanceof Error)) return false;
|
|
476
|
-
const msg = error.message;
|
|
477
|
-
return msg.includes("Could not find the module") || msg.includes("client reference not found");
|
|
478
|
-
}
|
|
479
|
-
/**
|
|
480
|
-
* Trigger a full page reload to pick up new bundles.
|
|
481
|
-
*
|
|
482
|
-
* Sets a sessionStorage flag before reloading. If the flag is already
|
|
483
|
-
* set (meaning we already reloaded once for this reason), we don't
|
|
484
|
-
* reload again — this prevents infinite reload loops if the error
|
|
485
|
-
* persists after reload (e.g., a genuine bug rather than a stale bundle).
|
|
486
|
-
*
|
|
487
|
-
* @returns true if a reload was triggered, false if suppressed (loop guard)
|
|
488
|
-
*/
|
|
489
|
-
function triggerStaleReload() {
|
|
490
|
-
try {
|
|
491
|
-
if (sessionStorage.getItem(RELOAD_FLAG_KEY)) {
|
|
492
|
-
console.warn("[timber] Stale client reference detected again after reload. Not reloading to prevent infinite loop. This may indicate a deployment issue — try a hard refresh.");
|
|
493
|
-
return false;
|
|
494
|
-
}
|
|
495
|
-
sessionStorage.setItem(RELOAD_FLAG_KEY, "1");
|
|
496
|
-
console.warn("[timber] Stale client reference detected — the server has been redeployed with new bundles. Reloading to pick up the new version.");
|
|
497
|
-
window.location.reload();
|
|
498
|
-
return true;
|
|
499
|
-
} catch {
|
|
500
|
-
if (document.cookie.includes("__timber_stale_reload=1") || memoryReloadCount > 0) {
|
|
501
|
-
console.warn("[timber] Stale client reference detected again after reload. Not reloading to prevent infinite loop. This may indicate a deployment issue — try a hard refresh.");
|
|
502
|
-
return false;
|
|
503
|
-
}
|
|
504
|
-
memoryReloadCount++;
|
|
505
|
-
try {
|
|
506
|
-
document.cookie = `${RELOAD_FLAG_KEY}=1; max-age=60; path=/; SameSite=Lax`;
|
|
507
|
-
} catch {}
|
|
508
|
-
console.warn("[timber] Stale client reference detected — the server has been redeployed with new bundles. Reloading to pick up the new version.");
|
|
509
|
-
window.location.reload();
|
|
510
|
-
return true;
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
//#endregion
|
|
514
433
|
//#region src/client/router.ts
|
|
515
434
|
/**
|
|
516
435
|
* Check if an error is an abort error (connection closed / fetch aborted).
|
|
@@ -741,8 +660,7 @@ function createRouter(deps) {
|
|
|
741
660
|
} catch (error) {
|
|
742
661
|
if (error instanceof VersionSkewError) {
|
|
743
662
|
setHardNavigating(true);
|
|
744
|
-
|
|
745
|
-
triggerStaleReload();
|
|
663
|
+
window.location.reload();
|
|
746
664
|
return new Promise(() => {});
|
|
747
665
|
}
|
|
748
666
|
if (error instanceof RedirectError) {
|
|
@@ -756,11 +674,6 @@ function createRouter(deps) {
|
|
|
756
674
|
window.location.href = error.url;
|
|
757
675
|
return new Promise(() => {});
|
|
758
676
|
}
|
|
759
|
-
if (isStaleClientReference(error)) {
|
|
760
|
-
setHardNavigating(true);
|
|
761
|
-
triggerStaleReload();
|
|
762
|
-
return new Promise(() => {});
|
|
763
|
-
}
|
|
764
677
|
if (isAbortError(error)) return;
|
|
765
678
|
throw error;
|
|
766
679
|
} finally {
|
|
@@ -785,11 +698,6 @@ function createRouter(deps) {
|
|
|
785
698
|
});
|
|
786
699
|
applyHead(headElements);
|
|
787
700
|
} catch (error) {
|
|
788
|
-
if (isStaleClientReference(error)) {
|
|
789
|
-
setHardNavigating(true);
|
|
790
|
-
triggerStaleReload();
|
|
791
|
-
return new Promise(() => {});
|
|
792
|
-
}
|
|
793
701
|
if (isAbortError(error)) return;
|
|
794
702
|
throw error;
|
|
795
703
|
} finally {
|
|
@@ -821,11 +729,6 @@ function createRouter(deps) {
|
|
|
821
729
|
applyHead(headElements);
|
|
822
730
|
restoreScrollAfterPaint(scrollY);
|
|
823
731
|
} catch (error) {
|
|
824
|
-
if (isStaleClientReference(error)) {
|
|
825
|
-
setHardNavigating(true);
|
|
826
|
-
triggerStaleReload();
|
|
827
|
-
return new Promise(() => {});
|
|
828
|
-
}
|
|
829
732
|
if (isAbortError(error)) return;
|
|
830
733
|
throw error;
|
|
831
734
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.js","names":[],"sources":["../../src/client/segment-cache.ts","../../src/client/history.ts","../../src/client/rsc-fetch.ts","../../src/client/stale-reload.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// Segment Cache — stores the mounted segment tree and prefetched payloads\n// See design/19-client-navigation.md for architecture details.\n\nimport type { HeadElement } from './head';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional head elements and segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n headElements: HeadElement[] | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /** Route params from X-Timber-Params header for populating useSegmentParams(). */\n params?: Record<string, string | string[]> | null;\n /** Segment paths skipped by the server (for client-side merging). */\n skippedSegments?: string[] | null;\n}\n\n/**\n * A node in the client-side segment tree. Each node represents a mounted\n * layout or page segment with its RSC flight payload.\n */\nexport interface SegmentNode {\n /** The segment's URL pattern (e.g., \"/\", \"/dashboard\", \"/projects/[id]\") */\n segment: string;\n /** The RSC flight payload for this segment (opaque to the cache) */\n payload: unknown;\n /** Whether the segment is async (async layouts always re-render on navigation) */\n isAsync: boolean;\n /** Child segments keyed by segment path */\n children: Map<string, SegmentNode>;\n}\n\n/**\n * Serialized state tree sent via X-Timber-State-Tree header.\n * Only sync segments are included — async segments always re-render.\n */\nexport interface StateTree {\n segments: string[];\n}\n\n// ─── Segment Cache ───────────────────────────────────────────────\n\n/**\n * Maintains the client-side segment tree representing currently mounted\n * layouts and pages. Used for navigation reconciliation — the router diffs\n * new routes against this tree to determine which segments to re-fetch.\n */\nexport class SegmentCache {\n private root: SegmentNode | undefined;\n\n get(segment: string): SegmentNode | undefined {\n if (segment === '/' || segment === this.root?.segment) {\n return this.root;\n }\n return undefined;\n }\n\n set(segment: string, node: SegmentNode): void {\n if (segment === '/' || !this.root) {\n this.root = node;\n }\n }\n\n clear(): void {\n this.root = undefined;\n }\n\n /**\n * Serialize the mounted segment tree for the X-Timber-State-Tree header.\n * Only includes sync segments — async segments are excluded because the\n * server must always re-render them (they may depend on request context).\n *\n * When mergeableFilter is provided, only segments whose paths are in the\n * set are included. This ensures the server only skips segments that the\n * client can actually merge (i.e., segments whose cached element tree\n * contains an inner SegmentProvider the merger can splice into).\n *\n * This is a performance optimization only, NOT a security boundary.\n * The server always runs all access.ts files regardless of the state tree.\n */\n serializeStateTree(mergeableFilter?: Set<string>): StateTree {\n const segments: string[] = [];\n if (this.root) {\n collectSyncSegments(this.root, segments, mergeableFilter);\n }\n return { segments };\n }\n}\n\n/** Recursively collect sync segment paths from the tree */\nfunction collectSyncSegments(\n node: SegmentNode,\n out: string[],\n mergeableFilter?: Set<string>\n): void {\n if (!node.isAsync && (!mergeableFilter || mergeableFilter.has(node.segment))) {\n out.push(node.segment);\n }\n for (const child of node.children.values()) {\n collectSyncSegments(child, out, mergeableFilter);\n }\n}\n\n// ─── Segment Tree Builder ────────────────────────────────────────\n\n/**\n * Segment metadata from the server, sent via X-Timber-Segments header.\n * Describes a rendered segment's path and whether it's async.\n */\nexport interface SegmentInfo {\n path: string;\n /** Outlet key — includes route group name when applicable (e.g., \"/(marketing)\"). */\n segmentId?: string;\n isAsync: boolean;\n}\n\n/**\n * Build a SegmentNode tree from flat segment metadata.\n *\n * Takes an ordered list of segment descriptors (root → leaf) from the\n * server's X-Timber-Segments header and constructs the hierarchical\n * tree structure that SegmentCache expects.\n *\n * Each segment is nested as a child of the previous one, forming a\n * linear chain from root to leaf. The leaf segment (page) is excluded\n * from the tree — pages are never cached across navigations.\n */\nexport function buildSegmentTree(segments: SegmentInfo[]): SegmentNode | undefined {\n // Need at least a root segment to build a tree\n if (segments.length === 0) return undefined;\n\n // Exclude the leaf (page) — pages always re-render on navigation.\n // Only layouts are cached in the segment tree.\n const layouts = segments.length > 1 ? segments.slice(0, -1) : segments;\n\n let root: SegmentNode | undefined;\n let parent: SegmentNode | undefined;\n\n for (const info of layouts) {\n const id = info.segmentId ?? info.path;\n const node: SegmentNode = {\n segment: id,\n payload: null,\n isAsync: info.isAsync,\n children: new Map(),\n };\n\n if (!root) {\n root = node;\n }\n\n if (parent) {\n parent.children.set(id, node);\n }\n\n parent = node;\n }\n\n return root;\n}\n\n// ─── Prefetch Cache ──────────────────────────────────────────────\n\ninterface PrefetchEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/**\n * Short-lived cache for hover-triggered prefetches. Entries expire after\n * 30 seconds. When a link is clicked, the prefetched payload is consumed\n * (moved to the history stack) and removed from this cache.\n *\n * timber.js does NOT prefetch on viewport intersection — only explicit\n * hover on <Link prefetch> triggers a prefetch.\n */\nexport class PrefetchCache {\n private static readonly TTL_MS = 30_000;\n private entries = new Map<string, PrefetchEntry>();\n\n set(url: string, result: PrefetchResult): void {\n this.entries.set(url, {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(url: string): PrefetchResult | undefined {\n const entry = this.entries.get(url);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(url);\n return undefined;\n }\n return entry.result;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(url: string): PrefetchResult | undefined {\n const result = this.get(url);\n if (result !== undefined) {\n this.entries.delete(url);\n }\n return result;\n }\n}\n","// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { HeadElement } from './head';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /** Resolved head elements for this page (title, meta tags). Null for SSR'd initial page. */\n headElements?: HeadElement[] | null;\n /** Route params for this page (for useParams). Null for SSR'd initial page. */\n params?: Record<string, string | string[]> | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Supports two keying modes:\n * - **URL-keyed** (default): entries keyed by pathname + search.\n * Used with the History API fallback.\n * - **Entry-key + URL**: when the Navigation API is available,\n * entries can also be stored by Navigation entry key for\n * disambiguation of duplicate URLs in the history stack.\n * Falls back to URL lookup when entry key is not found.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries persist for the session duration (no expiry) and are cleared\n * when the tab is closed — matching browser back-button behavior.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n /** Entries keyed by Navigation API entry key for duplicate URL disambiguation. */\n private entryKeyMap = new Map<string, HistoryEntry>();\n\n push(url: string, entry: HistoryEntry, entryKey?: string): void {\n this.entries.set(url, entry);\n if (entryKey) {\n this.entryKeyMap.set(entryKey, entry);\n }\n }\n\n /**\n * Get an entry. When an entry key is provided (Navigation API),\n * tries the entry-key map first for accurate disambiguation of\n * duplicate URLs, then falls back to URL lookup.\n */\n get(url: string, entryKey?: string): HistoryEntry | undefined {\n if (entryKey) {\n const byKey = this.entryKeyMap.get(entryKey);\n if (byKey) return byKey;\n }\n return this.entries.get(url);\n }\n\n has(url: string): boolean {\n return this.entries.has(url);\n }\n}\n","/**\n * RSC Fetch — handles fetching and parsing RSC Flight payloads.\n *\n * Extracted from router.ts to keep both files under the 500-line limit.\n * This module handles:\n * - Cache-busting URL generation for RSC requests\n * - Building RSC request headers (Accept, X-Timber-State-Tree)\n * - Extracting metadata from RSC response headers\n * - Fetching and decoding RSC payloads\n *\n * See design/19-client-navigation.md §\"RSC Payload Handling\"\n */\n\nimport type { SegmentInfo } from './segment-cache';\nimport type { HeadElement } from './head';\nimport type { RouterDeps } from './router';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Result of fetching an RSC payload — includes head elements and segment metadata. */\nexport interface FetchResult {\n payload: unknown;\n /**\n * Promise that settles when the RSC decode completes or fails.\n * The payload thenable is NOT awaited before returning (for streaming),\n * so callers must monitor this to catch async decode errors\n * (truncated streams, Flight parse failures) that would otherwise\n * become unhandled rejections.\n */\n decodePromise: Promise<void> | null;\n headElements: HeadElement[] | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo: SegmentInfo[] | null;\n /** Route params from X-Timber-Params header for populating useSegmentParams(). */\n params: Record<string, string | string[]> | null;\n /** Segment paths that were skipped by the server (for client-side merging). */\n skippedSegments: string[] | null;\n}\n\n// ─── Constants ───────────────────────────────────────────────────\n\nexport const RSC_CONTENT_TYPE = 'text/x-component';\n\n// ─── URL Helpers ─────────────────────────────────────────────────\n\n/**\n * Generate a short random cache-busting ID (5 chars, a-z0-9).\n * Matches the format Next.js uses for _rsc params.\n */\nfunction generateCacheBustId(): string {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';\n let id = '';\n for (let i = 0; i < 5; i++) {\n id += chars[(Math.random() * 36) | 0];\n }\n return id;\n}\n\n/**\n * Append a `_rsc=<id>` query parameter to the URL.\n * Follows Next.js's pattern — prevents CDN/browser from serving cached HTML\n * for RSC navigation requests and signals that this is an RSC fetch.\n */\nfunction appendRscParam(url: string): string {\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}_rsc=${generateCacheBustId()}`;\n}\n\n// ─── Deployment ID ───────────────────────────────────────────────\n\n/**\n * The client's deployment ID, set at bootstrap from the runtime config.\n * Sent with every RSC/action request for version skew detection.\n * Null in dev mode. See TIM-446.\n */\nlet clientDeploymentId: string | null = null;\n\n/** Set the client deployment ID. Called once at bootstrap. */\nexport function setClientDeploymentId(id: string | null): void {\n clientDeploymentId = id;\n}\n\n/** Get the client deployment ID. */\nexport function getClientDeploymentId(): string | null {\n return clientDeploymentId;\n}\n\n// ─── Reload Signal ───────────────────────────────────────────────\n\n/** Header name used by the server to signal a version skew reload. */\nexport const RELOAD_HEADER = 'X-Timber-Reload';\n\n/** Header name for the client's deployment ID. */\nexport const DEPLOYMENT_ID_HEADER = 'X-Timber-Deployment-Id';\n\n/**\n * Check if a response signals a version skew reload.\n * Triggers a full page reload if the server indicates the client is stale.\n */\nexport function checkReloadSignal(response: Response): boolean {\n return response.headers.get(RELOAD_HEADER) === '1';\n}\n\n// ─── Header Builder ──────────────────────────────────────────────\n\nexport function buildRscHeaders(\n stateTree: { segments: string[] } | undefined,\n currentUrl?: string\n): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: RSC_CONTENT_TYPE,\n };\n if (stateTree) {\n headers['X-Timber-State-Tree'] = JSON.stringify(stateTree);\n }\n // Send current URL for intercepting route resolution.\n // The server uses this to determine if an intercepting route should\n // render instead of the actual target route (modal pattern).\n // See design/07-routing.md §\"Intercepting Routes\"\n if (currentUrl) {\n headers['X-Timber-URL'] = currentUrl;\n }\n // Send deployment ID for version skew detection (TIM-446).\n // The server compares this against the current build's ID.\n // On mismatch, the server signals a reload instead of returning\n // an RSC payload with mismatched module references.\n if (clientDeploymentId) {\n headers[DEPLOYMENT_ID_HEADER] = clientDeploymentId;\n }\n return headers;\n}\n\n// ─── Response Header Extraction ──────────────────────────────────\n\n/** Dev-only warning for malformed framework headers. Tree-shaken in production. */\nfunction warnMalformedHeader(headerName: string, raw: string): void {\n if (process.env.NODE_ENV !== 'production') {\n const preview = raw.length > 200 ? raw.slice(0, 200) + '…' : raw;\n console.warn(\n `[timber] Malformed ${headerName} header \\u2014 JSON.parse failed. ` +\n `This indicates a framework bug or header corruption. Raw (first 200 chars): ${preview}`\n );\n }\n}\n\n/**\n * Extract head elements from the X-Timber-Head response header.\n * Returns null if the header is missing or malformed.\n */\nexport function extractHeadElements(response: Response): HeadElement[] | null {\n const header = response.headers.get('X-Timber-Head');\n if (!header) return null;\n try {\n return JSON.parse(decodeURIComponent(header));\n } catch {\n warnMalformedHeader('X-Timber-Head', header);\n return null;\n }\n}\n\n/**\n * Extract segment metadata from the X-Timber-Segments response header.\n * Returns null if the header is missing or malformed.\n *\n * Format: JSON array of {path, isAsync} objects describing the rendered\n * segment chain from root to leaf. Used to populate the client-side\n * segment cache for state tree diffing on subsequent navigations.\n */\nexport function extractSegmentInfo(response: Response): SegmentInfo[] | null {\n const header = response.headers.get('X-Timber-Segments');\n if (!header) return null;\n try {\n return JSON.parse(header);\n } catch {\n warnMalformedHeader('X-Timber-Segments', header);\n return null;\n }\n}\n\n/**\n * Extract skipped segment paths from the X-Timber-Skipped-Segments header.\n * Returns null if the header is missing or malformed.\n *\n * When the server skips sync layouts the client already has cached,\n * it sends this header listing the skipped segment paths (outermost first).\n * The client uses this to merge the partial payload with cached segments.\n */\nexport function extractSkippedSegments(response: Response): string[] | null {\n const header = response.headers.get('X-Timber-Skipped-Segments');\n if (!header) return null;\n try {\n const parsed = JSON.parse(header);\n return Array.isArray(parsed) ? parsed : null;\n } catch {\n warnMalformedHeader('X-Timber-Skipped-Segments', header);\n return null;\n }\n}\n\n/**\n * Extract route params from the X-Timber-Params response header.\n * Returns null if the header is missing or malformed.\n *\n * Used to populate useSegmentParams() after client-side navigation.\n */\nexport function extractParams(response: Response): Record<string, string | string[]> | null {\n const header = response.headers.get('X-Timber-Params');\n if (!header) return null;\n try {\n return JSON.parse(header);\n } catch {\n warnMalformedHeader('X-Timber-Params', header);\n return null;\n }\n}\n\n// ─── Redirect Error ──────────────────────────────────────────────\n\n/**\n * Thrown when an RSC payload response contains X-Timber-Redirect header.\n * Caught in navigate() to trigger a soft router navigation to the redirect target.\n */\nexport class RedirectError extends Error {\n readonly redirectUrl: string;\n constructor(url: string) {\n super(`Server redirect to ${url}`);\n this.redirectUrl = url;\n }\n}\n\n/**\n * Thrown when the server signals a version skew (X-Timber-Reload header).\n * Caught in navigate() to trigger a full page reload via triggerStaleReload().\n * See TIM-446.\n */\nexport class VersionSkewError extends Error {\n constructor() {\n super('Version skew detected — server has been redeployed');\n }\n}\n\n/**\n * Thrown when the server returns an error for an RSC payload request.\n * The server sends X-Timber-Error header and a JSON body instead of a\n * broken RSC stream for any RenderError (4xx or 5xx). Caught in\n * navigate() to trigger a hard navigation so the server can render\n * the error page as HTML.\n *\n * See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n */\nexport class ServerErrorResponse extends Error {\n readonly status: number;\n readonly url: string;\n constructor(status: number, url: string) {\n super(`Server error ${status} during navigation to ${url}`);\n this.status = status;\n this.url = url;\n }\n}\n\n// ─── Stream Completion Tracking ───────────────────────────────────\n\n/**\n * Wrap a response body stream to track when it's fully consumed.\n * Returns a new body that passes all chunks through unchanged, plus\n * a `done` promise that resolves when the last chunk is read (or\n * rejects if the stream errors).\n *\n * Used to keep React transitions open for the full RSC stream\n * duration — createFromFetch's thenable resolves on shell arrival,\n * but we need stream completion for useOptimistic pending state.\n */\nfunction trackStreamCompletion(body: ReadableStream<Uint8Array>): {\n body: ReadableStream<Uint8Array>;\n done: Promise<void>;\n} {\n let resolveDone!: () => void;\n let rejectDone!: (e: unknown) => void;\n const done = new Promise<void>((res, rej) => {\n resolveDone = res;\n rejectDone = rej;\n });\n\n const reader = body.getReader();\n const tracked = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const result = await reader.read();\n if (result.done) {\n controller.close();\n resolveDone();\n } else {\n controller.enqueue(result.value);\n }\n } catch (error) {\n controller.error(error);\n rejectDone(error);\n }\n },\n cancel(reason) {\n reader.cancel(reason);\n resolveDone();\n },\n });\n\n return { body: tracked, done };\n}\n\n// ─── Fetch ───────────────────────────────────────────────────────\n\n/**\n * Fetch an RSC payload from the server. If a decodeRsc function is provided,\n * the response is decoded into a React element tree via createFromFetch.\n * Otherwise, the raw response text is returned (test mode).\n *\n * Also extracts head elements from the X-Timber-Head response header\n * so the client can update document.title and <meta> tags after navigation.\n */\nexport async function fetchRscPayload(\n url: string,\n deps: RouterDeps,\n stateTree?: { segments: string[] },\n currentUrl?: string,\n signal?: AbortSignal\n): Promise<FetchResult> {\n const rscUrl = appendRscParam(url);\n const headers = buildRscHeaders(stateTree, currentUrl);\n if (deps.decodeRsc) {\n // Production path: use createFromFetch for streaming RSC decoding.\n // createFromFetch takes a Promise<Response> and progressively parses\n // the RSC Flight stream as chunks arrive.\n //\n // Intercept the response to read X-Timber-Head before createFromFetch\n // consumes the body. Reading headers does NOT consume the body stream.\n const fetchPromise = deps.fetch(rscUrl, { headers, redirect: 'manual', signal });\n let headElements: HeadElement[] | null = null;\n let segmentInfo: SegmentInfo[] | null = null;\n let params: Record<string, string | string[]> | null = null;\n let skippedSegments: string[] | null = null;\n // Track when the full RSC body stream is consumed (not just shell).\n // Initialized to resolved for bodyless responses; overwritten when\n // the response has a body.\n let streamDone: Promise<void> = Promise.resolve();\n\n const wrappedPromise = fetchPromise.then((response) => {\n // Version skew detection (TIM-446): if the server signals a reload,\n // throw VersionSkewError so the caller (router navigate) can trigger\n // a full page reload via triggerStaleReload().\n if (checkReloadSignal(response)) {\n throw new VersionSkewError();\n }\n // Detect server-side redirects. The server returns 204 + X-Timber-Redirect\n // for RSC payload requests instead of a raw 302, because fetch with\n // redirect: \"manual\" turns 302s into opaque redirects (status 0, null body)\n // which crashes createFromFetch when it tries to read the body stream.\n const redirectLocation =\n response.headers.get('X-Timber-Redirect') ||\n (response.status >= 300 && response.status < 400 ? response.headers.get('Location') : null);\n if (redirectLocation) {\n throw new RedirectError(redirectLocation);\n }\n // Detect server error responses. The server returns X-Timber-Error header\n // with a JSON body instead of a broken RSC stream for any RenderError\n // (4xx or 5xx). Hard-navigate so the server renders the error page as HTML.\n // See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n if (response.headers.get('X-Timber-Error') === '1') {\n throw new ServerErrorResponse(response.status, url);\n }\n headElements = extractHeadElements(response);\n segmentInfo = extractSegmentInfo(response);\n params = extractParams(response);\n skippedSegments = extractSkippedSegments(response);\n\n // Wrap the body to track full stream consumption. createFromFetch's\n // thenable resolves when the root model (shell) arrives, but we need\n // to know when ALL chunks are read so the React transition stays\n // open for the full streaming duration (keeps useOptimistic alive).\n if (response.body) {\n const tracked = trackStreamCompletion(response.body);\n streamDone = tracked.done;\n streamDone.catch(() => {}); // prevent unhandled rejection\n return new Response(tracked.body, {\n headers: response.headers,\n status: response.status,\n });\n }\n return response;\n });\n // Await headers so headElements/segmentInfo/params are populated.\n await wrappedPromise;\n // Start decoding but do NOT await — return the in-progress thenable.\n // React can render a Flight thenable directly: it suspends on unresolved\n // parts and progressively renders as chunks arrive, spreading work across\n // frames instead of blocking the main thread in one burst.\n const payload = deps.decodeRsc(wrappedPromise);\n // Combine stream completion with payload error propagation.\n // streamDone keeps the transition open for the full RSC stream\n // duration (useOptimistic pending state). payloadError propagates\n // decode failures (stale client references, Flight parse errors)\n // so the router's catch block can trigger recovery (stale reload).\n const payloadError = new Promise<void>((_, reject) => {\n Promise.resolve(payload).then(() => {}, reject);\n });\n payloadError.catch(() => {});\n const decodePromise = Promise.race([streamDone, payloadError]);\n return {\n payload,\n decodePromise,\n headElements,\n segmentInfo,\n params,\n skippedSegments,\n };\n }\n // Test/fallback path: return raw text\n const response = await deps.fetch(rscUrl, { headers, redirect: 'manual', signal });\n // Check for redirect in test path too\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('Location');\n if (location) {\n throw new RedirectError(location);\n }\n }\n return {\n payload: await response.text(),\n decodePromise: null,\n headElements: extractHeadElements(response),\n segmentInfo: extractSegmentInfo(response),\n params: extractParams(response),\n skippedSegments: extractSkippedSegments(response),\n };\n}\n","/**\n * Stale Client Reference Reload\n *\n * When a new deployment ships updated bundles, clients running stale\n * JavaScript may encounter \"Could not find the module\" errors during\n * RSC Flight stream decoding. This happens because the RSC payload\n * references module IDs from the new bundle that don't exist in the\n * old client bundle.\n *\n * This module detects these specific errors and triggers a full page\n * reload so the browser fetches the new bundle. A sessionStorage flag\n * guards against infinite reload loops.\n *\n * See: LOCAL-332\n */\n\nconst RELOAD_FLAG_KEY = '__timber_stale_reload';\n\n/**\n * In-memory fallback counter for environments where sessionStorage is\n * unavailable (private browsing, storage full, extension interference).\n * Incremented each time triggerStaleReload() falls into the catch path.\n * If the counter exceeds 0 on a subsequent call, the reload is suppressed\n * to prevent an infinite loop. Resets naturally on page load (module\n * re-evaluates) and can be manually reset via clearStaleReloadFlag().\n */\nlet memoryReloadCount = 0;\n\n/**\n * Check if an error is a stale client reference error from React's\n * Flight client. These errors have the message pattern:\n * \"Could not find the module \\\"<id>\\\"\"\n *\n * This is thrown by react-server-dom-webpack's client when the RSC\n * payload references a module ID that doesn't exist in the client's\n * module map — typically because the server has been redeployed with\n * new bundle hashes while the client is still running old JavaScript.\n */\nexport function isStaleClientReference(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const msg = error.message;\n return msg.includes('Could not find the module') || msg.includes('client reference not found');\n}\n\n/**\n * Check if an error is a chunk load failure from a dynamic import.\n *\n * After a deployment, old chunk filenames no longer exist. When the client\n * tries to dynamically import a chunk that's been replaced, the browser\n * throws one of these errors:\n *\n * - Chromium: \"Failed to fetch dynamically imported module: <url>\"\n * - Firefox: \"error loading dynamically imported module: <url>\"\n * - Safari: \"Importing a module script failed.\"\n * - Vite/Rollup: \"Unable to preload CSS for <url>\"\n *\n * See TIM-446\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const msg = error.message.toLowerCase();\n return (\n msg.includes('failed to fetch dynamically imported module') ||\n msg.includes('error loading dynamically imported module') ||\n msg.includes('importing a module script failed') ||\n msg.includes('unable to preload css') ||\n // Webpack-style chunk load errors (unlikely in Vite but defensive)\n msg.includes('loading chunk') ||\n msg.includes('loading css chunk')\n );\n}\n\n/**\n * Trigger a full page reload to pick up new bundles.\n *\n * Sets a sessionStorage flag before reloading. If the flag is already\n * set (meaning we already reloaded once for this reason), we don't\n * reload again — this prevents infinite reload loops if the error\n * persists after reload (e.g., a genuine bug rather than a stale bundle).\n *\n * @returns true if a reload was triggered, false if suppressed (loop guard)\n */\nexport function triggerStaleReload(): boolean {\n try {\n // Check if we already reloaded — prevent infinite loop\n if (sessionStorage.getItem(RELOAD_FLAG_KEY)) {\n console.warn(\n '[timber] Stale client reference detected again after reload. ' +\n 'Not reloading to prevent infinite loop. ' +\n 'This may indicate a deployment issue — try a hard refresh.'\n );\n return false;\n }\n\n // Set the flag before reloading\n sessionStorage.setItem(RELOAD_FLAG_KEY, '1');\n\n console.warn(\n '[timber] Stale client reference detected — the server has been ' +\n 'redeployed with new bundles. Reloading to pick up the new version.'\n );\n\n window.location.reload();\n return true;\n } catch {\n // sessionStorage unavailable (private browsing, storage full, etc.)\n // Use document.cookie as a reload-persistent fallback loop guard.\n // Module-level memoryReloadCount resets on every reload, so it can't\n // detect cross-reload loops. Cookies persist across reloads and are\n // available even when sessionStorage is blocked (TIM-576).\n const cookieFlag = document.cookie.includes(RELOAD_FLAG_KEY + '=1');\n if (cookieFlag || memoryReloadCount > 0) {\n console.warn(\n '[timber] Stale client reference detected again after reload. ' +\n 'Not reloading to prevent infinite loop. ' +\n 'This may indicate a deployment issue — try a hard refresh.'\n );\n return false;\n }\n\n memoryReloadCount++;\n // Set a short-lived cookie (60s) as the persistent loop guard.\n // It auto-expires so it won't block future legitimate reloads.\n try {\n document.cookie = `${RELOAD_FLAG_KEY}=1; max-age=60; path=/; SameSite=Lax`;\n } catch {\n // Cookie API unavailable — proceed anyway, memoryReloadCount guards same-page loops\n }\n console.warn(\n '[timber] Stale client reference detected — the server has been ' +\n 'redeployed with new bundles. Reloading to pick up the new version.'\n );\n window.location.reload();\n return true;\n }\n}\n\n/**\n * Clear the stale reload flag. Called on successful bootstrap to reset\n * the loop guard — if the page loaded successfully, the next stale\n * reference error should trigger a fresh reload attempt.\n */\nexport function clearStaleReloadFlag(): void {\n memoryReloadCount = 0;\n try {\n sessionStorage.removeItem(RELOAD_FLAG_KEY);\n } catch {\n // sessionStorage unavailable — nothing to clear\n }\n // Also clear the cookie fallback\n try {\n document.cookie = `${RELOAD_FLAG_KEY}=; max-age=0; path=/; SameSite=Lax`;\n } catch {\n // Cookie API unavailable\n }\n}\n","// Segment Router — manages client-side navigation and RSC payload fetching\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache, buildSegmentTree } from './segment-cache';\nimport type { SegmentInfo } from './segment-cache';\nimport { HistoryStack } from './history';\nimport type { HeadElement } from './head';\nimport { setCurrentParams } from './use-segment-params.js';\nimport {\n setNavigationState,\n getNavigationState,\n type NavigationState,\n} from './navigation-context.js';\n\nimport {\n fetchRscPayload,\n RedirectError,\n ServerErrorResponse,\n VersionSkewError,\n} from './rsc-fetch.js';\nimport { setHardNavigating } from './navigation-root.js';\nimport { isStaleClientReference, triggerStaleReload } from './stale-reload.js';\nimport type { FetchResult } from './rsc-fetch.js';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface NavigationOptions {\n /** Set to false to prevent scroll-to-top on forward navigation */\n scroll?: boolean;\n /** Use replaceState instead of pushState (replaces current history entry) */\n replace?: boolean;\n /**\n * @internal AbortSignal from the Navigation API's NavigateEvent.\n * When provided, the signal is linked to the router's per-navigation\n * AbortController so in-flight RSC fetches are cancelled when a new\n * navigation starts.\n */\n _signal?: AbortSignal;\n /**\n * @internal Skip pushState/replaceState — the Navigation API has already\n * updated the URL via event.intercept(). Used for external navigations\n * intercepted by the navigate event handler.\n */\n _skipHistory?: boolean;\n}\n\n/**\n * Function that decodes an RSC Flight stream into a React element tree.\n * In production: createFromFetch from @vitejs/plugin-rsc/browser.\n * In tests: a mock that returns the raw payload.\n */\nexport type RscDecoder = (fetchPromise: Promise<Response>) => unknown;\n\n/**\n * Function that renders a decoded RSC element tree into the DOM.\n * In production: reactRoot.render(element).\n * In tests: a no-op or mock.\n *\n * Receives the current NavigationState explicitly — no temporal\n * coupling with setNavigationState/getNavigationState. The renderer\n * wraps the element in NavigationProvider with this state.\n */\nexport type RootRenderer = (element: unknown, navState: NavigationState) => void;\n\n/**\n * Platform dependencies injected for testability. In production these\n * map to browser APIs; in tests they're replaced with mocks.\n */\nexport interface RouterDeps {\n fetch: (url: string, init: RequestInit) => Promise<Response>;\n pushState: (data: unknown, unused: string, url: string) => void;\n replaceState: (data: unknown, unused: string, url: string) => void;\n scrollTo: (x: number, y: number) => void;\n getCurrentUrl: () => string;\n getScrollY: () => number;\n /** Decode RSC Flight stream into React elements. If not provided, raw response text is stored. */\n decodeRsc?: RscDecoder;\n /** Render decoded RSC tree into the DOM. If not provided, rendering is a no-op. */\n renderRoot?: RootRenderer;\n /**\n * Schedule a callback after the next paint. In the browser, this is\n * requestAnimationFrame + setTimeout(0) to run after React commits.\n * In tests, this runs the callback synchronously.\n */\n afterPaint?: (callback: () => void) => void;\n /** Apply resolved head elements (title, meta tags) to the DOM after navigation. */\n applyHead?: (elements: HeadElement[]) => void;\n /**\n * Run a navigation inside a React transition with optimistic pending URL.\n * The pending URL shows immediately (useOptimistic urgent update) and\n * reverts when the transition commits (atomic with the new tree).\n *\n * The `perform` callback receives a `wrapPayload` function to wrap the\n * decoded RSC payload with NavigationProvider + NuqsAdapter before\n * NavigationRoot sets it as the new element. The `wrapPayload` function\n * receives the NavigationState explicitly — no temporal coupling with\n * getNavigationState().\n *\n * If not provided (tests), the router falls back to renderRoot.\n */\n navigateTransition?: (\n pendingUrl: string,\n perform: (\n wrapPayload: (\n payload: unknown,\n navState: NavigationState,\n segmentUpdates?: Map<string, unknown>\n ) => unknown\n ) => Promise<{ element: unknown; decodePromise: Promise<void> | null }>\n ) => Promise<void>;\n\n /**\n * Whether the Navigation API is active and handling traversals.\n * When true, the popstate handler is a no-op — the Navigation API's\n * navigate event covers back/forward button presses.\n */\n navigationApiActive?: boolean;\n\n /**\n * Called around pushState/replaceState to set a flag that prevents\n * the Navigation API's navigate listener from double-handling\n * router-initiated navigations.\n */\n setRouterNavigating?: (value: boolean) => void;\n\n /**\n * Save scroll position via the Navigation API's per-entry state.\n * When provided, used instead of history.replaceState for scroll storage.\n */\n saveNavigationEntryScroll?: (scrollY: number) => void;\n\n /**\n * Signal that a router-initiated navigation has completed. Resolves the\n * deferred promise that ties the browser's native loading state to the\n * navigation lifecycle. Called in the finally block of navigate/refresh,\n * aligned with when the TopLoader's pendingUrl clears.\n */\n completeRouterNavigation?: () => void;\n\n /**\n * Get the current unwrapped RSC payload element. Used for partial\n * navigation: the router re-wraps the same element with new\n * NavigationProvider context so mounted SegmentOutlets are preserved.\n */\n _getCurrentPayload?: () => unknown;\n\n /**\n * Initiate a navigation via the Navigation API (`navigation.navigate()`).\n * Fires the navigate event BEFORE committing the URL, allowing Chrome\n * to show its native loading indicator. Falls back to pushState when\n * unavailable.\n */\n navigationNavigate?: (url: string, replace: boolean) => void;\n}\n\nexport interface RouterInstance {\n /** Navigate to a new URL (forward navigation) */\n navigate(url: string, options?: NavigationOptions): Promise<void>;\n /** Full re-render of the current URL — no state tree sent */\n refresh(): Promise<void>;\n /** Handle a popstate event (back/forward button). scrollY is read from history.state. */\n handlePopState(url: string, scrollY?: number, externalSignal?: AbortSignal): Promise<void>;\n /** Whether a navigation is currently in flight */\n isPending(): boolean;\n /** The URL currently being navigated to, or null if idle */\n getPendingUrl(): string | null;\n /** Subscribe to pending state changes */\n onPendingChange(listener: (pending: boolean) => void): () => void;\n /** Prefetch an RSC payload for a URL (used by Link hover) */\n prefetch(url: string): void;\n /**\n * Apply a piggybacked revalidation payload from a server action response.\n * Renders the element tree and updates head elements without a server fetch.\n * See design/08-forms-and-actions.md §\"Single-Roundtrip Revalidation\".\n */\n applyRevalidation(element: unknown, headElements: HeadElement[] | null): void;\n /**\n * Populate the segment cache from server-provided segment metadata.\n * Called on initial hydration with segment info embedded in the HTML.\n */\n initSegmentCache(segments: SegmentInfo[]): void;\n\n /** The segment cache (exposed for tests and <Link> prefetch) */\n segmentCache: SegmentCache;\n /** The prefetch cache (exposed for tests and <Link> prefetch) */\n prefetchCache: PrefetchCache;\n /** The history stack (exposed for tests) */\n historyStack: HistoryStack;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\n/**\n * Router navigation phase — discriminated union replacing scattered\n * `pending` + `pendingUrl` boolean flags.\n *\n * - `idle`: No navigation in flight. The committed params/pathname\n * are current.\n * - `navigating`: A fetch or render is in progress. `targetUrl` is\n * the destination being navigated to.\n */\nexport type RouterPhase = { phase: 'idle' } | { phase: 'navigating'; targetUrl: string };\n\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n // AbortController for the current in-flight navigation.\n // When a new navigation starts, the previous controller is aborted,\n // cancelling any in-progress RSC fetch. This provides automatic\n // cancellation of stale fetches regardless of Navigation API support.\n let currentNavAbort: AbortController | null = null;\n\n /**\n * Create a new AbortController for a navigation, aborting any\n * previous in-flight navigation. Optionally links to an external\n * signal (e.g., from the Navigation API's NavigateEvent.signal).\n */\n function createNavAbort(externalSignal?: AbortSignal): AbortController {\n // Abort previous navigation's fetch\n currentNavAbort?.abort();\n const controller = new AbortController();\n currentNavAbort = controller;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n if (externalSignal) {\n if (externalSignal.aborted) {\n controller.abort();\n } else {\n externalSignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return controller;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify external store listeners (non-React consumers).\n // React-facing pending state is handled by useOptimistic in\n // NavigationRoot via navigateTransition — not this function.\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /** Update the segment cache from server-provided segment metadata. */\n function updateSegmentCache(segmentInfo: SegmentInfo[] | null | undefined): void {\n if (!segmentInfo || segmentInfo.length === 0) return;\n const tree = buildSegmentTree(segmentInfo);\n if (tree) {\n segmentCache.set('/', tree);\n }\n }\n\n /** Render a decoded RSC payload into the DOM if a renderer is available. */\n function renderPayload(payload: unknown, navState: NavigationState): void {\n if (deps.renderRoot) {\n deps.renderRoot(payload, navState);\n }\n }\n\n function isPartialNavigation(skippedSegments: string[] | null | undefined): boolean {\n return skippedSegments != null && skippedSegments.length > 0;\n }\n\n /**\n * Build a segment updates map for partial navigation. Identifies the\n * first non-skipped segment and maps it to the payload content.\n */\n function buildSegmentUpdates(result: FetchResult): Map<string, unknown> {\n const skipped = new Set(result.skippedSegments!);\n const segmentInfo = result.segmentInfo;\n const updates = new Map<string, unknown>();\n if (segmentInfo) {\n for (const info of segmentInfo) {\n if (!skipped.has(info.segmentId ?? info.path)) {\n // Use segmentId (outlet key) when available — route groups\n // use a disambiguated key like \"/(marketing)\" instead of \"/\".\n updates.set(info.segmentId ?? info.path, result.payload);\n break;\n }\n }\n }\n return updates;\n }\n\n /**\n * Update navigation state (params + pathname) for the next render.\n *\n * Sets the module-level fallback (for tests and SSR) and the\n * globalThis bridge, then returns the NavigationState so callers\n * can pass it explicitly to renderRoot/wrapPayload — eliminating\n * temporal coupling with getNavigationState().\n */\n function updateNavigationState(\n params: Record<string, string | string[]> | null | undefined,\n url: string\n ): NavigationState {\n const resolvedParams = params ?? {};\n // Module-level fallback for tests (no NavigationProvider) and SSR\n setCurrentParams(resolvedParams);\n // globalThis bridge — kept for backward compat\n const parsed = new URL(url, 'http://localhost');\n const pathname = parsed.pathname || '/';\n const search = parsed.search;\n const navState: NavigationState = { params: resolvedParams, pathname, search };\n setNavigationState(navState);\n return navState;\n }\n\n /**\n * Render a payload via navigateTransition (production) or renderRoot (tests).\n * The perform callback should fetch data, update state, and return the\n * FetchResult plus the NavigationState (so it can be passed explicitly\n * to wrapPayload/renderRoot without temporal coupling).\n */\n interface TransitionResult {\n headElements: HeadElement[] | null;\n decodePromise: Promise<void> | null;\n }\n\n async function renderViaTransition(\n url: string,\n perform: () => Promise<FetchResult & { navState: NavigationState }>\n ): Promise<TransitionResult> {\n if (deps.navigateTransition) {\n let headElements: HeadElement[] | null = null;\n await deps.navigateTransition(url, async (wrapPayload) => {\n const result = await perform();\n headElements = result.headElements;\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result);\n\n historyStack.push(url, {\n payload: null,\n headElements: result.headElements,\n params: result.params,\n });\n\n // Re-wrap the CURRENT element with new context values.\n // SegmentOutlets read updates from SegmentUpdateContext;\n // NavigationProvider gets new params/pathname.\n const element = wrapPayload(\n deps._getCurrentPayload?.() ?? result.payload,\n result.navState,\n segmentUpdates\n );\n return { element, decodePromise: result.decodePromise };\n }\n\n // Full navigation — empty updates, render the new tree.\n historyStack.push(url, {\n payload: result.payload,\n headElements: result.headElements,\n params: result.params,\n });\n const element = wrapPayload(result.payload, result.navState);\n return { element, decodePromise: result.decodePromise };\n });\n // decodePromise is awaited inside the transition's startTransition\n // callback (NavigationRoot), so we don't need it here.\n return { headElements, decodePromise: null };\n }\n // Fallback: no transition (tests, no React tree)\n const result = await perform();\n if (isPartialNavigation(result.skippedSegments)) {\n historyStack.push(url, {\n payload: null,\n headElements: result.headElements,\n params: result.params,\n });\n } else {\n // Resolve thenables before storing/rendering in the fallback path\n // (tests without navigateTransition). In production, React handles\n // thenables via Suspense; in tests, renderRoot expects resolved values.\n const payload =\n result.payload != null && typeof result.payload === 'object' && 'then' in result.payload\n ? await (result.payload as PromiseLike<unknown>)\n : result.payload;\n historyStack.push(url, {\n payload,\n headElements: result.headElements,\n params: result.params,\n });\n renderPayload(payload, result.navState);\n }\n return { headElements: result.headElements, decodePromise: result.decodePromise };\n }\n\n /** Apply head elements (title, meta tags) to the DOM if available. */\n function applyHead(elements: HeadElement[] | null | undefined): void {\n if (elements && deps.applyHead) {\n deps.applyHead(elements);\n }\n }\n\n /** Run a callback after the next paint (after React commit). */\n function afterPaint(callback: () => void): void {\n if (deps.afterPaint) {\n deps.afterPaint(callback);\n } else {\n callback();\n }\n }\n\n /**\n * Schedule scroll restoration after the next paint and fire the\n * scroll-restored event. Used by navigate, popstate, and refresh.\n */\n function restoreScrollAfterPaint(scrollY: number): void {\n afterPaint(() => {\n deps.scrollTo(0, scrollY);\n window.dispatchEvent(new Event('timber:scroll-restored'));\n });\n }\n\n /**\n * Core navigation logic shared between the transition and fallback paths.\n * Fetches the RSC payload, updates all state, and returns the result.\n */\n async function performNavigationFetch(\n url: string,\n options: { replace: boolean; signal?: AbortSignal; skipHistory?: boolean }\n ): Promise<FetchResult & { navState: NavigationState }> {\n // Check prefetch cache first. PrefetchResult has optional segmentInfo/params\n // fields — normalize to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(url);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n decodePromise: null,\n headElements: prefetched.headElements,\n segmentInfo: prefetched.segmentInfo ?? null,\n params: prefetched.params ?? null,\n skippedSegments: prefetched.skippedSegments ?? null,\n }\n : undefined;\n\n if (result === undefined) {\n // Fetch RSC payload with state tree for partial rendering.\n // Send current URL for intercepting route resolution (modal pattern).\n const stateTree = segmentCache.serializeStateTree();\n const rawCurrentUrl = deps.getCurrentUrl();\n const currentUrl = rawCurrentUrl.startsWith('http')\n ? new URL(rawCurrentUrl).pathname\n : new URL(rawCurrentUrl, 'http://localhost').pathname;\n result = await fetchRscPayload(url, deps, stateTree, currentUrl, options.signal);\n }\n\n // Update the browser history — skip when the Navigation API has already\n // updated the URL via event.intercept() (external navigations).\n if (!options.skipHistory) {\n // Set the router-navigating flag so the Navigation API's navigate\n // listener doesn't double-intercept this pushState/replaceState.\n deps.setRouterNavigating?.(true);\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', url);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', url);\n }\n deps.setRouterNavigating?.(false);\n }\n\n // NOTE: History push is deferred — the merged payload (after segment\n // merging in renderViaTransition) is stored by the caller, not here.\n // Storing result.payload here would record the partial (pre-merge)\n // RSC tree, causing handlePopState to replay an incomplete tree.\n\n // Update the segment cache with the new route's segment tree.\n updateSegmentCache(result.segmentInfo);\n\n // Update navigation state and capture it for explicit passing.\n const navState = updateNavigationState(result.params, url);\n\n return { ...result, navState };\n }\n\n async function navigate(url: string, options: NavigationOptions = {}): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n const externalSignal = options._signal as AbortSignal | undefined;\n const skipHistory = options._skipHistory === true;\n\n // Create an abort controller for this navigation. Links to the external\n // signal (Navigation API's event.signal) when provided.\n const navAbort = createNavAbort(externalSignal);\n\n // Capture the departing page's scroll position for scroll={false} preservation.\n const currentScrollY = deps.getScrollY();\n\n // Save the departing page's scroll position — use Navigation API entry\n // state when available, otherwise fall back to history.state.\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(currentScrollY);\n } else {\n deps.replaceState({ timber: true, scrollY: currentScrollY }, '', deps.getCurrentUrl());\n }\n\n // When Navigation API is active, initiate the navigation via\n // navigation.navigate() BEFORE the fetch. Unlike history.pushState()\n // which commits the URL synchronously (so Chrome sees it as \"done\"),\n // navigation.navigate() fires the navigate event before committing.\n // Our handler intercepts with a deferred promise, and Chrome shows\n // its native loading indicator until completeRouterNavigation()\n // resolves it in the finally block (same time as TopLoader clears).\n let effectiveSkipHistory = skipHistory;\n if (!skipHistory && deps.navigationNavigate) {\n deps.setRouterNavigating?.(true);\n deps.navigationNavigate(url, replace);\n deps.setRouterNavigating?.(false);\n effectiveSkipHistory = true;\n }\n\n setPending(true, url);\n\n try {\n const { headElements } = await renderViaTransition(url, () =>\n performNavigationFetch(url, {\n replace,\n signal: navAbort.signal,\n skipHistory: effectiveSkipHistory,\n })\n );\n\n // Update document.title and <meta> tags with the new page's metadata\n applyHead(headElements);\n\n // Notify nuqs adapter (and any other listeners) that navigation completed.\n window.dispatchEvent(new Event('timber:navigation-end'));\n\n // Scroll-to-top on forward navigation, or restore captured position\n // for scroll={false}. React's render() on the document root can reset\n // scroll during DOM reconciliation, so all scroll must be actively managed.\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n } catch (error) {\n // Version skew — server has been redeployed. Trigger full page reload\n // so the browser fetches the new bundle. See TIM-446.\n // Set hard-navigating flag to prevent Navigation API interception\n // and React from rendering during page teardown. See TIM-626.\n if (error instanceof VersionSkewError) {\n setHardNavigating(true);\n // Import triggerStaleReload dynamically to avoid circular deps\n // and keep the reload logic centralized with its loop guard.\n const { triggerStaleReload } = await import('./stale-reload.js');\n triggerStaleReload();\n // Return a never-resolving promise — page is reloading.\n return new Promise(() => {}) as never;\n }\n // Server-side redirect during RSC fetch → soft router navigation.\n // The redirect navigate will push/replace its own URL.\n if (error instanceof RedirectError) {\n setPending(false);\n deps.completeRouterNavigation?.();\n await navigate(error.redirectUrl, { replace: true });\n return;\n }\n // Server 5xx error — hard-navigate so the server renders the\n // error page as HTML. See design/10-error-handling.md\n // §\"Error Page Rendering for Client Navigation\".\n //\n // Set hard-navigating flag BEFORE setting window.location.href:\n // 1. Prevents Navigation API from intercepting → infinite loop\n // 2. Causes NavigationRoot to throw unresolvedThenable → prevents\n // React from rendering children during page teardown (avoids\n // \"Rendered more hooks\" crashes). See TIM-626.\n if (error instanceof ServerErrorResponse) {\n setHardNavigating(true);\n window.location.href = error.url;\n return new Promise(() => {}) as never;\n }\n // Stale client reference from streaming RSC decode — the server\n // was redeployed with new bundles. Same recovery as VersionSkewError.\n if (isStaleClientReference(error)) {\n setHardNavigating(true);\n triggerStaleReload();\n return new Promise(() => {}) as never;\n }\n // Abort errors are not application errors — swallow silently.\n if (isAbortError(error)) return;\n throw error;\n } finally {\n // Clear the abort controller so we don't abort a completed navigation\n // when the next one starts. In dev mode, the RSC body stream stays\n // open after data arrives (React's Flight client waits for debug rows).\n // Aborting a \"completed\" navigation kills the open stream reader →\n // \"BodyStreamBuffer was aborted\". By clearing the controller here,\n // createNavAbort() becomes a no-op for completed navigations.\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n // Resolve the Navigation API deferred — clears the browser's native\n // loading state (tab spinner) at the same time as the TopLoader.\n deps.completeRouterNavigation?.();\n }\n }\n\n async function refresh(): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n const navAbort = createNavAbort();\n\n setPending(true, currentUrl);\n\n try {\n const { headElements } = await renderViaTransition(currentUrl, async () => {\n // No state tree sent — server renders the complete RSC payload\n const result = await fetchRscPayload(\n currentUrl,\n deps,\n undefined,\n undefined,\n navAbort.signal\n );\n // History push handled by renderViaTransition (stores merged payload)\n updateSegmentCache(result.segmentInfo);\n const navState = updateNavigationState(result.params, currentUrl);\n return { ...result, navState };\n });\n\n applyHead(headElements);\n } catch (error) {\n if (isStaleClientReference(error)) {\n setHardNavigating(true);\n triggerStaleReload();\n return new Promise(() => {}) as never;\n }\n // Stale transition (superseded by a newer navigation) or aborted\n // fetch — silently ignore. See TIM-629.\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n deps.completeRouterNavigation?.();\n }\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal\n ): Promise<void> {\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip\n const navState = updateNavigationState(entry.params, url);\n renderPayload(entry.payload, navState);\n applyHead(entry.headElements);\n restoreScrollAfterPaint(scrollY);\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n const navAbort = createNavAbort(externalSignal);\n setPending(true, url);\n try {\n const { headElements } = await renderViaTransition(url, async () => {\n const stateTree = segmentCache.serializeStateTree();\n const result = await fetchRscPayload(url, deps, stateTree, undefined, navAbort.signal);\n updateSegmentCache(result.segmentInfo);\n const navState = updateNavigationState(result.params, url);\n // History push handled by renderViaTransition (stores merged payload)\n return { ...result, navState };\n });\n\n applyHead(headElements);\n restoreScrollAfterPaint(scrollY);\n } catch (error) {\n if (isStaleClientReference(error)) {\n setHardNavigating(true);\n triggerStaleReload();\n return new Promise(() => {}) as never;\n }\n // Stale transition (superseded by a newer navigation) or aborted\n // fetch — silently ignore. See TIM-629.\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n }\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n */\n function prefetch(url: string): void {\n // Don't prefetch if already cached\n if (prefetchCache.get(url) !== undefined) return;\n if (historyStack.has(url)) return;\n\n // Fire-and-forget fetch\n const stateTree = segmentCache.serializeStateTree();\n void fetchRscPayload(url, deps, stateTree).then(\n (result) => {\n result.decodePromise?.catch(() => {});\n prefetchCache.set(url, result);\n },\n () => {\n // Prefetch failure is non-fatal — navigation will fetch fresh\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n prefetch,\n applyRevalidation(element: unknown, headElements: HeadElement[] | null): void {\n // Render the piggybacked element tree from a server action response.\n // Updates the current history entry with the fresh payload and applies\n // head elements — same as refresh() but without a server fetch.\n // Revalidation payloads are already resolved (no Flight thenable),\n // so no segment merging is needed — just cache and render.\n const currentUrl = deps.getCurrentUrl();\n historyStack.push(currentUrl, {\n payload: element,\n headElements,\n });\n\n // Revalidation doesn't change params/pathname — preserve current state.\n // DO NOT call updateNavigationState(null, ...) here: that normalizes\n // params to {}, clearing dynamic route params on every action response.\n const navState = getNavigationState();\n renderPayload(element, navState);\n applyHead(headElements);\n },\n initSegmentCache: (segments: SegmentInfo[]) => updateSegmentCache(segments),\n segmentCache,\n prefetchCache,\n historyStack,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * On the client, reads from NavigationContext which is updated atomically\n * with the RSC tree render. This replaces the previous useSyncExternalStore\n * approach which read window.location.search directly — causing React to\n * detect external store tearing during transitions and fall back to\n * synchronous rendering (renderRootSync instead of renderRootConcurrent),\n * blocking the main thread and freezing animations.\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * During SSR, reads the request search params from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.js';\nimport { useNavigationContext } from './navigation-context.js';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.js';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n try {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- conditional on environment, not render path\n const navContext = useNavigationContext();\n if (navContext !== null) {\n return getSearchParams(navContext.search);\n }\n } catch {\n // No React dispatcher available (called outside a component).\n }\n\n // SSR path: read from ALS-backed SSR data context.\n const ssrData = getSsrData();\n if (ssrData) return new URLSearchParams(ssrData.searchParams);\n\n // Final fallback: window.location (tests, edge cases).\n if (typeof window !== 'undefined') return getSearchParams(window.location.search);\n return new URLSearchParams();\n}\n"],"mappings":";;;;;;;;;;;;;;AAiDA,IAAa,eAAb,MAA0B;CACxB;CAEA,IAAI,SAA0C;EAC5C,IAAI,YAAY,OAAO,YAAY,KAAK,MAAM,SAC5C,OAAO,KAAK;CAGhB;CAEA,IAAI,SAAiB,MAAyB;EAC5C,IAAI,YAAY,OAAO,CAAC,KAAK,MAC3B,KAAK,OAAO;CAEhB;CAEA,QAAc;EACZ,KAAK,OAAO,KAAA;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gBAAgB,QAAiC;CACxD,IAAI,WAAW,cAAc;EAC3B,MAAM,SAAS,IAAI,gBAAgB,MAAM;EACzC,iBAAiB,QAAQ,MAAM;EAC/B,OAAO;CACT;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAmC;CACjD,IAAI;EAEF,MAAM,aAAa,qBAAqB;EACxC,IAAI,eAAe,MACjB,OAAO,gBAAgB,WAAW,MAAM;CAE5C,QAAQ,CAER;CAGA,MAAM,UAAU,WAAW;CAC3B,IAAI,SAAS,OAAO,IAAI,gBAAgB,QAAQ,YAAY;CAG5D,IAAI,OAAO,WAAW,aAAa,OAAO,gBAAgB,OAAO,SAAS,MAAM;CAChF,OAAO,IAAI,gBAAgB;AAC7B"}
|
|
1
|
+
{"version":3,"file":"internal.js","names":[],"sources":["../../src/client/segment-cache.ts","../../src/client/history.ts","../../src/client/rsc-fetch.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// Segment Cache — stores the mounted segment tree and prefetched payloads\n// See design/19-client-navigation.md for architecture details.\n\nimport type { HeadElement } from './head';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional head elements and segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n headElements: HeadElement[] | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /** Route params from X-Timber-Params header for populating useSegmentParams(). */\n params?: Record<string, string | string[]> | null;\n /** Segment paths skipped by the server (for client-side merging). */\n skippedSegments?: string[] | null;\n}\n\n/**\n * A node in the client-side segment tree. Each node represents a mounted\n * layout or page segment with its RSC flight payload.\n */\nexport interface SegmentNode {\n /** The segment's URL pattern (e.g., \"/\", \"/dashboard\", \"/projects/[id]\") */\n segment: string;\n /** The RSC flight payload for this segment (opaque to the cache) */\n payload: unknown;\n /** Whether the segment is async (async layouts always re-render on navigation) */\n isAsync: boolean;\n /** Child segments keyed by segment path */\n children: Map<string, SegmentNode>;\n}\n\n/**\n * Serialized state tree sent via X-Timber-State-Tree header.\n * Only sync segments are included — async segments always re-render.\n */\nexport interface StateTree {\n segments: string[];\n}\n\n// ─── Segment Cache ───────────────────────────────────────────────\n\n/**\n * Maintains the client-side segment tree representing currently mounted\n * layouts and pages. Used for navigation reconciliation — the router diffs\n * new routes against this tree to determine which segments to re-fetch.\n */\nexport class SegmentCache {\n private root: SegmentNode | undefined;\n\n get(segment: string): SegmentNode | undefined {\n if (segment === '/' || segment === this.root?.segment) {\n return this.root;\n }\n return undefined;\n }\n\n set(segment: string, node: SegmentNode): void {\n if (segment === '/' || !this.root) {\n this.root = node;\n }\n }\n\n clear(): void {\n this.root = undefined;\n }\n\n /**\n * Serialize the mounted segment tree for the X-Timber-State-Tree header.\n * Only includes sync segments — async segments are excluded because the\n * server must always re-render them (they may depend on request context).\n *\n * When mergeableFilter is provided, only segments whose paths are in the\n * set are included. This ensures the server only skips segments that the\n * client can actually merge (i.e., segments whose cached element tree\n * contains an inner SegmentProvider the merger can splice into).\n *\n * This is a performance optimization only, NOT a security boundary.\n * The server always runs all access.ts files regardless of the state tree.\n */\n serializeStateTree(mergeableFilter?: Set<string>): StateTree {\n const segments: string[] = [];\n if (this.root) {\n collectSyncSegments(this.root, segments, mergeableFilter);\n }\n return { segments };\n }\n}\n\n/** Recursively collect sync segment paths from the tree */\nfunction collectSyncSegments(\n node: SegmentNode,\n out: string[],\n mergeableFilter?: Set<string>\n): void {\n if (!node.isAsync && (!mergeableFilter || mergeableFilter.has(node.segment))) {\n out.push(node.segment);\n }\n for (const child of node.children.values()) {\n collectSyncSegments(child, out, mergeableFilter);\n }\n}\n\n// ─── Segment Tree Builder ────────────────────────────────────────\n\n/**\n * Segment metadata from the server, sent via X-Timber-Segments header.\n * Describes a rendered segment's path and whether it's async.\n */\nexport interface SegmentInfo {\n path: string;\n /** Outlet key — includes route group name when applicable (e.g., \"/(marketing)\"). */\n segmentId?: string;\n isAsync: boolean;\n}\n\n/**\n * Build a SegmentNode tree from flat segment metadata.\n *\n * Takes an ordered list of segment descriptors (root → leaf) from the\n * server's X-Timber-Segments header and constructs the hierarchical\n * tree structure that SegmentCache expects.\n *\n * Each segment is nested as a child of the previous one, forming a\n * linear chain from root to leaf. The leaf segment (page) is excluded\n * from the tree — pages are never cached across navigations.\n */\nexport function buildSegmentTree(segments: SegmentInfo[]): SegmentNode | undefined {\n // Need at least a root segment to build a tree\n if (segments.length === 0) return undefined;\n\n // Exclude the leaf (page) — pages always re-render on navigation.\n // Only layouts are cached in the segment tree.\n const layouts = segments.length > 1 ? segments.slice(0, -1) : segments;\n\n let root: SegmentNode | undefined;\n let parent: SegmentNode | undefined;\n\n for (const info of layouts) {\n const id = info.segmentId ?? info.path;\n const node: SegmentNode = {\n segment: id,\n payload: null,\n isAsync: info.isAsync,\n children: new Map(),\n };\n\n if (!root) {\n root = node;\n }\n\n if (parent) {\n parent.children.set(id, node);\n }\n\n parent = node;\n }\n\n return root;\n}\n\n// ─── Prefetch Cache ──────────────────────────────────────────────\n\ninterface PrefetchEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/**\n * Short-lived cache for hover-triggered prefetches. Entries expire after\n * 30 seconds. When a link is clicked, the prefetched payload is consumed\n * (moved to the history stack) and removed from this cache.\n *\n * timber.js does NOT prefetch on viewport intersection — only explicit\n * hover on <Link prefetch> triggers a prefetch.\n */\nexport class PrefetchCache {\n private static readonly TTL_MS = 30_000;\n private entries = new Map<string, PrefetchEntry>();\n\n set(url: string, result: PrefetchResult): void {\n this.entries.set(url, {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(url: string): PrefetchResult | undefined {\n const entry = this.entries.get(url);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(url);\n return undefined;\n }\n return entry.result;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(url: string): PrefetchResult | undefined {\n const result = this.get(url);\n if (result !== undefined) {\n this.entries.delete(url);\n }\n return result;\n }\n}\n","// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { HeadElement } from './head';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /** Resolved head elements for this page (title, meta tags). Null for SSR'd initial page. */\n headElements?: HeadElement[] | null;\n /** Route params for this page (for useParams). Null for SSR'd initial page. */\n params?: Record<string, string | string[]> | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Supports two keying modes:\n * - **URL-keyed** (default): entries keyed by pathname + search.\n * Used with the History API fallback.\n * - **Entry-key + URL**: when the Navigation API is available,\n * entries can also be stored by Navigation entry key for\n * disambiguation of duplicate URLs in the history stack.\n * Falls back to URL lookup when entry key is not found.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries persist for the session duration (no expiry) and are cleared\n * when the tab is closed — matching browser back-button behavior.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n /** Entries keyed by Navigation API entry key for duplicate URL disambiguation. */\n private entryKeyMap = new Map<string, HistoryEntry>();\n\n push(url: string, entry: HistoryEntry, entryKey?: string): void {\n this.entries.set(url, entry);\n if (entryKey) {\n this.entryKeyMap.set(entryKey, entry);\n }\n }\n\n /**\n * Get an entry. When an entry key is provided (Navigation API),\n * tries the entry-key map first for accurate disambiguation of\n * duplicate URLs, then falls back to URL lookup.\n */\n get(url: string, entryKey?: string): HistoryEntry | undefined {\n if (entryKey) {\n const byKey = this.entryKeyMap.get(entryKey);\n if (byKey) return byKey;\n }\n return this.entries.get(url);\n }\n\n has(url: string): boolean {\n return this.entries.has(url);\n }\n}\n","/**\n * RSC Fetch — handles fetching and parsing RSC Flight payloads.\n *\n * Extracted from router.ts to keep both files under the 500-line limit.\n * This module handles:\n * - Cache-busting URL generation for RSC requests\n * - Building RSC request headers (Accept, X-Timber-State-Tree)\n * - Extracting metadata from RSC response headers\n * - Fetching and decoding RSC payloads\n *\n * See design/19-client-navigation.md §\"RSC Payload Handling\"\n */\n\nimport type { SegmentInfo } from './segment-cache';\nimport type { HeadElement } from './head';\nimport type { RouterDeps } from './router';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Result of fetching an RSC payload — includes head elements and segment metadata. */\nexport interface FetchResult {\n payload: unknown;\n /**\n * Promise that settles when the RSC decode completes or fails.\n * The payload thenable is NOT awaited before returning (for streaming),\n * so callers must monitor this to catch async decode errors\n * (truncated streams, Flight parse failures) that would otherwise\n * become unhandled rejections.\n */\n decodePromise: Promise<void> | null;\n headElements: HeadElement[] | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo: SegmentInfo[] | null;\n /** Route params from X-Timber-Params header for populating useSegmentParams(). */\n params: Record<string, string | string[]> | null;\n /** Segment paths that were skipped by the server (for client-side merging). */\n skippedSegments: string[] | null;\n}\n\n// ─── Constants ───────────────────────────────────────────────────\n\nexport const RSC_CONTENT_TYPE = 'text/x-component';\n\n// ─── URL Helpers ─────────────────────────────────────────────────\n\n/**\n * Generate a short random cache-busting ID (5 chars, a-z0-9).\n * Matches the format Next.js uses for _rsc params.\n */\nfunction generateCacheBustId(): string {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';\n let id = '';\n for (let i = 0; i < 5; i++) {\n id += chars[(Math.random() * 36) | 0];\n }\n return id;\n}\n\n/**\n * Append a `_rsc=<id>` query parameter to the URL.\n * Follows Next.js's pattern — prevents CDN/browser from serving cached HTML\n * for RSC navigation requests and signals that this is an RSC fetch.\n */\nfunction appendRscParam(url: string): string {\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}_rsc=${generateCacheBustId()}`;\n}\n\n// ─── Deployment ID ───────────────────────────────────────────────\n\n/**\n * The client's deployment ID, set at bootstrap from the runtime config.\n * Sent with every RSC/action request for version skew detection.\n * Null in dev mode. See TIM-446.\n */\nlet clientDeploymentId: string | null = null;\n\n/** Set the client deployment ID. Called once at bootstrap. */\nexport function setClientDeploymentId(id: string | null): void {\n clientDeploymentId = id;\n}\n\n/** Get the client deployment ID. */\nexport function getClientDeploymentId(): string | null {\n return clientDeploymentId;\n}\n\n// ─── Reload Signal ───────────────────────────────────────────────\n\n/** Header name used by the server to signal a version skew reload. */\nexport const RELOAD_HEADER = 'X-Timber-Reload';\n\n/** Header name for the client's deployment ID. */\nexport const DEPLOYMENT_ID_HEADER = 'X-Timber-Deployment-Id';\n\n/**\n * Check if a response signals a version skew reload.\n * Triggers a full page reload if the server indicates the client is stale.\n */\nexport function checkReloadSignal(response: Response): boolean {\n return response.headers.get(RELOAD_HEADER) === '1';\n}\n\n// ─── Header Builder ──────────────────────────────────────────────\n\nexport function buildRscHeaders(\n stateTree: { segments: string[] } | undefined,\n currentUrl?: string\n): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: RSC_CONTENT_TYPE,\n };\n if (stateTree) {\n headers['X-Timber-State-Tree'] = JSON.stringify(stateTree);\n }\n // Send current URL for intercepting route resolution.\n // The server uses this to determine if an intercepting route should\n // render instead of the actual target route (modal pattern).\n // See design/07-routing.md §\"Intercepting Routes\"\n if (currentUrl) {\n headers['X-Timber-URL'] = currentUrl;\n }\n // Send deployment ID for version skew detection (TIM-446).\n // The server compares this against the current build's ID.\n // On mismatch, the server signals a reload instead of returning\n // an RSC payload with mismatched module references.\n if (clientDeploymentId) {\n headers[DEPLOYMENT_ID_HEADER] = clientDeploymentId;\n }\n return headers;\n}\n\n// ─── Response Header Extraction ──────────────────────────────────\n\n/** Dev-only warning for malformed framework headers. Tree-shaken in production. */\nfunction warnMalformedHeader(headerName: string, raw: string): void {\n if (process.env.NODE_ENV !== 'production') {\n const preview = raw.length > 200 ? raw.slice(0, 200) + '…' : raw;\n console.warn(\n `[timber] Malformed ${headerName} header \\u2014 JSON.parse failed. ` +\n `This indicates a framework bug or header corruption. Raw (first 200 chars): ${preview}`\n );\n }\n}\n\n/**\n * Extract head elements from the X-Timber-Head response header.\n * Returns null if the header is missing or malformed.\n */\nexport function extractHeadElements(response: Response): HeadElement[] | null {\n const header = response.headers.get('X-Timber-Head');\n if (!header) return null;\n try {\n return JSON.parse(decodeURIComponent(header));\n } catch {\n warnMalformedHeader('X-Timber-Head', header);\n return null;\n }\n}\n\n/**\n * Extract segment metadata from the X-Timber-Segments response header.\n * Returns null if the header is missing or malformed.\n *\n * Format: JSON array of {path, isAsync} objects describing the rendered\n * segment chain from root to leaf. Used to populate the client-side\n * segment cache for state tree diffing on subsequent navigations.\n */\nexport function extractSegmentInfo(response: Response): SegmentInfo[] | null {\n const header = response.headers.get('X-Timber-Segments');\n if (!header) return null;\n try {\n return JSON.parse(header);\n } catch {\n warnMalformedHeader('X-Timber-Segments', header);\n return null;\n }\n}\n\n/**\n * Extract skipped segment paths from the X-Timber-Skipped-Segments header.\n * Returns null if the header is missing or malformed.\n *\n * When the server skips sync layouts the client already has cached,\n * it sends this header listing the skipped segment paths (outermost first).\n * The client uses this to merge the partial payload with cached segments.\n */\nexport function extractSkippedSegments(response: Response): string[] | null {\n const header = response.headers.get('X-Timber-Skipped-Segments');\n if (!header) return null;\n try {\n const parsed = JSON.parse(header);\n return Array.isArray(parsed) ? parsed : null;\n } catch {\n warnMalformedHeader('X-Timber-Skipped-Segments', header);\n return null;\n }\n}\n\n/**\n * Extract route params from the X-Timber-Params response header.\n * Returns null if the header is missing or malformed.\n *\n * Used to populate useSegmentParams() after client-side navigation.\n */\nexport function extractParams(response: Response): Record<string, string | string[]> | null {\n const header = response.headers.get('X-Timber-Params');\n if (!header) return null;\n try {\n return JSON.parse(header);\n } catch {\n warnMalformedHeader('X-Timber-Params', header);\n return null;\n }\n}\n\n// ─── Redirect Error ──────────────────────────────────────────────\n\n/**\n * Thrown when an RSC payload response contains X-Timber-Redirect header.\n * Caught in navigate() to trigger a soft router navigation to the redirect target.\n */\nexport class RedirectError extends Error {\n readonly redirectUrl: string;\n constructor(url: string) {\n super(`Server redirect to ${url}`);\n this.redirectUrl = url;\n }\n}\n\n/**\n * Thrown when the server signals a version skew (X-Timber-Reload header).\n * Caught in navigate() to trigger a full page reload.\n * See TIM-446.\n */\nexport class VersionSkewError extends Error {\n constructor() {\n super('Version skew detected — server has been redeployed');\n }\n}\n\n/**\n * Thrown when the server returns an error for an RSC payload request.\n * The server sends X-Timber-Error header and a JSON body instead of a\n * broken RSC stream for any RenderError (4xx or 5xx). Caught in\n * navigate() to trigger a hard navigation so the server can render\n * the error page as HTML.\n *\n * See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n */\nexport class ServerErrorResponse extends Error {\n readonly status: number;\n readonly url: string;\n constructor(status: number, url: string) {\n super(`Server error ${status} during navigation to ${url}`);\n this.status = status;\n this.url = url;\n }\n}\n\n// ─── Stream Completion Tracking ───────────────────────────────────\n\n/**\n * Wrap a response body stream to track when it's fully consumed.\n * Returns a new body that passes all chunks through unchanged, plus\n * a `done` promise that resolves when the last chunk is read (or\n * rejects if the stream errors).\n *\n * Used to keep React transitions open for the full RSC stream\n * duration — createFromFetch's thenable resolves on shell arrival,\n * but we need stream completion for useOptimistic pending state.\n */\nfunction trackStreamCompletion(body: ReadableStream<Uint8Array>): {\n body: ReadableStream<Uint8Array>;\n done: Promise<void>;\n} {\n let resolveDone!: () => void;\n let rejectDone!: (e: unknown) => void;\n const done = new Promise<void>((res, rej) => {\n resolveDone = res;\n rejectDone = rej;\n });\n\n const reader = body.getReader();\n const tracked = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const result = await reader.read();\n if (result.done) {\n controller.close();\n resolveDone();\n } else {\n controller.enqueue(result.value);\n }\n } catch (error) {\n controller.error(error);\n rejectDone(error);\n }\n },\n cancel(reason) {\n reader.cancel(reason);\n resolveDone();\n },\n });\n\n return { body: tracked, done };\n}\n\n// ─── Fetch ───────────────────────────────────────────────────────\n\n/**\n * Fetch an RSC payload from the server. If a decodeRsc function is provided,\n * the response is decoded into a React element tree via createFromFetch.\n * Otherwise, the raw response text is returned (test mode).\n *\n * Also extracts head elements from the X-Timber-Head response header\n * so the client can update document.title and <meta> tags after navigation.\n */\nexport async function fetchRscPayload(\n url: string,\n deps: RouterDeps,\n stateTree?: { segments: string[] },\n currentUrl?: string,\n signal?: AbortSignal\n): Promise<FetchResult> {\n const rscUrl = appendRscParam(url);\n const headers = buildRscHeaders(stateTree, currentUrl);\n if (deps.decodeRsc) {\n // Production path: use createFromFetch for streaming RSC decoding.\n // createFromFetch takes a Promise<Response> and progressively parses\n // the RSC Flight stream as chunks arrive.\n //\n // Intercept the response to read X-Timber-Head before createFromFetch\n // consumes the body. Reading headers does NOT consume the body stream.\n const fetchPromise = deps.fetch(rscUrl, { headers, redirect: 'manual', signal });\n let headElements: HeadElement[] | null = null;\n let segmentInfo: SegmentInfo[] | null = null;\n let params: Record<string, string | string[]> | null = null;\n let skippedSegments: string[] | null = null;\n // Track when the full RSC body stream is consumed (not just shell).\n // Initialized to resolved for bodyless responses; overwritten when\n // the response has a body.\n let streamDone: Promise<void> = Promise.resolve();\n\n const wrappedPromise = fetchPromise.then((response) => {\n // Version skew detection (TIM-446): if the server signals a reload,\n // throw VersionSkewError so the caller (router navigate) can trigger\n // a full page reload.\n if (checkReloadSignal(response)) {\n throw new VersionSkewError();\n }\n // Detect server-side redirects. The server returns 204 + X-Timber-Redirect\n // for RSC payload requests instead of a raw 302, because fetch with\n // redirect: \"manual\" turns 302s into opaque redirects (status 0, null body)\n // which crashes createFromFetch when it tries to read the body stream.\n const redirectLocation =\n response.headers.get('X-Timber-Redirect') ||\n (response.status >= 300 && response.status < 400 ? response.headers.get('Location') : null);\n if (redirectLocation) {\n throw new RedirectError(redirectLocation);\n }\n // Detect server error responses. The server returns X-Timber-Error header\n // with a JSON body instead of a broken RSC stream for any RenderError\n // (4xx or 5xx). Hard-navigate so the server renders the error page as HTML.\n // See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n if (response.headers.get('X-Timber-Error') === '1') {\n throw new ServerErrorResponse(response.status, url);\n }\n headElements = extractHeadElements(response);\n segmentInfo = extractSegmentInfo(response);\n params = extractParams(response);\n skippedSegments = extractSkippedSegments(response);\n\n // Wrap the body to track full stream consumption. createFromFetch's\n // thenable resolves when the root model (shell) arrives, but we need\n // to know when ALL chunks are read so the React transition stays\n // open for the full streaming duration (keeps useOptimistic alive).\n if (response.body) {\n const tracked = trackStreamCompletion(response.body);\n streamDone = tracked.done;\n streamDone.catch(() => {}); // prevent unhandled rejection\n return new Response(tracked.body, {\n headers: response.headers,\n status: response.status,\n });\n }\n return response;\n });\n // Await headers so headElements/segmentInfo/params are populated.\n await wrappedPromise;\n // Start decoding but do NOT await — return the in-progress thenable.\n // React can render a Flight thenable directly: it suspends on unresolved\n // parts and progressively renders as chunks arrive, spreading work across\n // frames instead of blocking the main thread in one burst.\n const payload = deps.decodeRsc(wrappedPromise);\n // Combine stream completion with payload error propagation.\n // streamDone keeps the transition open for the full RSC stream\n // duration (useOptimistic pending state). payloadError propagates\n // decode failures (stale client references, Flight parse errors)\n // so the router's catch block can trigger recovery (stale reload).\n const payloadError = new Promise<void>((_, reject) => {\n Promise.resolve(payload).then(() => {}, reject);\n });\n payloadError.catch(() => {});\n const decodePromise = Promise.race([streamDone, payloadError]);\n return {\n payload,\n decodePromise,\n headElements,\n segmentInfo,\n params,\n skippedSegments,\n };\n }\n // Test/fallback path: return raw text\n const response = await deps.fetch(rscUrl, { headers, redirect: 'manual', signal });\n // Check for redirect in test path too\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('Location');\n if (location) {\n throw new RedirectError(location);\n }\n }\n return {\n payload: await response.text(),\n decodePromise: null,\n headElements: extractHeadElements(response),\n segmentInfo: extractSegmentInfo(response),\n params: extractParams(response),\n skippedSegments: extractSkippedSegments(response),\n };\n}\n","// Segment Router — manages client-side navigation and RSC payload fetching\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache, buildSegmentTree } from './segment-cache';\nimport type { SegmentInfo } from './segment-cache';\nimport { HistoryStack } from './history';\nimport type { HeadElement } from './head';\nimport { setCurrentParams } from './use-segment-params.js';\nimport {\n setNavigationState,\n getNavigationState,\n type NavigationState,\n} from './navigation-context.js';\n\nimport {\n fetchRscPayload,\n RedirectError,\n ServerErrorResponse,\n VersionSkewError,\n} from './rsc-fetch.js';\nimport { setHardNavigating } from './navigation-root.js';\nimport type { FetchResult } from './rsc-fetch.js';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface NavigationOptions {\n /** Set to false to prevent scroll-to-top on forward navigation */\n scroll?: boolean;\n /** Use replaceState instead of pushState (replaces current history entry) */\n replace?: boolean;\n /**\n * @internal AbortSignal from the Navigation API's NavigateEvent.\n * When provided, the signal is linked to the router's per-navigation\n * AbortController so in-flight RSC fetches are cancelled when a new\n * navigation starts.\n */\n _signal?: AbortSignal;\n /**\n * @internal Skip pushState/replaceState — the Navigation API has already\n * updated the URL via event.intercept(). Used for external navigations\n * intercepted by the navigate event handler.\n */\n _skipHistory?: boolean;\n}\n\n/**\n * Function that decodes an RSC Flight stream into a React element tree.\n * In production: createFromFetch from @vitejs/plugin-rsc/browser.\n * In tests: a mock that returns the raw payload.\n */\nexport type RscDecoder = (fetchPromise: Promise<Response>) => unknown;\n\n/**\n * Function that renders a decoded RSC element tree into the DOM.\n * In production: reactRoot.render(element).\n * In tests: a no-op or mock.\n *\n * Receives the current NavigationState explicitly — no temporal\n * coupling with setNavigationState/getNavigationState. The renderer\n * wraps the element in NavigationProvider with this state.\n */\nexport type RootRenderer = (element: unknown, navState: NavigationState) => void;\n\n/**\n * Platform dependencies injected for testability. In production these\n * map to browser APIs; in tests they're replaced with mocks.\n */\nexport interface RouterDeps {\n fetch: (url: string, init: RequestInit) => Promise<Response>;\n pushState: (data: unknown, unused: string, url: string) => void;\n replaceState: (data: unknown, unused: string, url: string) => void;\n scrollTo: (x: number, y: number) => void;\n getCurrentUrl: () => string;\n getScrollY: () => number;\n /** Decode RSC Flight stream into React elements. If not provided, raw response text is stored. */\n decodeRsc?: RscDecoder;\n /** Render decoded RSC tree into the DOM. If not provided, rendering is a no-op. */\n renderRoot?: RootRenderer;\n /**\n * Schedule a callback after the next paint. In the browser, this is\n * requestAnimationFrame + setTimeout(0) to run after React commits.\n * In tests, this runs the callback synchronously.\n */\n afterPaint?: (callback: () => void) => void;\n /** Apply resolved head elements (title, meta tags) to the DOM after navigation. */\n applyHead?: (elements: HeadElement[]) => void;\n /**\n * Run a navigation inside a React transition with optimistic pending URL.\n * The pending URL shows immediately (useOptimistic urgent update) and\n * reverts when the transition commits (atomic with the new tree).\n *\n * The `perform` callback receives a `wrapPayload` function to wrap the\n * decoded RSC payload with NavigationProvider + NuqsAdapter before\n * NavigationRoot sets it as the new element. The `wrapPayload` function\n * receives the NavigationState explicitly — no temporal coupling with\n * getNavigationState().\n *\n * If not provided (tests), the router falls back to renderRoot.\n */\n navigateTransition?: (\n pendingUrl: string,\n perform: (\n wrapPayload: (\n payload: unknown,\n navState: NavigationState,\n segmentUpdates?: Map<string, unknown>\n ) => unknown\n ) => Promise<{ element: unknown; decodePromise: Promise<void> | null }>\n ) => Promise<void>;\n\n /**\n * Whether the Navigation API is active and handling traversals.\n * When true, the popstate handler is a no-op — the Navigation API's\n * navigate event covers back/forward button presses.\n */\n navigationApiActive?: boolean;\n\n /**\n * Called around pushState/replaceState to set a flag that prevents\n * the Navigation API's navigate listener from double-handling\n * router-initiated navigations.\n */\n setRouterNavigating?: (value: boolean) => void;\n\n /**\n * Save scroll position via the Navigation API's per-entry state.\n * When provided, used instead of history.replaceState for scroll storage.\n */\n saveNavigationEntryScroll?: (scrollY: number) => void;\n\n /**\n * Signal that a router-initiated navigation has completed. Resolves the\n * deferred promise that ties the browser's native loading state to the\n * navigation lifecycle. Called in the finally block of navigate/refresh,\n * aligned with when the TopLoader's pendingUrl clears.\n */\n completeRouterNavigation?: () => void;\n\n /**\n * Get the current unwrapped RSC payload element. Used for partial\n * navigation: the router re-wraps the same element with new\n * NavigationProvider context so mounted SegmentOutlets are preserved.\n */\n _getCurrentPayload?: () => unknown;\n\n /**\n * Initiate a navigation via the Navigation API (`navigation.navigate()`).\n * Fires the navigate event BEFORE committing the URL, allowing Chrome\n * to show its native loading indicator. Falls back to pushState when\n * unavailable.\n */\n navigationNavigate?: (url: string, replace: boolean) => void;\n}\n\nexport interface RouterInstance {\n /** Navigate to a new URL (forward navigation) */\n navigate(url: string, options?: NavigationOptions): Promise<void>;\n /** Full re-render of the current URL — no state tree sent */\n refresh(): Promise<void>;\n /** Handle a popstate event (back/forward button). scrollY is read from history.state. */\n handlePopState(url: string, scrollY?: number, externalSignal?: AbortSignal): Promise<void>;\n /** Whether a navigation is currently in flight */\n isPending(): boolean;\n /** The URL currently being navigated to, or null if idle */\n getPendingUrl(): string | null;\n /** Subscribe to pending state changes */\n onPendingChange(listener: (pending: boolean) => void): () => void;\n /** Prefetch an RSC payload for a URL (used by Link hover) */\n prefetch(url: string): void;\n /**\n * Apply a piggybacked revalidation payload from a server action response.\n * Renders the element tree and updates head elements without a server fetch.\n * See design/08-forms-and-actions.md §\"Single-Roundtrip Revalidation\".\n */\n applyRevalidation(element: unknown, headElements: HeadElement[] | null): void;\n /**\n * Populate the segment cache from server-provided segment metadata.\n * Called on initial hydration with segment info embedded in the HTML.\n */\n initSegmentCache(segments: SegmentInfo[]): void;\n\n /** The segment cache (exposed for tests and <Link> prefetch) */\n segmentCache: SegmentCache;\n /** The prefetch cache (exposed for tests and <Link> prefetch) */\n prefetchCache: PrefetchCache;\n /** The history stack (exposed for tests) */\n historyStack: HistoryStack;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\n/**\n * Router navigation phase — discriminated union replacing scattered\n * `pending` + `pendingUrl` boolean flags.\n *\n * - `idle`: No navigation in flight. The committed params/pathname\n * are current.\n * - `navigating`: A fetch or render is in progress. `targetUrl` is\n * the destination being navigated to.\n */\nexport type RouterPhase = { phase: 'idle' } | { phase: 'navigating'; targetUrl: string };\n\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n // AbortController for the current in-flight navigation.\n // When a new navigation starts, the previous controller is aborted,\n // cancelling any in-progress RSC fetch. This provides automatic\n // cancellation of stale fetches regardless of Navigation API support.\n let currentNavAbort: AbortController | null = null;\n\n /**\n * Create a new AbortController for a navigation, aborting any\n * previous in-flight navigation. Optionally links to an external\n * signal (e.g., from the Navigation API's NavigateEvent.signal).\n */\n function createNavAbort(externalSignal?: AbortSignal): AbortController {\n // Abort previous navigation's fetch\n currentNavAbort?.abort();\n const controller = new AbortController();\n currentNavAbort = controller;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n if (externalSignal) {\n if (externalSignal.aborted) {\n controller.abort();\n } else {\n externalSignal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n }\n\n return controller;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify external store listeners (non-React consumers).\n // React-facing pending state is handled by useOptimistic in\n // NavigationRoot via navigateTransition — not this function.\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /** Update the segment cache from server-provided segment metadata. */\n function updateSegmentCache(segmentInfo: SegmentInfo[] | null | undefined): void {\n if (!segmentInfo || segmentInfo.length === 0) return;\n const tree = buildSegmentTree(segmentInfo);\n if (tree) {\n segmentCache.set('/', tree);\n }\n }\n\n /** Render a decoded RSC payload into the DOM if a renderer is available. */\n function renderPayload(payload: unknown, navState: NavigationState): void {\n if (deps.renderRoot) {\n deps.renderRoot(payload, navState);\n }\n }\n\n function isPartialNavigation(skippedSegments: string[] | null | undefined): boolean {\n return skippedSegments != null && skippedSegments.length > 0;\n }\n\n /**\n * Build a segment updates map for partial navigation. Identifies the\n * first non-skipped segment and maps it to the payload content.\n */\n function buildSegmentUpdates(result: FetchResult): Map<string, unknown> {\n const skipped = new Set(result.skippedSegments!);\n const segmentInfo = result.segmentInfo;\n const updates = new Map<string, unknown>();\n if (segmentInfo) {\n for (const info of segmentInfo) {\n if (!skipped.has(info.segmentId ?? info.path)) {\n // Use segmentId (outlet key) when available — route groups\n // use a disambiguated key like \"/(marketing)\" instead of \"/\".\n updates.set(info.segmentId ?? info.path, result.payload);\n break;\n }\n }\n }\n return updates;\n }\n\n /**\n * Update navigation state (params + pathname) for the next render.\n *\n * Sets the module-level fallback (for tests and SSR) and the\n * globalThis bridge, then returns the NavigationState so callers\n * can pass it explicitly to renderRoot/wrapPayload — eliminating\n * temporal coupling with getNavigationState().\n */\n function updateNavigationState(\n params: Record<string, string | string[]> | null | undefined,\n url: string\n ): NavigationState {\n const resolvedParams = params ?? {};\n // Module-level fallback for tests (no NavigationProvider) and SSR\n setCurrentParams(resolvedParams);\n // globalThis bridge — kept for backward compat\n const parsed = new URL(url, 'http://localhost');\n const pathname = parsed.pathname || '/';\n const search = parsed.search;\n const navState: NavigationState = { params: resolvedParams, pathname, search };\n setNavigationState(navState);\n return navState;\n }\n\n /**\n * Render a payload via navigateTransition (production) or renderRoot (tests).\n * The perform callback should fetch data, update state, and return the\n * FetchResult plus the NavigationState (so it can be passed explicitly\n * to wrapPayload/renderRoot without temporal coupling).\n */\n interface TransitionResult {\n headElements: HeadElement[] | null;\n decodePromise: Promise<void> | null;\n }\n\n async function renderViaTransition(\n url: string,\n perform: () => Promise<FetchResult & { navState: NavigationState }>\n ): Promise<TransitionResult> {\n if (deps.navigateTransition) {\n let headElements: HeadElement[] | null = null;\n await deps.navigateTransition(url, async (wrapPayload) => {\n const result = await perform();\n headElements = result.headElements;\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result);\n\n historyStack.push(url, {\n payload: null,\n headElements: result.headElements,\n params: result.params,\n });\n\n // Re-wrap the CURRENT element with new context values.\n // SegmentOutlets read updates from SegmentUpdateContext;\n // NavigationProvider gets new params/pathname.\n const element = wrapPayload(\n deps._getCurrentPayload?.() ?? result.payload,\n result.navState,\n segmentUpdates\n );\n return { element, decodePromise: result.decodePromise };\n }\n\n // Full navigation — empty updates, render the new tree.\n historyStack.push(url, {\n payload: result.payload,\n headElements: result.headElements,\n params: result.params,\n });\n const element = wrapPayload(result.payload, result.navState);\n return { element, decodePromise: result.decodePromise };\n });\n // decodePromise is awaited inside the transition's startTransition\n // callback (NavigationRoot), so we don't need it here.\n return { headElements, decodePromise: null };\n }\n // Fallback: no transition (tests, no React tree)\n const result = await perform();\n if (isPartialNavigation(result.skippedSegments)) {\n historyStack.push(url, {\n payload: null,\n headElements: result.headElements,\n params: result.params,\n });\n } else {\n // Resolve thenables before storing/rendering in the fallback path\n // (tests without navigateTransition). In production, React handles\n // thenables via Suspense; in tests, renderRoot expects resolved values.\n const payload =\n result.payload != null && typeof result.payload === 'object' && 'then' in result.payload\n ? await (result.payload as PromiseLike<unknown>)\n : result.payload;\n historyStack.push(url, {\n payload,\n headElements: result.headElements,\n params: result.params,\n });\n renderPayload(payload, result.navState);\n }\n return { headElements: result.headElements, decodePromise: result.decodePromise };\n }\n\n /** Apply head elements (title, meta tags) to the DOM if available. */\n function applyHead(elements: HeadElement[] | null | undefined): void {\n if (elements && deps.applyHead) {\n deps.applyHead(elements);\n }\n }\n\n /** Run a callback after the next paint (after React commit). */\n function afterPaint(callback: () => void): void {\n if (deps.afterPaint) {\n deps.afterPaint(callback);\n } else {\n callback();\n }\n }\n\n /**\n * Schedule scroll restoration after the next paint and fire the\n * scroll-restored event. Used by navigate, popstate, and refresh.\n */\n function restoreScrollAfterPaint(scrollY: number): void {\n afterPaint(() => {\n deps.scrollTo(0, scrollY);\n window.dispatchEvent(new Event('timber:scroll-restored'));\n });\n }\n\n /**\n * Core navigation logic shared between the transition and fallback paths.\n * Fetches the RSC payload, updates all state, and returns the result.\n */\n async function performNavigationFetch(\n url: string,\n options: { replace: boolean; signal?: AbortSignal; skipHistory?: boolean }\n ): Promise<FetchResult & { navState: NavigationState }> {\n // Check prefetch cache first. PrefetchResult has optional segmentInfo/params\n // fields — normalize to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(url);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n decodePromise: null,\n headElements: prefetched.headElements,\n segmentInfo: prefetched.segmentInfo ?? null,\n params: prefetched.params ?? null,\n skippedSegments: prefetched.skippedSegments ?? null,\n }\n : undefined;\n\n if (result === undefined) {\n // Fetch RSC payload with state tree for partial rendering.\n // Send current URL for intercepting route resolution (modal pattern).\n const stateTree = segmentCache.serializeStateTree();\n const rawCurrentUrl = deps.getCurrentUrl();\n const currentUrl = rawCurrentUrl.startsWith('http')\n ? new URL(rawCurrentUrl).pathname\n : new URL(rawCurrentUrl, 'http://localhost').pathname;\n result = await fetchRscPayload(url, deps, stateTree, currentUrl, options.signal);\n }\n\n // Update the browser history — skip when the Navigation API has already\n // updated the URL via event.intercept() (external navigations).\n if (!options.skipHistory) {\n // Set the router-navigating flag so the Navigation API's navigate\n // listener doesn't double-intercept this pushState/replaceState.\n deps.setRouterNavigating?.(true);\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', url);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', url);\n }\n deps.setRouterNavigating?.(false);\n }\n\n // NOTE: History push is deferred — the merged payload (after segment\n // merging in renderViaTransition) is stored by the caller, not here.\n // Storing result.payload here would record the partial (pre-merge)\n // RSC tree, causing handlePopState to replay an incomplete tree.\n\n // Update the segment cache with the new route's segment tree.\n updateSegmentCache(result.segmentInfo);\n\n // Update navigation state and capture it for explicit passing.\n const navState = updateNavigationState(result.params, url);\n\n return { ...result, navState };\n }\n\n async function navigate(url: string, options: NavigationOptions = {}): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n const externalSignal = options._signal as AbortSignal | undefined;\n const skipHistory = options._skipHistory === true;\n\n // Create an abort controller for this navigation. Links to the external\n // signal (Navigation API's event.signal) when provided.\n const navAbort = createNavAbort(externalSignal);\n\n // Capture the departing page's scroll position for scroll={false} preservation.\n const currentScrollY = deps.getScrollY();\n\n // Save the departing page's scroll position — use Navigation API entry\n // state when available, otherwise fall back to history.state.\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(currentScrollY);\n } else {\n deps.replaceState({ timber: true, scrollY: currentScrollY }, '', deps.getCurrentUrl());\n }\n\n // When Navigation API is active, initiate the navigation via\n // navigation.navigate() BEFORE the fetch. Unlike history.pushState()\n // which commits the URL synchronously (so Chrome sees it as \"done\"),\n // navigation.navigate() fires the navigate event before committing.\n // Our handler intercepts with a deferred promise, and Chrome shows\n // its native loading indicator until completeRouterNavigation()\n // resolves it in the finally block (same time as TopLoader clears).\n let effectiveSkipHistory = skipHistory;\n if (!skipHistory && deps.navigationNavigate) {\n deps.setRouterNavigating?.(true);\n deps.navigationNavigate(url, replace);\n deps.setRouterNavigating?.(false);\n effectiveSkipHistory = true;\n }\n\n setPending(true, url);\n\n try {\n const { headElements } = await renderViaTransition(url, () =>\n performNavigationFetch(url, {\n replace,\n signal: navAbort.signal,\n skipHistory: effectiveSkipHistory,\n })\n );\n\n // Update document.title and <meta> tags with the new page's metadata\n applyHead(headElements);\n\n // Notify nuqs adapter (and any other listeners) that navigation completed.\n window.dispatchEvent(new Event('timber:navigation-end'));\n\n // Scroll-to-top on forward navigation, or restore captured position\n // for scroll={false}. React's render() on the document root can reset\n // scroll during DOM reconciliation, so all scroll must be actively managed.\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n } catch (error) {\n // Version skew — server has been redeployed. Full page reload\n // so the browser fetches the new bundle. See TIM-446.\n if (error instanceof VersionSkewError) {\n setHardNavigating(true);\n window.location.reload();\n return new Promise(() => {}) as never;\n }\n // Server-side redirect during RSC fetch → soft router navigation.\n // The redirect navigate will push/replace its own URL.\n if (error instanceof RedirectError) {\n setPending(false);\n deps.completeRouterNavigation?.();\n await navigate(error.redirectUrl, { replace: true });\n return;\n }\n // Server 5xx error — hard-navigate so the server renders the\n // error page as HTML. See design/10-error-handling.md\n // §\"Error Page Rendering for Client Navigation\".\n //\n // Set hard-navigating flag BEFORE setting window.location.href:\n // 1. Prevents Navigation API from intercepting → infinite loop\n // 2. Causes NavigationRoot to throw unresolvedThenable → prevents\n // React from rendering children during page teardown (avoids\n // \"Rendered more hooks\" crashes). See TIM-626.\n if (error instanceof ServerErrorResponse) {\n setHardNavigating(true);\n window.location.href = error.url;\n return new Promise(() => {}) as never;\n }\n // Abort errors are not application errors — swallow silently.\n if (isAbortError(error)) return;\n throw error;\n } finally {\n // Clear the abort controller so we don't abort a completed navigation\n // when the next one starts. In dev mode, the RSC body stream stays\n // open after data arrives (React's Flight client waits for debug rows).\n // Aborting a \"completed\" navigation kills the open stream reader →\n // \"BodyStreamBuffer was aborted\". By clearing the controller here,\n // createNavAbort() becomes a no-op for completed navigations.\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n // Resolve the Navigation API deferred — clears the browser's native\n // loading state (tab spinner) at the same time as the TopLoader.\n deps.completeRouterNavigation?.();\n }\n }\n\n async function refresh(): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n const navAbort = createNavAbort();\n\n setPending(true, currentUrl);\n\n try {\n const { headElements } = await renderViaTransition(currentUrl, async () => {\n // No state tree sent — server renders the complete RSC payload\n const result = await fetchRscPayload(\n currentUrl,\n deps,\n undefined,\n undefined,\n navAbort.signal\n );\n // History push handled by renderViaTransition (stores merged payload)\n updateSegmentCache(result.segmentInfo);\n const navState = updateNavigationState(result.params, currentUrl);\n return { ...result, navState };\n });\n\n applyHead(headElements);\n } catch (error) {\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n deps.completeRouterNavigation?.();\n }\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal\n ): Promise<void> {\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip\n const navState = updateNavigationState(entry.params, url);\n renderPayload(entry.payload, navState);\n applyHead(entry.headElements);\n restoreScrollAfterPaint(scrollY);\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n const navAbort = createNavAbort(externalSignal);\n setPending(true, url);\n try {\n const { headElements } = await renderViaTransition(url, async () => {\n const stateTree = segmentCache.serializeStateTree();\n const result = await fetchRscPayload(url, deps, stateTree, undefined, navAbort.signal);\n updateSegmentCache(result.segmentInfo);\n const navState = updateNavigationState(result.params, url);\n // History push handled by renderViaTransition (stores merged payload)\n return { ...result, navState };\n });\n\n applyHead(headElements);\n restoreScrollAfterPaint(scrollY);\n } catch (error) {\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n }\n setPending(false);\n }\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n */\n function prefetch(url: string): void {\n // Don't prefetch if already cached\n if (prefetchCache.get(url) !== undefined) return;\n if (historyStack.has(url)) return;\n\n // Fire-and-forget fetch\n const stateTree = segmentCache.serializeStateTree();\n void fetchRscPayload(url, deps, stateTree).then(\n (result) => {\n result.decodePromise?.catch(() => {});\n prefetchCache.set(url, result);\n },\n () => {\n // Prefetch failure is non-fatal — navigation will fetch fresh\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n prefetch,\n applyRevalidation(element: unknown, headElements: HeadElement[] | null): void {\n // Render the piggybacked element tree from a server action response.\n // Updates the current history entry with the fresh payload and applies\n // head elements — same as refresh() but without a server fetch.\n // Revalidation payloads are already resolved (no Flight thenable),\n // so no segment merging is needed — just cache and render.\n const currentUrl = deps.getCurrentUrl();\n historyStack.push(currentUrl, {\n payload: element,\n headElements,\n });\n\n // Revalidation doesn't change params/pathname — preserve current state.\n // DO NOT call updateNavigationState(null, ...) here: that normalizes\n // params to {}, clearing dynamic route params on every action response.\n const navState = getNavigationState();\n renderPayload(element, navState);\n applyHead(headElements);\n },\n initSegmentCache: (segments: SegmentInfo[]) => updateSegmentCache(segments),\n segmentCache,\n prefetchCache,\n historyStack,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * On the client, reads from NavigationContext which is updated atomically\n * with the RSC tree render. This replaces the previous useSyncExternalStore\n * approach which read window.location.search directly — causing React to\n * detect external store tearing during transitions and fall back to\n * synchronous rendering (renderRootSync instead of renderRootConcurrent),\n * blocking the main thread and freezing animations.\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * During SSR, reads the request search params from the SSR ALS context\n * (populated by ssr-entry.ts) instead of window.location.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.js';\nimport { useNavigationContext } from './navigation-context.js';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.js';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n try {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- conditional on environment, not render path\n const navContext = useNavigationContext();\n if (navContext !== null) {\n return getSearchParams(navContext.search);\n }\n } catch {\n // No React dispatcher available (called outside a component).\n }\n\n // SSR path: read from ALS-backed SSR data context.\n const ssrData = getSsrData();\n if (ssrData) return new URLSearchParams(ssrData.searchParams);\n\n // Final fallback: window.location (tests, edge cases).\n if (typeof window !== 'undefined') return getSearchParams(window.location.search);\n return new URLSearchParams();\n}\n"],"mappings":";;;;;;;;;;;;;AAiDA,IAAa,eAAb,MAA0B;CACxB;CAEA,IAAI,SAA0C;EAC5C,IAAI,YAAY,OAAO,YAAY,KAAK,MAAM,SAC5C,OAAO,KAAK;CAGhB;CAEA,IAAI,SAAiB,MAAyB;EAC5C,IAAI,YAAY,OAAO,CAAC,KAAK,MAC3B,KAAK,OAAO;CAEhB;CAEA,QAAc;EACZ,KAAK,OAAO,KAAA;CACd;;;;;;;;;;;;;;CAeA,mBAAmB,iBAA0C;EAC3D,MAAM,WAAqB,CAAC;EAC5B,IAAI,KAAK,MACP,oBAAoB,KAAK,MAAM,UAAU,eAAe;EAE1D,OAAO,EAAE,SAA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AAW,cAAc;EAC3B,MAAM,SAAS,IAAI,gBAAgB,MAAM;EACzC,iBAAiB,QAAQ,MAAM;EAC/B,OAAO;CACT;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAmC;CACjD,IAAI;EAEF,MAAM,aAAa,qBAAqB;EACxC,IAAI,eAAe,MACjB,OAAO,gBAAgB,WAAW,MAAM;CAE5C,QAAQ,CAER;CAGA,MAAM,UAAU,WAAW;CAC3B,IAAI,SAAS,OAAO,IAAI,gBAAgB,QAAQ,YAAY;CAG5D,IAAI,OAAO,WAAW,aAAa,OAAO,gBAAgB,OAAO,SAAS,MAAM;CAChF,OAAO,IAAI,gBAAgB;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/client/router.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAoB,MAAM,iBAAiB,CAAC;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/client/router.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAoB,MAAM,iBAAiB,CAAC;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AAajC,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,MAAM,CAAC,EAAE,OAAO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AI,MAAM,GAAG,IAAI,CAAC;IAC/B,yCAAyC;IACzC,eAAe,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAClE,6DAA6D;IAC7D,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;;;OAIG;IACH,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;IAC9E;;;OAGG;IACH,gBAAgB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IAEhD,gEAAgE;IAChE,YAAY,EAAE,YAAY,CAAC;IAC3B,iEAAiE;IACjE,aAAa,EAAE,aAAa,CAAC;IAC7B,4CAA4C;IAC5C,YAAY,EAAE,YAAY,CAAC;CAC5B;AAcD;;;GAGG;AACH;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzF,wBAAgB,YAAY,CAAC,IAAI,EAAE,UAAU,GAAG,cAAc,CA0hB7D"}
|
|
@@ -89,7 +89,7 @@ export declare class RedirectError extends Error {
|
|
|
89
89
|
}
|
|
90
90
|
/**
|
|
91
91
|
* Thrown when the server signals a version skew (X-Timber-Reload header).
|
|
92
|
-
* Caught in navigate() to trigger a full page reload
|
|
92
|
+
* Caught in navigate() to trigger a full page reload.
|
|
93
93
|
* See TIM-446.
|
|
94
94
|
*/
|
|
95
95
|
export declare class VersionSkewError extends Error {
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.143",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
|
@@ -114,11 +114,6 @@
|
|
|
114
114
|
"publishConfig": {
|
|
115
115
|
"access": "public"
|
|
116
116
|
},
|
|
117
|
-
"scripts": {
|
|
118
|
-
"build": "vite build --config vite.lib.config.ts && tsc --emitDeclarationOnly --project tsconfig.json --outDir dist",
|
|
119
|
-
"typecheck": "tsgo --noEmit",
|
|
120
|
-
"prepublishOnly": "pnpm run build"
|
|
121
|
-
},
|
|
122
117
|
"dependencies": {
|
|
123
118
|
"@opentelemetry/api": "^1.9.1",
|
|
124
119
|
"@opentelemetry/context-async-hooks": "^2.7.1",
|
|
@@ -134,8 +129,9 @@
|
|
|
134
129
|
"@vitejs/plugin-react": "^6.0.0",
|
|
135
130
|
"@vitejs/plugin-rsc": ">=0.5.27",
|
|
136
131
|
"nuqs": "^2.0.0",
|
|
137
|
-
"react": "19.3.0-canary-
|
|
138
|
-
"react-dom": "19.3.0-canary-
|
|
132
|
+
"react": ">=19.3.0-canary-43bcbf80-20260603",
|
|
133
|
+
"react-dom": ">=19.3.0-canary-43bcbf80-20260603",
|
|
134
|
+
"react-server-dom-webpack": ">=19.3.0-canary-43bcbf80-20260603",
|
|
139
135
|
"vite": "^8.0.13",
|
|
140
136
|
"wrangler": "^4.0.0",
|
|
141
137
|
"zod": "^3.22.0 || ^4.0.0"
|
|
@@ -162,5 +158,9 @@
|
|
|
162
158
|
},
|
|
163
159
|
"engines": {
|
|
164
160
|
"node": ">=22.12.0"
|
|
161
|
+
},
|
|
162
|
+
"scripts": {
|
|
163
|
+
"build": "vite build --config vite.lib.config.ts && tsc --emitDeclarationOnly --project tsconfig.json --outDir dist",
|
|
164
|
+
"typecheck": "tsgo --noEmit"
|
|
165
165
|
}
|
|
166
166
|
}
|
package/src/cli.ts
CHANGED
|
File without changes
|
|
@@ -17,7 +17,6 @@
|
|
|
17
17
|
import { setServerCallback, encodeReply, createFromFetch } from '../../rsc-runtime/browser.js';
|
|
18
18
|
import { getRouter, getRouterOrNull } from '#client-internal';
|
|
19
19
|
import { setHardNavigating } from '../navigation-root.js';
|
|
20
|
-
import { isStaleClientReference, triggerStaleReload } from '../stale-reload.js';
|
|
21
20
|
import { getClientDeploymentId, DEPLOYMENT_ID_HEADER, RELOAD_HEADER } from '../rsc-fetch.js';
|
|
22
21
|
|
|
23
22
|
export function setupServerActions(): void {
|
|
@@ -59,17 +58,7 @@ export function setupServerActions(): void {
|
|
|
59
58
|
return res;
|
|
60
59
|
});
|
|
61
60
|
|
|
62
|
-
|
|
63
|
-
try {
|
|
64
|
-
decoded = await createFromFetch(response);
|
|
65
|
-
} catch (error) {
|
|
66
|
-
if (isStaleClientReference(error)) {
|
|
67
|
-
triggerStaleReload();
|
|
68
|
-
// Return a never-resolving promise to prevent further processing
|
|
69
|
-
return new Promise(() => {});
|
|
70
|
-
}
|
|
71
|
-
throw error;
|
|
72
|
-
}
|
|
61
|
+
const decoded = await createFromFetch(response);
|
|
73
62
|
|
|
74
63
|
// Handle redirect — server encoded the redirect location in the RSC stream
|
|
75
64
|
// instead of returning HTTP 302. Perform a client-side SPA navigation.
|
|
@@ -21,8 +21,7 @@
|
|
|
21
21
|
* 5. hydrateApp() — hydrateRoot or deferred createRoot
|
|
22
22
|
* 6. setupPostHydration() — history stack, popstate, scroll
|
|
23
23
|
* 7. setupHmr() — dev-only HMR wiring
|
|
24
|
-
* 8.
|
|
25
|
-
* 9. timber-ready signal — E2E test readiness indicator
|
|
24
|
+
* 8. timber-ready signal — E2E test readiness indicator
|
|
26
25
|
*
|
|
27
26
|
* Design docs: 18-build-system.md §"Entry Files", 19-client-navigation.md
|
|
28
27
|
*/
|
|
@@ -42,12 +41,6 @@ import { setLinkCodecs } from '../../params/codec-registry.js';
|
|
|
42
41
|
setLinkCodecs(schemaCodecs);
|
|
43
42
|
|
|
44
43
|
import { setClientDeploymentId } from '../rsc-fetch.js';
|
|
45
|
-
import {
|
|
46
|
-
isStaleClientReference,
|
|
47
|
-
isChunkLoadError,
|
|
48
|
-
triggerStaleReload,
|
|
49
|
-
clearStaleReloadFlag,
|
|
50
|
-
} from '../stale-reload.js';
|
|
51
44
|
|
|
52
45
|
import { setupServerActions } from './action-dispatch.js';
|
|
53
46
|
import { createRscPayloadStream } from './rsc-stream.js';
|
|
@@ -104,40 +97,7 @@ function bootstrap(runtimeConfig: typeof config): void {
|
|
|
104
97
|
|
|
105
98
|
bootstrap(config);
|
|
106
99
|
|
|
107
|
-
// ─── 8.
|
|
108
|
-
|
|
109
|
-
// Clear the stale reload flag on successful bootstrap. If the page
|
|
110
|
-
// loaded and bootstrapped without hitting a stale reference error,
|
|
111
|
-
// the loop guard should reset so the next stale error gets a fresh
|
|
112
|
-
// reload attempt.
|
|
113
|
-
clearStaleReloadFlag();
|
|
114
|
-
|
|
115
|
-
// Global error handler for stale client reference errors during hydration.
|
|
116
|
-
// The initial RSC payload is decoded lazily by React via createFromReadableStream.
|
|
117
|
-
// If the payload references a module ID from a newer deployment, the error
|
|
118
|
-
// surfaces as an unhandled rejection during React's render/hydration cycle.
|
|
119
|
-
// This handler catches those errors and triggers a full page reload.
|
|
120
|
-
//
|
|
121
|
-
// Also catches chunk load failures (dynamic import of missing assets after
|
|
122
|
-
// a deployment) — these surface as "Failed to fetch dynamically imported module"
|
|
123
|
-
// or "Loading chunk <name> failed" errors. See TIM-446.
|
|
124
|
-
window.addEventListener('unhandledrejection', (event) => {
|
|
125
|
-
if (isStaleClientReference(event.reason) || isChunkLoadError(event.reason)) {
|
|
126
|
-
event.preventDefault();
|
|
127
|
-
triggerStaleReload();
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
// Also catch synchronous errors from chunk loads (some browsers throw
|
|
132
|
-
// TypeError synchronously instead of via unhandled rejection).
|
|
133
|
-
window.addEventListener('error', (event) => {
|
|
134
|
-
if (isChunkLoadError(event.error)) {
|
|
135
|
-
event.preventDefault();
|
|
136
|
-
triggerStaleReload();
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
// ─── 9. Ready Signal ────────────────────────────────────────────
|
|
100
|
+
// ─── 8. Ready Signal ────────────────────────────────────────────
|
|
141
101
|
|
|
142
102
|
// Signal that the client runtime has been initialized.
|
|
143
103
|
// Used by E2E tests to wait for hydration before interacting.
|
|
@@ -17,7 +17,6 @@ import { TimberNuqsAdapter } from '../nuqs-adapter.js';
|
|
|
17
17
|
import { NavigationProvider } from '../navigation-context.js';
|
|
18
18
|
import { transitionRender, navigateTransition } from '../navigation-root.js';
|
|
19
19
|
import { SegmentUpdateContext, EMPTY_SEGMENT_UPDATES } from '../segment-update-context.js';
|
|
20
|
-
import { isStaleClientReference, triggerStaleReload } from '../stale-reload.js';
|
|
21
20
|
import {
|
|
22
21
|
hasNavigationApi,
|
|
23
22
|
setupNavigationApi,
|
|
@@ -79,30 +78,8 @@ export function createTimberRouter(options?: RouterInitOptions): RouterInitResul
|
|
|
79
78
|
getCurrentUrl: () => window.location.pathname + window.location.search,
|
|
80
79
|
getScrollY,
|
|
81
80
|
|
|
82
|
-
// Decode RSC Flight stream using createFromFetch.
|
|
83
|
-
// createFromFetch takes a Promise<Response> and progressively
|
|
84
|
-
// parses the RSC stream as chunks arrive.
|
|
85
|
-
//
|
|
86
|
-
// Wrapped with stale client reference detection: if the server
|
|
87
|
-
// has been redeployed with new bundles, the RSC payload may
|
|
88
|
-
// reference module IDs that don't exist in the old client bundle.
|
|
89
|
-
// We catch "Could not find the module" errors and trigger a full
|
|
90
|
-
// page reload so the browser fetches the new bundle.
|
|
91
|
-
// Pass the fetch promise directly to createFromFetch for streaming.
|
|
92
|
-
// React progressively renders chunks via Suspense as they arrive.
|
|
93
|
-
// The transition stays open via decodePromise (awaited inside
|
|
94
|
-
// startTransition) so useOptimistic pending state persists for
|
|
95
|
-
// the full stream duration.
|
|
96
81
|
decodeRsc: (fetchPromise: Promise<Response>) => {
|
|
97
|
-
|
|
98
|
-
return createFromFetch(fetchPromise);
|
|
99
|
-
} catch (error) {
|
|
100
|
-
if (isStaleClientReference(error)) {
|
|
101
|
-
triggerStaleReload();
|
|
102
|
-
return new Promise(() => {});
|
|
103
|
-
}
|
|
104
|
-
throw error;
|
|
105
|
-
}
|
|
82
|
+
return createFromFetch(fetchPromise);
|
|
106
83
|
},
|
|
107
84
|
|
|
108
85
|
// Render decoded RSC tree via NavigationRoot's state-based mechanism.
|
package/src/client/router.ts
CHANGED
|
@@ -19,7 +19,6 @@ import {
|
|
|
19
19
|
VersionSkewError,
|
|
20
20
|
} from './rsc-fetch.js';
|
|
21
21
|
import { setHardNavigating } from './navigation-root.js';
|
|
22
|
-
import { isStaleClientReference, triggerStaleReload } from './stale-reload.js';
|
|
23
22
|
import type { FetchResult } from './rsc-fetch.js';
|
|
24
23
|
|
|
25
24
|
// ─── Types ───────────────────────────────────────────────────────
|
|
@@ -565,17 +564,11 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
565
564
|
// scroll during DOM reconciliation, so all scroll must be actively managed.
|
|
566
565
|
restoreScrollAfterPaint(scroll ? 0 : currentScrollY);
|
|
567
566
|
} catch (error) {
|
|
568
|
-
// Version skew — server has been redeployed.
|
|
567
|
+
// Version skew — server has been redeployed. Full page reload
|
|
569
568
|
// so the browser fetches the new bundle. See TIM-446.
|
|
570
|
-
// Set hard-navigating flag to prevent Navigation API interception
|
|
571
|
-
// and React from rendering during page teardown. See TIM-626.
|
|
572
569
|
if (error instanceof VersionSkewError) {
|
|
573
570
|
setHardNavigating(true);
|
|
574
|
-
|
|
575
|
-
// and keep the reload logic centralized with its loop guard.
|
|
576
|
-
const { triggerStaleReload } = await import('./stale-reload.js');
|
|
577
|
-
triggerStaleReload();
|
|
578
|
-
// Return a never-resolving promise — page is reloading.
|
|
571
|
+
window.location.reload();
|
|
579
572
|
return new Promise(() => {}) as never;
|
|
580
573
|
}
|
|
581
574
|
// Server-side redirect during RSC fetch → soft router navigation.
|
|
@@ -600,13 +593,6 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
600
593
|
window.location.href = error.url;
|
|
601
594
|
return new Promise(() => {}) as never;
|
|
602
595
|
}
|
|
603
|
-
// Stale client reference from streaming RSC decode — the server
|
|
604
|
-
// was redeployed with new bundles. Same recovery as VersionSkewError.
|
|
605
|
-
if (isStaleClientReference(error)) {
|
|
606
|
-
setHardNavigating(true);
|
|
607
|
-
triggerStaleReload();
|
|
608
|
-
return new Promise(() => {}) as never;
|
|
609
|
-
}
|
|
610
596
|
// Abort errors are not application errors — swallow silently.
|
|
611
597
|
if (isAbortError(error)) return;
|
|
612
598
|
throw error;
|
|
@@ -651,13 +637,6 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
651
637
|
|
|
652
638
|
applyHead(headElements);
|
|
653
639
|
} catch (error) {
|
|
654
|
-
if (isStaleClientReference(error)) {
|
|
655
|
-
setHardNavigating(true);
|
|
656
|
-
triggerStaleReload();
|
|
657
|
-
return new Promise(() => {}) as never;
|
|
658
|
-
}
|
|
659
|
-
// Stale transition (superseded by a newer navigation) or aborted
|
|
660
|
-
// fetch — silently ignore. See TIM-629.
|
|
661
640
|
if (isAbortError(error)) return;
|
|
662
641
|
throw error;
|
|
663
642
|
} finally {
|
|
@@ -705,13 +684,6 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
705
684
|
applyHead(headElements);
|
|
706
685
|
restoreScrollAfterPaint(scrollY);
|
|
707
686
|
} catch (error) {
|
|
708
|
-
if (isStaleClientReference(error)) {
|
|
709
|
-
setHardNavigating(true);
|
|
710
|
-
triggerStaleReload();
|
|
711
|
-
return new Promise(() => {}) as never;
|
|
712
|
-
}
|
|
713
|
-
// Stale transition (superseded by a newer navigation) or aborted
|
|
714
|
-
// fetch — silently ignore. See TIM-629.
|
|
715
687
|
if (isAbortError(error)) return;
|
|
716
688
|
throw error;
|
|
717
689
|
} finally {
|
package/src/client/rsc-fetch.ts
CHANGED
|
@@ -230,7 +230,7 @@ export class RedirectError extends Error {
|
|
|
230
230
|
|
|
231
231
|
/**
|
|
232
232
|
* Thrown when the server signals a version skew (X-Timber-Reload header).
|
|
233
|
-
* Caught in navigate() to trigger a full page reload
|
|
233
|
+
* Caught in navigate() to trigger a full page reload.
|
|
234
234
|
* See TIM-446.
|
|
235
235
|
*/
|
|
236
236
|
export class VersionSkewError extends Error {
|
|
@@ -345,7 +345,7 @@ export async function fetchRscPayload(
|
|
|
345
345
|
const wrappedPromise = fetchPromise.then((response) => {
|
|
346
346
|
// Version skew detection (TIM-446): if the server signals a reload,
|
|
347
347
|
// throw VersionSkewError so the caller (router navigate) can trigger
|
|
348
|
-
// a full page reload
|
|
348
|
+
// a full page reload.
|
|
349
349
|
if (checkReloadSignal(response)) {
|
|
350
350
|
throw new VersionSkewError();
|
|
351
351
|
}
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Stale Client Reference Reload
|
|
3
|
-
*
|
|
4
|
-
* When a new deployment ships updated bundles, clients running stale
|
|
5
|
-
* JavaScript may encounter "Could not find the module" errors during
|
|
6
|
-
* RSC Flight stream decoding. This happens because the RSC payload
|
|
7
|
-
* references module IDs from the new bundle that don't exist in the
|
|
8
|
-
* old client bundle.
|
|
9
|
-
*
|
|
10
|
-
* This module detects these specific errors and triggers a full page
|
|
11
|
-
* reload so the browser fetches the new bundle. A sessionStorage flag
|
|
12
|
-
* guards against infinite reload loops.
|
|
13
|
-
*
|
|
14
|
-
* See: LOCAL-332
|
|
15
|
-
*/
|
|
16
|
-
/**
|
|
17
|
-
* Check if an error is a stale client reference error from React's
|
|
18
|
-
* Flight client. These errors have the message pattern:
|
|
19
|
-
* "Could not find the module \"<id>\""
|
|
20
|
-
*
|
|
21
|
-
* This is thrown by react-server-dom-webpack's client when the RSC
|
|
22
|
-
* payload references a module ID that doesn't exist in the client's
|
|
23
|
-
* module map — typically because the server has been redeployed with
|
|
24
|
-
* new bundle hashes while the client is still running old JavaScript.
|
|
25
|
-
*/
|
|
26
|
-
export declare function isStaleClientReference(error: unknown): boolean;
|
|
27
|
-
/**
|
|
28
|
-
* Check if an error is a chunk load failure from a dynamic import.
|
|
29
|
-
*
|
|
30
|
-
* After a deployment, old chunk filenames no longer exist. When the client
|
|
31
|
-
* tries to dynamically import a chunk that's been replaced, the browser
|
|
32
|
-
* throws one of these errors:
|
|
33
|
-
*
|
|
34
|
-
* - Chromium: "Failed to fetch dynamically imported module: <url>"
|
|
35
|
-
* - Firefox: "error loading dynamically imported module: <url>"
|
|
36
|
-
* - Safari: "Importing a module script failed."
|
|
37
|
-
* - Vite/Rollup: "Unable to preload CSS for <url>"
|
|
38
|
-
*
|
|
39
|
-
* See TIM-446
|
|
40
|
-
*/
|
|
41
|
-
export declare function isChunkLoadError(error: unknown): boolean;
|
|
42
|
-
/**
|
|
43
|
-
* Trigger a full page reload to pick up new bundles.
|
|
44
|
-
*
|
|
45
|
-
* Sets a sessionStorage flag before reloading. If the flag is already
|
|
46
|
-
* set (meaning we already reloaded once for this reason), we don't
|
|
47
|
-
* reload again — this prevents infinite reload loops if the error
|
|
48
|
-
* persists after reload (e.g., a genuine bug rather than a stale bundle).
|
|
49
|
-
*
|
|
50
|
-
* @returns true if a reload was triggered, false if suppressed (loop guard)
|
|
51
|
-
*/
|
|
52
|
-
export declare function triggerStaleReload(): boolean;
|
|
53
|
-
/**
|
|
54
|
-
* Clear the stale reload flag. Called on successful bootstrap to reset
|
|
55
|
-
* the loop guard — if the page loaded successfully, the next stale
|
|
56
|
-
* reference error should trigger a fresh reload attempt.
|
|
57
|
-
*/
|
|
58
|
-
export declare function clearStaleReloadFlag(): void;
|
|
59
|
-
//# sourceMappingURL=stale-reload.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stale-reload.d.ts","sourceRoot":"","sources":["../../src/client/stale-reload.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAcH;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAI9D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAYxD;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,IAAI,OAAO,CAqD5C;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAa3C"}
|
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Stale Client Reference Reload
|
|
3
|
-
*
|
|
4
|
-
* When a new deployment ships updated bundles, clients running stale
|
|
5
|
-
* JavaScript may encounter "Could not find the module" errors during
|
|
6
|
-
* RSC Flight stream decoding. This happens because the RSC payload
|
|
7
|
-
* references module IDs from the new bundle that don't exist in the
|
|
8
|
-
* old client bundle.
|
|
9
|
-
*
|
|
10
|
-
* This module detects these specific errors and triggers a full page
|
|
11
|
-
* reload so the browser fetches the new bundle. A sessionStorage flag
|
|
12
|
-
* guards against infinite reload loops.
|
|
13
|
-
*
|
|
14
|
-
* See: LOCAL-332
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
const RELOAD_FLAG_KEY = '__timber_stale_reload';
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* In-memory fallback counter for environments where sessionStorage is
|
|
21
|
-
* unavailable (private browsing, storage full, extension interference).
|
|
22
|
-
* Incremented each time triggerStaleReload() falls into the catch path.
|
|
23
|
-
* If the counter exceeds 0 on a subsequent call, the reload is suppressed
|
|
24
|
-
* to prevent an infinite loop. Resets naturally on page load (module
|
|
25
|
-
* re-evaluates) and can be manually reset via clearStaleReloadFlag().
|
|
26
|
-
*/
|
|
27
|
-
let memoryReloadCount = 0;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Check if an error is a stale client reference error from React's
|
|
31
|
-
* Flight client. These errors have the message pattern:
|
|
32
|
-
* "Could not find the module \"<id>\""
|
|
33
|
-
*
|
|
34
|
-
* This is thrown by react-server-dom-webpack's client when the RSC
|
|
35
|
-
* payload references a module ID that doesn't exist in the client's
|
|
36
|
-
* module map — typically because the server has been redeployed with
|
|
37
|
-
* new bundle hashes while the client is still running old JavaScript.
|
|
38
|
-
*/
|
|
39
|
-
export function isStaleClientReference(error: unknown): boolean {
|
|
40
|
-
if (!(error instanceof Error)) return false;
|
|
41
|
-
const msg = error.message;
|
|
42
|
-
return msg.includes('Could not find the module') || msg.includes('client reference not found');
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Check if an error is a chunk load failure from a dynamic import.
|
|
47
|
-
*
|
|
48
|
-
* After a deployment, old chunk filenames no longer exist. When the client
|
|
49
|
-
* tries to dynamically import a chunk that's been replaced, the browser
|
|
50
|
-
* throws one of these errors:
|
|
51
|
-
*
|
|
52
|
-
* - Chromium: "Failed to fetch dynamically imported module: <url>"
|
|
53
|
-
* - Firefox: "error loading dynamically imported module: <url>"
|
|
54
|
-
* - Safari: "Importing a module script failed."
|
|
55
|
-
* - Vite/Rollup: "Unable to preload CSS for <url>"
|
|
56
|
-
*
|
|
57
|
-
* See TIM-446
|
|
58
|
-
*/
|
|
59
|
-
export function isChunkLoadError(error: unknown): boolean {
|
|
60
|
-
if (!(error instanceof Error)) return false;
|
|
61
|
-
const msg = error.message.toLowerCase();
|
|
62
|
-
return (
|
|
63
|
-
msg.includes('failed to fetch dynamically imported module') ||
|
|
64
|
-
msg.includes('error loading dynamically imported module') ||
|
|
65
|
-
msg.includes('importing a module script failed') ||
|
|
66
|
-
msg.includes('unable to preload css') ||
|
|
67
|
-
// Webpack-style chunk load errors (unlikely in Vite but defensive)
|
|
68
|
-
msg.includes('loading chunk') ||
|
|
69
|
-
msg.includes('loading css chunk')
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Trigger a full page reload to pick up new bundles.
|
|
75
|
-
*
|
|
76
|
-
* Sets a sessionStorage flag before reloading. If the flag is already
|
|
77
|
-
* set (meaning we already reloaded once for this reason), we don't
|
|
78
|
-
* reload again — this prevents infinite reload loops if the error
|
|
79
|
-
* persists after reload (e.g., a genuine bug rather than a stale bundle).
|
|
80
|
-
*
|
|
81
|
-
* @returns true if a reload was triggered, false if suppressed (loop guard)
|
|
82
|
-
*/
|
|
83
|
-
export function triggerStaleReload(): boolean {
|
|
84
|
-
try {
|
|
85
|
-
// Check if we already reloaded — prevent infinite loop
|
|
86
|
-
if (sessionStorage.getItem(RELOAD_FLAG_KEY)) {
|
|
87
|
-
console.warn(
|
|
88
|
-
'[timber] Stale client reference detected again after reload. ' +
|
|
89
|
-
'Not reloading to prevent infinite loop. ' +
|
|
90
|
-
'This may indicate a deployment issue — try a hard refresh.'
|
|
91
|
-
);
|
|
92
|
-
return false;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Set the flag before reloading
|
|
96
|
-
sessionStorage.setItem(RELOAD_FLAG_KEY, '1');
|
|
97
|
-
|
|
98
|
-
console.warn(
|
|
99
|
-
'[timber] Stale client reference detected — the server has been ' +
|
|
100
|
-
'redeployed with new bundles. Reloading to pick up the new version.'
|
|
101
|
-
);
|
|
102
|
-
|
|
103
|
-
window.location.reload();
|
|
104
|
-
return true;
|
|
105
|
-
} catch {
|
|
106
|
-
// sessionStorage unavailable (private browsing, storage full, etc.)
|
|
107
|
-
// Use document.cookie as a reload-persistent fallback loop guard.
|
|
108
|
-
// Module-level memoryReloadCount resets on every reload, so it can't
|
|
109
|
-
// detect cross-reload loops. Cookies persist across reloads and are
|
|
110
|
-
// available even when sessionStorage is blocked (TIM-576).
|
|
111
|
-
const cookieFlag = document.cookie.includes(RELOAD_FLAG_KEY + '=1');
|
|
112
|
-
if (cookieFlag || memoryReloadCount > 0) {
|
|
113
|
-
console.warn(
|
|
114
|
-
'[timber] Stale client reference detected again after reload. ' +
|
|
115
|
-
'Not reloading to prevent infinite loop. ' +
|
|
116
|
-
'This may indicate a deployment issue — try a hard refresh.'
|
|
117
|
-
);
|
|
118
|
-
return false;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
memoryReloadCount++;
|
|
122
|
-
// Set a short-lived cookie (60s) as the persistent loop guard.
|
|
123
|
-
// It auto-expires so it won't block future legitimate reloads.
|
|
124
|
-
try {
|
|
125
|
-
document.cookie = `${RELOAD_FLAG_KEY}=1; max-age=60; path=/; SameSite=Lax`;
|
|
126
|
-
} catch {
|
|
127
|
-
// Cookie API unavailable — proceed anyway, memoryReloadCount guards same-page loops
|
|
128
|
-
}
|
|
129
|
-
console.warn(
|
|
130
|
-
'[timber] Stale client reference detected — the server has been ' +
|
|
131
|
-
'redeployed with new bundles. Reloading to pick up the new version.'
|
|
132
|
-
);
|
|
133
|
-
window.location.reload();
|
|
134
|
-
return true;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Clear the stale reload flag. Called on successful bootstrap to reset
|
|
140
|
-
* the loop guard — if the page loaded successfully, the next stale
|
|
141
|
-
* reference error should trigger a fresh reload attempt.
|
|
142
|
-
*/
|
|
143
|
-
export function clearStaleReloadFlag(): void {
|
|
144
|
-
memoryReloadCount = 0;
|
|
145
|
-
try {
|
|
146
|
-
sessionStorage.removeItem(RELOAD_FLAG_KEY);
|
|
147
|
-
} catch {
|
|
148
|
-
// sessionStorage unavailable — nothing to clear
|
|
149
|
-
}
|
|
150
|
-
// Also clear the cookie fallback
|
|
151
|
-
try {
|
|
152
|
-
document.cookie = `${RELOAD_FLAG_KEY}=; max-age=0; path=/; SameSite=Lax`;
|
|
153
|
-
} catch {
|
|
154
|
-
// Cookie API unavailable
|
|
155
|
-
}
|
|
156
|
-
}
|