@timber-js/app 0.2.0-alpha.171 → 0.2.0-alpha.173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/_chunks/{actions-O_LsyCE4.js → actions-pN8r5Vnh.js} +3 -3
  2. package/dist/_chunks/{actions-O_LsyCE4.js.map → actions-pN8r5Vnh.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-B-lhk9p4.js → cache-api-2hT5kfsr.js} +2 -2
  4. package/dist/_chunks/{cache-api-B-lhk9p4.js.map → cache-api-2hT5kfsr.js.map} +1 -1
  5. package/dist/_chunks/{canonicalize-Du3o_ptW.js → canonicalize-DQHyFClh.js} +2 -1
  6. package/dist/_chunks/canonicalize-DQHyFClh.js.map +1 -0
  7. package/dist/_chunks/{cli-schema-sync-B5FDplGI.js → cli-schema-sync-DvdvFwwE.js} +3 -3
  8. package/dist/_chunks/{cli-schema-sync-B5FDplGI.js.map → cli-schema-sync-DvdvFwwE.js.map} +1 -1
  9. package/dist/_chunks/{logger-AWfuX-KJ.js → logger-kUT0QH0K.js} +23 -1
  10. package/dist/_chunks/logger-kUT0QH0K.js.map +1 -0
  11. package/dist/_chunks/{walkers-DCoE-LJf.js → walkers-Bv63zfAC.js} +2 -2
  12. package/dist/_chunks/{walkers-DCoE-LJf.js.map → walkers-Bv63zfAC.js.map} +1 -1
  13. package/dist/cache/index.js +1 -1
  14. package/dist/cli.d.ts +3 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +9 -5
  17. package/dist/cli.js.map +1 -1
  18. package/dist/client/internal.js +40 -6
  19. package/dist/client/internal.js.map +1 -1
  20. package/dist/client/rsc-fetch.d.ts +1 -1
  21. package/dist/client/segment-cache.d.ts +20 -3
  22. package/dist/client/segment-cache.d.ts.map +1 -1
  23. package/dist/client/segment-outlet.d.ts +10 -2
  24. package/dist/client/segment-outlet.d.ts.map +1 -1
  25. package/dist/client/slot-context.d.ts +10 -8
  26. package/dist/client/slot-context.d.ts.map +1 -1
  27. package/dist/client/slot-provider.d.ts +5 -0
  28. package/dist/client/slot-provider.d.ts.map +1 -1
  29. package/dist/index.js +5 -5
  30. package/dist/routing/index.js +2 -2
  31. package/dist/server/access-gate.d.ts.map +1 -1
  32. package/dist/server/als-registry.d.ts +26 -0
  33. package/dist/server/als-registry.d.ts.map +1 -1
  34. package/dist/server/cookie-context.d.ts.map +1 -1
  35. package/dist/server/index.js +2 -2
  36. package/dist/server/internal.js +1614 -1667
  37. package/dist/server/internal.js.map +1 -1
  38. package/dist/server/metadata-routes.d.ts +13 -0
  39. package/dist/server/metadata-routes.d.ts.map +1 -1
  40. package/dist/server/metadata.d.ts +8 -0
  41. package/dist/server/metadata.d.ts.map +1 -1
  42. package/dist/server/prebuilt/slots.d.ts +33 -8
  43. package/dist/server/prebuilt/slots.d.ts.map +1 -1
  44. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  45. package/dist/server/request-context.d.ts +15 -0
  46. package/dist/server/request-context.d.ts.map +1 -1
  47. package/dist/server/route-element-builder.d.ts +9 -11
  48. package/dist/server/route-element-builder.d.ts.map +1 -1
  49. package/dist/server/rsc-entry/helpers.d.ts +18 -10
  50. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  51. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  52. package/dist/server/rsc-entry/rsc-payload.d.ts +2 -1
  53. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  54. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -0
  55. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  56. package/dist/server/slot-resolver.d.ts +46 -1
  57. package/dist/server/slot-resolver.d.ts.map +1 -1
  58. package/dist/server/state-tree-diff.d.ts +36 -3
  59. package/dist/server/state-tree-diff.d.ts.map +1 -1
  60. package/dist/server/tree-builder.d.ts +7 -0
  61. package/dist/server/tree-builder.d.ts.map +1 -1
  62. package/package.json +1 -1
  63. package/src/cli.ts +15 -5
  64. package/src/client/rsc-fetch.ts +1 -1
  65. package/src/client/segment-cache.ts +83 -10
  66. package/src/client/segment-outlet.tsx +24 -2
  67. package/src/client/slot-context.ts +10 -8
  68. package/src/client/slot-provider.tsx +9 -2
  69. package/src/server/access-gate.tsx +28 -1
  70. package/src/server/als-registry.ts +44 -0
  71. package/src/server/cookie-context.ts +7 -1
  72. package/src/server/deny-renderer.ts +1 -1
  73. package/src/server/metadata-routes.ts +95 -0
  74. package/src/server/metadata.ts +21 -0
  75. package/src/server/prebuilt/slots.ts +39 -16
  76. package/src/server/prebuilt-builder.ts +6 -5
  77. package/src/server/prebuilt-runtime.ts +11 -11
  78. package/src/server/request-context.ts +53 -1
  79. package/src/server/route-element-builder.ts +72 -144
  80. package/src/server/rsc-entry/helpers.ts +68 -14
  81. package/src/server/rsc-entry/render-route.ts +11 -3
  82. package/src/server/rsc-entry/rsc-payload.ts +16 -3
  83. package/src/server/rsc-entry/ssr-renderer.ts +3 -1
  84. package/src/server/slot-resolver.ts +321 -12
  85. package/src/server/state-tree-diff.ts +104 -8
  86. package/src/server/tree-builder.ts +10 -0
  87. package/dist/_chunks/canonicalize-Du3o_ptW.js.map +0 -1
  88. package/dist/_chunks/logger-AWfuX-KJ.js.map +0 -1
  89. package/dist/client/child-segment-context.d.ts +0 -22
  90. package/dist/client/child-segment-context.d.ts.map +0 -1
  91. package/dist/client/child-segment-outlet.d.ts +0 -18
  92. package/dist/client/child-segment-outlet.d.ts.map +0 -1
  93. package/dist/client/child-segment-provider.d.ts +0 -21
  94. package/dist/client/child-segment-provider.d.ts.map +0 -1
  95. package/src/client/child-segment-context.ts +0 -40
  96. package/src/client/child-segment-outlet.tsx +0 -25
  97. package/src/client/child-segment-provider.tsx +0 -27
