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

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 (408) hide show
  1. package/dist/_chunks/{actions-DIgnvDrG.js → actions-BkwgRwCl.js} +146 -12
  2. package/dist/_chunks/actions-BkwgRwCl.js.map +1 -0
  3. package/dist/_chunks/{als-registry-PPYstxK0.js → als-registry-C-iwbtvI.js} +4 -3
  4. package/dist/_chunks/{als-registry-PPYstxK0.js.map → als-registry-C-iwbtvI.js.map} +1 -1
  5. package/dist/_chunks/{als-slots-kbQrHTzm.js → als-slots-CVTF-AMz.js} +3 -3
  6. package/dist/_chunks/als-slots-CVTF-AMz.js.map +1 -0
  7. package/dist/_chunks/{cache-api-uWQwuxWb.js → cache-api-BGA7c5qJ.js} +5 -5
  8. package/dist/_chunks/{cache-api-uWQwuxWb.js.map → cache-api-BGA7c5qJ.js.map} +1 -1
  9. package/dist/_chunks/{chains-C7CExrUI.js → chains-Cuwwjv6T.js} +2 -2
  10. package/dist/_chunks/{chains-C7CExrUI.js.map → chains-Cuwwjv6T.js.map} +1 -1
  11. package/dist/_chunks/chains-LGjBHfSN.js +1 -0
  12. package/dist/_chunks/{classify-Cj9EeZoL.js → classify-Y8S9C0Na.js} +2 -2
  13. package/dist/_chunks/{classify-Cj9EeZoL.js.map → classify-Y8S9C0Na.js.map} +1 -1
  14. package/dist/_chunks/{cli-check-C3QOAru7.js → cli-check-KeE1QaIx.js} +7 -6
  15. package/dist/_chunks/cli-check-KeE1QaIx.js.map +1 -0
  16. package/dist/_chunks/{cli-schema-sync-DQUS_o3V.js → cli-schema-sync-DZEF31wd.js} +2 -2
  17. package/dist/_chunks/{cli-schema-sync-DQUS_o3V.js.map → cli-schema-sync-DZEF31wd.js.map} +1 -1
  18. package/dist/_chunks/{cli-schema-sync-BRxZz66D.js → cli-schema-sync-_y5O6MIg.js} +1 -1
  19. package/dist/_chunks/{client-dep-entries-ZETBdLgv.js → client-dep-entries-DpiwvoDi.js} +2 -2
  20. package/dist/_chunks/{client-dep-entries-ZETBdLgv.js.map → client-dep-entries-DpiwvoDi.js.map} +1 -1
  21. package/dist/_chunks/{cloudflare-Dk5Hqo-O.js → cloudflare-9dbhVOxS.js} +2 -2
  22. package/dist/_chunks/{cloudflare-Dk5Hqo-O.js.map → cloudflare-9dbhVOxS.js.map} +1 -1
  23. package/dist/_chunks/{convention-lint-BoVISNS6.js → convention-lint-0AEsPK2T.js} +378 -10
  24. package/dist/_chunks/convention-lint-0AEsPK2T.js.map +1 -0
  25. package/dist/_chunks/dev-server-CboXr8zX.js +1 -0
  26. package/dist/_chunks/{dev-server-C5R6jx8Q.js → dev-server-DYDr8KIc.js} +9 -3
  27. package/dist/_chunks/dev-server-DYDr8KIc.js.map +1 -0
  28. package/dist/_chunks/{dist-C1Rjlo6s.js → dist-GyaJm4GA.js} +18 -2
  29. package/dist/_chunks/dist-GyaJm4GA.js.map +1 -0
  30. package/dist/_chunks/{error-boundary-DB51f9ih.js → error-boundary-wuNvAJ4n.js} +11 -14
  31. package/dist/_chunks/error-boundary-wuNvAJ4n.js.map +1 -0
  32. package/dist/_chunks/{flight-source-node-D9cHBhjP.js → flight-source-node-KQsX_OhS.js} +4 -7
  33. package/dist/_chunks/flight-source-node-KQsX_OhS.js.map +1 -0
  34. package/dist/_chunks/{json-lossy-check-Y1GxqVX_.js → json-lossy-check-BVDALqMf.js} +2 -2
  35. package/dist/_chunks/{json-lossy-check-Y1GxqVX_.js.map → json-lossy-check-BVDALqMf.js.map} +1 -1
  36. package/dist/_chunks/key-headers-uIig1_mU.js +40 -0
  37. package/dist/_chunks/key-headers-uIig1_mU.js.map +1 -0
  38. package/dist/_chunks/{live-graph-BDQWvnMm.js → live-graph-VhzO7Ol9.js} +4 -4
  39. package/dist/_chunks/{live-graph-BDQWvnMm.js.map → live-graph-VhzO7Ol9.js.map} +1 -1
  40. package/dist/_chunks/{logger-DmRR9tmZ.js → logger-C4m8rfMy.js} +2 -2
  41. package/dist/_chunks/{logger-DmRR9tmZ.js.map → logger-C4m8rfMy.js.map} +1 -1
  42. package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -1
  43. package/dist/_chunks/{node-response-yp8zdyRp.js → node-response-8Vz29cGS.js} +2 -2
  44. package/dist/_chunks/{node-response-yp8zdyRp.js.map → node-response-8Vz29cGS.js.map} +1 -1
  45. package/dist/_chunks/{poison-scan-WQgUydF_.js → poison-scan-Dpl3ibG-.js} +2 -2
  46. package/dist/_chunks/{poison-scan-WQgUydF_.js.map → poison-scan-Dpl3ibG-.js.map} +1 -1
  47. package/dist/_chunks/{rsc-cache-key-D0cb0Gmc.js → rsc-cache-key-BGvUtMtN.js} +40 -4
  48. package/dist/_chunks/{rsc-cache-key-D0cb0Gmc.js.map → rsc-cache-key-BGvUtMtN.js.map} +1 -1
  49. package/dist/_chunks/{scanner-C9Lrf77z.js → scanner-CCEHN9Jg.js} +14 -81
  50. package/dist/_chunks/scanner-CCEHN9Jg.js.map +1 -0
  51. package/dist/_chunks/{sizeof-BISkSaU0.js → sizeof-CIF7fwSJ.js} +2 -2
  52. package/dist/_chunks/{sizeof-BISkSaU0.js.map → sizeof-CIF7fwSJ.js.map} +1 -1
  53. package/dist/_chunks/{walkers-Bxv4v7tX.js → walkers-BbotBhNG.js} +3 -3
  54. package/dist/_chunks/{walkers-Bxv4v7tX.js.map → walkers-BbotBhNG.js.map} +1 -1
  55. package/dist/adapters/cloudflare-dev.js +1 -1
  56. package/dist/adapters/cloudflare-kv-cache.js +2 -2
  57. package/dist/adapters/cloudflare.js +1 -1
  58. package/dist/analyze/crawl-entry.js +3 -3
  59. package/dist/analyze/graph-command.js +2 -2
  60. package/dist/cache/index.js +2 -2
  61. package/dist/cache/stores/memory.js +1 -1
  62. package/dist/cdn/workers-cache-purge.js +1 -1
  63. package/dist/cli-check.d.ts +3 -0
  64. package/dist/cli-check.d.ts.map +1 -1
  65. package/dist/cli.js +3 -3
  66. package/dist/client/browser-entry/router-init.d.ts +0 -1
  67. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  68. package/dist/client/error-boundary.js +1 -1
  69. package/dist/client/index.js +2 -2
  70. package/dist/client/index.js.map +1 -1
  71. package/dist/client/internal.js +4 -5
  72. package/dist/client/internal.js.map +1 -1
  73. package/dist/client/navigation-commit.d.ts +3 -5
  74. package/dist/client/navigation-commit.d.ts.map +1 -1
  75. package/dist/client/outlet-content-cache.d.ts +25 -30
  76. package/dist/client/outlet-content-cache.d.ts.map +1 -1
  77. package/dist/client/outlet-scope-context.d.ts +4 -4
  78. package/dist/client/outlet-scope-context.d.ts.map +1 -1
  79. package/dist/client/params-context.d.ts +1 -1
  80. package/dist/client/router-types.d.ts +3 -13
  81. package/dist/client/router-types.d.ts.map +1 -1
  82. package/dist/client/router.d.ts.map +1 -1
  83. package/dist/client/segment-cache.d.ts +2 -2
  84. package/dist/client/segment-outlet.d.ts +12 -13
  85. package/dist/client/segment-outlet.d.ts.map +1 -1
  86. package/dist/client/stale-segment.d.ts +2 -2
  87. package/dist/config-types.d.ts +22 -15
  88. package/dist/config-types.d.ts.map +1 -1
  89. package/dist/config-validation.d.ts.map +1 -1
  90. package/dist/cookies/define-cookie.d.ts.map +1 -1
  91. package/dist/cookies/index.js +5 -2
  92. package/dist/cookies/index.js.map +1 -1
  93. package/dist/index.d.ts +1 -0
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +109 -26
  96. package/dist/index.js.map +1 -1
  97. package/dist/native/rsc/cookies/define-cookie.js +6 -2
  98. package/dist/native/rsc/cookies/define-cookie.js.map +1 -1
  99. package/dist/native/rsc/manifest.json +12 -4
  100. package/dist/native/rsc/routing/segment-keys.js +11 -1
  101. package/dist/native/rsc/routing/segment-keys.js.map +1 -1
  102. package/dist/native/rsc/search-params/define.js +4 -1
  103. package/dist/native/rsc/search-params/define.js.map +1 -1
  104. package/dist/native/rsc/server/als-registry.js +2 -2
  105. package/dist/native/rsc/server/als-registry.js.map +1 -1
  106. package/dist/native/rsc/server/client-state-tree.js +13 -12
  107. package/dist/native/rsc/server/client-state-tree.js.map +1 -1
  108. package/dist/native/rsc/server/cookie-context.js +12 -0
  109. package/dist/native/rsc/server/cookie-context.js.map +1 -1
  110. package/dist/native/rsc/server/flight-source-node.js +2 -5
  111. package/dist/native/rsc/server/flight-source-node.js.map +1 -1
  112. package/dist/native/rsc/server/flight-source.js +8 -40
  113. package/dist/native/rsc/server/flight-source.js.map +1 -1
  114. package/dist/native/rsc/server/framework-stack-frames.js +18 -0
  115. package/dist/native/rsc/server/framework-stack-frames.js.map +1 -0
  116. package/dist/native/rsc/server/prebuilt-builder.js +15 -1
  117. package/dist/native/rsc/server/prebuilt-builder.js.map +1 -1
  118. package/dist/native/rsc/server/request-context.js +11 -5
  119. package/dist/native/rsc/server/request-context.js.map +1 -1
  120. package/dist/native/rsc/server/route-element-builder.js +29 -11
  121. package/dist/native/rsc/server/route-element-builder.js.map +1 -1
  122. package/dist/native/rsc/server/route-module-loader.js +14 -6
  123. package/dist/native/rsc/server/route-module-loader.js.map +1 -1
  124. package/dist/native/rsc/server/rsc-cache-key-guard.js +5 -1
  125. package/dist/native/rsc/server/rsc-cache-key-guard.js.map +1 -1
  126. package/dist/native/rsc/server/rsc-entry/render-route.js +10 -29
  127. package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
  128. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +7 -2
  129. package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js.map +1 -1
  130. package/dist/native/rsc/server/rsc-entry/rsc-stream.js +2 -5
  131. package/dist/native/rsc/server/rsc-entry/rsc-stream.js.map +1 -1
  132. package/dist/native/rsc/server/segment-lifetime/document-outlet.js +24 -0
  133. package/dist/native/rsc/server/segment-lifetime/document-outlet.js.map +1 -0
  134. package/dist/native/rsc/server/segment-lifetime/key-digest.js +74 -0
  135. package/dist/native/rsc/server/segment-lifetime/key-digest.js.map +1 -0
  136. package/dist/native/rsc/server/segment-lifetime/outlet-gate.js +44 -0
  137. package/dist/native/rsc/server/segment-lifetime/outlet-gate.js.map +1 -0
  138. package/dist/native/rsc/server/segment-lifetime/read-rule.js +78 -0
  139. package/dist/native/rsc/server/segment-lifetime/read-rule.js.map +1 -0
  140. package/dist/native/rsc/server/segment-lifetime/read-scope.js +41 -0
  141. package/dist/native/rsc/server/segment-lifetime/read-scope.js.map +1 -0
  142. package/dist/native/rsc/server/segment-lifetime/segment-key.js +64 -0
  143. package/dist/native/rsc/server/segment-lifetime/segment-key.js.map +1 -0
  144. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js +72 -0
  145. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js.map +1 -0
  146. package/dist/native/rsc/server/slot-resolver.js +51 -27
  147. package/dist/native/rsc/server/slot-resolver.js.map +1 -1
  148. package/dist/native/rsc/server/slot-subtree-contain.js +17 -89
  149. package/dist/native/rsc/server/slot-subtree-contain.js.map +1 -1
  150. package/dist/native/rsc/server/subtree-walk.js +140 -0
  151. package/dist/native/rsc/server/subtree-walk.js.map +1 -0
  152. package/dist/native/rsc/server/vite-handoff-rsc.js.map +1 -1
  153. package/dist/native/rsc/shared/als-slots.js +2 -2
  154. package/dist/native/rsc/shared/als-slots.js.map +1 -1
  155. package/dist/native/rsc/shared/cookie-read-through.js +5 -0
  156. package/dist/native/rsc/shared/cookie-read-through.js.map +1 -0
  157. package/dist/native/rsc/shared/key-headers.js +20 -0
  158. package/dist/native/rsc/shared/key-headers.js.map +1 -0
  159. package/dist/native/rsc/shared/outlet-decision.js.map +1 -1
  160. package/dist/native/rsc/shared/route-options-export.js +8 -0
  161. package/dist/native/rsc/shared/route-options-export.js.map +1 -0
  162. package/dist/native/rsc/shared/rsc-cache-key.js +19 -3
  163. package/dist/native/rsc/shared/rsc-cache-key.js.map +1 -1
  164. package/dist/native/rsc/shims/headers.js +3 -4
  165. package/dist/native/rsc/shims/headers.js.map +1 -1
  166. package/dist/native/ssr/client/outlet-content-cache.js +12 -18
  167. package/dist/native/ssr/client/outlet-content-cache.js.map +1 -1
  168. package/dist/native/ssr/client/outlet-scope-context.js.map +1 -1
  169. package/dist/native/ssr/client/segment-outlet.js +6 -19
  170. package/dist/native/ssr/client/segment-outlet.js.map +1 -1
  171. package/dist/native/ssr/cookies/define-cookie.js +6 -2
  172. package/dist/native/ssr/cookies/define-cookie.js.map +1 -1
  173. package/dist/native/ssr/manifest.json +5 -1
  174. package/dist/native/ssr/search-params/define.js +4 -1
  175. package/dist/native/ssr/search-params/define.js.map +1 -1
  176. package/dist/native/ssr/server/als-registry.js +2 -2
  177. package/dist/native/ssr/server/als-registry.js.map +1 -1
  178. package/dist/native/ssr/server/client-state-tree.js +13 -12
  179. package/dist/native/ssr/server/client-state-tree.js.map +1 -1
  180. package/dist/native/ssr/server/cookie-context.js +12 -0
  181. package/dist/native/ssr/server/cookie-context.js.map +1 -1
  182. package/dist/native/ssr/server/flight-source-node.js +2 -5
  183. package/dist/native/ssr/server/flight-source-node.js.map +1 -1
  184. package/dist/native/ssr/server/flight-source.js +1 -1
  185. package/dist/native/ssr/server/flight-source.js.map +1 -1
  186. package/dist/native/ssr/server/framework-stack-frames.js +18 -0
  187. package/dist/native/ssr/server/framework-stack-frames.js.map +1 -0
  188. package/dist/native/ssr/server/request-context.js +11 -5
  189. package/dist/native/ssr/server/request-context.js.map +1 -1
  190. package/dist/native/ssr/server/rsc-cache-key-guard.js +5 -1
  191. package/dist/native/ssr/server/rsc-cache-key-guard.js.map +1 -1
  192. package/dist/native/ssr/server/segment-lifetime/key-digest.js +6 -0
  193. package/dist/native/ssr/server/segment-lifetime/key-digest.js.map +1 -0
  194. package/dist/native/ssr/server/segment-lifetime/read-rule.js +78 -0
  195. package/dist/native/ssr/server/segment-lifetime/read-rule.js.map +1 -0
  196. package/dist/native/ssr/server/vite-handoff-rsc.js.map +1 -1
  197. package/dist/native/ssr/shared/als-slots.js +2 -2
  198. package/dist/native/ssr/shared/als-slots.js.map +1 -1
  199. package/dist/native/ssr/shared/cookie-read-through.js +5 -0
  200. package/dist/native/ssr/shared/cookie-read-through.js.map +1 -0
  201. package/dist/native/ssr/shared/key-headers.js +13 -0
  202. package/dist/native/ssr/shared/key-headers.js.map +1 -0
  203. package/dist/native/ssr/shared/rsc-cache-key.js +19 -3
  204. package/dist/native/ssr/shared/rsc-cache-key.js.map +1 -1
  205. package/dist/native/ssr/shims/headers.js +3 -4
  206. package/dist/native/ssr/shims/headers.js.map +1 -1
  207. package/dist/plugins/callsite-jsx.d.ts +8 -1
  208. package/dist/plugins/callsite-jsx.d.ts.map +1 -1
  209. package/dist/plugins/entries.d.ts.map +1 -1
  210. package/dist/plugins/prerender-sugar.d.ts +9 -8
  211. package/dist/plugins/prerender-sugar.d.ts.map +1 -1
  212. package/dist/plugins/routing.d.ts.map +1 -1
  213. package/dist/routing/convention-lint.d.ts +11 -3
  214. package/dist/routing/convention-lint.d.ts.map +1 -1
  215. package/dist/routing/export-detect.d.ts +50 -23
  216. package/dist/routing/export-detect.d.ts.map +1 -1
  217. package/dist/routing/index.js +2 -2
  218. package/dist/routing/route-options-lint.d.ts +36 -0
  219. package/dist/routing/route-options-lint.d.ts.map +1 -0
  220. package/dist/routing/route-options.d.ts +55 -0
  221. package/dist/routing/route-options.d.ts.map +1 -0
  222. package/dist/routing/segment-keys.d.ts +38 -4
  223. package/dist/routing/segment-keys.d.ts.map +1 -1
  224. package/dist/search-params/index.js +5 -2
  225. package/dist/search-params/index.js.map +1 -1
  226. package/dist/server/als-registry.d.ts +22 -13
  227. package/dist/server/als-registry.d.ts.map +1 -1
  228. package/dist/server/client-state-tree.d.ts +11 -10
  229. package/dist/server/client-state-tree.d.ts.map +1 -1
  230. package/dist/server/cookie-context.d.ts +3 -0
  231. package/dist/server/cookie-context.d.ts.map +1 -1
  232. package/dist/server/flight-source-node.d.ts +1 -6
  233. package/dist/server/flight-source-node.d.ts.map +1 -1
  234. package/dist/server/flight-source.d.ts +4 -28
  235. package/dist/server/flight-source.d.ts.map +1 -1
  236. package/dist/server/framework-stack-frames.d.ts +20 -0
  237. package/dist/server/framework-stack-frames.d.ts.map +1 -0
  238. package/dist/server/index.d.ts +1 -0
  239. package/dist/server/index.d.ts.map +1 -1
  240. package/dist/server/index.js +2 -2
  241. package/dist/server/internal.js +102 -28
  242. package/dist/server/internal.js.map +1 -1
  243. package/dist/server/prebuilt/capture-routes.d.ts +1 -1
  244. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  245. package/dist/server/request-context.d.ts +6 -1
  246. package/dist/server/request-context.d.ts.map +1 -1
  247. package/dist/server/route-element-builder.d.ts +2 -2
  248. package/dist/server/route-element-builder.d.ts.map +1 -1
  249. package/dist/server/route-module-loader.d.ts +10 -2
  250. package/dist/server/route-module-loader.d.ts.map +1 -1
  251. package/dist/server/rsc-cache-key-guard.d.ts +3 -1
  252. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -1
  253. package/dist/server/rsc-entry/helpers.d.ts +1 -1
  254. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  255. package/dist/server/rsc-entry/render-route.d.ts +10 -1
  256. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  257. package/dist/server/rsc-entry/revalidate-renderer.d.ts +12 -0
  258. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -1
  259. package/dist/server/rsc-entry/rsc-stream.d.ts +2 -11
  260. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  261. package/dist/server/segment-lifetime/document-outlet.d.ts +66 -0
  262. package/dist/server/segment-lifetime/document-outlet.d.ts.map +1 -0
  263. package/dist/server/segment-lifetime/key-digest.d.ts +46 -0
  264. package/dist/server/segment-lifetime/key-digest.d.ts.map +1 -0
  265. package/dist/server/segment-lifetime/outlet-gate.d.ts +58 -0
  266. package/dist/server/segment-lifetime/outlet-gate.d.ts.map +1 -0
  267. package/dist/server/segment-lifetime/read-rule.d.ts +53 -0
  268. package/dist/server/segment-lifetime/read-rule.d.ts.map +1 -0
  269. package/dist/server/segment-lifetime/read-scope.d.ts +40 -0
  270. package/dist/server/segment-lifetime/read-scope.d.ts.map +1 -0
  271. package/dist/server/segment-lifetime/segment-key.d.ts +63 -0
  272. package/dist/server/segment-lifetime/segment-key.d.ts.map +1 -0
  273. package/dist/server/segment-lifetime/slot-outlets.d.ts +81 -0
  274. package/dist/server/segment-lifetime/slot-outlets.d.ts.map +1 -0
  275. package/dist/server/slot-resolver.d.ts +10 -5
  276. package/dist/server/slot-resolver.d.ts.map +1 -1
  277. package/dist/server/slot-subtree-contain.d.ts +2 -6
  278. package/dist/server/slot-subtree-contain.d.ts.map +1 -1
  279. package/dist/server/subtree-walk.d.ts +56 -0
  280. package/dist/server/subtree-walk.d.ts.map +1 -0
  281. package/dist/server/types.d.ts +75 -0
  282. package/dist/server/types.d.ts.map +1 -1
  283. package/dist/server/vite-handoff-rsc.d.ts +1 -10
  284. package/dist/server/vite-handoff-rsc.d.ts.map +1 -1
  285. package/dist/shared/als-slots.d.ts +12 -2
  286. package/dist/shared/als-slots.d.ts.map +1 -1
  287. package/dist/shared/cookie-read-through.d.ts +18 -0
  288. package/dist/shared/cookie-read-through.d.ts.map +1 -0
  289. package/dist/shared/key-headers.d.ts +13 -0
  290. package/dist/shared/key-headers.d.ts.map +1 -0
  291. package/dist/shared/outlet-decision.d.ts +16 -28
  292. package/dist/shared/outlet-decision.d.ts.map +1 -1
  293. package/dist/shared/payload-root.d.ts +1 -1
  294. package/dist/shared/route-options-export.d.ts +13 -0
  295. package/dist/shared/route-options-export.d.ts.map +1 -0
  296. package/dist/shared/rsc-cache-key.d.ts +22 -0
  297. package/dist/shared/rsc-cache-key.d.ts.map +1 -1
  298. package/dist/shared/segment-info.d.ts +7 -5
  299. package/dist/shared/segment-info.d.ts.map +1 -1
  300. package/dist/shims/headers.d.ts.map +1 -1
  301. package/docs/api/30-api-server.mdx +29 -0
  302. package/docs/api/32-api-cache.mdx +10 -4
  303. package/docs/api/34-api-config.mdx +5 -0
  304. package/docs/learn/09-streaming.mdx +6 -2
  305. package/docs/learn/10-caching.mdx +10 -4
  306. package/package.json +1 -1
  307. package/src/cli-check.ts +11 -3
  308. package/src/client/browser-entry/index.ts +0 -2
  309. package/src/client/browser-entry/router-init.ts +2 -4
  310. package/src/client/error-boundary.tsx +1 -1
  311. package/src/client/navigation-commit.ts +9 -14
  312. package/src/client/outlet-content-cache.ts +36 -42
  313. package/src/client/outlet-scope-context.ts +5 -5
  314. package/src/client/params-context.ts +1 -1
  315. package/src/client/router-types.ts +3 -14
  316. package/src/client/router.ts +1 -2
  317. package/src/client/rsc-fetch.ts +1 -1
  318. package/src/client/segment-cache.ts +2 -2
  319. package/src/client/segment-outlet.tsx +19 -45
  320. package/src/client/stale-segment.ts +2 -2
  321. package/src/config-types.ts +23 -15
  322. package/src/config-validation.ts +17 -1
  323. package/src/cookies/define-cookie.ts +5 -1
  324. package/src/index.ts +2 -1
  325. package/src/plugins/callsite-jsx.ts +104 -6
  326. package/src/plugins/entries.ts +3 -1
  327. package/src/plugins/prerender-sugar.ts +34 -18
  328. package/src/plugins/routing.ts +3 -1
  329. package/src/routing/convention-lint.ts +18 -7
  330. package/src/routing/export-detect.ts +14 -117
  331. package/src/routing/route-options-lint.ts +153 -0
  332. package/src/routing/route-options.ts +439 -0
  333. package/src/routing/scanner.ts +1 -1
  334. package/src/routing/segment-keys.ts +53 -4
  335. package/src/rsc-runtime/vendor-types.d.ts +5 -1
  336. package/src/search-params/define.ts +1 -1
  337. package/src/server/als-registry.ts +25 -17
  338. package/src/server/client-state-tree.ts +30 -27
  339. package/src/server/cookie-context.ts +17 -0
  340. package/src/server/flight-source-node.ts +1 -5
  341. package/src/server/flight-source.ts +8 -82
  342. package/src/server/framework-stack-frames.ts +41 -0
  343. package/src/server/index.ts +7 -0
  344. package/src/server/prebuilt/capture-routes.ts +1 -1
  345. package/src/server/prebuilt-builder.ts +30 -2
  346. package/src/server/request-context.ts +31 -6
  347. package/src/server/route-element-builder.ts +92 -18
  348. package/src/server/route-module-loader.ts +43 -10
  349. package/src/server/rsc-cache-key-guard.ts +17 -2
  350. package/src/server/rsc-entry/helpers.ts +1 -1
  351. package/src/server/rsc-entry/index.ts +16 -3
  352. package/src/server/rsc-entry/render-route.ts +22 -51
  353. package/src/server/rsc-entry/revalidate-renderer.ts +16 -2
  354. package/src/server/rsc-entry/rsc-stream.ts +3 -23
  355. package/src/server/segment-lifetime/document-outlet.ts +98 -0
  356. package/src/server/segment-lifetime/key-digest.ts +139 -0
  357. package/src/server/segment-lifetime/outlet-gate.ts +102 -0
  358. package/src/server/segment-lifetime/read-rule.ts +193 -0
  359. package/src/server/segment-lifetime/read-scope.ts +101 -0
  360. package/src/server/segment-lifetime/segment-key.ts +168 -0
  361. package/src/server/segment-lifetime/slot-outlets.ts +180 -0
  362. package/src/server/slot-resolver.ts +103 -60
  363. package/src/server/slot-subtree-contain.ts +35 -182
  364. package/src/server/subtree-walk.ts +316 -0
  365. package/src/server/types.ts +91 -0
  366. package/src/server/vite-handoff-rsc.ts +1 -12
  367. package/src/shared/als-slots.ts +19 -8
  368. package/src/shared/cookie-read-through.ts +18 -0
  369. package/src/shared/key-headers.ts +42 -0
  370. package/src/shared/outlet-decision.ts +16 -30
  371. package/src/shared/payload-root.ts +1 -1
  372. package/src/shared/route-options-export.ts +14 -0
  373. package/src/shared/rsc-cache-key.ts +41 -2
  374. package/src/shared/segment-info.ts +7 -5
  375. package/src/shims/headers.ts +5 -4
  376. package/dist/_chunks/actions-DIgnvDrG.js.map +0 -1
  377. package/dist/_chunks/als-slots-kbQrHTzm.js.map +0 -1
  378. package/dist/_chunks/chains-CSslTUdI.js +0 -1
  379. package/dist/_chunks/cli-check-C3QOAru7.js.map +0 -1
  380. package/dist/_chunks/convention-lint-BoVISNS6.js.map +0 -1
  381. package/dist/_chunks/dev-server-B8roKA3Q.js +0 -1
  382. package/dist/_chunks/dev-server-C5R6jx8Q.js.map +0 -1
  383. package/dist/_chunks/dist-C1Rjlo6s.js.map +0 -1
  384. package/dist/_chunks/error-boundary-DB51f9ih.js.map +0 -1
  385. package/dist/_chunks/flight-source-node-D9cHBhjP.js.map +0 -1
  386. package/dist/_chunks/scanner-C9Lrf77z.js.map +0 -1
  387. package/dist/native/rsc/server/segment-hash/capture.js +0 -107
  388. package/dist/native/rsc/server/segment-hash/capture.js.map +0 -1
  389. package/dist/native/rsc/server/segment-hash/outlet.js +0 -81
  390. package/dist/native/rsc/server/segment-hash/outlet.js.map +0 -1
  391. package/dist/native/rsc/server/segment-hash/stream-tap.js +0 -139
  392. package/dist/native/rsc/server/segment-hash/stream-tap.js.map +0 -1
  393. package/dist/native/rsc/server/segment-hash/value-hash.js +0 -171
  394. package/dist/native/rsc/server/segment-hash/value-hash.js.map +0 -1
  395. package/dist/native/ssr/server/segment-hash/value-hash.js +0 -162
  396. package/dist/native/ssr/server/segment-hash/value-hash.js.map +0 -1
  397. package/dist/server/segment-hash/capture.d.ts +0 -77
  398. package/dist/server/segment-hash/capture.d.ts.map +0 -1
  399. package/dist/server/segment-hash/outlet.d.ts +0 -65
  400. package/dist/server/segment-hash/outlet.d.ts.map +0 -1
  401. package/dist/server/segment-hash/stream-tap.d.ts +0 -49
  402. package/dist/server/segment-hash/stream-tap.d.ts.map +0 -1
  403. package/dist/server/segment-hash/value-hash.d.ts +0 -70
  404. package/dist/server/segment-hash/value-hash.d.ts.map +0 -1
  405. package/src/server/segment-hash/capture.ts +0 -232
  406. package/src/server/segment-hash/outlet.ts +0 -185
  407. package/src/server/segment-hash/stream-tap.ts +0 -244
  408. package/src/server/segment-hash/value-hash.ts +0 -338
