@timber-js/app 0.2.0-alpha.224 → 0.2.0-alpha.225

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 (77) hide show
  1. package/dist/_chunks/{actions-7dTXYJfu.js → actions-B1xSIv32.js} +2 -2
  2. package/dist/_chunks/{actions-7dTXYJfu.js.map → actions-B1xSIv32.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-TDZ4hlDc.js → cache-api-DsSXA4Sp.js} +68 -47
  4. package/dist/_chunks/cache-api-DsSXA4Sp.js.map +1 -0
  5. package/dist/_chunks/{cli-check-Dv3f8d2j.js → cli-check-B33yhAPa.js} +2 -2
  6. package/dist/_chunks/{cli-check-Dv3f8d2j.js.map → cli-check-B33yhAPa.js.map} +1 -1
  7. package/dist/_chunks/cli-context-BPdyA7Fp.js +1 -0
  8. package/dist/_chunks/{cli-context-CbZp32SK.js → cli-context-CwTKMjVe.js} +10 -2
  9. package/dist/_chunks/cli-context-CwTKMjVe.js.map +1 -0
  10. package/dist/_chunks/{error-boundary-DRQXGWCp.js → error-boundary-D3YyVVuP.js} +2 -2
  11. package/dist/_chunks/{error-boundary-DRQXGWCp.js.map → error-boundary-D3YyVVuP.js.map} +1 -1
  12. package/dist/_chunks/{singleflight-BChPMjwH.js → singleflight-CzoOVB9Y.js} +2 -3
  13. package/dist/_chunks/singleflight-CzoOVB9Y.js.map +1 -0
  14. package/dist/_chunks/{status-page-marker-XIQXlTOb.js → status-page-marker-C8POawuF.js} +2 -2
  15. package/dist/_chunks/{status-page-marker-XIQXlTOb.js.map → status-page-marker-C8POawuF.js.map} +1 -1
  16. package/dist/adapters/cloudflare-kv-cache.d.ts +0 -1
  17. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -1
  18. package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
  19. package/dist/cache/index.d.ts +5 -5
  20. package/dist/cache/index.d.ts.map +1 -1
  21. package/dist/cache/index.js +1 -1
  22. package/dist/cache/redis-handler.d.ts +0 -1
  23. package/dist/cache/redis-handler.d.ts.map +1 -1
  24. package/dist/cache/singleflight.d.ts +12 -2
  25. package/dist/cache/singleflight.d.ts.map +1 -1
  26. package/dist/cache/stable-stringify.d.ts +6 -0
  27. package/dist/cache/stable-stringify.d.ts.map +1 -1
  28. package/dist/cache/tag-aware-handler.d.ts +0 -1
  29. package/dist/cache/tag-aware-handler.d.ts.map +1 -1
  30. package/dist/cache/timber-cache.d.ts +1 -1
  31. package/dist/cache/timber-cache.d.ts.map +1 -1
  32. package/dist/cli-context.d.ts +8 -0
  33. package/dist/cli-context.d.ts.map +1 -1
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +8 -2
  36. package/dist/cli.js.map +1 -1
  37. package/dist/client/error-boundary.js +1 -1
  38. package/dist/client/internal.js +3 -3
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +112 -0
  41. package/dist/index.js.map +1 -1
  42. package/dist/plugins/client-in-server-package-deps.d.ts +63 -0
  43. package/dist/plugins/client-in-server-package-deps.d.ts.map +1 -0
  44. package/dist/plugins/optimize-package-imports.d.ts +11 -0
  45. package/dist/plugins/optimize-package-imports.d.ts.map +1 -1
  46. package/dist/server/flight-injector-core.d.ts.map +1 -1
  47. package/dist/server/index.js +1 -1
  48. package/dist/server/internal.js +162 -33
  49. package/dist/server/internal.js.map +1 -1
  50. package/dist/server/pipeline-helpers.d.ts +5 -2
  51. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  52. package/dist/server/pipeline.d.ts.map +1 -1
  53. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  54. package/dist/server/response-framing.d.ts +43 -0
  55. package/dist/server/response-framing.d.ts.map +1 -0
  56. package/package.json +2 -2
  57. package/src/adapters/cloudflare-kv-cache.ts +1 -5
  58. package/src/cache/index.ts +7 -27
  59. package/src/cache/redis-handler.ts +1 -5
  60. package/src/cache/singleflight.ts +17 -5
  61. package/src/cache/stable-stringify.ts +53 -0
  62. package/src/cache/tag-aware-handler.ts +1 -5
  63. package/src/cache/timber-cache.ts +55 -52
  64. package/src/cli-context.ts +9 -0
  65. package/src/cli.ts +16 -0
  66. package/src/index.ts +2 -0
  67. package/src/plugins/client-in-server-package-deps.ts +139 -0
  68. package/src/plugins/optimize-package-imports.ts +1 -1
  69. package/src/server/flight-injector-core.ts +13 -9
  70. package/src/server/pipeline-helpers.ts +9 -5
  71. package/src/server/pipeline.ts +7 -0
  72. package/src/server/prebuilt-runtime.ts +125 -121
  73. package/src/server/response-framing.ts +59 -0
  74. package/dist/_chunks/cache-api-TDZ4hlDc.js.map +0 -1
  75. package/dist/_chunks/cli-context-CbZp32SK.js.map +0 -1
  76. package/dist/_chunks/cli-context-n5hmkdla.js +0 -1
  77. package/dist/_chunks/singleflight-BChPMjwH.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singleflight-CzoOVB9Y.js","names":[],"sources":["../../src/cache/singleflight.ts"],"sourcesContent":["/**\n * Singleflight coalesces concurrent calls with the same key into a single\n * execution. All callers receive the same result (or error).\n *\n * Per-process, in-memory. Each process coalesces independently.\n *\n * An optional `timeoutMs` prevents hung `fn()` calls from permanently\n * blocking all future callers for that key. When set, `fn()` is raced\n * against a timeout — if the timeout fires first, the promise rejects\n * with `SingleflightTimeoutError`, `finally` cleans up the key, and\n * subsequent callers can retry. See TIM-518.\n */\n\nexport interface SingleflightOptions {\n /**\n * Default maximum time (ms) a coalesced call may run before being\n * rejected. A `timeoutMs` passed to `do()` overrides it for that flight.\n */\n timeoutMs?: number;\n}\n\nexport interface Singleflight {\n /**\n * Run `fn` once per key; concurrent callers join the in-flight call.\n * `timeoutMs` (default: the instance option) applies to the flight this\n * call starts — a caller that joins an existing flight inherits its\n * timeout. Passing it per call lets callers with different timeouts\n * share one keyspace instead of each needing its own instance.\n */\n do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>, timeoutMs?: number): Promise<T>;\n /** Return the in-flight promise for a key, or undefined if none. */\n get(key: string): Promise<unknown> | undefined;\n}\n\n/**\n * Error thrown when a singleflight call exceeds `timeoutMs`.\n * Exported so callers can distinguish timeout from other errors.\n */\nexport class SingleflightTimeoutError extends Error {\n constructor(key: string, timeoutMs: number) {\n super(`Singleflight timeout: key \"${key}\" exceeded ${timeoutMs}ms`);\n this.name = 'SingleflightTimeoutError';\n }\n}\n\nexport function createSingleflight(opts?: SingleflightOptions): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n return {\n do<T>(\n key: string,\n fn: (signal: AbortSignal) => Promise<T>,\n timeoutMs = opts?.timeoutMs\n ): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\n const ac = new AbortController();\n let promise: Promise<T>;\n\n if (timeoutMs != null && timeoutMs > 0) {\n // Race fn() against a timeout to prevent hung calls from\n // permanently blocking the key. See TIM-518.\n // Abort the signal on timeout so the callback can skip\n // side effects (e.g. cache writes). See TIM-1092.\n promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n // The timeout error is also the signal's reason, so the body\n // can tell why it was aborted (runBackgroundFlight reports it).\n const timeout = new SingleflightTimeoutError(key, timeoutMs);\n ac.abort(timeout);\n reject(timeout);\n }, timeoutMs);\n try {\n fn(ac.signal).then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n } catch (err) {\n clearTimeout(timer);\n reject(err);\n }\n });\n } else {\n promise = fn(ac.signal);\n }\n\n const tracked = promise.finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, tracked);\n return tracked as Promise<T>;\n },\n get(key: string): Promise<unknown> | undefined {\n return inflight.get(key);\n },\n };\n}\n"],"mappings":";;;;;AAsCA,IAAa,2BAAb,cAA8C,MAAM;CAClD,YAAY,KAAa,WAAmB;EAC1C,MAAM,8BAA8B,IAAI,aAAa,UAAU,GAAG;EAClE,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,mBAAmB,MAA0C;CAC3E,MAAM,2BAAW,IAAI,IAA8B;CACnD,OAAO;EACL,GACE,KACA,IACA,YAAY,MAAM,WACN;GACZ,MAAM,WAAW,SAAS,IAAI,GAAG;GACjC,IAAI,UAAU,OAAO;GAErB,MAAM,KAAK,IAAI,gBAAgB;GAC/B,IAAI;GAEJ,IAAI,aAAa,QAAQ,YAAY,GAKnC,UAAU,IAAI,SAAY,SAAS,WAAW;IAC5C,MAAM,QAAQ,iBAAiB;KAG7B,MAAM,UAAU,IAAI,yBAAyB,KAAK,SAAS;KAC3D,GAAG,MAAM,OAAO;KAChB,OAAO,OAAO;IAChB,GAAG,SAAS;IACZ,IAAI;KACF,GAAG,GAAG,MAAM,CAAC,CAAC,MACX,UAAU;MACT,aAAa,KAAK;MAClB,QAAQ,KAAK;KACf,IACC,QAAQ;MACP,aAAa,KAAK;MAClB,OAAO,GAAG;KACZ,CACF;IACF,SAAS,KAAK;KACZ,aAAa,KAAK;KAClB,OAAO,GAAG;IACZ;GACF,CAAC;QAED,UAAU,GAAG,GAAG,MAAM;GAGxB,MAAM,UAAU,QAAQ,cAAc;IACpC,SAAS,OAAO,GAAG;GACrB,CAAC;GAED,SAAS,IAAI,KAAK,OAAO;GACzB,OAAO;EACT;EACA,IAAI,KAA2C;GAC7C,OAAO,SAAS,IAAI,GAAG;EACzB;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as createSingleflight } from "./singleflight-BChPMjwH.js";
1
+ import { n as createSingleflight } from "./singleflight-CzoOVB9Y.js";
2
2
  import { a as _setStatusPageRendered, f as statusPageRendered, r as _setOnStatusPageRendered, u as onStatusPageRendered } from "./state-B-EBjeER.js";
3
3
  import { useLayoutEffect } from "react";
4
4
  // src/shared/rsc-error-envelope.ts
@@ -556,4 +556,4 @@ function StatusPageMarker({ children }) {
556
556
  }
557
557
  export { routerUrlKey as a, prefetchScopeOf as c, parseRouterUrl as i, TIMBER_ERROR_HEADER as l, createNavigationCommitter as n, PrefetchCache as o, isPartialNavigation as r, SegmentCache as s, StatusPageMarker as t };
558
558
 
559
- //# sourceMappingURL=status-page-marker-XIQXlTOb.js.map
559
+ //# sourceMappingURL=status-page-marker-C8POawuF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"status-page-marker-XIQXlTOb.js","names":[],"sources":["../../src/shared/rsc-error-envelope.ts","../../src/client/segment-cache.ts","../../src/client/router-url.ts","../../src/client/navigation-commit.ts","../../src/client/status-page-marker.tsx"],"sourcesContent":["/**\n * The hard-navigate error envelope shared by the server and the client router.\n *\n * A client-navigation (RSC) request cannot carry an error *page* — the response\n * body must be Flight data or the decoder crashes. Instead the server answers\n * with this envelope: an `X-Timber-Error: 1` header and a minimal JSON body.\n * The client treats it as \"give up on SPA navigation and hard-navigate\", and\n * the resulting document request renders the real error page as HTML.\n *\n * The header name lives here so the four server producers and the single\n * client consumer cannot drift apart. See design/10-error-handling.md\n * §\"Error Page Rendering for Client Navigation\".\n */\n\n/** Header the client checks to decide whether to hard-navigate. */\nexport const TIMBER_ERROR_HEADER = 'X-Timber-Error';\n","// Segment Cache — stores the mounted segment tree and prefetched payloads\n// See design/19-client-navigation.md for architecture details.\n\nimport type { PublishedParams } from '../shared/payload-root.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport { createSingleflight } from '../cache/singleflight.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n /**\n * Completion of the full Flight stream, when the prefetch is still decoding.\n * Carried through to the navigation that consumes the entry so a decode\n * failure reaches *that* navigation's recovery rather than dying with the\n * prefetch (TIM-1275).\n */\n decodePromise?: Promise<void> | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /**\n * The params published beside `payload`, split off the same payload root.\n * Carried so a consumed prefetch publishes the params of the tree it is\n * about to render, and not the ones already on screen.\n */\n params?: PublishedParams | Promise<PublishedParams>;\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 /**\n * The segment's `app/` directory path, groups included (e.g. `/(browse)/feed`).\n * Undefined for slot nodes and for servers that predate the field.\n */\n treePath?: 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 * Content key for slot nodes — opaque string the server computed from\n * owner parts, slot name, entry file, and slot params. Advertised back\n * to the server so it can decide skips by key membership (TIM-1370).\n */\n contentKey?: 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 * Monotonic counter. Bumped by `invalidateReuse()` (TIM-1466).\n * `serializeStateTree` suppresses `segments` and `slots` when\n * `reuseInvalidatedAt > reuseRestoredAt`. Only `restoreReuse()`\n * advances `reuseRestoredAt` — `set()` does not, because a\n * pre-invalidation navigation's commit thunk would lift suppression\n * before a post-invalidation request has been sent (codex on #1167).\n */\n private reuseInvalidatedAt = 0;\n private reuseRestoredAt = 0;\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 this.reuseRestoredAt = this.reuseInvalidatedAt;\n }\n\n /**\n * Suppress segment and slot reuse without destroying the tree\n * structure (TIM-1466). `serializeStateTree` sends empty\n * `segments`/`slots` (forcing a full render) while `treePaths`\n * still reflects the mounted tree for interception scoping.\n * Call `restoreReuse()` once post-invalidation data has been\n * fetched and committed.\n */\n invalidateReuse(): void {\n this.reuseInvalidatedAt++;\n }\n\n /**\n * Lift reuse suppression. Called after the segment cache has been\n * rebuilt from a response that was fetched with suppression active\n * (i.e. the server sent a full render). Safe to call idempotently.\n */\n restoreReuse(): void {\n this.reuseRestoredAt = this.reuseInvalidatedAt;\n }\n\n /** Whether segment/slot reuse is currently suppressed (TIM-1466). */\n isReuseSuppressed(): boolean {\n return this.reuseInvalidatedAt > this.reuseRestoredAt;\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 * `treePaths` is collected UNFILTERED, unlike `segments` and `slots`. Those\n * two answer \"what may the server skip re-rendering?\", so every reason a\n * segment cannot be reused is a reason to leave it out. `treePaths` answers\n * \"what is mounted right now?\" for interception scoping — a request-dependent\n * layout is still on screen, and dropping it would silently narrow the scope\n * the server sees and cancel a modal that should open (TIM-1282).\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 const treePaths: string[] = [];\n const suppressed = this.reuseInvalidatedAt > this.reuseRestoredAt;\n if (this.root) {\n if (!suppressed) {\n collectSyncSegments(this.root, segments, mergeableFilter);\n collectSyncSlots(this.root, slots);\n }\n collectTreePaths(this.root, treePaths);\n }\n const tree: StateTree = { segments };\n if (slots.length > 0) {\n tree.slots = slots;\n }\n if (treePaths.length > 0) {\n tree.treePaths = treePaths;\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/**\n * Recursively collect the `app/` directory path of every mounted segment.\n *\n * Slots are not walked: a slot's own sub-tree can never own an intercepting\n * slot's scope, because scopes are always ordinary segments (`interception.ts`\n * derives one from the slot owner's ancestor chain).\n */\nfunction collectTreePaths(node: SegmentNode, out: string[]): void {\n if (node.treePath) out.push(node.treePath);\n for (const child of node.children.values()) {\n collectTreePaths(child, out);\n }\n}\n\n/**\n * Recursively collect content keys from cacheable slots.\n *\n * The server advertises a content key per slot on every render (TIM-1370),\n * encoding the owner's URL parts, the slot name, the matched entry file,\n * and the slot's params. The client stores this key and sends it back on\n * the next navigation so the server can decide skips by key membership —\n * no departing URL reconstruction needed.\n */\nfunction collectSyncSlots(node: SegmentNode, out: string[]): void {\n if (node.slots) {\n for (const slot of node.slots.values()) {\n if (!slot.isRequestDependent && !slot.denied && slot.contentKey) {\n out.push(slot.contentKey);\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 * 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 treePath: info.treePath,\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 contentKey: slotInfo.contentKey,\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 ReadyEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/** Sentinel value for negative cache entries (URL is not a route). */\nconst NEGATIVE_ENTRY: PrefetchResult = Object.freeze({ payload: null });\n\n/**\n * Timeout for the in-flight singleflight (TIM-1438). Per CLAUDE.md's\n * singleflight rule: \"Never write a coalescing Map without a timeout.\"\n * A hung prefetch cannot block clicks or suppress hovers forever.\n */\nconst PREFETCH_SINGLEFLIGHT_TIMEOUT_MS = 5_000;\n\n/**\n * Identifies a prefetched payload. A payload is addressed by *every* input that\n * changes the server's answer, not by the destination alone.\n *\n * The server's answer for a destination depends on where the request came\n * from — that is the whole mechanism behind intercepting routes, and it also\n * drives slot-skip resolution. A prefetch issued from `/gallery` is a modal\n * payload; the same URL prefetched from `/` is the full page. Keying on the\n * destination alone let the first click after a hover be answered with\n * whichever variant happened to be fetched (TIM-1265).\n *\n * `from` alone stopped being enough in TIM-1282. It is a pathname, and once\n * interception scope comes from the rendered tree rather than the address, one\n * pathname no longer names one source tree: `/photo/1` is the address both for\n * a modal open over `(browse)` and for `(landing)`'s canonical page. A key\n * without the scope hands the modal payload to the canonical page's click,\n * which renders it without the server's scope check ever running.\n *\n * The two reads happen at different instants — `scope` is sampled at hover and\n * again at click — which is why a tree that changed in between produces a\n * *miss* and a refetch rather than a wrong hit.\n */\nexport interface PrefetchKey {\n /** Destination URL — hash-less `pathname + search`, as navigate() fetches it. */\n url: string;\n /** Departing pathname — the `X-Timber-URL` the prefetch was issued with. */\n from: string;\n /**\n * The rendered scope the prefetch was issued with — the `treePaths` half of\n * `X-Timber-State-Tree`, joined. Empty when none crossed.\n */\n scope: string;\n}\n\n/**\n * Compose the map key. Length-prefixed rather than delimiter-joined for the\n * same reason `shared/rsc-cache-key.ts` is: any delimiter is forgeable by a\n * value containing it, and a URL may contain any character a delimiter could.\n */\nfunction prefetchMapKey(key: PrefetchKey): string {\n return `${key.from.length}:${key.from}:${key.scope.length}:${key.scope}:${key.url}`;\n}\n\n/**\n * The `scope` half of a `PrefetchKey`, derived from the state tree that will\n * actually be sent. Taking it from the header value rather than re-walking the\n * cache is the point: the key varies by exactly what the request varies by.\n */\nexport function prefetchScopeOf(stateTree: StateTree | undefined): string {\n return stateTree?.treePaths?.join('\\u0000') ?? '';\n}\n\n/** Outcome of a prefetch flight — discriminated so NonRscResponse is a\n * success (stores a negative entry) rather than a rejection.\n * `startGen` is the eviction generation at flight start — joiners that\n * started after a gen bump must reject pre-invalidation results (TIM-1464). */\nexport type FlightOutcome =\n | { kind: 'ready'; result: PrefetchResult; startGen: number }\n | { kind: 'non-route'; startGen: number };\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 * In-flight dedup (TIM-1438): concurrent fetches for the same key are\n * coalesced by a `createSingleflight` instance. A hover starts a flight;\n * a click for the same key joins it instead of issuing a duplicate. The\n * singleflight enforces a 5-second timeout and cleans up automatically\n * on settlement.\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, ReadyEntry>();\n private flights = createSingleflight({ timeoutMs: PREFETCH_SINGLEFLIGHT_TIMEOUT_MS });\n private evictionGen = 0;\n\n set(key: PrefetchKey, result: PrefetchResult): void {\n this.entries.set(prefetchMapKey(key), {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(key: PrefetchKey): PrefetchResult | undefined {\n const mapKey = prefetchMapKey(key);\n const entry = this.entries.get(mapKey);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(mapKey);\n return undefined;\n }\n return entry.result;\n }\n\n /** True if a ready or negative entry exists for this key. */\n has(key: PrefetchKey): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(key: PrefetchKey): PrefetchResult | undefined {\n const result = this.get(key);\n if (result !== undefined) {\n this.entries.delete(prefetchMapKey(key));\n }\n return result;\n }\n\n /**\n * Fetch or coalesce with an in-flight fetch for this key (TIM-1438).\n *\n * Concurrent callers (hover + click, repeated hovers) get the same\n * promise. On success the result is stored as a ready entry. On\n * NonRscResponse a negative entry is stored and the outcome is\n * `{ kind: 'non-route' }`. Other errors (network, version skew)\n * reject — the singleflight cleans up the key and subsequent callers\n * retry.\n *\n * The singleflight signal is passed to `doFetch` so a timed-out flight\n * aborts the underlying fetch rather than leaving it running.\n */\n fetchOrCoalesce(\n key: PrefetchKey,\n doFetch: (signal: AbortSignal) => Promise<PrefetchResult>,\n isNonRoute: (error: unknown) => boolean\n ): Promise<FlightOutcome> {\n // Capture the eviction generation before the flight starts. If an\n // action evicts caches while this flight is in progress, the gen\n // will have bumped and the stale result is discarded (TIM-1476).\n // The starting gen is also included in the outcome so joiners\n // that started after a gen bump can detect pre-invalidation\n // results (TIM-1464).\n const genAtStart = this.evictionGen;\n return this.flights.do(prefetchMapKey(key), async (signal) => {\n try {\n const result = await doFetch(signal);\n if (!signal.aborted && this.evictionGen === genAtStart) this.set(key, result);\n return { kind: 'ready' as const, result, startGen: genAtStart };\n } catch (err) {\n if (isNonRoute(err)) {\n if (!signal.aborted && this.evictionGen === genAtStart) this.setNegative(key);\n return { kind: 'non-route' as const, startGen: genAtStart };\n }\n throw err;\n }\n });\n }\n\n /**\n * Join an in-flight singleflight fetch if one exists for this key.\n * Returns the in-flight promise or undefined. Used by the click path to\n * coalesce with a hover prefetch without starting a new flight — when no\n * flight exists, the click issues its own fetch with the navigation's\n * abort signal so superseded navigations abort immediately (TIM-1438).\n */\n joinInflight(key: PrefetchKey): Promise<FlightOutcome> | undefined {\n return this.flights.get(prefetchMapKey(key)) as Promise<FlightOutcome> | undefined;\n }\n\n /**\n * Store a negative entry — the URL is not a route (non-RSC Content-Type).\n *\n * Keyed like every other entry even though \"not a route\" does not actually\n * vary by departing URL: a source-independent negative would be a second\n * keying rule to keep correct, and the only cost of the uniform one is a\n * repeated fetch for a link hovered from a second page.\n */\n setNegative(key: PrefetchKey): void {\n this.set(key, NEGATIVE_ENTRY);\n }\n\n /** Check if the entry is a negative cache entry (URL is not a route). */\n isNegative(key: PrefetchKey): boolean {\n return this.get(key) === NEGATIVE_ENTRY;\n }\n\n /**\n * Evict all ready entries and fence in-flight singleflights (TIM-1476).\n * Called after a server action that revalidated data — the mutation may\n * affect any route, not just the paths the server named. In-flight\n * singleflights are not aborted (they may carry post-mutation data),\n * but their results are discarded if they complete after eviction:\n * `fetchOrCoalesce` captures the generation before the flight and\n * skips the store when it has been bumped.\n *\n * Consumers that join an in-flight flight via `joinInflight` must\n * check `getEvictionGen()` before and after the await: if the gen\n * changed, the result predates the eviction and must be discarded\n * (codex on #1131 round 2).\n */\n clearReady(): void {\n this.entries.clear();\n this.evictionGen++;\n }\n\n getEvictionGen(): number {\n return this.evictionGen;\n }\n}\n","/**\n * How the client router reads the URLs it is handed.\n *\n * One parser, so the places that key or compare by URL — the history stack,\n * the navigation state a page renders with, the departing page sent as\n * `X-Timber-URL` — cannot disagree about what a URL says. They did: a\n * history entry stored under `navigate('/café')`'s spelling was looked up\n * under the address bar's `/caf%C3%A9`, and missed (TIM-1541).\n */\n\nconst BASE = 'http://localhost';\n\n/**\n * Parse a router URL. A URL that starts with \"/\" is a path — including one\n * that starts with \"//\": that is the pathname a document at\n * `https://host//a/b` reports, and resolved against a base it would parse as\n * a scheme-relative reference to host `a`. Anything else resolves against a\n * placeholder origin, so an absolute URL keeps its own.\n */\nexport function parseRouterUrl(url: string): URL {\n return url.startsWith('/') ? new URL(BASE + url) : new URL(url, BASE);\n}\n\n/**\n * The spelling a URL is stored and looked up under: the browser's own\n * pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one\n * key. The fragment is dropped — it is client-only.\n */\nexport function routerUrlKey(url: string): string {\n const parsed = parseRouterUrl(url);\n return parsed.pathname + parsed.search;\n}\n","/**\n * What it means for a page to be \"current\" on the client.\n *\n * One module owns every write that makes a navigation's destination the\n * current page, and the read that describes the current page back to the\n * server. Keeping them together is the point: `X-Timber-State-Tree` is\n * derived from the segment cache, so the thing that publishes and the thing\n * that reports have to agree about when a page becomes current.\n *\n * See design/19-client-navigation.md §\"State Update Invariants\".\n */\n\nimport { buildSegmentTree, type SegmentCache } from './segment-cache.ts';\nimport type { HistoryStack } from './history.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport {\n statusPageRendered,\n _setStatusPageRendered,\n onStatusPageRendered,\n _setOnStatusPageRendered,\n} from './state.ts';\n\n// ─── What a status page teaches the cache ─────────────────────────────────\n//\n// A status page replaces a subtree: a deny page lands at the segment owning\n// the matched file and nothing below it mounts; an `error.tsx` fallback\n// discards everything under the boundary that rendered it. `X-Timber-Segments`\n// nonetheless describes the whole chain the payload was built against — it\n// must, because a partial navigation picks its merge point out of it — so the\n// cache has to be told not to learn from such a tree.\n//\n// The HTTP status used to say so, and could not be trusted to: an RSC payload\n// response commits one macrotask after its first chunk, and a nested\n// component that denies after I/O puts its row in the stream after the\n// status line has gone out (TIM-1489). The only thing that reliably knows a\n// status page rendered is the status page itself, and the only moment that\n// matters is the commit that puts it on screen — so every status page the\n// framework produces is wrapped in `StatusPageMarker`, whose layout effect\n// reports on each commit that renders it. Layout effects run child-before-\n// parent, so the report lands before `NavigationRoot`'s publish of that\n// same commit, and never for a render React discards. Without Suspense\n// around the row, the transition cannot commit until the row has arrived, so\n// this covers the delayed nested case too, which no status ever could.\n//\n// The report also clears the cache on the spot, because not every commit\n// has a navigation to consume it: a deny row arriving inside a Suspense\n// boundary after its navigation published, or a status document being\n// hydrated, would otherwise leave a tree in the cache that is no longer on\n// screen. Consuming the flag at commit is what keeps the same navigation from\n// re-seeding it a moment later. Both are over-approximations — a page-level\n// deny leaves every layout standing — at the cost of one full render on the\n// next navigation.\n//\n// Slot boundaries do not report: a slot degrading is the page staying, and\n// the chain it mounted is the chain the header describes. See TIM-1356,\n// TIM-1495, design/04-authorization.md §\"Where a Deny Page Renders\".\n\n/**\n * Record that a status page for the main route is on screen. Called from\n * `StatusPageMarker`'s layout effect; consumed by the commit of the\n * navigation whose tree it belongs to, and acted on immediately for the\n * commits that have none.\n */\nexport function reportStatusPageRendered(): void {\n _setStatusPageRendered(true);\n onStatusPageRendered?.();\n}\n\n/** Everything a commit needs to describe the page it makes current. */\nexport interface NavigationCommitInput {\n payload: unknown;\n /** The params that payload published — replayed with it on popstate. */\n params: ParamsSource;\n /**\n * The rendered chain's metadata, or null/undefined when this commit\n * carries none at all — a revalidation payload, or a history entry\n * stored before the channel existed.\n *\n * An empty *array* is a different statement from an absent one: the\n * server rendered a route with no layout-bearing segments (a layoutless\n * app — the missing-root-layout check is a warning, not an error), so\n * the correct tree is the empty one. Collapsing the two left the\n * departing route's tree in place, which `treePaths` then reported as\n * mounted — enough to select an intercepting rewrite whose slot is not\n * on screen (TIM-1282).\n */\n segmentInfo?: SegmentInfo[] | null;\n /** When true, clear the segment cache if segmentInfo is absent\n * (popstate replay for entries without layout metadata). */\n clearSegmentCacheOnEmpty?: boolean;\n /**\n * Layouts the server skipped on this response (`X-Timber-Skipped-Segments`),\n * when it came from a fetch. Omitted by replays and revalidation.\n *\n * Together with `skipped` slot entries in `segmentInfo`, this decides\n * whether the payload can be *replayed*. A partial payload only renders\n * merged over the tree on screen, and a `skip=true` outlet resolves against\n * the slot content cache at render time — so a stored copy of either,\n * replayed later, shows whatever the client holds *then*, not what was on\n * screen when the entry committed. Such entries store a null payload and\n * traversals to them fetch instead. Decided here, not at the fetch call\n * sites, because there are three of those (`performNavigationFetch`,\n * `refresh()`, and uncached traversal) and a rule applied at one of them\n * holds by accident: `performNavigationFetch` had the check and\n * `fetchCommitAndRender` did not, so a back/forward fetch that was\n * answered with skips stored the holes (TIM-1432).\n */\n skippedSegments?: string[] | null;\n}\n\n/** Whether a response skipped layouts — its payload merges over the tree on screen. */\nexport function isPartialNavigation(skippedSegments: string[] | null | undefined): boolean {\n return skippedSegments != null && skippedSegments.length > 0;\n}\n\n/**\n * Whether a payload can stand on its own when replayed from the history\n * stack. See `NavigationCommitInput.skippedSegments`.\n */\nfunction isReplayable(opts: NavigationCommitInput): boolean {\n return !isPartialNavigation(opts.skippedSegments) && !hasSkippedSlot(opts.segmentInfo);\n}\n\nfunction hasSkippedSlot(segmentInfo: SegmentInfo[] | null | undefined): boolean {\n return segmentInfo?.some((s) => s.slot && s.skipped) ?? false;\n}\n\n/**\n * The metadata a committed page keeps — on its history entry, and as the\n * current page's `committedSegmentInfo()`. `skipped` describes the\n * *response* — \"this slot's content was omitted\" — and neither stores such\n * a payload (the entry stores null). Kept, the flag outlives the response:\n * `applyActionResult()` reuses the current page's metadata beside a full\n * re-render and would have that judged non-replayable too.\n */\nfunction storedSegmentInfo(segmentInfo: SegmentInfo[] | null | undefined) {\n if (!hasSkippedSlot(segmentInfo)) return segmentInfo;\n return segmentInfo!.map(({ skipped: _skipped, ...rest }) => rest);\n}\n\n/**\n * A navigation's destination, split into what a render needs and what a\n * commit publishes.\n */\nexport interface PreparedNavigation {\n /** The state the incoming tree renders with. Pure — safe before winning. */\n navState: NavigationState;\n /** Publishes the destination. Call only once the render has won. */\n commit: () => void;\n}\n\nexport interface NavigationCommitter {\n prepareNavigation(url: string, opts: NavigationCommitInput): PreparedNavigation;\n currentStateTree(): StateTree | undefined;\n /**\n * The segment metadata of the page the last commit made current, as that\n * commit recorded it — null when it carried none.\n *\n * Server-action responses carry no segment metadata, so a revalidation\n * re-renders the current page with this. It is the committer's own record\n * rather than a history-stack lookup: the stack is keyed by the URL string\n * a navigation was asked for, and the current page is known by\n * `window.location`'s spelling of it, and the two need not agree\n * (`/a?` against `/a`, a percent-encoded path against a decoded one).\n */\n committedSegmentInfo(): SegmentInfo[] | null;\n /** Whether segment reuse is currently suppressed (TIM-1466). */\n isSegmentReuseSuppressed(): boolean;\n /** Lift segment reuse suppression after fresh data has been fetched (TIM-1466). */\n restoreSegmentReuse(): void;\n}\n\n/**\n * Derive the navigation state (pathname + search) a URL renders with.\n *\n * Pure. The value travels with the tree it describes — callers pass it to\n * `wrapPayload`, and the router's record of the displayed tree keeps it\n * beside that tree — so there is no store to publish it to (TIM-1541).\n */\nexport function deriveNavigationState(url: string): NavigationState {\n // Params are not part of it. They travel with the payload and are published\n // by the one client-owned `ParamsProvider` as the new tree renders, which is\n // also what clears the previous route's — a route with no params of its own\n // still publishes an empty record (TIM-1294/TIM-1297, and the clearing\n // requirement from TIM-1285).\n const parsed = parseRouterUrl(url);\n return { pathname: parsed.pathname || '/', search: parsed.search };\n}\n\nexport function createNavigationCommitter(deps: {\n segmentCache: SegmentCache;\n historyStack: HistoryStack;\n /** Read at call time — the router's `clientSegmentCache` opt-in. */\n clientSegmentCache: () => boolean | undefined;\n}): NavigationCommitter {\n const { segmentCache, historyStack } = deps;\n\n // See `committedSegmentInfo`. Written only by a commit.\n let committedSegmentInfo: SegmentInfo[] | null = null;\n\n // See `reportStatusPageRendered`: a status page that commits with no\n // navigation to consume the report still empties the cache.\n _setOnStatusPageRendered(() => segmentCache.clear());\n\n /**\n * Update the segment cache from server-provided segment metadata.\n *\n * Runs whether or not `clientSegmentCache` is enabled: the tree is also\n * where the mounted tree paths come from, and those cross on every\n * navigation. What the flag gates is which parts get serialized — see\n * `currentStateTree`.\n */\n function updateSegmentCache(segmentInfo: SegmentInfo[]): void {\n const tree = buildSegmentTree(segmentInfo);\n if (tree) {\n segmentCache.set('/', tree);\n }\n }\n\n return {\n committedSegmentInfo: () => committedSegmentInfo,\n isSegmentReuseSuppressed: () => segmentCache.isReuseSuppressed(),\n restoreSegmentReuse: () => segmentCache.restoreReuse(),\n\n /**\n * The X-Timber-State-Tree to send with the next RSC request.\n *\n * Two different things travel on one header. `segments`/`slots` are the\n * caching opt-in and are omitted unless `clientSegmentCache` is on.\n * `treePaths` is how the server learns which route is actually mounted,\n * which stops being derivable from the address bar as soon as a modal is\n * open — so it crosses regardless (TIM-1282). Undefined when there is\n * nothing to say, so a no-op header never enters the `_rsc` cache key.\n *\n * Reads what the last *committed* navigation published, so a superseded\n * navigation's destination can never end up describing the mounted tree\n * (TIM-1301).\n */\n currentStateTree(): StateTree | undefined {\n const tree = segmentCache.serializeStateTree();\n if (deps.clientSegmentCache()) return tree;\n return tree.treePaths ? { segments: [], treePaths: tree.treePaths } : undefined;\n },\n\n /**\n * Prepare all navigation-owned state for a new page — without publishing\n * any of it. Every code path that changes the \"current page\" must go\n * through this function, which is what makes \"forgot a field\" impossible\n * by construction.\n *\n * Returns the destination's `NavigationState`, which is a pure function of\n * the URL and is what the incoming tree is *rendered* with, plus a\n * `commit` thunk that performs the writes that make a page current:\n * 1. Segment cache — update from server-provided segment metadata\n * 2. The current page's segment metadata (`committedSegmentInfo`)\n * 3. History stack — store the payload for instant back/forward replay\n *\n * Pathname and search are not written here: they are the returned\n * `navState`, which the tree renders with and the router's record of the\n * displayed tree keeps (browser-entry/router-init.ts `publishTree`).\n *\n * Nothing is written until `commit()` runs, and on a transitioned\n * navigation it runs only once the transition is known to have won — see\n * `renderViaTransition` and `NavigationRoot`. A navigation superseded\n * while its payload was in flight never calls it, so the cache, the\n * pathname the client reports and the history stack all keep describing\n * the route still on screen (TIM-1301).\n *\n * Callers with state of their own to publish — the address bar, the\n * client's record of the mounted tree — wrap this thunk rather than\n * commit beside it, so there stays exactly one moment at which a page\n * becomes current.\n */\n prepareNavigation(url: string, opts: NavigationCommitInput): PreparedNavigation {\n const navState = deriveNavigationState(url);\n const payload = isReplayable(opts) ? opts.payload : null;\n\n // The tree this navigation renders has not rendered yet. Whatever a\n // boundary reported before now belongs to a commit that had no\n // navigation to consume it — a hydration, a row that arrived inside a\n // Suspense boundary after its navigation had published — and must not\n // be charged to this one.\n _setStatusPageRendered(false);\n\n return {\n navState,\n commit() {\n // A tree in which a boundary rendered a status page is not one to\n // cache — see the module note. Read at commit rather than at\n // prepare because that is when the boundary has spoken: the row it\n // renders may not have existed when the response headers were read.\n // The history entry records the same thing, or a traversal back to\n // this URL would replay the metadata this drops.\n const cacheable = !statusPageRendered;\n _setStatusPageRendered(false);\n const segmentInfo = cacheable ? opts.segmentInfo : [];\n\n if (segmentInfo && segmentInfo.length > 0) {\n updateSegmentCache(segmentInfo);\n } else if (segmentInfo?.length === 0 || opts.clearSegmentCacheOnEmpty) {\n segmentCache.clear();\n }\n\n committedSegmentInfo = storedSegmentInfo(segmentInfo) ?? null;\n\n historyStack.push(url, {\n payload,\n params: opts.params,\n segmentInfo: committedSegmentInfo,\n });\n },\n };\n },\n };\n}\n","'use client';\n\n/**\n * The one way a status page tells the router it is on screen.\n *\n * A status page replaces a subtree, and the segment cache must not learn a\n * chain that never mounted (see `navigation-commit.ts` §\"What a status page\n * teaches the cache\"). Status pages are produced in three places — an\n * in-tree catch site rendering the page it owns, the server's fallback\n * renderers, and a client boundary rendering its fallback for a Flight row —\n * and every one of them wraps the page in this marker, so the report does\n * not depend on which producer it was. In particular the in-tree case, the\n * common `access.ts` deny, never involves a client boundary at all.\n *\n * A layout effect, on every commit that renders the marker rather than on\n * mount only: React reuses the fiber when one status page is replaced by\n * another at the same position, and the second one must report too. Layout\n * effects run child-before-parent, so the report lands before the ancestor\n * `NavigationRoot` publishes the same commit, and never for a render React\n * discards. Idempotent, so StrictMode's double invocation and a status page\n * re-rendering on its own state are harmless. See TIM-1495.\n */\n\nimport { useLayoutEffect, type ReactNode } from 'react';\nimport { reportStatusPageRendered } from './navigation-commit.ts';\n\nexport function StatusPageMarker({ children }: { children: ReactNode }): ReactNode {\n useLayoutEffect(() => {\n reportStatusPageRendered();\n });\n return children;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,IAAa,sBAAsB;;;;;;;AC2DnC,IAAa,eAAb,MAA0B;CACxB;;;;;;;;;CASA,qBAA6B;CAC7B,kBAA0B;CAE1B,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;EACZ,KAAK,kBAAkB,KAAK;CAC9B;;;;;;;;;CAUA,kBAAwB;EACtB,KAAK;CACP;;;;;;CAOA,eAAqB;EACnB,KAAK,kBAAkB,KAAK;CAC9B;;CAGA,oBAA6B;E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C8POawuF.js","names":[],"sources":["../../src/shared/rsc-error-envelope.ts","../../src/client/segment-cache.ts","../../src/client/router-url.ts","../../src/client/navigation-commit.ts","../../src/client/status-page-marker.tsx"],"sourcesContent":["/**\n * The hard-navigate error envelope shared by the server and the client router.\n *\n * A client-navigation (RSC) request cannot carry an error *page* — the response\n * body must be Flight data or the decoder crashes. Instead the server answers\n * with this envelope: an `X-Timber-Error: 1` header and a minimal JSON body.\n * The client treats it as \"give up on SPA navigation and hard-navigate\", and\n * the resulting document request renders the real error page as HTML.\n *\n * The header name lives here so the four server producers and the single\n * client consumer cannot drift apart. See design/10-error-handling.md\n * §\"Error Page Rendering for Client Navigation\".\n */\n\n/** Header the client checks to decide whether to hard-navigate. */\nexport const TIMBER_ERROR_HEADER = 'X-Timber-Error';\n","// Segment Cache — stores the mounted segment tree and prefetched payloads\n// See design/19-client-navigation.md for architecture details.\n\nimport type { PublishedParams } from '../shared/payload-root.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport { createSingleflight } from '../cache/singleflight.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** A prefetched RSC result with optional segment metadata. */\nexport interface PrefetchResult {\n payload: unknown;\n /**\n * Completion of the full Flight stream, when the prefetch is still decoding.\n * Carried through to the navigation that consumes the entry so a decode\n * failure reaches *that* navigation's recovery rather than dying with the\n * prefetch (TIM-1275).\n */\n decodePromise?: Promise<void> | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo?: SegmentInfo[] | null;\n /**\n * The params published beside `payload`, split off the same payload root.\n * Carried so a consumed prefetch publishes the params of the tree it is\n * about to render, and not the ones already on screen.\n */\n params?: PublishedParams | Promise<PublishedParams>;\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 /**\n * The segment's `app/` directory path, groups included (e.g. `/(browse)/feed`).\n * Undefined for slot nodes and for servers that predate the field.\n */\n treePath?: 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 * Content key for slot nodes — opaque string the server computed from\n * owner parts, slot name, entry file, and slot params. Advertised back\n * to the server so it can decide skips by key membership (TIM-1370).\n */\n contentKey?: 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 * Monotonic counter. Bumped by `invalidateReuse()` (TIM-1466).\n * `serializeStateTree` suppresses `segments` and `slots` when\n * `reuseInvalidatedAt > reuseRestoredAt`. Only `restoreReuse()`\n * advances `reuseRestoredAt` — `set()` does not, because a\n * pre-invalidation navigation's commit thunk would lift suppression\n * before a post-invalidation request has been sent (codex on #1167).\n */\n private reuseInvalidatedAt = 0;\n private reuseRestoredAt = 0;\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 this.reuseRestoredAt = this.reuseInvalidatedAt;\n }\n\n /**\n * Suppress segment and slot reuse without destroying the tree\n * structure (TIM-1466). `serializeStateTree` sends empty\n * `segments`/`slots` (forcing a full render) while `treePaths`\n * still reflects the mounted tree for interception scoping.\n * Call `restoreReuse()` once post-invalidation data has been\n * fetched and committed.\n */\n invalidateReuse(): void {\n this.reuseInvalidatedAt++;\n }\n\n /**\n * Lift reuse suppression. Called after the segment cache has been\n * rebuilt from a response that was fetched with suppression active\n * (i.e. the server sent a full render). Safe to call idempotently.\n */\n restoreReuse(): void {\n this.reuseRestoredAt = this.reuseInvalidatedAt;\n }\n\n /** Whether segment/slot reuse is currently suppressed (TIM-1466). */\n isReuseSuppressed(): boolean {\n return this.reuseInvalidatedAt > this.reuseRestoredAt;\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 * `treePaths` is collected UNFILTERED, unlike `segments` and `slots`. Those\n * two answer \"what may the server skip re-rendering?\", so every reason a\n * segment cannot be reused is a reason to leave it out. `treePaths` answers\n * \"what is mounted right now?\" for interception scoping — a request-dependent\n * layout is still on screen, and dropping it would silently narrow the scope\n * the server sees and cancel a modal that should open (TIM-1282).\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 const treePaths: string[] = [];\n const suppressed = this.reuseInvalidatedAt > this.reuseRestoredAt;\n if (this.root) {\n if (!suppressed) {\n collectSyncSegments(this.root, segments, mergeableFilter);\n collectSyncSlots(this.root, slots);\n }\n collectTreePaths(this.root, treePaths);\n }\n const tree: StateTree = { segments };\n if (slots.length > 0) {\n tree.slots = slots;\n }\n if (treePaths.length > 0) {\n tree.treePaths = treePaths;\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/**\n * Recursively collect the `app/` directory path of every mounted segment.\n *\n * Slots are not walked: a slot's own sub-tree can never own an intercepting\n * slot's scope, because scopes are always ordinary segments (`interception.ts`\n * derives one from the slot owner's ancestor chain).\n */\nfunction collectTreePaths(node: SegmentNode, out: string[]): void {\n if (node.treePath) out.push(node.treePath);\n for (const child of node.children.values()) {\n collectTreePaths(child, out);\n }\n}\n\n/**\n * Recursively collect content keys from cacheable slots.\n *\n * The server advertises a content key per slot on every render (TIM-1370),\n * encoding the owner's URL parts, the slot name, the matched entry file,\n * and the slot's params. The client stores this key and sends it back on\n * the next navigation so the server can decide skips by key membership —\n * no departing URL reconstruction needed.\n */\nfunction collectSyncSlots(node: SegmentNode, out: string[]): void {\n if (node.slots) {\n for (const slot of node.slots.values()) {\n if (!slot.isRequestDependent && !slot.denied && slot.contentKey) {\n out.push(slot.contentKey);\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 * 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 treePath: info.treePath,\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 contentKey: slotInfo.contentKey,\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 ReadyEntry {\n result: PrefetchResult;\n expiresAt: number;\n}\n\n/** Sentinel value for negative cache entries (URL is not a route). */\nconst NEGATIVE_ENTRY: PrefetchResult = Object.freeze({ payload: null });\n\n/**\n * Timeout for the in-flight singleflight (TIM-1438). Per CLAUDE.md's\n * singleflight rule: \"Never write a coalescing Map without a timeout.\"\n * A hung prefetch cannot block clicks or suppress hovers forever.\n */\nconst PREFETCH_SINGLEFLIGHT_TIMEOUT_MS = 5_000;\n\n/**\n * Identifies a prefetched payload. A payload is addressed by *every* input that\n * changes the server's answer, not by the destination alone.\n *\n * The server's answer for a destination depends on where the request came\n * from — that is the whole mechanism behind intercepting routes, and it also\n * drives slot-skip resolution. A prefetch issued from `/gallery` is a modal\n * payload; the same URL prefetched from `/` is the full page. Keying on the\n * destination alone let the first click after a hover be answered with\n * whichever variant happened to be fetched (TIM-1265).\n *\n * `from` alone stopped being enough in TIM-1282. It is a pathname, and once\n * interception scope comes from the rendered tree rather than the address, one\n * pathname no longer names one source tree: `/photo/1` is the address both for\n * a modal open over `(browse)` and for `(landing)`'s canonical page. A key\n * without the scope hands the modal payload to the canonical page's click,\n * which renders it without the server's scope check ever running.\n *\n * The two reads happen at different instants — `scope` is sampled at hover and\n * again at click — which is why a tree that changed in between produces a\n * *miss* and a refetch rather than a wrong hit.\n */\nexport interface PrefetchKey {\n /** Destination URL — hash-less `pathname + search`, as navigate() fetches it. */\n url: string;\n /** Departing pathname — the `X-Timber-URL` the prefetch was issued with. */\n from: string;\n /**\n * The rendered scope the prefetch was issued with — the `treePaths` half of\n * `X-Timber-State-Tree`, joined. Empty when none crossed.\n */\n scope: string;\n}\n\n/**\n * Compose the map key. Length-prefixed rather than delimiter-joined for the\n * same reason `shared/rsc-cache-key.ts` is: any delimiter is forgeable by a\n * value containing it, and a URL may contain any character a delimiter could.\n */\nfunction prefetchMapKey(key: PrefetchKey): string {\n return `${key.from.length}:${key.from}:${key.scope.length}:${key.scope}:${key.url}`;\n}\n\n/**\n * The `scope` half of a `PrefetchKey`, derived from the state tree that will\n * actually be sent. Taking it from the header value rather than re-walking the\n * cache is the point: the key varies by exactly what the request varies by.\n */\nexport function prefetchScopeOf(stateTree: StateTree | undefined): string {\n return stateTree?.treePaths?.join('\\u0000') ?? '';\n}\n\n/** Outcome of a prefetch flight — discriminated so NonRscResponse is a\n * success (stores a negative entry) rather than a rejection.\n * `startGen` is the eviction generation at flight start — joiners that\n * started after a gen bump must reject pre-invalidation results (TIM-1464). */\nexport type FlightOutcome =\n | { kind: 'ready'; result: PrefetchResult; startGen: number }\n | { kind: 'non-route'; startGen: number };\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 * In-flight dedup (TIM-1438): concurrent fetches for the same key are\n * coalesced by a `createSingleflight` instance. A hover starts a flight;\n * a click for the same key joins it instead of issuing a duplicate. The\n * singleflight enforces a 5-second timeout and cleans up automatically\n * on settlement.\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, ReadyEntry>();\n private flights = createSingleflight({ timeoutMs: PREFETCH_SINGLEFLIGHT_TIMEOUT_MS });\n private evictionGen = 0;\n\n set(key: PrefetchKey, result: PrefetchResult): void {\n this.entries.set(prefetchMapKey(key), {\n result,\n expiresAt: Date.now() + PrefetchCache.TTL_MS,\n });\n }\n\n get(key: PrefetchKey): PrefetchResult | undefined {\n const mapKey = prefetchMapKey(key);\n const entry = this.entries.get(mapKey);\n if (!entry) return undefined;\n if (Date.now() >= entry.expiresAt) {\n this.entries.delete(mapKey);\n return undefined;\n }\n return entry.result;\n }\n\n /** True if a ready or negative entry exists for this key. */\n has(key: PrefetchKey): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Get and remove the entry (used when navigation consumes a prefetch) */\n consume(key: PrefetchKey): PrefetchResult | undefined {\n const result = this.get(key);\n if (result !== undefined) {\n this.entries.delete(prefetchMapKey(key));\n }\n return result;\n }\n\n /**\n * Fetch or coalesce with an in-flight fetch for this key (TIM-1438).\n *\n * Concurrent callers (hover + click, repeated hovers) get the same\n * promise. On success the result is stored as a ready entry. On\n * NonRscResponse a negative entry is stored and the outcome is\n * `{ kind: 'non-route' }`. Other errors (network, version skew)\n * reject — the singleflight cleans up the key and subsequent callers\n * retry.\n *\n * The singleflight signal is passed to `doFetch` so a timed-out flight\n * aborts the underlying fetch rather than leaving it running.\n */\n fetchOrCoalesce(\n key: PrefetchKey,\n doFetch: (signal: AbortSignal) => Promise<PrefetchResult>,\n isNonRoute: (error: unknown) => boolean\n ): Promise<FlightOutcome> {\n // Capture the eviction generation before the flight starts. If an\n // action evicts caches while this flight is in progress, the gen\n // will have bumped and the stale result is discarded (TIM-1476).\n // The starting gen is also included in the outcome so joiners\n // that started after a gen bump can detect pre-invalidation\n // results (TIM-1464).\n const genAtStart = this.evictionGen;\n return this.flights.do(prefetchMapKey(key), async (signal) => {\n try {\n const result = await doFetch(signal);\n if (!signal.aborted && this.evictionGen === genAtStart) this.set(key, result);\n return { kind: 'ready' as const, result, startGen: genAtStart };\n } catch (err) {\n if (isNonRoute(err)) {\n if (!signal.aborted && this.evictionGen === genAtStart) this.setNegative(key);\n return { kind: 'non-route' as const, startGen: genAtStart };\n }\n throw err;\n }\n });\n }\n\n /**\n * Join an in-flight singleflight fetch if one exists for this key.\n * Returns the in-flight promise or undefined. Used by the click path to\n * coalesce with a hover prefetch without starting a new flight — when no\n * flight exists, the click issues its own fetch with the navigation's\n * abort signal so superseded navigations abort immediately (TIM-1438).\n */\n joinInflight(key: PrefetchKey): Promise<FlightOutcome> | undefined {\n return this.flights.get(prefetchMapKey(key)) as Promise<FlightOutcome> | undefined;\n }\n\n /**\n * Store a negative entry — the URL is not a route (non-RSC Content-Type).\n *\n * Keyed like every other entry even though \"not a route\" does not actually\n * vary by departing URL: a source-independent negative would be a second\n * keying rule to keep correct, and the only cost of the uniform one is a\n * repeated fetch for a link hovered from a second page.\n */\n setNegative(key: PrefetchKey): void {\n this.set(key, NEGATIVE_ENTRY);\n }\n\n /** Check if the entry is a negative cache entry (URL is not a route). */\n isNegative(key: PrefetchKey): boolean {\n return this.get(key) === NEGATIVE_ENTRY;\n }\n\n /**\n * Evict all ready entries and fence in-flight singleflights (TIM-1476).\n * Called after a server action that revalidated data — the mutation may\n * affect any route, not just the paths the server named. In-flight\n * singleflights are not aborted (they may carry post-mutation data),\n * but their results are discarded if they complete after eviction:\n * `fetchOrCoalesce` captures the generation before the flight and\n * skips the store when it has been bumped.\n *\n * Consumers that join an in-flight flight via `joinInflight` must\n * check `getEvictionGen()` before and after the await: if the gen\n * changed, the result predates the eviction and must be discarded\n * (codex on #1131 round 2).\n */\n clearReady(): void {\n this.entries.clear();\n this.evictionGen++;\n }\n\n getEvictionGen(): number {\n return this.evictionGen;\n }\n}\n","/**\n * How the client router reads the URLs it is handed.\n *\n * One parser, so the places that key or compare by URL — the history stack,\n * the navigation state a page renders with, the departing page sent as\n * `X-Timber-URL` — cannot disagree about what a URL says. They did: a\n * history entry stored under `navigate('/café')`'s spelling was looked up\n * under the address bar's `/caf%C3%A9`, and missed (TIM-1541).\n */\n\nconst BASE = 'http://localhost';\n\n/**\n * Parse a router URL. A URL that starts with \"/\" is a path — including one\n * that starts with \"//\": that is the pathname a document at\n * `https://host//a/b` reports, and resolved against a base it would parse as\n * a scheme-relative reference to host `a`. Anything else resolves against a\n * placeholder origin, so an absolute URL keeps its own.\n */\nexport function parseRouterUrl(url: string): URL {\n return url.startsWith('/') ? new URL(BASE + url) : new URL(url, BASE);\n}\n\n/**\n * The spelling a URL is stored and looked up under: the browser's own\n * pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one\n * key. The fragment is dropped — it is client-only.\n */\nexport function routerUrlKey(url: string): string {\n const parsed = parseRouterUrl(url);\n return parsed.pathname + parsed.search;\n}\n","/**\n * What it means for a page to be \"current\" on the client.\n *\n * One module owns every write that makes a navigation's destination the\n * current page, and the read that describes the current page back to the\n * server. Keeping them together is the point: `X-Timber-State-Tree` is\n * derived from the segment cache, so the thing that publishes and the thing\n * that reports have to agree about when a page becomes current.\n *\n * See design/19-client-navigation.md §\"State Update Invariants\".\n */\n\nimport { buildSegmentTree, type SegmentCache } from './segment-cache.ts';\nimport type { HistoryStack } from './history.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport {\n statusPageRendered,\n _setStatusPageRendered,\n onStatusPageRendered,\n _setOnStatusPageRendered,\n} from './state.ts';\n\n// ─── What a status page teaches the cache ─────────────────────────────────\n//\n// A status page replaces a subtree: a deny page lands at the segment owning\n// the matched file and nothing below it mounts; an `error.tsx` fallback\n// discards everything under the boundary that rendered it. `X-Timber-Segments`\n// nonetheless describes the whole chain the payload was built against — it\n// must, because a partial navigation picks its merge point out of it — so the\n// cache has to be told not to learn from such a tree.\n//\n// The HTTP status used to say so, and could not be trusted to: an RSC payload\n// response commits one macrotask after its first chunk, and a nested\n// component that denies after I/O puts its row in the stream after the\n// status line has gone out (TIM-1489). The only thing that reliably knows a\n// status page rendered is the status page itself, and the only moment that\n// matters is the commit that puts it on screen — so every status page the\n// framework produces is wrapped in `StatusPageMarker`, whose layout effect\n// reports on each commit that renders it. Layout effects run child-before-\n// parent, so the report lands before `NavigationRoot`'s publish of that\n// same commit, and never for a render React discards. Without Suspense\n// around the row, the transition cannot commit until the row has arrived, so\n// this covers the delayed nested case too, which no status ever could.\n//\n// The report also clears the cache on the spot, because not every commit\n// has a navigation to consume it: a deny row arriving inside a Suspense\n// boundary after its navigation published, or a status document being\n// hydrated, would otherwise leave a tree in the cache that is no longer on\n// screen. Consuming the flag at commit is what keeps the same navigation from\n// re-seeding it a moment later. Both are over-approximations — a page-level\n// deny leaves every layout standing — at the cost of one full render on the\n// next navigation.\n//\n// Slot boundaries do not report: a slot degrading is the page staying, and\n// the chain it mounted is the chain the header describes. See TIM-1356,\n// TIM-1495, design/04-authorization.md §\"Where a Deny Page Renders\".\n\n/**\n * Record that a status page for the main route is on screen. Called from\n * `StatusPageMarker`'s layout effect; consumed by the commit of the\n * navigation whose tree it belongs to, and acted on immediately for the\n * commits that have none.\n */\nexport function reportStatusPageRendered(): void {\n _setStatusPageRendered(true);\n onStatusPageRendered?.();\n}\n\n/** Everything a commit needs to describe the page it makes current. */\nexport interface NavigationCommitInput {\n payload: unknown;\n /** The params that payload published — replayed with it on popstate. */\n params: ParamsSource;\n /**\n * The rendered chain's metadata, or null/undefined when this commit\n * carries none at all — a revalidation payload, or a history entry\n * stored before the channel existed.\n *\n * An empty *array* is a different statement from an absent one: the\n * server rendered a route with no layout-bearing segments (a layoutless\n * app — the missing-root-layout check is a warning, not an error), so\n * the correct tree is the empty one. Collapsing the two left the\n * departing route's tree in place, which `treePaths` then reported as\n * mounted — enough to select an intercepting rewrite whose slot is not\n * on screen (TIM-1282).\n */\n segmentInfo?: SegmentInfo[] | null;\n /** When true, clear the segment cache if segmentInfo is absent\n * (popstate replay for entries without layout metadata). */\n clearSegmentCacheOnEmpty?: boolean;\n /**\n * Layouts the server skipped on this response (`X-Timber-Skipped-Segments`),\n * when it came from a fetch. Omitted by replays and revalidation.\n *\n * Together with `skipped` slot entries in `segmentInfo`, this decides\n * whether the payload can be *replayed*. A partial payload only renders\n * merged over the tree on screen, and a `skip=true` outlet resolves against\n * the slot content cache at render time — so a stored copy of either,\n * replayed later, shows whatever the client holds *then*, not what was on\n * screen when the entry committed. Such entries store a null payload and\n * traversals to them fetch instead. Decided here, not at the fetch call\n * sites, because there are three of those (`performNavigationFetch`,\n * `refresh()`, and uncached traversal) and a rule applied at one of them\n * holds by accident: `performNavigationFetch` had the check and\n * `fetchCommitAndRender` did not, so a back/forward fetch that was\n * answered with skips stored the holes (TIM-1432).\n */\n skippedSegments?: string[] | null;\n}\n\n/** Whether a response skipped layouts — its payload merges over the tree on screen. */\nexport function isPartialNavigation(skippedSegments: string[] | null | undefined): boolean {\n return skippedSegments != null && skippedSegments.length > 0;\n}\n\n/**\n * Whether a payload can stand on its own when replayed from the history\n * stack. See `NavigationCommitInput.skippedSegments`.\n */\nfunction isReplayable(opts: NavigationCommitInput): boolean {\n return !isPartialNavigation(opts.skippedSegments) && !hasSkippedSlot(opts.segmentInfo);\n}\n\nfunction hasSkippedSlot(segmentInfo: SegmentInfo[] | null | undefined): boolean {\n return segmentInfo?.some((s) => s.slot && s.skipped) ?? false;\n}\n\n/**\n * The metadata a committed page keeps — on its history entry, and as the\n * current page's `committedSegmentInfo()`. `skipped` describes the\n * *response* — \"this slot's content was omitted\" — and neither stores such\n * a payload (the entry stores null). Kept, the flag outlives the response:\n * `applyActionResult()` reuses the current page's metadata beside a full\n * re-render and would have that judged non-replayable too.\n */\nfunction storedSegmentInfo(segmentInfo: SegmentInfo[] | null | undefined) {\n if (!hasSkippedSlot(segmentInfo)) return segmentInfo;\n return segmentInfo!.map(({ skipped: _skipped, ...rest }) => rest);\n}\n\n/**\n * A navigation's destination, split into what a render needs and what a\n * commit publishes.\n */\nexport interface PreparedNavigation {\n /** The state the incoming tree renders with. Pure — safe before winning. */\n navState: NavigationState;\n /** Publishes the destination. Call only once the render has won. */\n commit: () => void;\n}\n\nexport interface NavigationCommitter {\n prepareNavigation(url: string, opts: NavigationCommitInput): PreparedNavigation;\n currentStateTree(): StateTree | undefined;\n /**\n * The segment metadata of the page the last commit made current, as that\n * commit recorded it — null when it carried none.\n *\n * Server-action responses carry no segment metadata, so a revalidation\n * re-renders the current page with this. It is the committer's own record\n * rather than a history-stack lookup: the stack is keyed by the URL string\n * a navigation was asked for, and the current page is known by\n * `window.location`'s spelling of it, and the two need not agree\n * (`/a?` against `/a`, a percent-encoded path against a decoded one).\n */\n committedSegmentInfo(): SegmentInfo[] | null;\n /** Whether segment reuse is currently suppressed (TIM-1466). */\n isSegmentReuseSuppressed(): boolean;\n /** Lift segment reuse suppression after fresh data has been fetched (TIM-1466). */\n restoreSegmentReuse(): void;\n}\n\n/**\n * Derive the navigation state (pathname + search) a URL renders with.\n *\n * Pure. The value travels with the tree it describes — callers pass it to\n * `wrapPayload`, and the router's record of the displayed tree keeps it\n * beside that tree — so there is no store to publish it to (TIM-1541).\n */\nexport function deriveNavigationState(url: string): NavigationState {\n // Params are not part of it. They travel with the payload and are published\n // by the one client-owned `ParamsProvider` as the new tree renders, which is\n // also what clears the previous route's — a route with no params of its own\n // still publishes an empty record (TIM-1294/TIM-1297, and the clearing\n // requirement from TIM-1285).\n const parsed = parseRouterUrl(url);\n return { pathname: parsed.pathname || '/', search: parsed.search };\n}\n\nexport function createNavigationCommitter(deps: {\n segmentCache: SegmentCache;\n historyStack: HistoryStack;\n /** Read at call time — the router's `clientSegmentCache` opt-in. */\n clientSegmentCache: () => boolean | undefined;\n}): NavigationCommitter {\n const { segmentCache, historyStack } = deps;\n\n // See `committedSegmentInfo`. Written only by a commit.\n let committedSegmentInfo: SegmentInfo[] | null = null;\n\n // See `reportStatusPageRendered`: a status page that commits with no\n // navigation to consume the report still empties the cache.\n _setOnStatusPageRendered(() => segmentCache.clear());\n\n /**\n * Update the segment cache from server-provided segment metadata.\n *\n * Runs whether or not `clientSegmentCache` is enabled: the tree is also\n * where the mounted tree paths come from, and those cross on every\n * navigation. What the flag gates is which parts get serialized — see\n * `currentStateTree`.\n */\n function updateSegmentCache(segmentInfo: SegmentInfo[]): void {\n const tree = buildSegmentTree(segmentInfo);\n if (tree) {\n segmentCache.set('/', tree);\n }\n }\n\n return {\n committedSegmentInfo: () => committedSegmentInfo,\n isSegmentReuseSuppressed: () => segmentCache.isReuseSuppressed(),\n restoreSegmentReuse: () => segmentCache.restoreReuse(),\n\n /**\n * The X-Timber-State-Tree to send with the next RSC request.\n *\n * Two different things travel on one header. `segments`/`slots` are the\n * caching opt-in and are omitted unless `clientSegmentCache` is on.\n * `treePaths` is how the server learns which route is actually mounted,\n * which stops being derivable from the address bar as soon as a modal is\n * open — so it crosses regardless (TIM-1282). Undefined when there is\n * nothing to say, so a no-op header never enters the `_rsc` cache key.\n *\n * Reads what the last *committed* navigation published, so a superseded\n * navigation's destination can never end up describing the mounted tree\n * (TIM-1301).\n */\n currentStateTree(): StateTree | undefined {\n const tree = segmentCache.serializeStateTree();\n if (deps.clientSegmentCache()) return tree;\n return tree.treePaths ? { segments: [], treePaths: tree.treePaths } : undefined;\n },\n\n /**\n * Prepare all navigation-owned state for a new page — without publishing\n * any of it. Every code path that changes the \"current page\" must go\n * through this function, which is what makes \"forgot a field\" impossible\n * by construction.\n *\n * Returns the destination's `NavigationState`, which is a pure function of\n * the URL and is what the incoming tree is *rendered* with, plus a\n * `commit` thunk that performs the writes that make a page current:\n * 1. Segment cache — update from server-provided segment metadata\n * 2. The current page's segment metadata (`committedSegmentInfo`)\n * 3. History stack — store the payload for instant back/forward replay\n *\n * Pathname and search are not written here: they are the returned\n * `navState`, which the tree renders with and the router's record of the\n * displayed tree keeps (browser-entry/router-init.ts `publishTree`).\n *\n * Nothing is written until `commit()` runs, and on a transitioned\n * navigation it runs only once the transition is known to have won — see\n * `renderViaTransition` and `NavigationRoot`. A navigation superseded\n * while its payload was in flight never calls it, so the cache, the\n * pathname the client reports and the history stack all keep describing\n * the route still on screen (TIM-1301).\n *\n * Callers with state of their own to publish — the address bar, the\n * client's record of the mounted tree — wrap this thunk rather than\n * commit beside it, so there stays exactly one moment at which a page\n * becomes current.\n */\n prepareNavigation(url: string, opts: NavigationCommitInput): PreparedNavigation {\n const navState = deriveNavigationState(url);\n const payload = isReplayable(opts) ? opts.payload : null;\n\n // The tree this navigation renders has not rendered yet. Whatever a\n // boundary reported before now belongs to a commit that had no\n // navigation to consume it — a hydration, a row that arrived inside a\n // Suspense boundary after its navigation had published — and must not\n // be charged to this one.\n _setStatusPageRendered(false);\n\n return {\n navState,\n commit() {\n // A tree in which a boundary rendered a status page is not one to\n // cache — see the module note. Read at commit rather than at\n // prepare because that is when the boundary has spoken: the row it\n // renders may not have existed when the response headers were read.\n // The history entry records the same thing, or a traversal back to\n // this URL would replay the metadata this drops.\n const cacheable = !statusPageRendered;\n _setStatusPageRendered(false);\n const segmentInfo = cacheable ? opts.segmentInfo : [];\n\n if (segmentInfo && segmentInfo.length > 0) {\n updateSegmentCache(segmentInfo);\n } else if (segmentInfo?.length === 0 || opts.clearSegmentCacheOnEmpty) {\n segmentCache.clear();\n }\n\n committedSegmentInfo = storedSegmentInfo(segmentInfo) ?? null;\n\n historyStack.push(url, {\n payload,\n params: opts.params,\n segmentInfo: committedSegmentInfo,\n });\n },\n };\n },\n };\n}\n","'use client';\n\n/**\n * The one way a status page tells the router it is on screen.\n *\n * A status page replaces a subtree, and the segment cache must not learn a\n * chain that never mounted (see `navigation-commit.ts` §\"What a status page\n * teaches the cache\"). Status pages are produced in three places — an\n * in-tree catch site rendering the page it owns, the server's fallback\n * renderers, and a client boundary rendering its fallback for a Flight row —\n * and every one of them wraps the page in this marker, so the report does\n * not depend on which producer it was. In particular the in-tree case, the\n * common `access.ts` deny, never involves a client boundary at all.\n *\n * A layout effect, on every commit that renders the marker rather than on\n * mount only: React reuses the fiber when one status page is replaced by\n * another at the same position, and the second one must report too. Layout\n * effects run child-before-parent, so the report lands before the ancestor\n * `NavigationRoot` publishes the same commit, and never for a render React\n * discards. Idempotent, so StrictMode's double invocation and a status page\n * re-rendering on its own state are harmless. See TIM-1495.\n */\n\nimport { useLayoutEffect, type ReactNode } from 'react';\nimport { reportStatusPageRendered } from './navigation-commit.ts';\n\nexport function StatusPageMarker({ children }: { children: ReactNode }): ReactNode {\n useLayoutEffect(() => {\n reportStatusPageRendered();\n });\n return children;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,IAAa,sBAAsB;;;;;;;AC2DnC,IAAa,eAAb,MAA0B;CACxB;;;;;;;;;CASA,qBAA6B;CAC7B,kBAA0B;CAE1B,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;EACZ,KAAK,kBAAkB,KAAK;CAC9B;;;;;;;;;CAUA,kBAAwB;EACtB,KAAK;CACP;;;;;;CAOA,eAAqB;EACnB,KAAK,kBAAkB,KAAK;CAC9B;;CAGA,oBAA6B;EAC3B,OAAO,KAAK,qBAAqB,KAAK;CACxC;;;;;;;;;;;;;;;;;;;;;CAsBA,mBAAmB,iBAA0C;EAC3D,MAAM,WAAqB,CAAC;EAC5B,MAAM,QAAkB,CA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IjD,+BAA+B,aAAa,MAAM,CAAC;;;;;;;;;CAUnD,SAAS,mBAAmB,aAAkC;EAC5D,MAAM,OAAO,iBAAiB,WAAW;EACzC,IAAI,MACF,aAAa,IAAI,KAAK,IAAI;CAE9B;CAEA,OAAO;EACL,4BAA4B;EAC5B,gCAAgC,aAAa,kBAAkB;EAC/D,2BAA2B,aAAa,aAAa;;;;;;;;;;;;;;;EAgBrD,mBAA0C;GACxC,MAAM,OAAO,aAAa,mBAAmB;GAC7C,IAAI,KAAK,mBAAmB,GAAG,OAAO;GACtC,OAAO,KAAK,YAAY;IAAE,UAAU,CAAC;IAAG,WAAW,KAAK;GAAU,IAAI,KAAA;EACxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA,kBAAkB,KAAa,MAAiD;GAC9E,MAAM,WAAW,sBAAsB,GAAG;GAC1C,MAAM,UAAU,aAAa,IAAI,IAAI,KAAK,UAAU;GAOpD,uBAAuB,KAAK;GAE5B,OAAO;IACL;IACA,SAAS;KAOP,MAAM,YAAY,CAAC;KACnB,uBAAuB,KAAK;KAC5B,MAAM,cAAc,YAAY,KAAK,cAAc,CAAC;KAEpD,IAAI,eAAe,YAAY,SAAS,GACtC,mBAAmB,WAAW;UACzB,IAAI,aAAa,WAAW,KAAK,KAAK,0BAC3C,aAAa,MAAM;KAGrB,uBAAuB,kBAAkB,WAAW,KAAK;KAEzD,aAAa,KAAK,KAAK;MACrB;MACA,QAAQ,KAAK;MACb,aAAa;KACf,CAAC;IACH;GACF;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;ACnSA,SAAgB,iBAAiB,EAAE,YAAgD;CACjF,sBAAsB;EACpB,yBAAyB;CAC3B,CAAC;CACD,OAAO;AACT"}
@@ -55,7 +55,6 @@ export declare class CloudflareKVCacheHandler implements CacheHandler {
55
55
  set(key: string, value: unknown, opts: {
56
56
  ttl: number;
57
57
  tags: string[];
58
- generation?: number;
59
58
  }): Promise<void>;
60
59
  invalidate(opts: {
61
60
  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M,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,EAG5D;IAED,wEAAwE;IACxE,OAAO,CAAC,KAAK;IAYb,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,MAAM;IAIR,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC,CAQzE;IAEK,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAoC3F;IAEK,UAAU,CAAC,IAAI,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAgDpE;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-kv-cache.js","names":[],"sources":["../../src/adapters/cloudflare-kv-cache.ts"],"sourcesContent":["import type { CacheHandler } from '../cache/index.ts';\nimport { getCloudflareBindings } from './cloudflare.ts';\nimport { warnLossyJsonValue } from '../cache/json-lossy-check.ts';\n\n/**\n * Cloudflare Workers KV interface — the subset of KVNamespace we depend on.\n * Users don't need to import this; the handler resolves the binding internally\n * via `getCloudflareBindings()`.\n */\nexport interface CloudflareKVNamespace {\n get(key: string, options: { type: 'json' }): Promise<unknown>;\n get(key: string, options?: { type?: string }): Promise<string | null>;\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;\n delete(key: string): Promise<void>;\n}\n\ninterface KVCacheEntry {\n value: unknown;\n tags: string[];\n expiresAt: number;\n}\n\ninterface TagIndexEntry {\n key: string;\n /** Physical KV expiry — the 2× TTL deadline. Members are pruned at this\n * timestamp (not the logical expiresAt) so stale entries in the SWR window\n * remain in the index for `invalidate({tag})` to find. */\n expiresAt: number;\n}\n\n// 30 days in ms — used as the grace period for legacy tag index entries whose\n// original expiry is unknown. Must be a concrete number, not Infinity, because\n// JSON.stringify(Infinity) produces null and the entry would be pruned on read.\nconst LEGACY_GRACE_MS = 30 * 86400 * 1000;\n\n/**\n * Parse a tag index value, handling both the old format (string[]) and the\n * new format (TagIndexEntry[]). Old-format entries get a 30-day grace period\n * so they survive until explicitly invalidated or cycled through a new set().\n */\nfunction parseTagIndex(raw: unknown, now: number): TagIndexEntry[] {\n if (!Array.isArray(raw)) return [];\n const legacyDeadline = now + LEGACY_GRACE_MS;\n return raw.map((item: unknown) => {\n if (typeof item === 'string') return { key: item, expiresAt: legacyDeadline };\n return item as TagIndexEntry;\n });\n}\n\nfunction computeIndexTtl(entries: TagIndexEntry[], now: number): number {\n const maxExpiresAt = Math.max(...entries.map((e) => e.expiresAt));\n return Math.max(Math.ceil((maxExpiresAt - now) / 1000), 60);\n}\n\n/**\n * Cloudflare Workers KV–backed CacheHandler.\n *\n * Uses tag index keys for tag-based invalidation (KV has no secondary indexes).\n * Stores entries with 2× TTL so stale entries survive for `staleWhileRevalidate`\n * reads. The logical staleness is determined by the `expiresAt` timestamp inside\n * the entry payload.\n *\n * **Consistency:** KV is eventually consistent (~60s propagation). TTL is the\n * primary expiry mechanism. Tag invalidation is best-effort — do not rely on it\n * for security-critical cache purging (use short TTLs instead).\n *\n * ```ts\n * // timber.config.ts\n * import { CloudflareKVCacheHandler } from '@timber-js/app/adapters/cloudflare/cache';\n *\n * export default {\n * cacheHandler: new CloudflareKVCacheHandler({ bindingName: 'TIMBER_CACHE' }),\n * };\n * ```\n */\nexport class CloudflareKVCacheHandler implements CacheHandler {\n private bindingName: string;\n private prefix: string;\n\n constructor(options: { bindingName: string; prefix?: string }) {\n this.bindingName = options.bindingName;\n this.prefix = options.prefix ?? 'tc:';\n }\n\n /** Resolve the KV binding from the current request's Cloudflare env. */\n private getKV(): CloudflareKVNamespace {\n const env = getCloudflareBindings<Record<string, CloudflareKVNamespace>>();\n const kv = env[this.bindingName];\n if (!kv) {\n throw new Error(\n `CloudflareKVCacheHandler: binding \"${this.bindingName}\" not found. ` +\n 'Check your wrangler.jsonc kv_namespaces configuration.'\n );\n }\n return kv;\n }\n\n private dataKey(key: string): string {\n return `${this.prefix}d:${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}t:${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const kv = this.getKV();\n const raw = await kv.get(this.dataKey(key), { type: 'json' });\n if (!raw) return null;\n\n const entry = raw as KVCacheEntry;\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void> {\n warnLossyJsonValue(value, key);\n const kv = this.getKV();\n const entry: KVCacheEntry = {\n value,\n tags: opts.tags,\n expiresAt: Date.now() + opts.ttl * 1000,\n };\n\n // KV expirationTtl minimum is 60s. Use 2× TTL (min 60s) so stale entries\n // survive for staleWhileRevalidate background refetches.\n const kvTtl = Math.max(opts.ttl * 2, 60);\n\n // Serialize upfront so BigInt/non-serializable errors throw before any\n // writes — prevents tag indexes pointing at stale data from a prior set().\n const payload = JSON.stringify(entry);\n\n // Tag indexes are written BEFORE the data key so that a partial network\n // failure on the data write never leaves an entry invisible to\n // invalidate({tag}). A dangling tag-index reference to a non-existent\n // data key is harmless — invalidate() re-checks stored tags and cleans\n // up on the next pass.\n const now = Date.now();\n const kvExpiresAt = now + kvTtl * 1000;\n await Promise.all(\n opts.tags.map(async (tag) => {\n const existing = parseTagIndex(await kv.get(this.tagKey(tag), { type: 'json' }), now);\n const fresh = existing.filter((e) => e.expiresAt > now && e.key !== key);\n fresh.push({ key, expiresAt: kvExpiresAt });\n await kv.put(this.tagKey(tag), JSON.stringify(fresh), {\n expirationTtl: computeIndexTtl(fresh, now),\n });\n })\n );\n\n await kv.put(this.dataKey(key), payload, { expirationTtl: kvTtl });\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n const kv = this.getKV();\n\n if (opts.key) {\n // Read entry to find its tags, then clean up tag indexes\n const raw = (await kv.get(this.dataKey(opts.key), { type: 'json' })) as KVCacheEntry | null;\n if (raw) {\n await Promise.all(\n raw.tags.map(async (tag) => {\n const now = Date.now();\n const entries = parseTagIndex(await kv.get(this.tagKey(tag), { type: 'json' }), now);\n const filtered = entries.filter((e) => e.key !== opts.key);\n if (filtered.length > 0) {\n await kv.put(this.tagKey(tag), JSON.stringify(filtered), {\n expirationTtl: computeIndexTtl(filtered, now),\n });\n } else {\n await kv.delete(this.tagKey(tag));\n }\n })\n );\n }\n await kv.delete(this.dataKey(opts.key));\n }\n\n if (opts.tag) {\n const entries = parseTagIndex(\n await kv.get(this.tagKey(opts.tag), { type: 'json' }),\n Date.now()\n );\n if (entries.length > 0) {\n // Re-check each member's stored tags before deleting — the tag index\n // can contain stale references from partial writes or entries whose\n // tags changed since they were indexed. Mirrors Redis handler behavior.\n await Promise.all(\n entries.map(async (e) => {\n const raw = (await kv.get(this.dataKey(e.key), {\n type: 'json',\n })) as KVCacheEntry | null;\n if (!raw) return;\n if (raw.tags?.includes(opts.tag!)) {\n await kv.delete(this.dataKey(e.key));\n }\n })\n );\n }\n await kv.delete(this.tagKey(opts.tag));\n }\n }\n}\n"],"mappings":";;;AAiCA,IAAM,kBAAkB;;;;;;AAOxB,SAAS,cAAc,KAAc,KAA8B;CACjE,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,OAAO,CAAC;CACjC,MAAM,iBAAiB,MAAM;CAC7B,OAAO,IAAI,KAAK,SAAkB;EAChC,IAAI,OAAO,SAAS,UAAU,OAAO;GAAE,KAAK;GAAM,WAAW;EAAe;EAC5E,OAAO;CACT,CAAC;AACH;AAEA,SAAS,gBAAgB,SAA0B,KAAqB;CACtE,MAAM,eAAe,KAAK,IAAI,GAAG,QAAQ,KAAK,MAAM,EAAE,SAA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,QAAQ,IACZ,QAAQ,IAAI,OAAO,MAAM;IACvB,MAAM,MAAO,MAAM,GAAG,IAAI,KAAK,QAAQ,EAAE,GAAG,GAAG,EAC7C,MAAM,OACR,CAAC;IACD,IAAI,CAAC,KAAK;IACV,IAAI,IAAI,MAAM,SAAS,KAAK,GAAI,GAC9B,MAAM,GAAG,OAAO,KAAK,QAAQ,EAAE,GAAG,CAAC;GAEvC,CAAC,CACH;GAEF,MAAM,GAAG,OAAO,KAAK,OAAO,KAAK,GAAG,CAAC;EACvC;CACF;AACF"}
1
+ {"version":3,"file":"cloudflare-kv-cache.js","names":[],"sources":["../../src/adapters/cloudflare-kv-cache.ts"],"sourcesContent":["import type { CacheHandler } from '../cache/index.ts';\nimport { getCloudflareBindings } from './cloudflare.ts';\nimport { warnLossyJsonValue } from '../cache/json-lossy-check.ts';\n\n/**\n * Cloudflare Workers KV interface — the subset of KVNamespace we depend on.\n * Users don't need to import this; the handler resolves the binding internally\n * via `getCloudflareBindings()`.\n */\nexport interface CloudflareKVNamespace {\n get(key: string, options: { type: 'json' }): Promise<unknown>;\n get(key: string, options?: { type?: string }): Promise<string | null>;\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;\n delete(key: string): Promise<void>;\n}\n\ninterface KVCacheEntry {\n value: unknown;\n tags: string[];\n expiresAt: number;\n}\n\ninterface TagIndexEntry {\n key: string;\n /** Physical KV expiry — the 2× TTL deadline. Members are pruned at this\n * timestamp (not the logical expiresAt) so stale entries in the SWR window\n * remain in the index for `invalidate({tag})` to find. */\n expiresAt: number;\n}\n\n// 30 days in ms — used as the grace period for legacy tag index entries whose\n// original expiry is unknown. Must be a concrete number, not Infinity, because\n// JSON.stringify(Infinity) produces null and the entry would be pruned on read.\nconst LEGACY_GRACE_MS = 30 * 86400 * 1000;\n\n/**\n * Parse a tag index value, handling both the old format (string[]) and the\n * new format (TagIndexEntry[]). Old-format entries get a 30-day grace period\n * so they survive until explicitly invalidated or cycled through a new set().\n */\nfunction parseTagIndex(raw: unknown, now: number): TagIndexEntry[] {\n if (!Array.isArray(raw)) return [];\n const legacyDeadline = now + LEGACY_GRACE_MS;\n return raw.map((item: unknown) => {\n if (typeof item === 'string') return { key: item, expiresAt: legacyDeadline };\n return item as TagIndexEntry;\n });\n}\n\nfunction computeIndexTtl(entries: TagIndexEntry[], now: number): number {\n const maxExpiresAt = Math.max(...entries.map((e) => e.expiresAt));\n return Math.max(Math.ceil((maxExpiresAt - now) / 1000), 60);\n}\n\n/**\n * Cloudflare Workers KV–backed CacheHandler.\n *\n * Uses tag index keys for tag-based invalidation (KV has no secondary indexes).\n * Stores entries with 2× TTL so stale entries survive for `staleWhileRevalidate`\n * reads. The logical staleness is determined by the `expiresAt` timestamp inside\n * the entry payload.\n *\n * **Consistency:** KV is eventually consistent (~60s propagation). TTL is the\n * primary expiry mechanism. Tag invalidation is best-effort — do not rely on it\n * for security-critical cache purging (use short TTLs instead).\n *\n * ```ts\n * // timber.config.ts\n * import { CloudflareKVCacheHandler } from '@timber-js/app/adapters/cloudflare/cache';\n *\n * export default {\n * cacheHandler: new CloudflareKVCacheHandler({ bindingName: 'TIMBER_CACHE' }),\n * };\n * ```\n */\nexport class CloudflareKVCacheHandler implements CacheHandler {\n private bindingName: string;\n private prefix: string;\n\n constructor(options: { bindingName: string; prefix?: string }) {\n this.bindingName = options.bindingName;\n this.prefix = options.prefix ?? 'tc:';\n }\n\n /** Resolve the KV binding from the current request's Cloudflare env. */\n private getKV(): CloudflareKVNamespace {\n const env = getCloudflareBindings<Record<string, CloudflareKVNamespace>>();\n const kv = env[this.bindingName];\n if (!kv) {\n throw new Error(\n `CloudflareKVCacheHandler: binding \"${this.bindingName}\" not found. ` +\n 'Check your wrangler.jsonc kv_namespaces configuration.'\n );\n }\n return kv;\n }\n\n private dataKey(key: string): string {\n return `${this.prefix}d:${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}t:${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const kv = this.getKV();\n const raw = await kv.get(this.dataKey(key), { type: 'json' });\n if (!raw) return null;\n\n const entry = raw as KVCacheEntry;\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void> {\n warnLossyJsonValue(value, key);\n const kv = this.getKV();\n const entry: KVCacheEntry = {\n value,\n tags: opts.tags,\n expiresAt: Date.now() + opts.ttl * 1000,\n };\n\n // KV expirationTtl minimum is 60s. Use 2× TTL (min 60s) so stale entries\n // survive for staleWhileRevalidate background refetches.\n const kvTtl = Math.max(opts.ttl * 2, 60);\n\n // Serialize upfront so BigInt/non-serializable errors throw before any\n // writes — prevents tag indexes pointing at stale data from a prior set().\n const payload = JSON.stringify(entry);\n\n // Tag indexes are written BEFORE the data key so that a partial network\n // failure on the data write never leaves an entry invisible to\n // invalidate({tag}). A dangling tag-index reference to a non-existent\n // data key is harmless — invalidate() re-checks stored tags and cleans\n // up on the next pass.\n const now = Date.now();\n const kvExpiresAt = now + kvTtl * 1000;\n await Promise.all(\n opts.tags.map(async (tag) => {\n const existing = parseTagIndex(await kv.get(this.tagKey(tag), { type: 'json' }), now);\n const fresh = existing.filter((e) => e.expiresAt > now && e.key !== key);\n fresh.push({ key, expiresAt: kvExpiresAt });\n await kv.put(this.tagKey(tag), JSON.stringify(fresh), {\n expirationTtl: computeIndexTtl(fresh, now),\n });\n })\n );\n\n await kv.put(this.dataKey(key), payload, { expirationTtl: kvTtl });\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n const kv = this.getKV();\n\n if (opts.key) {\n // Read entry to find its tags, then clean up tag indexes\n const raw = (await kv.get(this.dataKey(opts.key), { type: 'json' })) as KVCacheEntry | null;\n if (raw) {\n await Promise.all(\n raw.tags.map(async (tag) => {\n const now = Date.now();\n const entries = parseTagIndex(await kv.get(this.tagKey(tag), { type: 'json' }), now);\n const filtered = entries.filter((e) => e.key !== opts.key);\n if (filtered.length > 0) {\n await kv.put(this.tagKey(tag), JSON.stringify(filtered), {\n expirationTtl: computeIndexTtl(filtered, now),\n });\n } else {\n await kv.delete(this.tagKey(tag));\n }\n })\n );\n }\n await kv.delete(this.dataKey(opts.key));\n }\n\n if (opts.tag) {\n const entries = parseTagIndex(\n await kv.get(this.tagKey(opts.tag), { type: 'json' }),\n Date.now()\n );\n if (entries.length > 0) {\n // Re-check each member's stored tags before deleting — the tag index\n // can contain stale references from partial writes or entries whose\n // tags changed since they were indexed. Mirrors Redis handler behavior.\n await Promise.all(\n entries.map(async (e) => {\n const raw = (await kv.get(this.dataKey(e.key), {\n type: 'json',\n })) as KVCacheEntry | null;\n if (!raw) return;\n if (raw.tags?.includes(opts.tag!)) {\n await kv.delete(this.dataKey(e.key));\n }\n })\n );\n }\n await kv.delete(this.tagKey(opts.tag));\n }\n }\n}\n"],"mappings":";;;AAiCA,IAAM,kBAAkB;;;;;;AAOxB,SAAS,cAAc,KAAc,KAA8B;CACjE,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,OAAO,CAAC;CACjC,MAAM,iBAAiB,MAAM;CAC7B,OAAO,IAAI,KAAK,SAAkB;EAChC,IAAI,OAAO,SAAS,UAAU,OAAO;GAAE,KAAK;GAAM,WAAW;EAAe;EAC5E,OAAO;CACT,CAAC;AACH;AAEA,SAAS,gBAAgB,SAA0B,KAAqB;CACtE,MAAM,eAAe,KAAK,IAAI,GAAG,QAAQ,KAAK,MAAM,EAAE,SAAS,CAAC;CAChE,OAAO,KAAK,IAAI,KAAK,MAAM,eAAe,OAAO,GAAI,GAAG,EAAE;AAC5D;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,2BAAb,MAA8D;CAC5D;CACA;CAEA,YAAY,SAAmD;EAC7D,KAAK,cAAc,QAAQ;EAC3B,KAAK,SAAS,QAAQ,UAAU;CAClC;;CAGA,QAAuC;EAErC,MAAM,KADM,sBACD,CAAA,CAAI,KAAK;EACpB,IAAI,CAAC,IACH,MAAM,IAAI,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AAG,CAAC;EACvC;CACF;AACF"}
@@ -6,7 +6,6 @@ export interface CacheHandler {
6
6
  set(key: string, value: unknown, opts: {
7
7
  ttl: number;
8
8
  tags: string[];
9
- generation?: number;
10
9
  }): Promise<void>;
11
10
  invalidate(opts: {
12
11
  key?: string;
@@ -18,8 +17,11 @@ export interface CacheOptions<Fn extends (...args: any[]) => any> {
18
17
  key?: (...args: Parameters<Fn>) => string;
19
18
  staleWhileRevalidate?: boolean;
20
19
  tags?: string[] | ((...args: Parameters<Fn>) => string[]);
21
- /** Timeout (ms) for singleflight-coalesced calls. Prevents hung fn() from
22
- * permanently blocking all future callers for the same cache key. See TIM-518. */
20
+ /** Timeout (ms) for an execution this wrapper starts. Prevents hung fn() from
21
+ * permanently blocking all future callers for the same cache key (TIM-518).
22
+ * A call that joins an execution already in flight for the key waits under
23
+ * that execution's timeout, so wrappers sharing an explicit `key` should
24
+ * agree on it (design/06 §Residual write races). */
23
25
  timeoutMs?: number;
24
26
  }
25
27
  export interface MemoryCacheHandlerOptions {
@@ -37,7 +39,6 @@ export interface MemoryCacheHandlerOptions {
37
39
  }
38
40
  export declare class MemoryCacheHandler implements CacheHandler {
39
41
  private store;
40
- private generations;
41
42
  private maxEntries;
42
43
  private maxBytes;
43
44
  private maxEntryBytes;
@@ -51,7 +52,6 @@ export declare class MemoryCacheHandler implements CacheHandler {
51
52
  set(key: string, value: unknown, opts: {
52
53
  ttl: number;
53
54
  tags: string[];
54
- generation?: number;
55
55
  }): Promise<void>;
56
56
  invalidate(opts: {
57
57
  key?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cache/index.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACrE,GAAG,CACD,GA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,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAU;IAEtC,YAAY,IAAI,CAAC,EAAE,yBAAyB,EAM3C;IAEK,GAAG,CAAC,GAAG,EAAE,MAAM;;;cAUpB;IAEK,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,iBAsC3E;IAEK,UAAU,CAAC,IAAI,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,iBAgBpD;IAED,gDAAgD;IAChD,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,sIAAsI;IACtI,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,6CAA6C;IAC7C,OAAO,CAAC,WAAW;CAQpB;AAED,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAGlE,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
@@ -1,4 +1,4 @@
1
1
  import { b as setCacheHandler, v as getCacheHandler } from "../_chunks/dev-store-BvdqtHvK.js";
2
- import { f as MemoryCacheHandler, h as setDefaultSingleflightTimeout, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-TDZ4hlDc.js";
2
+ import { f as MemoryCacheHandler, h as setDefaultSingleflightTimeout, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-DsSXA4Sp.js";
3
3
  import { t as estimateByteSize } from "../_chunks/sizeof-DG4W40lv.js";
4
4
  export { MemoryCacheHandler, RedisCacheHandler, TagAwareCacheHandler, cache, estimateByteSize, getCacheHandler, setCacheHandler, setDefaultSingleflightTimeout };
@@ -166,7 +166,6 @@ export declare class RedisCacheHandler implements CacheHandler {
166
166
  set(key: string, value: unknown, opts: {
167
167
  ttl: number;
168
168
  tags: string[];
169
- generation?: number;
170
169
  }): Promise<void>;
171
170
  private execOp;
172
171
  invalidate(opts: {
@@ -1 +1 @@
1
- {"version":3,"file":"redis-handler.d.ts","sourceRoot":"","sources":["../../src/cache/redis-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+EG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAC7D;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,GAC9C;IAAE,EAAE,EAAE,UAAU,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,EAAE,EAAE,UAAU,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/B,MAAM,WAAW,WAAW;IAC1B,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AC,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAKD;;;;;;;;;;GAUG;AACH,qBAAa,iBAAkB,YAAW,YAAY;IACpD,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,MAAM,CAAS;IAEvB,YAAY,MAAM,EAAE,WAAW,EAAE,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,EAG1D;IAED,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,MAAM;IAIR,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC,CAOzE;IAEK,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA8B3F;YAEa,MAAM;IAoBd,UAAU,CAAC,IAAI,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAwCpE;CACF"}
@@ -11,11 +11,21 @@
11
11
  * subsequent callers can retry. See TIM-518.
12
12
  */
13
13
  export interface SingleflightOptions {
14
- /** Maximum time (ms) a coalesced call may run before being rejected. */
14
+ /**
15
+ * Default maximum time (ms) a coalesced call may run before being
16
+ * rejected. A `timeoutMs` passed to `do()` overrides it for that flight.
17
+ */
15
18
  timeoutMs?: number;
16
19
  }
17
20
  export interface Singleflight {
18
- do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
21
+ /**
22
+ * Run `fn` once per key; concurrent callers join the in-flight call.
23
+ * `timeoutMs` (default: the instance option) applies to the flight this
24
+ * call starts — a caller that joins an existing flight inherits its
25
+ * timeout. Passing it per call lets callers with different timeouts
26
+ * share one keyspace instead of each needing its own instance.
27
+ */
28
+ do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>, timeoutMs?: number): Promise<T>;
19
29
  /** Return the in-flight promise for a key, or undefined if none. */
20
30
  get(key: string): Promise<unknown> | undefined;
21
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"singleflight.d.ts","sourceRoot":"","sources":["../../src/cache/singleflight.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,WAAW,mBAAmB;IAClC,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxE,oEAAoE;IACpE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC;CAChD;AAED;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAY,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAGzC;CACF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,YAAY,CAwD3E"}
1
+ {"version":3,"file":"singleflight.d.ts","sourceRoot":"","sources":["../../src/cache/singleflight.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B;;;;;;OAMG;IACH,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5F,oEAAoE;IACpE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC;CAChD;AAED;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAY,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAGzC;CACF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,YAAY,CA0D3E"}
@@ -11,6 +11,12 @@
11
11
  * instances holding data behind getters or internal slots) — throw instead:
12
12
  * every such value would collapse to the same cache key, silently returning
13
13
  * one argument's cached data for another (TIM-1020).
14
+ *
15
+ * The same rule covers what JSON.stringify flattens: NaN, Infinity and
16
+ * -Infinity all become `null` there and -0 becomes `0`, and a typed array
17
+ * becomes a plain index object, so `Uint8Array`, `Int8Array` and
18
+ * `{ "0": 1 }` with the same values would share an entry. Both get a
19
+ * representation of their own (GHSA-rhh4-g77r-r9qj class).
14
20
  */
15
21
  export declare function stableStringify(value: unknown): string;
16
22
  //# sourceMappingURL=stable-stringify.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stable-stringify.d.ts","sourceRoot":"","sources":["../../src/cache/stable-stringify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAqEtD"}
1
+ {"version":3,"file":"stable-stringify.d.ts","sourceRoot":"","sources":["../../src/cache/stable-stringify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAkFtD"}
@@ -40,7 +40,6 @@ export declare class TagAwareCacheHandler implements CacheHandler {
40
40
  set(key: string, value: unknown, opts: {
41
41
  ttl: number;
42
42
  tags: string[];
43
- generation?: number;
44
43
  }): Promise<void>;
45
44
  invalidate(opts: {
46
45
  key?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"tag-aware-handler.d.ts","sourceRoot":"","sources":["../../src/cache/tag-aware-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAiD7C,qBAAa,oBAAqB,YAAW,YAAY;IACvD,OAAO,CAAC,KAAK,CAAa;IAC1B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAW;IAE3B,YAAY,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,EAIxD;IAED,IAAI,WAAW,IAAI,QAAQ,GAAG,UAAU,GAAG,OAAO,CAEjD;IAED,OAAO,CAAC,OAAO;IAIf,yEAAyE;IACzE,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,SAAS;IAIjB,OAAO,CAAC,aAAa;IAIf,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC,CAsBzE;IAEK,GAAG,CACP,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,OAAO,EACd,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,GACzD,OAAO,CAAC,IAAI,CAAC,CAgDf;IAEK,UAAU,CAAC,IAAI,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA0CpE;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} from './index.ts';
2
2
  /**
3
- * Set the timeout for the module-level default singleflight.
3
+ * Set the timeout for cache calls without a per-call timeoutMs.
4
4
  * Called at framework boot with renderTimeoutMs from timber.config.ts so that
5
5
  * cache calls without a per-call timeoutMs still get deadlock protection.
6
6
  * See design/06-caching.md §"Singleflight Timeout — Deadlock Risk".
@@ -1 +1 @@
1
- {"version":3,"file":"timber-cache.d.ts","sourceRoot":"","sources":["../../src/cache/timber-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAkC7D;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAErE;AAoED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,wBAAgB,WAAW,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EACrE,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,YAAY,CAAC,EAAE,CAAC,EACtB,UAAU,EAAE,MAAM,YAAY,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,EAAE,CAqJJ"}
1
+ {"version":3,"file":"timber-cache.d.ts","sourceRoot":"","sources":["../../src/cache/timber-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA4B7D;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAErE;AAoED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,wBAAgB,WAAW,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EACrE,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,YAAY,CAAC,EAAE,CAAC,EACtB,UAAU,EAAE,MAAM,YAAY,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,EAAE,CA8JJ"}
@@ -27,6 +27,14 @@ export interface PluginWithApi {
27
27
  name: string;
28
28
  api?: unknown;
29
29
  }
30
+ /**
31
+ * Whether a resolved Vite plugin list includes timber. Vite resolves a
32
+ * missing config file to an empty one rather than failing, so a caller that
33
+ * needs timber must ask — `timber dev` would otherwise serve plain Vite.
34
+ */
35
+ export declare function hasTimberPlugin(plugins: readonly {
36
+ name: string;
37
+ }[]): boolean;
30
38
  /**
31
39
  * Vite's own `resolveConfig`, narrowed to what this module passes and reads.
32
40
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cli-context.d.ts","sourceRoot":"","sources":["../src/cli-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAK5E,8DAA8D;AAC9D,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAC9B,YAAY,EAAE;IAAE,UAAU,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,EAChD,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,MAAM,EACnB,cAAc,EAAE,MAAM,KACnB,OAAO,CAAC;IAAE,OAAO,EAAE,SAAS,aAAa,EAAE,CAAA;CAAE,CAAC,CAAC;AAkCpD;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,MAAM,GAAG,SAAS,EAClC,iBAAiB,GAAE,iBAA4C,GAC9D,OAAO,CAAC,aAAa,CAAC,CAsBxB"}
1
+ {"version":3,"file":"cli-context.d.ts","sourceRoot":"","sources":["../src/cli-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAqB,KAAK,aAAa,EAAE,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;;;;;;;;;;;GAaG;AACH,wBAAsB,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwErF;AAED;;;;GAIG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAMvF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBzF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAMxF;AAID;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA6C7D"}
package/dist/cli.js CHANGED
@@ -88,6 +88,12 @@ function parseArgs(args) {
88
88
  async function runDev(options, _deps) {
89
89
  if (process.env.__TIMBER_DEV_WORKER) {
90
90
  const server = await (_deps?.createServer ?? (await import("vite")).createServer)({ configFile: options.config });
91
+ const { hasTimberPlugin } = await import("./_chunks/cli-context-BPdyA7Fp.js");
92
+ if (!hasTimberPlugin(server.config.plugins)) {
93
+ await server.close();
94
+ const where = server.config.configFile ?? `no Vite config found in ${server.config.root}`;
95
+ throw new Error(`[timber] The Vite config does not use the timber plugin (${where}).\n\n \`timber dev\` stopped instead of starting plain Vite. This happens when a\n config file changes on disk, for example a git checkout to a branch\n without timber. Run \`timber dev\` again once vite.config.ts lists timber().`);
96
+ }
91
97
  await server.listen();
92
98
  server.printUrls();
93
99
  return;
@@ -145,7 +151,7 @@ async function runBuild(options, _deps) {
145
151
  * exists but fails to load throws, naming the file (TIM-1066).
146
152
  */
147
153
  async function runPreview(options, _deps) {
148
- const { resolveTimberContext } = await import("./_chunks/cli-context-n5hmkdla.js");
154
+ const { resolveTimberContext } = await import("./_chunks/cli-context-BPdyA7Fp.js");
149
155
  const { adapterConfig, contextAdapter } = await import("./_chunks/plugin-context-BfSRKJfz.js");
150
156
  const ctx = await resolveTimberContext("preview", options.config, _deps?.resolveViteConfig);
151
157
  const adapter = contextAdapter(ctx);
@@ -173,7 +179,7 @@ async function runPreview(options, _deps) {
173
179
  * `--project` names the tsconfig handed to tsgo.
174
180
  */
175
181
  async function runCheck(options, _deps) {
176
- const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-Dv3f8d2j.js");
182
+ const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-B33yhAPa.js");
177
183
  const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);
178
184
  await runTypeCheck({
179
185
  root,