@timber-js/app 0.2.0-alpha.235 → 0.2.0-alpha.237

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 (300) hide show
  1. package/dist/_chunks/{actions-CYjRMpZI.js → actions-Top9GftB.js} +3 -3
  2. package/dist/_chunks/{actions-CYjRMpZI.js.map → actions-Top9GftB.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-BZJNt01a.js → cache-api-Bo8c7XVF.js} +6 -6
  4. package/dist/_chunks/{cache-api-BZJNt01a.js.map → cache-api-Bo8c7XVF.js.map} +1 -1
  5. package/dist/_chunks/{chains-D-RRc7CM.js → chains-BsGKkMTK.js} +2 -2
  6. package/dist/_chunks/{chains-D-RRc7CM.js.map → chains-BsGKkMTK.js.map} +1 -1
  7. package/dist/_chunks/chains-DHmoKxkO.js +1 -0
  8. package/dist/_chunks/{classify-_W0RWa5w.js → classify-cmE0Gins.js} +2 -2
  9. package/dist/_chunks/{classify-_W0RWa5w.js.map → classify-cmE0Gins.js.map} +1 -1
  10. package/dist/_chunks/{cli-check-Dl3yo3Zv.js → cli-check-BwiahbTC.js} +3 -3
  11. package/dist/_chunks/{cli-check-Dl3yo3Zv.js.map → cli-check-BwiahbTC.js.map} +1 -1
  12. package/dist/_chunks/{cli-schema-sync-CyrOHbAo.js → cli-schema-sync-B2ldclRO.js} +2 -2
  13. package/dist/_chunks/{cli-schema-sync-CyrOHbAo.js.map → cli-schema-sync-B2ldclRO.js.map} +1 -1
  14. package/dist/_chunks/{cli-schema-sync-CTWiBMZZ.js → cli-schema-sync-Brw7kTmm.js} +1 -1
  15. package/dist/_chunks/{client-dep-entries-C9hv-3k9.js → client-dep-entries-C1nMlLKV.js} +2 -2
  16. package/dist/_chunks/{client-dep-entries-C9hv-3k9.js.map → client-dep-entries-C1nMlLKV.js.map} +1 -1
  17. package/dist/_chunks/{cloudflare-_2fhxQE8.js → cloudflare-Dk5Hqo-O.js} +3 -3
  18. package/dist/_chunks/{cloudflare-_2fhxQE8.js.map → cloudflare-Dk5Hqo-O.js.map} +1 -1
  19. package/dist/_chunks/{convention-lint-D54k6uUM.js → convention-lint-CLpuzY5h.js} +3 -3
  20. package/dist/_chunks/{convention-lint-D54k6uUM.js.map → convention-lint-CLpuzY5h.js.map} +1 -1
  21. package/dist/_chunks/dev-server-BGGGhHXx.js +1 -0
  22. package/dist/_chunks/{dev-server-cmWVDgTf.js → dev-server-lrdpD7Ws.js} +121 -5
  23. package/dist/_chunks/dev-server-lrdpD7Ws.js.map +1 -0
  24. package/dist/_chunks/{dev-span-_NzMX-au.js → dev-span-RsVeYYc_.js} +5 -2
  25. package/dist/_chunks/dev-span-RsVeYYc_.js.map +1 -0
  26. package/dist/_chunks/{error-boundary-Cf1m-Ywk.js → error-boundary-Bh-egWUI.js} +6 -6
  27. package/dist/_chunks/{error-boundary-Cf1m-Ywk.js.map → error-boundary-Bh-egWUI.js.map} +1 -1
  28. package/dist/_chunks/{flight-source-node-BGanuoSS.js → flight-source-node-BsrlUjMO.js} +7 -3
  29. package/dist/_chunks/flight-source-node-BsrlUjMO.js.map +1 -0
  30. package/dist/_chunks/{href-BtspoNc9.js → href-8l5VD23D.js} +2 -2
  31. package/dist/_chunks/{href-BtspoNc9.js.map → href-8l5VD23D.js.map} +1 -1
  32. package/dist/_chunks/{json-lossy-check-BXM45k8p.js → json-lossy-check-D47R9Fp5.js} +2 -2
  33. package/dist/_chunks/{json-lossy-check-BXM45k8p.js.map → json-lossy-check-D47R9Fp5.js.map} +1 -1
  34. package/dist/_chunks/{live-graph-C7-yA8W9.js → live-graph-ChuFfmLi.js} +4 -4
  35. package/dist/_chunks/{live-graph-C7-yA8W9.js.map → live-graph-ChuFfmLi.js.map} +1 -1
  36. package/dist/_chunks/{logger-YtMSKfft.js → logger-DDLtp5e-.js} +16 -1
  37. package/dist/_chunks/logger-DDLtp5e-.js.map +1 -0
  38. package/dist/_chunks/navigation-root-Cvb7P1ud.js.map +1 -1
  39. package/dist/_chunks/{node-response-D3hXWb8y.js → node-response-omewa8e6.js} +21 -4
  40. package/dist/_chunks/node-response-omewa8e6.js.map +1 -0
  41. package/dist/_chunks/{poison-scan-CRSP06Es.js → poison-scan-CJ9QfJWb.js} +2 -2
  42. package/dist/_chunks/{poison-scan-CRSP06Es.js.map → poison-scan-CJ9QfJWb.js.map} +1 -1
  43. package/dist/_chunks/render-timeout-MrrqD1wd.js.map +1 -1
  44. package/dist/_chunks/{scanner-BNQ4qnLX.js → scanner-CrB_h6FA.js} +5 -5
  45. package/dist/_chunks/{scanner-BNQ4qnLX.js.map → scanner-CrB_h6FA.js.map} +1 -1
  46. package/dist/_chunks/{sizeof-Cmx6Fs-Y.js → sizeof-DVhEVN_y.js} +2 -2
  47. package/dist/_chunks/{sizeof-Cmx6Fs-Y.js.map → sizeof-DVhEVN_y.js.map} +1 -1
  48. package/dist/_chunks/{walkers-DFC9KsBL.js → walkers-BUvpsb2Q.js} +3 -3
  49. package/dist/_chunks/{walkers-DFC9KsBL.js.map → walkers-BUvpsb2Q.js.map} +1 -1
  50. package/dist/adapters/cloudflare-dev.js +1 -1
  51. package/dist/adapters/cloudflare-kv-cache.js +2 -2
  52. package/dist/adapters/cloudflare.js +1 -1
  53. package/dist/adapters/nitro.js +1 -1
  54. package/dist/analyze/crawl-entry.js +3 -3
  55. package/dist/analyze/graph-command.js +3 -3
  56. package/dist/cache/index.js +2 -2
  57. package/dist/cache/stores/memory.js +1 -1
  58. package/dist/cli.js +3 -3
  59. package/dist/client/dev-pill/index.d.ts +2 -1
  60. package/dist/client/dev-pill/index.d.ts.map +1 -1
  61. package/dist/client/dev-pill/view.d.ts.map +1 -1
  62. package/dist/client/error-boundary.js +1 -1
  63. package/dist/client/index.js +4 -4
  64. package/dist/client/internal.js +3 -3
  65. package/dist/cookies/index.js +1 -1
  66. package/dist/dev-tools/await-span.d.ts +7 -0
  67. package/dist/dev-tools/await-span.d.ts.map +1 -1
  68. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  69. package/dist/dev-tools/logger.d.ts +8 -2
  70. package/dist/dev-tools/logger.d.ts.map +1 -1
  71. package/dist/dev-tools/span-sink.d.ts +9 -1
  72. package/dist/dev-tools/span-sink.d.ts.map +1 -1
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +73 -31
  75. package/dist/index.js.map +1 -1
  76. package/dist/native/rsc/_react/chunks/{react-server-dom-webpack-server.node.development-hQ_odxIB.js → react-server-dom-webpack-server.node.development-CAttMzVD.js} +2 -2
  77. package/dist/native/rsc/_react/flight-client.js +2 -2
  78. package/dist/native/rsc/_react/flight-server.js +1 -1
  79. package/dist/native/rsc/_react/flight-static.js +1 -1
  80. package/dist/native/rsc/adapters/cloudflare-kv-cache.js +1 -1
  81. package/dist/native/rsc/adapters/cloudflare.js +2 -2
  82. package/dist/native/rsc/cache/cache-api.js +3 -3
  83. package/dist/native/rsc/cache/index.js +3 -3
  84. package/dist/native/rsc/cache/timber-cache.js +2 -2
  85. package/dist/native/rsc/cdn/index.js +1 -1
  86. package/dist/native/rsc/client/use-cookie.js +1 -1
  87. package/dist/native/rsc/dev-tools/404-page.js +1 -1
  88. package/dist/native/rsc/dev-tools/await-span.js +5 -2
  89. package/dist/native/rsc/dev-tools/await-span.js.map +1 -1
  90. package/dist/native/rsc/dev-tools/error-page.js +2 -2
  91. package/dist/native/rsc/dev-tools/instrumentation.js +38 -3
  92. package/dist/native/rsc/dev-tools/instrumentation.js.map +1 -1
  93. package/dist/native/rsc/dev-tools/logger.js +123 -80
  94. package/dist/native/rsc/dev-tools/logger.js.map +1 -1
  95. package/dist/native/rsc/dev-tools/span-sink.js +1 -0
  96. package/dist/native/rsc/dev-tools/span-sink.js.map +1 -1
  97. package/dist/native/rsc/dev-tools/terminal.js +1 -1
  98. package/dist/native/rsc/manifest.json +1 -0
  99. package/dist/native/rsc/params/index.js +1 -1
  100. package/dist/native/rsc/routing/collision-probe.js +1 -1
  101. package/dist/native/rsc/routing/interception.js +1 -1
  102. package/dist/native/rsc/search-params/define.js +2 -2
  103. package/dist/native/rsc/server/abort-scope.js +6 -2
  104. package/dist/native/rsc/server/abort-scope.js.map +1 -1
  105. package/dist/native/rsc/server/access-gate.js +1 -1
  106. package/dist/native/rsc/server/action-client.js +2 -2
  107. package/dist/native/rsc/server/action-handler.js +8 -8
  108. package/dist/native/rsc/server/actions.js +3 -3
  109. package/dist/native/rsc/server/children-interception.js +1 -1
  110. package/dist/native/rsc/server/deny-boundary.js +1 -1
  111. package/dist/native/rsc/server/deny-renderer.js +10 -10
  112. package/dist/native/rsc/server/fallback-error.js +1 -1
  113. package/dist/native/rsc/server/flight-injector-core.js +2 -2
  114. package/dist/native/rsc/server/flight-source-node.js +8 -4
  115. package/dist/native/rsc/server/flight-source-node.js.map +1 -1
  116. package/dist/native/rsc/server/index.js +4 -4
  117. package/dist/native/rsc/server/interception-gates.js +2 -2
  118. package/dist/native/rsc/server/internal.js +15 -15
  119. package/dist/native/rsc/server/logger.js +2 -2
  120. package/dist/native/rsc/server/metadata-route-links.js +1 -1
  121. package/dist/native/rsc/server/node-body-response.js +1 -1
  122. package/dist/native/rsc/server/param-coercion.js +1 -1
  123. package/dist/native/rsc/server/pipeline-helpers.js +11 -11
  124. package/dist/native/rsc/server/pipeline-helpers.js.map +1 -1
  125. package/dist/native/rsc/server/pipeline-interception.js +4 -4
  126. package/dist/native/rsc/server/pipeline-metadata-route.js +11 -11
  127. package/dist/native/rsc/server/pipeline-metadata-route.js.map +1 -1
  128. package/dist/native/rsc/server/pipeline-outcome.js +4 -4
  129. package/dist/native/rsc/server/pipeline-phases.js +11 -11
  130. package/dist/native/rsc/server/pipeline.js +10 -10
  131. package/dist/native/rsc/server/prebuilt/capture-render.js +1 -1
  132. package/dist/native/rsc/server/prebuilt/dev-store.js +1 -1
  133. package/dist/native/rsc/server/prebuilt/overlay.js +3 -3
  134. package/dist/native/rsc/server/prebuilt-builder.js +8 -8
  135. package/dist/native/rsc/server/prebuilt-runtime.js +15 -15
  136. package/dist/native/rsc/server/primitives.js +2 -2
  137. package/dist/native/rsc/server/publish-params.js +1 -1
  138. package/dist/native/rsc/server/render-timeout.js.map +1 -1
  139. package/dist/native/rsc/server/request-context.js +1 -1
  140. package/dist/native/rsc/server/route-element-builder.js +7 -7
  141. package/dist/native/rsc/server/route-element-helpers.js +1 -1
  142. package/dist/native/rsc/server/route-handler.js +1 -1
  143. package/dist/native/rsc/server/rsc-entry/action-dispatcher.js +1 -1
  144. package/dist/native/rsc/server/rsc-entry/action-middleware-runner.js +1 -1
  145. package/dist/native/rsc/server/rsc-entry/api-handler.js +1 -1
  146. package/dist/native/rsc/server/rsc-entry/deny-fallback.js +6 -6
  147. package/dist/native/rsc/server/rsc-entry/error-renderer.js +7 -7
  148. package/dist/native/rsc/server/rsc-entry/helpers.js +1 -1
  149. package/dist/native/rsc/server/rsc-entry/render-route.js +4 -4
  150. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +7 -7
  151. package/dist/native/rsc/server/rsc-entry/rsc-payload.js +3 -3
  152. package/dist/native/rsc/server/rsc-entry/rsc-stream.js +6 -6
  153. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +10 -10
  154. package/dist/native/rsc/server/rsc-error-envelope.js +1 -1
  155. package/dist/native/rsc/server/safe-load.js +14 -2
  156. package/dist/native/rsc/server/safe-load.js.map +1 -1
  157. package/dist/native/rsc/server/sitemap-handler.js +1 -1
  158. package/dist/native/rsc/server/skippable-prefix.js +2 -2
  159. package/dist/native/rsc/server/slot-interception.js +1 -1
  160. package/dist/native/rsc/server/slot-resolver.js +11 -11
  161. package/dist/native/rsc/server/static-generator.js +2 -2
  162. package/dist/native/rsc/server/traced-access.js +1 -1
  163. package/dist/native/rsc/server/tracing.js +10 -0
  164. package/dist/native/rsc/server/tracing.js.map +1 -1
  165. package/dist/native/rsc/shared/dev-span.js +8 -2
  166. package/dist/native/rsc/shared/dev-span.js.map +1 -1
  167. package/dist/native/rsc/shared/href.js +1 -1
  168. package/dist/native/rsc/shared/span-waterfall.js +90 -0
  169. package/dist/native/rsc/shared/span-waterfall.js.map +1 -0
  170. package/dist/native/ssr/adapters/cloudflare-kv-cache.js +1 -1
  171. package/dist/native/ssr/adapters/cloudflare.js +2 -2
  172. package/dist/native/ssr/cache/cache-api.js +3 -3
  173. package/dist/native/ssr/cache/guarded-read.js +1 -1
  174. package/dist/native/ssr/cache/index.js +3 -3
  175. package/dist/native/ssr/cache/timber-cache.js +3 -3
  176. package/dist/native/ssr/cdn/index.js +1 -1
  177. package/dist/native/ssr/client/error-boundary.js +1 -1
  178. package/dist/native/ssr/client/index.js +5 -5
  179. package/dist/native/ssr/client/link.js +5 -5
  180. package/dist/native/ssr/client/navigation-commit.js +2 -2
  181. package/dist/native/ssr/client/nuqs-adapter.js +2 -2
  182. package/dist/native/ssr/client/params-context.js +1 -1
  183. package/dist/native/ssr/client/router-skew.js +1 -1
  184. package/dist/native/ssr/client/rsc-fetch.js +2 -2
  185. package/dist/native/ssr/client/use-pending-navigation.js +1 -1
  186. package/dist/native/ssr/client/use-search-params.js +2 -2
  187. package/dist/native/ssr/client/use-segment-params.js +1 -1
  188. package/dist/native/ssr/client/use-selected-layout-segment.js +1 -1
  189. package/dist/native/ssr/dev-tools/await-span.js +5 -2
  190. package/dist/native/ssr/dev-tools/await-span.js.map +1 -1
  191. package/dist/native/ssr/dev-tools/instrumentation.js +38 -3
  192. package/dist/native/ssr/dev-tools/instrumentation.js.map +1 -1
  193. package/dist/native/ssr/dev-tools/logger.js +123 -80
  194. package/dist/native/ssr/dev-tools/logger.js.map +1 -1
  195. package/dist/native/ssr/dev-tools/span-sink.js +1 -0
  196. package/dist/native/ssr/dev-tools/span-sink.js.map +1 -1
  197. package/dist/native/ssr/manifest.json +1 -0
  198. package/dist/native/ssr/params/index.js +1 -1
  199. package/dist/native/ssr/search-params/define.js +2 -2
  200. package/dist/native/ssr/server/abort-scope.js +6 -2
  201. package/dist/native/ssr/server/abort-scope.js.map +1 -1
  202. package/dist/native/ssr/server/access-gate.js +1 -1
  203. package/dist/native/ssr/server/action-client.js +2 -2
  204. package/dist/native/ssr/server/actions.js +3 -3
  205. package/dist/native/ssr/server/deny-boundary.js +2 -2
  206. package/dist/native/ssr/server/flight-injector-core.js +1 -1
  207. package/dist/native/ssr/server/flight-source-node.js +8 -4
  208. package/dist/native/ssr/server/flight-source-node.js.map +1 -1
  209. package/dist/native/ssr/server/index.js +4 -4
  210. package/dist/native/ssr/server/internal.js +12 -12
  211. package/dist/native/ssr/server/logger.js +2 -2
  212. package/dist/native/ssr/server/node-body-response.js +1 -1
  213. package/dist/native/ssr/server/node-stream-transforms.js +2 -2
  214. package/dist/native/ssr/server/param-coercion.js +3 -3
  215. package/dist/native/ssr/server/pipeline-helpers.js +8 -8
  216. package/dist/native/ssr/server/pipeline-helpers.js.map +1 -1
  217. package/dist/native/ssr/server/pipeline-interception.js +4 -4
  218. package/dist/native/ssr/server/pipeline-metadata-route.js +11 -11
  219. package/dist/native/ssr/server/pipeline-metadata-route.js.map +1 -1
  220. package/dist/native/ssr/server/pipeline-outcome.js +4 -4
  221. package/dist/native/ssr/server/pipeline-phases.js +10 -10
  222. package/dist/native/ssr/server/pipeline.js +10 -10
  223. package/dist/native/ssr/server/prebuilt/capture-render.js +2 -2
  224. package/dist/native/ssr/server/prebuilt/dev-store.js +1 -1
  225. package/dist/native/ssr/server/prebuilt/overlay.js +4 -4
  226. package/dist/native/ssr/server/prebuilt-runtime.js +14 -14
  227. package/dist/native/ssr/server/primitives.js +2 -2
  228. package/dist/native/ssr/server/render-timeout.js +3 -4
  229. package/dist/native/ssr/server/render-timeout.js.map +1 -1
  230. package/dist/native/ssr/server/request-context.js +2 -2
  231. package/dist/native/ssr/server/route-handler.js +1 -1
  232. package/dist/native/ssr/server/rsc-error-envelope.js +1 -1
  233. package/dist/native/ssr/server/safe-load.js +10 -1
  234. package/dist/native/ssr/server/safe-load.js.map +1 -1
  235. package/dist/native/ssr/server/ssr-form-state.js +2 -2
  236. package/dist/native/ssr/server/ssr-wrappers.js +1 -1
  237. package/dist/native/ssr/server/traced-access.js +1 -1
  238. package/dist/native/ssr/server/tracing.js +10 -0
  239. package/dist/native/ssr/server/tracing.js.map +1 -1
  240. package/dist/native/ssr/shared/dev-span.js +8 -2
  241. package/dist/native/ssr/shared/dev-span.js.map +1 -1
  242. package/dist/native/ssr/shared/href.js +1 -1
  243. package/dist/native/ssr/shared/span-waterfall.js +90 -0
  244. package/dist/native/ssr/shared/span-waterfall.js.map +1 -0
  245. package/dist/plugins/dev-precompile.d.ts +84 -0
  246. package/dist/plugins/dev-precompile.d.ts.map +1 -0
  247. package/dist/plugins/dev-server.d.ts.map +1 -1
  248. package/dist/plugins/entries.d.ts.map +1 -1
  249. package/dist/plugins/virtual-ids.d.ts +16 -0
  250. package/dist/plugins/virtual-ids.d.ts.map +1 -0
  251. package/dist/routes/index.js +1 -1
  252. package/dist/routing/index.js +3 -3
  253. package/dist/search-params/index.js +2 -2
  254. package/dist/server/abort-scope.d.ts +7 -0
  255. package/dist/server/abort-scope.d.ts.map +1 -1
  256. package/dist/server/flight-source-node.d.ts.map +1 -1
  257. package/dist/server/index.js +2 -2
  258. package/dist/server/internal.js +57 -17
  259. package/dist/server/internal.js.map +1 -1
  260. package/dist/server/render-timeout.d.ts.map +1 -1
  261. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  262. package/dist/server/safe-load.d.ts +22 -0
  263. package/dist/server/safe-load.d.ts.map +1 -1
  264. package/dist/server/tracing.d.ts.map +1 -1
  265. package/dist/shared/dev-span.d.ts +12 -1
  266. package/dist/shared/dev-span.d.ts.map +1 -1
  267. package/dist/shared/span-waterfall.d.ts +88 -0
  268. package/dist/shared/span-waterfall.d.ts.map +1 -0
  269. package/package.json +2 -2
  270. package/src/client/dev-pill/index.ts +5 -2
  271. package/src/client/dev-pill/store.ts +1 -1
  272. package/src/client/dev-pill/view.ts +15 -5
  273. package/src/dev-tools/await-span.ts +10 -0
  274. package/src/dev-tools/instrumentation.ts +44 -6
  275. package/src/dev-tools/logger.ts +230 -155
  276. package/src/dev-tools/span-sink.ts +34 -3
  277. package/src/index.ts +21 -11
  278. package/src/plugins/dev-precompile.ts +168 -0
  279. package/src/plugins/dev-server.ts +16 -3
  280. package/src/plugins/entries.ts +1 -11
  281. package/src/plugins/virtual-ids.ts +15 -0
  282. package/src/server/abort-scope.ts +20 -1
  283. package/src/server/flight-source-node.ts +11 -2
  284. package/src/server/pipeline-helpers.ts +2 -2
  285. package/src/server/pipeline-metadata-route.ts +2 -2
  286. package/src/server/render-timeout.ts +8 -5
  287. package/src/server/rsc-entry/index.ts +5 -0
  288. package/src/server/safe-load.ts +53 -1
  289. package/src/server/tracing.ts +29 -0
  290. package/src/shared/dev-span.ts +17 -2
  291. package/src/{client/dev-pill/waterfall.ts → shared/span-waterfall.ts} +84 -51
  292. package/dist/_chunks/chains-KblEfYzm.js +0 -1
  293. package/dist/_chunks/dev-server-DrYBIg66.js +0 -1
  294. package/dist/_chunks/dev-server-cmWVDgTf.js.map +0 -1
  295. package/dist/_chunks/dev-span-_NzMX-au.js.map +0 -1
  296. package/dist/_chunks/flight-source-node-BGanuoSS.js.map +0 -1
  297. package/dist/_chunks/logger-YtMSKfft.js.map +0 -1
  298. package/dist/_chunks/node-response-D3hXWb8y.js.map +0 -1
  299. package/dist/client/dev-pill/waterfall.d.ts +0 -64
  300. package/dist/client/dev-pill/waterfall.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"navigation-root-Cvb7P1ud.js","names":[],"sources":["../../src/client/router-ref.ts","../../src/client/global-context.ts","../../src/client/navigation-context.ts","../../src/client/router-url.ts","../../src/client/use-pending-navigation.ts","../../src/client/top-loader.tsx","../../src/client/navigation-root.tsx"],"sourcesContent":["// Global router reference — shared between browser-entry and client hooks.\n//\n// Delegates to client/state.ts for the actual module-level variable.\n// This ensures singleton semantics regardless of import path — all\n// callers converge on the same state.ts instance via the barrel.\n//\n// See design/18-build-system.md §\"Module Singleton Strategy\"\n\nimport type { RouterInstance } from './router-types.ts';\nimport { globalRouter, _setGlobalRouter } from './state.ts';\n\n/**\n * Set the global router instance. Called once during bootstrap.\n */\nexport function setGlobalRouter(router: RouterInstance): void {\n _setGlobalRouter(router);\n}\n\n/**\n * Get the global router instance. Throws if called before bootstrap.\n * Used by client-side hooks (usePendingNavigation, etc.)\n */\nexport function getRouter(): RouterInstance {\n if (!globalRouter) {\n throw new Error('[timber] Router not initialized. getRouter() was called before bootstrap().');\n }\n return globalRouter;\n}\n\n/**\n * Get the global router instance or null if not yet initialized.\n * Used by useRouter() methods to avoid silent failures — callers\n * can log a meaningful warning instead of silently no-oping.\n */\nexport function getRouterOrNull(): RouterInstance | null {\n return globalRouter;\n}\n\n/**\n * Reset the global router to null. Used only in tests to isolate\n * module-level state between test cases.\n * @internal\n */\nexport function resetGlobalRouter(): void {\n _setGlobalRouter(null);\n}\n","/**\n * createGlobalContext — a React context with a process-wide singleton identity.\n *\n * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as\n * NavigationContext. The RSC client bundler can duplicate a module across\n * chunks (browser-entry graph + client-reference graph). With ESM output,\n * each chunk gets its own module scope — a bare createContext at module\n * level would create separate instances per chunk. globalThis guarantees a\n * single instance regardless of duplication.\n *\n * One context per React instance, not per process. Duplicated chunks share\n * one React, so they share the context. A dev SSR program reload evaluates\n * React and react-dom/server again, in the same process: the new renderer\n * must get a context of its own. Handed the previous one, React logs\n * \"Detected multiple renderers concurrently rendering the same context\n * provider\" on every client-component edit, and the stale context keeps a\n * piece of the discarded copy alive (TIM-1590).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n */\n\nimport React from 'react';\n\n/** The part of a React instance a context comes from. */\nexport interface ContextFactory {\n createContext?: typeof React.createContext;\n}\n\n/**\n * The context `key` names for this React instance, created on first use.\n * Pass the key as a `Symbol.for('…')` literal at the call site, so each key\n * stays greppable in the build output (tests/bundle-singleton-audit.test.ts\n * checks `__timber_nav_ctx`).\n */\nexport function createGlobalContext<T>(key: symbol, defaultValue: T): React.Context<T> {\n return createGlobalContextFor(React, key, defaultValue);\n}\n\n/** createGlobalContext for a given React instance. Exported for tests. */\nexport function createGlobalContextFor<T>(\n react: ContextFactory,\n key: symbol,\n defaultValue: T\n): React.Context<T> {\n if (typeof react.createContext !== 'function') {\n // RSC environment — createContext not available. Return a dummy that\n // won't be used (the consumers only render on the client / during SSR).\n return undefined as unknown as React.Context<T>;\n }\n const slot: unknown = Reflect.get(globalThis, key);\n const byReact = slot instanceof WeakMap ? slot : new WeakMap<object, React.Context<T>>();\n if (byReact !== slot) Reflect.set(globalThis, key, byReact);\n let ctx: React.Context<T> | undefined = byReact.get(react);\n if (!ctx) {\n ctx = react.createContext<T>(defaultValue);\n byReact.set(react, ctx);\n }\n return ctx;\n}\n","'use client';\n\n/**\n * NavigationContext — React context for navigation state.\n *\n * Holds the current pathname and search, updated atomically with the RSC\n * tree on each navigation. This replaces the previous useSyncExternalStore\n * approach for usePathname() and useSearchParams(), which suffered from a\n * timing gap: the new tree could commit before the external store\n * re-renders fired, causing a frame where both old and new active states\n * were visible simultaneously.\n *\n * Segment params are NOT here — see the note on NavigationState below.\n *\n * By wrapping the RSC payload element in NavigationProvider inside the\n * router's `renderTree` (browser-entry/router-init.ts), the context value and the element tree are passed to\n * reactRoot.render() in the same call — atomic by construction.\n * All consumers (usePathname, useSearchParams) see the new values in the\n * same render pass as the new tree.\n *\n * During SSR, the wrapper chain mounts this same provider with the\n * request's pathname and raw search string (TIM-1424), so the hooks\n * resolve through the identical code path on both sides. Per-request\n * isolation is by construction — the value is part of the request's\n * element tree.\n *\n * This module is `'use client'` and is never evaluated in the RSC\n * environment. The shims plugin resolves next/navigation to\n * navigation-rsc.ts in RSC, which has throwing stubs (TIM-1420).\n *\n * SINGLETON GUARANTEE: All shared mutable state uses globalThis via\n * Symbol.for keys. The RSC client bundler can duplicate this module\n * across chunks (browser-entry graph + client-reference graph). With\n * ESM output, each chunk gets its own module scope — module-level\n * variables would create separate singleton instances per chunk.\n * globalThis guarantees a single instance regardless of duplication.\n *\n * This workaround will be removed when Rolldown ships `format: 'app'`\n * (module registry format that deduplicates like webpack/Turbopack).\n * See design/27-chunking-strategy.md.\n *\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { useContext, createElement, type ReactNode } from 'react';\nimport { createGlobalContext } from './global-context.ts';\n\n// ---------------------------------------------------------------------------\n// Context type\n// ---------------------------------------------------------------------------\n\n/**\n * What the browser knows about the current location.\n *\n * Params are deliberately absent: they are a property of the tree the server\n * rendered, not of the address bar, and they now travel inside the payload as\n * the payload root. Keeping a copy here meant the router had to thread\n * the record from a response header into context on every path — navigation,\n * traversal, prefetch, revalidation — and each of those was a place to drop it\n * (TIM-1294).\n */\nexport interface NavigationState {\n pathname: string;\n search: string;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy context initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Context instances are stored on globalThis (NOT in module-level\n * variables) because the ESM bundler can duplicate this module across\n * chunks. Module-level variables would create separate instances per\n * chunk — the provider in NavigationRoot (index chunk) would use\n * context A while the consumer in usePendingNavigation (shared chunk)\n * reads from context B. globalThis guarantees a single instance.\n *\n * This module is `'use client'` so it is never evaluated in the RSC\n * environment — `createContext` and `useContext` are always available.\n * The shims plugin resolves next/navigation to navigation-rsc.ts in RSC,\n * which has throwing stubs for the hooks (TIM-1420).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n *\n * Exported for `usePendingNavigation(select)`, which reads it with React\n * `use()` — only in its selector form, so the plain form does not re-render\n * on every commit.\n */\nexport function getOrCreateContext(): import('react').Context<NavigationState | null> {\n return createGlobalContext<NavigationState | null>(Symbol.for('__timber_nav_ctx'), null);\n}\n\n/**\n * Read the navigation context. Returns null only when no provider is above\n * the caller — a component rendered outside the timber app.\n *\n * Internal — used by usePathname() and useSearchParams().\n */\nexport function useNavigationContext(): NavigationState | null {\n return useContext(getOrCreateContext());\n}\n\n// ---------------------------------------------------------------------------\n// Provider component\n// ---------------------------------------------------------------------------\n\nexport interface NavigationProviderProps {\n value: NavigationState;\n children?: ReactNode;\n}\n\n/**\n * Wraps children with NavigationContext.Provider.\n *\n * Used in browser-entry/router-init.ts `renderTree` to wrap the RSC payload element\n * so that navigation state updates atomically with the tree render.\n */\nexport function NavigationProvider({\n value,\n children,\n}: NavigationProviderProps): import('react').ReactElement {\n return createElement(getOrCreateContext().Provider, { value }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Pending navigation state lives in the router, not here\n// ---------------------------------------------------------------------------\n\n/**\n * There was a second React context here — `PendingNavigationContext`, holding\n * the in-flight navigation URL, provided by `NavigationRoot` out of a\n * `useState` — plus a `usePendingNavigationUrl()` reader for it. Both are gone\n * (TIM-1307).\n *\n * Nothing read them. `usePendingNavigation()` (use-pending-navigation.ts) and\n * `TopLoader` both subscribe to the router's external pending store via\n * `useSyncExternalStore`: sync priority, immune to transition entanglement,\n * and cleared by `runNavigation`'s supersession-guarded `finally` (TIM-1034).\n * The context was a parallel representation of the same fact that no consumer\n * ever migrated to, and one that could not even agree with the store — a\n * navigation superseded by a cached popstate replay left its URL set until the\n * next full navigation, because the staleness guard skipped the clear and no\n * other path touched it.\n *\n * One representation, and it is the router's. See\n * design/19-client-navigation.md §\"How Pending State Works\".\n */\n","/**\n * How the client router reads the URLs it is handed.\n *\n * One parser, so the places that key or compare by URL — the history stack,\n * the navigation state a page renders with, the departing page sent as\n * `X-Timber-URL` — cannot disagree about what a URL says. They did: a\n * history entry stored under `navigate('/café')`'s spelling was looked up\n * under the address bar's `/caf%C3%A9`, and missed (TIM-1541).\n */\n\nconst BASE = 'http://localhost';\n\n/**\n * Parse a router URL. A URL that starts with \"/\" is a path — including one\n * that starts with \"//\": that is the pathname a document at\n * `https://host//a/b` reports, and resolved against a base it would parse as\n * a scheme-relative reference to host `a`. Anything else resolves against a\n * placeholder origin, so an absolute URL keeps its own.\n */\nexport function parseRouterUrl(url: string): URL {\n return url.startsWith('/') ? new URL(BASE + url) : new URL(url, BASE);\n}\n\n/**\n * The spelling a URL is stored and looked up under: the browser's own\n * pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one\n * key. The fragment is dropped — it is client-only.\n */\nexport function routerUrlKey(url: string): string {\n const parsed = parseRouterUrl(url);\n return parsed.pathname + parsed.search;\n}\n","import { use, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { getOrCreateContext } from './navigation-context.ts';\nimport { getRouterOrNull } from './router-ref.ts';\nimport { parseRouterUrl } from './router-url.ts';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n const router = getRouterOrNull();\n if (!router) return () => {};\n return router.onPendingChange(onStoreChange);\n}\n\nfunction isPending(): boolean {\n const router = getRouterOrNull();\n return router ? router.isPending() : false;\n}\n\nconst HAS_SCHEME = /^[a-z][a-z\\d+.-]*:/i;\n\n/**\n * A router URL as a `URL`, read the way the router reads it (`parseRouterUrl`)\n * so `to` names the page the router will commit. Anything without a scheme is\n * a path on this document's origin; an absolute URL keeps its own.\n */\nfunction pageUrl(url: string): URL {\n const parsed = parseRouterUrl(url);\n if (HAS_SCHEME.test(url)) return parsed;\n return new URL(window.location.origin + parsed.pathname + parsed.search + parsed.hash);\n}\n\n/**\n * Decides what a component wants to know about the navigation in flight.\n *\n * `to` is where the router is going, with the `#fragment` of a link or\n * `router.push()` that has one (traversals and refreshes carry none). `from`\n * is the page the navigation departs from, as the calling component rendered\n * it — not the address bar, which on Back/Forward has already moved. Both are\n * fresh `URL`s; don't mutate them.\n */\nexport type PendingNavigationSelector<T> = (to: URL, from: URL) => T;\n\n/**\n * Whether an RSC navigation is in flight — until its payload has decoded and\n * React has committed the destination, so it never turns false while the\n * departing page is still on screen.\n *\n * Reads the router's external pending store via `useSyncExternalStore`, so\n * only components that call this hook re-render when a navigation starts or\n * ends.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return <nav className={isPending ? 'opacity-50' : ''}>…</nav>\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean;\n/**\n * The selector form: `select(to, from)` while a navigation is in flight,\n * `false` when none is. A navigation starting, being superseded or ending\n * re-renders the component only when the result changes (`Object.is`), so\n * return a primitive. The selector form also re-renders on commits, as\n * `usePathname()` does. A superseded navigation reports the newest target; a\n * followed redirect reports the redirect's destination.\n *\n * ```tsx\n * // Dim a list only while its own sort/filter/page navigation is in flight.\n * const replacing = usePendingNavigation((to, from) => to.pathname === from.pathname)\n * ```\n *\n * See design/19-client-navigation.md §\"Where the navigation is going\".\n */\nexport function usePendingNavigation<T>(select: PendingNavigationSelector<T>): T | false;\nexport function usePendingNavigation<T>(select?: PendingNavigationSelector<T>): T | boolean {\n // Read only by the selector form, so the plain form — TopLoader, a global\n // spinner — does not re-render on every commit.\n const nav = select ? use(getOrCreateContext()) : null;\n if (select && nav === null) {\n throw new Error(\n '[timber] usePendingNavigation(select) was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n const rendered = nav ? nav.pathname + nav.search : null;\n\n // The page each navigation departs from: what this component was rendering\n // when it first saw the target. Held for the navigation's lifetime because\n // the location context moves to the destination at its commit, while the\n // router is still pending — read live, a link away would report \"same page\"\n // for that commit and for any streaming tail after it.\n const departure = useRef<{ target: string; from: string } | null>(null);\n\n const getSnapshot = useMemo((): (() => T | boolean) => {\n if (!select || rendered === null) return isPending;\n // `getSnapshot` must return the same value for the same store state, and\n // a selector returning `to` would otherwise hand React a new URL per call.\n let last: { target: string; from: string; value: T } | null = null;\n return () => {\n const target = getRouterOrNull()?.getPendingUrl() ?? null;\n if (target === null) {\n departure.current = null;\n return false;\n }\n if (departure.current?.target !== target) departure.current = { target, from: rendered };\n const from = departure.current.from;\n if (last?.target !== target || last.from !== from) {\n last = { target, from, value: select(pageUrl(target), pageUrl(from)) };\n }\n return last.value;\n };\n }, [select, rendered]);\n\n // The same read on the server: no router there, so it reports idle.\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","/**\n * TopLoader — Built-in progress bar for client navigations.\n *\n * Shows an animated progress bar at the top of the viewport while an RSC\n * navigation is in flight. Injected automatically by the framework into\n * NavigationRoot — users never render this component directly.\n *\n * Configuration is via timber.config.ts `topLoader` key. Enabled by default.\n * Users who want a fully custom progress indicator disable the built-in one\n * (`topLoader: { enabled: false }`) and use `usePendingNavigation()` directly.\n *\n * Animation approach: pure CSS @keyframes. The bar crawls from 0% to ~90%\n * width over ~30s using ease-out timing. When navigation completes, the bar\n * snaps to 100% and fades out over 200ms. No JS animation loops (RAF, setInterval).\n *\n * Phase transitions are derived synchronously during render (React's\n * getDerivedStateFromProps pattern) — no useEffect needed for state tracking.\n * The finishing → hidden cleanup uses onTransitionEnd from the CSS transition.\n *\n * When delay > 0, CSS animation-delay + a visibility keyframe ensure the bar\n * stays invisible during the delay period. If navigation finishes before the\n * delay, the bar was never visible so the finish transition is also invisible.\n *\n * See design/19-client-navigation.md §\"usePendingNavigation()\"\n * See LOCAL-336 for design decisions.\n */\n\n'use client';\n\nimport { useState, createElement } from 'react';\nimport { usePendingNavigation } from './use-pending-navigation.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TopLoaderConfig {\n /** Whether the top-loader is enabled. Default: true. */\n enabled?: boolean;\n /** Bar color. Default: '#2299DD'. */\n color?: string;\n /** Bar height in pixels. Default: 3. */\n height?: number;\n /** Show subtle glow/shadow effect. Default: false. */\n shadow?: boolean;\n /** Delay in ms before showing the bar. Default: 0. */\n delay?: number;\n /** CSS z-index. Default: 1600. */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#2299DD';\nconst DEFAULT_HEIGHT = 3;\nconst DEFAULT_SHADOW = false;\nconst DEFAULT_DELAY = 0;\nconst DEFAULT_Z_INDEX = 1600;\n\n// ─── Keyframes ───────────────────────────────────────────────────\n\n// Unique keyframes name to avoid collisions with user styles.\nconst CRAWL_KEYFRAMES = '__timber_top_loader_crawl';\nconst APPEAR_KEYFRAMES = '__timber_top_loader_appear';\nconst FINISH_KEYFRAMES = '__timber_top_loader_finish';\n\n// Track whether the @keyframes rules have been injected into the document.\nlet keyframesInjected = false;\n\n/**\n * Inject the @keyframes rules into the document head once.\n * Called during render (idempotent). Uses a <style> tag so the\n * animations are available for inline-styled elements.\n */\nfunction ensureKeyframes(): void {\n if (keyframesInjected) return;\n if (typeof document === 'undefined') return;\n\n const style = document.createElement('style');\n style.textContent = `\n@keyframes ${CRAWL_KEYFRAMES} {\n 0% { width: 0%; }\n 100% { width: 90%; }\n}\n@keyframes ${APPEAR_KEYFRAMES} {\n from { opacity: 0; }\n to { opacity: 1; }\n}\n@keyframes ${FINISH_KEYFRAMES} {\n 0% { width: 90%; opacity: 1; }\n 50% { width: 100%; opacity: 1; }\n 100% { width: 100%; opacity: 0; }\n}\n`;\n document.head.appendChild(style);\n keyframesInjected = true;\n}\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Internal top-loader component. Injected by NavigationRoot.\n *\n * Reads pending navigation state from the router's external store, via\n * usePendingNavigation() — the one pending representation (TIM-1307).\n * Phase transitions are derived synchronously during render:\n *\n * hidden → crawling: when isPending becomes true\n * crawling → finishing: when isPending becomes false\n * finishing → hidden: when CSS transition ends (onTransitionEnd)\n * finishing → crawling: when isPending becomes true again\n *\n * No useEffect — all state changes are either derived during render\n * (getDerivedStateFromProps pattern) or triggered by DOM events.\n */\nexport function TopLoader({ config }: { config?: TopLoaderConfig }): React.ReactElement | null {\n // Read pending state from the router's external store via\n // useSyncExternalStore (inside usePendingNavigation). Only this\n // component re-renders when pending changes — no full-tree re-render.\n const isPending = usePendingNavigation();\n\n const color = config?.color ?? DEFAULT_COLOR;\n const height = config?.height ?? DEFAULT_HEIGHT;\n const shadow = config?.shadow ?? DEFAULT_SHADOW;\n const delay = config?.delay ?? DEFAULT_DELAY;\n const zIndex = config?.zIndex ?? DEFAULT_Z_INDEX;\n\n const [phase, setPhase] = useState<'hidden' | 'crawling' | 'finishing'>('hidden');\n\n // ─── Synchronous phase derivation (getDerivedStateFromProps) ──\n // React allows setState during render if the value changes — it\n // immediately re-renders with the updated state before committing.\n\n if (isPending && (phase === 'hidden' || phase === 'finishing')) {\n setPhase('crawling');\n }\n if (!isPending && phase === 'crawling') {\n setPhase('finishing');\n }\n\n // Inject keyframes on first visible render (idempotent)\n if (phase !== 'hidden') {\n ensureKeyframes();\n }\n\n if (phase === 'hidden') return null;\n\n // ─── Styles ──────────────────────────────────────────────────\n\n const containerStyle: React.CSSProperties = {\n position: 'fixed',\n top: 0,\n left: 0,\n width: '100%',\n height: `${height}px`,\n zIndex,\n pointerEvents: 'none',\n };\n\n const barStyle: React.CSSProperties = {\n height: '100%',\n backgroundColor: color,\n ...(phase === 'crawling'\n ? {\n // Crawl from 0% to 90% over 30s. When delay > 0, both the crawl\n // and a visibility animation are delayed — the bar stays at width 0%\n // and opacity 0 during the delay, then appears and starts crawling.\n // With delay 0, the appear animation is instant (0s duration, no delay).\n animation: [\n `${CRAWL_KEYFRAMES} 30s ease-out ${delay}ms forwards`,\n `${APPEAR_KEYFRAMES} 0s ${delay}ms both`,\n ].join(', '),\n }\n : {\n // Finishing: fill to 100% then fade out via a keyframe animation.\n // We use a keyframe instead of a CSS transition because the\n // animation-to-transition handoff is unreliable — the browser\n // may not capture the animated width as the transition's \"from\"\n // value when both the animation removal and transition are\n // applied in the same render frame.\n animation: `${FINISH_KEYFRAMES} 400ms ease forwards`,\n }),\n ...(shadow\n ? {\n boxShadow: `0 0 10px ${color}, 0 0 5px ${color}`,\n }\n : {}),\n };\n\n // Clean up the finishing phase when the finish animation completes.\n const handleAnimationEnd =\n phase === 'finishing'\n ? (e: React.AnimationEvent) => {\n if (e.animationName === FINISH_KEYFRAMES) {\n setPhase('hidden');\n }\n }\n : undefined;\n\n return createElement(\n 'div',\n {\n 'style': containerStyle,\n 'aria-hidden': 'true',\n 'data-timber-top-loader': '',\n },\n createElement('div', { style: barStyle, onAnimationEnd: handleAnimationEnd })\n );\n}\n","/**\n * NavigationRoot — the component the router renders the page through.\n *\n * It is stateless. The router owns the displayed tree and drives React with\n * `root.render(<NavigationRoot rendered={{ element, publish }} />)` inside a\n * synchronous `startTransition` (see `client/react-root.ts`). A transition\n * update keeps the committed tree on screen while the incoming one resolves,\n * instead of replacing it with a Suspense fallback — the reason this\n * component exists (TIM-1306).\n *\n * It used to hold the tree in `useState` and register `setState` closures\n * into module globals during render so the router could reach into it, with a\n * second set of stand-in closures for the window before a root existed\n * (TIM-600). Inverting that — router calls React, not the reverse — deleted\n * all of it (TIM-1431). Next.js's `use-action-queue.ts` says it wants this\n * shape and cannot have it because it must decode Flight during render;\n * timber decodes in `router-pipeline.ts`, so nothing stands in the way.\n *\n * What this component does own is **the commit-time publish**: a navigation's\n * state (segment cache, address bar, history stack, pathname) is published\n * from a layout effect keyed on the tree object, so the event that puts a\n * route on screen is the event that makes it current (TIM-1301). Props work\n * for that exactly as state did.\n *\n * This component holds no pending state. The `TopLoader` it renders and the\n * public `usePendingNavigation()` both subscribe to the router's external\n * pending store; NavigationRoot's own `pendingUrl` was a second, unread\n * representation of the same fact and is gone (TIM-1307).\n *\n * Hard navigation guard: When a hard navigation is triggered (500 error,\n * version skew), the component throws an unresolved thenable AFTER all\n * hooks to suspend forever — preventing React from rendering children\n * during page teardown. The throw must come after hooks to satisfy\n * React's rules (same hook count every render) while still preventing\n * child renders that could hit hook count mismatches in components\n * whose positions shift during teardown. This pattern is borrowed from\n * Next.js (app-router.tsx pushRef.mpaNavigation — also after hooks).\n *\n * See design/05-streaming.md §\"deferSuspenseFor\"\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { createElement, Fragment, useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { TopLoader, type TopLoaderConfig } from './top-loader.tsx';\n\n// ─── Rendered Tree ──────────────────────────────────────────────\n\n/**\n * The tree the router has handed to React, and the state publish that belongs\n * to it. They travel as one object so React's commit of the tree is the event\n * that publishes — see the effect in NavigationRoot. Every `render` builds a\n * fresh one, which is what keys that effect: a tree is published once, however\n * many times React re-runs the effect for it.\n */\nexport interface RenderedTree {\n element: ReactNode;\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. Runs when React commits\n * `element`, never before (TIM-1301). Null for a render that has nothing to\n * publish on commit (hydration, the shallow search re-wrap).\n */\n publish: (() => void) | null;\n}\n\n/**\n * Hand a tree to React in a transition. `publish` runs when React commits it.\n *\n * Every path that puts a page on screen goes through one of these — a\n * navigation, a revalidation, a popstate replay, a shallow search re-wrap —\n * and it is always a synchronous `startTransition` around `root.render`.\n * The production one is `createReactRoot().render`.\n *\n * `types` are the view transition types this render animates as\n * (design/37-navigation-api.md §\"Transition types\"). They are added with\n * `addTransitionType` inside that same `startTransition`, and nowhere else:\n * React queues types per root and hands them to the next transition-only\n * commit, so a type added in any other scope describes whichever tree commits\n * next rather than this one (TIM-1463, TIM-1471). Empty for the shallow search\n * re-wrap, which re-renders the displayed page rather than changing it.\n */\nexport type NavigationRender = (\n element: ReactNode,\n publish: (() => void) | null,\n types: readonly string[]\n) => void;\n\n// ─── Hard Navigation Guard ──────────────────────────────────────\n\n/**\n * Module-level flag indicating a hard (MPA) navigation is in progress.\n *\n * When true:\n * - NavigationRoot throws an unresolved thenable to suspend forever,\n * preventing React from rendering children during page teardown\n * (avoids \"Rendered more hooks\" crashes).\n * - The Navigation API handler skips interception, letting the browser\n * perform a full page load (prevents infinite loops where\n * window.location.href → navigate event → router.navigate → 500 →\n * window.location.href → ...).\n *\n * Uses globalThis for singleton guarantee across chunks (same pattern\n * as NavigationContext). See design/19-client-navigation.md §\"Singleton\n * Guarantee via globalThis\".\n */\nconst HARD_NAV_KEY = Symbol.for('__timber_hard_navigating');\n\nfunction getHardNavStore(): { value: boolean } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[HARD_NAV_KEY]) {\n g[HARD_NAV_KEY] = { value: false };\n }\n return g[HARD_NAV_KEY] as { value: boolean };\n}\n\n/**\n * Set the hard-navigating flag. Call this BEFORE setting\n * window.location.href or window.location.reload() to prevent:\n * 1. React from rendering children during page teardown\n * 2. Navigation API from intercepting the hard navigation\n */\nexport function setHardNavigating(value: boolean): void {\n getHardNavStore().value = value;\n}\n\n/**\n * Check if a hard navigation is in progress.\n * Used by NavigationRoot (throw unresolvedThenable) and by the\n * Navigation API handler (skip interception).\n */\nexport function isHardNavigating(): boolean {\n return getHardNavStore().value;\n}\n\n/**\n * A thenable that never resolves. When thrown during React render,\n * it causes the component to suspend forever — React keeps the\n * old committed tree visible and never attempts to render children.\n *\n * This is the same pattern Next.js uses in app-router.tsx for MPA\n * navigations (pushRef.mpaNavigation → throw unresolvedThenable).\n */\n// for React's Suspense mechanism. Same pattern as Next.js's unresolvedThenable.\n// eslint-disable-next-line unicorn/no-thenable -- Intentionally a never-resolving thenable\nconst unresolvedThenable = { then() {} } as PromiseLike<never>;\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Root component the router renders the page through.\n *\n * Renders the TopLoader alongside the tree it is given. Neither adds a DOM\n * element on the hydration path, so the tree matches the server HTML.\n *\n * Rendered only by `createReactRoot` (client/react-root.ts): hydration passes\n * `{ element, publish: null }`, and every later render is a synchronous\n * `startTransition(() => root.render(...))` with a fresh `rendered` object.\n */\nexport function NavigationRoot({\n rendered,\n topLoaderConfig,\n}: {\n rendered: RenderedTree;\n topLoaderConfig?: TopLoaderConfig;\n}): ReactNode {\n // Publish the navigation's state when React commits its tree — not when the\n // tree is handed over. A tree React is still waiting on, or one a later\n // navigation replaces before React renders it, has been *given* to React\n // without being on screen; publishing then describes a route the user never\n // saw, which is the defect this ordering exists to prevent (TIM-1301).\n //\n // A **layout** effect, so the publish lands before the browser paints and,\n // more importantly, before every descendant's passive effect. A destination\n // component that navigates from a mount effect — a redirect guard, a\n // `refresh()` on mount — would otherwise start its navigation while the\n // segment cache, address bar and pathname still described the departing\n // route, and send an X-Timber-State-Tree for a tree that is no longer\n // mounted (codex on #998).\n //\n // Descendant *layout* effects still run first: React runs layout effects\n // child-before-parent, and the only way to precede them would be a fiber\n // rendered as an earlier sibling of the payload. That is not free here —\n // `server/ssr-wrappers.tsx` mirrors this component's fiber shape so `useId`\n // agrees across hydration, and an extra sibling shifts every id in the\n // payload subtree. A layout effect that navigates on mount is the price.\n //\n // Keyed on the tree object rather than on the effect run. A publish moves\n // the address bar, which is not idempotent, so any second invocation for the\n // same tree — an effect re-run React is entitled to perform, StrictMode's\n // double-invoke — must be a no-op rather than a second history entry.\n const publishedRef = useRef<RenderedTree | null>(null);\n useLayoutEffect(() => {\n if (publishedRef.current === rendered) return;\n publishedRef.current = rendered;\n rendered.publish?.();\n }, [rendered]);\n\n // ─── Hard navigation guard ─────────────────────────────────\n // When a hard navigation is in progress (500 error, version skew),\n // suspend forever to prevent React from rendering children during\n // page teardown. This avoids \"Rendered more hooks\" crashes in\n // CHILD components whose hook counts may shift during teardown.\n //\n // CRITICAL: This throw MUST come AFTER all hooks (the useRef and\n // useLayoutEffect above). React requires the same hooks to run on every\n // render. If we threw before hooks, React would see 0 hooks on the\n // re-render vs 2 on the initial render — triggering the exact \"Rendered\n // more hooks\" error we're trying to prevent.\n //\n // By placing it after hooks but before the return, all hooks\n // satisfy React's rules, but the thrown thenable prevents any\n // children from rendering. Same pattern as Next.js app-router.tsx\n // (pushRef.mpaNavigation — also placed after all hooks).\n if (isHardNavigating()) {\n throw unresolvedThenable;\n }\n\n // Inject TopLoader alongside the element tree. It subscribes to the router's\n // pending store itself, so it takes no props from here beyond its config,\n // and only it re-renders when a navigation starts or ends. Its slot holds\n // `null` when the loader is disabled via config.\n //\n // This Fragment is a FORK — two children — so it advances React's tree\n // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`\n // mirrors it for exactly that reason, and renders the document's default\n // <meta> tags in the first slot. The fork is unconditional so the server\n // never needs to know whether the loader is enabled: a `null` child still\n // counts toward the fork on both sides. See tests/ssr-wrapper-parity.test.ts.\n const showTopLoader = topLoaderConfig?.enabled !== false;\n return createElement(\n Fragment,\n null,\n showTopLoader ? createElement(TopLoader, { config: topLoaderConfig }) : null,\n rendered.element\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,gBAAgB,QAA8B;CAC5D,iBAAiB,MAAM;AACzB;;;;;AAMA,SAAgB,YAA4B;CAC1C,IAAI,CAAC,cACH,MAAM,IAAI,MAAM,6EAA6E;CAE/F,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAyC;CACvD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACFA,SAAgB,oBAAuB,KAAa,cAAmC;CACrF,OAAO,uBAAuB,OAAO,KAAK,YAAY;AACxD;;AAGA,SAAgB,uBACd,OACA,KACA,cACkB;CAClB,IAAI,OAAO,MAAM,kBAAkB,YAGjC;CAEF,MAAM,OAAgB,QAAQ,IAAI,YAAY,GAAG;CACjD,MAAM,UAAU,gBAAgB,UAAU,uBAAO,IAAI,QAAkC;CACvF,IAAI,YAAY,MAAM,QAAQ,IAAI,YAAY,KAAK,OAAO;CAC1D,IAAI,MAAoC,QAAQ,IAAI,KAAK;CACzD,IAAI,CAAC,KAAK;EACR,MAAM,MAAM,cAAiB,YAAY;EACzC,QAAQ,IAAI,OAAO,GAAG;CACxB;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC+BA,SAAgB,qBAAsE;CACpF,OAAO,oBAA4C,OAAO,IAAI,kBAAkB,GAAG,IAAI;AACzF;;;;;;;AAQA,SAAgB,uBAA+C;CAC7D,OAAO,WAAW,mBAAmB,CAAC;AACxC;;;;;;;AAiBA,SAAgB,mBAAmB,EACjC,OACA,YACwD;CACxD,OAAO,cAAc,mBAAmB,CAAC,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ;AACzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC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AAW,UAAU,KAAK,SAAS,MAC3C,OAAO;IAAE;IAAQ;IAAM,OAAO,OAAO,QAAQ,MAAM,GAAG,QAAQ,IAAI,CAAC;GAAE;GAEvE,OAAO,KAAK;EACd;CACF,GAAG,CAAC,QAAQ,QAAQ,CAAC;CAGrB,OAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEZA,IAAM,eAAe,OAAO,IAAI,0BAA0B;AAE1D,SAAS,kBAAsC;CAC7C,MAAM,IAAI;CACV,IAAI,CAAC,EAAE,eACL,EAAE,gBAAgB,EAAE,OAAO,MAAM;CAEnC,OAAO,EAAE;AACX;;;;;;;AAQA,SAAgB,kBAAkB,OAAsB;CACtD,gBAAgB,CAAC,CAAC,QAAQ;AAC5B"}