@@ -1 +1 @@
1
- {"version":3,"file":"metadata-routes-MXNjWOt5.js","names":[],"sources":["../../src/routing/segment-keys.ts","../../src/server/metadata-routes.ts"],"sourcesContent":["/**\n * Segment key computation — the stable identity of a segment in the route tree.\n *\n * A segment key is the string that names a segment across the RSC/SSR/client\n * boundary: it appears in the X-Timber-State-Tree header, the X-Timber-Segments\n * header, SegmentOutlet props, the client segment cache, and (since TIM-1279)\n * interception scoping.\n *\n * This module lives in `routing/` rather than `server/` because the keys are a\n * property of the route tree itself — both the build-time scanner tree and the\n * runtime manifest tree produce identical keys for the same directory, which is\n * what lets a build-time value (an interception scope) be compared against a\n * request-time matched chain.\n *\n * See design/19-client-navigation.md §\"X-Timber-State-Tree Header\"\n */\n\n/**\n * Segment node shape expected by computeSegmentKeys.\n *\n * Structurally satisfied by both `SegmentNode` (build time) and\n * `ManifestSegmentNode` (request time) — keys depend only on the\n * URL path and the segment classification, never on file payloads.\n */\n\nexport interface SegmentKeyInput {\n urlPath: string;\n segmentName?: string;\n segmentType?: string;\n}\n\n/**\n * Compute state-tree keys for a segment chain.\n *\n * Non-group segments use their urlPath as-is. Route groups accumulate\n * ancestor group names to produce globally unique keys:\n * app/(a)/(shared)/dashboard → keys: ['/', '/(a)', '/(a)/(shared)', '/dashboard']\n *\n * **An intercepting segment switches the chain to name accumulation for good.**\n * A children-path interception (TIM-1280) puts an intercepting node and its\n * descendants into the *main* rendered chain, and their `urlPath`s are not\n * URLs: interception adds no URL depth, so `app/(browse)/(...)[artistSlug]/[year]`\n * carries `/` and `/[year]`. Keyed by urlPath the intercepting node would\n * collide with its own owner, and `[year]` with any top-level `[year]` route —\n * so a client that had one mounted would reuse the wrong cached layout. The\n * switch is sticky rather than per-node because the *descendants* are where\n * the false URLs are; the intercepting node alone is not the problem.\n *\n * This is the single source of truth for segment keys — used by the\n * element builder (skip decisions, SegmentOutlet props), segment info\n * (X-Timber-Segments header), the client cache/state tree, and\n * interception scoping (`routing/interception.ts`).\n */\nexport function computeSegmentKeys(segments: SegmentKeyInput[]): string[] {\n const keys: string[] = [];\n let prevKey = '';\n let insideIntercepting = false;\n\n for (const segment of segments) {\n if (segment.segmentType === 'intercepting') insideIntercepting = true;\n if (segment.segmentType === 'group' || insideIntercepting) {\n const base = prevKey === '/' ? '' : prevKey;\n const key = `${base}/${segment.segmentName}`;\n keys.push(key);\n prevKey = key;\n } else {\n keys.push(segment.urlPath);\n prevKey = segment.urlPath;\n }\n }\n\n return keys;\n}\n\n/**\n * Compute tree paths for a segment chain — the directory path of each segment\n * with slots elided, e.g. `app/(browse)/feed` → `/(browse)/feed`.\n *\n * This is `computeSegmentKeys` with the group branch applied to *every*\n * segment rather than only to groups. That one difference is the whole point:\n * `computeSegmentKeys` resets to `urlPath` at each URL-visible segment, so\n * `(browse)/feed` and `(landing)/feed` both key as `/feed`. Two directories\n * that render different layouts must not share an identity.\n *\n * Used for interception scoping (`routing/interception.ts`), where the\n * question is \"does this route pass through *that* directory?\" — not \"does it\n * render this URL?\". Not interchangeable with `computeSegmentKeys`: the state\n * tree is keyed by URL on purpose, because the client caches by URL.\n */\nexport function computeSegmentTreePaths(segments: SegmentKeyInput[]): string[] {\n const paths: string[] = [];\n let prev = '';\n\n for (const segment of segments) {\n const name = segment.segmentName ?? '';\n if (!name) {\n // The app root — no directory name of its own.\n paths.push('/');\n prev = '/';\n continue;\n }\n const base = prev === '/' ? '' : prev;\n const path = `${base}/${name}`;\n paths.push(path);\n prev = path;\n }\n\n return paths;\n}\n\n/**\n * The directory names a tree path is built from — `/` is none, `/feed/(a)` is\n * `['feed', '(a)']`.\n *\n * The inverse of the walk above, and it lives beside it so the format is\n * stated once: `findChainByTreePath` (`server/children-interception.ts`) walks\n * these names back down the tree to the directory the path addresses, and\n * `treePathDepth` counts them. Both are readings of the same string, and a\n * reader that disagreed with the producer about what separates two names\n * resolves an interception to the wrong node or to none.\n */\nexport function treePathNames(treePath: string): string[] {\n return treePath === '/' ? [] : treePath.slice(1).split('/');\n}\n\n/**\n * How many directories a tree path names — `/` is 0, `/feed` is 1,\n * `/feed/(a)` is 2.\n *\n * Two tree paths on a single rendered chain are strictly nested, so on that\n * chain depth orders them totally — which is what makes it usable as \"the\n * deeper of these two directories\" wherever a route passes through both\n * (`routing/interception.ts`).\n */\nexport function treePathDepth(treePath: string): number {\n return treePathNames(treePath).length;\n}\n\n/**\n * Compute a unique key for a parallel route slot.\n * Format: `{parentSegmentId}/@{slotName}`, e.g. `/@sidebar` or `/dashboard/@modal`.\n */\nexport function computeSlotKey(parentSegmentId: string, slotName: string): string {\n const name = slotName.startsWith('@') ? slotName : `@${slotName}`;\n const prefix = parentSegmentId === '/' ? '' : parentSegmentId;\n return `${prefix}/${name}`;\n}\n\n/**\n * The outlet key of a layout's `children`. A layout's own outlet covers its\n * chrome; everything it receives as `children` — this segment's boundaries\n * and metadata collectors, the next segment's access gate, the page — is a\n * separate outlet, so an unchanged layout\n * dedupes while what is under it changes. Keyed as the implicit `children`\n * slot; the route scanner rejects an `@children` directory.\n * See design/52-segment-hash-dedupe.md §\"The unit is the segment's own output\".\n */\nexport function childrenOutletKey(segmentId: string): string {\n return computeSlotKey(segmentId, '@children');\n}\n","/**\n * Metadata route classification for timber.js.\n *\n * Metadata routes are file-based endpoints that generate well-known URLs for\n * crawlers and browsers (sitemap.xml, robots.txt, OG images, etc.).\n *\n * These routes run through proxy.ts but NOT through middleware.ts or access.ts —\n * they are public endpoints by nature.\n *\n * See design/16-metadata.md §\"Metadata Routes\"\n */\n\nimport type { HeadElement } from './metadata.ts';\nimport type { Metadata } from './types.ts';\nimport type { ManifestSegmentNode } from './route-matcher.ts';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Classification of a metadata route file. */\nexport interface MetadataRouteInfo {\n /** The metadata route type. */\n type: MetadataRouteType;\n /** The content type to serve this route with. */\n contentType: string;\n /** Whether this route can appear in nested segments (not just app root). */\n nestable: boolean;\n}\n\nexport type MetadataRouteType =\n | 'sitemap'\n | 'robots'\n | 'manifest'\n | 'favicon'\n | 'icon'\n | 'opengraph-image'\n | 'apple-icon';\n\n// ─── Convention Table ────────────────────────────────────────────────────────\n\n/**\n * All recognized metadata route file conventions.\n *\n * Each entry maps a base file name (without extension) to its route info.\n * The extensions determine whether the file is static or dynamic.\n *\n * Static extensions: .xml, .txt, .json, .png, .jpg, .ico, .svg\n * Dynamic extensions: .ts, .tsx\n */\nexport const METADATA_ROUTE_CONVENTIONS: Record<\n string,\n {\n type: MetadataRouteType;\n contentType: string;\n nestable: boolean;\n staticExtensions: string[];\n dynamicExtensions: string[];\n /**\n * The URL path basename this file serves at (relative to segment).\n * For image routes, the full serve path includes an extension via\n * `resolveServePathForFile()`.\n */\n servePath: string;\n /**\n * When set, image routes append `.{serveExtension}` to the serve path.\n * Dynamic handlers (`.ts`/`.tsx`) use this as the default. Static files\n * use their own extension instead. Non-image routes leave this undefined.\n */\n serveExtension?: string;\n }\n> = {\n 'sitemap': {\n type: 'sitemap',\n contentType: 'application/xml',\n nestable: true,\n staticExtensions: ['xml'],\n dynamicExtensions: ['ts'],\n servePath: 'sitemap.xml',\n },\n 'robots': {\n type: 'robots',\n contentType: 'text/plain',\n nestable: false,\n staticExtensions: ['txt'],\n dynamicExtensions: ['ts'],\n servePath: 'robots.txt',\n },\n 'manifest': {\n type: 'manifest',\n contentType: 'application/manifest+json',\n nestable: false,\n staticExtensions: ['json'],\n dynamicExtensions: ['ts'],\n servePath: 'manifest.webmanifest',\n },\n 'favicon': {\n type: 'favicon',\n contentType: 'image/x-icon',\n nestable: false,\n staticExtensions: ['ico'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'favicon.ico',\n },\n 'icon': {\n type: 'icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg', 'svg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'icon',\n serveExtension: 'png',\n },\n 'opengraph-image': {\n type: 'opengraph-image',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'opengraph-image',\n serveExtension: 'png',\n },\n\n 'apple-icon': {\n type: 'apple-icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'apple-icon',\n serveExtension: 'png',\n },\n};\n\n// ─── MIME Type Resolution ─────────────────────────────────────────────────────\n\n/**\n * Map of file extensions to MIME types for static metadata route files.\n * Used to resolve the generic `image/*` content type for static image files.\n */\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n xml: 'application/xml',\n txt: 'text/plain',\n json: 'application/json',\n ico: 'image/x-icon',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\n\n/**\n * Resolve the concrete MIME type for a static metadata route file.\n *\n * For generic content types like `image/*`, this resolves to the actual\n * MIME type based on the file extension (e.g. `image/png` for `.png`).\n *\n * @param conventionContentType - The content type from the convention table (may be generic like `image/*`)\n * @param extension - The file extension without leading dot (e.g. \"png\", \"xml\")\n * @returns The resolved MIME type\n */\nexport function resolveStaticContentType(conventionContentType: string, extension: string): string {\n if (conventionContentType.includes('*')) {\n return EXTENSION_MIME_TYPES[extension] ?? 'application/octet-stream';\n }\n return conventionContentType;\n}\n\n/**\n * Check if a file extension represents a static (non-code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"xml\", \"png\", \"ts\")\n * @returns true if this is a static file, false if dynamic or unrecognized\n */\nexport function isStaticMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.staticExtensions.includes(extension);\n}\n\n/**\n * Check if a file extension represents a dynamic (code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"ts\", \"tsx\")\n * @returns true if this is a dynamic file, false if static or unrecognized\n */\nexport function isDynamicMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.dynamicExtensions.includes(extension);\n}\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\n/**\n * Classify a file name as a metadata route, or return null if it's not one.\n *\n * @param fileName - The full file name including extension (e.g. \"sitemap.xml\", \"icon.tsx\")\n * @returns Classification info, or null if not a metadata route\n */\nexport function classifyMetadataRoute(fileName: string): MetadataRouteInfo | null {\n const dotIndex = fileName.lastIndexOf('.');\n if (dotIndex === -1) return null;\n\n const baseName = fileName.slice(0, dotIndex);\n const ext = fileName.slice(dotIndex + 1);\n\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return null;\n\n const isStatic = convention.staticExtensions.includes(ext);\n const isDynamic = convention.dynamicExtensions.includes(ext);\n\n if (!isStatic && !isDynamic) return null;\n\n return {\n type: convention.type,\n contentType: convention.contentType,\n nestable: convention.nestable,\n };\n}\n\n/**\n * Resolve the serve path for a metadata route file.\n *\n * For image routes (icon, opengraph-image, apple-icon), the serve path includes\n * a file extension so CDNs cache correctly:\n * - Dynamic handlers (.ts/.tsx) use the convention's `serveExtension` (default: .png)\n * - Static files use their own extension (e.g., icon.svg → icon.svg)\n *\n * Non-image routes return the convention's `servePath` as-is (already includes\n * extension: sitemap.xml, robots.txt, etc.).\n */\nexport function resolveServePathForFile(baseName: string, filePath: string): string {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return baseName;\n\n if (!convention.serveExtension) return convention.servePath;\n\n const ext = filePath.slice(filePath.lastIndexOf('.') + 1);\n if (convention.staticExtensions.includes(ext)) {\n return `${convention.servePath}.${ext}`;\n }\n return `${convention.servePath}.${convention.serveExtension}`;\n}\n\n/**\n * Get the default serve path for a metadata route type (using default extension\n * for image routes). Used for auto-link generation when only the type is known.\n */\nexport function getMetadataRouteServePath(type: MetadataRouteType): string {\n for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.type === type) {\n if (convention.serveExtension) {\n return `${convention.servePath}.${convention.serveExtension}`;\n }\n return convention.servePath;\n }\n }\n throw new Error(`[timber] Unknown metadata route type: ${type}`);\n}\n\n/**\n * All possible serve path segments for metadata routes (includes extension\n * variants for image routes).\n */\nconst METADATA_SERVE_PATHS = new Set<string>();\nfor (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.serveExtension) {\n for (const ext of [...convention.staticExtensions, convention.serveExtension]) {\n METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);\n }\n } else {\n METADATA_SERVE_PATHS.add(convention.servePath);\n }\n}\n\nexport function isMetadataRouteServePath(pathname: string): boolean {\n let lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1);\n const qIdx = lastSegment.indexOf('?');\n let query = '';\n if (qIdx !== -1) {\n query = lastSegment.slice(qIdx + 1);\n lastSegment = lastSegment.slice(0, qIdx);\n }\n if (!METADATA_SERVE_PATHS.has(lastSegment)) return false;\n // Vite module requests (e.g., /src/icon.svg?import) use special query params.\n // These are source assets, not metadata routes.\n if (/(?:^|&)(?:import|url|raw|worker|inline)(?:&|$)/.test(query)) return false;\n return true;\n}\n\n/** A <link> auto-link tag. */\nexport interface AutoLinkLink {\n tag: 'link';\n rel: string;\n href: string;\n type?: string;\n}\n\n/** A <meta> auto-link tag. */\nexport interface AutoLinkMeta {\n tag: 'meta';\n property?: string;\n name?: string;\n content: string;\n}\n\nexport type AutoLinkTag = AutoLinkLink | AutoLinkMeta;\n\n/**\n * Get the auto-link tags to inject into <head> for metadata route files\n * discovered in a segment.\n *\n * Returns link tags for icon/apple-icon/manifest, and meta tags for\n * opengraph-image (emits both og:image and twitter:image). Returns null\n * for types that don't auto-link (favicon, sitemap, robots).\n *\n * @param type - The metadata route type\n * @param href - The resolved URL path to the metadata route\n * @returns Tag descriptor(s) for the <head>, or null if no auto-link\n */\nexport function getMetadataRouteAutoLink(type: MetadataRouteType, href: string): AutoLinkTag[] {\n switch (type) {\n case 'icon':\n return [{ tag: 'link', rel: 'icon', href }];\n case 'apple-icon':\n return [{ tag: 'link', rel: 'apple-touch-icon', href }];\n case 'manifest':\n return [{ tag: 'link', rel: 'manifest', href }];\n case 'opengraph-image':\n return [\n { tag: 'meta', property: 'og:image', content: href },\n { tag: 'meta', name: 'twitter:image', content: href },\n ];\n default:\n return [];\n }\n}\n"],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AAMA,IAAM,uCAAuB,IAAI,IAAY;AAC7C,KAAK,MAAM,cAAc,OAAO,OAAO,0BAA0B,GAC/D,IAAI,WAAW,gBACb,KAAK,MAAM,OAAO,CAAC,GAAG,WAAW,kBAAkB,WAAW,cAAc,GAC1E,qBAAqB,IAAI,GAAG,WAAW,UAAU,GAAG,KAAK;KAG3D,qBAAqB,IAAI,WAAW,SAAS;AAIjD,SAAgB,yBAAyB,UAA2B;CAClE,IAAI,cAAc,SAAS,MAAM,SAAS,YAAY,GAAG,IAAI,CAAC;CAC9D,MAAM,OAAO,YAAY,QAAQ,GAAG;CACpC,IAAI,QAAQ;CACZ,IAAI,SAAS,IAAI;EACf,QAAQ,YAAY,MAAM,OAAO,CAAC;EAClC,cAAc,YAAY,MAAM,GAAG,IAAI;CACzC;CACA,IAAI,CAAC,qBAAqB,IAAI,WAAW,GAAG,OAAO;CAGnD,IAAI,iDAAiD,KAAK,KAAK,GAAG,OAAO;CACzE,OAAO;AACT;;;;;;;;;;;;;AAgCA,SAAgB,yBAAyB,MAAyB,MAA6B;CAC7F,QAAQ,MAAR;EACE,KAAK,QACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAQ;EAAK,CAAC;EAC5C,KAAK,cACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAoB;EAAK,CAAC;EACxD,KAAK,YACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAY;EAAK,CAAC;EAChD,KAAK,mBACH,OAAO,CACL;GAAE,KAAK;GAAQ,UAAU;GAAY,SAAS;EAAK,GACnD;GAAE,KAAK;GAAQ,MAAM;GAAiB,SAAS;EAAK,CACtD;EACF,SACE,OAAO,CAAC;CACZ;AACF"}
1
+ {"version":3,"file":"metadata-routes-MXNjWOt5.js","names":[],"sources":["../../src/routing/segment-keys.ts","../../src/server/metadata-routes.ts"],"sourcesContent":["/**\n * Segment key computation — the stable identity of a segment in the route tree.\n *\n * A segment key is the string that names a segment across the RSC/SSR/client\n * boundary: it appears in the X-Timber-State-Tree header, the X-Timber-Segments\n * header, SegmentOutlet props, the client segment cache, and (since TIM-1279)\n * interception scoping.\n *\n * This module lives in `routing/` rather than `server/` because the keys are a\n * property of the route tree itself — both the build-time scanner tree and the\n * runtime manifest tree produce identical keys for the same directory, which is\n * what lets a build-time value (an interception scope) be compared against a\n * request-time matched chain.\n *\n * See design/19-client-navigation.md §\"X-Timber-State-Tree Header\"\n */\n\n/**\n * Segment node shape expected by computeSegmentKeys.\n *\n * Structurally satisfied by both `SegmentNode` (build time) and\n * `ManifestSegmentNode` (request time) — keys depend only on the\n * URL path and the segment classification, never on file payloads.\n */\n\nexport interface SegmentKeyInput {\n urlPath: string;\n segmentName?: string;\n segmentType?: string;\n}\n\n/**\n * Compute state-tree keys for a segment chain.\n *\n * Non-group segments use their urlPath as-is. Route groups accumulate\n * ancestor group names to produce globally unique keys:\n * app/(a)/(shared)/dashboard → keys: ['/', '/(a)', '/(a)/(shared)', '/dashboard']\n *\n * **An intercepting segment switches the chain to name accumulation for good.**\n * A children-path interception (TIM-1280) puts an intercepting node and its\n * descendants into the *main* rendered chain, and their `urlPath`s are not\n * URLs: interception adds no URL depth, so `app/(browse)/(...)[artistSlug]/[year]`\n * carries `/` and `/[year]`. Keyed by urlPath the intercepting node would\n * collide with its own owner, and `[year]` with any top-level `[year]` route —\n * so a client that had one mounted would reuse the wrong cached layout. The\n * switch is sticky rather than per-node because the *descendants* are where\n * the false URLs are; the intercepting node alone is not the problem.\n *\n * This is the single source of truth for segment keys — used by the\n * element builder (skip decisions, SegmentOutlet props), segment info\n * (X-Timber-Segments header), the client cache/state tree, and\n * interception scoping (`routing/interception.ts`).\n */\nexport function computeSegmentKeys(segments: SegmentKeyInput[]): string[] {\n const keys: string[] = [];\n let prevKey = '';\n let insideIntercepting = false;\n\n for (const segment of segments) {\n if (segment.segmentType === 'intercepting') insideIntercepting = true;\n if (segment.segmentType === 'group' || insideIntercepting) {\n const base = prevKey === '/' ? '' : prevKey;\n const key = `${base}/${segment.segmentName}`;\n keys.push(key);\n prevKey = key;\n } else {\n keys.push(segment.urlPath);\n prevKey = segment.urlPath;\n }\n }\n\n return keys;\n}\n\n/**\n * Compute tree paths for a segment chain — the directory path of each segment\n * with slots elided, e.g. `app/(browse)/feed` → `/(browse)/feed`.\n *\n * This is `computeSegmentKeys` with the group branch applied to *every*\n * segment rather than only to groups. That one difference is the whole point:\n * `computeSegmentKeys` resets to `urlPath` at each URL-visible segment, so\n * `(browse)/feed` and `(landing)/feed` both key as `/feed`. Two directories\n * that render different layouts must not share an identity.\n *\n * Used for interception scoping (`routing/interception.ts`), where the\n * question is \"does this route pass through *that* directory?\" — not \"does it\n * render this URL?\". Not interchangeable with `computeSegmentKeys`: the state\n * tree is keyed by URL on purpose, because the client caches by URL.\n */\nexport function computeSegmentTreePaths(segments: SegmentKeyInput[]): string[] {\n const paths: string[] = [];\n let prev = '';\n\n for (const segment of segments) {\n const name = segment.segmentName ?? '';\n if (!name) {\n // The app root — no directory name of its own.\n paths.push('/');\n prev = '/';\n continue;\n }\n const base = prev === '/' ? '' : prev;\n const path = `${base}/${name}`;\n paths.push(path);\n prev = path;\n }\n\n return paths;\n}\n\n/**\n * The directory names a tree path is built from — `/` is none, `/feed/(a)` is\n * `['feed', '(a)']`.\n *\n * The inverse of the walk above, and it lives beside it so the format is\n * stated once: `findChainByTreePath` (`server/children-interception.ts`) walks\n * these names back down the tree to the directory the path addresses, and\n * `treePathDepth` counts them. Both are readings of the same string, and a\n * reader that disagreed with the producer about what separates two names\n * resolves an interception to the wrong node or to none.\n */\nexport function treePathNames(treePath: string): string[] {\n return treePath === '/' ? [] : treePath.slice(1).split('/');\n}\n\n/**\n * How many directories a tree path names — `/` is 0, `/feed` is 1,\n * `/feed/(a)` is 2.\n *\n * Two tree paths on a single rendered chain are strictly nested, so on that\n * chain depth orders them totally — which is what makes it usable as \"the\n * deeper of these two directories\" wherever a route passes through both\n * (`routing/interception.ts`).\n */\nexport function treePathDepth(treePath: string): number {\n return treePathNames(treePath).length;\n}\n\n/**\n * Compute a unique key for a parallel route slot.\n * Format: `{parentSegmentId}/@{slotName}`, e.g. `/@sidebar` or `/dashboard/@modal`.\n */\nexport function computeSlotKey(parentSegmentId: string, slotName: string): string {\n const name = slotName.startsWith('@') ? slotName : `@${slotName}`;\n const prefix = parentSegmentId === '/' ? '' : parentSegmentId;\n return `${prefix}/${name}`;\n}\n\n/**\n * The outlet key of a layout's `children`. A layout's own outlet covers its\n * chrome; everything it receives as `children` — this segment's boundaries\n * and metadata collectors, the next segment's access gate, the page — is a\n * separate outlet, so a skipped 'document' layout never freezes what is under\n * it. Keyed as the implicit `children` slot; the route scanner rejects an\n * `@children` directory. See design/53-segment-lifetime.md §\"Skipping\".\n */\nexport function childrenOutletKey(segmentId: string): string {\n return computeSlotKey(segmentId, '@children');\n}\n\n/**\n * The outlet keys of `'document'` segments (design/53-segment-lifetime.md\n * §\"Skipping\"), by the segment's **tree path** — its directory path, route\n * groups and `@slot` directories included. A `'document'` skip is\n * identity-addressed (the client renders what it holds at this key, under a\n * digest bound to it), so the key must name one segment. Segment ids\n * (`computeSegmentKeys`) do not: `(landing)/feed` and `(browse)/feed` both\n * key as `/feed`, which a content-addressed hash skip survives and a digest\n * skip would not.\n *\n * `#` starts a URL fragment, so no routable segment is named with it — the\n * same reason the metadata outlet is `#metadata`. A `'document'` layout's\n * `children` outlet is `childrenOutletKey` of its layout key in a slot; on the\n * main chain it keeps `childrenOutletKey(segmentId)`.\n */\nexport function pageOutletKey(treePath: string): string {\n return `${treePath === '/' ? '' : treePath}/#page`;\n}\n\n/** See `pageOutletKey`. */\nexport function layoutOutletKey(treePath: string): string {\n return `${treePath === '/' ? '' : treePath}/#layout`;\n}\n\n/**\n * The full tree path of a slot's matched chain (or a prefix of it) — the key\n * the ALS slot params map, the generated `getSegmentParams` overloads and a\n * slot's `'document'` outlets all use.\n *\n * Built from the parent's tree path plus each chain node's directory name,\n * so an intercepting node contributes its marker\n * (`/gallery/@modal/(.)photo/[id]`) and a route group contributes its\n * parentheses.\n *\n * One definition for the render path, the eager access path and the outlet\n * keys: they key the same things, and a divergence would silently strand one\n * of them.\n */\nexport function slotChainTreePath(\n chain: ReadonlyArray<{ segmentName?: string }>,\n parentTreePath: string\n): string {\n const slotSuffix = chain\n .map((s) => s.segmentName)\n .filter(Boolean)\n .join('/');\n const prefix = parentTreePath === '/' ? '' : parentTreePath;\n return `${prefix}/${slotSuffix}`;\n}\n","/**\n * Metadata route classification for timber.js.\n *\n * Metadata routes are file-based endpoints that generate well-known URLs for\n * crawlers and browsers (sitemap.xml, robots.txt, OG images, etc.).\n *\n * These routes run through proxy.ts but NOT through middleware.ts or access.ts —\n * they are public endpoints by nature.\n *\n * See design/16-metadata.md §\"Metadata Routes\"\n */\n\nimport type { HeadElement } from './metadata.ts';\nimport type { Metadata } from './types.ts';\nimport type { ManifestSegmentNode } from './route-matcher.ts';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Classification of a metadata route file. */\nexport interface MetadataRouteInfo {\n /** The metadata route type. */\n type: MetadataRouteType;\n /** The content type to serve this route with. */\n contentType: string;\n /** Whether this route can appear in nested segments (not just app root). */\n nestable: boolean;\n}\n\nexport type MetadataRouteType =\n | 'sitemap'\n | 'robots'\n | 'manifest'\n | 'favicon'\n | 'icon'\n | 'opengraph-image'\n | 'apple-icon';\n\n// ─── Convention Table ────────────────────────────────────────────────────────\n\n/**\n * All recognized metadata route file conventions.\n *\n * Each entry maps a base file name (without extension) to its route info.\n * The extensions determine whether the file is static or dynamic.\n *\n * Static extensions: .xml, .txt, .json, .png, .jpg, .ico, .svg\n * Dynamic extensions: .ts, .tsx\n */\nexport const METADATA_ROUTE_CONVENTIONS: Record<\n string,\n {\n type: MetadataRouteType;\n contentType: string;\n nestable: boolean;\n staticExtensions: string[];\n dynamicExtensions: string[];\n /**\n * The URL path basename this file serves at (relative to segment).\n * For image routes, the full serve path includes an extension via\n * `resolveServePathForFile()`.\n */\n servePath: string;\n /**\n * When set, image routes append `.{serveExtension}` to the serve path.\n * Dynamic handlers (`.ts`/`.tsx`) use this as the default. Static files\n * use their own extension instead. Non-image routes leave this undefined.\n */\n serveExtension?: string;\n }\n> = {\n 'sitemap': {\n type: 'sitemap',\n contentType: 'application/xml',\n nestable: true,\n staticExtensions: ['xml'],\n dynamicExtensions: ['ts'],\n servePath: 'sitemap.xml',\n },\n 'robots': {\n type: 'robots',\n contentType: 'text/plain',\n nestable: false,\n staticExtensions: ['txt'],\n dynamicExtensions: ['ts'],\n servePath: 'robots.txt',\n },\n 'manifest': {\n type: 'manifest',\n contentType: 'application/manifest+json',\n nestable: false,\n staticExtensions: ['json'],\n dynamicExtensions: ['ts'],\n servePath: 'manifest.webmanifest',\n },\n 'favicon': {\n type: 'favicon',\n contentType: 'image/x-icon',\n nestable: false,\n staticExtensions: ['ico'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'favicon.ico',\n },\n 'icon': {\n type: 'icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg', 'svg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'icon',\n serveExtension: 'png',\n },\n 'opengraph-image': {\n type: 'opengraph-image',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'opengraph-image',\n serveExtension: 'png',\n },\n\n 'apple-icon': {\n type: 'apple-icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'apple-icon',\n serveExtension: 'png',\n },\n};\n\n// ─── MIME Type Resolution ─────────────────────────────────────────────────────\n\n/**\n * Map of file extensions to MIME types for static metadata route files.\n * Used to resolve the generic `image/*` content type for static image files.\n */\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n xml: 'application/xml',\n txt: 'text/plain',\n json: 'application/json',\n ico: 'image/x-icon',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\n\n/**\n * Resolve the concrete MIME type for a static metadata route file.\n *\n * For generic content types like `image/*`, this resolves to the actual\n * MIME type based on the file extension (e.g. `image/png` for `.png`).\n *\n * @param conventionContentType - The content type from the convention table (may be generic like `image/*`)\n * @param extension - The file extension without leading dot (e.g. \"png\", \"xml\")\n * @returns The resolved MIME type\n */\nexport function resolveStaticContentType(conventionContentType: string, extension: string): string {\n if (conventionContentType.includes('*')) {\n return EXTENSION_MIME_TYPES[extension] ?? 'application/octet-stream';\n }\n return conventionContentType;\n}\n\n/**\n * Check if a file extension represents a static (non-code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"xml\", \"png\", \"ts\")\n * @returns true if this is a static file, false if dynamic or unrecognized\n */\nexport function isStaticMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.staticExtensions.includes(extension);\n}\n\n/**\n * Check if a file extension represents a dynamic (code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"ts\", \"tsx\")\n * @returns true if this is a dynamic file, false if static or unrecognized\n */\nexport function isDynamicMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.dynamicExtensions.includes(extension);\n}\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\n/**\n * Classify a file name as a metadata route, or return null if it's not one.\n *\n * @param fileName - The full file name including extension (e.g. \"sitemap.xml\", \"icon.tsx\")\n * @returns Classification info, or null if not a metadata route\n */\nexport function classifyMetadataRoute(fileName: string): MetadataRouteInfo | null {\n const dotIndex = fileName.lastIndexOf('.');\n if (dotIndex === -1) return null;\n\n const baseName = fileName.slice(0, dotIndex);\n const ext = fileName.slice(dotIndex + 1);\n\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return null;\n\n const isStatic = convention.staticExtensions.includes(ext);\n const isDynamic = convention.dynamicExtensions.includes(ext);\n\n if (!isStatic && !isDynamic) return null;\n\n return {\n type: convention.type,\n contentType: convention.contentType,\n nestable: convention.nestable,\n };\n}\n\n/**\n * Resolve the serve path for a metadata route file.\n *\n * For image routes (icon, opengraph-image, apple-icon), the serve path includes\n * a file extension so CDNs cache correctly:\n * - Dynamic handlers (.ts/.tsx) use the convention's `serveExtension` (default: .png)\n * - Static files use their own extension (e.g., icon.svg → icon.svg)\n *\n * Non-image routes return the convention's `servePath` as-is (already includes\n * extension: sitemap.xml, robots.txt, etc.).\n */\nexport function resolveServePathForFile(baseName: string, filePath: string): string {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return baseName;\n\n if (!convention.serveExtension) return convention.servePath;\n\n const ext = filePath.slice(filePath.lastIndexOf('.') + 1);\n if (convention.staticExtensions.includes(ext)) {\n return `${convention.servePath}.${ext}`;\n }\n return `${convention.servePath}.${convention.serveExtension}`;\n}\n\n/**\n * Get the default serve path for a metadata route type (using default extension\n * for image routes). Used for auto-link generation when only the type is known.\n */\nexport function getMetadataRouteServePath(type: MetadataRouteType): string {\n for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.type === type) {\n if (convention.serveExtension) {\n return `${convention.servePath}.${convention.serveExtension}`;\n }\n return convention.servePath;\n }\n }\n throw new Error(`[timber] Unknown metadata route type: ${type}`);\n}\n\n/**\n * All possible serve path segments for metadata routes (includes extension\n * variants for image routes).\n */\nconst METADATA_SERVE_PATHS = new Set<string>();\nfor (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.serveExtension) {\n for (const ext of [...convention.staticExtensions, convention.serveExtension]) {\n METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);\n }\n } else {\n METADATA_SERVE_PATHS.add(convention.servePath);\n }\n}\n\nexport function isMetadataRouteServePath(pathname: string): boolean {\n let lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1);\n const qIdx = lastSegment.indexOf('?');\n let query = '';\n if (qIdx !== -1) {\n query = lastSegment.slice(qIdx + 1);\n lastSegment = lastSegment.slice(0, qIdx);\n }\n if (!METADATA_SERVE_PATHS.has(lastSegment)) return false;\n // Vite module requests (e.g., /src/icon.svg?import) use special query params.\n // These are source assets, not metadata routes.\n if (/(?:^|&)(?:import|url|raw|worker|inline)(?:&|$)/.test(query)) return false;\n return true;\n}\n\n/** A <link> auto-link tag. */\nexport interface AutoLinkLink {\n tag: 'link';\n rel: string;\n href: string;\n type?: string;\n}\n\n/** A <meta> auto-link tag. */\nexport interface AutoLinkMeta {\n tag: 'meta';\n property?: string;\n name?: string;\n content: string;\n}\n\nexport type AutoLinkTag = AutoLinkLink | AutoLinkMeta;\n\n/**\n * Get the auto-link tags to inject into <head> for metadata route files\n * discovered in a segment.\n *\n * Returns link tags for icon/apple-icon/manifest, and meta tags for\n * opengraph-image (emits both og:image and twitter:image). Returns null\n * for types that don't auto-link (favicon, sitemap, robots).\n *\n * @param type - The metadata route type\n * @param href - The resolved URL path to the metadata route\n * @returns Tag descriptor(s) for the <head>, or null if no auto-link\n */\nexport function getMetadataRouteAutoLink(type: MetadataRouteType, href: string): AutoLinkTag[] {\n switch (type) {\n case 'icon':\n return [{ tag: 'link', rel: 'icon', href }];\n case 'apple-icon':\n return [{ tag: 'link', rel: 'apple-touch-icon', href }];\n case 'manifest':\n return [{ tag: 'link', rel: 'manifest', href }];\n case 'opengraph-image':\n return [\n { tag: 'meta', property: 'og:image', content: href },\n { tag: 'meta', name: 'twitter:image', content: href },\n ];\n default:\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyFA,SAAgB,wBAAwB,UAAuC;CAC7E,MAAM,QAAkB,CAAC;CACzB,IAAI,OAAO;CAEX,KAAK,MAAM,WAAW,UAAU;EAC9B,MAAM,OAAO,QAAQ,eAAe;EACpC,IAAI,CA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AAI,GAAG,WAAW,UAAU,GAAG,KAAK;KAG3D,qBAAqB,IAAI,WAAW,SAAS;AAIjD,SAAgB,yBAAyB,UAA2B;CAClE,IAAI,cAAc,SAAS,MAAM,SAAS,YAAY,GAAG,IAAI,CAAC;CAC9D,MAAM,OAAO,YAAY,QAAQ,GAAG;CACpC,IAAI,QAAQ;CACZ,IAAI,SAAS,IAAI;EACf,QAAQ,YAAY,MAAM,OAAO,CAAC;EAClC,cAAc,YAAY,MAAM,GAAG,IAAI;CACzC;CACA,IAAI,CAAC,qBAAqB,IAAI,WAAW,GAAG,OAAO;CAGnD,IAAI,iDAAiD,KAAK,KAAK,GAAG,OAAO;CACzE,OAAO;AACT;;;;;;;;;;;;;AAgCA,SAAgB,yBAAyB,MAAyB,MAA6B;CAC7F,QAAQ,MAAR;EACE,KAAK,QACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAQ;EAAK,CAAC;EAC5C,KAAK,cACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAoB;EAAK,CAAC;EACxD,KAAK,YACH,OAAO,CAAC;GAAE,KAAK;GAAQ,KAAK;GAAY;EAAK,CAAC;EAChD,KAAK,mBACH,OAAO,CACL;GAAE,KAAK;GAAQ,UAAU;GAAY,SAAS;EAAK,GACnD;GAAE,KAAK;GAAQ,MAAM;GAAiB,SAAS;EAAK,CACtD;EACF,SACE,OAAO,CAAC;CACZ;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as getLogger } from "./logger-DmRR9tmZ.js";
1
+ import { t as getLogger } from "./logger-C4m8rfMy.js";
2
2
  // src/server/abort-scope.ts
3
3
  /**
4
4
  * Abort listeners scoped to the work they guard.
@@ -281,4 +281,4 @@ function discardResponseBody(response) {
281
281
  }
282
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 };
283
283
 
284
- //# sourceMappingURL=node-response-yp8zdyRp.js.map
284
+ //# sourceMappingURL=node-response-8Vz29cGS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-response-yp8zdyRp.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":";;;;;;;;;;;;;;;;;;;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;EACP,IAAI,QAAQ;EACZ;CACF;CAIA,IAAI;EACF,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxC,QAAQ,CAER;AACF"}
1
+ {"version":3,"file":"node-response-8Vz29cGS.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,aAC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ACF;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-Cj9EeZoL.js";
2
+ import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-Y8S9C0Na.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-WQgUydF_.js.map
98
+ //# sourceMappingURL=poison-scan-Dpl3ibG-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"poison-scan-WQgUydF_.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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;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-Dpl3ibG-.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,MAAc,MAAwB;CAC5E,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO,CAAC;CAC9C,IAAI;CACJ,IAAI;EAEF,UAAU,SAAS,MAAM,EAAE,MAAM,YAAY,IAAI,EAAE,CAAC;CACtD,QAAQ;EACN,OAAO,CAAC;CACV;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AqB,SAAS;CACvE,MAAM,kBAAkB,SAAS,YAAY,SAAS,YAAY,SAAS;CAC3E,OAAO,QAAQ,QACZ,WACE,OAAO,YAAY,iBAAiB,mBACpC,OAAO,YAAY,iBAAiB,eACzC;AACF"}
@@ -207,8 +207,9 @@ async function rscCacheKey(lookup) {
207
207
  if (!subtle) return null;
208
208
  let canonical = "";
209
209
  for (const name of RSC_KEY_HEADERS) {
210
- const value = lookup(name);
211
- if (value == null) continue;
210
+ const raw = lookup(name);
211
+ if (raw == null) continue;
212
+ const value = name === "X-Timber-State-Tree" ? stateTreeKeyValue(raw) : raw;
212
213
  canonical += `${name.toLowerCase()}:${value.length}:${value}`;
213
214
  }
214
215
  const digest = await subtle.digest("SHA-256", new TextEncoder().encode(canonical));
@@ -217,6 +218,41 @@ async function rscCacheKey(lookup) {
217
218
  return KEY_PREFIX + hex;
218
219
  }
219
220
  /**
221
+ * The part of an `X-Timber-State-Tree` value that enters the key: everything
222
+ * but `documents`.
223
+ *
224
+ * `documents` carries the key digests of `'document'` segments, and a digest
225
+ * is derived from cookie values (design/53-segment-lifetime.md §"The key
226
+ * digest"). It is keyed and per render, so nothing can be read from it — but
227
+ * a URL is logged by proxies, CDNs and analytics, and a value derived from a
228
+ * cookie does not belong in one. The response still varies on it, so a
229
+ * request that carries `documents` is made unstorable by shared caches
230
+ * instead (`server/rsc-cache-key-guard.ts`).
231
+ *
232
+ * A value that is not a JSON object enters the key unchanged: it is not a
233
+ * state tree a client sent, and dropping it would let two different headers
234
+ * share a key.
235
+ */
236
+ function stateTreeKeyValue(value) {
237
+ let parsed;
238
+ try {
239
+ parsed = JSON.parse(value);
240
+ } catch {
241
+ return value;
242
+ }
243
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return value;
244
+ if (!("documents" in parsed)) return value;
245
+ const { documents: _documents, ...rest } = parsed;
246
+ return JSON.stringify(rest);
247
+ }
248
+ /**
249
+ * Whether an `X-Timber-State-Tree` value carries `'document'` key digests —
250
+ * a request whose response varies on an input `rscCacheKey` leaves out.
251
+ */
252
+ function stateTreeHasDocuments(value) {
253
+ return value !== null && stateTreeKeyValue(value) !== value;
254
+ }
255
+ /**
220
256
  * An unverifiable stand-in key, for the one case where the digest cannot be
221
257
  * computed: `crypto.subtle` is absent in non-secure browsing contexts.
222
258
  * `crypto.getRandomValues` is not gated that way, so it is available exactly
@@ -237,6 +273,6 @@ function recordLookup(headers) {
237
273
  for (const name of Object.keys(headers)) lowered[name.toLowerCase()] = headers[name];
238
274
  return (name) => lowered[name.toLowerCase()];
239
275
  }
240
- export { randomRscCacheKey as a, stripRscCacheKey as c, isRscCacheKeyShape as i, RSC_KEY_PARAM as n, recordLookup as o, appVisibleSearch as r, rscCacheKey as s, RSC_KEY_HEADERS as t };
276
+ export { randomRscCacheKey as a, stateTreeHasDocuments as c, isRscCacheKeyShape as i, stripRscCacheKey as l, RSC_KEY_PARAM as n, recordLookup as o, appVisibleSearch as r, rscCacheKey as s, RSC_KEY_HEADERS as t };
241
277
 
242
- //# sourceMappingURL=rsc-cache-key-D0cb0Gmc.js.map
278
+ //# sourceMappingURL=rsc-cache-key-BGvUtMtN.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rsc-cache-key-D0cb0Gmc.js","names":[],"sources":["../../src/shared/rsc-cache-key.ts"],"sourcesContent":["/**\n * The `_rsc` payload cache key — derived identically on both sides.\n *\n * The client puts this in the payload URL so the document and its Flight\n * payload occupy different cache keys (TIM-1268). The server recomputes it\n * from the received headers so a request cannot claim one client's key while\n * sending another client's headers — see `server/rsc-cache-key-guard.ts`.\n * Both sides must agree exactly, which is why the derivation lives here and\n * not in either one.\n *\n * Isomorphic: no server or client imports. The browser bundle audit\n * (`tests/client-bundle-audit.test.ts`) enforces the client half of that.\n *\n * See design/19-client-navigation.md §\"The `_rsc` cache key\".\n */\n\n/**\n * Digest length in hex characters. 128 bits: the origin guard compares a\n * caller-supplied key against a recomputed one, so the relevant bound is a\n * birthday attack (an attacker who can influence a victim's `X-Timber-URL`\n * gets to search both sides), not second preimage. 64 bits would fall to\n * ~2^32 work; 128 puts it at 2^64.\n */\nconst KEY_HEX_LENGTH = 32;\n\n/**\n * Marks a value as a framework-issued key, and versions the derivation.\n *\n * Without it, an application value that happened to be 32 lowercase hex — an\n * MD5, a token — is indistinguishable from a forged claim: both are \"the\n * right shape, the wrong digest\", and no information in the value separates\n * them. So the exemption cannot key on shape alone.\n *\n * The prefix resolves that because it is anchored to the address the\n * victim's own client uses. A payload lives at `?_rsc=1.<digest>`, so\n * anything aimed at that cache entry must carry the prefix and therefore\n * gets validated; anything without it cannot be addressing a payload URL at\n * all, and is exempt as application data. An attacker cannot both hit the\n * victim's cache key and dodge the check.\n *\n * The version component also gives the derivation a migration path: the\n * client and the origin must agree byte for byte, so a future change to the\n * canonical form can be rolled out by bumping this instead of a flag day.\n */\nconst KEY_PREFIX = '1.';\n\n/**\n * The request headers that vary an RSC payload response, in canonical\n * casing — this list is also emitted verbatim as the response's `Vary`\n * tokens (`server/pipeline.ts`), since \"what varies the response\" is one\n * question with one answer, not two lists that happen to agree.\n *\n * This list is the contract, and it is enforced rather than trusted:\n * `tests/rsc-cache-key.test.ts` asserts that the header names\n * `buildRscHeaders()` can emit are exactly this set. A header added to the\n * request without being added here fails that test, because a varying input\n * outside the key is precisely the cache-poisoning hazard the key exists to\n * close.\n *\n * **No credentials, session identifiers, or user-supplied content may be\n * added.** Every value here is hashed into a URL, and URLs are logged by\n * proxies, CDNs, and origin access logs. `fnv1aHash` is a cache-key hash,\n * not a KDF — a low-entropy secret would be recoverable by brute force.\n * Authentication travels on cookies, which never enter the key.\n */\nexport const RSC_KEY_HEADERS = [\n 'Accept',\n 'X-Timber-State-Tree',\n 'X-Timber-URL',\n 'X-Timber-Deployment-Id',\n] as const;\n\n/**\n * Whether a value could be a key this module produced.\n *\n * `_rsc` is not a reserved parameter name — an application may already use\n * it for its own search state, including for a value that happens to look\n * like a digest. Anything without the `KEY_PREFIX` is therefore application\n * data, not a claim on a payload cache key, and the origin guard leaves it\n * alone rather than penalizing the response.\n *\n * Derived from `KEY_PREFIX` and `KEY_HEX_LENGTH` rather than spelled again,\n * so the shape cannot drift from the digest that has to satisfy it.\n *\n * Ignoring a malformed value costs no protection: clients only ever send\n * well-formed keys, so a URL bearing a malformed one is an address no\n * legitimate request will ever ask for, and nothing can be poisoned at an\n * address nobody reads.\n */\nexport function isRscCacheKeyShape(value: string): boolean {\n if (!value.startsWith(KEY_PREFIX)) return false;\n const digest = value.slice(KEY_PREFIX.length);\n return digest.length === KEY_HEX_LENGTH && /^[0-9a-f]+$/.test(digest);\n}\n\n/**\n * The query parameter carrying the payload cache key.\n *\n * Spelled here rather than at each of the four places that read or write it\n * — the client that appends it, the origin guard that validates it, and the\n * strip below — because it is a wire contract between two independent\n * implementations, exactly like the digest itself.\n */\nexport const RSC_KEY_PARAM = '_rsc';\n\n// ─── Keeping the key out of application state ────────────────────────────\n\n/**\n * Decode one raw `name` or `value` the way `URLSearchParams` does:\n * `application/x-www-form-urlencoded`, so `+` is a space.\n *\n * Malformed percent-escapes throw in `decodeURIComponent`. `URLSearchParams`\n * leaves those bytes as-is rather than throwing, and so do we — a pair we\n * cannot decode is by definition not the framework's, so it is kept.\n */\nfunction formDecode(raw: string): string {\n try {\n return decodeURIComponent(raw.replace(/\\+/g, ' '));\n } catch {\n return raw;\n }\n}\n\n/**\n * Remove framework-issued `_rsc` values from a raw query string.\n *\n * Only values matching `isRscCacheKeyShape` are removed. `_rsc` is not a\n * reserved name (see that function), so `/search?_rsc=foo` is application\n * state and survives — the same exemption the origin guard applies, derived\n * from the same predicate so the two cannot disagree about what \"ours\"\n * means.\n *\n * Operates on the raw string rather than round-tripping through\n * `URLSearchParams`, so every surviving pair keeps its original bytes.\n * Re-serializing would rewrite `?b` as `?b=` and `?a=%7E` as `?a=~` on RSC\n * navigations only, which is the same class of inconsistency this function\n * exists to remove.\n *\n * Matching decodes the name, because `?%5Frsc=<key>` is a `_rsc` parameter\n * as far as `URLSearchParams` is concerned — the same reasoning as the\n * guard's fast path.\n *\n * @param search - `url.search`, with or without the leading `?`.\n * @returns The query string including a leading `?`, or `''` if empty.\n */\nexport function stripRscCacheKey(search: string): string {\n const query = search.startsWith('?') ? search.slice(1) : search;\n if (query === '') return '';\n const kept = query.split('&').filter((pair) => {\n const eq = pair.indexOf('=');\n if (formDecode(eq === -1 ? pair : pair.slice(0, eq)) !== RSC_KEY_PARAM) return true;\n return !isRscCacheKeyShape(eq === -1 ? '' : formDecode(pair.slice(eq + 1)));\n });\n const result = kept.join('&');\n return result === '' ? '' : `?${result}`;\n}\n\n/** A request's search state as application code should see it. */\nexport interface AppVisibleSearch {\n /** Parsed params, with the framework's cache key removed. */\n params: URLSearchParams;\n /** The matching raw query string — `''` or `?…`. */\n search: string;\n}\n\n/**\n * The search state application code sees, for any request URL.\n *\n * The `_rsc` key rides on the payload URL of every RSC navigation and on no\n * other request, so reading search params straight off `req.url` makes the\n * same page observe different search state depending on whether it was\n * reached by a full load or a client navigation — and lets the cache key\n * leak into whatever the page builds from it: a canonical URL, a pagination\n * link, an analytics payload (TIM-1272).\n *\n * Every application-facing derivation of search state goes through here.\n * `params` and `search` are returned together, from one strip, because they\n * are two views of one answer and were previously two expressions that had\n * to agree.\n *\n * The raw request URL is deliberately untouched: `server/rsc-cache-key-guard.ts`\n * still reads the parameter from `req.url` to bind the key to the request.\n */\nexport function appVisibleSearch(url: URL): AppVisibleSearch {\n const search = stripRscCacheKey(url.search);\n return { params: new URLSearchParams(search), search };\n}\n\n/**\n * Reads a header value by name. Must be case-insensitive — `Headers.get()`\n * already is, and `recordLookup` below makes a plain record so.\n */\nexport type HeaderLookup = (name: string) => string | null | undefined;\n\n/**\n * Compute the `_rsc` cache key for a request.\n *\n * Absent headers are omitted rather than sent as empty, so \"header missing\"\n * and \"header present but empty\" produce different keys.\n *\n * Values are length-prefixed rather than delimiter-separated. Any delimiter\n * can be forged by a value that contains it: with a `\\0` separator, an\n * `accept` of `a\\nx-timber-url\\0b` serializes identically to an `accept` of\n * `a` alongside an `x-timber-url` of `b`, which would let one header claim\n * another's key. HTTP forbids control characters in header values and both\n * `fetch()` and the server runtime reject them, so this is defense in depth\n * — but a length prefix is unambiguous for *any* content, which is a\n * property worth having in a function whose whole job is to be agreed on by\n * two independent implementations.\n *\n * SHA-256, truncated to 128 bits. A fast non-cryptographic hash is the\n * obvious choice for a cache key and is the wrong one here: the origin\n * *compares* this value against a recomputed one, which makes it a check.\n * FNV-1a — used for timber's other cache keys — is a multiply-xor over a\n * fixed field, so an attacker controlling a few bytes of any input (their\n * own `X-Timber-URL`, say) can solve for a chosen digest rather than search\n * for one, and forge a key belonging to somebody else.\n *\n * Returns `null` when no digest is available — `crypto.subtle` is absent in\n * non-secure browsing contexts (plain `http://` on a LAN address). Callers\n * must treat that as \"no key\", never as \"key matches\": the client omits the\n * parameter and the server refuses to share-cache. That returns those\n * clients to the pre-TIM-1268 posture, where `Vary` alone separates HTML\n * from Flight — acceptable, because a non-secure origin has no shared-CDN\n * caching story to protect in the first place.\n */\nexport async function rscCacheKey(lookup: HeaderLookup): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n let canonical = '';\n for (const name of RSC_KEY_HEADERS) {\n const value = lookup(name);\n if (value == null) continue;\n // Lowercased in the canonical form so the two implementations cannot\n // disagree over the casing of the constant they share.\n canonical += `${name.toLowerCase()}:${value.length}:${value}`;\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(canonical));\n let hex = '';\n for (const byte of new Uint8Array(digest, 0, KEY_HEX_LENGTH / 2)) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return KEY_PREFIX + hex;\n}\n\n/**\n * An unverifiable stand-in key, for the one case where the digest cannot be\n * computed: `crypto.subtle` is absent in non-secure browsing contexts.\n * `crypto.getRandomValues` is not gated that way, so it is available exactly\n * where the digest is not.\n *\n * Carries `KEY_PREFIX` like any other key, so the origin reads it as a claim\n * it cannot verify — and refuses to share-cache the response — rather than\n * exempting it as application data. Lives here so the prefix has one home.\n */\nexport function randomRscCacheKey(): string {\n const bytes = new Uint8Array(KEY_HEX_LENGTH / 2);\n globalThis.crypto.getRandomValues(bytes);\n return KEY_PREFIX + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** Build a case-insensitive lookup over a plain header record. */\nexport function recordLookup(headers: Record<string, string>): HeaderLookup {\n const lowered: Record<string, string> = {};\n for (const name of Object.keys(headers)) {\n lowered[name.toLowerCase()] = headers[name];\n }\n return (name) => lowered[name.toLowerCase()];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;AAqBvB,IAAM,aAAa;;;;;;;;;;;;;;;;;;;;AAqBnB,IAAa,kBAAkB;CAC7B;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,mBAAmB,OAAwB;CACzD,IAAI,CAAC,MAAM,WAAW,UAAU,GAAG,OAAO;CAC1C,MAAM,SAAS,MAAM,MAAM,CAAiB;CAC5C,OAAO,OAAO,WAAW,kBAAkB,cAAc,KAAK,MAAM;AACtE;;;;;;;;;AAUA,IAAa,gBAAgB;;;;;;;;;AAY7B,SAAS,WAAW,KAAqB;CACvC,IAAI;EACF,OAAO,mBAAmB,IAAI,QAAQ,OAAO,GAAG,CAAC;CACnD,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,QAAQ,OAAO,WAAW,GAAG,IAAI,OAAO,MAAM,CAAC,IAAI;CACzD,IAAI,UAAU,IAAI,OAAO;CAMzB,MAAM,SALO,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS;EAC7C,MAAM,KAAK,KAAK,QAAQ,GAAG;EAC3B,IAAI,WAAW,OAAO,KAAK,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,MAAA,QAAqB,OAAO;EAC/E,OAAO,CAA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KAAK,YAAY,KAAK,QAAQ;CAExC,QAAQ,SAAS,QAAQ,KAAK,YAAY;AAC5C"}
1
+ {"version":3,"file":"rsc-cache-key-BGvUtMtN.js","names":[],"sources":["../../src/shared/rsc-cache-key.ts"],"sourcesContent":["/**\n * The `_rsc` payload cache key — derived identically on both sides.\n *\n * The client puts this in the payload URL so the document and its Flight\n * payload occupy different cache keys (TIM-1268). The server recomputes it\n * from the received headers so a request cannot claim one client's key while\n * sending another client's headers — see `server/rsc-cache-key-guard.ts`.\n * Both sides must agree exactly, which is why the derivation lives here and\n * not in either one.\n *\n * Isomorphic: no server or client imports. The browser bundle audit\n * (`tests/client-bundle-audit.test.ts`) enforces the client half of that.\n *\n * See design/19-client-navigation.md §\"The `_rsc` cache key\".\n */\n\n/**\n * Digest length in hex characters. 128 bits: the origin guard compares a\n * caller-supplied key against a recomputed one, so the relevant bound is a\n * birthday attack (an attacker who can influence a victim's `X-Timber-URL`\n * gets to search both sides), not second preimage. 64 bits would fall to\n * ~2^32 work; 128 puts it at 2^64.\n */\nconst KEY_HEX_LENGTH = 32;\n\n/**\n * Marks a value as a framework-issued key, and versions the derivation.\n *\n * Without it, an application value that happened to be 32 lowercase hex — an\n * MD5, a token — is indistinguishable from a forged claim: both are \"the\n * right shape, the wrong digest\", and no information in the value separates\n * them. So the exemption cannot key on shape alone.\n *\n * The prefix resolves that because it is anchored to the address the\n * victim's own client uses. A payload lives at `?_rsc=1.<digest>`, so\n * anything aimed at that cache entry must carry the prefix and therefore\n * gets validated; anything without it cannot be addressing a payload URL at\n * all, and is exempt as application data. An attacker cannot both hit the\n * victim's cache key and dodge the check.\n *\n * The version component also gives the derivation a migration path: the\n * client and the origin must agree byte for byte, so a future change to the\n * canonical form can be rolled out by bumping this instead of a flag day.\n */\nconst KEY_PREFIX = '1.';\n\n/**\n * The request headers that vary an RSC payload response, in canonical\n * casing — this list is also emitted verbatim as the response's `Vary`\n * tokens (`server/pipeline.ts`), since \"what varies the response\" is one\n * question with one answer, not two lists that happen to agree.\n *\n * This list is the contract, and it is enforced rather than trusted:\n * `tests/rsc-cache-key.test.ts` asserts that the header names\n * `buildRscHeaders()` can emit are exactly this set. A header added to the\n * request without being added here fails that test, because a varying input\n * outside the key is precisely the cache-poisoning hazard the key exists to\n * close.\n *\n * **No credentials, session identifiers, or user-supplied content may be\n * added.** Every value here is hashed into a URL, and URLs are logged by\n * proxies, CDNs, and origin access logs. `fnv1aHash` is a cache-key hash,\n * not a KDF — a low-entropy secret would be recoverable by brute force.\n * Authentication travels on cookies, which never enter the key.\n */\nexport const RSC_KEY_HEADERS = [\n 'Accept',\n 'X-Timber-State-Tree',\n 'X-Timber-URL',\n 'X-Timber-Deployment-Id',\n] as const;\n\n/**\n * Whether a value could be a key this module produced.\n *\n * `_rsc` is not a reserved parameter name — an application may already use\n * it for its own search state, including for a value that happens to look\n * like a digest. Anything without the `KEY_PREFIX` is therefore application\n * data, not a claim on a payload cache key, and the origin guard leaves it\n * alone rather than penalizing the response.\n *\n * Derived from `KEY_PREFIX` and `KEY_HEX_LENGTH` rather than spelled again,\n * so the shape cannot drift from the digest that has to satisfy it.\n *\n * Ignoring a malformed value costs no protection: clients only ever send\n * well-formed keys, so a URL bearing a malformed one is an address no\n * legitimate request will ever ask for, and nothing can be poisoned at an\n * address nobody reads.\n */\nexport function isRscCacheKeyShape(value: string): boolean {\n if (!value.startsWith(KEY_PREFIX)) return false;\n const digest = value.slice(KEY_PREFIX.length);\n return digest.length === KEY_HEX_LENGTH && /^[0-9a-f]+$/.test(digest);\n}\n\n/**\n * The query parameter carrying the payload cache key.\n *\n * Spelled here rather than at each of the four places that read or write it\n * — the client that appends it, the origin guard that validates it, and the\n * strip below — because it is a wire contract between two independent\n * implementations, exactly like the digest itself.\n */\nexport const RSC_KEY_PARAM = '_rsc';\n\n// ─── Keeping the key out of application state ────────────────────────────\n\n/**\n * Decode one raw `name` or `value` the way `URLSearchParams` does:\n * `application/x-www-form-urlencoded`, so `+` is a space.\n *\n * Malformed percent-escapes throw in `decodeURIComponent`. `URLSearchParams`\n * leaves those bytes as-is rather than throwing, and so do we — a pair we\n * cannot decode is by definition not the framework's, so it is kept.\n */\nfunction formDecode(raw: string): string {\n try {\n return decodeURIComponent(raw.replace(/\\+/g, ' '));\n } catch {\n return raw;\n }\n}\n\n/**\n * Remove framework-issued `_rsc` values from a raw query string.\n *\n * Only values matching `isRscCacheKeyShape` are removed. `_rsc` is not a\n * reserved name (see that function), so `/search?_rsc=foo` is application\n * state and survives — the same exemption the origin guard applies, derived\n * from the same predicate so the two cannot disagree about what \"ours\"\n * means.\n *\n * Operates on the raw string rather than round-tripping through\n * `URLSearchParams`, so every surviving pair keeps its original bytes.\n * Re-serializing would rewrite `?b` as `?b=` and `?a=%7E` as `?a=~` on RSC\n * navigations only, which is the same class of inconsistency this function\n * exists to remove.\n *\n * Matching decodes the name, because `?%5Frsc=<key>` is a `_rsc` parameter\n * as far as `URLSearchParams` is concerned — the same reasoning as the\n * guard's fast path.\n *\n * @param search - `url.search`, with or without the leading `?`.\n * @returns The query string including a leading `?`, or `''` if empty.\n */\nexport function stripRscCacheKey(search: string): string {\n const query = search.startsWith('?') ? search.slice(1) : search;\n if (query === '') return '';\n const kept = query.split('&').filter((pair) => {\n const eq = pair.indexOf('=');\n if (formDecode(eq === -1 ? pair : pair.slice(0, eq)) !== RSC_KEY_PARAM) return true;\n return !isRscCacheKeyShape(eq === -1 ? '' : formDecode(pair.slice(eq + 1)));\n });\n const result = kept.join('&');\n return result === '' ? '' : `?${result}`;\n}\n\n/** A request's search state as application code should see it. */\nexport interface AppVisibleSearch {\n /** Parsed params, with the framework's cache key removed. */\n params: URLSearchParams;\n /** The matching raw query string — `''` or `?…`. */\n search: string;\n}\n\n/**\n * The search state application code sees, for any request URL.\n *\n * The `_rsc` key rides on the payload URL of every RSC navigation and on no\n * other request, so reading search params straight off `req.url` makes the\n * same page observe different search state depending on whether it was\n * reached by a full load or a client navigation — and lets the cache key\n * leak into whatever the page builds from it: a canonical URL, a pagination\n * link, an analytics payload (TIM-1272).\n *\n * Every application-facing derivation of search state goes through here.\n * `params` and `search` are returned together, from one strip, because they\n * are two views of one answer and were previously two expressions that had\n * to agree.\n *\n * The raw request URL is deliberately untouched: `server/rsc-cache-key-guard.ts`\n * still reads the parameter from `req.url` to bind the key to the request.\n */\nexport function appVisibleSearch(url: URL): AppVisibleSearch {\n const search = stripRscCacheKey(url.search);\n return { params: new URLSearchParams(search), search };\n}\n\n/**\n * Reads a header value by name. Must be case-insensitive — `Headers.get()`\n * already is, and `recordLookup` below makes a plain record so.\n */\nexport type HeaderLookup = (name: string) => string | null | undefined;\n\n/**\n * Compute the `_rsc` cache key for a request.\n *\n * Absent headers are omitted rather than sent as empty, so \"header missing\"\n * and \"header present but empty\" produce different keys.\n *\n * Values are length-prefixed rather than delimiter-separated. Any delimiter\n * can be forged by a value that contains it: with a `\\0` separator, an\n * `accept` of `a\\nx-timber-url\\0b` serializes identically to an `accept` of\n * `a` alongside an `x-timber-url` of `b`, which would let one header claim\n * another's key. HTTP forbids control characters in header values and both\n * `fetch()` and the server runtime reject them, so this is defense in depth\n * — but a length prefix is unambiguous for *any* content, which is a\n * property worth having in a function whose whole job is to be agreed on by\n * two independent implementations.\n *\n * SHA-256, truncated to 128 bits. A fast non-cryptographic hash is the\n * obvious choice for a cache key and is the wrong one here: the origin\n * *compares* this value against a recomputed one, which makes it a check.\n * FNV-1a — used for timber's other cache keys — is a multiply-xor over a\n * fixed field, so an attacker controlling a few bytes of any input (their\n * own `X-Timber-URL`, say) can solve for a chosen digest rather than search\n * for one, and forge a key belonging to somebody else.\n *\n * Returns `null` when no digest is available — `crypto.subtle` is absent in\n * non-secure browsing contexts (plain `http://` on a LAN address). Callers\n * must treat that as \"no key\", never as \"key matches\": the client omits the\n * parameter and the server refuses to share-cache. That returns those\n * clients to the pre-TIM-1268 posture, where `Vary` alone separates HTML\n * from Flight — acceptable, because a non-secure origin has no shared-CDN\n * caching story to protect in the first place.\n */\nexport async function rscCacheKey(lookup: HeaderLookup): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n let canonical = '';\n for (const name of RSC_KEY_HEADERS) {\n const raw = lookup(name);\n if (raw == null) continue;\n const value = name === 'X-Timber-State-Tree' ? stateTreeKeyValue(raw) : raw;\n // Lowercased in the canonical form so the two implementations cannot\n // disagree over the casing of the constant they share.\n canonical += `${name.toLowerCase()}:${value.length}:${value}`;\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(canonical));\n let hex = '';\n for (const byte of new Uint8Array(digest, 0, KEY_HEX_LENGTH / 2)) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return KEY_PREFIX + hex;\n}\n\n/**\n * The part of an `X-Timber-State-Tree` value that enters the key: everything\n * but `documents`.\n *\n * `documents` carries the key digests of `'document'` segments, and a digest\n * is derived from cookie values (design/53-segment-lifetime.md §\"The key\n * digest\"). It is keyed and per render, so nothing can be read from it — but\n * a URL is logged by proxies, CDNs and analytics, and a value derived from a\n * cookie does not belong in one. The response still varies on it, so a\n * request that carries `documents` is made unstorable by shared caches\n * instead (`server/rsc-cache-key-guard.ts`).\n *\n * A value that is not a JSON object enters the key unchanged: it is not a\n * state tree a client sent, and dropping it would let two different headers\n * share a key.\n */\nexport function stateTreeKeyValue(value: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return value;\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return value;\n if (!('documents' in parsed)) return value;\n const { documents: _documents, ...rest } = parsed as Record<string, unknown>;\n void _documents;\n return JSON.stringify(rest);\n}\n\n/**\n * Whether an `X-Timber-State-Tree` value carries `'document'` key digests —\n * a request whose response varies on an input `rscCacheKey` leaves out.\n */\nexport function stateTreeHasDocuments(value: string | null): boolean {\n return value !== null && stateTreeKeyValue(value) !== value;\n}\n\n/**\n * An unverifiable stand-in key, for the one case where the digest cannot be\n * computed: `crypto.subtle` is absent in non-secure browsing contexts.\n * `crypto.getRandomValues` is not gated that way, so it is available exactly\n * where the digest is not.\n *\n * Carries `KEY_PREFIX` like any other key, so the origin reads it as a claim\n * it cannot verify — and refuses to share-cache the response — rather than\n * exempting it as application data. Lives here so the prefix has one home.\n */\nexport function randomRscCacheKey(): string {\n const bytes = new Uint8Array(KEY_HEX_LENGTH / 2);\n globalThis.crypto.getRandomValues(bytes);\n return KEY_PREFIX + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** Build a case-insensitive lookup over a plain header record. */\nexport function recordLookup(headers: Record<string, string>): HeaderLookup {\n const lowered: Record<string, string> = {};\n for (const name of Object.keys(headers)) {\n lowered[name.toLowerCase()] = headers[name];\n }\n return (name) => lowered[name.toLowerCase()];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;AAqBvB,IAAM,aAAa;;;;;;;;;;;;;;;;;;;;AAqBnB,IAAa,kBAAkB;CAC7B;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,mBAAmB,OAAwB;CACzD,IAAI,CAAC,MAAM,WAAW,UAAU,GAAG,OAAO;CAC1C,MAAM,SAAS,MAAM,MAAM,CAAiB;CAC5C,OAAO,OAAO,WAAW,kBAAkB,cAAc,KAAK,MAAM;AACtE;;;;;;;;;AAUA,IAAa,gBAAgB;;;;;;;;;AAY7B,SAAS,WAAW,KAAqB;CACvC,IAAI;EACF,OAAO,mBAAmB,IAAI,QAAQ,OAAO,GAAG,CAAC;CACnD,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,QAAQ,OAAO,WAAW,GAAG,IAAI,OAAO,MAAM,CAAC,IAAI;CACzD,IAAI,UAAU,IAAI,OAAO;CAMzB,MAAM,SALO,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS;EAC7C,MAAM,KAAK,KAAK,QAAQ,G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nF,IAAI,EAAE,eAAe,SAAS,OAAO;CACrC,MAAM,EAAE,WAAW,YAAY,GAAG,SAAS;CAE3C,OAAO,KAAK,UAAU,IAAI;AAC5B;;;;;AAMA,SAAgB,sBAAsB,OAA+B;CACnE,OAAO,UAAU,QAAQ,kBAAkB,KAAK,MAAM;AACxD;;;;;;;;;;;AAYA,SAAgB,oBAA4B;CAC1C,MAAM,QAAQ,IAAI,WAAW,iBAAiB,CAAC;CAC/C,WAAW,OAAO,gBAAgB,KAAK;CACvC,OAAO,aAAa,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AACpF;;AAGA,SAAgB,aAAa,SAA+C;CAC1E,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,GACpC,QAAQ,KAAK,YAAY,KAAK,QAAQ;CAExC,QAAQ,SAAS,QAAQ,KAAK,YAAY;AAC5C"}
@@ -1,7 +1,7 @@
1
1
  import { i as DEFAULT_PAGE_EXTENSIONS, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
2
2
  import { a as findOrderDependentCollision, i as validateInterceptionPlacement, n as computeInterceptedBase, r as computeInterceptedUrlBase } from "./interception-CtNt9jPt.js";
3
3
  import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-MXNjWOt5.js";
4
- import { b as swallow } from "./logger-DmRR9tmZ.js";
4
+ import { b as swallow } from "./logger-C4m8rfMy.js";
5
5
  import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
6
6
  import { parseAst } from "vite";
7
7
  import { basename, extname, join } from "node:path";
@@ -267,9 +267,14 @@ function readFileCached(filePath) {
267
267
  * default exports, replacing the regex-based approach that was fragile
268
268
  * with TypeScript syntax (type exports, `as` aliases, comments, etc.).
269
269
  */
270
- function tryParse(source) {
270
+ /**
271
+ * Parse a module. `lang` defaults to `tsx`; pass `ts` for `.ts` files, where
272
+ * an angle-bracket cast or a generic arrow (`<T>(x: T) => x`) is valid
273
+ * TypeScript but a TSX parse error.
274
+ */
275
+ function tryParse(source, lang = "tsx") {
271
276
  try {
272
- return parseAst(source, { lang: "tsx" });
277
+ return parseAst(source, { lang });
273
278
  } catch {
274
279
  return null;
275
280
  }
@@ -473,82 +478,6 @@ function fileHasStarExport(filePath) {
473
478
  return false;
474
479
  }
475
480
  }
476
- function extractLiteralValue(node) {
477
- if (!node) return void 0;
478
- const n = node;
479
- if (n.type === "Literal") return n.value;
480
- if (n.type === "UnaryExpression" && n.operator === "-" && n.argument?.type === "Literal") return -n.argument.value;
481
- if (n.type === "ArrayExpression") {
482
- const elements = n.elements;
483
- if (!elements) return void 0;
484
- const result = [];
485
- for (const el of elements) {
486
- const v = extractLiteralValue(el);
487
- if (v === void 0) return void 0;
488
- result.push(v);
489
- }
490
- return result;
491
- }
492
- }
493
- function extractObjectLiteral(node) {
494
- if (node.type !== "ObjectExpression") return void 0;
495
- const props = node.properties;
496
- if (!props) return void 0;
497
- const result = {};
498
- for (const prop of props) {
499
- const p = prop;
500
- if (p.type === "SpreadElement") return void 0;
501
- if (p.type !== "Property" || p.computed) return void 0;
502
- const key = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : void 0;
503
- if (!key) return void 0;
504
- const value = extractLiteralValue(p.value);
505
- if (value === void 0) return void 0;
506
- result[key] = value;
507
- }
508
- return result;
509
- }
510
- /**
511
- * Extract the value of `export const prerender` from a file.
512
- * Returns undefined if the file doesn't export `prerender` or can't be parsed.
513
- *
514
- * Supports:
515
- * export const prerender = true;
516
- * export const prerender = false;
517
- * export const prerender = { ttl: 3600, tags: ['docs'] };
518
- */
519
- function getPrerenderExport(filePath) {
520
- if (!existsSync(filePath)) return void 0;
521
- try {
522
- const program = tryParse(readFileCached(filePath));
523
- if (!program) return void 0;
524
- for (const stmt of program.body) {
525
- if (stmt.type !== "ExportNamedDeclaration") continue;
526
- if (stmt.exportKind === "type") continue;
527
- if (!stmt.declaration) continue;
528
- const decl = stmt.declaration;
529
- if (decl.type !== "VariableDeclaration") continue;
530
- const declarations = decl.declarations;
531
- if (!declarations) continue;
532
- for (const d of declarations) {
533
- if (d.id?.name !== "prerender" || !d.init) continue;
534
- const init = d.init;
535
- if (init.type === "Literal" && typeof init.value === "boolean") return init.value;
536
- if (init.type === "ObjectExpression") {
537
- const obj = extractObjectLiteral(init);
538
- if (!obj) return void 0;
539
- const result = {};
540
- if ("ttl" in obj && typeof obj.ttl === "number") result.ttl = obj.ttl;
541
- if ("tags" in obj && Array.isArray(obj.tags) && obj.tags.every((t) => typeof t === "string")) result.tags = obj.tags;
542
- return result;
543
- }
544
- return;
545
- }
546
- }
547
- return;
548
- } catch {
549
- return;
550
- }
551
- }
552
481
  function getCsrfExport(filePath) {
553
482
  if (!existsSync(filePath)) return "absent";
554
483
  const program = tryParse(readFileCached(filePath));
@@ -615,6 +544,10 @@ function fileHasDirective(filePath, directive) {
615
544
  return false;
616
545
  }
617
546
  }
547
+ /** Route files the AST checks can read; `.mdx` and `.json` are skipped. */
548
+ function isScriptExtension(ext) {
549
+ return ext === "tsx" || ext === "ts" || ext === "jsx" || ext === "js";
550
+ }
618
551
  // src/routing/scanner.ts
619
552
  /**
620
553
  * Route discovery scanner.
@@ -1039,6 +972,6 @@ function findScriptExtFile(dirPath, name) {
1039
972
  } catch {}
1040
973
  }
1041
974
  }
1042
- export { fileHasDefaultExport as a, getCsrfExport as c, fileHasAnyExport as i, getPrerenderExport as l, scanRoutes as n, fileHasDirective as o, fileDefaultExportIsLocalValue as r, fileHasStarExport as s, isRouteConventionFile as t, readFileCached as u };
975
+ export { fileHasAnyExport as a, fileHasStarExport as c, patternBinds as d, tryParse as f, fileDefaultExportIsLocalValue as i, getCsrfExport as l, scanRoutes as n, fileHasDefaultExport as o, readFileCached as p, TRANSPARENT_WRAPPERS as r, fileHasDirective as s, isRouteConventionFile as t, isScriptExtension as u };
1043
976
 
1044
- //# sourceMappingURL=scanner-C9Lrf77z.js.map
977
+ //# sourceMappingURL=scanner-CCEHN9Jg.js.map