@@ -37,15 +37,28 @@ var SegmentCache = class {
37
37
  */
38
38
  serializeStateTree(mergeableFilter) {
39
39
  const segments = [];
40
- if (this.root) collectSyncSegments(this.root, segments, mergeableFilter);
41
- return { segments };
40
+ const slots = [];
41
+ if (this.root) {
42
+ collectSyncSegments(this.root, segments, mergeableFilter);
43
+ collectSyncSlots(this.root, slots);
44
+ }
45
+ const tree = { segments };
46
+ if (slots.length > 0) tree.slots = slots;
47
+ return tree;
42
48
  }
43
49
  };
44
50
  /** Recursively collect sync segment paths from the tree */
45
51
  function collectSyncSegments(node, out, mergeableFilter) {
46
- if (!node.isAsync && (!mergeableFilter || mergeableFilter.has(node.segment))) out.push(node.segment);
52
+ if (!node.isRequestDependent && (!mergeableFilter || mergeableFilter.has(node.segment))) out.push(node.segment);
47
53
  for (const child of node.children.values()) collectSyncSegments(child, out, mergeableFilter);
48
54
  }
55
+ /** Recursively collect cacheable slot paths from the tree */
56
+ function collectSyncSlots(node, out) {
57
+ if (node.slots) {
58
+ for (const slot of node.slots.values()) if (!slot.isRequestDependent && !slot.denied) out.push(slot.segment);
59
+ }
60
+ for (const child of node.children.values()) collectSyncSlots(child, out);
61
+ }
49
62
  /**
50
63
  * Build a SegmentNode tree from flat segment metadata.
51
64
  *
@@ -59,20 +72,41 @@ function collectSyncSegments(node, out, mergeableFilter) {
59
72
  */