1
+ {"version":3,"file":"navigation-root-Cvb7P1ud.js","names":[],"sources":["../../src/client/router-ref.ts","../../src/client/global-context.ts","../../src/client/navigation-context.ts","../../src/client/router-url.ts","../../src/client/use-pending-navigation.ts","../../src/client/navigation-root.tsx"],"sourcesContent":["// Global router reference — shared between browser-entry and client hooks.\n//\n// Delegates to client/state.ts for the actual module-level variable.\n// This ensures singleton semantics regardless of import path — all\n// callers converge on the same state.ts instance via the barrel.\n//\n// See design/18-build-system.md §\"Module Singleton Strategy\"\n\nimport type { RouterInstance } from './router-types.ts';\nimport { globalRouter, _setGlobalRouter } from './state.ts';\n\n/**\n * Set the global router instance. Called once during bootstrap.\n */\nexport function setGlobalRouter(router: RouterInstance): void {\n _setGlobalRouter(router);\n}\n\n/**\n * Get the global router instance. Throws if called before bootstrap.\n * Used by client-side hooks (usePendingNavigation, etc.)\n */\nexport function getRouter(): RouterInstance {\n if (!globalRouter) {\n throw new Error('[timber] Router not initialized. getRouter() was called before bootstrap().');\n }\n return globalRouter;\n}\n\n/**\n * Get the global router instance or null if not yet initialized.\n * Used by useRouter() methods to avoid silent failures — callers\n * can log a meaningful warning instead of silently no-oping.\n */\nexport function getRouterOrNull(): RouterInstance | null {\n return globalRouter;\n}\n\n/**\n * Reset the global router to null. Used only in tests to isolate\n * module-level state between test cases.\n * @internal\n */\nexport function resetGlobalRouter(): void {\n _setGlobalRouter(null);\n}\n","/**\n * createGlobalContext — a React context with a process-wide singleton identity.\n *\n * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as\n * NavigationContext. The RSC client bundler can duplicate a module across\n * chunks (browser-entry graph + client-reference graph). With ESM output,\n * each chunk gets its own module scope — a bare createContext at module\n * level would create separate instances per chunk. globalThis guarantees a\n * single instance regardless of duplication.\n *\n * One context per React instance, not per process. Duplicated chunks share\n * one React, so they share the context. A dev SSR program reload evaluates\n * React and react-dom/server again, in the same process: the new renderer\n * must get a context of its own. Handed the previous one, React logs\n * \"Detected multiple renderers concurrently rendering the same context\n * provider\" on every client-component edit, and the stale context keeps a\n * piece of the discarded copy alive (TIM-1590).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n */\n\nimport React from 'react';\n\n/** The part of a React instance a context comes from. */\nexport interface ContextFactory {\n createContext?: typeof React.createContext;\n}\n\n/**\n * The context `key` names for this React instance, created on first use.\n * Pass the key as a `Symbol.for('…')` literal at the call site, so each key\n * stays greppable in the build output (tests/bundle-singleton-audit.test.ts\n * checks `__timber_nav_ctx`).\n */\nexport function createGlobalContext<T>(key: symbol, defaultValue: T): React.Context<T> {\n return createGlobalContextFor(React, key, defaultValue);\n}\n\n/** createGlobalContext for a given React instance. Exported for tests. */\nexport function createGlobalContextFor<T>(\n react: ContextFactory,\n key: symbol,\n defaultValue: T\n): React.Context<T> {\n if (typeof react.createContext !== 'function') {\n // RSC environment — createContext not available. Return a dummy that\n // won't be used (the consumers only render on the client / during SSR).\n return undefined as unknown as React.Context<T>;\n }\n const slot: unknown = Reflect.get(globalThis, key);\n const byReact = slot instanceof WeakMap ? slot : new WeakMap<object, React.Context<T>>();\n if (byReact !== slot) Reflect.set(globalThis, key, byReact);\n let ctx: React.Context<T> | undefined = byReact.get(react);\n if (!ctx) {\n ctx = react.createContext<T>(defaultValue);\n byReact.set(react, ctx);\n }\n return ctx;\n}\n","'use client';\n\n/**\n * NavigationContext — React context for navigation state.\n *\n * Holds the current pathname and search, updated atomically with the RSC\n * tree on each navigation. This replaces the previous useSyncExternalStore\n * approach for usePathname() and useSearchParams(), which suffered from a\n * timing gap: the new tree could commit before the external store\n * re-renders fired, causing a frame where both old and new active states\n * were visible simultaneously.\n *\n * Segment params are NOT here — see the note on NavigationState below.\n *\n * By wrapping the RSC payload element in NavigationProvider inside the\n * router's `renderTree` (browser-entry/router-init.ts), the context value and the element tree are passed to\n * reactRoot.render() in the same call — atomic by construction.\n * All consumers (usePathname, useSearchParams) see the new values in the\n * same render pass as the new tree.\n *\n * During SSR, the wrapper chain mounts this same provider with the\n * request's pathname and raw search string (TIM-1424), so the hooks\n * resolve through the identical code path on both sides. Per-request\n * isolation is by construction — the value is part of the request's\n * element tree.\n *\n * This module is `'use client'` and is never evaluated in the RSC\n * environment. The shims plugin resolves next/navigation to\n * navigation-rsc.ts in RSC, which has throwing stubs (TIM-1420).\n *\n * SINGLETON GUARANTEE: All shared mutable state uses globalThis via\n * Symbol.for keys. The RSC client bundler can duplicate this module\n * across chunks (browser-entry graph + client-reference graph). With\n * ESM output, each chunk gets its own module scope — module-level\n * variables would create separate singleton instances per chunk.\n * globalThis guarantees a single instance regardless of duplication.\n *\n * This workaround will be removed when Rolldown ships `format: 'app'`\n * (module registry format that deduplicates like webpack/Turbopack).\n * See design/27-chunking-strategy.md.\n *\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { useContext, createElement, type ReactNode } from 'react';\nimport { createGlobalContext } from './global-context.ts';\n\n// ---------------------------------------------------------------------------\n// Context type\n// ---------------------------------------------------------------------------\n\n/**\n * What the browser knows about the current location.\n *\n * Params are deliberately absent: they are a property of the tree the server\n * rendered, not of the address bar, and they now travel inside the payload as\n * the payload root. Keeping a copy here meant the router had to thread\n * the record from a response header into context on every path — navigation,\n * traversal, prefetch, revalidation — and each of those was a place to drop it\n * (TIM-1294).\n */\nexport interface NavigationState {\n pathname: string;\n search: string;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy context initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Context instances are stored on globalThis (NOT in module-level\n * variables) because the ESM bundler can duplicate this module across\n * chunks. Module-level variables would create separate instances per\n * chunk — the provider in NavigationRoot (index chunk) would use\n * context A while the consumer in usePendingNavigation (shared chunk)\n * reads from context B. globalThis guarantees a single instance.\n *\n * This module is `'use client'` so it is never evaluated in the RSC\n * environment — `createContext` and `useContext` are always available.\n * The shims plugin resolves next/navigation to navigation-rsc.ts in RSC,\n * which has throwing stubs for the hooks (TIM-1420).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n *\n * Exported for `usePendingNavigation(select)`, which reads it with React\n * `use()` — only in its selector form, so the plain form does not re-render\n * on every commit.\n */\nexport function getOrCreateContext(): import('react').Context<NavigationState | null> {\n return createGlobalContext<NavigationState | null>(Symbol.for('__timber_nav_ctx'), null);\n}\n\n/**\n * Read the navigation context. Returns null only when no provider is above\n * the caller — a component rendered outside the timber app.\n *\n * Internal — used by usePathname() and useSearchParams().\n */\nexport function useNavigationContext(): NavigationState | null {\n return useContext(getOrCreateContext());\n}\n\n// ---------------------------------------------------------------------------\n// Provider component\n// ---------------------------------------------------------------------------\n\nexport interface NavigationProviderProps {\n value: NavigationState;\n children?: ReactNode;\n}\n\n/**\n * Wraps children with NavigationContext.Provider.\n *\n * Used in browser-entry/router-init.ts `renderTree` to wrap the RSC payload element\n * so that navigation state updates atomically with the tree render.\n */\nexport function NavigationProvider({\n value,\n children,\n}: NavigationProviderProps): import('react').ReactElement {\n return createElement(getOrCreateContext().Provider, { value }, children);\n}\n\n// ---------------------------------------------------------------------------\n// Pending navigation state lives in the router, not here\n// ---------------------------------------------------------------------------\n\n/**\n * There was a second React context here — `PendingNavigationContext`, holding\n * the in-flight navigation URL, provided by `NavigationRoot` out of a\n * `useState` — plus a `usePendingNavigationUrl()` reader for it. Both are gone\n * (TIM-1307).\n *\n * Nothing read them. `usePendingNavigation()` (use-pending-navigation.ts) and\n * `TopLoader` both subscribe to the router's external pending store via\n * `useSyncExternalStore`: sync priority, immune to transition entanglement,\n * and cleared by `runNavigation`'s supersession-guarded `finally` (TIM-1034).\n * The context was a parallel representation of the same fact that no consumer\n * ever migrated to, and one that could not even agree with the store — a\n * navigation superseded by a cached popstate replay left its URL set until the\n * next full navigation, because the staleness guard skipped the clear and no\n * other path touched it.\n *\n * One representation, and it is the router's. See\n * design/19-client-navigation.md §\"How Pending State Works\".\n */\n","/**\n * How the client router reads the URLs it is handed.\n *\n * One parser, so the places that key or compare by URL — the history stack,\n * the navigation state a page renders with, the departing page sent as\n * `X-Timber-URL` — cannot disagree about what a URL says. They did: a\n * history entry stored under `navigate('/café')`'s spelling was looked up\n * under the address bar's `/caf%C3%A9`, and missed (TIM-1541).\n */\n\nconst BASE = 'http://localhost';\n\n/**\n * Parse a router URL. A URL that starts with \"/\" is a path — including one\n * that starts with \"//\": that is the pathname a document at\n * `https://host//a/b` reports, and resolved against a base it would parse as\n * a scheme-relative reference to host `a`. Anything else resolves against a\n * placeholder origin, so an absolute URL keeps its own.\n */\nexport function parseRouterUrl(url: string): URL {\n return url.startsWith('/') ? new URL(BASE + url) : new URL(url, BASE);\n}\n\n/**\n * The spelling a URL is stored and looked up under: the browser's own\n * pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one\n * key. The fragment is dropped — it is client-only.\n */\nexport function routerUrlKey(url: string): string {\n const parsed = parseRouterUrl(url);\n return parsed.pathname + parsed.search;\n}\n","import { use, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { getOrCreateContext } from './navigation-context.ts';\nimport { getRouterOrNull } from './router-ref.ts';\nimport { parseRouterUrl } from './router-url.ts';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n const router = getRouterOrNull();\n if (!router) return () => {};\n return router.onPendingChange(onStoreChange);\n}\n\nfunction isPending(): boolean {\n const router = getRouterOrNull();\n return router ? router.isPending() : false;\n}\n\nconst HAS_SCHEME = /^[a-z][a-z\\d+.-]*:/i;\n\n/**\n * A router URL as a `URL`, read the way the router reads it (`parseRouterUrl`)\n * so `to` names the page the router will commit. Anything without a scheme is\n * a path on this document's origin; an absolute URL keeps its own.\n */\nfunction pageUrl(url: string): URL {\n const parsed = parseRouterUrl(url);\n if (HAS_SCHEME.test(url)) return parsed;\n return new URL(window.location.origin + parsed.pathname + parsed.search + parsed.hash);\n}\n\n/**\n * Decides what a component wants to know about the navigation in flight.\n *\n * `to` is where the router is going, with the `#fragment` of a link or\n * `router.push()` that has one (traversals and refreshes carry none). `from`\n * is the page the navigation departs from, as the calling component rendered\n * it — not the address bar, which on Back/Forward has already moved. Both are\n * fresh `URL`s; don't mutate them.\n */\nexport type PendingNavigationSelector<T> = (to: URL, from: URL) => T;\n\n/**\n * Whether an RSC navigation is in flight — until its payload has decoded and\n * React has committed the destination, so it never turns false while the\n * departing page is still on screen.\n *\n * Reads the router's external pending store via `useSyncExternalStore`, so\n * only components that call this hook re-render when a navigation starts or\n * ends.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return <nav className={isPending ? 'opacity-50' : ''}>…</nav>\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean;\n/**\n * The selector form: `select(to, from)` while a navigation is in flight,\n * `false` when none is. A navigation starting, being superseded or ending\n * re-renders the component only when the result changes (`Object.is`), so\n * return a primitive. The selector form also re-renders on commits, as\n * `usePathname()` does. A superseded navigation reports the newest target; a\n * followed redirect reports the redirect's destination.\n *\n * ```tsx\n * // Dim a list only while its own sort/filter/page navigation is in flight.\n * const replacing = usePendingNavigation((to, from) => to.pathname === from.pathname)\n * ```\n *\n * See design/19-client-navigation.md §\"Where the navigation is going\".\n */\nexport function usePendingNavigation<T>(select: PendingNavigationSelector<T>): T | false;\nexport function usePendingNavigation<T>(select?: PendingNavigationSelector<T>): T | boolean {\n // Read only by the selector form, so the plain form — TopLoader, a global\n // spinner — does not re-render on every commit.\n const nav = select ? use(getOrCreateContext()) : null;\n if (select && nav === null) {\n throw new Error(\n '[timber] usePendingNavigation(select) was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n const rendered = nav ? nav.pathname + nav.search : null;\n\n // The page each navigation departs from: what this component was rendering\n // when it first saw the target. Held for the navigation's lifetime because\n // the location context moves to the destination at its commit, while the\n // router is still pending — read live, a link away would report \"same page\"\n // for that commit and for any streaming tail after it.\n const departure = useRef<{ target: string; from: string } | null>(null);\n\n const getSnapshot = useMemo((): (() => T | boolean) => {\n if (!select || rendered === null) return isPending;\n // `getSnapshot` must return the same value for the same store state, and\n // a selector returning `to` would otherwise hand React a new URL per call.\n let last: { target: string; from: string; value: T } | null = null;\n return () => {\n const target = getRouterOrNull()?.getPendingUrl() ?? null;\n if (target === null) {\n departure.current = null;\n return false;\n }\n if (departure.current?.target !== target) departure.current = { target, from: rendered };\n const from = departure.current.from;\n if (last?.target !== target || last.from !== from) {\n last = { target, from, value: select(pageUrl(target), pageUrl(from)) };\n }\n return last.value;\n };\n }, [select, rendered]);\n\n // The same read on the server: no router there, so it reports idle.\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","/**\n * NavigationRoot — the component the router renders the page through.\n *\n * It is stateless. The router owns the displayed tree and drives React with\n * `root.render(<NavigationRoot rendered={{ element, publish }} />)` inside a\n * synchronous `startTransition` (see `client/react-root.ts`). A transition\n * update keeps the committed tree on screen while the incoming one resolves,\n * instead of replacing it with a Suspense fallback — the reason this\n * component exists (TIM-1306).\n *\n * It used to hold the tree in `useState` and register `setState` closures\n * into module globals during render so the router could reach into it, with a\n * second set of stand-in closures for the window before a root existed\n * (TIM-600). Inverting that — router calls React, not the reverse — deleted\n * all of it (TIM-1431). Next.js's `use-action-queue.ts` says it wants this\n * shape and cannot have it because it must decode Flight during render;\n * timber decodes in `router-pipeline.ts`, so nothing stands in the way.\n *\n * What this component does own is **the commit-time publish**: a navigation's\n * state (segment cache, address bar, history stack, pathname) is published\n * from a layout effect keyed on the tree object, so the event that puts a\n * route on screen is the event that makes it current (TIM-1301). Props work\n * for that exactly as state did.\n *\n * This component holds no pending state. The `TopLoader` it renders and the\n * public `usePendingNavigation()` both subscribe to the router's external\n * pending store; NavigationRoot's own `pendingUrl` was a second, unread\n * representation of the same fact and is gone (TIM-1307).\n *\n * Hard navigation guard: When a hard navigation is triggered (500 error,\n * version skew), the component throws an unresolved thenable AFTER all\n * hooks to suspend forever — preventing React from rendering children\n * during page teardown. The throw must come after hooks to satisfy\n * React's rules (same hook count every render) while still preventing\n * child renders that could hit hook count mismatches in components\n * whose positions shift during teardown. This pattern is borrowed from\n * Next.js (app-router.tsx pushRef.mpaNavigation — also after hooks).\n *\n * See design/05-streaming.md §\"deferSuspenseFor\"\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { createElement, Fragment, useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { TopLoader, type TopLoaderConfig } from './top-loader.tsx';\n\n// ─── Rendered Tree ──────────────────────────────────────────────\n\n/**\n * The tree the router has handed to React, and the state publish that belongs\n * to it. They travel as one object so React's commit of the tree is the event\n * that publishes — see the effect in NavigationRoot. Every `render` builds a\n * fresh one, which is what keys that effect: a tree is published once, however\n * many times React re-runs the effect for it.\n */\nexport interface RenderedTree {\n element: ReactNode;\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. Runs when React commits\n * `element`, never before (TIM-1301). Null for a render that has nothing to\n * publish on commit (hydration, the shallow search re-wrap).\n */\n publish: (() => void) | null;\n}\n\n/**\n * Hand a tree to React in a transition. `publish` runs when React commits it.\n *\n * Every path that puts a page on screen goes through one of these — a\n * navigation, a revalidation, a popstate replay, a shallow search re-wrap —\n * and it is always a synchronous `startTransition` around `root.render`.\n * The production one is `createReactRoot().render`.\n *\n * `types` are the view transition types this render animates as\n * (design/37-navigation-api.md §\"Transition types\"). They are added with\n * `addTransitionType` inside that same `startTransition`, and nowhere else:\n * React queues types per root and hands them to the next transition-only\n * commit, so a type added in any other scope describes whichever tree commits\n * next rather than this one (TIM-1463, TIM-1471). Empty for the shallow search\n * re-wrap, which re-renders the displayed page rather than changing it.\n */\nexport type NavigationRender = (\n element: ReactNode,\n publish: (() => void) | null,\n types: readonly string[]\n) => void;\n\n// ─── Hard Navigation Guard ──────────────────────────────────────\n\n/**\n * Module-level flag indicating a hard (MPA) navigation is in progress.\n *\n * When true:\n * - NavigationRoot throws an unresolved thenable to suspend forever,\n * preventing React from rendering children during page teardown\n * (avoids \"Rendered more hooks\" crashes).\n * - The Navigation API handler skips interception, letting the browser\n * perform a full page load (prevents infinite loops where\n * window.location.href → navigate event → router.navigate → 500 →\n * window.location.href → ...).\n *\n * Uses globalThis for singleton guarantee across chunks (same pattern\n * as NavigationContext). See design/19-client-navigation.md §\"Singleton\n * Guarantee via globalThis\".\n */\nconst HARD_NAV_KEY = Symbol.for('__timber_hard_navigating');\n\nfunction getHardNavStore(): { value: boolean } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[HARD_NAV_KEY]) {\n g[HARD_NAV_KEY] = { value: false };\n }\n return g[HARD_NAV_KEY] as { value: boolean };\n}\n\n/**\n * Set the hard-navigating flag. Call this BEFORE setting\n * window.location.href or window.location.reload() to prevent:\n * 1. React from rendering children during page teardown\n * 2. Navigation API from intercepting the hard navigation\n */\nexport function setHardNavigating(value: boolean): void {\n getHardNavStore().value = value;\n}\n\n/**\n * Check if a hard navigation is in progress.\n * Used by NavigationRoot (throw unresolvedThenable) and by the\n * Navigation API handler (skip interception).\n */\nexport function isHardNavigating(): boolean {\n return getHardNavStore().value;\n}\n\n/**\n * A thenable that never resolves. When thrown during React render,\n * it causes the component to suspend forever — React keeps the\n * old committed tree visible and never attempts to render children.\n *\n * This is the same pattern Next.js uses in app-router.tsx for MPA\n * navigations (pushRef.mpaNavigation → throw unresolvedThenable).\n */\n// for React's Suspense mechanism. Same pattern as Next.js's unresolvedThenable.\n// eslint-disable-next-line unicorn/no-thenable -- Intentionally a never-resolving thenable\nconst unresolvedThenable = { then() {} } as PromiseLike<never>;\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Root component the router renders the page through.\n *\n * Renders the TopLoader alongside the tree it is given. Neither adds a DOM\n * element on the hydration path, so the tree matches the server HTML.\n *\n * Rendered only by `createReactRoot` (client/react-root.ts): hydration passes\n * `{ element, publish: null }`, and every later render is a synchronous\n * `startTransition(() => root.render(...))` with a fresh `rendered` object.\n */\nexport function NavigationRoot({\n rendered,\n topLoaderConfig,\n}: {\n rendered: RenderedTree;\n topLoaderConfig?: TopLoaderConfig;\n}): ReactNode {\n // Publish the navigation's state when React commits its tree — not when the\n // tree is handed over. A tree React is still waiting on, or one a later\n // navigation replaces before React renders it, has been *given* to React\n // without being on screen; publishing then describes a route the user never\n // saw, which is the defect this ordering exists to prevent (TIM-1301).\n //\n // A **layout** effect, so the publish lands before the browser paints and,\n // more importantly, before every descendant's passive effect. A destination\n // component that navigates from a mount effect — a redirect guard, a\n // `refresh()` on mount — would otherwise start its navigation while the\n // segment cache, address bar and pathname still described the departing\n // route, and send an X-Timber-State-Tree for a tree that is no longer\n // mounted (codex on #998).\n //\n // Descendant *layout* effects still run first: React runs layout effects\n // child-before-parent, and the only way to precede them would be a fiber\n // rendered as an earlier sibling of the payload. That is not free here —\n // `server/ssr-wrappers.tsx` mirrors this component's fiber shape so `useId`\n // agrees across hydration, and an extra sibling shifts every id in the\n // payload subtree. A layout effect that navigates on mount is the price.\n //\n // Keyed on the tree object rather than on the effect run. A publish moves\n // the address bar, which is not idempotent, so any second invocation for the\n // same tree — an effect re-run React is entitled to perform, StrictMode's\n // double-invoke — must be a no-op rather than a second history entry.\n const publishedRef = useRef<RenderedTree | null>(null);\n useLayoutEffect(() => {\n if (publishedRef.current === rendered) return;\n publishedRef.current = rendered;\n rendered.publish?.();\n }, [rendered]);\n\n // ─── Hard navigation guard ─────────────────────────────────\n // When a hard navigation is in progress (500 error, version skew),\n // suspend forever to prevent React from rendering children during\n // page teardown. This avoids \"Rendered more hooks\" crashes in\n // CHILD components whose hook counts may shift during teardown.\n //\n // CRITICAL: This throw MUST come AFTER all hooks (the useRef and\n // useLayoutEffect above). React requires the same hooks to run on every\n // render. If we threw before hooks, React would see 0 hooks on the\n // re-render vs 2 on the initial render — triggering the exact \"Rendered\n // more hooks\" error we're trying to prevent.\n //\n // By placing it after hooks but before the return, all hooks\n // satisfy React's rules, but the thrown thenable prevents any\n // children from rendering. Same pattern as Next.js app-router.tsx\n // (pushRef.mpaNavigation — also placed after all hooks).\n if (isHardNavigating()) {\n throw unresolvedThenable;\n }\n\n // Inject TopLoader alongside the element tree. It subscribes to the router's\n // pending store itself, so it takes no props from here beyond its config,\n // and only it re-renders when a navigation starts or ends. Its slot holds\n // `null` when the loader is disabled via config.\n //\n // This Fragment is a FORK — two children — so it advances React's tree\n // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`\n // mirrors it for exactly that reason, and renders the document's default\n // <meta> tags in the first slot. The fork is unconditional so the server\n // never needs to know whether the loader is enabled: a `null` child still\n // counts toward the fork on both sides. See tests/ssr-wrapper-parity.test.ts.\n const showTopLoader = topLoaderConfig?.enabled !== false;\n return createElement(\n Fragment,\n null,\n showTopLoader ? createElement(TopLoader, { config: topLoaderConfig }) : null,\n rendered.element\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,gBAAgB,QAA8B;CAC5D,iBAAiB,MAAM;AACzB;;;;;AAMA,SAAgB,YAA4B;CAC1C,IAAI,CAAC,cACH,MAAM,IAAI,MAAM,6EAA6E;CAE/F,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAyC;CACvD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACFA,SAAgB,oBAAu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AEnC,OAAO,EAAE;AACX;;;;;;;AAQA,SAAgB,kBAAkB,OAAsB;CACtD,gBAAgB,CAAC,CAAC,QAAQ;AAC5B"}
@@ -1,4 +1,4 @@
1
- import { t as getLogger } from "./logger-YtMSKfft.js";
1
+ import { t as getLogger } from "./logger-DDLtp5e-.js";
2
2
  // src/server/abort-scope.ts
3
3
  /**
4
4
  * Abort listeners scoped to the work they guard.
@@ -35,7 +35,7 @@ function onAbortUntil(signal, onAbort, until) {
35
35
  if (until instanceof AbortSignal) scope = until;
36
36
  else {
37
37
  const ended = new AbortController();
38
- const end = () => ended.abort();
38
+ const end = () => endScope(ended);
39
39
  until.then(end, end);
40
40
  scope = ended.signal;
41
41
  }
@@ -44,6 +44,23 @@ function onAbortUntil(signal, onAbort, until) {
44
44
  signal: scope
45
45
  });
46
46
  }
47
+ /**
48
+ * The reason every scope controller aborts with. Nothing reads a scope
49
+ * signal's reason (it only removes listeners, through addEventListener's
50
+ * `signal` option), and `abort()` with no reason builds a DOMException, stack
51
+ * trace included, on every call: several per request, ~1.8% of an HTML
52
+ * request's CPU (TIM-1626).
53
+ */
54
+ var SCOPE_ENDED = Symbol("timber.scope-ended");
55
+ /**
56
+ * End a scope: abort a server-private controller whose signal only bounds
57
+ * listeners (an `onAbortUntil` `until`). Never use it on a signal anything
58
+ * reads a reason from — a render, fetch or stream would see this symbol
59
+ * instead of an AbortError.
60
+ */
61
+ function endScope(scope) {
62
+ scope.abort(SCOPE_ENDED);
63
+ }
47
64
  // src/server/render-utils.ts
48
65
  /**
49
66
  * The reason to abort a render with when its consumer releases it.
@@ -262,6 +279,6 @@ function discardResponseBody(response) {
262
279
  response.body?.cancel().catch(() => {});
263
280
  } catch {}
264
281
  }
265
- export { DEFAULT_MAX_BUFFER_BYTES as a, drainWithDeadline as c, isAbortError as d, releaseReason as f, withResponseInit as i, teeBufferExceeded as l, discardResponseBody as n, concatBytes as o, onAbortUntil as p, nodeBodyOps as r, createStreamTimingRecorder as s, NODE_BODY as t, wrapResponseWithStreamTiming as u };
282
+ export { DEFAULT_MAX_BUFFER_BYTES as a, drainWithDeadline as c, isAbortError as d, releaseReason as f, withResponseInit as i, teeBufferExceeded as l, onAbortUntil as m, discardResponseBody as n, concatBytes as o, endScope as p, nodeBodyOps as r, createStreamTimingRecorder as s, NODE_BODY as t, wrapResponseWithStreamTiming as u };
266
283
 
267
- //# sourceMappingURL=node-response-D3hXWb8y.js.map
284
+ //# sourceMappingURL=node-response-omewa8e6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-response-omewa8e6.js","names":[],"sources":["../../src/server/abort-scope.ts","../../src/server/render-utils.ts","../../src/server/stream-utils.ts","../../src/server/node-response.ts"],"sourcesContent":["/**\n * Abort listeners scoped to the work they guard.\n *\n * A request's signal outlives the render, stream, or timer that listens to\n * it, and a listener left on it keeps everything its closure holds reachable\n * from the request. In production that only delays collection until the\n * request is garbage. In dev it pins the request forever: React's dev Flight\n * server tracks every live promise in an async-hook Map whose debug chains\n * reach the request, so any promise reachable from the request is never\n * collected and never leaves that Map (TIM-1589).\n *\n * So server code never calls `signal.addEventListener('abort', …)` itself\n * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}\n * takes the end of the listener's scope as a required argument, which makes\n * a listener without a removal unwritable.\n */\n\n/**\n * Call `onAbort` if `signal` aborts before the scope `until` ends. If\n * `signal` has already aborted, `onAbort` runs now.\n *\n * `until` is the scope: a promise (the listener is removed when it fulfills\n * or rejects, a microtask later) or an `AbortSignal` (removed synchronously\n * when it aborts; use one when an abort later in the same tick must not\n * fire, as after a timeout's `cancel()`).\n */\nexport function onAbortUntil(\n signal: AbortSignal | undefined,\n onAbort: () => void,\n until: PromiseLike<unknown> | AbortSignal\n): void {\n if (!signal) return;\n if (signal.aborted) {\n onAbort();\n return;\n }\n let scope: AbortSignal;\n if (until instanceof AbortSignal) {\n scope = until;\n } else {\n const ended = new AbortController();\n const end = (): void => endScope(ended);\n until.then(end, end);\n scope = ended.signal;\n }\n // addEventListener's own `signal` option removes the listener when the\n // scope aborts: the platform's one-step removal, no handle to keep.\n signal.addEventListener('abort', onAbort, { once: true, signal: scope });\n}\n\n/**\n * The reason every scope controller aborts with. Nothing reads a scope\n * signal's reason (it only removes listeners, through addEventListener's\n * `signal` option), and `abort()` with no reason builds a DOMException, stack\n * trace included, on every call: several per request, ~1.8% of an HTML\n * request's CPU (TIM-1626).\n */\nconst SCOPE_ENDED: unique symbol = Symbol('timber.scope-ended');\n\n/**\n * End a scope: abort a server-private controller whose signal only bounds\n * listeners (an `onAbortUntil` `until`). Never use it on a signal anything\n * reads a reason from — a render, fetch or stream would see this symbol\n * instead of an AbortError.\n */\nexport function endScope(scope: AbortController): void {\n scope.abort(SCOPE_ENDED);\n}\n","/**\n * Shared render-phase utilities — used by both the Node.js and Web\n * stream wrappers. Pure functions only; no stream-shape dependencies.\n *\n * Consolidated from duplicated copies in node-stream-transforms.ts,\n * ssr-render.ts, and rsc-entry/helpers.ts. See TIM-1071 item 1.\n */\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` in csp-nonce.ts and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n\n/**\n * The reason to abort a render with when its consumer releases it.\n *\n * The framework releases a Flight render it no longer needs — the renderer\n * once a deny or redirect is captured, a tee once either branch is done —\n * usually without a reason. React then reports the abort to the render's\n * `onError` as a plain `Error(\"The render was aborted by the server without a\n * reason.\")`, which reads as an application failure: a `metadata()` that\n * denies while the page is still fetching logged an unhandled render error\n * (TIM-1597). An `AbortError` is what {@link isAbortError} already treats as\n * not-an-error. A reason the caller did pass (a timeout, the tee's divergence\n * guard) is kept, so those still reach the log.\n */\nexport function releaseReason(reason: unknown): unknown {\n return reason ?? new DOMException('The render was released by its consumer.', 'AbortError');\n}\n\n/**\n * Check if an error is an abort error (connection closed by client).\n *\n * When the browser aborts a request (page refresh, navigation away),\n * the AbortSignal fires and React/streams throw an AbortError. This\n * is not an application error — suppress it from error boundaries and logs.\n *\n * A native `ReadableStream.tee()` cancels its source with an array of both\n * branches' reasons (Streams spec, ReadableStreamDefaultTee), so a Web\n * render released through a tee is aborted with `[reason1, reason2]`. That is\n * an abort when every entry is — a tee whose branches were both released\n * ({@link releaseReason}) — and an error when any entry is, such as the\n * divergence guard's.\n */\nexport function isAbortError(error: unknown): boolean {\n if (Array.isArray(error)) return error.length > 0 && error.every(isAbortError);\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n/**\n * Inline script that adds `<meta name=\"robots\" content=\"noindex\">` to the\n * document head. Injected when a render-phase error replaces the shell so\n * search engines don't index error pages.\n *\n * MUST be byte-identical across all stream wrappers (Node and Web) for a\n * given nonce to ensure consistent Content-Length headers — which is why\n * both wrappers call this one function rather than inlining the string.\n */\nexport function noindexScript(nonce?: string): string {\n return `<script${nonceAttr(nonce)}>document.head.appendChild(Object.assign(document.createElement(\"meta\"),{name:\"robots\",content:\"noindex\"}))</script>`;\n}\n","/**\n * Stream utilities for the RSC rendering pipeline.\n *\n * teeWithErrorPropagation — wraps native ReadableStream.tee() with:\n * 1. Cross-branch error propagation (error on one branch cancels the other)\n * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)\n *\n * This prevents two classes of bugs:\n * - Silent stalls when one tee branch errors and the other hangs indefinitely\n * - Unbounded memory growth when one consumer (SSR) is much slower than the other\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\"\n */\n\nimport { getLogger } from './logger.ts';\n\n/** Default maximum buffer divergence before cancellation (5MB). */\nexport const DEFAULT_MAX_BUFFER_BYTES = 5 * 1024 * 1024;\n\nexport interface TeeOptions {\n /**\n * Maximum byte divergence between the two branches before both are\n * cancelled. When one branch has consumed this many more bytes than\n * the other, the tee's internal buffer is at least this large.\n *\n * Default: 5MB.\n */\n maxBufferBytes?: number;\n}\n\n/**\n * Tee a ReadableStream with error propagation and buffer monitoring.\n *\n * Delegates to the native `stream.tee()` for the actual forking, then wraps\n * each branch in a ReadableStream that:\n * - Tracks bytes consumed per branch\n * - Cancels both branches if byte divergence exceeds `maxBufferBytes`\n * - Cancels the other branch if either branch is cancelled or errors\n *\n * The returned streams are drop-in replacements for the native tee branches.\n */\nexport function teeWithErrorPropagation(\n stream: ReadableStream<Uint8Array>,\n options?: TeeOptions\n): [ReadableStream<Uint8Array>, ReadableStream<Uint8Array>] {\n const maxBuffer = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n const [rawBranch1, rawBranch2] = stream.tee();\n\n // Shared state for cross-branch coordination\n let consumed1 = 0;\n let consumed2 = 0;\n let cancelled = false;\n\n // Readers and controllers are assigned when wrapBranch creates the wrapped\n // streams. We store them so cancelBoth can cancel raw tee branches AND\n // error the wrapped stream controllers for cross-branch propagation.\n let rawReader1: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rawReader2: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let controller1: ReadableStreamDefaultController<Uint8Array> | undefined;\n let controller2: ReadableStreamDefaultController<Uint8Array> | undefined;\n\n /**\n * Cancel both tee branches. `initiator` is the branch index (0 or 1)\n * that triggered the cancellation — its controller is already being\n * closed/errored by the pull/cancel that triggered this, so we skip it.\n * Pass -1 to cancel+error both (e.g., from the buffer divergence guard).\n *\n * Both raw readers are always canceled regardless of initiator, because\n * the tee source stream is only released when both branches are canceled.\n * ReadableStreamDefaultReader.cancel() is idempotent, so double-cancel\n * is safe.\n */\n function cancelBoth(reason: unknown, initiator: number = -1): void {\n if (cancelled) return;\n cancelled = true;\n // Cancel both raw readers — tee source requires both branches canceled.\n rawReader1?.cancel(reason).catch(() => {});\n rawReader2?.cancel(reason).catch(() => {});\n // Error wrapped controllers so consumers see the failure.\n // Skip the initiator's controller — it's already being closed/errored.\n if (initiator !== 0) {\n try {\n controller1?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n if (initiator !== 1) {\n try {\n controller2?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n }\n\n function wrapBranch(\n branchIndex: number,\n rawBranch: ReadableStream<Uint8Array>,\n assignReader: (r: ReadableStreamDefaultReader<Uint8Array>) => void,\n assignController: (c: ReadableStreamDefaultController<Uint8Array>) => void,\n addConsumed: (n: number) => void,\n getSelfConsumed: () => number,\n getOtherConsumed: () => number\n ): ReadableStream<Uint8Array> {\n const reader = rawBranch.getReader();\n assignReader(reader);\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n assignController(controller);\n },\n\n async pull(controller) {\n if (cancelled) {\n return;\n }\n\n try {\n const { done, value } = await reader.read();\n\n // Re-check after await — cancelBoth may have fired while we\n // were waiting on the raw reader.\n if (cancelled) return;\n\n if (done) {\n try {\n controller.close();\n } catch {\n /* controller already errored by cancelBoth */\n }\n return;\n }\n\n addConsumed(value.byteLength);\n\n // Check buffer divergence: the difference in consumed bytes\n // approximates the tee's internal buffer size.\n const divergence = getSelfConsumed() - getOtherConsumed();\n if (divergence > maxBuffer) {\n cancelBoth(teeBufferExceeded(maxBuffer, divergence));\n return;\n }\n\n controller.enqueue(value);\n } catch (err) {\n if (!cancelled) {\n // Source stream errored — propagate to both branches.\n // cancelBoth with initiator skips our own controller,\n // so we error it explicitly here.\n cancelBoth(err, branchIndex);\n try {\n controller.error(err);\n } catch {\n /* already closed/errored */\n }\n }\n }\n },\n\n cancel(reason) {\n // Consumer cancelled this branch — propagate to the other\n cancelBoth(reason, branchIndex);\n },\n });\n }\n\n const wrapped1 = wrapBranch(\n 0,\n rawBranch1,\n (r) => {\n rawReader1 = r;\n },\n (c) => {\n controller1 = c;\n },\n (n) => {\n consumed1 += n;\n },\n () => consumed1,\n () => consumed2\n );\n\n const wrapped2 = wrapBranch(\n 1,\n rawBranch2,\n (r) => {\n rawReader2 = r;\n },\n (c) => {\n controller2 = c;\n },\n (n) => {\n consumed2 += n;\n },\n () => consumed2,\n () => consumed1\n );\n\n return [wrapped1, wrapped2];\n}\n\n/**\n * Stream-lifecycle timing for one response body: firstChunk, lastChunk,\n * close, maxGap (largest inter-chunk gap), chunk count, and byte count,\n * logged once when the stream terminates (clean close OR\n * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`. The\n * Web body wrapper below and the Node body (`node-body-response.ts`) feed\n * the same recorder, so the two report identically.\n */\nexport interface StreamTimingRecorder {\n chunk(byteLength: number): void;\n end(cancelled: boolean): void;\n}\n\nexport function createStreamTimingRecorder(startTime: number): StreamTimingRecorder {\n let firstChunkMs = 0;\n let lastChunkMs = 0;\n let maxGapMs = 0;\n let prevChunkTime = 0;\n let chunks = 0;\n let bytes = 0;\n let ended = false;\n\n return {\n chunk(byteLength) {\n const now = performance.now();\n const relativeMs = Math.round(now - startTime);\n if (chunks === 0) {\n firstChunkMs = relativeMs;\n } else {\n const gap = Math.round(now - prevChunkTime);\n if (gap > maxGapMs) maxGapMs = gap;\n }\n prevChunkTime = now;\n lastChunkMs = relativeMs;\n chunks++;\n bytes += byteLength;\n },\n end(cancelled) {\n if (ended) return;\n ended = true;\n const closeMs = Math.round(performance.now() - startTime);\n getLogger().debug('stream-lifecycle', {\n firstChunkMs,\n lastChunkMs,\n closeMs,\n maxGapMs,\n chunks,\n bytes,\n ...(cancelled ? { cancelled: true } : {}),\n });\n },\n };\n}\n\n/**\n * Wrap a Web response body with stream-lifecycle timing instrumentation\n * ({@link createStreamTimingRecorder}).\n *\n * Uses a manual reader pump to guarantee logging on all termination\n * paths — TransformStream.flush() is not called on cancellation.\n */\nexport function wrapResponseWithStreamTiming(\n body: ReadableStream<Uint8Array>,\n startTime: number\n): ReadableStream<Uint8Array> {\n const timing = createStreamTimingRecorder(startTime);\n const reader = body.getReader();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n timing.end(false);\n controller.close();\n return;\n }\n timing.chunk(value.byteLength);\n controller.enqueue(value);\n } catch (err) {\n timing.end(false);\n controller.error(err);\n }\n },\n\n cancel(reason) {\n timing.end(true);\n reader.cancel(reason).catch(() => {});\n },\n });\n}\n\n/** Format bytes as human-readable string (e.g., \"5.00 MB\"). */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n}\n\n/**\n * The error both tee implementations (this Web one and the Node one in\n * `flight-source-node.ts`) cancel with when one branch lags the other by more\n * than `maxBuffer` bytes. Warns once, here, so the two cannot drift.\n */\nexport function teeBufferExceeded(maxBuffer: number, divergence: number): Error {\n const error = new Error(\n `RSC stream tee buffer exceeded ${formatBytes(maxBuffer)} ` +\n `(divergence: ${formatBytes(divergence)}). ` +\n `This usually means SSR is much slower than the inline stream consumer. ` +\n `Consider reducing RSC payload size or increasing the tee buffer limit.`\n );\n console.warn(`[timber] ${error.message}`);\n return error;\n}\n\n/**\n * A pull reader over any chunk stream: a Web reader, or the Flight reader in\n * `flight-source.ts`, which reads a Node or Web Flight source.\n */\nexport interface ChunkReader<T> {\n read(): Promise<ReadableStreamReadResult<T>>;\n cancel(reason?: unknown): void;\n}\n\n/**\n * Read a chunk stream to completion under one overall deadline. Every read\n * is raced against the time remaining, and the reader is cancelled on every\n * exit, so a stalled upstream never outlives the deadline. See\n * design/02-rendering-pipeline.md §\"Always Timeout-Guard Stream Reads\".\n *\n * @param label - Prefix for the timeout error message. Both ways the deadline\n * can pass (between reads, or while a read is pending) reject with the same\n * `${label} did not complete within ${timeoutMs}ms`.\n */\nexport async function drainWithDeadline<T>(\n reader: ChunkReader<T>,\n timeoutMs: number,\n label: string\n): Promise<T[]> {\n const chunks: T[] = [];\n const deadline = Date.now() + timeoutMs;\n const deadlineError = () => new Error(`${label} did not complete within ${timeoutMs}ms`);\n try {\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw deadlineError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(deadlineError()), remaining);\n });\n let result: Awaited<ReturnType<ChunkReader<T>['read']>>;\n try {\n result = await Promise.race([reader.read(), timeout]);\n } finally {\n clearTimeout(timer);\n }\n if (result.done) return chunks;\n chunks.push(result.value);\n }\n } finally {\n reader.cancel();\n }\n}\n\n/** Concatenate byte chunks into one array. */\nexport function concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Read a byte stream to completion under one overall deadline and return\n * the concatenated bytes ({@link drainWithDeadline}). The static generator's\n * body drain uses it; Flight renders use `collectFlightBytes`\n * (`flight-source.ts`), which reads either source kind the same way.\n */\nexport async function readAllBytesWithDeadline(\n stream: ReadableStream<Uint8Array>,\n timeoutMs: number,\n label: string\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks = await drainWithDeadline(\n { read: () => reader.read(), cancel: (reason) => void reader.cancel(reason).catch(() => {}) },\n timeoutMs,\n label\n );\n return concatBytes(chunks);\n}\n","/**\n * Responses with a Node body — the platform-neutral half.\n *\n * On Node, SSR's HTML and Flight payload bodies are Node `Readable`s. They\n * travel the pipeline as a `NodeBodyResponse` (`node-body-response.ts`, Node\n * only): a real `Response` whose body stays a Node stream until the adapter\n * pipes it to the socket, so a response is never converted Node → Web → Node\n * (LOCAL-1475). srvx (nitro, the dev server) and nitro-preview's sender take\n * the Node body through `_toNodeResponse()`. Any code that reads the body\n * through the Web API still works: the response then converts once.\n *\n * Pipeline code shared with Workers re-wraps, strips, or times a response\n * through the helpers here, which ask the response itself to do the Node\n * work, so this module never imports `node:stream`. A response is recognised\n * by a `Symbol.for` brand, not `instanceof`: the RSC and SSR environments\n * load separate copies of the class.\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport type { Duplex } from 'node:stream';\n\n/** The brand a Node-body response carries, keyed by a registry symbol. */\nexport const NODE_BODY = Symbol.for('timber.response.nodeBody');\n\n/**\n * What a Node-body response can do with its body, for code that cannot import\n * the class: platform-neutral modules, and the standalone `_compress.mjs`,\n * which reaches these through the same registry symbol. Each one takes the\n * body: the response it was called on no longer has one.\n */\nexport interface NodeBodyOps {\n /**\n * Whether the response still owns a body. False for a null-body status\n * (204, 205, 304, …) and once the body was taken. Being branded says\n * nothing about this — ask here instead of reading `.body`, which would\n * convert it.\n */\n readonly hasBody: boolean;\n /** The same body under a new status and headers. */\n rewrap(init: ResponseInit): Response;\n /** Release the body unread (HEAD, a discarded document), aborting its producer. */\n discard(): void;\n /** The same body, reporting stream timing when it ends (detailed Server-Timing). */\n timed(startTime: number): Response;\n /**\n * The body piped through `stream` (gzip), as a Node-body response under\n * `init`. An error or destroy on either end tears down both.\n */\n through(stream: Duplex, init: ResponseInit): Response;\n}\n\ninterface NodeBodyBranded {\n [NODE_BODY]: NodeBodyOps;\n}\n\nfunction isNodeBodyBranded(response: Response): response is Response & NodeBodyBranded {\n return NODE_BODY in response;\n}\n\n/** The Node-body operations of `response`, or `null` for a Web-body response. */\nexport function nodeBodyOps(response: Response): NodeBodyOps | null {\n return isNodeBodyBranded(response) ? response[NODE_BODY] : null;\n}\n\n/**\n * `response`'s body under a new status and headers. A Node body moves to the\n * new response without converting; a Web body is reused as is.\n */\nexport function withResponseInit(response: Response, init: ResponseInit): Response {\n return nodeBodyOps(response)?.rewrap(init) ?? new Response(response.body, init);\n}\n\n/**\n * Release a response's body unread. A live producer (an SSR render, a Flight\n * render) is behind it; dropping the reference without this leaks it for the\n * lifetime of the render (design/13-security.md A4).\n */\nexport function discardResponseBody(response: Response): void {\n const ops = nodeBodyOps(response);\n if (ops) {\n ops.discard();\n return;\n }\n // `cancel()` rejects if the stream is already errored and throws\n // synchronously if it is locked — neither is actionable, the body is being\n // discarded either way.\n try {\n response.body?.cancel().catch(() => {});\n } catch {\n /* stream already locked or disturbed */\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aACd,QACA,SACA,OACM;CACN,IAAI,CAAC,QAAQ;CACb,IAAI,OAAO,SAAS;EAClB,QAAQ;EACR;CACF;CACA,IAAI;CACJ,IAAI,iBAAiB,aACnB,QAAQ;MACH;EACL,MAAM,QAAQ,IAAI,gBAAgB;EAClC,MAAM,YAAkB,SAAS,KAAK;EACtC,MAAM,KAAK,KAAK,GAAG;EACnB,QAAQ,MAAM;CAChB;CAGA,OAAO,iBAAiB,SAAS,SAAS;EAAE,MAAM;EAAM,QAAQ;CAAM,CAAC;AACzE;;;;;;;;AASA,IAAM,cAA6B,OAAO,oBAAoB;;;;;;;AAQ9D,SAAgB,SAAS,OAA8B;CACrD,MAAM,MAAM,WAAW;AACzB;;;;;;;;;;;;;;;AClCA,SAAgB,cAAc,QAA0B;CACtD,OAAO,UAAU,IAAI,aAAa,4CAA4C,YAAY;AAC5F;;;;;;;;;;;;;;;AAgBA,SAAgB,aAAa,OAAyB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,SAAS,KAAK,MAAM,MAAM,YAAY;CAC7E,IAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc,OAAO;CACzE,IAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc,OAAO;CAClE,OAAO;AACT;;;;;;;;;;;;;;;;ACvCA,IAAa,2BAA2B;AAsMxC,SAAgB,2BAA2B,WAAyC;CAClF,IAAI,eAAe;CACnB,IAAI,cAAc;CAClB,IAAI,WAAW;CACf,IAAI,gBAAgB;CACpB,IAAI,SAAS;CACb,IAAI,QAAQ;CACZ,IAAI,QAAQ;CAEZ,OAAO;EACL,MAAM,YAAY;GAChB,MAAM,MAAM,YAAY,IAA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OAAO,YAAY,QAAQ,CAAC,EAAE,OAAO,IAAI,KAAK,IAAI,SAAS,SAAS,MAAM,IAAI;AAChF;;;;;;AAOA,SAAgB,oBAAoB,UAA0B;CAC5D,MAAM,MAAM,YAAY,QAAQ;CAChC,IAAI,KAAK;EACP,IAAI,QAAQ;EACZ;CACF;CAIA,IAAI;EACF,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxC,QAAQ,CAER;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { n as INFERRED_RULES, t as EXPLICIT_MARKERS } from "./poison-rules-Bmz-lCPi.js";
2
- import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-_W0RWa5w.js";
2
+ import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-cmE0Gins.js";
3
3
  import { parseAst } from "vite";
4
4
  // src/analyze/poison-scan.ts
5
5
  /**
@@ -95,4 +95,4 @@ function poisoningsFor(kind, pending, signals) {
95
95
  }
96
96
  export { importSignals as n, poisoningsFor as r, collectImportSpecifiers as t };
97
97
 
98
- //# sourceMappingURL=poison-scan-CRSP06Es.js.map
98
+ //# sourceMappingURL=poison-scan-CJ9QfJWb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"poison-scan-CRSP06Es.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;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AAO;GACb;GACA,SAAS,OAAO,cAAc,gBAAgB,gBAAgB;GAC9D,aAAa,eAAe,OAAO,UAAU;EAC/C,CAAC;EAGL,KAAK,MAAM,QAAQ,gBACjB,IAAI,KAAK,gBAAgB,SAAS,GAChC,QAAQ,KAAK;GACX,MAAM,KAAK;GACX;GACA,SAAS,KAAK;GACd,aAAa,KAAK;EACpB,CAAC;CAGP;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,cACd,MACA,SACA,SACa;CACb,IAAI,WAAW,QAAQ,WAAW,GAAG,OAAO,CAAC;CAC7C,MAAM,kBACJ,SAAS,qBAAqB,SAAS,qBAAqB,SAAS;CACvE,MAAM,kBAAkB,SAAS,YAAY,SAAS,YAAY,SAAS;CAC3E,OAAO,QAAQ,QACZ,WACE,OAAO,YAAY,iBAAiB,mBACpC,OAAO,YAAY,iBAAiB,eACzC;AACF"}
1
+ {"version":3,"file":"poison-scan-CJ9QfJWb.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,wBACP,YACS;CACT,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,OAAO,WAAW,OAAO,MAAM,EAAE,eAAe,UAAU,EAAE,eAAe,MAAM;AACnF;;;;;;;AAQA,SAAgB,wBAAwB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AS,KAAK;GACd,aAAa,KAAK;EACpB,CAAC;CAGP;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,cACd,MACA,SACA,SACa;CACb,IAAI,WAAW,QAAQ,WAAW,GAAG,OAAO,CAAC;CAC7C,MAAM,kBACJ,SAAS,qBAAqB,SAAS,qBAAqB,SAAS;CACvE,MAAM,kBAAkB,SAAS,YAAY,SAAS,YAAY,SAAS;CAC3E,OAAO,QAAQ,QACZ,WACE,OAAO,YAAY,iBAAiB,mBACpC,OAAO,YAAY,iBAAiB,eACzC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"render-timeout-MrrqD1wd.js","names":[],"sources":["../../src/server/render-timeout.ts"],"sourcesContent":["/**\n * Render timeout utilities for SSR streaming pipeline.\n *\n * Provides a RenderTimeoutError class and a helper to create\n * timeout-guarded AbortSignals. Used to defend against hung RSC\n * streams and infinite SSR renders.\n *\n * Design doc: 02-rendering-pipeline.md §\"Streaming Constraints\"\n */\n\nimport { onAbortUntil } from './abort-scope.ts';\n\n/** `renderTimeoutMs` when timber.config.ts leaves it unset. */\nexport const DEFAULT_RENDER_TIMEOUT_MS = 30_000;\n\n/**\n * What `renderTimeoutMs: 0` means: a safety ceiling, never \"no timeout\" —\n * an unbounded render or singleflight wait can hang a connection or\n * deadlock a cache key forever.\n */\nexport const RENDER_TIMEOUT_CEILING_MS = 120_000;\n\n/**\n * The one mapping from configured `renderTimeoutMs` to the timeout every\n * consumer enforces. Config enters the runtime already resolved (the\n * runtime config module, static generation's options), so readers never\n * see 0 or undefined.\n */\nexport function resolveRenderTimeoutMs(configured: number | undefined): number {\n return (configured ?? DEFAULT_RENDER_TIMEOUT_MS) || RENDER_TIMEOUT_CEILING_MS;\n}\n\n/**\n * Error thrown when an SSR render or RSC stream read exceeds the\n * configured timeout. Callers can check `instanceof RenderTimeoutError`\n * to distinguish timeout from other errors and return a 504 or close\n * the connection cleanly.\n */\nexport class RenderTimeoutError extends Error {\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number, context?: string) {\n const message = context\n ? `Render timeout after ${timeoutMs}ms: ${context}`\n : `Render timeout after ${timeoutMs}ms`;\n super(message);\n this.name = 'RenderTimeoutError';\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Result of createRenderTimeout — an AbortSignal that fires after\n * the given duration, plus a cancel function to clear the timer\n * when the render completes normally.\n */\nexport interface RenderTimeout {\n /** AbortSignal that aborts after timeoutMs. */\n signal: AbortSignal;\n /** Cancel the timeout timer. Call this when the render completes. */\n cancel: () => void;\n}\n\n/**\n * Create a render timeout that aborts after the given duration.\n *\n * Returns an AbortSignal and a cancel function. The signal fires\n * with a RenderTimeoutError as the abort reason after `timeoutMs`.\n * Call `cancel()` when the render completes to prevent the timeout\n * from firing.\n *\n * If an existing `parentSignal` is provided, the returned signal\n * aborts when either the parent signal or the timeout fires —\n * whichever comes first.\n */\nexport function createRenderTimeout(timeoutMs: number, parentSignal?: AbortSignal): RenderTimeout {\n const controller = new AbortController();\n const reason = new RenderTimeoutError(timeoutMs, 'RSC stream read timed out');\n\n const timer = setTimeout(() => controller.abort(reason), timeoutMs);\n const scope = new AbortController();\n\n // The parent listener lasts until cancel() (server/abort-scope.ts).\n onAbortUntil(\n parentSignal,\n () => {\n clearTimeout(timer);\n controller.abort(parentSignal?.reason);\n },\n scope.signal\n );\n\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n scope.abort();\n },\n };\n}\n\n/**\n * Race a promise against a timeout. Rejects with RenderTimeoutError\n * if the promise does not resolve within `timeoutMs`.\n *\n * Used to guard individual `rscReader.read()` calls inside pullLoop.\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n context?: string\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new RenderTimeoutError(timeoutMs, context));\n }, timeoutMs);\n });\n\n return Promise.race([promise, timeoutPromise]).finally(() => {\n clearTimeout(timer!);\n });\n}\n"],"mappings":";;AAaA,IAAa,4BAA4B;;;;;;AAOzC,IAAa,4BAA4B;;;;;;;AAQzC,SAAgB,uBAAuB,YAAwC;CAC7E,QAAQ,cAAA,QAAA;AACV;;;;;;;AAQA,IAAa,qBAAb,cAAwC,MAAM;CAC5C;CAEA,YAAY,WAAmB,SAAkB;EAC/C,MAAM,UAAU,UACZ,wBAAwB,UAAU,MAAM,YACxC,wBAAwB,UAAU;EACtC,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;;;;;;AA0DA,SAAgB,YACd,SACA,WACA,SACY;CACZ,IAAI;CACJ,MAAM,iBAAiB,IAAI,SAAgB,UAAU,WAAW;EAC9D,QAAQ,iBAAiB;GACvB,OAAO,IAAI,mBAAmB,WAAW,OAAO,CAAC;EACnD,GAAG,SAAS;CACd,CAAC;CAED,OAAO,QAAQ,KAAK,CAAC,SAAS,cAAc,CAAC,CAAC,CAAC,cAAc;EAC3D,aAAa,KAAM;CACrB,CAAC;AACH"}
1
+ {"version":3,"file":"render-timeout-MrrqD1wd.js","names":[],"sources":["../../src/server/render-timeout.ts"],"sourcesContent":["/**\n * Render timeout utilities for SSR streaming pipeline.\n *\n * Provides a RenderTimeoutError class and a helper to create\n * timeout-guarded AbortSignals. Used to defend against hung RSC\n * streams and infinite SSR renders.\n *\n * Design doc: 02-rendering-pipeline.md §\"Streaming Constraints\"\n */\n\nimport { endScope, onAbortUntil } from './abort-scope.ts';\n\n/** `renderTimeoutMs` when timber.config.ts leaves it unset. */\nexport const DEFAULT_RENDER_TIMEOUT_MS = 30_000;\n\n/**\n * What `renderTimeoutMs: 0` means: a safety ceiling, never \"no timeout\" —\n * an unbounded render or singleflight wait can hang a connection or\n * deadlock a cache key forever.\n */\nexport const RENDER_TIMEOUT_CEILING_MS = 120_000;\n\n/**\n * The one mapping from configured `renderTimeoutMs` to the timeout every\n * consumer enforces. Config enters the runtime already resolved (the\n * runtime config module, static generation's options), so readers never\n * see 0 or undefined.\n */\nexport function resolveRenderTimeoutMs(configured: number | undefined): number {\n return (configured ?? DEFAULT_RENDER_TIMEOUT_MS) || RENDER_TIMEOUT_CEILING_MS;\n}\n\n/**\n * Error thrown when an SSR render or RSC stream read exceeds the\n * configured timeout. Callers can check `instanceof RenderTimeoutError`\n * to distinguish timeout from other errors and return a 504 or close\n * the connection cleanly.\n */\nexport class RenderTimeoutError extends Error {\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number, context?: string) {\n const message = context\n ? `Render timeout after ${timeoutMs}ms: ${context}`\n : `Render timeout after ${timeoutMs}ms`;\n super(message);\n this.name = 'RenderTimeoutError';\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Result of createRenderTimeout — an AbortSignal that fires after\n * the given duration, plus a cancel function to clear the timer\n * when the render completes normally.\n */\nexport interface RenderTimeout {\n /** AbortSignal that aborts after timeoutMs. */\n signal: AbortSignal;\n /** Cancel the timeout timer. Call this when the render completes. */\n cancel: () => void;\n}\n\n/**\n * Create a render timeout that aborts after the given duration.\n *\n * Returns an AbortSignal and a cancel function. The signal fires\n * with a RenderTimeoutError as the abort reason after `timeoutMs`.\n * Call `cancel()` when the render completes to prevent the timeout\n * from firing.\n *\n * If an existing `parentSignal` is provided, the returned signal\n * aborts when either the parent signal or the timeout fires —\n * whichever comes first.\n */\nexport function createRenderTimeout(timeoutMs: number, parentSignal?: AbortSignal): RenderTimeout {\n const controller = new AbortController();\n // The error is built when the timer fires, not up front: almost every\n // render finishes in time, and an Error captures a stack trace.\n const timer = setTimeout(\n () => controller.abort(new RenderTimeoutError(timeoutMs, 'RSC stream read timed out')),\n timeoutMs\n );\n const scope = new AbortController();\n\n // The parent listener lasts until cancel() (server/abort-scope.ts).\n onAbortUntil(\n parentSignal,\n () => {\n clearTimeout(timer);\n controller.abort(parentSignal?.reason);\n },\n scope.signal\n );\n\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n endScope(scope);\n },\n };\n}\n\n/**\n * Race a promise against a timeout. Rejects with RenderTimeoutError\n * if the promise does not resolve within `timeoutMs`.\n *\n * Used to guard individual `rscReader.read()` calls inside pullLoop.\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n context?: string\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new RenderTimeoutError(timeoutMs, context));\n }, timeoutMs);\n });\n\n return Promise.race([promise, timeoutPromise]).finally(() => {\n clearTimeout(timer!);\n });\n}\n"],"mappings":";;AAaA,IAAa,4BAA4B;;;;;;AAOzC,IAAa,4BAA4B;;;;;;;AAQzC,SAAgB,uBAAuB,YAAwC;CAC7E,QAAQ,cAAA,QAAA;AACV;;;;;;;AAQA,IAAa,qBAAb,cAAwC,MAAM;CAC5C;CAEA,YAAY,WAAmB,SAAkB;EAC/C,MAAM,UAAU,UACZ,wBAAwB,UAAU,MAAM,YACxC,wBAAwB,UAAU;EACtC,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;;;;;;AA6DA,SAAgB,YACd,SACA,WACA,SACY;CACZ,IAAI;CACJ,MAAM,iBAAiB,IAAI,SAAgB,UAAU,WAAW;EAC9D,QAAQ,iBAAiB;GACvB,OAAO,IAAI,mBAAmB,WAAW,OAAO,CAAC;EACnD,GAAG,SAAS;CACd,CAAC;CAED,OAAO,QAAQ,KAAK,CAAC,SAAS,cAAc,CAAC,CAAC,CAAC,cAAc;EAC3D,aAAa,KAAM;CACrB,CAAC;AACH"}
@@ -1,9 +1,9 @@
1
- import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-BL26HCDd.js";
2
- import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
3
- import { t as matchUrlParts } from "./tree-match-Bqdr9szG.js";
4
1
  import { i as DEFAULT_PAGE_EXTENSIONS, n as classifyUrlSegment, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
5
2
  import { n as treePathDepth, t as computeSegmentTreePaths } from "./segment-keys-Y60KNc8C.js";
6
- import { b as swallow } from "./logger-YtMSKfft.js";
3
+ import { t as matchUrlParts } from "./tree-match-Bqdr9szG.js";
4
+ import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-BL26HCDd.js";
5
+ import { b as swallow } from "./logger-DDLtp5e-.js";
6
+ import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
7
7
  import { parseAst } from "vite";
8
8
  import { basename, extname, join } from "node:path";
9
9
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -2045,4 +2045,4 @@ function findScriptExtFile(dirPath, name) {
2045
2045
  }
2046
2046
  export { fileHasDefaultExport as a, getCsrfExport as c, collectInterceptionRewrites as d, fileHasAnyExport as i, getPrerenderExport as l, scanRoutes as n, fileHasDirective as o, fileDefaultExportIsLocalValue as r, fileHasStarExport as s, isRouteConventionFile as t, readFileCached as u };
2047
2047
 
2048
- //# sourceMappingURL=scanner-BNQ4qnLX.js.map
2048
+ //# sourceMappingURL=scanner-CrB_h6FA.js.map