@timber-js/app 0.2.0-alpha.239 → 0.2.0-alpha.240

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 (332) hide show
  1. package/dist/_chunks/{actions-Top9GftB.js → actions-DIgnvDrG.js} +4 -4
  2. package/dist/_chunks/{actions-Top9GftB.js.map → actions-DIgnvDrG.js.map} +1 -1
  3. package/dist/_chunks/{als-registry-DpygwCp0.js → als-registry-PPYstxK0.js} +2 -1
  4. package/dist/_chunks/{als-registry-DpygwCp0.js.map → als-registry-PPYstxK0.js.map} +1 -1
  5. package/dist/_chunks/{cache-api-Bo8c7XVF.js → cache-api-uWQwuxWb.js} +5 -5
  6. package/dist/_chunks/{cache-api-Bo8c7XVF.js.map → cache-api-uWQwuxWb.js.map} +1 -1
  7. package/dist/_chunks/{chains-DMoHX4yH.js → chains-C7CExrUI.js} +2 -2
  8. package/dist/_chunks/{chains-DMoHX4yH.js.map → chains-C7CExrUI.js.map} +1 -1
  9. package/dist/_chunks/chains-CSslTUdI.js +1 -0
  10. package/dist/_chunks/{classify-BwyAd-dZ.js → classify-Cj9EeZoL.js} +2 -2
  11. package/dist/_chunks/{classify-BwyAd-dZ.js.map → classify-Cj9EeZoL.js.map} +1 -1
  12. package/dist/_chunks/{cli-check-DQAD9MLo.js → cli-check-C3QOAru7.js} +3 -3
  13. package/dist/_chunks/{cli-check-DQAD9MLo.js.map → cli-check-C3QOAru7.js.map} +1 -1
  14. package/dist/_chunks/{cli-schema-sync-C_xNLqBj.js → cli-schema-sync-BRxZz66D.js} +1 -1
  15. package/dist/_chunks/{cli-schema-sync-CmGls3dc.js → cli-schema-sync-DQUS_o3V.js} +2 -2
  16. package/dist/_chunks/{cli-schema-sync-CmGls3dc.js.map → cli-schema-sync-DQUS_o3V.js.map} +1 -1
  17. package/dist/_chunks/{client-dep-entries-C5BTQtFS.js → client-dep-entries-ZETBdLgv.js} +2 -2
  18. package/dist/_chunks/{client-dep-entries-C5BTQtFS.js.map → client-dep-entries-ZETBdLgv.js.map} +1 -1
  19. package/dist/_chunks/{convention-lint-GQA6WTRo.js → convention-lint-BoVISNS6.js} +3 -3
  20. package/dist/_chunks/{convention-lint-GQA6WTRo.js.map → convention-lint-BoVISNS6.js.map} +1 -1
  21. package/dist/_chunks/dev-server-B8roKA3Q.js +1 -0
  22. package/dist/_chunks/{dev-server-Cr3_Fu5A.js → dev-server-C5R6jx8Q.js} +2 -2
  23. package/dist/_chunks/{dev-server-Cr3_Fu5A.js.map → dev-server-C5R6jx8Q.js.map} +1 -1
  24. package/dist/_chunks/{dev-span-RsVeYYc_.js → dev-span-0aG7Q_Ph.js} +3 -7
  25. package/dist/_chunks/dev-span-0aG7Q_Ph.js.map +1 -0
  26. package/dist/_chunks/{error-boundary-Bh-egWUI.js → error-boundary-DB51f9ih.js} +98 -419
  27. package/dist/_chunks/error-boundary-DB51f9ih.js.map +1 -0
  28. package/dist/_chunks/{flight-source-node-BsrlUjMO.js → flight-source-node-D9cHBhjP.js} +7 -4
  29. package/dist/_chunks/flight-source-node-D9cHBhjP.js.map +1 -0
  30. package/dist/_chunks/{json-lossy-check-D47R9Fp5.js → json-lossy-check-Y1GxqVX_.js} +2 -2
  31. package/dist/_chunks/{json-lossy-check-D47R9Fp5.js.map → json-lossy-check-Y1GxqVX_.js.map} +1 -1
  32. package/dist/_chunks/{live-graph-HcLScfiV.js → live-graph-BDQWvnMm.js} +4 -4
  33. package/dist/_chunks/{live-graph-HcLScfiV.js.map → live-graph-BDQWvnMm.js.map} +1 -1
  34. package/dist/_chunks/{logger-DDLtp5e-.js → logger-DmRR9tmZ.js} +2 -2
  35. package/dist/_chunks/{logger-DDLtp5e-.js.map → logger-DmRR9tmZ.js.map} +1 -1
  36. package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -1
  37. package/dist/_chunks/{node-response-omewa8e6.js → node-response-yp8zdyRp.js} +2 -2
  38. package/dist/_chunks/{node-response-omewa8e6.js.map → node-response-yp8zdyRp.js.map} +1 -1
  39. package/dist/_chunks/plugin-context-BtaQcMuh.js.map +1 -1
  40. package/dist/_chunks/{poison-scan-DONdiCGX.js → poison-scan-WQgUydF_.js} +2 -2
  41. package/dist/_chunks/{poison-scan-DONdiCGX.js.map → poison-scan-WQgUydF_.js.map} +1 -1
  42. package/dist/_chunks/{scanner-DSAJjH0x.js → scanner-C9Lrf77z.js} +3 -2
  43. package/dist/_chunks/{scanner-DSAJjH0x.js.map → scanner-C9Lrf77z.js.map} +1 -1
  44. package/dist/_chunks/{sizeof-DVhEVN_y.js → sizeof-BISkSaU0.js} +2 -2
  45. package/dist/_chunks/{sizeof-DVhEVN_y.js.map → sizeof-BISkSaU0.js.map} +1 -1
  46. package/dist/_chunks/{walkers-96YopJds.js → walkers-Bxv4v7tX.js} +3 -3
  47. package/dist/_chunks/{walkers-96YopJds.js.map → walkers-Bxv4v7tX.js.map} +1 -1
  48. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  49. package/dist/analyze/crawl-entry.js +3 -3
  50. package/dist/analyze/graph-command.js +2 -2
  51. package/dist/cache/index.js +2 -2
  52. package/dist/cache/stores/memory.js +1 -1
  53. package/dist/cdn/workers-cache-purge.js +1 -1
  54. package/dist/cli.js +3 -3
  55. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
  56. package/dist/client/browser-entry/hydrate.d.ts +1 -1
  57. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  58. package/dist/client/error-boundary.d.ts +1 -0
  59. package/dist/client/error-boundary.d.ts.map +1 -1
  60. package/dist/client/error-boundary.js +1 -1
  61. package/dist/client/history.d.ts +4 -5
  62. package/dist/client/history.d.ts.map +1 -1
  63. package/dist/client/index.js +6 -7
  64. package/dist/client/index.js.map +1 -1
  65. package/dist/client/internal.d.ts +1 -1
  66. package/dist/client/internal.d.ts.map +1 -1
  67. package/dist/client/internal.js +194 -55
  68. package/dist/client/internal.js.map +1 -1
  69. package/dist/client/navigation-commit.d.ts +6 -25
  70. package/dist/client/navigation-commit.d.ts.map +1 -1
  71. package/dist/client/outlet-content-cache.d.ts +59 -0
  72. package/dist/client/outlet-content-cache.d.ts.map +1 -0
  73. package/dist/client/outlet-scope-context.d.ts +30 -0
  74. package/dist/client/outlet-scope-context.d.ts.map +1 -0
  75. package/dist/client/params-context.d.ts +10 -11
  76. package/dist/client/params-context.d.ts.map +1 -1
  77. package/dist/client/router-pipeline.d.ts +5 -5
  78. package/dist/client/router-pipeline.d.ts.map +1 -1
  79. package/dist/client/router-types.d.ts +10 -24
  80. package/dist/client/router-types.d.ts.map +1 -1
  81. package/dist/client/router.d.ts.map +1 -1
  82. package/dist/client/rsc-fetch.d.ts +4 -17
  83. package/dist/client/rsc-fetch.d.ts.map +1 -1
  84. package/dist/client/segment-cache.d.ts +15 -103
  85. package/dist/client/segment-cache.d.ts.map +1 -1
  86. package/dist/client/segment-outlet.d.ts +28 -52
  87. package/dist/client/segment-outlet.d.ts.map +1 -1
  88. package/dist/client/stale-segment.d.ts +39 -0
  89. package/dist/client/stale-segment.d.ts.map +1 -0
  90. package/dist/client/use-segment-params.d.ts +1 -1
  91. package/dist/config-types.d.ts +7 -6
  92. package/dist/config-types.d.ts.map +1 -1
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +9 -732
  95. package/dist/index.js.map +1 -1
  96. package/dist/native/rsc/manifest.json +6 -4
  97. package/dist/native/rsc/routing/segment-keys.js +3 -11
  98. package/dist/native/rsc/routing/segment-keys.js.map +1 -1
  99. package/dist/native/rsc/server/access-gate.js +3 -7
  100. package/dist/native/rsc/server/access-gate.js.map +1 -1
  101. package/dist/native/rsc/server/als-registry.js +2 -1
  102. package/dist/native/rsc/server/als-registry.js.map +1 -1
  103. package/dist/native/rsc/server/build-manifest.js.map +1 -1
  104. package/dist/native/rsc/server/chain-url-parts.js +1 -6
  105. package/dist/native/rsc/server/chain-url-parts.js.map +1 -1
  106. package/dist/native/rsc/server/client-state-tree.js +33 -0
  107. package/dist/native/rsc/server/client-state-tree.js.map +1 -0
  108. package/dist/native/rsc/server/flight-source-node.js +5 -2
  109. package/dist/native/rsc/server/flight-source-node.js.map +1 -1
  110. package/dist/native/rsc/server/flight-source.js +46 -7
  111. package/dist/native/rsc/server/flight-source.js.map +1 -1
  112. package/dist/native/rsc/server/pipeline-interception.js +1 -1
  113. package/dist/native/rsc/server/publish-params.js.map +1 -1
  114. package/dist/native/rsc/server/route-element-builder.js +43 -61
  115. package/dist/native/rsc/server/route-element-builder.js.map +1 -1
  116. package/dist/native/rsc/server/rsc-entry/helpers.js +5 -28
  117. package/dist/native/rsc/server/rsc-entry/helpers.js.map +1 -1
  118. package/dist/native/rsc/server/rsc-entry/render-route.js +33 -7
  119. package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
  120. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +2 -1
  121. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js.map +1 -1
  122. package/dist/native/rsc/server/rsc-entry/rsc-payload.js +2 -5
  123. package/dist/native/rsc/server/rsc-entry/rsc-payload.js.map +1 -1
  124. package/dist/native/rsc/server/rsc-entry/rsc-stream.js +44 -40
  125. package/dist/native/rsc/server/rsc-entry/rsc-stream.js.map +1 -1
  126. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +1 -1
  127. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js.map +1 -1
  128. package/dist/native/rsc/server/segment-hash/capture.js +107 -0
  129. package/dist/native/rsc/server/segment-hash/capture.js.map +1 -0
  130. package/dist/native/rsc/server/segment-hash/outlet.js +81 -0
  131. package/dist/native/rsc/server/segment-hash/outlet.js.map +1 -0
  132. package/dist/native/rsc/server/segment-hash/stream-tap.js +139 -0
  133. package/dist/native/rsc/server/segment-hash/stream-tap.js.map +1 -0
  134. package/dist/native/rsc/server/segment-hash/value-hash.js +171 -0
  135. package/dist/native/rsc/server/segment-hash/value-hash.js.map +1 -0
  136. package/dist/native/rsc/server/slot-resolver.js +20 -124
  137. package/dist/native/rsc/server/slot-resolver.js.map +1 -1
  138. package/dist/native/rsc/server/vite-handoff-rsc.js.map +1 -1
  139. package/dist/native/rsc/shared/outlet-decision.js +5 -0
  140. package/dist/native/rsc/shared/outlet-decision.js.map +1 -0
  141. package/dist/native/ssr/client/error-boundary.js +16 -3
  142. package/dist/native/ssr/client/error-boundary.js.map +1 -1
  143. package/dist/native/ssr/client/navigation-commit.js +1 -5
  144. package/dist/native/ssr/client/navigation-commit.js.map +1 -1
  145. package/dist/native/ssr/client/outlet-content-cache.js +53 -0
  146. package/dist/native/ssr/client/outlet-content-cache.js.map +1 -0
  147. package/dist/native/ssr/client/outlet-scope-context.js +12 -0
  148. package/dist/native/ssr/client/outlet-scope-context.js.map +1 -0
  149. package/dist/native/ssr/client/params-context.js.map +1 -1
  150. package/dist/native/ssr/client/rsc-fetch.js +1 -12
  151. package/dist/native/ssr/client/rsc-fetch.js.map +1 -1
  152. package/dist/native/ssr/client/segment-outlet.js +34 -13
  153. package/dist/native/ssr/client/segment-outlet.js.map +1 -1
  154. package/dist/native/ssr/client/stale-segment.js +29 -0
  155. package/dist/native/ssr/client/stale-segment.js.map +1 -0
  156. package/dist/native/ssr/manifest.json +5 -4
  157. package/dist/native/ssr/routing/segment-keys.js +5 -1
  158. package/dist/native/ssr/routing/segment-keys.js.map +1 -1
  159. package/dist/native/ssr/server/access-gate.js +3 -7
  160. package/dist/native/ssr/server/access-gate.js.map +1 -1
  161. package/dist/native/ssr/server/als-registry.js +1 -0
  162. package/dist/native/ssr/server/als-registry.js.map +1 -1
  163. package/dist/native/ssr/server/build-manifest.js.map +1 -1
  164. package/dist/native/ssr/server/client-state-tree.js +33 -0
  165. package/dist/native/ssr/server/client-state-tree.js.map +1 -0
  166. package/dist/native/ssr/server/flight-source-node.js +5 -2
  167. package/dist/native/ssr/server/flight-source-node.js.map +1 -1
  168. package/dist/native/ssr/server/flight-source.js +1 -0
  169. package/dist/native/ssr/server/flight-source.js.map +1 -1
  170. package/dist/native/ssr/server/pipeline-interception.js +1 -1
  171. package/dist/native/ssr/server/segment-hash/value-hash.js +162 -0
  172. package/dist/native/ssr/server/segment-hash/value-hash.js.map +1 -0
  173. package/dist/native/ssr/server/ssr-wrappers.js.map +1 -1
  174. package/dist/native/ssr/server/vite-handoff-rsc.js.map +1 -1
  175. package/dist/native/ssr/shared/payload-root.js.map +1 -1
  176. package/dist/plugin-context.d.ts +0 -16
  177. package/dist/plugin-context.d.ts.map +1 -1
  178. package/dist/plugins/build-manifest.d.ts.map +1 -1
  179. package/dist/routing/index.js +2 -2
  180. package/dist/routing/segment-keys.d.ts +8 -21
  181. package/dist/routing/segment-keys.d.ts.map +1 -1
  182. package/dist/server/access-gate.d.ts +0 -14
  183. package/dist/server/access-gate.d.ts.map +1 -1
  184. package/dist/server/als-registry.d.ts +16 -0
  185. package/dist/server/als-registry.d.ts.map +1 -1
  186. package/dist/server/build-manifest.d.ts +1 -10
  187. package/dist/server/build-manifest.d.ts.map +1 -1
  188. package/dist/server/chain-url-parts.d.ts +3 -13
  189. package/dist/server/chain-url-parts.d.ts.map +1 -1
  190. package/dist/server/client-state-tree.d.ts +31 -0
  191. package/dist/server/client-state-tree.d.ts.map +1 -0
  192. package/dist/server/flight-source-node.d.ts +6 -1
  193. package/dist/server/flight-source-node.d.ts.map +1 -1
  194. package/dist/server/flight-source.d.ts +27 -0
  195. package/dist/server/flight-source.d.ts.map +1 -1
  196. package/dist/server/index.js +2 -2
  197. package/dist/server/internal.js +48 -47
  198. package/dist/server/internal.js.map +1 -1
  199. package/dist/server/publish-params.d.ts +5 -4
  200. package/dist/server/publish-params.d.ts.map +1 -1
  201. package/dist/server/route-element-builder.d.ts +4 -19
  202. package/dist/server/route-element-builder.d.ts.map +1 -1
  203. package/dist/server/rsc-entry/helpers.d.ts +7 -13
  204. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  205. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  206. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -1
  207. package/dist/server/rsc-entry/rsc-payload.d.ts +1 -2
  208. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  209. package/dist/server/rsc-entry/rsc-stream.d.ts +11 -2
  210. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  211. package/dist/server/rsc-entry/ssr-renderer.d.ts +0 -2
  212. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  213. package/dist/server/segment-hash/capture.d.ts +77 -0
  214. package/dist/server/segment-hash/capture.d.ts.map +1 -0
  215. package/dist/server/segment-hash/outlet.d.ts +65 -0
  216. package/dist/server/segment-hash/outlet.d.ts.map +1 -0
  217. package/dist/server/segment-hash/stream-tap.d.ts +49 -0
  218. package/dist/server/segment-hash/stream-tap.d.ts.map +1 -0
  219. package/dist/server/segment-hash/value-hash.d.ts +70 -0
  220. package/dist/server/segment-hash/value-hash.d.ts.map +1 -0
  221. package/dist/server/slot-resolver.d.ts +13 -78
  222. package/dist/server/slot-resolver.d.ts.map +1 -1
  223. package/dist/server/ssr-wrappers.d.ts +7 -9
  224. package/dist/server/ssr-wrappers.d.ts.map +1 -1
  225. package/dist/server/vite-handoff-rsc.d.ts +10 -1
  226. package/dist/server/vite-handoff-rsc.d.ts.map +1 -1
  227. package/dist/shared/outlet-decision.d.ts +48 -0
  228. package/dist/shared/outlet-decision.d.ts.map +1 -0
  229. package/dist/shared/payload-root.d.ts +5 -8
  230. package/dist/shared/payload-root.d.ts.map +1 -1
  231. package/dist/shared/segment-info.d.ts +13 -28
  232. package/dist/shared/segment-info.d.ts.map +1 -1
  233. package/package.json +1 -1
  234. package/src/client/browser-entry/action-dispatch.ts +1 -15
  235. package/src/client/browser-entry/hydrate.ts +3 -3
  236. package/src/client/browser-entry/router-init.ts +28 -47
  237. package/src/client/error-boundary.tsx +49 -9
  238. package/src/client/history.ts +4 -5
  239. package/src/client/internal.ts +1 -1
  240. package/src/client/navigation-commit.ts +25 -83
  241. package/src/client/outlet-content-cache.ts +119 -0
  242. package/src/client/outlet-scope-context.ts +42 -0
  243. package/src/client/params-context.ts +11 -12
  244. package/src/client/router-pipeline.ts +10 -74
  245. package/src/client/router-types.ts +11 -26
  246. package/src/client/router.ts +7 -22
  247. package/src/client/rsc-fetch.ts +5 -30
  248. package/src/client/segment-cache.ts +19 -264
  249. package/src/client/segment-outlet.tsx +80 -72
  250. package/src/client/stale-segment.ts +60 -0
  251. package/src/client/use-segment-params.ts +1 -1
  252. package/src/config-types.ts +7 -6
  253. package/src/index.ts +0 -2
  254. package/src/plugin-context.ts +0 -16
  255. package/src/plugins/build-manifest.ts +1 -22
  256. package/src/routing/scanner.ts +12 -0
  257. package/src/routing/segment-keys.ts +9 -35
  258. package/src/rsc-runtime/vendor-types.d.ts +8 -0
  259. package/src/server/access-gate.tsx +3 -32
  260. package/src/server/als-registry.ts +23 -0
  261. package/src/server/build-manifest.ts +1 -11
  262. package/src/server/chain-url-parts.ts +3 -21
  263. package/src/server/client-state-tree.ts +75 -0
  264. package/src/server/flight-source-node.ts +7 -2
  265. package/src/server/flight-source.ts +102 -9
  266. package/src/server/pipeline-interception.ts +1 -1
  267. package/src/server/publish-params.ts +5 -4
  268. package/src/server/route-element-builder.ts +77 -206
  269. package/src/server/rsc-entry/helpers.ts +11 -65
  270. package/src/server/rsc-entry/render-route.ts +54 -28
  271. package/src/server/rsc-entry/revalidate-renderer.ts +2 -1
  272. package/src/server/rsc-entry/rsc-payload.ts +11 -39
  273. package/src/server/rsc-entry/rsc-stream.ts +123 -101
  274. package/src/server/rsc-entry/ssr-renderer.ts +1 -3
  275. package/src/server/segment-hash/capture.ts +232 -0
  276. package/src/server/segment-hash/outlet.ts +185 -0
  277. package/src/server/segment-hash/stream-tap.ts +244 -0
  278. package/src/server/segment-hash/value-hash.ts +338 -0
  279. package/src/server/slot-resolver.ts +37 -323
  280. package/src/server/ssr-wrappers.tsx +7 -9
  281. package/src/server/vite-handoff-rsc.ts +12 -1
  282. package/src/shared/outlet-decision.ts +54 -0
  283. package/src/shared/payload-root.ts +5 -8
  284. package/src/shared/segment-info.ts +13 -28
  285. package/dist/_chunks/chains-CmzbpG-6.js +0 -1
  286. package/dist/_chunks/dev-server--4_Ogy_6.js +0 -1
  287. package/dist/_chunks/dev-span-RsVeYYc_.js.map +0 -1
  288. package/dist/_chunks/error-boundary-Bh-egWUI.js.map +0 -1
  289. package/dist/_chunks/flight-source-node-BsrlUjMO.js.map +0 -1
  290. package/dist/client/segment-update-context.d.ts +0 -15
  291. package/dist/client/segment-update-context.d.ts.map +0 -1
  292. package/dist/client/slot-content-cache-context.d.ts +0 -35
  293. package/dist/client/slot-content-cache-context.d.ts.map +0 -1
  294. package/dist/native/rsc/server/request-dep.js +0 -12
  295. package/dist/native/rsc/server/request-dep.js.map +0 -1
  296. package/dist/native/rsc/server/route-element-helpers.js +0 -20
  297. package/dist/native/rsc/server/route-element-helpers.js.map +0 -1
  298. package/dist/native/rsc/server/skippable-prefix.js +0 -72
  299. package/dist/native/rsc/server/skippable-prefix.js.map +0 -1
  300. package/dist/native/rsc/server/state-tree-diff.js +0 -35
  301. package/dist/native/rsc/server/state-tree-diff.js.map +0 -1
  302. package/dist/native/ssr/client/segment-cache.js +0 -119
  303. package/dist/native/ssr/client/segment-cache.js.map +0 -1
  304. package/dist/native/ssr/client/segment-update-context.js +0 -9
  305. package/dist/native/ssr/client/segment-update-context.js.map +0 -1
  306. package/dist/native/ssr/client/slot-content-cache-context.js +0 -8
  307. package/dist/native/ssr/client/slot-content-cache-context.js.map +0 -1
  308. package/dist/native/ssr/server/state-tree-diff.js +0 -23
  309. package/dist/native/ssr/server/state-tree-diff.js.map +0 -1
  310. package/dist/plugins/request-dep/analysis.d.ts +0 -106
  311. package/dist/plugins/request-dep/analysis.d.ts.map +0 -1
  312. package/dist/plugins/request-dep/index.d.ts +0 -75
  313. package/dist/plugins/request-dep/index.d.ts.map +0 -1
  314. package/dist/plugins/request-dep/origin.d.ts +0 -61
  315. package/dist/plugins/request-dep/origin.d.ts.map +0 -1
  316. package/dist/server/request-dep.d.ts +0 -15
  317. package/dist/server/request-dep.d.ts.map +0 -1
  318. package/dist/server/route-element-helpers.d.ts +0 -12
  319. package/dist/server/route-element-helpers.d.ts.map +0 -1
  320. package/dist/server/skippable-prefix.d.ts +0 -29
  321. package/dist/server/skippable-prefix.d.ts.map +0 -1
  322. package/dist/server/state-tree-diff.d.ts +0 -78
  323. package/dist/server/state-tree-diff.d.ts.map +0 -1
  324. package/src/client/segment-update-context.ts +0 -23
  325. package/src/client/slot-content-cache-context.ts +0 -43
  326. package/src/plugins/request-dep/analysis.ts +0 -447
  327. package/src/plugins/request-dep/index.ts +0 -376
  328. package/src/plugins/request-dep/origin.ts +0 -310
  329. package/src/server/request-dep.ts +0 -37
  330. package/src/server/route-element-helpers.ts +0 -37
  331. package/src/server/skippable-prefix.ts +0 -172
  332. package/src/server/state-tree-diff.ts +0 -132
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-boundary-DB51f9ih.js","names":[],"sources":["../../src/shared/payload-root.ts","../../src/client/navigation-commit.ts","../../src/client/rsc-fetch.ts","../../src/client/unload-guard.ts","../../src/client/stale-client.ts","../../src/client/navigation-transition.ts","../../src/client/router-skew.ts","../../src/client/router-effects.ts","../../src/client/outlet-scope-context.ts","../../src/client/status-page-marker.tsx","../../src/shared/error-digest.ts","../../src/client/stale-segment.ts","../../src/client/error-boundary.tsx"],"sourcesContent":["/**\n * The shape of an RSC payload's root row.\n *\n * Every tree the server sends the browser is serialized as\n * `{ tree, params, slotParams }` — the route's element tree, plus the coerced\n * params it rendered with, as *siblings* rather than as a wrapper around the\n * tree. See design/41-global-params.md §\"Transport\".\n *\n * Two reasons it is a sibling field rather than a provider inside the payload\n * (TIM-1297, which is TIM-1294's mechanism corrected):\n *\n * 1. **A provider inside the payload cannot reach a skipped segment.** A\n * segment the server skipped renders the content the client cached for it\n * (design/52-segment-hash-dedupe.md), and that copy carries whatever was\n * inside it when it was committed — never the incoming route's provider.\n * Params belong to the *navigation*, so the provider has to be owned by the\n * client, above the payload root, and there must be exactly one.\n *\n * 2. **Element props are not readable at the instant the root resolves.**\n * Flight outlines a React element's props and fills the record in after the\n * root row resolves, so a reader that unblocks on the root sees `{}` — and\n * since the object is filled *in place*, its identity never changes and any\n * memo keyed on it caches the empty snapshot permanently. A plain model\n * field has no such window: the root chunk stays blocked until everything\n * it references has resolved.\n *\n * This module is the single declaration of that shape. The server builds roots\n * through `server/publish-params.ts` and the client reads them through the\n * helpers here — producer and consumer do not each describe the payload.\n */\n\nimport type { CoercedParams } from './param-value.ts';\nimport type { SlotParamsRecord } from './slot-params.ts';\n\n/** The params published beside a tree. */\nexport interface PublishedParams {\n /** The main route's coerced params. */\n params: CoercedParams;\n /** Per-slot params, or null when the route rendered no slots with params. */\n slotParams: SlotParamsRecord | null;\n}\n\n/**\n * Params ready to publish: settled, or a promise the root provider suspends on.\n *\n * Both forms exist on purpose. The hydration path cannot await — `hydrateRoot`\n * has to be called before the inline Flight stream has necessarily produced\n * the root row — so it hands over the promise and suspends exactly where React\n * was already going to suspend on the tree. Every other path settles it inside\n * the navigation transition first, which is what keeps a decode failure inside\n * the app's own error boundaries instead of above them (TIM-1297).\n */\nexport type ParamsSource = PublishedParams | Promise<PublishedParams>;\n\n/** The root row of an RSC payload. */\nexport interface RscPayloadRoot extends PublishedParams {\n /** The route's element tree. */\n tree: unknown;\n}\n\n/**\n * What a reader gets when the value it was handed is not a payload root.\n *\n * In the browser this is unreachable for a real response: all four producers\n * of a route payload go through `withPublishedParams`, and a client talking to\n * a different build is answered with 204 at Stage 1c\n * (`server/pipeline-phases.ts`) before any payload exists. It is what a page\n * with no payload at all publishes — a document hydrated without an inlined\n * payload, or a prefetch entry that carries no params.\n */\nexport const NO_PUBLISHED_PARAMS: PublishedParams = { params: {}, slotParams: null };\n\n/** True when `value` carries published params — a root, or a read of one. */\nfunction hasPublishedParams(value: unknown): value is PublishedParams {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'params' in value &&\n typeof (value as PublishedParams).params === 'object' &&\n (value as PublishedParams).params !== null\n );\n}\n\n/**\n * Read the params published beside a tree.\n *\n * Accepts a payload root *or* a `PublishedParams` already split off one, so\n * the client can pre-resolve on the navigation path and still hand the same\n * value to the same provider. Never throws.\n */\nexport function readPublishedParams(source: unknown): PublishedParams {\n if (!hasPublishedParams(source)) return NO_PUBLISHED_PARAMS;\n return { params: source.params, slotParams: source.slotParams ?? null };\n}\n\n/**\n * Read the renderable tree out of a payload root.\n *\n * Returns the value unchanged when it is not a root, so a malformed value\n * reaches React (and its error boundaries) rather than vanishing here.\n */\nexport function readPayloadTree(root: unknown): unknown {\n if (typeof root === 'object' && root !== null && 'tree' in root && hasPublishedParams(root)) {\n return (root as RscPayloadRoot).tree;\n }\n return root;\n}\n\n/** A decoded payload, split into the two things the client does with it. */\nexport interface SplitPayload {\n /** The renderable tree — an element, or a thenable React suspends on. */\n tree: unknown;\n /**\n * The params published beside it. Settled when the root already is, so the\n * hydration path can render without an extra await.\n *\n * **Never rejects.** A decode failure has to surface through `tree`: where\n * React renders it on hydration, so the error boundary *around the tree*\n * catches it, and where the router awaits it before handing a navigation\n * over, so the navigation fails and recovers. Rejecting here too would take\n * down the provider above every boundary in the app, turning a contained\n * failure into a blank page (TIM-1297).\n */\n params: ParamsSource;\n}\n\n/**\n * Split a decoded payload root into its tree and its params.\n *\n * Accepts a settled root or a thenable of one, and preserves which it was: a\n * settled root splits synchronously, so no code path gains a suspend point it\n * did not already have.\n */\nexport function splitPayloadRoot(root: unknown): SplitPayload {\n if (\n typeof root !== 'object' ||\n root === null ||\n typeof (root as PromiseLike<unknown>).then !== 'function'\n ) {\n return { tree: readPayloadTree(root), params: readPublishedParams(root) };\n }\n const settled = root as PromiseLike<unknown>;\n const tree = Promise.resolve(settled).then(readPayloadTree);\n // The rejection still reaches React through its own read of `tree`; this\n // only marks it handled for the case where nothing renders it (a partial\n // navigation whose segment update finds no matching outlet).\n tree.catch(() => {});\n const params = Promise.resolve(settled).then(readPublishedParams, () => NO_PUBLISHED_PARAMS);\n return { tree, params };\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 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// can nonetheless describe the whole chain the payload was built against — a\n// deny that lands after the headers went out is not in it — so the cache of\n// mounted tree paths 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 a narrower interception\n// scope on the 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\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}\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 /**\n * The segment hashes the client holds content for, by outlet path\n * (`OutletContentCache.hashes()`). Empty outside a browser router.\n */\n outletHashes: () => Record<string, string>;\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 return {\n committedSegmentInfo: () => committedSegmentInfo,\n\n /**\n * The X-Timber-State-Tree to send with the next RSC request.\n *\n * Two different things travel on one header. `hashes` are the caching\n * opt-in — the segment hashes the client holds content for — and are\n * omitted unless `clientSegmentCache` is on (design/52).\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: StateTree = {};\n const treePaths = segmentCache.treePaths();\n if (treePaths.length > 0) tree.treePaths = treePaths;\n if (deps.clientSegmentCache()) {\n const hashes = deps.outletHashes();\n if (Object.keys(hashes).length > 0) tree.hashes = hashes;\n }\n return tree.treePaths || tree.hashes ? tree : 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 = opts.payload;\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 segmentCache.record(segmentInfo);\n } else if (segmentInfo?.length === 0 || opts.clearSegmentCacheOnEmpty) {\n segmentCache.clear();\n }\n\n committedSegmentInfo = segmentInfo ?? null;\n\n historyStack.push(url, {\n payload,\n params: opts.params,\n segmentInfo: committedSegmentInfo,\n });\n },\n };\n },\n };\n}\n","/**\n * RSC Fetch — handles fetching and parsing RSC Flight payloads.\n *\n * Extracted from router.ts to keep both files under the 500-line limit.\n * This module handles:\n * - Cache-busting URL generation for RSC requests\n * - Building RSC request headers (Accept, X-Timber-State-Tree)\n * - Extracting metadata from RSC response headers\n * - Fetching and decoding RSC payloads\n *\n * See design/19-client-navigation.md §\"RSC Payload Handling\"\n */\n\nimport {\n rscCacheKey,\n recordLookup,\n randomRscCacheKey,\n RSC_KEY_PARAM,\n} from '../shared/rsc-cache-key.ts';\nimport type { RscManifest, RscManifestEntry } from '../shared/rsc-manifest.ts';\nimport { splitPayloadRoot, type PublishedParams } from '../shared/payload-root.ts';\nimport { normalizeBasePath, stripBasePath, withBasePath } from '../shared/base-path.ts';\nimport { rscPayloadPath } from '../shared/rsc-payload-path.ts';\nimport type { SegmentInfo, StateTree } from '../shared/segment-info.ts';\nimport { TIMBER_ERROR_HEADER } from '../shared/rsc-error-envelope.ts';\nimport { RSC_CONTENT_TYPE, isRscContentType } from '../shared/rsc-media-type.ts';\nimport type { RouterDeps } from './router-types.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\n/** Result of fetching an RSC payload — includes segment metadata. */\nexport interface FetchResult {\n /** The renderable tree, split off the payload root. */\n payload: unknown;\n /**\n * The params the same payload published beside that tree.\n *\n * Not a separate channel: both fields come out of one `splitPayloadRoot`\n * call on one decoded root, so a response cannot deliver a tree and another\n * route's params. They used to arrive on their own header, which is how a\n * navigation could render one route and publish another's (TIM-1285,\n * TIM-1294).\n */\n params: PublishedParams | Promise<PublishedParams>;\n /**\n * Promise that settles when the RSC decode completes or fails.\n * The payload thenable is NOT awaited before returning (for streaming),\n * so callers must monitor this to catch async decode errors\n * (truncated streams, Flight parse failures) that would otherwise\n * become unhandled rejections.\n */\n decodePromise: Promise<void> | null;\n /** Segment metadata from X-Timber-Segments header for populating the segment cache. */\n segmentInfo: SegmentInfo[] | null;\n}\n\n// ─── URL Helpers ─────────────────────────────────────────────────\n\n/**\n * Append a `_rsc=<key>` query parameter to the URL (TIM-1268).\n *\n * The key is a deterministic hash of the RSC request headers, so identical\n * requests share a URL and the payload becomes cacheable. It also keeps the\n * document and the payload on different URLs, so a shared cache cannot\n * return HTML for an RSC request (or vice versa) even where `Vary` is\n * opt-in configuration rather than default behaviour — Cloudflare and\n * CloudFront both. See GHSA-wfc6-r584-vfw7, design/13-security.md.\n *\n * The origin recomputes this key from the received headers and refuses to\n * let a mismatched response be shared-cached, so a caller cannot claim\n * another client's key while sending its own headers.\n *\n * Falls back to a random value when no key can be derived — `crypto.subtle`\n * is absent in non-secure browsing contexts (plain `http://` on a LAN\n * address). Dropping the parameter instead would put the payload back on\n * the document URL, where a query-keyed cache that ignores `Vary` could\n * store a Flight response under `/about` and serve it to an HTML\n * navigation. The random parameter this feature replaced did separate those\n * representations, and the fallback must not be worse than what it\n * replaced. The origin cannot verify a random key, so it refuses to\n * share-cache the response — which is exactly the old behaviour, where a\n * unique URL was never a cache hit anyway.\n *\n * Strips any #fragment before appending — fragments are client-only and\n * fetch() discards them, so _rsc would land inside the hash and be lost.\n */\nasync function appendRscParam(url: string, headers: Record<string, string>): Promise<string> {\n const hashIndex = url.indexOf('#');\n const urlWithoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);\n const key = (await rscCacheKey(recordLookup(headers))) ?? randomRscCacheKey();\n const separator = urlWithoutHash.includes('?') ? '&' : '?';\n return `${urlWithoutHash}${separator}${RSC_KEY_PARAM}=${key}`;\n}\n\n// ─── Deployment ID ───────────────────────────────────────────────\n\n/**\n * The client's deployment ID, set at bootstrap from the runtime config.\n * Sent with every RSC/action request for version skew detection.\n * Null in dev mode. See TIM-446.\n */\nlet clientDeploymentId: string | null = null;\n\n/** Set the client deployment ID. Called once at bootstrap. */\nexport function setClientDeploymentId(id: string | null): void {\n clientDeploymentId = id;\n}\n\n/** Get the client deployment ID. */\nexport function getClientDeploymentId(): string | null {\n return clientDeploymentId;\n}\n\n// ─── Base Path ───────────────────────────────────────────────────\n\n/**\n * The deployment base path (Vite's resolved `base`), normalized.\n * Set at bootstrap from `virtual:timber-config`; `'/'` unless the app is\n * deployed under a sub-path. See design/11-platform.md, TIM-1261.\n *\n * **The base is applied in exactly one place: at fetch time**\n * (`toStaticRscUrl`). The static build writes the RSC manifest with\n * root-relative keys *and* root-relative URLs, so the generated site stays\n * relocatable and there is no second copy of the base to drift from this one.\n */\nlet basePath = '/';\n\n/** Set the deployment base path. Called once at bootstrap. */\nexport function setBasePath(base: string | undefined): void {\n basePath = normalizeBasePath(base);\n}\n\n/** Get the normalized deployment base path. @internal Exported for testing. */\nexport function getBasePath(): string {\n return basePath;\n}\n\n// ─── Static Mode ────────────────────────────────────────────────\n\n/**\n * When true, RSC fetches use _rsc/*.rsc file URLs instead of\n * the route URL with Accept headers. Static hosts ignore Accept\n * headers, so the client must fetch the pre-generated .rsc files\n * directly. Set at bootstrap from virtual:timber-config output mode.\n */\nlet staticMode = false;\n\nexport function setStaticMode(enabled: boolean): void {\n staticMode = enabled;\n}\n\nexport function isStaticMode(): boolean {\n return staticMode;\n}\n\n/**\n * RSC manifest mapping unhashed → content-hashed `.rsc` URLs. Populated from\n * `window.__TIMBER_RSC_MANIFEST__` (injected into HTML during static\n * generation). Shape shared with the static build that writes it — see\n * `shared/rsc-manifest.ts`. See TIM-1254.\n */\nlet rscManifest: RscManifest | null = null;\n\nfunction getRscManifest(): RscManifest | null {\n if (rscManifest) return rscManifest;\n if (typeof window !== 'undefined' && (window as any).__TIMBER_RSC_MANIFEST__) {\n rscManifest = (window as any).__TIMBER_RSC_MANIFEST__;\n }\n return rscManifest;\n}\n\n/** @internal Exported for testing. */\nexport function setRscManifest(manifest: RscManifest | null): void {\n rscManifest = manifest;\n}\n\n/** A resolved static payload target: the URL to fetch, and how it was resolved. */\ninterface StaticRscTarget {\n /** Fetchable URL — base-prefixed. */\n url: string;\n /**\n * True when the RSC manifest supplied a content-hashed filename. The hash\n * guarantees freshness, so no `_rsc` cache key is appended (TIM-1254).\n */\n hashed: boolean;\n}\n\n/**\n * Resolve a route URL to the `_rsc/*.rsc` file to fetch. The naming rule is\n * `shared/rsc-payload-path.ts`, shared with the build that writes the files.\n *\n * When an RSC manifest is available (hashed filenames from TIM-1254),\n * the manifest is consulted to resolve to the hashed path.\n *\n * / → /_rsc/index.rsc (or /_rsc/index-B7YxEKdN.rsc with manifest)\n * /about → /_rsc/about/index.rsc (or /_rsc/about/index-C8ZzFLfO.rsc)\n * /blog/hello → /_rsc/blog/hello/index.rsc\n *\n * The manifest is written and read in route space (no base prefix), so the\n * base is applied here — once, on the way out. See client/base-path.ts.\n */\nfunction toStaticRscUrl(url: string): StaticRscTarget {\n const unhashed = toUnhashedRscUrl(url);\n const hashedUrl = manifestLookup(unhashed);\n return { url: withBasePath(basePath, hashedUrl ?? unhashed), hashed: hashedUrl !== null };\n}\n\n/**\n * Compute the unhashed `_rsc/*.rsc` path for a route URL.\n *\n * Returns a **route-space** path: the deployment base is stripped from the\n * incoming URL and is NOT re-applied, because this value doubles as the RSC\n * manifest key, and the manifest is base-less. `toStaticRscUrl` applies the\n * base to whatever is actually fetched.\n *\n * @internal Exported for testing.\n */\nexport function toUnhashedRscUrl(url: string): string {\n const hashIndex = url.indexOf('#');\n const queryIndex = url.indexOf('?');\n const hashEnd = hashIndex === -1 ? url.length : hashIndex;\n const queryEnd = queryIndex === -1 ? url.length : queryIndex;\n const end = Math.min(hashEnd, queryEnd);\n let pathname = stripBasePath(basePath, url.slice(0, end));\n // Strip trailing slash (unless root) to match static build output naming\n if (pathname.length > 1 && pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n return rscPayloadPath(pathname);\n}\n\n/**\n * Look up a key in the RSC manifest, falling back to percent-decoded\n * lookup for encoded browser URLs. Returns the entry or null.\n */\nfunction manifestEntry(key: string): RscManifestEntry | null {\n const manifest = getRscManifest();\n if (!manifest) return null;\n if (manifest[key]) return manifest[key];\n try {\n const decoded = decodeURIComponent(key);\n if (decoded !== key && manifest[decoded]) return manifest[decoded];\n } catch {\n // Malformed percent sequence (e.g. /100%.rsc) — skip decoded lookup\n }\n return null;\n}\n\n/**\n * Look up the hashed URL for an unhashed RSC path.\n */\nfunction manifestLookup(key: string): string | null {\n return manifestEntry(key)?.url ?? null;\n}\n\n// The manifest used to inline each route's params, because a generated\n// `.rsc` file carries no response headers and the header channel therefore\n// did not exist on the static path (TIM-1255, TIM-1285). The `.rsc` file now\n// carries them itself — they are props inside the payload — so the static\n// path needs no special case at all.\n\n// ─── Reload Signal ───────────────────────────────────────────────\n\n/** Header name used by the server to signal a version skew reload. */\nexport const RELOAD_HEADER = 'X-Timber-Reload';\n\n/** Header name for the client's deployment ID. */\nexport const DEPLOYMENT_ID_HEADER = 'X-Timber-Deployment-Id';\n\n/**\n * Check if a response signals a version skew reload.\n * Triggers a full page reload if the server indicates the client is stale.\n */\nexport function checkReloadSignal(response: Response): boolean {\n return response.headers.get(RELOAD_HEADER) === '1';\n}\n\n// ─── Header Builder ──────────────────────────────────────────────\n\n/**\n * Build the headers for an RSC payload request.\n *\n * **Every header added here is hashed into the payload URL** as the `_rsc`\n * cache key (see `rscCacheKey`), and URLs are logged by proxies, CDNs, and\n * origin access logs. So: no credentials, no session identifiers, no\n * user-supplied content. `fnv1aHash` is a cache-key hash, not a KDF — a\n * low-entropy secret would be recoverable from the URL by brute force.\n * Authentication already travels on cookies, which are not part of this\n * object and never enter the key.\n */\nexport function buildRscHeaders(\n stateTree: StateTree | undefined,\n currentUrl?: string\n): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: RSC_CONTENT_TYPE,\n };\n if (stateTree) {\n headers['X-Timber-State-Tree'] = JSON.stringify(stateTree);\n }\n // Send current URL for intercepting route resolution.\n // The server uses this to determine if an intercepting route should\n // render instead of the actual target route (modal pattern).\n // See design/07-routing.md §\"Intercepting Routes\"\n if (currentUrl) {\n headers['X-Timber-URL'] = currentUrl;\n }\n // Send deployment ID for version skew detection (TIM-446).\n // The server compares this against the current build's ID.\n // On mismatch, the server signals a reload instead of returning\n // an RSC payload with mismatched module references.\n if (clientDeploymentId) {\n headers[DEPLOYMENT_ID_HEADER] = clientDeploymentId;\n }\n return headers;\n}\n\n// ─── Response Header Extraction ──────────────────────────────────\n\n/** Dev-only warning for malformed framework headers. Tree-shaken in production. */\nfunction warnMalformedHeader(headerName: string, raw: string): void {\n if (process.env.NODE_ENV !== 'production') {\n const preview = raw.length > 200 ? raw.slice(0, 200) + '…' : raw;\n console.warn(\n `[timber] Malformed ${headerName} header \\u2014 JSON.parse failed. ` +\n `This indicates a framework bug or header corruption. Raw (first 200 chars): ${preview}`\n );\n }\n}\n\n/**\n * Extract segment metadata from the X-Timber-Segments response header.\n * Returns null if the header is missing or malformed.\n *\n * Format: JSON array of {path, segmentId?, treePath?} objects describing the\n * mounted layout-bearing segments from root to leaf. The client reports the\n * tree paths back for interception scoping (TIM-1282).\n */\nexport function extractSegmentInfo(response: Response): SegmentInfo[] | null {\n const header = response.headers.get('X-Timber-Segments');\n if (!header) return null;\n try {\n return JSON.parse(header);\n } catch {\n warnMalformedHeader('X-Timber-Segments', header);\n return null;\n }\n}\n\n// ─── Redirect Error ──────────────────────────────────────────────\n\n/**\n * Thrown when an RSC payload response contains X-Timber-Redirect header.\n * Caught in navigate() to trigger a soft router navigation to the redirect target.\n */\nexport class RedirectError extends Error {\n readonly redirectUrl: string;\n constructor(url: string) {\n super(`Server redirect to ${url}`);\n this.redirectUrl = url;\n }\n}\n\n/**\n * Thrown when the server signals a version skew (X-Timber-Reload header).\n * Caught in navigate() to trigger a full page reload.\n * See TIM-446.\n */\nexport class VersionSkewError extends Error {\n constructor() {\n super('Version skew detected — server has been redeployed');\n }\n}\n\n/**\n * Thrown when the server returns an error for an RSC payload request.\n * The server sends X-Timber-Error header and a JSON body instead of a\n * RSC stream it cannot answer in-SPA (a deny that needs a fallback page, a\n * broken first read). Caught in\n * navigate() to trigger a hard navigation so the server can render\n * the error page as HTML.\n *\n * See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n */\nexport class ServerErrorResponse extends Error {\n readonly status: number;\n readonly url: string;\n constructor(status: number, url: string) {\n super(`Server error ${status} during navigation to ${url}`);\n this.status = status;\n this.url = url;\n }\n}\n\n/**\n * Thrown when the RSC fetch response has a Content-Type that is not\n * text/x-component — e.g., a static asset (image, CSS, JS) served\n * for a same-origin URL that isn't a route. The response body is\n * cancelled immediately (headers-only cost). Caught in navigate()\n * to trigger a hard navigation; caught in prefetch() to store a\n * negative cache entry so click hard-navigates without a second fetch.\n *\n * See TIM-1231.\n */\nexport class NonRscResponse extends Error {\n readonly url: string;\n constructor(url: string) {\n super(`Non-RSC response for ${url}`);\n this.url = url;\n }\n}\n\n// ─── Stream Completion Tracking ───────────────────────────────────\n\n/**\n * Wrap a response body stream to track when it's fully consumed.\n * Returns a new body that passes all chunks through unchanged, plus\n * a `done` promise that resolves when the last chunk is read (or\n * rejects if the stream errors).\n *\n * createFromFetch's thenable resolves on shell arrival, but callers need to\n * know when the stream is fully decoded: that is what `navigateTransition`'s\n * returned promise means, and what the router's pending store, the Navigation\n * API deferred and `<Link>`'s `isPending` are all timed against.\n */\nfunction trackStreamCompletion(body: ReadableStream<Uint8Array>): {\n body: ReadableStream<Uint8Array>;\n done: Promise<void>;\n} {\n let resolveDone!: () => void;\n let rejectDone!: (e: unknown) => void;\n const done = new Promise<void>((res, rej) => {\n resolveDone = res;\n rejectDone = rej;\n });\n\n const reader = body.getReader();\n const tracked = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const result = await reader.read();\n if (result.done) {\n controller.close();\n resolveDone();\n } else {\n controller.enqueue(result.value);\n }\n } catch (error) {\n controller.error(error);\n rejectDone(error);\n }\n },\n cancel(reason) {\n reader.cancel(reason);\n resolveDone();\n },\n });\n\n return { body: tracked, done };\n}\n\n// ─── Fetch ───────────────────────────────────────────────────────\n\n/**\n * Fetch an RSC payload from the server and start decoding it.\n *\n * Every response is classified here, once: a version-skew reload, a 204 or\n * 3xx redirect, a server error envelope and a non-RSC body are each turned\n * into their error before `decodeRsc` sees the body. There is no second\n * path — tests decode real Flight bytes through the same code (TIM-1541).\n */\nexport async function fetchRscPayload(\n url: string,\n deps: RouterDeps,\n stateTree?: StateTree,\n currentUrl?: string,\n signal?: AbortSignal\n): Promise<FetchResult> {\n // In static mode, fetch the pre-generated _rsc/*.rsc file directly\n // instead of the route URL with Accept headers. Static hosts ignore\n // Accept headers, so the route URL would return HTML.\n const staticTarget = staticMode ? toStaticRscUrl(url) : null;\n const fetchTarget = staticTarget ? staticTarget.url : url;\n // Static hosts resolve neither segment hashes nor intercepting routes,\n // so neither the state tree nor the source URL is sent — and neither may\n // fragment the cache key of a file that does not vary on them.\n const headers = staticMode\n ? buildRscHeaders(undefined, undefined)\n : buildRscHeaders(stateTree, currentUrl);\n // Skip the cache key when the manifest supplies a content-hashed\n // URL — the hash itself guarantees freshness, and the param would defeat\n // the immutable cache headers on /_rsc/* (TIM-1254).\n const rscUrl = staticTarget?.hashed ? fetchTarget : await appendRscParam(fetchTarget, headers);\n // Deriving the cache key is async (SubtleCrypto), so the fetch is no\n // longer issued in the same tick as the call. A navigation superseded\n // during that window would otherwise still hit the network with an\n // already-aborted signal.\n signal?.throwIfAborted();\n // createFromFetch takes a Promise<Response> and progressively parses\n // the RSC Flight stream as chunks arrive.\n //\n // Intercept the response to read segment metadata before createFromFetch\n // consumes the body. Reading headers does NOT consume the body stream.\n const fetchPromise = deps.fetch(rscUrl, { headers, redirect: 'manual', signal });\n let segmentInfo: SegmentInfo[] | null = null;\n // Track when the full RSC body stream is consumed (not just shell).\n // Initialized to resolved for bodyless responses; overwritten when\n // the response has a body.\n let streamDone: Promise<void> = Promise.resolve();\n\n const wrappedPromise = fetchPromise.then((response) => {\n // Version skew detection (TIM-446): if the server signals a reload,\n // throw VersionSkewError so the caller (router navigate) can trigger\n // a full page reload.\n if (checkReloadSignal(response)) {\n throw new VersionSkewError();\n }\n // Detect server-side redirects. The server returns 204 + X-Timber-Redirect\n // for RSC payload requests instead of a raw 302, because fetch with\n // redirect: \"manual\" turns 302s into opaque redirects (status 0, null body)\n // which crashes createFromFetch when it tries to read the body stream.\n const redirectLocation =\n response.headers.get('X-Timber-Redirect') ||\n (response.status >= 300 && response.status < 400 ? response.headers.get('Location') : null);\n if (redirectLocation) {\n throw new RedirectError(redirectLocation);\n }\n // Detect server error responses. The server returns X-Timber-Error header\n // with a JSON body instead of an RSC stream it cannot answer in-SPA.\n // Hard-navigate so the server renders the error page as HTML.\n // See design/10-error-handling.md §\"Error Page Rendering for Client Navigation\"\n if (response.headers.get(TIMBER_ERROR_HEADER) === '1') {\n throw new ServerErrorResponse(response.status, url);\n }\n // Content-Type guard: reject non-RSC responses before createFromFetch\n // tries to parse the body as Flight data.\n // In static mode, accept octet-stream/text/plain/absent content-type\n // (static hosts serve .rsc files with these), but still reject 404s\n // and text/html (missing .rsc file → host returns 404 page or SPA\n // HTML fallback). See TIM-1231, TIM-1243, TIM-1247.\n if (staticMode) {\n const contentType = response.headers.get('content-type');\n if (\n !response.ok ||\n (contentType && contentType.split(';')[0].trim().toLowerCase() === 'text/html')\n ) {\n response.body?.cancel();\n throw new NonRscResponse(url);\n }\n } else {\n if (!isRscContentType(response.headers.get('content-type'))) {\n response.body?.cancel();\n throw new NonRscResponse(url);\n }\n }\n // Metadata (<title>/<meta>/<link>) now rides the RSC Flight payload\n // as React elements — React 19 Float handles them. See TIM-1151.\n segmentInfo = extractSegmentInfo(response);\n\n // Wrap the body to track full stream consumption. createFromFetch's\n // thenable resolves when the root model (shell) arrives, but we need\n // to know when ALL chunks are read — that is what the navigation\n // promise resolving means, and what keeps the pending store set.\n if (response.body) {\n const tracked = trackStreamCompletion(response.body);\n streamDone = tracked.done;\n streamDone.catch(() => {}); // prevent unhandled rejection\n return new Response(tracked.body, {\n headers: response.headers,\n status: response.status,\n });\n }\n return response;\n });\n // Await headers so segmentInfo is populated.\n await wrappedPromise;\n // Start decoding but do NOT await — return the in-progress thenable.\n // React can render a Flight thenable directly: it suspends on unresolved\n // parts and progressively renders as chunks arrive, spreading work across\n // frames instead of blocking the main thread in one burst.\n const root = deps.decodeRsc(wrappedPromise);\n // One split, one root: the tree and the params it was rendered with come\n // apart here and nowhere else, so nothing downstream has to keep them\n // paired by hand.\n const { tree: payload, params } = splitPayloadRoot(root);\n // Settles once the stream has ended AND the root has decoded, and rejects\n // as soon as either fails. streamDone marks the end of the RSC stream,\n // which is what the navigation promise resolves on; the root's rejection\n // carries decode failures (stale client references, Flight parse errors)\n // so the router's catch block can trigger recovery (stale reload).\n //\n // Not a race between the two: a payload that arrives whole — a small\n // static `.rsc` file — ends its stream before Flight rejects the root it\n // could not decode, and a race resolved on the stream, so the failure\n // never reached recovery and the skew was never recorded (TIM-1541).\n const rootDecoded = Promise.resolve(root).then(() => {});\n rootDecoded.catch(() => {});\n const decodePromise = Promise.all([streamDone, rootDecoded]).then(() => {});\n // Mark handled, like rootDecoded above. The same rejection reaches the\n // router through `payload`, and a navigation that recovers by hard\n // navigating (version skew, non-RSC response) hangs deliberately and never\n // awaits this one — leaving it to surface as an unhandled rejection.\n decodePromise.catch(() => {});\n return {\n payload,\n params,\n decodePromise,\n segmentInfo,\n };\n}\n","/**\n * Page unload detection — suppresses spurious errors during page refresh/navigation.\n *\n * When the user refreshes the page or navigates away while React is still\n * streaming Suspense content, the aborted connection causes streaming errors.\n * These are not application errors — they're a side effect of the browser\n * tearing down the connection. This module tracks whether the page is being\n * unloaded so error boundaries and error handlers can suppress abort-related\n * errors during the unload window.\n *\n * This is the single owner of \"is this document going away\". Anything that\n * needs the answer imports `isPageUnloading()` — an unload flag maintained a\n * second time somewhere else is a flag that will drift out of agreement with\n * this one (TIM-1260).\n *\n * Mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n *\n * See design/10-error-handling.md §\"Known limitation: deny() inside Suspense and hydration\"\n */\n\nimport { unloading, _setUnloading } from './state.ts';\n\n/**\n * Departure is *committed*: `pagehide` has fired, or this document has called\n * reload() on itself. `beforeunload` alone doesn't qualify — it is\n * speculative, and the user can still cancel out of it.\n */\nlet committed = false;\n\nif (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', () => {\n _setUnloading(true);\n\n // An app with an unsaved-changes prompt can have this cancelled. Nothing\n // fires to say so, so the only signal is that the page is still running\n // afterwards — and timers are blocked while the modal is up, so this task\n // cannot run until the user has chosen. If they left, `pagehide` has\n // already committed and this is a no-op.\n setTimeout(() => {\n if (!committed) _setUnloading(false);\n }, 0);\n });\n\n // pagehide is the committed-departure event, and fires for both navigations\n // and bfcache entry. Safari in particular may skip beforeunload entirely.\n window.addEventListener('pagehide', () => {\n committed = true;\n _setUnloading(true);\n });\n\n window.addEventListener('pageshow', (event) => {\n // A bfcache restore un-does the teardown `pagehide` announced: the same\n // document is alive again, with this module's state intact. Without the\n // reset, every consumer would go on suppressing errors on a live page.\n if (event.persisted) {\n committed = false;\n _setUnloading(false);\n }\n });\n}\n\n/**\n * Returns true if the page is currently being unloaded (user refreshed\n * or navigated away). Error boundaries should suppress errors in this state.\n */\nexport function isPageUnloading(): boolean {\n return unloading;\n}\n","/**\n * Stale Client — knowing when this bundle has been superseded.\n *\n * Layer 1 of version skew handling (see design/33-version-skew.md) is\n * proactive: the server compares `X-Timber-Deployment-Id` against the current\n * build and answers a stale client with `X-Timber-Reload: 1`. That covers\n * every RSC navigation and every server action — as long as there is a server\n * in the request path.\n *\n * This module is the reactive half, plus the state both halves feed. It\n * recognizes the two error shapes a stale client produces on its own:\n *\n * 1. **Stale client references** — React's Flight client throws\n * \"Could not find the module …\" when an RSC payload names a client module\n * ID that isn't in this bundle's manifest.\n * 2. **Chunk load failures** — a content-hashed chunk that no longer exists on\n * the CDN fails to `import()`. Every engine words this differently.\n *\n * It matters most for `output: 'static'`, where there is no server to send the\n * reload header and this is the *only* skew detection that can run.\n *\n * **Nothing here reloads the page.** A stale client is recorded, not acted on;\n * the router turns the next user-initiated navigation into a full document\n * load. See design/33-version-skew.md §\"Recovery on the next navigation\" for\n * why — a self-issued `location.reload()` cannot tell a recovery from a bounce\n * between two live deployments, and mid-rollout it produces exactly that loop.\n *\n * See TIM-1260, TIM-1275.\n */\n\n// The only import: the shared unload state. Kept minimal because this module\n// is reached from the error boundary, a `'use client'` component evaluated in\n// the SSR graph too — a dependency on the client fetch layer would drag that\n// graph along with it.\nimport { isPageUnloading } from './unload-guard.ts';\n\n// ─── Error Shapes ────────────────────────────────────────────────\n\n/**\n * Substrings that identify a failed dynamic import, lowercased for\n * case-insensitive matching. Engines and bundlers each word this\n * differently and none of them expose a stable error code.\n */\nconst CHUNK_LOAD_PATTERNS = [\n // Chromium\n 'failed to fetch dynamically imported module',\n // Firefox\n 'error loading dynamically imported module',\n // Safari\n 'importing a module script failed',\n // Vite's preload helper, for the stylesheet of a lazily-imported chunk\n 'unable to preload css for',\n];\n\n/** Substring React's Flight client uses when a client module ID is unknown. */\nconst STALE_REFERENCE_PATTERN = 'could not find the module';\n\n/**\n * Pull a comparable message out of an unknown thrown value. Rejections cross\n * enough boundaries (event handlers, `unhandledrejection`, Vite's preload\n * event) that the value is not reliably an `Error`.\n */\nfunction messageOf(error: unknown): string {\n if (typeof error === 'string') return error.toLowerCase();\n if (error instanceof Error) return error.message.toLowerCase();\n if (error && typeof error === 'object' && 'message' in error) {\n const message = (error as { message: unknown }).message;\n if (typeof message === 'string') return message.toLowerCase();\n }\n return '';\n}\n\n/**\n * True when the error is React's \"client reference not in this manifest\"\n * failure — the payload was produced by a build this bundle doesn't match.\n */\nexport function isStaleClientReference(error: unknown): boolean {\n return messageOf(error).includes(STALE_REFERENCE_PATTERN);\n}\n\n/**\n * True when the error is a failed dynamic import or CSS preload — the\n * content-hashed chunk this bundle asks for is gone from the CDN.\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (error instanceof Error && error.name === 'ChunkLoadError') return true;\n const message = messageOf(error);\n return CHUNK_LOAD_PATTERNS.some((pattern) => message.includes(pattern));\n}\n\n// ─── Staleness ───────────────────────────────────────────────────\n\n/**\n * True once this client is known to be running against a superseded\n * deployment. One-way: a document that has gone stale cannot come back, since\n * the only way to get fresh code is to load a new document.\n *\n * In-memory on purpose. Persisting it would be wrong — the next document gets\n * whatever build the server hands it, and if that one is stale too it will\n * find out the same way.\n */\nlet stale = false;\n\n/**\n * True once {@link initStaleClient} has seen a deployment ID — i.e. this is a\n * production build. False in dev, where nothing is ever stale: HMR owns code\n * updates, and a failed dynamic import is a real error the developer needs to\n * see rather than something a page load fixes.\n */\nlet deployed = false;\n\n/** Whether this client has been superseded by a newer deployment. */\nexport function isClientStale(): boolean {\n return stale;\n}\n\n/**\n * Record that the origin has told us this client is stale — the `X-Timber-Reload`\n * header on an RSC or action response. Authoritative, so it is not gated on\n * anything: a dev server never sends the header in the first place.\n */\nexport function markClientStale(): void {\n stale = true;\n}\n\n/**\n * Record staleness if `error` is one of the shapes a superseded bundle\n * produces. Returns whether it did, so a caller mid-navigation can decide to\n * hard-navigate instead of surfacing the error.\n *\n * Inference, unlike {@link markClientStale}, so it is gated on being a\n * production build. This is the single place that gate lives — call sites\n * cannot see each other, and \"remember to gate the next one too\" is not a\n * guarantee.\n */\nexport function markStaleFromError(error: unknown): boolean {\n if (!deployed) return false;\n\n // A document being torn down aborts its in-flight dynamic imports, and an\n // aborted import reads exactly like a chunk the CDN has dropped. That is not\n // evidence of staleness, and the bit outlives the teardown that produced it:\n // a document entering the back-forward cache is frozen, not destroyed, so a\n // false positive recorded on the way out would cost the *restored* page its\n // client-side navigation for good. `unload-guard.ts` clears its own flag on\n // a persisted `pageshow`; this one is one-way by design, so it has to not be\n // set in the first place.\n if (isPageUnloading()) return false;\n\n if (!isStaleClientReference(error) && !isChunkLoadError(error)) return false;\n stale = true;\n return true;\n}\n\n// ─── Initialization ──────────────────────────────────────────────\n\n/**\n * The underlying error Vite attaches to a `vite:preloadError` event.\n *\n * Narrowed at runtime rather than cast: the property is Vite's, not ours, and\n * a shape change should fall back to matching the event itself rather than\n * silently reading `undefined` forever.\n */\nfunction preloadErrorPayload(event: Event): unknown {\n return 'payload' in event ? (event as Event & { payload: unknown }).payload : event;\n}\n\n/**\n * Arm the module, and register the listeners that catch stale-client errors\n * never passing through the router: a lazily imported client component, a\n * preloaded stylesheet, anything that rejects outside a navigation.\n *\n * No-op when `deploymentId` is null — that is dev. Called from the browser\n * entry before hydration, so it precedes any render or navigation that could\n * throw.\n */\nexport function initStaleClient(deploymentId: string | null): void {\n if (!deploymentId) return;\n deployed = true;\n\n // Vite dispatches this for failed chunk/CSS preloads. Note what is *not*\n // here: `preventDefault()`. Recording staleness is not recovering from this\n // error — the page is still broken until the user navigates — so Vite must\n // go on rethrowing it rather than have it silently swallowed.\n window.addEventListener('vite:preloadError', (event) => {\n markStaleFromError(preloadErrorPayload(event));\n });\n\n window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {\n markStaleFromError(event.reason);\n });\n}\n","/**\n * Navigation transition — the router-level hand-off of a navigation's tree to\n * React, and the supersession that governs it.\n *\n * `navigateTransition` runs a navigation's fetch OUTSIDE any transition scope\n * and hands the resulting tree to React through a `NavigationRender`, which\n * is a synchronous `startTransition` around `root.render` (client/react-root.ts).\n * Two React behaviours force that shape; both were measured on React 19.2.7\n * (tests/navigation-transition-suspense.test.ts pins the observable half).\n *\n * 1. A transition scope does not survive an `await`. `startTransition`\n * restores the previous scope in its `finally`, which for an async\n * callback runs when that callback RETURNS — i.e. at its first `await`.\n * So an update scheduled past an await inside `startTransition(async …)`\n * is an ordinary urgent update:\n *\n * startTransition(() => render(x)) -> 'HOME' held\n * startTransition(async () => { await p; render(x) }) -> fallback shown\n *\n * Left uncorrected, every navigation whose new tree suspends replaces the\n * visible page with a Suspense fallback — the exact thing NavigationRoot\n * exists to prevent (TIM-1306). React documents the caveat under\n * `startTransition`: updates after an await need their own transition.\n *\n * 2. Re-wrapping *inside* the async callback is not enough. Returning a\n * thenable from `startTransition` hands it to `ReactSharedInternals.S`,\n * which calls react-dom's `entangleAsyncAction`. That opens an action\n * scope: `currentEntangledLane` collects EVERY transition update\n * scheduled while the scope is open — including one from a nested,\n * fully synchronous `startTransition` — and rendering that lane throws\n * `currentEntangledActionThenable`, suspending until the action settles.\n * Which is after the promise `navigateTransition` hands back, so a caller\n * that awaits a navigation and then reads the DOM sees the departing\n * page, and the TIM-1301 publish (a layout effect on the commit) is just\n * as late. (Not `ReactSharedInternals.asyncTransitions` — that counter is\n * write-only in 19.2.7.)\n *\n * No async action is created here, so every navigation commits as soon as\n * React can render its destination — where TIM-1301 put it. That holds for\n * ALL of them. It used not to hold for `<Link>`, which wrapped\n * `router.navigate()` in its own `useTransition`: that action scope entangled\n * the root's updates just the same, so a Link navigation committed only once\n * the payload had finished decoding, and with it `pushState`, the segment\n * cache and `timber:navigation-end`. Link now calls `router.navigate()`\n * outside any transition and tracks its own `isPending` with a plain\n * `useState` (TIM-1307).\n *\n * Nothing here may reopen an action scope: no `startTransition` callback in\n * this path may return a thenable, and no caller may invoke this from inside\n * a React action scope — except one that settles that action at `handedOff`,\n * which commits the action and the tree together on purpose (a server action\n * redirect, TIM-1573). That is a rule about `startTransition`, not about\n * `perform` — `perform` is async by contract and is awaited OUTSIDE any\n * transition scope, which is exactly why it is safe.\n *\n * Standalone `startTransition` rather than `useTransition`'s is deliberate:\n * the hook's is tied to a single fiber and tracks one async callback at a\n * time, and two overlapping navigations through it corrupted React's hook\n * tracking (\"Rendered more hooks than during the previous render\"). Each\n * navigation needs an independent lane. This matches the Next.js pattern\n * (TIM-625): \"No useTransition in the router at all — only standalone\n * startTransition.\"\n *\n * See design/19-client-navigation.md §\"How Pending State Works\"\n */\n\nimport type { ReactNode } from 'react';\nimport type { NavigationRender } from './navigation-root.tsx';\n\n// ─── Transition Result ──────────────────────────────────────────\n\n/**\n * What a navigation's `perform()` hands back to the transition.\n *\n * Declared once and shared by every layer that passes it along — the router's\n * `RouterDeps.navigateTransition` imports it too — so a field cannot be added\n * to the producer and dropped by the adapter in between. `E` is the element\n * type: `ReactNode` here, `unknown` in the router, which never touches it.\n */\nexport interface TransitionResult<E = ReactNode> {\n /** The wrapped tree to render. */\n element: E;\n /** Resolves when the Flight stream finishes decoding, or null. */\n decodePromise: Promise<void> | null;\n /**\n * Publishes the navigation's state — segment cache, pathname, address bar,\n * history stack, and the client's record of the mounted tree — and\n * announces it to listeners outside React.\n *\n * Run when React commits this tree, not when the tree is handed over: a\n * tree React is still waiting on, or one a later navigation replaces first,\n * has been given to React without being on screen. A superseded navigation\n * never runs it and leaves every one of those consumers describing the\n * route still on screen (TIM-1301).\n */\n commit: () => void;\n}\n\n/** What happened to this navigation's tree. */\nexport type CommitOutcome = 'committed' | 'superseded' | 'failed';\n\n/**\n * A navigation as its caller sees it: three endings, which arrive in either\n * order.\n *\n * The handle itself is the promise that settles when the payload has\n * **decoded** — or the navigation was superseded or failed. Scroll\n * restoration, the Navigation API deferred and the router's pending store\n * are timed against it. It does not mean the destination is on screen: a\n * destination that streams commits before its decode finishes, and one\n * waiting on a Suspense boundary commits after.\n *\n * Built by attaching the other two endings to that promise, so awaiting a\n * navigation keeps meaning what it always has, and a caller that wants more\n * than one ending awaits them side by side instead of combining callbacks\n * by hand (TIM-1462).\n */\nexport interface NavigationHandle extends Promise<void> {\n /**\n * Resolves once the navigation's final tree — after any redirect the\n * router follows — has been handed to React: its transition is scheduled,\n * and React has not yet committed it. Never rejects.\n *\n * A navigation that ends without handing a tree over (superseded or\n * failed first) resolves it as it settles, so `router.navigate()` and\n * `refresh()` never leave it pending past the handle itself.\n * `navigateTransition`'s own handle does not — a redirect the router\n * follows hands its tree over later — so there it may never settle.\n *\n * A server action that redirects settles its `useActionState` here, so\n * React commits the action's result and the destination together\n * (TIM-1573).\n */\n readonly handedOff: Promise<void>;\n /**\n * Resolves exactly once, never rejects: `'committed'` when React commits\n * this navigation's tree, or — so nothing waits on a commit that will\n * never come — `'superseded'` or `'failed'` when it is abandoned:\n * superseded by a newer navigation (before or after its tree was handed\n * to React) or failed. A followed redirect is one logical navigation, so\n * this is the redirect hop's outcome. `<Link>` holds `isPending` until\n * both this and the decode have settled (TIM-1418).\n *\n * The one exception is a stale client, which leaves the SPA before it\n * navigates at all: the document is being replaced, and nothing on the\n * handle settles. A navigation that fails into a document load\n * (a server error, a non-RSC response, a version skew) settles this\n * `'failed'` before it leaves.\n */\n readonly committed: Promise<CommitOutcome>;\n}\n\n/** The outcome of a render that ended without committing. */\nexport function abandonedOutcome(owner: RenderOwner): CommitOutcome {\n return owner.outcome === 'superseded' ? 'superseded' : 'failed';\n}\n\n// ─── RenderOwner ────────────────────────────────────────────────\n\n/**\n * A per-render identity that replaces the transition counter, the\n * `handedOffNavAborts` set, and the `AbortController`-as-owner pattern.\n *\n * The navigation lifecycle holds one slot (`current: RenderOwner | null`).\n * All supersession is \"take the slot\":\n *\n * - Navigation takes unconditionally (previous owner gets settled + aborted\n * if !handedOff).\n * - Revalidation takes only if empty (epoch check).\n * - Handover gate before root.render checks `current === owner`.\n * - `settle()` is called from NavigationRoot publish (committed), slot\n * takeover (superseded), or rejection (failed).\n *\n * `settle()` records the outcome and resolves `displaced` for non-committed\n * outcomes. The `outcome` field is first-wins with one exception:\n * `settle('superseded')` overrides a prior `'committed'`, because a\n * committed-but-still-decoding navigation can be displaced by a successor\n * and the post-decode check must throw rather than letting the old\n * navigation continue.\n *\n * TIM-1481: replaces counter + waiters + bumpTransitionCounter +\n * supersedeNavigationTransitions + handedOffNavAborts + globalThis singleton.\n */\nexport interface RenderOwner {\n readonly kind: 'navigation' | 'revalidation';\n readonly fetchAbort: AbortController;\n handedOff: boolean;\n /** Sync read for the post-perform() check. null until settled. */\n outcome: CommitOutcome | null;\n /**\n * Resolves when this owner is displaced — a successor supersedes it or it\n * fails. Does NOT resolve on commit: a committed navigation still waits\n * for its decode to finish. Used to stop waiting on a decode that is no\n * longer this navigation's business.\n */\n readonly displaced: Promise<void>;\n /**\n * Record this owner's outcome and, for non-committed outcomes, resolve\n * `displaced`. First-wins with one exception: `settle('superseded')`\n * overrides a prior `'committed'`.\n */\n settle: (outcome: CommitOutcome) => void;\n}\n\n/**\n * Create a fresh RenderOwner. Exported so tests that call\n * `navigateTransition` directly can construct one without a router.\n */\nexport function createRenderOwner(kind: 'navigation' | 'revalidation'): RenderOwner {\n let resolveDisplaced!: () => void;\n const displaced = new Promise<void>((r) => {\n resolveDisplaced = r;\n });\n\n const owner: RenderOwner = {\n kind,\n fetchAbort: new AbortController(),\n handedOff: false,\n outcome: null,\n displaced,\n settle(outcome: CommitOutcome): void {\n if (owner.outcome === null) {\n owner.outcome = outcome;\n } else if (outcome === 'superseded' && owner.outcome === 'committed') {\n // A committed-but-still-decoding navigation can be displaced by a\n // successor. Override so the post-decode check throws AbortError\n // rather than letting the old navigation continue with scroll\n // restoration while a newer navigation is active.\n owner.outcome = 'superseded';\n }\n // Resolve `displaced` for any non-committed outcome, even if the\n // outcome field was already set. A committed-but-still-decoding\n // navigation must be woken when a successor supersedes it — the old\n // counter-based waiter did this because the counter bumped regardless\n // of commit state. A commit does NOT resolve displaced: that would\n // end the decode wait early, clearing pending state before the Flight\n // stream finishes.\n if (outcome !== 'committed') {\n resolveDisplaced();\n }\n },\n };\n return owner;\n}\n\n// ─── navigateTransition ─────────────────────────────────────────\n\n/**\n * Run a full navigation, handing its tree to React in a transition.\n *\n * The `perform` callback fetches the RSC payload, updates router state, and\n * returns the wrapped React element. `perform` is async by contract and runs\n * OUTSIDE any transition scope — only the `render` that hands its result over\n * is wrapped, in a synchronous `startTransition` (see the module comment).\n *\n * Do not call this from inside a React action scope, and never let a\n * `startTransition` callback in this path return a thenable: either opens an\n * action scope that entangles the update and defers the commit until the\n * action settles (TIM-1306, TIM-1307).\n *\n * Returns a `NavigationHandle` whose promise resolves when the async work\n * completes — the payload is fetched, decoded, and handed to React. It does\n * **not** wait for React to\n * commit the tree, so the state that publishes on that commit (address bar,\n * segment cache, history entry, pathname) may still be a beat behind when it\n * resolves. Anything that needs the destination to be current should listen\n * for `timber:navigation-end`, which is dispatched by the publish itself.\n *\n * Awaiting the publish here was tried and rejected: it makes the promise\n * depend on a React commit, which never arrives if the root unmounts\n * mid-navigation, and deadlocks any caller that awaits a navigation inside\n * `act()`.\n *\n * Rejects with an `AbortError` when a newer transition started while this\n * one's `perform()` was in flight — the stale tree is never handed to React\n * and its `commit` never runs (TIM-629, TIM-1301).\n *\n * The commit is the handle's `committed`, a separate promise that nothing is\n * forced to await — so it can depend on React where the decode promise must\n * not. It settles exactly once: when React commits this navigation's tree,\n * or when the navigation is abandoned instead — superseded by a newer\n * transition (before or after its tree was handed to React) or failed. It is\n * how `<Link>` keeps `isPending` up until the destination is on screen\n * without scheduling anything against React's lanes (TIM-1418).\n *\n * `types` are the view transition types `render` adds beside the tree\n * (design/37-navigation-api.md §\"Transition types\"). They are fixed before\n * `perform` runs — what a render animates as is decided by the operation that\n * started it, not by what the fetch returns.\n *\n * `owner` is the `RenderOwner` for this render (TIM-1481). Supersession is\n * detected via `owner.outcome` (sync) and `owner.displaced` (async).\n * No module-level state; no globalThis singleton.\n *\n * `handedOff` resolves right after `render` has scheduled the tree — in a\n * microtask, so before the Scheduler task that renders and commits it — and not\n * at all when the navigation ends first. A caller inside a React action scope\n * may settle that action there (and only there): the render is already\n * entangled with the scope, so settling commits the action and this tree\n * together, where settling earlier commits the action alone and settling on\n * the commit deadlocks. The server action redirect is that caller (TIM-1573).\n *\n * Used for: navigate(), refresh(), popstate with fetch.\n */\nexport function navigateTransition(\n owner: RenderOwner,\n perform: () => Promise<TransitionResult>,\n render: NavigationRender,\n types: readonly string[]\n): NavigationHandle {\n const superseded = () => new DOMException('Navigation superseded', 'AbortError');\n\n let handOff!: () => void;\n const handedOff = new Promise<void>((resolve) => (handOff = resolve));\n // Exactly once, on whichever comes first — a promise settles only once:\n // the commit, a supersession, or a failure.\n let settleCommit!: (outcome: CommitOutcome) => void;\n const committed = new Promise<CommitOutcome>((resolve) => (settleCommit = resolve));\n\n // Watch for displacement from outside (a successor taking the slot).\n void owner.displaced.then(() => {\n if (owner.outcome === 'superseded') settleCommit('superseded');\n });\n\n const decoded = (async () => {\n try {\n const { element, decodePromise, commit } = await perform();\n if (owner.outcome !== null) {\n decodePromise?.catch(() => {});\n throw superseded();\n }\n // Hand the tree over with its commit attached. NavigationRoot runs it if\n // and when React commits this tree, so a navigation that is superseded\n // while its payload streams publishes nothing (TIM-1301).\n //\n // This is THE update that must not hide the departing page (TIM-1306);\n // `render` is the synchronous transition around `root.render`.\n render(\n element,\n () => {\n try {\n commit();\n } finally {\n settleCommit('committed');\n }\n },\n types\n );\n handOff();\n // React may commit the tree before this settles — that is the point:\n // the destination reveals as React is able to render it\n // rather than waiting for the whole Flight stream. The await is here so\n // the promise this function hands back still means \"the payload is\n // decoded\", which is what the router's scroll restoration and\n // `<Link>`'s `isPending` are timed against.\n //\n // ...unless this navigation loses first, in which case it stops waiting\n // on a stream that is no longer its business.\n if (decodePromise) {\n await settleOnDecodeOrDisplacement(decodePromise, owner);\n }\n if (owner.outcome !== null && owner.outcome !== 'committed') {\n throw superseded();\n }\n } catch (error) {\n settleCommit(abandonedOutcome(owner));\n throw error;\n }\n })();\n return Object.assign(decoded, { handedOff, committed });\n}\n\n/**\n * Wait for the payload to finish decoding, OR for this owner to be\n * displaced — whichever happens first.\n *\n * A superseded navigation must stop waiting on its own stream. The stream is\n * deliberately NOT aborted once its tree has been handed to React (the tree\n * may be on screen with boundaries still feeding from it — see\n * `RenderOwner.handedOff`), so there is nothing left to make `decodePromise`\n * settle promptly. Awaiting it bare would keep the loser's\n * `router.navigate()` promise pending for the rest of the stream — and\n * forever if it stalls — which is what `<Link>`'s `isPending` is timed\n * against, so the losing link would sit spinning while the winner loaded\n * (codex on #1004).\n *\n * A decode *failure* still propagates: it is a real error for this\n * navigation, and the caller's recovery is timed against it.\n */\nfunction settleOnDecodeOrDisplacement(\n decodePromise: Promise<void>,\n owner: RenderOwner\n): Promise<void> {\n // Only bail early for displacement (superseded/failed), not for commit.\n // A committed tree still needs to wait for its decode to finish — pending\n // state and the Link indicator are timed against it.\n if (owner.outcome !== null && owner.outcome !== 'committed') {\n return Promise.resolve();\n }\n return Promise.race([decodePromise, owner.displaced]);\n}\n","/**\n * Router Skew Recording — turning a rejection into \"this bundle is superseded\".\n *\n * Detection lives in `stale-client.ts`; this is the one place the router (and\n * anything else holding an RSC rejection) turns an error into that verdict.\n * Recovery is not here: every path that gives up on client-side navigation —\n * skew or not — leaves through `createSpaExits()` in `router-effects.ts`.\n *\n * See design/33-version-skew.md §\"Recovery on the next navigation\"\n */\n\nimport { VersionSkewError } from './rsc-fetch.ts';\nimport { markClientStale, markStaleFromError } from './stale-client.ts';\n\n/**\n * Record a version skew if `error` is one, and report whether it was.\n *\n * `VersionSkewError` is the origin saying so outright; the reactive shapes are\n * inferred from the error text and are a no-op in dev.\n *\n * Closes over nothing — anywhere an RSC payload can fail needs it, including\n * places that have no router instance to hand.\n */\nexport function recordSkew(error: unknown): boolean {\n if (error instanceof VersionSkewError) {\n markClientStale();\n return true;\n }\n return markStaleFromError(error);\n}\n","/**\n * Router Effects — full-page navigation and post-paint scroll.\n *\n * The two things the router does *to the document* rather than to its own\n * state: leaving the SPA entirely, and moving the scroll position once React\n * has committed. Extracted from `router.ts` to keep that file focused on\n * navigation state (see design/18-build-system.md §\"No file >500 lines\").\n *\n * See design/19-client-navigation.md §\"Scroll Restoration\"\n */\n\nimport { setHardNavigating } from './navigation-root.tsx';\nimport {\n abandonedOutcome,\n type CommitOutcome,\n type NavigationHandle,\n type RenderOwner,\n} from './navigation-transition.ts';\nimport { RedirectError, ServerErrorResponse, NonRscResponse } from './rsc-fetch.ts';\nimport { recordSkew } from './router-skew.ts';\n\n/** The subset of `RouterDeps` the post-paint scroll effects need. */\nexport interface ScrollEffectDeps {\n scrollTo: (x: number, y: number) => void;\n afterPaint?: (callback: () => void) => void;\n scrollToHash?: (hash: string) => boolean;\n}\n\nexport interface ScrollEffects {\n /**\n * Schedule scroll restoration after the next paint and fire the\n * scroll-restored event. Used by navigate, popstate, and refresh.\n */\n restoreScrollAfterPaint: (scrollY: number) => void;\n /**\n * Scroll to the element matching the URL #fragment after paint, falling\n * back to scroll-to-top when no element matches (matching full-page-load\n * behavior for an unknown fragment). Used by forward navigation to a\n * hash-bearing URL (TIM-1035).\n */\n scrollToHashAfterPaint: (hash: string) => void;\n}\n\nexport function createScrollEffects(deps: ScrollEffectDeps): ScrollEffects {\n /** Run a callback after the next paint (after React commit). */\n function afterPaint(callback: () => void): void {\n if (deps.afterPaint) {\n deps.afterPaint(callback);\n } else {\n callback();\n }\n }\n\n function restoreScrollAfterPaint(scrollY: number): void {\n afterPaint(() => {\n deps.scrollTo(0, scrollY);\n window.dispatchEvent(new Event('timber:scroll-restored'));\n });\n }\n\n function scrollToHashAfterPaint(hash: string): void {\n afterPaint(() => {\n if (deps.scrollToHash?.(hash) !== true) {\n deps.scrollTo(0, 0);\n }\n window.dispatchEvent(new Event('timber:scroll-restored'));\n });\n }\n\n return { restoreScrollAfterPaint, scrollToHashAfterPaint };\n}\n\n/**\n * Leave the SPA and never come back.\n *\n * Every router path that gives up on client-side navigation does the same\n * three things: flag the hard navigation so the Navigation API and React stop\n * acting on a dying document, perform the document load, then block forever so\n * the caller cannot carry on rendering into it. The returned promise is\n * deliberately unresolvable — `location` assignment does not stop this turn of\n * the event loop.\n *\n * Callers: server error, non-RSC response, and every version skew path\n * ([33-version-skew.md](../../../../design/33-version-skew.md)).\n */\nexport function leaveSpa(url: string, fromUrl: string): Promise<never> {\n setHardNavigating(true);\n hardNavigate(url, fromUrl);\n return new Promise<never>(() => {});\n}\n\nexport interface SpaExitDeps {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n /** Supersede whatever is in flight and take ownership. */\n supersede: () => void;\n}\n\nexport interface SpaExits {\n /**\n * Leave the SPA — but only if `owner` still owns the router. Every\n * failure a navigation can end on (a server error, a non-RSC response, a\n * version skew) can surface long after the user has clicked something else:\n * a fetch that was never cancellable, a Flight thenable that rejects late.\n * Hard navigating to the abandoned URL would undo that click, so a\n * navigation that no longer owns the router does nothing and lets the one\n * that does drive. Never resolves when it does navigate.\n *\n * Must be called from inside the `runNavigation()` callback. That function's\n * `finally` clears the current controller, so an ownership check downstream\n * of it compares against `null` and never leaves at all.\n */\n leaveSpaIfOwned: (owner: RenderOwner, url: string, fromUrl: string) => Promise<void>;\n\n /**\n * Leave the SPA from a path that never entered `runNavigation()` — the\n * stale-client short circuits, which decide before any fetch is attempted.\n *\n * Supersedes first. Nothing else on those paths takes ownership, so without\n * it an in-flight navigation keeps the router: when its fetch or decode\n * fails a moment later it still passes its own ownership check and hard\n * navigates to *its* URL, overwriting the document load started here.\n */\n leaveSpaSuperseding: (url: string, fromUrl: string) => Promise<never>;\n}\n\n/**\n * The two ownership-aware ways out of the SPA.\n *\n * Both wrap {@link leaveSpa} with the question \"is this navigation still the\n * one the user is waiting for?\" — asked before leaving on a failure, answered\n * by force on a path that decided before any navigation began. They live\n * together because every caller of `leaveSpa()` needs one or the other, and\n * an unguarded call is the bug (TIM-1275, TIM-1276).\n */\nexport function createSpaExits({ currentOwner, supersede }: SpaExitDeps): SpaExits {\n async function leaveSpaIfOwned(owner: RenderOwner, url: string, fromUrl: string): Promise<void> {\n if (currentOwner() !== owner) return;\n await leaveSpa(url, fromUrl);\n }\n\n function leaveSpaSuperseding(url: string, fromUrl: string): Promise<never> {\n supersede();\n return leaveSpa(url, fromUrl);\n }\n\n return { leaveSpaIfOwned, leaveSpaSuperseding };\n}\n\nexport interface NavigationRecoveryDeps {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n leaveSpaIfOwned: SpaExits['leaveSpaIfOwned'];\n /**\n * Follow a redirect to `url` — the router's own `navigate()`, carrying\n * the interrupted navigation's {@link RedirectHop}.\n */\n navigate: (url: string, hop: RedirectHop) => NavigationHandle;\n}\n\n/**\n * What a redirect hop inherits from the navigation the redirect interrupted.\n */\nexport interface RedirectHop {\n /**\n * The view transition types of the interrupted render, so a redirected Back\n * still animates as Back and a link's own `transitionTypes` survive the\n * hop (TIM-1471).\n */\n types: readonly string[];\n /**\n * The interrupted navigation's history mode. A push stays a push: the\n * address bar moves only when a destination commits, so the interrupted\n * navigation wrote no entry, and replacing would overwrite the page being\n * left — Back would skip it (TIM-1571). A refresh or a traversal replaces:\n * the browser is already on the entry being redirected.\n */\n replace: boolean;\n /**\n * The interrupted navigation's scroll mode. `<Link scroll={false}>` to a\n * URL that redirects — a non-canonical `/x/` among them — still keeps the\n * scroll position; the hop would otherwise default to scrolling to the top.\n */\n scroll: boolean;\n}\n\n/**\n * The endings a navigation reports beside its decode — the `handedOff` and\n * `committed` of its {@link NavigationHandle} — fed by the renders it runs.\n *\n * A followed redirect is one logical navigation, so its endings are the\n * redirect hop's: the hop's commit is the one the caller is waiting for.\n * `<Link>` holds `isPending` until it, and a `'failed'` from the\n * interrupted render would release it on the hop's decode, ahead of a\n * commit React is still holding (TIM-1571). A server action redirect waits\n * for the tree that is finally handed to React, which is the redirected one\n * (TIM-1573). So a render's `'failed'` is not this navigation's:\n * `navigateTransition` settles it as soon as `perform` throws, before the\n * router knows the failure is a redirect it will follow. Recovery decides,\n * and either adopts the hop or settles the outcome itself.\n */\nexport interface NavigationEndings {\n /** Report a render's endings — every outcome but `'failed'` at once. */\n track(render: NavigationHandle): void;\n /** Make a redirect hop's endings this navigation's. */\n adopt(hop: NavigationHandle): void;\n /** Settle `committed`. The first outcome wins. */\n settle(outcome: CommitOutcome): void;\n}\n\n/**\n * Run a navigation as a {@link NavigationHandle}. `run` is the navigation:\n * its promise is the handle's decode, and it reports its renders' other\n * endings into the {@link NavigationEndings} it is given.\n *\n * A navigation that ends without reporting — superseded, or failed, before\n * any render — settles them as it ends: `committed` as `'failed'` if it\n * rejected (an outcome already reported wins), and `handedOff` either way,\n * so neither waits on a render that will not come.\n */\nexport function runAsHandle(run: (endings: NavigationEndings) => Promise<void>): NavigationHandle {\n let handOff!: () => void;\n const handedOff = new Promise<void>((resolve) => (handOff = resolve));\n let settle!: (outcome: CommitOutcome) => void;\n const committed = new Promise<CommitOutcome>((resolve) => (settle = resolve));\n const endings: NavigationEndings = {\n track(render) {\n void render.handedOff.then(handOff);\n void render.committed.then((outcome) => {\n if (outcome !== 'failed') settle(outcome);\n });\n },\n adopt(hop) {\n void hop.handedOff.then(handOff);\n void hop.committed.then(settle);\n },\n settle,\n };\n // Handled here and rethrown, so a caller that ignores the handle still\n // sees the rejection as unhandled — the regime `useRouter().push()` relies\n // on.\n const decoded = run(endings).then(handOff, (error: unknown) => {\n settle('failed');\n handOff();\n throw error;\n });\n return Object.assign(decoded, { handedOff, committed });\n}\n\n/**\n * The URL a redirect hop navigates to. A redirect target without a fragment\n * keeps the one the navigation asked for, as a browser does for a 3xx\n * (RFC 9110 §10.2.2): the server never sees the fragment, so a soft redirect\n * — `<Link href=\"/docs/#install\">` answered with `/docs` — cannot carry it.\n */\nexport function redirectHopUrl(redirectUrl: string, requestedUrl: string): string {\n if (redirectUrl.includes('#')) return redirectUrl;\n const hashIndex = requestedUrl.indexOf('#');\n return hashIndex === -1 ? redirectUrl : redirectUrl + requestedUrl.slice(hashIndex);\n}\n\n/**\n * Answer the failures an RSC fetch can end on, or report that this one is not\n * ours to answer.\n *\n * Returns `true` when the error was handled; the caller rethrows on `false`.\n * Handling a failure by leaving the SPA never resolves at all — the document\n * is going away and the caller must not carry on rendering into it.\n *\n * There is exactly one family of these and one response to it, so it lives in\n * one function rather than once per fetch path. `navigate()`, `refresh()` and\n * an uncached traversal all reach it: the latter two used to rethrow instead,\n * and since nobody awaits a traversal that meant pressing Back on a 500 left\n * the user on the old document with an unhandled rejection (TIM-1277).\n *\n * Order matters in exactly one way: `recordSkew()` ends in error-*text*\n * matching, so it goes last and can never pre-empt a framework control-flow\n * signal whose message happens to read like a stale bundle. The class checks\n * above it are mutually exclusive, so their order is free.\n *\n * Must be called from inside the `runNavigation()` callback — see\n * {@link SpaExits.leaveSpaIfOwned}.\n */\nexport function createNavigationRecovery({\n currentOwner,\n leaveSpaIfOwned,\n navigate,\n}: NavigationRecoveryDeps) {\n return async function recoverFromNavigationError(\n error: unknown,\n owner: RenderOwner,\n url: string,\n fromUrl: string,\n /** What a redirect hop inherits from the navigation that failed. */\n hop: RedirectHop,\n /** The failed navigation's endings; a followed redirect's become them. */\n endings: NavigationEndings\n ): Promise<boolean> {\n if (error instanceof RedirectError) {\n // Same ownership rule as leaving the SPA: a superseded navigation must\n // not steer the document to the destination it was abandoned for.\n if (currentOwner() !== owner) {\n endings.settle('superseded');\n return true;\n }\n const redirected = navigate(redirectHopUrl(error.redirectUrl, url), hop);\n endings.adopt(redirected);\n await redirected;\n return true;\n }\n // Anything else ends this navigation here — superseded if a successor\n // took the router, failed otherwise.\n endings.settle(abandonedOutcome(owner));\n // A server error, a non-RSC response and a version skew all end the same\n // way: hand `url` back to the server as a document load, so it can render\n // the outcome as HTML (design/10-error-handling.md §\"Error Page Rendering\n // for Client Navigation\").\n if (\n error instanceof ServerErrorResponse ||\n error instanceof NonRscResponse ||\n recordSkew(error)\n ) {\n await leaveSpaIfOwned(owner, url, fromUrl);\n return true;\n }\n return false;\n };\n}\n\n/**\n * Perform the full document load.\n *\n * `fromUrl` is the URL the navigation departed from, passed explicitly\n * because the address bar may have already been updated.\n *\n * When the target differs from the departure point only by #fragment,\n * assigning `href` is a hash change, not a load — so assign first (to update\n * the address bar) and then reload (TIM-1235).\n */\nexport function hardNavigate(url: string, fromUrl: string): void {\n const current = new URL(fromUrl, window.location.origin);\n const target = new URL(url, window.location.origin);\n if (target.pathname === current.pathname && target.search === current.search) {\n window.location.href = url;\n window.location.reload();\n } else {\n window.location.href = url;\n }\n}\n","/**\n * OutletScopeContext — the decisions a skipped outlet hands to the outlets\n * nested directly inside it.\n *\n * A skipped outlet renders its cached content, and that content still holds\n * the nested `SegmentOutlet` elements from when it was committed — with\n * their old decisions. The skip carries the new ones (`SkipDecision.outlets`)\n * and provides them here, so each old outlet element renders its segment's\n * new decision in place: same element type, same position, so React keeps\n * every component's state below it.\n *\n * Every `SegmentOutlet` provides a scope to its content — the skip's\n * decisions, or none — so the element structure is the same whether a\n * segment was sent or skipped.\n *\n * Singleton across bundler-duplicated chunks via `createGlobalContext`.\n * See design/52-segment-hash-dedupe.md §\"Wire format\".\n */\n\n'use client';\n\nimport type { OutletDecisionValue } from '../shared/outlet-decision.ts';\nimport { createGlobalContext } from './global-context.ts';\n\nexport interface OutletScope {\n /**\n * Set inside a skipped outlet's cached content. There, an outlet with no\n * entry in `decisions` would render a stale decision, so it refuses to.\n */\n skipped: boolean;\n decisions: ReadonlyMap<string, OutletDecisionValue>;\n}\n\nexport const LIVE_OUTLET_SCOPE: OutletScope = Object.freeze({\n skipped: false,\n decisions: new Map<string, OutletDecisionValue>(),\n});\n\nexport const OutletScopeContext = createGlobalContext<OutletScope>(\n Symbol.for('__timber_outlet_scope_ctx'),\n LIVE_OUTLET_SCOPE\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","/**\n * The digest an unhandled render error carries across Flight, and the\n * correlation ID error pages read back out of it.\n *\n * Flight's `onError` (server/rsc-entry/rsc-stream.ts) returns this string for\n * any error that is not a deny or redirect, and React sets it as `digest` on\n * the Error it revives for that row, in SSR and on the client alike. The\n * `errorId` is the one the server logged the error with, so an error page\n * that shows it gives the reader something to quote that an operator can\n * find. It is the `digest` prop every TSX error page receives.\n *\n * `message` is the real message only in dev; production sends a fixed string\n * (design/13-security.md §\"Errors don't leak\").\n */\n\ninterface ErrorRowDigest {\n type: 'error';\n message: string;\n errorId: string;\n}\n\nexport function encodeErrorDigest(digest: Omit<ErrorRowDigest, 'type'>): string {\n const row: ErrorRowDigest = { type: 'error', ...digest };\n return JSON.stringify(row);\n}\n\n/**\n * The correlation ID in an error's Flight digest, or `null` when the error\n * carries none — a deny or redirect row, an error that never crossed Flight,\n * or anything that is not an object.\n */\nexport function errorDigestId(error: unknown): string | null {\n if (typeof error !== 'object' || error === null) return null;\n const digest: unknown = Reflect.get(error, 'digest');\n if (typeof digest !== 'string') return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(digest);\n } catch {\n // A digest someone else set (a library's own error): not ours to read.\n return null;\n }\n if (typeof parsed !== 'object' || parsed === null) return null;\n const errorId: unknown = Reflect.get(parsed, 'errorId');\n return Reflect.get(parsed, 'type') === 'error' && typeof errorId === 'string' ? errorId : null;\n}\n","/**\n * The error a `SegmentOutlet` throws when it cannot render what the server\n * decided — a skip whose content the client no longer holds under that hash,\n * or an outlet inside a skipped segment that received no new decision.\n *\n * Either means the client's record moved on between the request and the\n * response (a prefetch consumed late, a replayed payload whose content was\n * evicted). Rendering anything else would show content the server did not\n * produce, so the error passes every boundary to the terminal, which fetches\n * the page again (`recoverFromStaleSegment`) — and leaves the SPA only if\n * that misses too (design/52 §\"The client checks before reusing\").\n */\n\nexport interface StaleSegmentDigest {\n type: 'stale-segment';\n leaveSpa: true;\n}\n\nexport function staleSegmentError(segmentPath: string): Error {\n const error = new Error(`[timber] content for segment \"${segmentPath}\" is no longer held`);\n const digest: StaleSegmentDigest = { type: 'stale-segment', leaveSpa: true };\n (error as Error & { digest: string }).digest = JSON.stringify(digest);\n return error;\n}\n\n/** The router surface recovery needs. */\ninterface RecoveryRouter {\n getPendingUrl(): string | null;\n navigate(url: string, options?: { replace?: boolean; scroll?: boolean }): PromiseLike<unknown>;\n refresh(): PromiseLike<unknown>;\n}\n\n/** A recovery in flight: a second stale segment during it leaves the SPA. */\nlet recovering = false;\n\n/**\n * Answer a stale segment by fetching the page again inside the SPA. The new\n * request advertises only what the client holds now, so every skip it gets\n * names content that is there. A navigation still in flight is re-requested;\n * otherwise the page on the address bar — a traversal has already moved it —\n * is refreshed, which sends no hashes at all.\n *\n * Returns false when the caller should leave the SPA instead: there is no\n * router, or this miss happened while recovering from the last one.\n */\nexport function recoverFromStaleSegment(router: RecoveryRouter | null): boolean {\n if (!router || recovering) return false;\n recovering = true;\n const pending = router.getPendingUrl();\n const done = () => {\n recovering = false;\n };\n queueMicrotask(() => {\n const handle = pending\n ? router.navigate(pending, { replace: true, scroll: false })\n : router.refresh();\n Promise.resolve(handle).then(done, done);\n });\n return true;\n}\n","'use client';\n\n/**\n * Framework-injected React error boundary.\n *\n * Catches errors thrown by children and renders a fallback component\n * with the appropriate props based on error type:\n * - DenySignal (4xx) → { status, data }\n * - Unhandled error (500) → { error, digest, reset }, where `digest` is the\n * ID the server logged the error with (shared/error-digest.ts)\n *\n * The `status` prop controls which errors this boundary catches:\n * - Specific code (e.g. 403) → only that status\n * - Category (400) → any 4xx\n * - Category (500) → any 5xx\n * - Omitted → catches everything (error.tsx behavior)\n *\n * See design/10-error-handling.md §\"Status-Code Files\"\n */\n\nimport {\n Component,\n createContext,\n createElement,\n useContext,\n useEffect,\n useRef,\n type ReactNode,\n} from 'react';\nimport { OutletScopeContext } from './outlet-scope-context.ts';\nimport { getRouterOrNull } from './router-ref.ts';\nimport { markStaleFromError } from './stale-client.ts';\nimport { StatusPageMarker } from './status-page-marker.tsx';\nimport { errorDigestId } from '../shared/error-digest.ts';\nimport { leaveSpa } from './router-effects.ts';\n// Page unload detection: when the page is being torn down, error boundaries\n// suppress activation — the error is from the aborted connection, not the\n// application. unload-guard.ts is the single owner of that state; this module\n// used to keep its own copy, which drifted (TIM-1260).\nimport { isPageUnloading } from './unload-guard.ts';\nimport { recoverFromStaleSegment, type StaleSegmentDigest } from './stale-segment.ts';\n\n// ─── Ancestry Context ────────────────────────────────────────────────────────\n\n/**\n * Tracks the chain of segment keys from root to the current boundary.\n * Each keyed `TimberErrorBoundary` appends its `segmentKey`; unkeyed\n * slot boundaries pass the parent value through. The claim rule uses\n * this to find the first *reachable* owner from the `owners` list,\n * eliminating the owner-below-throw-site escape. See TIM-1450.\n */\nconst DenyAncestryContext = createContext<readonly string[]>([]);\n\nexport { DenyAncestryContext };\n\n// ─── Digest Types ────────────────────────────────────────────────────────────\n\n/** Structured digest returned by RSC onError for DenySignal. */\ninterface DenyDigest {\n type: 'deny';\n status: number;\n data: unknown;\n /**\n * Ordered candidate owners — segment keys of segments with matching deny\n * pages, best match first. Present = addressed (a boundary should render\n * it). In-tree hoists produce a single-element list; late addressing\n * (TIM-1450) produces the full candidate list so the boundary can find the\n * first *reachable* owner via its ancestry context.\n */\n owners?: string[];\n /**\n * A deny no boundary in this tree may place: a gate for a segment of the\n * URL's own route that an intercepted navigation did not render (TIM-1607).\n * Every boundary declines it but the terminal, which leaves the SPA.\n */\n leaveSpa?: boolean;\n}\n\n/** Structured digest returned by RSC onError for RedirectSignal. */\ninterface RedirectDigest {\n type: 'redirect';\n location: string;\n status: number;\n}\n\ntype ParsedDigest = DenyDigest | RedirectDigest | StaleSegmentDigest;\n\n// ─── Props & State ───────────────────────────────────────────────────────────\n\nexport interface TimberErrorBoundaryProps {\n /** The component to render when an error is caught. */\n fallbackComponent?: (...args: unknown[]) => ReactNode;\n /**\n * Status code filter. If set, only catches errors matching this status.\n * 400 = any 4xx, 500 = any 5xx, specific number = exact match.\n */\n status?: number;\n /**\n * When true, this boundary wraps a parallel slot. Slot denials are\n * graceful degradation: the boundary claims any addressed deny that\n * reaches it and leaves the page's segment chain unmarked.\n */\n isSlotBoundary?: boolean;\n /**\n * Segment key of the segment that declared this boundary. Only meaningful\n * against a deny digest carrying `owners`. See the decline rule in\n * `render()` and TIM-1356.\n */\n segmentKey?: string;\n /**\n * Catch denies only; re-throw everything else. Set on the copy of a\n * segment's boundaries placed outside its layout, which gives a deny thrown\n * from that layout's own chrome a catcher keyed to the segment — without\n * changing where a 5xx from the same chrome goes. See TIM-1450.\n */\n denyOnly?: boolean;\n /**\n * The deny chain's terminal: the outermost framework boundary, which claims\n * any deny that streamed past every segment boundary and renders the\n * framework default page. Implies `denyOnly`. Only a deny thrown from a\n * layout's chrome with no status file at or above that layout gets here —\n * the segment copies (`denyOnly`) claim every other shape. See TIM-1450.\n */\n lastResort?: boolean;\n children: ReactNode;\n}\n\ninterface TimberErrorBoundaryState {\n hasError: boolean;\n error: Error | null;\n}\n\n// Module-level guard: the first boundary to catch a given redirect digest\n// schedules the navigation and marks it handled here. Subsequent renders\n// (React retries the error-boundary render path multiple times in dev, and\n// outer boundaries that also see the error) become no-ops, preventing\n// duplicate router.navigate() calls.\nconst _handledRedirects = new WeakSet<object>();\n\n// The same guard for the terminal's exit: React may render the fallback\n// path more than once for one error, and the document load must start once.\nconst _handledExits = new WeakSet<object>();\n\n// Companion guard keyed by location: client-render redirect() (the\n// next/navigation shim) throws a FRESH error instance on every render\n// attempt, and React replays the errored render — so the WeakSet alone\n// would schedule the navigation twice. While a navigation to a location\n// is pending, further redirect errors for the same location are no-ops.\nlet _pendingRedirectLocation: string | null = null;\n\n// ─── Component ───────────────────────────────────────────────────────────────\n\n/**\n * Resets a boundary showing an error once a new navigation reaches it.\n *\n * Live content resets the boundary through new `children`. Content a skip\n * reuses (design/52) is the same element tree as before — the boundary sees\n * the same `children` and would keep showing the old error, never mounting\n * the nested outlet that holds the new decision. What a skip does change is\n * the outlet scope: a new one for every decision. A scope other than the one\n * the error was shown under is a navigation that reached this boundary.\n */\nfunction ResetOnNewDecisions({ reset, children }: { reset: () => void; children?: ReactNode }) {\n const scope = useContext(OutletScopeContext);\n const shownUnder = useRef(scope);\n useEffect(() => {\n if (scope !== shownUnder.current) reset();\n }, [scope, reset]);\n return children;\n}\n\nexport class TimberErrorBoundary extends Component<\n TimberErrorBoundaryProps,\n TimberErrorBoundaryState\n> {\n constructor(props: TimberErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n static getDerivedStateFromError(error: Error): TimberErrorBoundaryState {\n // Suppress error boundaries during page unload (refresh/navigate away).\n // The aborted connection causes React's streaming hydration to error,\n // but the page is about to be replaced — showing an error boundary\n // would be a jarring flash for the user.\n if (isPageUnloading()) {\n return { hasError: false, error: null };\n }\n\n return { hasError: true, error };\n }\n\n componentDidCatch(error: Error): void {\n // A stale bundle most often surfaces here rather than as a rejected\n // navigation: a client reference missing from this build's manifest, or\n // a lazily-imported chunk the CDN no longer has, thrown during render.\n //\n // Recording it is all that happens — this boundary still renders its\n // fallback, and the recovery is the user's next navigation, which the\n // router turns into a full document load. Reloading from here would be a\n // page load the user did not ask for, on a page that may be mid-rollout\n // and would come back just as stale (TIM-1275).\n markStaleFromError(error);\n }\n\n componentDidUpdate(prevProps: TimberErrorBoundaryProps): void {\n // Reset error state when children change (e.g. client-side navigation).\n // Without this, navigating from one error page to another keeps the\n // stale error — getDerivedStateFromError doesn't re-fire for new children.\n if (this.state.hasError && prevProps.children !== this.props.children) {\n this.setState({ hasError: false, error: null });\n }\n }\n\n /** Reset the error state so children re-render. */\n private reset = () => {\n this.setState({ hasError: false, error: null });\n };\n\n static override contextType = DenyAncestryContext;\n declare context: readonly string[];\n\n private get childAncestry(): readonly string[] {\n const parent = this.context ?? [];\n const key = this.props.segmentKey;\n // A segment has two keyed boundary sets (outside and inside its layout);\n // the inner one sees its own key already present and adds nothing.\n return key && !parent.includes(key) ? [...parent, key] : parent;\n }\n\n render(): ReactNode {\n if (!this.state.hasError || !this.state.error) {\n return createElement(\n DenyAncestryContext.Provider,\n { value: this.childAncestry },\n this.props.children\n );\n }\n return createElement(\n ResetOnNewDecisions,\n { reset: this.reset },\n this.fallback(this.state.error)\n );\n }\n\n private fallback(error: Error): ReactNode {\n const parsed = parseDigest(error);\n\n // RedirectSignal handling splits by environment:\n //\n // - SSR (no window): re-throw so the Fizz shell fails and the server\n // pipeline catch block can produce a proper HTTP 3xx response. See\n // design/04-authorization.md.\n //\n // - Client (window exists): a RedirectSignal that leaked into the RSC\n // Flight payload during client navigation would otherwise bubble past\n // every error boundary to `window.onerror`, which in dev triggers the\n // Vite error overlay (false positive — navigation itself works).\n // Instead, ask the router to perform an SPA navigation to the target\n // and render nothing while it takes over. The router's own catch path\n // handles cross-origin / hard navigations. See TIM-838.\n if (parsed?.type === 'redirect') {\n if (typeof window === 'undefined') {\n throw error;\n }\n // Dedupe: React may render the error-boundary fallback path more\n // than once for a single caught error (dev-mode double render, and\n // additional boundaries above us in the tree). Only schedule the\n // navigation on the first render that sees this error instance.\n const alreadyHandled =\n _handledRedirects.has(error) || _pendingRedirectLocation === parsed.location;\n if (!alreadyHandled) {\n _handledRedirects.add(error);\n const router = getRouterOrNull();\n if (router) {\n _pendingRedirectLocation = parsed.location;\n // Schedule the navigation outside the render phase to avoid\n // setState-during-render warnings from router state updates.\n queueMicrotask(() => {\n router\n .navigate(parsed.location, { replace: true })\n .catch(() => {\n // Fall back to a hard navigation if the soft navigation fails.\n window.location.href = parsed.location;\n })\n .finally(() => {\n _pendingRedirectLocation = null;\n });\n });\n } else {\n // No router available (shouldn't happen post-bootstrap) — fall\n // back to a hard navigation so the user still ends up at the\n // target.\n window.location.href = parsed.location;\n }\n }\n // Nothing to show, but still a subtree replaced: a layout that\n // redirected after I/O never mounted its children, and the commit that\n // renders this empty spot must not teach the cache otherwise — or the\n // redirect's own navigation would advertise those layouts as mounted\n // and the server would skip into an outlet the client does not have.\n return this.markStatusPage(null);\n }\n\n // An error the tree cannot hold: a deny whose deny pages, and the\n // layouts they render in, belong to a route this tree is not (TIM-1607),\n // or a skipped segment whose content the client no longer holds\n // (client/stale-segment.ts). Nothing here may claim it — not a keyed\n // owner, not a slot, not a status filter — so it passes every boundary to\n // the terminal, which leaves the SPA below and lets the document request\n // render the URL's own answer.\n const leavesSpa = parsed?.type !== 'deny' || parsed.leaveSpa === true;\n if (parsed && 'leaveSpa' in parsed && parsed.leaveSpa && !this.props.lastResort) {\n throw error;\n }\n\n // Owner-addressed denies: the digest carries an ordered `owners` list\n // of segment keys with matching deny pages. This boundary claims the\n // deny only when it is the first *reachable* owner — i.e. its\n // segmentKey appears in `owners` AND in its ancestry (the chain from\n // root to here). Unreachable owners (below the throw site) are skipped,\n // and the first ancestor that IS reachable claims. This eliminates the\n // owner-below-throw-site escape (TIM-1450).\n //\n // Unkeyed boundaries (slots, or boundaries without deny chains) never\n // claim an addressed deny. See TIM-1356.\n if (parsed?.type === 'deny' && Array.isArray(parsed.owners) && parsed.owners.length > 0) {\n // Slot boundaries always claim addressed denies — graceful degradation\n // within the slot is correct regardless of which segment the owner\n // chain resolved to. Without this, the deny escapes the slot and\n // becomes a page-level 4xx. See TIM-1450.\n if (!this.props.lastResort && !this.props.isSlotBoundary) {\n const reachable = parsed.owners.find((k: string) => this.childAncestry.includes(k));\n if (!this.props.segmentKey || reachable !== this.props.segmentKey) {\n throw error;\n }\n }\n }\n // Deny-only boundaries (the outer segment copies) re-throw everything\n // else so a crash in a layout's chrome still reaches the documented 5xx\n // flow instead of a status page for an unrelated error.\n if (this.props.denyOnly && !this.props.lastResort && parsed?.type !== 'deny') {\n throw error;\n }\n // The terminal is where that flow ends on the client. A non-deny row\n // nothing claimed — a crash on a route with no\n // matching `error.tsx` — has no page to render in-SPA; React would\n // unmount the root. So the terminal does what the router does for an\n // error envelope (design/10 §\"Error Page Rendering for Client\n // Navigation\"): leave the SPA, and let the document request render the\n // real error page with the real status. On the server it re-throws so\n // the Fizz shell fails and the pipeline serves that page directly. The\n // envelope still covers errors that land inside Flight's opening window;\n // this covers the ones that land after it, which used to be held for\n // (TIM-1495, TIM-1497). A deny the tree cannot hold (above) leaves the\n // same way, for the same reason: no page for it exists in this SPA.\n if (this.props.lastResort && leavesSpa) {\n if (typeof window === 'undefined') {\n throw error;\n }\n if (!_handledExits.has(error)) {\n _handledExits.add(error);\n const router = getRouterOrNull();\n // A skip whose content the client no longer holds: fetch the page\n // again inside the SPA, and leave only if that fails the same way.\n if (parsed?.type === 'stale-segment' && recoverFromStaleSegment(router)) return null;\n const current = window.location.pathname + window.location.search;\n // The row arrived for the navigation in flight, whose URL is not on\n // the address bar yet; fall back to the current document.\n const target = router?.getPendingUrl() ?? current;\n queueMicrotask(() => {\n void leaveSpa(target, current);\n });\n }\n return null;\n }\n\n // If this boundary has a status filter, check whether the error matches.\n // Non-matching errors re-throw so an outer boundary can catch them.\n if (this.props.status != null) {\n const errorStatus = getErrorStatus(parsed, error);\n if (errorStatus == null || !statusMatches(this.props.status, errorStatus)) {\n // Re-throw: this boundary doesn't handle this error.\n throw error;\n }\n }\n\n return this.markStatusPage(this.renderFallback(parsed, error));\n }\n\n /**\n * The status page this boundary shows for a row it claimed. Its shape is\n * the file's documented contract: TSX status files get `{ status,\n * data }`, `error.tsx` gets `{ error, digest, reset }` (plus\n * the deny extras for dual-shape implementations — without the error prop,\n * an error.tsx reading error.message crashes on deny fall-through, TIM-1081).\n */\n private renderFallback(parsed: ParsedDigest | null, error: Error): ReactNode {\n if (parsed?.type === 'deny') {\n if (this.props.status != null) {\n return createElement(this.props.fallbackComponent as never, {\n status: parsed.status,\n data: parsed.data,\n });\n }\n return createElement(this.props.fallbackComponent as never, {\n error: denyError(parsed.status, error),\n digest: null,\n reset: this.reset,\n status: parsed.status,\n data: parsed.data,\n });\n }\n\n // Unhandled error (500)\n return createElement(this.props.fallbackComponent as never, {\n error,\n digest: errorDigestId(error),\n reset: this.reset,\n });\n }\n\n /**\n * A status page (or, for a redirect row, nothing at all) replaced part of\n * the main route, and the segment cache must not learn a chain that never\n * mounted; the marker tells the navigation that commits this tree. A boundary that declined in `render()` re-threw\n * before getting here, so only the boundary that put a page on screen\n * speaks. A slot degrading leaves the page and its chain intact, so slot\n * boundaries stay silent. See `status-page-marker.tsx` (TIM-1495).\n */\n private markStatusPage(page: ReactNode): ReactNode {\n if (this.props.isSlotBoundary) return page;\n return createElement(StatusPageMarker, null, page);\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Parse the structured digest from the error.\n * React sets `error.digest` from the string returned by RSC's onError.\n */\nfunction parseDigest(error: Error): ParsedDigest | null {\n const raw = (error as { digest?: string }).digest;\n if (typeof raw !== 'string') return null;\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === 'object' && typeof parsed.type === 'string') {\n return parsed as ParsedDigest;\n }\n } catch (e) {\n console.debug('[timber] error digest is not valid JSON:', e instanceof Error ? e.message : e);\n }\n return null;\n}\n\n/**\n * The Error an `error.tsx` serving a deny should receive.\n *\n * The error that actually arrives here is React's, not the framework's: a\n * server-thrown error crossing Flight has its message and name replaced with\n * a generic redacted string in production, by design. An `error.tsx` written\n * per the docs branches on `error.message` — so handing it the redacted error\n * gives it nothing to branch on, while the in-tree path hands the same file a\n * `DenySignal` named error reading `Access denied with status <N>` (see\n * `renderDenyEntry`). This reconstructs that shape from the digest, which is\n * where the status already is.\n *\n * Derived from the status alone — no stack, no server data — so it is safe on\n * the client for the same reason the digest is. See design/13-security.md\n * §\"Errors don't leak\", TIM-1081.\n */\nfunction denyError(status: number, original: Error): Error {\n // A dev build may have preserved something more useful than the redaction.\n if (original.name === 'DenySignal') return original;\n const error = new Error(`Access denied with status ${status}`);\n error.name = 'DenySignal';\n return error;\n}\n\n/**\n * Extract the HTTP status code from a parsed digest or error message.\n * Falls back to message pattern matching for errors without a digest.\n */\nfunction getErrorStatus(parsed: ParsedDigest | null, error: Error): number | null {\n if (parsed?.type === 'deny') return parsed.status;\n if (parsed?.type === 'redirect') return parsed.status;\n\n // Fallback: parse DenySignal message pattern for errors that lost their digest\n const match = error.message.match(/^Access denied with status (\\d+)$/);\n if (match) return parseInt(match[1], 10);\n\n // Unhandled errors are implicitly 500\n return 500;\n}\n\n/**\n * Check whether an error's status matches the boundary's status filter.\n * Category markers (400, 500) match any status in that range.\n */\nfunction statusMatches(boundaryStatus: number, errorStatus: number): boolean {\n // Category catch-all: 400 matches any 4xx, 500 matches any 5xx\n if (boundaryStatus === 400) return errorStatus >= 400 && errorStatus <= 499;\n if (boundaryStatus === 500) return errorStatus >= 500 && errorStatus <= 599;\n // Exact match\n return boundaryStatus === errorStatus;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsEA,IAAa,sBAAuC;CAAE,QAAQ,CAAC;CAAG,YAAY;AAAK;;AAGnF,SAAS,mBAAmB,OAA0C;CACpE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,OAAQ,MAA0B,WAAW,YAC5C,MAA0B,WAAW;AAE1C;;;;;;;;AASA,SAAgB,oBAAoB,QAAkC;CACpE,IAAI,CAAC,mBAAmB,MAAM,GAAG,OAAO;CACxC,OAAO;EAAE,QAAQ,OAAO;EAAQ,YAAY,OAAO,cAAc;CAAK;AACxE;;;;;;;AAQA,SAAgB,gBAAgB,MAAwB;CACtD,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,QAAQ,mBAAmB,IAAI,GACxF,OAAQ,KAAwB;CAElC,OAAO;AACT;;;;;;;;AA2BA,SAAgB,iBAAiB,MAA6B;C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AAS,UAAU,QAAgB,UAAwB;CAEzD,IAAI,SAAS,SAAS,cAAc,OAAO;CAC3C,MAAM,wBAAQ,IAAI,MAAM,6BAA6B,QAAQ;CAC7D,MAAM,OAAO;CACb,OAAO;AACT;;;;;AAMA,SAAS,eAAe,QAA6B,OAA6B;CAChF,IAAI,QAAQ,SAAS,QAAQ,OAAO,OAAO;CAC3C,IAAI,QAAQ,SAAS,YAAY,OAAO,OAAO;CAG/C,MAAM,QAAQ,MAAM,QAAQ,MAAM,mCAAmC;CACrE,IAAI,OAAO,OAAO,SAAS,MAAM,IAAI,EAAE;CAGvC,OAAO;AACT;;;;;AAMA,SAAS,cAAc,gBAAwB,aAA8B;CAE3E,IAAI,mBAAmB,KAAK,OAAO,eAAe,OAAO,eAAe;CACxE,IAAI,mBAAmB,KAAK,OAAO,eAAe,OAAO,eAAe;CAExE,OAAO,mBAAmB;AAC5B"}
@@ -1,4 +1,4 @@
1
- import { a as DEFAULT_MAX_BUFFER_BYTES, f as releaseReason, l as teeBufferExceeded, m as onAbortUntil, p as endScope, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-omewa8e6.js";
1
+ import { a as DEFAULT_MAX_BUFFER_BYTES, f as releaseReason, l as teeBufferExceeded, m as onAbortUntil, p as endScope, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-yp8zdyRp.js";
2
2
  import { r as RenderTimeoutError } from "./render-timeout-MrrqD1wd.js";
3
3
  import { Readable, Transform, pipeline } from "node:stream";
4
4
  // src/server/node-body-response.ts
@@ -249,15 +249,18 @@ function destroyNodeFlight(stream, reason) {
249
249
  * Web `cancel(reason)` hands Flight. The listener and the timer are
250
250
  * released when the source closes.
251
251
  */
252
- function pipeFlightToNode(flight, { signal, timeoutMs }) {
252
+ function pipeFlightToNode(flight, { signal, timeoutMs, tap }) {
253
253
  const scope = new AbortController();
254
254
  const timer = timeoutMs === void 0 ? void 0 : setTimeout(() => flight.abort(new RenderTimeoutError(timeoutMs, "Flight render")), timeoutMs);
255
255
  const stream = new Transform({
256
256
  objectMode: true,
257
257
  transform(chunk, _encoding, callback) {
258
- callback(null, typeof chunk === "string" ? chunk.toWellFormed() : chunk);
258
+ const out = typeof chunk === "string" ? chunk.toWellFormed() : chunk;
259
+ tap?.observe(typeof out === "string" ? Buffer.from(out) : out);
260
+ callback(null, out);
259
261
  },
260
262
  destroy(error, callback) {
263
+ tap?.end();
261
264
  endScope(scope);
262
265
  clearTimeout(timer);
263
266
  if (error == null && stream.writableEnded) {
@@ -517,4 +520,4 @@ function whenNodeFlightReadable(source) {
517
520
  }
518
521
  export { destroyNodeFlight, nodeFlightResponse, pipeFlightToNode, teeNodeFlight, whenNodeFlightReadable };
519
522
 
520
- //# sourceMappingURL=flight-source-node-BsrlUjMO.js.map
523
+ //# sourceMappingURL=flight-source-node-D9cHBhjP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flight-source-node-D9cHBhjP.js","names":["ignoreError"],"sources":["../../src/server/node-body-response.ts","../../src/server/flight-source-node.ts"],"sourcesContent":["/**\n * `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a\n * response built on Node streams reaches the socket without a Web Streams\n * round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.\n *\n * The status and headers are an ordinary `Response`'s. The body stays a Node\n * stream until one of two things takes it:\n *\n * - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and\n * the dev server send with srvx; nitro-preview's sender speaks it too). The\n * stream is piped straight into `ServerResponse`.\n * - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …\n * The response then converts its body once, with `Readable.toWeb`, and\n * behaves as a native `Response` from then on. Correct anywhere, so code\n * that does not know about Node bodies keeps working; pipeline code on the\n * hot path goes through `node-response.ts` instead, which never converts.\n *\n * Pattern from srvx's `NodeResponse` (`FastResponse`).\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport { Readable, Transform, pipeline, type Duplex } from 'node:stream';\nimport { NODE_BODY, type NodeBodyOps } from './node-response.ts';\nimport { createStreamTimingRecorder, wrapResponseWithStreamTiming } from './stream-utils.ts';\n\n/** Statuses whose responses carry no body (Fetch \"null body status\"). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);\n\nfunction ignoreError(): void {}\n\n/** Destroy a body nothing will read, without an unhandled `'error'`. */\nfunction destroyBody(body: Readable): void {\n if (!body.listeners('error').includes(ignoreError)) body.on('error', ignoreError);\n body.destroy();\n}\n\nexport class NodeBodyResponse extends Response {\n #body: Readable | null;\n #native: Response | null = null;\n /** An adapter or a pipeline op took the body: it is used, as a read one is. */\n #taken = false;\n\n constructor(body: Readable, init?: ResponseInit) {\n super(null, init);\n if (NULL_BODY_STATUSES.has(this.status)) {\n destroyBody(body);\n this.#body = null;\n } else {\n this.#body = body;\n }\n }\n\n /** Take the Node body; this response no longer has it. */\n #take(): Readable | null {\n const body = this.#body;\n if (body) this.#taken = true;\n this.#body = null;\n return body;\n }\n\n /**\n * This response as a native one, converting the Node body once. Throws, as\n * a native Response whose body was read does, if something already took\n * the body (an adapter, a re-wrap), rather than reading as empty.\n */\n #toNative(): Response {\n if (!this.#native) {\n if (this.#taken) throw new TypeError('Body is unusable: Body has already been read');\n const body = this.#body;\n this.#body = null;\n this.#native = new Response(\n body ? (Readable.toWeb(body) as ReadableStream<Uint8Array>) : null,\n {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n }\n );\n }\n return this.#native;\n }\n\n get [NODE_BODY](): NodeBodyOps {\n return {\n hasBody: this.#native ? this.#native.body !== null : this.#body !== null,\n rewrap: (init) => {\n if (this.#native) return new Response(this.#native.body, init);\n const body = this.#take();\n return body ? new NodeBodyResponse(body, init) : new Response(null, init);\n },\n discard: () => {\n if (this.#native) {\n this.#native.body?.cancel().catch(() => {});\n return;\n }\n const body = this.#take();\n if (body) destroyBody(body);\n },\n through: (stream, init) => {\n const body = this.#native\n ? this.#native.body && webToNode(this.#native.body)\n : this.#take();\n return body\n ? new NodeBodyResponse(pipeThrough(body, stream), init)\n : new Response(null, init);\n },\n timed: (startTime) => {\n const init = { status: this.status, statusText: this.statusText, headers: this.headers };\n if (this.#native) {\n const native = this.#native.body;\n return new Response(\n native ? wrapResponseWithStreamTiming(native, startTime) : null,\n init\n );\n }\n const body = this.#take();\n return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;\n },\n };\n }\n\n /**\n * srvx's protocol for a response with a Node body: srvx pipes `body` into\n * `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`\n * list, as srvx's own `NodeResponse` returns them.\n */\n _toNodeResponse(): {\n status: number;\n statusText: string;\n headers: string[];\n body: Readable | ReadableStream<Uint8Array> | null;\n } {\n const headers: string[] = [];\n for (const [name, value] of this.headers) headers.push(name, value);\n return {\n status: this.status,\n statusText: this.statusText,\n headers,\n body: this.#native ? this.#native.body : this.#take(),\n };\n }\n\n // ─── Web API: convert once, then behave natively ─────────────────────────\n\n get body(): Response['body'] {\n return this.#toNative().body;\n }\n\n get bodyUsed(): boolean {\n return this.#native ? this.#native.bodyUsed : this.#taken;\n }\n\n /**\n * The other half of srvx's protocol: srvx/bun and srvx/deno send\n * `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),\n * and their runtimes stream Web bodies natively. Converts once.\n */\n get _response(): Response {\n return this.#toNative();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.#toNative().arrayBuffer();\n }\n\n blob(): Promise<Blob> {\n return this.#toNative().blob();\n }\n\n // Built from arrayBuffer(): its type satisfies both lib.dom's `bytes()` and\n // the Workers types', which some importers (the website) merge in.\n bytes(): Promise<Uint8Array<ArrayBuffer>> {\n return this.#toNative()\n .arrayBuffer()\n .then((buffer) => new Uint8Array(buffer));\n }\n\n formData(): Promise<FormData> {\n return this.#toNative().formData();\n }\n\n json(): Promise<unknown> {\n return this.#toNative().json();\n }\n\n text(): Promise<string> {\n return this.#toNative().text();\n }\n\n clone(): Response {\n return this.#toNative().clone();\n }\n}\n\n/** `body` piped through `stream`; an error or destroy on either end tears down both. */\nfunction pipeThrough(body: Readable, stream: Duplex): Duplex {\n stream.on('error', ignoreError);\n pipeline(body, stream, ignoreError);\n return stream;\n}\n\n/** A Web body already taken out of this response, back as a Node stream. */\nfunction webToNode(body: ReadableStream<Uint8Array>): Readable {\n return Readable.fromWeb(body as import('node:stream/web').ReadableStream<Uint8Array>);\n}\n\n/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */\nfunction timeBody(body: Readable, startTime: number): Readable {\n const timing = createStreamTimingRecorder(startTime);\n const timed = new Transform({\n transform(chunk: Uint8Array, _encoding, callback) {\n timing.chunk(chunk.byteLength);\n callback(null, chunk);\n },\n flush(callback) {\n timing.end(false);\n callback();\n },\n // Reached by the consumer leaving early (a cancellation) and by the\n // producer failing; the producer path records itself first, below, so a\n // render error is not logged as a disconnect — as the Web wrapper logs it.\n destroy(error, callback) {\n timing.end(true);\n body.destroy(error ?? undefined);\n callback(error);\n },\n });\n timed.on('error', ignoreError);\n body.on('error', (error) => {\n timing.end(false);\n timed.destroy(error);\n });\n body.pipe(timed);\n return timed;\n}\n","/**\n * Node halves of the Flight source helpers in `flight-source.ts`.\n *\n * Only loaded on Node (`flight-source.ts` imports it behind\n * `nodeStreamsPlatform`), so Workers never evaluate it.\n *\n * A Node Flight source is an object-mode `Readable` whose chunks are exactly\n * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short\n * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.\n * The Node Flight client (`createFromNodeStream`) requires every string chunk\n * in its original shape — it throws \"String chunks need to be passed in their\n * original shape\" if one is split or merged — so nothing here splits or\n * concatenates a chunk on its way to a consumer.\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\",\n * §\"Stream Tee\"\n */\n\nimport { Readable, Transform } from 'node:stream';\nimport { NodeBodyResponse } from './node-body-response.ts';\nimport { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';\nimport { endScope, onAbortUntil } from './abort-scope.ts';\nimport { RenderTimeoutError } from './render-timeout.ts';\nimport { releaseReason } from './render-utils.ts';\n\n// `String.prototype.toWellFormed` ships in every Node timber supports\n// (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file\n// only runs on Node.\ndeclare global {\n interface String {\n toWellFormed(): string;\n }\n}\n\n/** A chunk of a Node Flight source. */\nexport type NodeFlightChunk = string | Uint8Array;\n\n/** The part of React's `PipeableStream` a Flight render hands us. */\nexport interface PipeableFlight {\n pipe<T extends NodeJS.WritableStream>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\n/**\n * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits\n * `'error'`, and a stream whose consumer already detached (an iterator that\n * returned, a pipeline that finished) or has not attached yet would otherwise\n * turn a cancel into an uncaught exception. Real consumers attach their own\n * listeners, which still see every error.\n */\nfunction ignoreError(): void {}\n\n/**\n * Release a Node Flight source: destroy it with `reason`, which aborts the\n * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web\n * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws\n * and never leaves an unhandled `'error'` event, whoever is listening.\n */\nexport function destroyNodeFlight(stream: Readable, reason: unknown): void {\n if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);\n const error =\n reason === undefined || reason === null\n ? undefined\n : reason instanceof Error\n ? reason\n : new Error(String(reason));\n stream.destroy(error);\n}\n\n/** When a Node Flight render is aborted, besides its consumer cancelling. */\nexport interface NodeFlightAbort {\n /** The request's signal (client disconnect). */\n signal?: AbortSignal;\n /** Abort with a `RenderTimeoutError` after this long, if still rendering. */\n timeoutMs?: number;\n /** Shown every chunk, and the end (`FlightRenderOptions.tap`). */\n tap?: { observe(chunk: Uint8Array): void; end(): void };\n}\n\n/**\n * Pipe a Flight render into an object-mode Node source.\n *\n * - Strings pass through `toWellFormed()`, as Next does\n * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline\n * copy round-trips through JSON + `TextEncoder`, which turns a lone\n * surrogate into U+FFFD, so without it SSR and hydration see different\n * text. Length in UTF-16 units is unchanged, so a text row's length header\n * still holds.\n * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the\n * request signal fires, when `timeoutMs` passes (design/02 §\"Always Wire\n * abort() to Both Request Signal AND Timeout\"), and when the source is\n * destroyed (a consumer cancelling), with the destroy reason — the reason a\n * Web `cancel(reason)` hands Flight. The listener and the timer are\n * released when the source closes.\n */\nexport function pipeFlightToNode(\n flight: PipeableFlight,\n { signal, timeoutMs, tap }: NodeFlightAbort\n): Readable {\n const scope = new AbortController();\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),\n timeoutMs\n );\n const stream = new Transform({\n objectMode: true,\n transform(chunk: NodeFlightChunk, _encoding, callback) {\n const out = typeof chunk === 'string' ? chunk.toWellFormed() : chunk;\n tap?.observe(typeof out === 'string' ? Buffer.from(out) : out);\n callback(null, out);\n },\n destroy(error, callback) {\n tap?.end();\n endScope(scope);\n clearTimeout(timer);\n // Flight ended the stream (React calls `end()` once the render is\n // complete) and nothing failed: the render is over, so there is\n // nothing to release. Every normally finished render takes this path,\n // and `releaseReason()` would build a DOMException just for React to\n // ignore it (TIM-1626).\n if (error == null && stream.writableEnded) {\n callback(error);\n return;\n }\n // A no-op once Flight has finished (it ignores abort after close). A\n // release without a reason aborts with an AbortError, so the render's\n // onError does not log the abort (releaseReason, TIM-1597).\n flight.abort(releaseReason(error));\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n // The listener lasts until the stream is destroyed (server/abort-scope.ts).\n onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);\n flight.pipe(stream);\n return stream;\n}\n\n/** Bytes a chunk occupies, for the tee's divergence guard. */\nfunction chunkByteLength(chunk: NodeFlightChunk): number {\n return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n}\n\n/**\n * Tee a Node Flight source into two object-mode branches, with the contract\n * of `teeWithErrorPropagation` (`stream-utils.ts`):\n *\n * - Each branch has its own queue, so the lagging branch buffers without\n * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted\n * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:\n * the inline branch is not read until Fizz emits its first HTML chunk, and\n * Fizz needs SSR to consume Flight first, so a `pipe()` into two\n * PassThroughs would deadlock once the inline one filled.\n * - The source is read at the pace of the faster branch (paused only while\n * neither branch wants data), like a Web `tee()`.\n * - An error on the source, or a branch destroyed before it ended, destroys\n * the other branch with an error and destroys the source — which aborts the\n * render — so neither consumer hangs and both are released.\n */\nexport function teeNodeFlight(\n source: Readable,\n maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES\n): [Readable, Readable] {\n interface Branch {\n readable: Readable;\n queue: Array<NodeFlightChunk | null>;\n /**\n * Bytes this branch holds that its consumer has not read: the queue, plus\n * chunks pushed into the readable and still in its buffer.\n */\n heldBytes: number;\n /**\n * Sizes of the chunks pushed into the readable, oldest first, until the\n * consumer reads them. In object mode `readableLength` counts buffered\n * chunks, so any beyond it at the front have been consumed.\n */\n pushedSizes: number[];\n /** `_read` was called and nothing has been pushed since. */\n wanting: boolean;\n }\n\n let tornDown = false;\n const branches: [Branch, Branch] = [createBranch(), createBranch()];\n\n function createBranch(): Branch {\n const branch: Branch = {\n readable: new Readable({\n objectMode: true,\n read() {\n settle(branch);\n branch.wanting = true;\n drain(branch);\n },\n destroy(error, callback) {\n // A branch that ended normally releases nothing; one destroyed\n // early (its consumer cancelled, or teardown) takes the rest down.\n if (!branch.readable.readableEnded) {\n teardown(error ?? new Error('RSC stream tee branch cancelled'), error);\n }\n callback(error);\n },\n }),\n queue: [],\n heldBytes: 0,\n pushedSizes: [],\n wanting: false,\n };\n branch.readable.on('error', ignoreError);\n return branch;\n }\n\n /** Stop counting the pushed chunks the consumer has read. */\n function settle(branch: Branch): void {\n while (branch.pushedSizes.length > branch.readable.readableLength) {\n branch.heldBytes -= branch.pushedSizes.shift() ?? 0;\n }\n }\n\n function drain(branch: Branch): void {\n while (branch.wanting) {\n const chunk = branch.queue.shift();\n if (chunk === undefined) break;\n if (chunk === null) {\n branch.wanting = false;\n branch.readable.push(null);\n return;\n }\n branch.pushedSizes.push(chunkByteLength(chunk));\n branch.wanting = branch.readable.push(chunk);\n }\n if (branch.wanting && source.isPaused()) source.resume();\n }\n\n /**\n * Destroy both branches and the source. `branchError` is what the branches'\n * consumers see; `sourceReason` is what Flight is aborted with — the\n * consumer's own cancel reason, which may be `undefined`, as with a Web tee.\n */\n function teardown(branchError: Error, sourceReason: Error | null | undefined): void {\n if (tornDown) return;\n tornDown = true;\n source.off('data', onData);\n for (const branch of branches) {\n branch.queue.length = 0;\n branch.heldBytes = 0;\n branch.pushedSizes.length = 0;\n if (!branch.readable.destroyed) branch.readable.destroy(branchError);\n }\n source.destroy(sourceReason ?? undefined);\n }\n\n function onData(chunk: NodeFlightChunk): void {\n const bytes = chunkByteLength(chunk);\n for (const branch of branches) {\n branch.queue.push(chunk);\n branch.heldBytes += bytes;\n drain(branch);\n }\n // What the lagging branch holds is the divergence between the two.\n for (const branch of branches) settle(branch);\n const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);\n if (divergence > maxBufferBytes) {\n const error = teeBufferExceeded(maxBufferBytes, divergence);\n teardown(error, error);\n return;\n }\n if (!branches[0].wanting && !branches[1].wanting) source.pause();\n }\n\n const finished = finishedState(source);\n if (finished) {\n if ('error' in finished) teardown(finished.error, finished.error);\n else for (const branch of branches) branch.readable.push(null);\n return [branches[0].readable, branches[1].readable];\n }\n\n source.on('data', onData);\n source.on('end', () => {\n for (const branch of branches) {\n branch.queue.push(null);\n drain(branch);\n }\n });\n source.on('error', (error: Error) => teardown(error, error));\n source.on('close', () => {\n if (!source.readableEnded) {\n teardown(new Error('RSC stream closed before it ended'), undefined);\n }\n });\n\n return [branches[0].readable, branches[1].readable];\n}\n\n/**\n * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a\n * Node stream all the way to the adapter, which pipes it to the socket\n * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.\n *\n * Every chunk that arrives in one tick goes out as one buffer, with string\n * chunks encoded straight into it. React writes a flush synchronously, and\n * its Node build passes each long row as its own string: a heavy payload\n * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays\n * per write. The body pauses the source while the client is slow (a payload\n * never piles up in memory), destroying it early destroys the source (which\n * aborts the render), and an error or early close on the source ends it.\n * Wired by hand rather than with `pipeline()`, which allocates an\n * AbortController and an error on every finish.\n */\nexport function nodeFlightResponse(source: Readable, init: ResponseInit): Response {\n return new NodeBodyResponse(batchFlightBytes(source), init);\n}\n\n/** Largest batch the payload body coalesces before pushing (and checking backpressure). */\nconst MAX_BATCH_BYTES = 64 * 1024;\n\nfunction batchFlightBytes(source: Readable): Readable {\n let batch: NodeFlightChunk[] = [];\n let batchBytes = 0;\n let scheduled = false;\n // Assigned once the source listeners exist; a body destroyed before then\n // (an already-finished source) has none to remove.\n let detach = (): void => {};\n\n // One allocation per batch: strings are encoded straight into it, at their\n // offset, rather than each into its own array and then copied.\n const emit = (): void => {\n scheduled = false;\n if (batch.length === 0 || bytes.destroyed) return;\n const merged = Buffer.allocUnsafe(batchBytes);\n let offset = 0;\n for (const chunk of batch) {\n if (typeof chunk === 'string') {\n offset += merged.write(chunk, offset);\n } else {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n }\n batch = [];\n batchBytes = 0;\n // Backpressure: a slow client stops the render's output here instead of\n // the whole payload piling up in memory. read() resumes it.\n if (!bytes.push(merged)) source.pause();\n };\n\n const bytes = new Readable({\n read() {\n if (source.isPaused()) source.resume();\n },\n destroy(error, callback) {\n // A batch still queued is dropped, so its microtask pushes nothing.\n batch = [];\n batchBytes = 0;\n detach();\n // The client left early: release the render.\n if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);\n callback(error);\n },\n });\n bytes.on('error', ignoreError);\n\n const finished = finishedState(source);\n if (finished) {\n // A finished source emits no more events for the wiring below to see.\n if ('error' in finished) bytes.destroy(finished.error);\n else bytes.push(null);\n return bytes;\n }\n\n const onData = (chunk: NodeFlightChunk): void => {\n batch.push(chunk);\n batchBytes += chunkByteLength(chunk);\n // A flush that writes a lot in one tick goes out in capped batches, so\n // backpressure can pause the source mid-flush instead of after it.\n if (batchBytes >= MAX_BATCH_BYTES) {\n emit();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(emit);\n }\n };\n const onEnd = (): void => {\n emit();\n bytes.push(null);\n };\n const onError = (error: Error): void => {\n bytes.destroy(error);\n };\n const onClose = (): void => {\n if (!source.readableEnded) {\n bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));\n }\n };\n detach = (): void => {\n source.off('data', onData);\n source.off('end', onEnd);\n source.off('error', onError);\n source.off('close', onClose);\n };\n source.on('data', onData);\n source.on('end', onEnd);\n source.on('error', onError);\n source.on('close', onClose);\n return bytes;\n}\n\n/**\n * Why `source` will never emit again, if it was destroyed or ended before a\n * consumer attached: `'end'`, `'error'` and `'close'` have already fired,\n * so a consumer that only listens would wait forever. `null` while live.\n */\nfunction finishedState(source: Readable): { ended: true } | { error: Error } | null {\n if (source.readableEnded) return { ended: true };\n if (!source.destroyed) return null;\n return { error: source.errored ?? new Error('RSC stream closed before it ended') };\n}\n\n/**\n * Settles once a chunk (or the end) can be read from `source`, without\n * consuming it: the chunk stays in the source for whatever reads it next.\n * Rejects if the source errors first.\n *\n * The `'readable'` listener is removed on settle; Node restores the stream's\n * flowing state on the next tick, so a consumer attached afterwards (a pipe,\n * a `'data'` listener) still starts it.\n */\nexport function whenNodeFlightReadable(source: Readable): Promise<void> {\n if (source.readableLength > 0) return Promise.resolve();\n const finished = finishedState(source);\n if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const settle = (error?: Error): void => {\n source.off('readable', onReadable);\n source.off('error', settle);\n source.off('close', onClose);\n if (error) reject(error);\n else resolve();\n };\n const onReadable = (): void => settle();\n const onClose = (): void => settle(source.errored ?? undefined);\n source.on('readable', onReadable);\n source.on('error', settle);\n source.on('close', onClose);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAE5D,SAASA,gBAAoB,CAAC;;AAG9B,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,KAAK,UAAU,OAAO,CAAC,CAAC,SAASA,aAAW,GAAG,KAAK,GAAG,SAASA,aAAW;CAChF,KAAK,QAAQ;AACf;AAEA,IAAa,mBAAb,MAAa,yBAAyB,SAAS;CAC7C;CACA,UAA2B;;CAE3B,SAAS;CAET,YAAY,MAAgB,MAAqB;EAC/C,MAAM,MAAM,IAAI;EAChB,IAAI,mBAAmB,IAAI,KAAK,MAAM,GAAG;GACvC,YAAY,IAAI;GAChB,KAAK,QAAQ;EACf,OACE,KAAK,QAAQ;CAEjB;;CAGA,QAAyB;EACvB,MAAM,OAAO,KAAK;EAClB,IAAI,MAAM,KAAK,SAAS;EACxB,KAAK,QAAQ;EACb,OAAO;CACT;;;;;;CAOA,YAAsB;EACpB,IAAI,CAAC,KAAK,SAAS;GACjB,IAAI,KAAK,QAAQ,MAAM,IAAI,UAAU,8CAA8C;GACnF,MAAM,OAAO,KAAK;GAClB,KAAK,QAAQ;GACb,KAAK,UAAU,IAAI,SACjB,OAAQ,SAAS,MAAM,IAAI,IAAmC,MAC9D;IACE,QAAQ,KAAK;IACb,YAAY,KAAK;IACjB,SAAS,KAAK;GAChB,CACF;EACF;EACA,OAAO,KAAK;CACd;CAEA,KAAK,aAA0B;EAC7B,OAAO;GACL,SAAS,KAAK,UAAU,KAAK,QAAQ,SAAS,OAAO,KAAK,UAAU;GACpE,SAAS,SAAS;IAChB,IAAI,KAAK,SAAS,OAAO,IAAI,SAAS,KAAK,QAAQ,MAAM,IAAI;IAC7D,MAAM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"./logger-DDLtp5e-.js";
1
+ import { o as logLossyCacheValue } from "./logger-DmRR9tmZ.js";
2
2
  // src/cache/json-lossy-check.ts
3
3
  var LOSSY_TYPES = [
4
4
  "Date",
@@ -62,4 +62,4 @@ function findLossyTypes(value, seen, depth) {
62
62
  }
63
63
  export { warnLossyJsonValue as t };
64
64
 
65
- //# sourceMappingURL=json-lossy-check-D47R9Fp5.js.map
65
+ //# sourceMappingURL=json-lossy-check-Y1GxqVX_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"json-lossy-check-D47R9Fp5.js","names":[],"sources":["../../src/cache/json-lossy-check.ts"],"sourcesContent":["import { logLossyCacheValue } from '../server/logger.ts';\n\nconst LOSSY_TYPES = ['Date', 'Map', 'Set', 'BigInt'] as const;\n\nlet hasWarned = false;\n\n/**\n * Dev-mode warning when a cache value contains types that lose fidelity\n * through JSON round-trip. Only runs in development — no-op in production.\n *\n * Detects: Date (→ ISO string), Map/Set (→ {}), BigInt (→ throws).\n * Emits once per process to avoid log spam.\n */\nexport function warnLossyJsonValue(value: unknown, cacheKey: string): void {\n if (hasWarned) return;\n if (process.env.NODE_ENV === 'production') return;\n\n const lossy = findLossyTypes(value, new Set(), 0);\n if (lossy.size === 0) return;\n\n hasWarned = true;\n logLossyCacheValue({ cacheKey, types: [...lossy].join(', ') });\n}\n\nfunction findLossyTypes(value: unknown, seen: Set<unknown>, depth: number): Set<string> {\n const lossy = new Set<string>();\n if (depth > 8 || value === null || value === undefined) return lossy;\n if (typeof value === 'bigint') {\n lossy.add('BigInt');\n return lossy;\n }\n if (typeof value !== 'object' && typeof value !== 'function') return lossy;\n if (seen.has(value)) return lossy;\n seen.add(value);\n\n if (value instanceof Date) {\n lossy.add('Date');\n return lossy;\n }\n if (value instanceof Map) {\n lossy.add('Map');\n return lossy;\n }\n if (value instanceof Set) {\n lossy.add('Set');\n return lossy;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n for (const t of findLossyTypes(item, seen, depth + 1)) lossy.add(t);\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n }\n\n for (const k of Object.keys(value as Record<string, unknown>)) {\n for (const t of findLossyTypes((value as Record<string, unknown>)[k], seen, depth + 1)) {\n lossy.add(t);\n }\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n}\n\n/** Reset warning state — for tests only. */\nexport function _resetLossyWarning(): void {\n hasWarned = false;\n}\n"],"mappings":";;AAEA,IAAM,cAAc;CAAC;CAAQ;CAAO;CAAO;AAAQ;AAEnD,IAAI,YAAY;;;;;;;;AAShB,SAAgB,mBAAmB,OAAgB,UAAwB;CACzE,IAAI,WAAW;CACf,IAAA,QAAA,IAAA,aAA6B,cAAc;CAE3C,MAAM,QAAQ,eAAe,uBAAO,IAAI,IAAI,GAAG,CAAC;CAChD,IAAI,MAAM,SAAS,GAAG;CAEtB,YAAY;CACZ,mBAAmB;EAAE;EAAU,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;CAAE,CAAC;AAC/D;AAEA,SAAS,eAAe,OAAgB,MAAoB,OAA4B;CACtF,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI,QAAQ,KAAK,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAC/D,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,IAAI,QAAQ;EAClB,OAAO;CACT;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO;CACrE,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CAEd,IAAI,iBAAiB,MAAM;EACzB,MAAM,IAAI,MAAM;EAChB,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,KAAK,MAAM,KAAK,eAAe,MAAM,MAAM,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC;GAClE,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;EAChD;EACA,OAAO;CACT;CAEA,KAAK,MAAM,KAAK,OAAO,KAAK,KAAgC,GAAG;EAC7D,KAAK,MAAM,KAAK,eAAgB,MAAkC,IAAI,MAAM,QAAQ,CAAC,GACnF,MAAM,IAAI,CAAC;EAEb,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;CAChD;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"json-lossy-check-Y1GxqVX_.js","names":[],"sources":["../../src/cache/json-lossy-check.ts"],"sourcesContent":["import { logLossyCacheValue } from '../server/logger.ts';\n\nconst LOSSY_TYPES = ['Date', 'Map', 'Set', 'BigInt'] as const;\n\nlet hasWarned = false;\n\n/**\n * Dev-mode warning when a cache value contains types that lose fidelity\n * through JSON round-trip. Only runs in development — no-op in production.\n *\n * Detects: Date (→ ISO string), Map/Set (→ {}), BigInt (→ throws).\n * Emits once per process to avoid log spam.\n */\nexport function warnLossyJsonValue(value: unknown, cacheKey: string): void {\n if (hasWarned) return;\n if (process.env.NODE_ENV === 'production') return;\n\n const lossy = findLossyTypes(value, new Set(), 0);\n if (lossy.size === 0) return;\n\n hasWarned = true;\n logLossyCacheValue({ cacheKey, types: [...lossy].join(', ') });\n}\n\nfunction findLossyTypes(value: unknown, seen: Set<unknown>, depth: number): Set<string> {\n const lossy = new Set<string>();\n if (depth > 8 || value === null || value === undefined) return lossy;\n if (typeof value === 'bigint') {\n lossy.add('BigInt');\n return lossy;\n }\n if (typeof value !== 'object' && typeof value !== 'function') return lossy;\n if (seen.has(value)) return lossy;\n seen.add(value);\n\n if (value instanceof Date) {\n lossy.add('Date');\n return lossy;\n }\n if (value instanceof Map) {\n lossy.add('Map');\n return lossy;\n }\n if (value instanceof Set) {\n lossy.add('Set');\n return lossy;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n for (const t of findLossyTypes(item, seen, depth + 1)) lossy.add(t);\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n }\n\n for (const k of Object.keys(value as Record<string, unknown>)) {\n for (const t of findLossyTypes((value as Record<string, unknown>)[k], seen, depth + 1)) {\n lossy.add(t);\n }\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n}\n\n/** Reset warning state — for tests only. */\nexport function _resetLossyWarning(): void {\n hasWarned = false;\n}\n"],"mappings":";;AAEA,IAAM,cAAc;CAAC;CAAQ;CAAO;CAAO;AAAQ;AAEnD,IAAI,YAAY;;;;;;;;AAShB,SAAgB,mBAAmB,OAAgB,UAAwB;CACzE,IAAI,WAAW;CACf,IAAA,QAAA,IAAA,aAA6B,cAAc;CAE3C,MAAM,QAAQ,eAAe,uBAAO,IAAI,IAAI,GAAG,CAAC;CAChD,IAAI,MAAM,SAAS,GAAG;CAEtB,YAAY;CACZ,mBAAmB;EAAE;EAAU,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;CAAE,CAAC;AAC/D;AAEA,SAAS,eAAe,OAAgB,MAAoB,OAA4B;CACtF,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI,QAAQ,KAAK,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAC/D,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,IAAI,QAAQ;EAClB,OAAO;CACT;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO;CACrE,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CAEd,IAAI,iBAAiB,MAAM;EACzB,MAAM,IAAI,MAAM;EAChB,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,KAAK,MAAM,KAAK,eAAe,MAAM,MAAM,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC;GAClE,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;EAChD;EACA,OAAO;CACT;CAEA,KAAK,MAAM,KAAK,OAAO,KAAK,KAAgC,GAAG;EAC7D,KAAK,MAAM,KAAK,eAAgB,MAAkC,IAAI,MAAM,QAAQ,CAAC,GACnF,MAAM,IAAI,CAAC;EAEb,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;CAChD;CACA,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
- import { i as detectDirective, n as classifyModule } from "./classify-BwyAd-dZ.js";
2
- import { n as stitchImportChains } from "./chains-DMoHX4yH.js";
3
- import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-DONdiCGX.js";
1
+ import { i as detectDirective, n as classifyModule } from "./classify-Cj9EeZoL.js";
2
+ import { n as stitchImportChains } from "./chains-C7CExrUI.js";
3
+ import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-WQgUydF_.js";
4
4
  import { i as scanProjectSourceFiles, t as buildSourceExtensions } from "./scan-CyizcBiX.js";
5
5
  import { normalizePath } from "vite";
6
6
  import { readFileSync } from "node:fs";
@@ -147,4 +147,4 @@ async function classifyLiveProject(ctx) {
147
147
  }
148
148
  export { classifyLiveFile, classifyLiveProject };
149
149
 
150
- //# sourceMappingURL=live-graph-HcLScfiV.js.map
150
+ //# sourceMappingURL=live-graph-BDQWvnMm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"live-graph-HcLScfiV.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;;;;;AAOA,eAAsB,iBACpB,SACA,KAIA,eAA4C,oBAAoB,GAIhE,QAC2B;CAC3B,MAAM,OAAO,cAAc,OAAO;CAClC,IAAI,OAAsB;CAC1B,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EAGd,QAAQ,KAAK;GACX,aAAa;GACb,IAAI;GACJ,SAAS,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACvF,CAAC;CACH;CACA,MAAM,YAAuB,SAAS,OAAO,OAAO,gBAAgB,MAAM,IAAI;CAC9E,MAAM,UAAU,SAAS,OAAO,CAAC,IAAI,cAAc,wBAAwB,MAAM,IAAI,CAAC;CAEtF,MAAM,cAA+B;EACnC,QAAQ,IAAI;EACZ,gBAAgB,IAAI;CACtB;CACA,MAAM,iBAAiB,eACrB;EACE;EACA,OAAO,SAAS,IAAI,KAAK,IAAI;EAC7B,OAAO,SAAS,IAAI,KAAK,IAAI;EAC7B,UAAU,SAAS,IAAI,QAAQ,IAAI;EACnC,gBAAgB,eAAe,IAAI,KAAK,IAAI;EAC5C;CACF,GACA,WACF;CAEA,MAAM,SAAS,eAAe,UAC1B,CAAC,IACD,mBAAmB,MAAM;EACvB,KAAK,IAAI;EACT,KAAK,IAAI;EACT,QAAQ,IAAI;EACZ,gBAAgB,IAAI;EACpB;CACF,CAAC;CAEL,OAAO;EACL,GAAG;EACH,UAAU,cAAc;EACxB;EACA,YAAY,cAAc,eAAe,MAAM,eAAe,SAAS,OAAO;CAChF;AACF;;;;;;AAOA,SAAS,sBAAmD;CAC1D,MAAM,wBAAQ,IAAI,IAAuB;CACzC,QAAQ,SAAS;EACf,MAAM,MAAM,MAAM,IAAI,IAAI;EAC1B,IAAI,QAAQ,KAAA,GAAW,OAAO;EAC9B,IAAI,YAAuB;EAC3B,IAAI;GACF,YAAY,gBAAgB,aAAa,MAAM,MAAM,GAAG,IAAI;EAC9D,QAAQ;GACN,YAAY;EACd;EACA,MAAM,IAAI,MAAM,SAAS;EACzB,OAAO;CACT;AACF;;;;;;;;AAsBA,eAAsB,oBAAoB,KAAmD;CAC3F,MAAM,QAAkB,CAAC;CACzB,MAAM,SAAsC,CAAC;CAC7C,MAAM,aAAa,sBAAsB,IAAI,cAAc;CAC3D,MAAM,uBACJ,IAAI,MACJ,QACC,YACC,OAAO,KAAK;EAAE,aAAa;EAAQ,IAAI,QAAQ;EAAK,SAAS,QAAQ;CAAQ,CAAC,GAChF,GACA,UACF;CACA,MAAM,UAA8B,CAAC;CACrC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,QAAQ,OACjB,QAAQ,KAAK,MAAM,iBAAiB,MAAM,KAAK,cAAc,MAAM,CAAC;CAEtE,QAAQ,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;CACvE,OAAO;EAAE,MAAM,IAAI;EAAM;EAAS;CAAO;AAC3C"}
1
+ {"version":3,"file":"live-graph-BDQWvnMm.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;;;;;AAOA,eAAsB,iBACpB,SACA,KAIA,eAA4C,oBAAoB,GAIhE,QAC2B;CAC3B,MAAM,OAAO,cAAc,OAAO;CAClC,IAAI,OAAsB;CAC1B,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EAGd,QAAQ,KAAK;GACX,aAAa;GACb,IAAI;GACJ,SAAS,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACvF,CAAC;CACH;CACA,MAAM,YAAuB,SAAS,OAAO,OAAO,gBAAgB,MAAM,IAAI;CAC9E,MAAM,UAAU,SAAS,OAAO,CAAC,IAAI,cAAc,wBAAwB,MAAM,IAAI,CAAC;CAEtF,MAAM,cAA+B;EACnC,QAAQ,IAAI;EACZ,gBAAgB,IAAI;CACtB;CACA,MAAM,iBAAiB,eACrB;EACE;EACA,OAAO,SAAS,IAAI,KAAK,IAAI;EAC7B,OAAO,SAAS,IAAI,KAAK,IAAI;EAC7B,UAAU,SAAS,IAAI,QAAQ,IAAI;EACnC,gBAAgB,eAAe,IAAI,KAAK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./als-registry-PPYstxK0.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { SpanStatusCode, trace } from "@opentelemetry/api";
4
4
  // src/server/signal-identity.ts
@@ -767,4 +767,4 @@ function swallow(err, reason, opts) {
767
767
  }
768
768
  export { runWithTraceId as A, addSpanEvent as C, getSpanId as D, getOtelTraceId as E, isControlFlowSignal as F, isDenySignal as I, isRedirectSignal as L, withSpan as M, DENY_BRAND as N, getTraceId as O, REDIRECT_BRAND as P, isDevMode as S, generateTraceId as T, logWaitUntilRejected as _, logKeyDisciplineViolation as a, swallow as b, logMiddlewareShortCircuit as c, logRequestCompleted as d, logRequestReceived as f, logSwrRefetchFailed as g, logSlowRequest as h, logCsrfRejected as i, setSpanAttribute as j, replaceTraceId as k, logProxyError as l, logRouteSetupError as m, logCacheMiss as n, logLossyCacheValue as o, logRouteError as p, logCacheReadFailed as r, logMiddlewareError as s, getLogger as t, logRenderError as u, logWaitUntilUnsupported as v, addSpanEventSync as w, isDebug as x, setLogger as y };
769
769
 
770
- //# sourceMappingURL=logger-DDLtp5e-.js.map
770
+ //# sourceMappingURL=logger-DmRR9tmZ.js.map