60
73
  function buildSegmentTree(segments) {
61
74
  if (segments.length === 0) return void 0;
75
+ const segmentEntries = [];
76
+ const slotEntries = [];
77
+ for (const info of segments) if (info.slot) slotEntries.push(info);
78
+ else segmentEntries.push(info);
62
79
  let root;
63
80
  let parent;
64
- for (const info of segments) {
81
+ const nodeById = /* @__PURE__ */ new Map();
82
+ for (const info of segmentEntries) {
65
83
  const id = info.segmentId ?? info.path;
66
84
  const node = {
67
85
  segment: id,
68
86
  payload: null,
69
- isAsync: info.isAsync,
87
+ isRequestDependent: info.isRequestDependent,
70
88
  children: /* @__PURE__ */ new Map()
71
89
  };
90
+ nodeById.set(id, node);
72
91
  if (!root) root = node;
73
92
  if (parent) parent.children.set(id, node);
74
93
  parent = node;
75
94
  }
95
+ for (const slotInfo of slotEntries) {
96
+ const parentId = slotInfo.parentSegment;
97
+ const parentNode = parentId ? nodeById.get(parentId) : root;
98
+ if (!parentNode) continue;
99
+ const slotId = slotInfo.segmentId ?? slotInfo.path;
100
+ const slotNode = {
101
+ segment: slotId,
102
+ payload: null,
103
+ isRequestDependent: slotInfo.isRequestDependent,
104
+ children: /* @__PURE__ */ new Map(),
105
+ denied: slotInfo.denied
106
+ };
107
+ if (!parentNode.slots) parentNode.slots = /* @__PURE__ */ new Map();
108
+ parentNode.slots.set(slotId, slotNode);
109
+ }
76
110
  return root;
77
111
  }
78
112
  /**
@@ -199,7 +233,7 @@ function warnMalformedHeader(headerName, raw) {
199
233
  * Extract segment metadata from the X-Timber-Segments response header.
200
234
  * Returns null if the header is missing or malformed.
201
235
  *
202
- * Format: JSON array of {path, isAsync} objects describing the rendered
236
+ * Format: JSON array of {path, isRequestDependent} objects describing the rendered
203
237
  * segment chain from root to leaf. Used to populate the client-side
204
238
  * segment cache for state tree diffing on subsequent navigations.
205
239
  */
@@ -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/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\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\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 // All entries are layout segments — the server filters out layoutless\n // segments (including the page leaf) in buildSegmentInfo. Cache every\n // entry; pages are never sent.\n let root: SegmentNode | undefined;\n let parent: SegmentNode | undefined;\n\n for (const info of segments) {\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 { SegmentInfo } from './segment-cache';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * Route params for this page (for useSegmentParams). Every entry that can\n * be replayed must carry them — the initial SSR entry gets them from the\n * server-embedded __timber_params, navigation entries from X-Timber-Params,\n * and revalidation overwrites preserve the current state (TIM-1037).\n */\n params?: Record<string, string | string[]> | null;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next forward navigation computes a\n * correct state tree. Without this, the segment cache retains the\n * *previous* page's segments after back-button, causing the server to\n * skip segments that aren't mounted — and the partial payload targets\n * a non-existent outlet.\n */\n segmentInfo?: SegmentInfo[] | 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 * Entries are keyed by pathname + search. Used with the History API\n * fallback and the Navigation API.\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\n push(url: string, entry: HistoryEntry): void {\n this.entries.set(url, entry);\n }\n\n get(url: string): HistoryEntry | undefined {\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 { RouterDeps } from './router';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Result of fetching an RSC payload — includes 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 /** 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 *\n * Strips any #fragment before appending — fragments are client-only and\n * fetch() discards them, so _rsc would land inside the hash and be lost.\n */\nfunction appendRscParam(url: string): string {\n const hashIndex = url.indexOf('#');\n const urlWithoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);\n const separator = urlWithoutHash.includes('?') ? '&' : '?';\n return `${urlWithoutHash}${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 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 */\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 segment metadata 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 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 // Metadata (<title>/<meta>/<link>) now rides the RSC Flight payload\n // as React elements — React 19 Float handles them. See TIM-1151.\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 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 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 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 { 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, supersedeNavigationTransitions } 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 /**\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 /**\n * Scroll the element matching a URL #fragment into view. Returns true\n * when a matching element was found and scrolled. When absent or false,\n * the router falls back to scroll-to-top on forward navigation — same\n * as a full page load with an unknown fragment landing at the top.\n */\n scrollToHash?: (hash: string) => boolean;\n\n /**\n * Whether the client segment cache is enabled. When false (the default),\n * the router does not send X-Timber-State-Tree headers and does not\n * populate the segment cache. Every navigation gets a full RSC payload.\n */\n clientSegmentCache?: boolean;\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): 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, superseding any\n * previous in-flight navigation. Optionally links to an external\n * signal (e.g., from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with three parts:\n * 1. Abort the previous navigation's fetch.\n * 2. Invalidate its render transition so a response that already\n * arrived can't commit a stale tree (NavigationRoot's transId guard).\n * 3. Resolve its Navigation API deferred — the superseded navigation's\n * finally block is staleness-guarded (see TIM-1034) and no longer\n * cleans up after itself, so the browser's native loading state for\n * the dead navigation is cleared here.\n */\n function createNavAbort(externalSignal?: AbortSignal): AbortController {\n if (currentNavAbort) {\n currentNavAbort.abort();\n supersedeNavigationTransitions();\n deps.completeRouterNavigation?.();\n }\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 (!deps.clientSegmentCache) return;\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 /**\n * Atomically update all navigation-owned state for a new page. Every\n * code path that changes the \"current page\" must go through this\n * function — making \"forgot a field\" impossible by construction.\n *\n * The three operations:\n * 1. Segment cache — update from server-provided segment metadata\n * 2. Navigation state — params + pathname for useSegmentParams/usePathname\n * 3. History stack — store the payload for instant back/forward replay\n */\n function commitNavigation(\n url: string,\n opts: {\n payload: unknown;\n params?: Record<string, string | string[]> | null;\n segmentInfo?: SegmentInfo[] | null;\n /** When true, clear the segment cache if segmentInfo is empty\n * (popstate replay for entries without layout metadata). */\n clearSegmentCacheOnEmpty?: boolean;\n }\n ): NavigationState {\n if (opts.segmentInfo && opts.segmentInfo.length > 0) {\n updateSegmentCache(opts.segmentInfo);\n } else if (opts.clearSegmentCacheOnEmpty) {\n segmentCache.clear();\n }\n\n const navState = updateNavigationState(opts.params, url);\n\n historyStack.push(url, {\n payload: opts.payload,\n params: navState.params,\n segmentInfo: opts.segmentInfo,\n });\n\n return navState;\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavAbort + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (navAbort: AbortController) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const navAbort = createNavAbort(externalSignal);\n setPending(true, url);\n try {\n await fn(navAbort);\n } catch (error) {\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n setPending(false);\n deps.completeRouterNavigation?.();\n }\n }\n }\n\n /**\n * Resolve thenable payloads in the test/fallback path (no navigateTransition).\n * In production, React handles thenables from createFromFetch directly via\n * Suspense. In tests, renderRoot is a plain mock that expects resolved values.\n */\n async function resolveForFallback(payload: unknown): Promise<unknown> {\n if (\n !deps.navigateTransition &&\n payload != null &&\n typeof payload === 'object' &&\n 'then' in payload\n ) {\n return await (payload as PromiseLike<unknown>);\n }\n return payload;\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, call commitNavigation, and return\n * the FetchResult plus the NavigationState.\n *\n * State management (segmentCache, navState, historyStack) is handled by\n * commitNavigation inside perform — this function only handles rendering.\n */\n async function renderViaTransition(\n url: string,\n perform: () => Promise<FetchResult & { navState: NavigationState }>\n ): Promise<void> {\n if (deps.navigateTransition) {\n await deps.navigateTransition(url, async (wrapPayload) => {\n const result = await perform();\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result);\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 const element = wrapPayload(result.payload, result.navState);\n return { element, decodePromise: result.decodePromise };\n });\n return;\n }\n // Fallback: no transition (tests, no React tree)\n const result = await perform();\n if (!isPartialNavigation(result.skippedSegments)) {\n renderPayload(result.payload, result.navState);\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 * Scroll to the element matching the URL #fragment after paint, falling\n * back to scroll-to-top when no element matches (matching full-page-load\n * behavior for an unknown fragment). Used by forward navigation to a\n * hash-bearing URL (TIM-1035).\n */\n function scrollToHashAfterPaint(hash: string): void {\n afterPaint(() => {\n if (deps.scrollToHash?.(hash) !== true) {\n deps.scrollTo(0, 0);\n }\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; commitUrl?: string; 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 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 = deps.clientSegmentCache ? segmentCache.serializeStateTree() : undefined;\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 // The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n if (!options.skipHistory) {\n const commitUrl = options.commitUrl ?? url;\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 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n deps.setRouterNavigating?.(false);\n }\n\n // Resolve thenable payloads in the test path so popstate replay\n // and renderPayload receive plain values (see resolveForFallback).\n const payload = await resolveForFallback(result.payload);\n\n // Atomically update all navigation state via commitNavigation.\n // Partial navigations store null payload — the partial RSC tree\n // can't be replayed standalone; popstate will fetch fresh.\n const isPartial = isPartialNavigation(result.skippedSegments);\n const navState = commitNavigation(url, {\n payload: isPartial ? null : payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n\n return { ...result, payload, 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 // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\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 let effectiveSkipHistory = skipHistory;\n\n await runNavigation(\n url,\n async (navAbort) => {\n // When Navigation API is active, initiate the navigation via\n // navigation.navigate() BEFORE the fetch. Must happen after\n // createNavAbort supersedes the previous navigation (done by\n // runNavigation) so the old deferred is resolved first.\n if (!effectiveSkipHistory && deps.navigationNavigate) {\n deps.setRouterNavigating?.(true);\n deps.navigationNavigate(url, replace);\n deps.setRouterNavigating?.(false);\n effectiveSkipHistory = true;\n }\n\n try {\n await renderViaTransition(fetchUrl, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: navAbort.signal,\n skipHistory: effectiveSkipHistory,\n })\n );\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, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n if (error instanceof VersionSkewError) {\n setHardNavigating(true);\n window.location.reload();\n await new Promise(() => {});\n }\n if (error instanceof RedirectError) {\n if (currentNavAbort !== navAbort) return;\n await navigate(error.redirectUrl, { replace: true });\n return;\n }\n if (error instanceof ServerErrorResponse) {\n setHardNavigating(true);\n window.location.href = error.url;\n await new Promise(() => {});\n }\n throw error;\n }\n },\n externalSignal\n );\n }\n\n async function refresh(): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n await runNavigation(currentUrl, async (navAbort) => {\n 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 const payload = await resolveForFallback(result.payload);\n const navState = commitNavigation(currentUrl, {\n payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, payload, navState };\n });\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 //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async () => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n const navState = commitNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n renderPayload(entry.payload, navState);\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\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 await runNavigation(\n url,\n async (navAbort) => {\n await renderViaTransition(url, async () => {\n const stateTree = deps.clientSegmentCache\n ? segmentCache.serializeStateTree()\n : undefined;\n const result = await fetchRscPayload(url, deps, stateTree, undefined, navAbort.signal);\n const payload = await resolveForFallback(result.payload);\n const navState = commitNavigation(url, {\n payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, payload, navState };\n });\n\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\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 // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // Don't prefetch if already cached\n if (prefetchCache.get(fetchUrl) !== undefined) return;\n if (historyStack.has(fetchUrl)) return;\n\n // Fire-and-forget fetch\n const stateTree = deps.clientSegmentCache ? segmentCache.serializeStateTree() : undefined;\n void fetchRscPayload(fetchUrl, deps, stateTree).then(\n (result) => {\n result.decodePromise?.catch(() => {});\n prefetchCache.set(fetchUrl, 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): void {\n // Render the piggybacked element tree from a server action response.\n // Updates the current history entry with the fresh payload —\n // same as refresh() but without a server fetch.\n const currentUrl = deps.getCurrentUrl();\n\n // Preserve existing segmentInfo so away-and-back navigation replays\n // with a correct segment cache (TIM-1037). Preserve current params\n // so dynamic route params aren't cleared to {}.\n const existingEntry = historyStack.get(currentUrl);\n const navState = commitNavigation(currentUrl, {\n payload: element,\n params: getNavigationState().params,\n segmentInfo: existingEntry?.segmentInfo,\n });\n renderPayload(element, navState);\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 during full navigations, AND by\n * syncShallowSearch() for shallow URL updates (nuqs shallow: true,\n * replaceUrl, or any external pushState/replaceState that changes the\n * query string). See router-init.ts.\n *\n * This replaces the previous useSyncExternalStore approach which read\n * window.location.search directly — causing React to detect external\n * store tearing during transitions and fall back to synchronous rendering\n * (renderRootSync instead of renderRootConcurrent), blocking the main\n * 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":";;;;;;;;;;;;;AA8CA,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,SAAS;CACpB;AACF;;AAGA,SAAS,oBACP,MACA,KACA,iBACM;CACN,IAAI,CAAC,KAAK,YAAY,CAAC,mBAAmB,gBAAgB,IAAI,KAAK,OAAO,IACxE,IAAI,KAAK,KAAK,OAAO;CAEvB,KAAK,MAAM,SAAS,KAAK,SAAS,OAAO,GACvC,oBAAoB,OAAO,KAAK,eAAe;AAEnD;;;;;;;;;;;;AA0BA,SAAgB,iBAAiB,UAAkD;CAEjF,IAAI,SAAS,WAAW,GAAG,OAAO,KAAA;CAKlC,IAAI;CACJ,I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;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\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\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 /**\n * Whether the segment/slot is request-dependent (calls getHeaders,\n * getSearchParams, cookies, etc.). Request-dependent segments always\n * re-render on navigation. For segments, this is still based on the\n * AsyncFunction heuristic (to be replaced separately). For slots,\n * this is taint-tracked via ALS.\n */\n isRequestDependent: boolean;\n /** Child segments keyed by segment path */\n children: Map<string, SegmentNode>;\n /** Parallel route slots keyed by slot path (e.g., \"/@sidebar\") */\n slots?: Map<string, SegmentNode>;\n /** Whether this slot's access.ts denied on its last render. */\n denied?: boolean;\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 slots?: 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 const slots: string[] = [];\n if (this.root) {\n collectSyncSegments(this.root, segments, mergeableFilter);\n collectSyncSlots(this.root, slots);\n }\n const tree: StateTree = { segments };\n if (slots.length > 0) {\n tree.slots = slots;\n }\n return tree;\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.isRequestDependent && (!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/** Recursively collect cacheable slot paths from the tree */\nfunction collectSyncSlots(node: SegmentNode, out: string[]): void {\n if (node.slots) {\n for (const slot of node.slots.values()) {\n // Exclude request-dependent slots (they must re-render every nav)\n // and denied slots (their cached content is denial fallback, not real content)\n if (!slot.isRequestDependent && !slot.denied) {\n out.push(slot.segment);\n }\n }\n }\n for (const child of node.children.values()) {\n collectSyncSlots(child, out);\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 isRequestDependent: boolean;\n /** True for parallel route slot entries. Slots are keyed by their slot path (e.g., \"/@sidebar\"). */\n slot?: boolean;\n /** Parent segment path for slot entries. Used to attach the slot to the correct SegmentNode. */\n parentSegment?: string;\n /** True when the slot's access.ts denied on this render. Denied slots are excluded from the state tree. */\n denied?: 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 // Separate slot entries from segment entries. Slots are attached to\n // their parent segment node after the main chain is built.\n const segmentEntries: SegmentInfo[] = [];\n const slotEntries: SegmentInfo[] = [];\n for (const info of segments) {\n if (info.slot) {\n slotEntries.push(info);\n } else {\n segmentEntries.push(info);\n }\n }\n\n // Build the main segment chain.\n let root: SegmentNode | undefined;\n let parent: SegmentNode | undefined;\n const nodeById = new Map<string, SegmentNode>();\n\n for (const info of segmentEntries) {\n const id = info.segmentId ?? info.path;\n const node: SegmentNode = {\n segment: id,\n payload: null,\n isRequestDependent: info.isRequestDependent,\n children: new Map(),\n };\n\n nodeById.set(id, node);\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 // Attach slot entries to their parent segment nodes.\n for (const slotInfo of slotEntries) {\n const parentId = slotInfo.parentSegment;\n const parentNode = parentId ? nodeById.get(parentId) : root;\n if (!parentNode) continue;\n\n const slotId = slotInfo.segmentId ?? slotInfo.path;\n const slotNode: SegmentNode = {\n segment: slotId,\n payload: null,\n isRequestDependent: slotInfo.isRequestDependent,\n children: new Map(),\n denied: slotInfo.denied,\n };\n\n if (!parentNode.slots) {\n parentNode.slots = new Map();\n }\n parentNode.slots.set(slotId, slotNode);\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 { SegmentInfo } from './segment-cache';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * Route params for this page (for useSegmentParams). Every entry that can\n * be replayed must carry them — the initial SSR entry gets them from the\n * server-embedded __timber_params, navigation entries from X-Timber-Params,\n * and revalidation overwrites preserve the current state (TIM-1037).\n */\n params?: Record<string, string | string[]> | null;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next forward navigation computes a\n * correct state tree. Without this, the segment cache retains the\n * *previous* page's segments after back-button, causing the server to\n * skip segments that aren't mounted — and the partial payload targets\n * a non-existent outlet.\n */\n segmentInfo?: SegmentInfo[] | 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 * Entries are keyed by pathname + search. Used with the History API\n * fallback and the Navigation API.\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\n push(url: string, entry: HistoryEntry): void {\n this.entries.set(url, entry);\n }\n\n get(url: string): HistoryEntry | undefined {\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 { RouterDeps } from './router';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Result of fetching an RSC payload — includes 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 /** 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 *\n * Strips any #fragment before appending — fragments are client-only and\n * fetch() discards them, so _rsc would land inside the hash and be lost.\n */\nfunction appendRscParam(url: string): string {\n const hashIndex = url.indexOf('#');\n const urlWithoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);\n const separator = urlWithoutHash.includes('?') ? '&' : '?';\n return `${urlWithoutHash}${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 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, isRequestDependent} 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 */\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 segment metadata 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 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 // Metadata (<title>/<meta>/<link>) now rides the RSC Flight payload\n // as React elements — React 19 Float handles them. See TIM-1151.\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 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 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 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 { 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, supersedeNavigationTransitions } 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 /**\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 /**\n * Scroll the element matching a URL #fragment into view. Returns true\n * when a matching element was found and scrolled. When absent or false,\n * the router falls back to scroll-to-top on forward navigation — same\n * as a full page load with an unknown fragment landing at the top.\n */\n scrollToHash?: (hash: string) => boolean;\n\n /**\n * Whether the client segment cache is enabled. When false (the default),\n * the router does not send X-Timber-State-Tree headers and does not\n * populate the segment cache. Every navigation gets a full RSC payload.\n */\n clientSegmentCache?: boolean;\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): 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, superseding any\n * previous in-flight navigation. Optionally links to an external\n * signal (e.g., from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with three parts:\n * 1. Abort the previous navigation's fetch.\n * 2. Invalidate its render transition so a response that already\n * arrived can't commit a stale tree (NavigationRoot's transId guard).\n * 3. Resolve its Navigation API deferred — the superseded navigation's\n * finally block is staleness-guarded (see TIM-1034) and no longer\n * cleans up after itself, so the browser's native loading state for\n * the dead navigation is cleared here.\n */\n function createNavAbort(externalSignal?: AbortSignal): AbortController {\n if (currentNavAbort) {\n currentNavAbort.abort();\n supersedeNavigationTransitions();\n deps.completeRouterNavigation?.();\n }\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 (!deps.clientSegmentCache) return;\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 /**\n * Atomically update all navigation-owned state for a new page. Every\n * code path that changes the \"current page\" must go through this\n * function — making \"forgot a field\" impossible by construction.\n *\n * The three operations:\n * 1. Segment cache — update from server-provided segment metadata\n * 2. Navigation state — params + pathname for useSegmentParams/usePathname\n * 3. History stack — store the payload for instant back/forward replay\n */\n function commitNavigation(\n url: string,\n opts: {\n payload: unknown;\n params?: Record<string, string | string[]> | null;\n segmentInfo?: SegmentInfo[] | null;\n /** When true, clear the segment cache if segmentInfo is empty\n * (popstate replay for entries without layout metadata). */\n clearSegmentCacheOnEmpty?: boolean;\n }\n ): NavigationState {\n if (opts.segmentInfo && opts.segmentInfo.length > 0) {\n updateSegmentCache(opts.segmentInfo);\n } else if (opts.clearSegmentCacheOnEmpty) {\n segmentCache.clear();\n }\n\n const navState = updateNavigationState(opts.params, url);\n\n historyStack.push(url, {\n payload: opts.payload,\n params: navState.params,\n segmentInfo: opts.segmentInfo,\n });\n\n return navState;\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavAbort + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (navAbort: AbortController) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const navAbort = createNavAbort(externalSignal);\n setPending(true, url);\n try {\n await fn(navAbort);\n } catch (error) {\n if (isAbortError(error)) return;\n throw error;\n } finally {\n if (currentNavAbort === navAbort) {\n currentNavAbort = null;\n setPending(false);\n deps.completeRouterNavigation?.();\n }\n }\n }\n\n /**\n * Resolve thenable payloads in the test/fallback path (no navigateTransition).\n * In production, React handles thenables from createFromFetch directly via\n * Suspense. In tests, renderRoot is a plain mock that expects resolved values.\n */\n async function resolveForFallback(payload: unknown): Promise<unknown> {\n if (\n !deps.navigateTransition &&\n payload != null &&\n typeof payload === 'object' &&\n 'then' in payload\n ) {\n return await (payload as PromiseLike<unknown>);\n }\n return payload;\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, call commitNavigation, and return\n * the FetchResult plus the NavigationState.\n *\n * State management (segmentCache, navState, historyStack) is handled by\n * commitNavigation inside perform — this function only handles rendering.\n */\n async function renderViaTransition(\n url: string,\n perform: () => Promise<FetchResult & { navState: NavigationState }>\n ): Promise<void> {\n if (deps.navigateTransition) {\n await deps.navigateTransition(url, async (wrapPayload) => {\n const result = await perform();\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result);\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 const element = wrapPayload(result.payload, result.navState);\n return { element, decodePromise: result.decodePromise };\n });\n return;\n }\n // Fallback: no transition (tests, no React tree)\n const result = await perform();\n if (!isPartialNavigation(result.skippedSegments)) {\n renderPayload(result.payload, result.navState);\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 * Scroll to the element matching the URL #fragment after paint, falling\n * back to scroll-to-top when no element matches (matching full-page-load\n * behavior for an unknown fragment). Used by forward navigation to a\n * hash-bearing URL (TIM-1035).\n */\n function scrollToHashAfterPaint(hash: string): void {\n afterPaint(() => {\n if (deps.scrollToHash?.(hash) !== true) {\n deps.scrollTo(0, 0);\n }\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; commitUrl?: string; 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 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 = deps.clientSegmentCache ? segmentCache.serializeStateTree() : undefined;\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 // The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n if (!options.skipHistory) {\n const commitUrl = options.commitUrl ?? url;\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 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n deps.setRouterNavigating?.(false);\n }\n\n // Resolve thenable payloads in the test path so popstate replay\n // and renderPayload receive plain values (see resolveForFallback).\n const payload = await resolveForFallback(result.payload);\n\n // Atomically update all navigation state via commitNavigation.\n // Partial navigations store null payload — the partial RSC tree\n // can't be replayed standalone; popstate will fetch fresh.\n const isPartial = isPartialNavigation(result.skippedSegments);\n const navState = commitNavigation(url, {\n payload: isPartial ? null : payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n\n return { ...result, payload, 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 // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\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 let effectiveSkipHistory = skipHistory;\n\n await runNavigation(\n url,\n async (navAbort) => {\n // When Navigation API is active, initiate the navigation via\n // navigation.navigate() BEFORE the fetch. Must happen after\n // createNavAbort supersedes the previous navigation (done by\n // runNavigation) so the old deferred is resolved first.\n if (!effectiveSkipHistory && deps.navigationNavigate) {\n deps.setRouterNavigating?.(true);\n deps.navigationNavigate(url, replace);\n deps.setRouterNavigating?.(false);\n effectiveSkipHistory = true;\n }\n\n try {\n await renderViaTransition(fetchUrl, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: navAbort.signal,\n skipHistory: effectiveSkipHistory,\n })\n );\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, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n if (error instanceof VersionSkewError) {\n setHardNavigating(true);\n window.location.reload();\n await new Promise(() => {});\n }\n if (error instanceof RedirectError) {\n if (currentNavAbort !== navAbort) return;\n await navigate(error.redirectUrl, { replace: true });\n return;\n }\n if (error instanceof ServerErrorResponse) {\n setHardNavigating(true);\n window.location.href = error.url;\n await new Promise(() => {});\n }\n throw error;\n }\n },\n externalSignal\n );\n }\n\n async function refresh(): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n await runNavigation(currentUrl, async (navAbort) => {\n 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 const payload = await resolveForFallback(result.payload);\n const navState = commitNavigation(currentUrl, {\n payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, payload, navState };\n });\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 //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async () => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n const navState = commitNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n renderPayload(entry.payload, navState);\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\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 await runNavigation(\n url,\n async (navAbort) => {\n await renderViaTransition(url, async () => {\n const stateTree = deps.clientSegmentCache\n ? segmentCache.serializeStateTree()\n : undefined;\n const result = await fetchRscPayload(url, deps, stateTree, undefined, navAbort.signal);\n const payload = await resolveForFallback(result.payload);\n const navState = commitNavigation(url, {\n payload,\n params: result.params,\n segmentInfo: result.segmentInfo,\n });\n return { ...result, payload, navState };\n });\n\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\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 // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // Don't prefetch if already cached\n if (prefetchCache.get(fetchUrl) !== undefined) return;\n if (historyStack.has(fetchUrl)) return;\n\n // Fire-and-forget fetch\n const stateTree = deps.clientSegmentCache ? segmentCache.serializeStateTree() : undefined;\n void fetchRscPayload(fetchUrl, deps, stateTree).then(\n (result) => {\n result.decodePromise?.catch(() => {});\n prefetchCache.set(fetchUrl, 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): void {\n // Render the piggybacked element tree from a server action response.\n // Updates the current history entry with the fresh payload —\n // same as refresh() but without a server fetch.\n const currentUrl = deps.getCurrentUrl();\n\n // Preserve existing segmentInfo so away-and-back navigation replays\n // with a correct segment cache (TIM-1037). Preserve current params\n // so dynamic route params aren't cleared to {}.\n const existingEntry = historyStack.get(currentUrl);\n const navState = commitNavigation(currentUrl, {\n payload: element,\n params: getNavigationState().params,\n segmentInfo: existingEntry?.segmentInfo,\n });\n renderPayload(element, navState);\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 during full navigations, AND by\n * syncShallowSearch() for shallow URL updates (nuqs shallow: true,\n * replaceUrl, or any external pushState/replaceState that changes the\n * query string). See router-init.ts.\n *\n * This replaces the previous useSyncExternalStore approach which read\n * window.location.search directly — causing React to detect external\n * store tearing during transitions and fall back to synchronous rendering\n * (renderRootSync instead of renderRootConcurrent), blocking the main\n * 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":";;;;;;;;;;;;;AAyDA,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,MAAM,QAAkB,CAAC;EACzB,IAAI,KAAK,MAAM;GACb,oBAAoB,KAAK,MAAM,UAAU,eAAe;GACxD,iBAAiB,KAAK,MAAM,KAAK;EACnC;EACA,MAAM,OAAkB,EAAE,SAAS;EACnC,IAAI,MAAM,SAAS,GACjB,KAAK,QAAQ;EAEf,OAAO;CACT;AACF;;AAGA,SAAS,oBACP,MACA,KACA,iBACM;CACN,IAAI,CAAC,KAAK,uBAAuB,CAAC,mBAAmB,gBAAgB,IAAI,KAAK,OAAO,IACnF,IAAI,KAAK,KAAK,OAAO;CAEvB,KAAK,MAAM,SAAS,KAAK,SAAS,OAAO,GACvC,oBAAoB,OAAO,KAAK,eAAe;AAEnD;;AAGA,SAAS,iBAAiB,MAAmB,KAAqB;CAChE,IAAI,KAAK;OACF,MAAM,QAAQ,KAAK,MAAM,OAAO,GAGnC,IAAI,CAAC,KAAK,sBAAsB,CAAC,KAAK,QACpC,IAAI,KAAK,KAAK,OAAO;CAAA;CAI3B,KAAK,MAAM,SAAS,KAAK,SAAS,OAAO,GACvC,iBAAiB,OAAO,GAAG;AAE/B;;;;;;;;;;;;AAgCA,SAAgB,iBAAiB,UAAkD;CAEjF,IAAI,SAAS,WAAW,GAAG,OAAO,KAAA;CAI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,OAAO,QAAQ;EAC/C;EACA;EACA,kBAAkB,SAAwB;GAIxC,MAAM,aAAa,KAAK,cAAc;GAKtC,MAAM,gBAAgB,aAAa,IAAI,UAAU;GAMjD,cAAc,SALG,iBAAiB,YAAY;IAC5C,SAAS;IACT,QAAQ,mBAAmB,CAAC,CAAC;IAC7B,aAAa,eAAe;GAC9B,CACuB,CAAQ;EACjC;EACA,mBAAmB,aAA4B,mBAAmB,QAAQ;EAC1E;EACA;EACA;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACxxBA,SAAS,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"}
@@ -51,7 +51,7 @@ export declare function buildRscHeaders(stateTree: {
51
51
  * Extract segment metadata from the X-Timber-Segments response header.
52
52
  * Returns null if the header is missing or malformed.
53
53
  *
54
- * Format: JSON array of {path, isAsync} objects describing the rendered
54
+ * Format: JSON array of {path, isRequestDependent} objects describing the rendered
55
55
  * segment chain from root to leaf. Used to populate the client-side
56
56
  * segment cache for state tree diffing on subsequent navigations.
57
57
  */
@@ -17,10 +17,20 @@ export interface SegmentNode {
17
17
  segment: string;
18
18
  /** The RSC flight payload for this segment (opaque to the cache) */
19
19
  payload: unknown;
20
- /** Whether the segment is async (async layouts always re-render on navigation) */
21
- isAsync: boolean;
20
+ /**
21
+ * Whether the segment/slot is request-dependent (calls getHeaders,
22
+ * getSearchParams, cookies, etc.). Request-dependent segments always
23
+ * re-render on navigation. For segments, this is still based on the
24
+ * AsyncFunction heuristic (to be replaced separately). For slots,
25
+ * this is taint-tracked via ALS.
26
+ */
27
+ isRequestDependent: boolean;
22
28
  /** Child segments keyed by segment path */
23
29
  children: Map<string, SegmentNode>;
30
+ /** Parallel route slots keyed by slot path (e.g., "/@sidebar") */
31
+ slots?: Map<string, SegmentNode>;
32
+ /** Whether this slot's access.ts denied on its last render. */
33
+ denied?: boolean;
24
34
  }
25
35
  /**
26
36
  * Serialized state tree sent via X-Timber-State-Tree header.
@@ -28,6 +38,7 @@ export interface SegmentNode {
28
38
  */
29
39
  export interface StateTree {
30
40
  segments: string[];
41
+ slots?: string[];
31
42
  }
32
43
  /**
33
44
  * Maintains the client-side segment tree representing currently mounted
@@ -62,7 +73,13 @@ export interface SegmentInfo {
62
73
  path: string;
63
74
  /** Outlet key — includes route group name when applicable (e.g., "/(marketing)"). */
64
75
  segmentId?: string;
65
- isAsync: boolean;
76
+ isRequestDependent: boolean;
77
+ /** True for parallel route slot entries. Slots are keyed by their slot path (e.g., "/@sidebar"). */
78
+ slot?: boolean;
79
+ /** Parent segment path for slot entries. Used to attach the slot to the correct SegmentNode. */
80
+ parentSegment?: string;
81
+ /** True when the slot's access.ts denied on this render. Denied slots are excluded from the state tree. */
82
+ denied?: boolean;
66
83
  }
67
84
  /**
68
85
  * Build a SegmentNode tree from flat segment metadata.
@@ -1 +1 @@
1
- {"version":3,"file":"segment-cache.d.ts","sourceRoot":"","sources":["../../src/client/segment-cache.ts"],"names":[],"mappings":"AAKA,8DAA8D;AAC9D,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,uFAAuF;IACvF,WAAW,CAAC,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACnC,kFAAkF;IAClF,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,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5C;IAED,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CAI5C;IAED,KAAK,IAAI,IAAI,CAEZ;IAED;;;;;;;;;;;;OAYG;IACH,kBAAkB,CAAC,eAAe,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,CAY3D;CACF;AAkCD;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,qFAAqF;IACrF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,oGAAoG;IACpG,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gGAAgG;IAChG,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2GAA2G;IAC3G,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,WAAW,GAAG,SAAS,CAiEjF;AASD;;;;;;;GAOG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAU;IACxC,OAAO,CAAC,OAAO,CAAoC;IAEnD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAK7C;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAQ3C;IAED,0EAA0E;IAC1E,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAM/C;CACF"}
@@ -27,11 +27,19 @@ export interface SegmentOutletProps {
27
27
  * Unique identifier for this segment. For normal segments this is the
28
28
  * urlPath (e.g., "/", "/dashboard"). For route groups this includes the
29
29
  * group name (e.g., "/(marketing)") to distinguish siblings that share
30
- * the same urlPath. Must match the segmentId used in state-tree-diff.ts.
30
+ * the same urlPath. For slots this includes the slot name (e.g., "/@sidebar").
31
+ * Must match the segmentId used in state-tree-diff.ts.
31
32
  */
32
33
  segmentPath: string;
33
34
  /** The segment's React subtree (layout + inner content). */
34
35
  children: ReactNode;
36
+ /**
37
+ * When true, the outlet returns cached content instead of rendering
38
+ * new children. Used for skipped parallel route slots — the server
39
+ * sends an empty SegmentOutlet with skip=true, and the client keeps
40
+ * the previously cached slot content.
41
+ */
42
+ skip?: boolean;
35
43
  }
36
44
  /**
37
45
  * Client component boundary at each layout segment in the element tree.
@@ -45,5 +53,5 @@ export interface SegmentOutletProps {
45
53
  * when the same type appears at the same tree position. The ref persists
46
54
  * across navigations because SegmentOutlet is reconciled, not remounted.
47
55
  */
48
- export declare function SegmentOutlet({ segmentPath, children }: SegmentOutletProps): ReactNode;
56
+ export declare function SegmentOutlet({ segmentPath, children, skip }: SegmentOutletProps): ReactNode;
49
57
  //# sourceMappingURL=segment-outlet.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"segment-outlet.d.ts","sourceRoot":"","sources":["../../src/client/segment-outlet.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAsB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAG3D,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB,4DAA4D;IAC5D,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE,EAAE,kBAAkB,aAsB1E"}
1
+ {"version":3,"file":"segment-outlet.d.ts","sourceRoot":"","sources":["../../src/client/segment-outlet.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAsB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAG3D,MAAM,WAAW,kBAAkB;IACjC;;;;;;OAMG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB,4DAA4D;IAC5D,QAAQ,EAAE,SAAS,CAAC;IAEpB;;;;;OAKG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,kBAAkB,aAmChF"}
@@ -8,18 +8,20 @@
8
8
  * SlotsProvider carrying the live slot values; each outlet reads its
9
9
  * value from this context by name.
10
10
  *
11
- * The value is a per-instance record — the NEAREST provider wins, so two
12
- * instances of the same cached component on one page each resolve their
13
- * own children, and a slot component nested inside another slot
14
- * component's children reads its own provider, not the outer one.
11
+ * Providers MERGE per-key with their parent: an inner SlotsProvider
12
+ * inherits the outer's values and overrides only the keys it declares.
13
+ * Two sibling instances each have their own provider and resolve
14
+ * independently. Layouts use a reserved slot name (LAYOUT_CHILDREN_SLOT)
15
+ * that cannot collide with user-declared slot names (TIM-1191).
15
16
  *
16
- * Generalizes the ChildSegmentContext pattern (TIM-1181) from a single
17
- * implicit `children` hole on layouts to explicitly declared, named slot
18
- * props on any cached component.
17
+ * Generalizes the original layout children pattern (TIM-1181) from a
18
+ * single implicit `children` hole on layouts to explicitly declared,
19
+ * named slot props on any cached component. Layouts use this same
20
+ * context with the reserved LAYOUT_CHILDREN_SLOT key (TIM-1191).
19
21
  *
20
22
  * SINGLETON GUARANTEE: globalThis + Symbol.for — the RSC client bundler
21
23
  * can duplicate this module across chunks; globalThis guarantees a single
22
- * context instance. Same pattern as ChildSegmentContext.
24
+ * context instance.
23
25
  *
24
26
  * See design/45-cache-lifetimes.md §Slot Components.
25
27
  */
@@ -1 +1 @@
1
- {"version":3,"file":"slot-context.d.ts","sourceRoot":"","sources":["../../src/client/slot-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAIH,OAAO,KAAK,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAE9C,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAiBnD,eAAO,MAAM,WAAW,kCAAuB,CAAC"}
1
+ {"version":3,"file":"slot-context.d.ts","sourceRoot":"","sources":["../../src/client/slot-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAIH,OAAO,KAAK,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAE9C,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAiBnD,eAAO,MAAM,WAAW,kCAAuB,CAAC"}
@@ -2,6 +2,11 @@
2
2
  * SlotsProvider — wraps a revived cached shell to supply live slot content
3
3
  * to the SlotOutlet holes inside it (TIM-1173).
4
4
  *
5
+ * Values MERGE with the nearest parent provider so that nesting a
6
+ * cache.component SlotsProvider inside a layout SlotsProvider preserves
7
+ * the layout's `children` slot while adding the component's own slots.
8
+ * Inner values override outer ones with the same name (spread order).
9
+ *
5
10
  * Tree structure per cached-component instance:
6
11
  * SlotsProvider(values={children: <Live />})
7
12
  * └── revived shell