@timber-js/app 0.2.0-alpha.20 → 0.2.0-alpha.201

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 (1332) hide show
  1. package/LICENSE +8 -0
  2. package/agent-skill.md +346 -0
  3. package/bin/timber.mjs +15 -1
  4. package/dist/_chunks/actions-HUdJADAD.js +345 -0
  5. package/dist/_chunks/actions-HUdJADAD.js.map +1 -0
  6. package/dist/_chunks/als-registry-C6kcfprT.js +41 -0
  7. package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -0
  8. package/dist/_chunks/als-slots-BEEIPKYm.js +26 -0
  9. package/dist/_chunks/als-slots-BEEIPKYm.js.map +1 -0
  10. package/dist/_chunks/base-path-DaQrzbez.js +80 -0
  11. package/dist/_chunks/base-path-DaQrzbez.js.map +1 -0
  12. package/dist/_chunks/build-manifest-DWppEdLB.js +86 -0
  13. package/dist/_chunks/build-manifest-DWppEdLB.js.map +1 -0
  14. package/dist/_chunks/build-output-helper-9dqCv1pZ.js +370 -0
  15. package/dist/_chunks/build-output-helper-9dqCv1pZ.js.map +1 -0
  16. package/dist/_chunks/cache-api-CAPbZTga.js +1149 -0
  17. package/dist/_chunks/cache-api-CAPbZTga.js.map +1 -0
  18. package/dist/_chunks/canonicalize-CgHoscYO.js +66 -0
  19. package/dist/_chunks/canonicalize-CgHoscYO.js.map +1 -0
  20. package/dist/_chunks/chains-CBNA0Ozj.js +412 -0
  21. package/dist/_chunks/chains-CBNA0Ozj.js.map +1 -0
  22. package/dist/_chunks/cli-check-BzMGuIH6.js +293 -0
  23. package/dist/_chunks/cli-check-BzMGuIH6.js.map +1 -0
  24. package/dist/_chunks/cli-schema-sync-DnXqcIIj.js +299 -0
  25. package/dist/_chunks/cli-schema-sync-DnXqcIIj.js.map +1 -0
  26. package/dist/_chunks/cloudflare-DxX1SU0g.js +1290 -0
  27. package/dist/_chunks/cloudflare-DxX1SU0g.js.map +1 -0
  28. package/dist/_chunks/codec-registry-oOUxugz3.js +21 -0
  29. package/dist/_chunks/codec-registry-oOUxugz3.js.map +1 -0
  30. package/dist/_chunks/convention-lint-DHOFvX5s.js +803 -0
  31. package/dist/_chunks/convention-lint-DHOFvX5s.js.map +1 -0
  32. package/dist/_chunks/csp-nonce-hOGniaG4.js +227 -0
  33. package/dist/_chunks/csp-nonce-hOGniaG4.js.map +1 -0
  34. package/dist/_chunks/dev-server-DioP7tkQ.js +2288 -0
  35. package/dist/_chunks/dev-server-DioP7tkQ.js.map +1 -0
  36. package/dist/_chunks/dist-DtrJyBbw.js +386 -0
  37. package/dist/_chunks/dist-DtrJyBbw.js.map +1 -0
  38. package/dist/_chunks/error-boundary-BQKxl6EX.js +1044 -0
  39. package/dist/_chunks/error-boundary-BQKxl6EX.js.map +1 -0
  40. package/dist/_chunks/fast-hash-C-tVYrLb.js +41 -0
  41. package/dist/_chunks/fast-hash-C-tVYrLb.js.map +1 -0
  42. package/dist/_chunks/file-cache-Dw6BJPG7.js +458 -0
  43. package/dist/_chunks/file-cache-Dw6BJPG7.js.map +1 -0
  44. package/dist/_chunks/format-BKclgVbk.js +14 -0
  45. package/dist/_chunks/format-BKclgVbk.js.map +1 -0
  46. package/dist/_chunks/fs-identity-D7vb6GdI.js +208 -0
  47. package/dist/_chunks/fs-identity-D7vb6GdI.js.map +1 -0
  48. package/dist/_chunks/graph-cache-Cv3njEH8.js +304 -0
  49. package/dist/_chunks/graph-cache-Cv3njEH8.js.map +1 -0
  50. package/dist/_chunks/href-validation-BIrxavIy.js +213 -0
  51. package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
  52. package/dist/_chunks/json-lossy-check-ClNvBM_3.js +63 -0
  53. package/dist/_chunks/json-lossy-check-ClNvBM_3.js.map +1 -0
  54. package/dist/_chunks/live-graph-VjHFF5EV.js +150 -0
  55. package/dist/_chunks/live-graph-VjHFF5EV.js.map +1 -0
  56. package/dist/_chunks/logger-DqJ2VoAY.js +1476 -0
  57. package/dist/_chunks/logger-DqJ2VoAY.js.map +1 -0
  58. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → metadata-routes-DSDjM_hJ.js} +71 -27
  59. package/dist/_chunks/metadata-routes-DSDjM_hJ.js.map +1 -0
  60. package/dist/_chunks/navigation-context-D0TU0Jog.js +135 -0
  61. package/dist/_chunks/navigation-context-D0TU0Jog.js.map +1 -0
  62. package/dist/_chunks/navigation-root-mHSK9psY.js +126 -0
  63. package/dist/_chunks/navigation-root-mHSK9psY.js.map +1 -0
  64. package/dist/_chunks/param-value-C8TNYchQ.js +66 -0
  65. package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
  66. package/dist/_chunks/plugin-context-8idfR3UZ.js +321 -0
  67. package/dist/_chunks/plugin-context-8idfR3UZ.js.map +1 -0
  68. package/dist/_chunks/poison-rules-DoEhbqaY.js +110 -0
  69. package/dist/_chunks/poison-rules-DoEhbqaY.js.map +1 -0
  70. package/dist/_chunks/poison-scan-lEbz4pQE.js +101 -0
  71. package/dist/_chunks/poison-scan-lEbz4pQE.js.map +1 -0
  72. package/dist/_chunks/purge-store-Byr8XOjU.js +14 -0
  73. package/dist/_chunks/purge-store-Byr8XOjU.js.map +1 -0
  74. package/dist/_chunks/resolve-schema-CBR6Lm4i.js +50 -0
  75. package/dist/_chunks/resolve-schema-CBR6Lm4i.js.map +1 -0
  76. package/dist/_chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  77. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js +243 -0
  78. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js.map +1 -0
  79. package/dist/_chunks/rsc-media-type-DDc7duTD.js +61 -0
  80. package/dist/_chunks/rsc-media-type-DDc7duTD.js.map +1 -0
  81. package/dist/_chunks/rsc-payload-path-B_LBodc2.js +48 -0
  82. package/dist/_chunks/rsc-payload-path-B_LBodc2.js.map +1 -0
  83. package/dist/_chunks/scan-BoP17W3w.js +140 -0
  84. package/dist/_chunks/scan-BoP17W3w.js.map +1 -0
  85. package/dist/_chunks/scanner-B_tnqFcF.js +1671 -0
  86. package/dist/_chunks/scanner-B_tnqFcF.js.map +1 -0
  87. package/dist/_chunks/schema-bridge-C83xa9lT.js +199 -0
  88. package/dist/_chunks/schema-bridge-C83xa9lT.js.map +1 -0
  89. package/dist/_chunks/segment-classify-C539Pa2O.js +197 -0
  90. package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -0
  91. package/dist/_chunks/segment-context-D9_89u34.js +34 -0
  92. package/dist/_chunks/segment-context-D9_89u34.js.map +1 -0
  93. package/dist/_chunks/segment-keys-D5hu1hz4.js +62 -0
  94. package/dist/_chunks/segment-keys-D5hu1hz4.js.map +1 -0
  95. package/dist/_chunks/singleflight-2lUWfcAk.js +54 -0
  96. package/dist/_chunks/singleflight-2lUWfcAk.js.map +1 -0
  97. package/dist/_chunks/sizeof-lXffQ1Vr.js +35 -0
  98. package/dist/_chunks/sizeof-lXffQ1Vr.js.map +1 -0
  99. package/dist/_chunks/{ssr-data-MjmprTmO.js → ssr-data-D6T6Y3ef.js} +3 -31
  100. package/dist/_chunks/ssr-data-D6T6Y3ef.js.map +1 -0
  101. package/dist/_chunks/state-FippDgxN.js +52 -0
  102. package/dist/_chunks/state-FippDgxN.js.map +1 -0
  103. package/dist/_chunks/status-page-marker-DwQBrLBz.js +496 -0
  104. package/dist/_chunks/status-page-marker-DwQBrLBz.js.map +1 -0
  105. package/dist/_chunks/tree-match-CdbvYTBz.js +122 -0
  106. package/dist/_chunks/tree-match-CdbvYTBz.js.map +1 -0
  107. package/dist/_chunks/use-query-states-I3JMng6J.js +226 -0
  108. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -0
  109. package/dist/_chunks/walkers-Cm3PC5JT.js +144 -0
  110. package/dist/_chunks/walkers-Cm3PC5JT.js.map +1 -0
  111. package/dist/adapters/build-output-helper.d.ts +72 -0
  112. package/dist/adapters/build-output-helper.d.ts.map +1 -0
  113. package/dist/adapters/cloudflare-dev.d.ts +109 -0
  114. package/dist/adapters/cloudflare-dev.d.ts.map +1 -0
  115. package/dist/adapters/cloudflare-dev.js +74 -0
  116. package/dist/adapters/cloudflare-dev.js.map +1 -0
  117. package/dist/adapters/cloudflare-kv-cache.d.ts +65 -0
  118. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -0
  119. package/dist/adapters/cloudflare-kv-cache.js +123 -0
  120. package/dist/adapters/cloudflare-kv-cache.js.map +1 -0
  121. package/dist/adapters/cloudflare.d.ts +200 -22
  122. package/dist/adapters/cloudflare.d.ts.map +1 -1
  123. package/dist/adapters/cloudflare.js +2 -188
  124. package/dist/adapters/compress-module.d.ts +17 -4
  125. package/dist/adapters/compress-module.d.ts.map +1 -1
  126. package/dist/adapters/fs-identity.d.ts +64 -0
  127. package/dist/adapters/fs-identity.d.ts.map +1 -0
  128. package/dist/adapters/nitro-presets.d.ts +37 -0
  129. package/dist/adapters/nitro-presets.d.ts.map +1 -0
  130. package/dist/adapters/nitro-preview.d.ts +32 -0
  131. package/dist/adapters/nitro-preview.d.ts.map +1 -0
  132. package/dist/adapters/nitro.d.ts +66 -37
  133. package/dist/adapters/nitro.d.ts.map +1 -1
  134. package/dist/adapters/nitro.js +457 -300
  135. package/dist/adapters/nitro.js.map +1 -1
  136. package/dist/adapters/shared.d.ts +62 -0
  137. package/dist/adapters/shared.d.ts.map +1 -0
  138. package/dist/adapters/types.d.ts +28 -6
  139. package/dist/adapters/types.d.ts.map +1 -1
  140. package/dist/analyze/chains.d.ts +124 -0
  141. package/dist/analyze/chains.d.ts.map +1 -0
  142. package/dist/analyze/classify.d.ts +150 -0
  143. package/dist/analyze/classify.d.ts.map +1 -0
  144. package/dist/analyze/crawl-entry.d.ts +17 -0
  145. package/dist/analyze/crawl-entry.d.ts.map +1 -0
  146. package/dist/analyze/crawl-entry.js +313 -0
  147. package/dist/analyze/crawl-entry.js.map +1 -0
  148. package/dist/analyze/crawl.d.ts +134 -0
  149. package/dist/analyze/crawl.d.ts.map +1 -0
  150. package/dist/analyze/graph-cache.d.ts +104 -0
  151. package/dist/analyze/graph-cache.d.ts.map +1 -0
  152. package/dist/analyze/graph-command.d.ts +43 -0
  153. package/dist/analyze/graph-command.d.ts.map +1 -0
  154. package/dist/analyze/graph-command.js +472 -0
  155. package/dist/analyze/graph-command.js.map +1 -0
  156. package/dist/analyze/live-graph.d.ts +81 -0
  157. package/dist/analyze/live-graph.d.ts.map +1 -0
  158. package/dist/analyze/poison-rules.d.ts +72 -0
  159. package/dist/analyze/poison-rules.d.ts.map +1 -0
  160. package/dist/analyze/poison-scan.d.ts +48 -0
  161. package/dist/analyze/poison-scan.d.ts.map +1 -0
  162. package/dist/analyze/scan.d.ts +73 -0
  163. package/dist/analyze/scan.d.ts.map +1 -0
  164. package/dist/cache/cache-api.d.ts +48 -0
  165. package/dist/cache/cache-api.d.ts.map +1 -0
  166. package/dist/cache/fast-hash.d.ts +5 -0
  167. package/dist/cache/fast-hash.d.ts.map +1 -1
  168. package/dist/cache/handler-store.d.ts +33 -0
  169. package/dist/cache/handler-store.d.ts.map +1 -0
  170. package/dist/cache/index.d.ts +32 -9
  171. package/dist/cache/index.d.ts.map +1 -1
  172. package/dist/cache/index.js +3 -326
  173. package/dist/cache/invalidation-epoch.d.ts +43 -0
  174. package/dist/cache/invalidation-epoch.d.ts.map +1 -0
  175. package/dist/cache/json-lossy-check.d.ts +11 -0
  176. package/dist/cache/json-lossy-check.d.ts.map +1 -0
  177. package/dist/cache/redis-handler.d.ts +141 -9
  178. package/dist/cache/redis-handler.d.ts.map +1 -1
  179. package/dist/cache/singleflight.d.ts +21 -2
  180. package/dist/cache/singleflight.d.ts.map +1 -1
  181. package/dist/cache/sizeof.d.ts +22 -0
  182. package/dist/cache/sizeof.d.ts.map +1 -0
  183. package/dist/cache/stable-stringify.d.ts +9 -0
  184. package/dist/cache/stable-stringify.d.ts.map +1 -1
  185. package/dist/cache/store.d.ts +53 -0
  186. package/dist/cache/store.d.ts.map +1 -0
  187. package/dist/cache/stores/cloudflare-kv.d.ts +38 -0
  188. package/dist/cache/stores/cloudflare-kv.d.ts.map +1 -0
  189. package/dist/cache/stores/cloudflare-kv.js +29 -0
  190. package/dist/cache/stores/cloudflare-kv.js.map +1 -0
  191. package/dist/cache/stores/memory.d.ts +42 -0
  192. package/dist/cache/stores/memory.d.ts.map +1 -0
  193. package/dist/cache/stores/memory.js +90 -0
  194. package/dist/cache/stores/memory.js.map +1 -0
  195. package/dist/cache/stores/redis.d.ts +69 -0
  196. package/dist/cache/stores/redis.d.ts.map +1 -0
  197. package/dist/cache/stores/redis.js +35 -0
  198. package/dist/cache/stores/redis.js.map +1 -0
  199. package/dist/cache/stores/vercel.d.ts +36 -0
  200. package/dist/cache/stores/vercel.d.ts.map +1 -0
  201. package/dist/cache/stores/vercel.js +33 -0
  202. package/dist/cache/stores/vercel.js.map +1 -0
  203. package/dist/cache/tag-aware-handler.d.ts +52 -0
  204. package/dist/cache/tag-aware-handler.d.ts.map +1 -0
  205. package/dist/cache/timber-cache.d.ts +21 -11
  206. package/dist/cache/timber-cache.d.ts.map +1 -1
  207. package/dist/cdn/cloudflare-purge.d.ts +23 -0
  208. package/dist/cdn/cloudflare-purge.d.ts.map +1 -0
  209. package/dist/cdn/cloudflare-purge.js +30 -0
  210. package/dist/cdn/cloudflare-purge.js.map +1 -0
  211. package/dist/cdn/fastly-purge.d.ts +25 -0
  212. package/dist/cdn/fastly-purge.d.ts.map +1 -0
  213. package/dist/cdn/fastly-purge.js +33 -0
  214. package/dist/cdn/fastly-purge.js.map +1 -0
  215. package/dist/cdn/headers.d.ts +97 -0
  216. package/dist/cdn/headers.d.ts.map +1 -0
  217. package/dist/cdn/index.d.ts +5 -0
  218. package/dist/cdn/index.d.ts.map +1 -0
  219. package/dist/cdn/index.js +94 -0
  220. package/dist/cdn/index.js.map +1 -0
  221. package/dist/cdn/purge-store.d.ts +23 -0
  222. package/dist/cdn/purge-store.d.ts.map +1 -0
  223. package/dist/cdn/workers-cache-purge.d.ts +20 -0
  224. package/dist/cdn/workers-cache-purge.d.ts.map +1 -0
  225. package/dist/cdn/workers-cache-purge.js +35 -0
  226. package/dist/cdn/workers-cache-purge.js.map +1 -0
  227. package/dist/cli-check.d.ts +163 -0
  228. package/dist/cli-check.d.ts.map +1 -0
  229. package/dist/cli-schema-sync.d.ts +59 -0
  230. package/dist/cli-schema-sync.d.ts.map +1 -0
  231. package/dist/cli.d.ts +81 -9
  232. package/dist/cli.d.ts.map +1 -1
  233. package/dist/cli.js +216 -51
  234. package/dist/cli.js.map +1 -1
  235. package/dist/client/browser-dev.d.ts +37 -1
  236. package/dist/client/browser-dev.d.ts.map +1 -1
  237. package/dist/client/browser-entry/action-dispatch.d.ts +19 -0
  238. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  239. package/dist/client/browser-entry/action-queue.d.ts +63 -0
  240. package/dist/client/browser-entry/action-queue.d.ts.map +1 -0
  241. package/dist/client/browser-entry/hmr.d.ts +21 -0
  242. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  243. package/dist/client/browser-entry/hydrate.d.ts +63 -0
  244. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  245. package/dist/client/browser-entry/index.d.ts +30 -0
  246. package/dist/client/browser-entry/index.d.ts.map +1 -0
  247. package/dist/client/browser-entry/post-hydration.d.ts +29 -0
  248. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  249. package/dist/client/browser-entry/router-init.d.ts +46 -0
  250. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  251. package/dist/client/browser-entry/rsc-stream.d.ts +32 -0
  252. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  253. package/dist/client/browser-entry/scroll.d.ts +28 -0
  254. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  255. package/dist/client/deny-last-resort.d.ts +29 -0
  256. package/dist/client/deny-last-resort.d.ts.map +1 -0
  257. package/dist/client/error-boundary.d.ts +55 -7
  258. package/dist/client/error-boundary.d.ts.map +1 -1
  259. package/dist/client/error-boundary.js +2 -126
  260. package/dist/client/error-reconstituter.d.ts +61 -0
  261. package/dist/client/error-reconstituter.d.ts.map +1 -0
  262. package/dist/client/form.d.ts +16 -27
  263. package/dist/client/form.d.ts.map +1 -1
  264. package/dist/client/global-context.d.ts +15 -0
  265. package/dist/client/global-context.d.ts.map +1 -0
  266. package/dist/client/history.d.ts +50 -9
  267. package/dist/client/history.d.ts.map +1 -1
  268. package/dist/client/index.d.ts +20 -33
  269. package/dist/client/index.d.ts.map +1 -1
  270. package/dist/client/index.js +323 -1148
  271. package/dist/client/index.js.map +1 -1
  272. package/dist/client/internal.d.ts +20 -0
  273. package/dist/client/internal.d.ts.map +1 -0
  274. package/dist/client/internal.js +818 -0
  275. package/dist/client/internal.js.map +1 -0
  276. package/dist/client/link.d.ts +63 -60
  277. package/dist/client/link.d.ts.map +1 -1
  278. package/dist/client/location-search.d.ts +12 -0
  279. package/dist/client/location-search.d.ts.map +1 -0
  280. package/dist/client/navigation-api.d.ts +121 -0
  281. package/dist/client/navigation-api.d.ts.map +1 -0
  282. package/dist/client/navigation-commit.d.ts +98 -0
  283. package/dist/client/navigation-commit.d.ts.map +1 -0
  284. package/dist/client/navigation-context.d.ts +51 -31
  285. package/dist/client/navigation-context.d.ts.map +1 -1
  286. package/dist/client/navigation-root.d.ts +98 -0
  287. package/dist/client/navigation-root.d.ts.map +1 -0
  288. package/dist/client/navigation-transition.d.ts +187 -0
  289. package/dist/client/navigation-transition.d.ts.map +1 -0
  290. package/dist/client/nuqs-adapter.d.ts +1 -1
  291. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  292. package/dist/client/params-context.d.ts +81 -0
  293. package/dist/client/params-context.d.ts.map +1 -0
  294. package/dist/client/react-root.d.ts +44 -0
  295. package/dist/client/react-root.d.ts.map +1 -0
  296. package/dist/client/router-effects.d.ts +130 -0
  297. package/dist/client/router-effects.d.ts.map +1 -0
  298. package/dist/client/router-lifecycle.d.ts +98 -0
  299. package/dist/client/router-lifecycle.d.ts.map +1 -0
  300. package/dist/client/router-pipeline.d.ts +87 -0
  301. package/dist/client/router-pipeline.d.ts.map +1 -0
  302. package/dist/client/router-ref.d.ts +2 -2
  303. package/dist/client/router-ref.d.ts.map +1 -1
  304. package/dist/client/router-skew.d.ts +21 -0
  305. package/dist/client/router-skew.d.ts.map +1 -0
  306. package/dist/client/router-types.d.ts +272 -0
  307. package/dist/client/router-types.d.ts.map +1 -0
  308. package/dist/client/router.d.ts +1 -97
  309. package/dist/client/router.d.ts.map +1 -1
  310. package/dist/client/rsc-fetch.d.ts +104 -26
  311. package/dist/client/rsc-fetch.d.ts.map +1 -1
  312. package/dist/client/segment-cache.d.ts +161 -25
  313. package/dist/client/segment-cache.d.ts.map +1 -1
  314. package/dist/client/segment-context.d.ts.map +1 -1
  315. package/dist/client/segment-outlet.d.ts +68 -0
  316. package/dist/client/segment-outlet.d.ts.map +1 -0
  317. package/dist/client/segment-update-context.d.ts +15 -0
  318. package/dist/client/segment-update-context.d.ts.map +1 -0
  319. package/dist/client/shallow-url.d.ts +10 -0
  320. package/dist/client/shallow-url.d.ts.map +1 -0
  321. package/dist/client/slot-content-cache-context.d.ts +35 -0
  322. package/dist/client/slot-content-cache-context.d.ts.map +1 -0
  323. package/dist/client/slot-context.d.ts +31 -0
  324. package/dist/client/slot-context.d.ts.map +1 -0
  325. package/dist/client/slot-outlet.d.ts +16 -0
  326. package/dist/client/slot-outlet.d.ts.map +1 -0
  327. package/dist/client/slot-provider.d.ts +25 -0
  328. package/dist/client/slot-provider.d.ts.map +1 -0
  329. package/dist/client/ssr-data.d.ts +29 -7
  330. package/dist/client/ssr-data.d.ts.map +1 -1
  331. package/dist/client/stale-client.d.ts +69 -0
  332. package/dist/client/stale-client.d.ts.map +1 -0
  333. package/dist/client/state.d.ts +19 -8
  334. package/dist/client/state.d.ts.map +1 -1
  335. package/dist/client/status-page-marker.d.ts +25 -0
  336. package/dist/client/status-page-marker.d.ts.map +1 -0
  337. package/dist/client/top-loader.d.ts +7 -6
  338. package/dist/client/top-loader.d.ts.map +1 -1
  339. package/dist/client/unload-guard.d.ts +5 -0
  340. package/dist/client/unload-guard.d.ts.map +1 -1
  341. package/dist/client/use-cookie.d.ts +12 -0
  342. package/dist/client/use-cookie.d.ts.map +1 -1
  343. package/dist/client/use-link-status.d.ts +5 -5
  344. package/dist/client/use-link-status.d.ts.map +1 -1
  345. package/dist/client/use-pathname.d.ts +13 -11
  346. package/dist/client/use-pathname.d.ts.map +1 -1
  347. package/dist/client/use-pending-navigation.d.ts +23 -0
  348. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  349. package/dist/client/use-query-states.d.ts +10 -4
  350. package/dist/client/use-query-states.d.ts.map +1 -1
  351. package/dist/client/use-router.d.ts +2 -2
  352. package/dist/client/use-router.d.ts.map +1 -1
  353. package/dist/client/use-search-params.d.ts +15 -8
  354. package/dist/client/use-search-params.d.ts.map +1 -1
  355. package/dist/client/use-segment-params.d.ts +55 -0
  356. package/dist/client/use-segment-params.d.ts.map +1 -0
  357. package/dist/codec.d.ts +69 -0
  358. package/dist/codec.d.ts.map +1 -0
  359. package/dist/codec.js +76 -0
  360. package/dist/codec.js.map +1 -0
  361. package/dist/config-types.d.ts +322 -0
  362. package/dist/config-types.d.ts.map +1 -0
  363. package/dist/config-validation.d.ts +51 -0
  364. package/dist/config-validation.d.ts.map +1 -0
  365. package/dist/cookies/define-cookie.d.ts +58 -25
  366. package/dist/cookies/define-cookie.d.ts.map +1 -1
  367. package/dist/cookies/index.d.ts +3 -2
  368. package/dist/cookies/index.d.ts.map +1 -1
  369. package/dist/cookies/index.js +256 -36
  370. package/dist/cookies/index.js.map +1 -1
  371. package/dist/cookies/json-cookie.d.ts +64 -0
  372. package/dist/cookies/json-cookie.d.ts.map +1 -0
  373. package/dist/cookies/validation.d.ts +34 -0
  374. package/dist/cookies/validation.d.ts.map +1 -0
  375. package/dist/dev-tools/404-page.d.ts +50 -0
  376. package/dist/dev-tools/404-page.d.ts.map +1 -0
  377. package/dist/dev-tools/browser-logs.d.ts +40 -0
  378. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  379. package/dist/dev-tools/debug-channel.d.ts +55 -0
  380. package/dist/dev-tools/debug-channel.d.ts.map +1 -0
  381. package/dist/dev-tools/dev-page-shell.d.ts +78 -0
  382. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  383. package/dist/dev-tools/error-page.d.ts +32 -0
  384. package/dist/dev-tools/error-page.d.ts.map +1 -0
  385. package/dist/dev-tools/holding-server.d.ts +46 -0
  386. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  387. package/dist/dev-tools/hydration-overlay.d.ts +11 -0
  388. package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
  389. package/dist/dev-tools/index.d.ts +31 -0
  390. package/dist/dev-tools/index.d.ts.map +1 -0
  391. package/dist/dev-tools/instrumentation.d.ts +59 -0
  392. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  393. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  394. package/dist/dev-tools/logger.d.ts.map +1 -0
  395. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +17 -3
  396. package/dist/dev-tools/logs.d.ts.map +1 -0
  397. package/dist/dev-tools/overlay.d.ts +91 -0
  398. package/dist/dev-tools/overlay.d.ts.map +1 -0
  399. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  400. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  401. package/dist/dev-tools/terminal.d.ts +28 -0
  402. package/dist/dev-tools/terminal.d.ts.map +1 -0
  403. package/dist/fonts/ast-walk.d.ts +68 -0
  404. package/dist/fonts/ast-walk.d.ts.map +1 -0
  405. package/dist/fonts/ast.d.ts +112 -8
  406. package/dist/fonts/ast.d.ts.map +1 -1
  407. package/dist/fonts/bundle.d.ts +50 -0
  408. package/dist/fonts/bundle.d.ts.map +1 -0
  409. package/dist/fonts/css.d.ts +1 -1
  410. package/dist/fonts/dev-middleware.d.ts +22 -0
  411. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  412. package/dist/fonts/fallbacks.d.ts +0 -7
  413. package/dist/fonts/fallbacks.d.ts.map +1 -1
  414. package/dist/fonts/google.d.ts +5 -3
  415. package/dist/fonts/google.d.ts.map +1 -1
  416. package/dist/fonts/local.d.ts +5 -5
  417. package/dist/fonts/local.d.ts.map +1 -1
  418. package/dist/fonts/paths.d.ts +43 -0
  419. package/dist/fonts/paths.d.ts.map +1 -0
  420. package/dist/fonts/pipeline.d.ts +177 -0
  421. package/dist/fonts/pipeline.d.ts.map +1 -0
  422. package/dist/fonts/transform.d.ts +82 -0
  423. package/dist/fonts/transform.d.ts.map +1 -0
  424. package/dist/fonts/types.d.ts +47 -1
  425. package/dist/fonts/types.d.ts.map +1 -1
  426. package/dist/fonts/virtual-modules.d.ts +77 -0
  427. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  428. package/dist/index.d.ts +35 -181
  429. package/dist/index.d.ts.map +1 -1
  430. package/dist/index.js +8462 -14279
  431. package/dist/index.js.map +1 -1
  432. package/dist/params/codec-registry.d.ts +26 -0
  433. package/dist/params/codec-registry.d.ts.map +1 -0
  434. package/dist/params/define-schema.d.ts +81 -0
  435. package/dist/params/define-schema.d.ts.map +1 -0
  436. package/dist/params/index.d.ts +5 -0
  437. package/dist/params/index.d.ts.map +1 -0
  438. package/dist/params/index.js +34 -0
  439. package/dist/params/index.js.map +1 -0
  440. package/dist/params/resolve-schema.d.ts +34 -0
  441. package/dist/params/resolve-schema.d.ts.map +1 -0
  442. package/dist/plugin-context.d.ts +276 -0
  443. package/dist/plugin-context.d.ts.map +1 -0
  444. package/dist/plugins/adapter-build.d.ts +21 -1
  445. package/dist/plugins/adapter-build.d.ts.map +1 -1
  446. package/dist/plugins/build-manifest.d.ts +7 -3
  447. package/dist/plugins/build-manifest.d.ts.map +1 -1
  448. package/dist/plugins/build-report.d.ts +47 -10
  449. package/dist/plugins/build-report.d.ts.map +1 -1
  450. package/dist/plugins/cache.d.ts +64 -0
  451. package/dist/plugins/cache.d.ts.map +1 -0
  452. package/dist/plugins/callsite-ast.d.ts +117 -0
  453. package/dist/plugins/callsite-ast.d.ts.map +1 -0
  454. package/dist/plugins/callsite-jsx.d.ts +35 -0
  455. package/dist/plugins/callsite-jsx.d.ts.map +1 -0
  456. package/dist/plugins/chunks.d.ts +11 -4
  457. package/dist/plugins/chunks.d.ts.map +1 -1
  458. package/dist/plugins/client-chunks.d.ts +40 -0
  459. package/dist/plugins/client-chunks.d.ts.map +1 -0
  460. package/dist/plugins/cloudflare-wasm.d.ts +21 -0
  461. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  462. package/dist/plugins/content.d.ts +1 -1
  463. package/dist/plugins/content.d.ts.map +1 -1
  464. package/dist/plugins/dev-discovery.d.ts +123 -0
  465. package/dist/plugins/dev-discovery.d.ts.map +1 -0
  466. package/dist/plugins/dev-server.d.ts +24 -1
  467. package/dist/plugins/dev-server.d.ts.map +1 -1
  468. package/dist/plugins/entries.d.ts +28 -4
  469. package/dist/plugins/entries.d.ts.map +1 -1
  470. package/dist/plugins/fonts.d.ts +16 -73
  471. package/dist/plugins/fonts.d.ts.map +1 -1
  472. package/dist/plugins/graph-endpoint.d.ts +112 -0
  473. package/dist/plugins/graph-endpoint.d.ts.map +1 -0
  474. package/dist/plugins/mdx.d.ts +18 -5
  475. package/dist/plugins/mdx.d.ts.map +1 -1
  476. package/dist/plugins/prebuilt-capture.d.ts +60 -0
  477. package/dist/plugins/prebuilt-capture.d.ts.map +1 -0
  478. package/dist/plugins/prebuilt-options-analysis.d.ts +40 -0
  479. package/dist/plugins/prebuilt-options-analysis.d.ts.map +1 -0
  480. package/dist/plugins/prebuilt.d.ts +82 -0
  481. package/dist/plugins/prebuilt.d.ts.map +1 -0
  482. package/dist/plugins/prerender-sugar.d.ts +39 -0
  483. package/dist/plugins/prerender-sugar.d.ts.map +1 -0
  484. package/dist/plugins/request-dep/analysis.d.ts +106 -0
  485. package/dist/plugins/request-dep/analysis.d.ts.map +1 -0
  486. package/dist/plugins/request-dep/index.d.ts +75 -0
  487. package/dist/plugins/request-dep/index.d.ts.map +1 -0
  488. package/dist/plugins/request-dep/origin.d.ts +61 -0
  489. package/dist/plugins/request-dep/origin.d.ts.map +1 -0
  490. package/dist/plugins/routing.d.ts +1 -1
  491. package/dist/plugins/routing.d.ts.map +1 -1
  492. package/dist/plugins/server-bundle.d.ts.map +1 -1
  493. package/dist/plugins/shims.d.ts +29 -5
  494. package/dist/plugins/shims.d.ts.map +1 -1
  495. package/dist/plugins/static-build.d.ts +218 -21
  496. package/dist/plugins/static-build.d.ts.map +1 -1
  497. package/dist/routing/codegen-shared.d.ts +26 -0
  498. package/dist/routing/codegen-shared.d.ts.map +1 -0
  499. package/dist/routing/codegen-types.d.ts +61 -0
  500. package/dist/routing/codegen-types.d.ts.map +1 -0
  501. package/dist/routing/codegen-write.d.ts +51 -0
  502. package/dist/routing/codegen-write.d.ts.map +1 -0
  503. package/dist/routing/codegen.d.ts +8 -3
  504. package/dist/routing/codegen.d.ts.map +1 -1
  505. package/dist/routing/collision-probe.d.ts +104 -0
  506. package/dist/routing/collision-probe.d.ts.map +1 -0
  507. package/dist/routing/collision-spaces.d.ts +26 -0
  508. package/dist/routing/collision-spaces.d.ts.map +1 -0
  509. package/dist/routing/convention-lint.d.ts +55 -0
  510. package/dist/routing/convention-lint.d.ts.map +1 -0
  511. package/dist/routing/export-detect.d.ts +72 -0
  512. package/dist/routing/export-detect.d.ts.map +1 -0
  513. package/dist/routing/file-cache.d.ts +8 -0
  514. package/dist/routing/file-cache.d.ts.map +1 -0
  515. package/dist/routing/index.d.ts +13 -7
  516. package/dist/routing/index.d.ts.map +1 -1
  517. package/dist/routing/index.js +5 -2
  518. package/dist/routing/interception-overlap.d.ts +35 -0
  519. package/dist/routing/interception-overlap.d.ts.map +1 -0
  520. package/dist/routing/interception.d.ts +234 -10
  521. package/dist/routing/interception.d.ts.map +1 -1
  522. package/dist/routing/link-codegen.d.ts +105 -0
  523. package/dist/routing/link-codegen.d.ts.map +1 -0
  524. package/dist/routing/manifest-codegen.d.ts +26 -0
  525. package/dist/routing/manifest-codegen.d.ts.map +1 -0
  526. package/dist/routing/scanner.d.ts +14 -10
  527. package/dist/routing/scanner.d.ts.map +1 -1
  528. package/dist/routing/schema-validation.d.ts +35 -0
  529. package/dist/routing/schema-validation.d.ts.map +1 -0
  530. package/dist/routing/segment-classify.d.ts +114 -0
  531. package/dist/routing/segment-classify.d.ts.map +1 -0
  532. package/dist/routing/segment-codegen.d.ts +38 -0
  533. package/dist/routing/segment-codegen.d.ts.map +1 -0
  534. package/dist/routing/segment-keys.d.ts +118 -0
  535. package/dist/routing/segment-keys.d.ts.map +1 -0
  536. package/dist/routing/slot-placement.d.ts +48 -0
  537. package/dist/routing/slot-placement.d.ts.map +1 -0
  538. package/dist/routing/types.d.ts +74 -26
  539. package/dist/routing/types.d.ts.map +1 -1
  540. package/dist/routing/walkers.d.ts +57 -0
  541. package/dist/routing/walkers.d.ts.map +1 -0
  542. package/dist/rsc-runtime/rsc.d.ts +1 -1
  543. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  544. package/dist/rsc-runtime/ssr.d.ts +14 -0
  545. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  546. package/dist/rsc-runtime/transforms.d.ts +13 -0
  547. package/dist/rsc-runtime/transforms.d.ts.map +1 -0
  548. package/dist/schema-bridge.d.ts +145 -0
  549. package/dist/schema-bridge.d.ts.map +1 -0
  550. package/dist/search-params/define.d.ts +262 -0
  551. package/dist/search-params/define.d.ts.map +1 -0
  552. package/dist/search-params/index.d.ts +3 -7
  553. package/dist/search-params/index.d.ts.map +1 -1
  554. package/dist/search-params/index.js +179 -360
  555. package/dist/search-params/index.js.map +1 -1
  556. package/dist/search-params/parse-total.d.ts +81 -0
  557. package/dist/search-params/parse-total.d.ts.map +1 -0
  558. package/dist/search-params/serialize-equal.d.ts +9 -0
  559. package/dist/search-params/serialize-equal.d.ts.map +1 -0
  560. package/dist/search-params/wrappers.d.ts +76 -0
  561. package/dist/search-params/wrappers.d.ts.map +1 -0
  562. package/dist/server/access-gate.d.ts +98 -10
  563. package/dist/server/access-gate.d.ts.map +1 -1
  564. package/dist/server/action-client.d.ts +42 -7
  565. package/dist/server/action-client.d.ts.map +1 -1
  566. package/dist/server/action-encryption.d.ts +76 -0
  567. package/dist/server/action-encryption.d.ts.map +1 -0
  568. package/dist/server/action-handler.d.ts +39 -5
  569. package/dist/server/action-handler.d.ts.map +1 -1
  570. package/dist/server/actions.d.ts +29 -35
  571. package/dist/server/actions.d.ts.map +1 -1
  572. package/dist/server/als-registry.d.ts +117 -13
  573. package/dist/server/als-registry.d.ts.map +1 -1
  574. package/dist/server/asset-headers.d.ts +8 -18
  575. package/dist/server/asset-headers.d.ts.map +1 -1
  576. package/dist/server/body-limits.d.ts.map +1 -1
  577. package/dist/server/build-manifest.d.ts +25 -30
  578. package/dist/server/build-manifest.d.ts.map +1 -1
  579. package/dist/server/canonicalize.d.ts +10 -0
  580. package/dist/server/canonicalize.d.ts.map +1 -1
  581. package/dist/server/chain-url-parts.d.ts +82 -0
  582. package/dist/server/chain-url-parts.d.ts.map +1 -0
  583. package/dist/server/children-interception.d.ts +49 -0
  584. package/dist/server/children-interception.d.ts.map +1 -0
  585. package/dist/server/coalesce-tick.d.ts +40 -0
  586. package/dist/server/coalesce-tick.d.ts.map +1 -0
  587. package/dist/server/compress.d.ts.map +1 -1
  588. package/dist/server/cookie-context.d.ts +170 -0
  589. package/dist/server/cookie-context.d.ts.map +1 -0
  590. package/dist/server/cookie-parsing.d.ts +65 -0
  591. package/dist/server/cookie-parsing.d.ts.map +1 -0
  592. package/dist/server/csp-nonce.d.ts +45 -0
  593. package/dist/server/csp-nonce.d.ts.map +1 -0
  594. package/dist/server/csrf.d.ts +3 -2
  595. package/dist/server/csrf.d.ts.map +1 -1
  596. package/dist/server/default-logger.d.ts +22 -0
  597. package/dist/server/default-logger.d.ts.map +1 -0
  598. package/dist/server/default-status-page.d.ts +45 -0
  599. package/dist/server/default-status-page.d.ts.map +1 -0
  600. package/dist/server/deny-boundary.d.ts +251 -0
  601. package/dist/server/deny-boundary.d.ts.map +1 -0
  602. package/dist/server/deny-renderer.d.ts +20 -10
  603. package/dist/server/deny-renderer.d.ts.map +1 -1
  604. package/dist/server/dev-source-map.d.ts +22 -0
  605. package/dist/server/dev-source-map.d.ts.map +1 -0
  606. package/dist/server/early-hints-sender.d.ts.map +1 -1
  607. package/dist/server/early-hints.d.ts +14 -12
  608. package/dist/server/early-hints.d.ts.map +1 -1
  609. package/dist/server/error-boundary-wrapper.d.ts +94 -10
  610. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  611. package/dist/server/error-response-headers.d.ts +3 -0
  612. package/dist/server/error-response-headers.d.ts.map +1 -0
  613. package/dist/server/fallback-error.d.ts +12 -7
  614. package/dist/server/fallback-error.d.ts.map +1 -1
  615. package/dist/server/flight-injection-state.d.ts +66 -0
  616. package/dist/server/flight-injection-state.d.ts.map +1 -0
  617. package/dist/server/flight-scripts.d.ts +45 -0
  618. package/dist/server/flight-scripts.d.ts.map +1 -0
  619. package/dist/server/form-data.d.ts +41 -0
  620. package/dist/server/form-data.d.ts.map +1 -1
  621. package/dist/server/form-flash.d.ts +1 -1
  622. package/dist/server/head-response.d.ts +35 -0
  623. package/dist/server/head-response.d.ts.map +1 -0
  624. package/dist/server/html-injector-core.d.ts +257 -0
  625. package/dist/server/html-injector-core.d.ts.map +1 -0
  626. package/dist/server/html-injectors.d.ts +84 -42
  627. package/dist/server/html-injectors.d.ts.map +1 -1
  628. package/dist/server/index.d.ts +18 -54
  629. package/dist/server/index.d.ts.map +1 -1
  630. package/dist/server/index.js +195 -2922
  631. package/dist/server/index.js.map +1 -1
  632. package/dist/server/instrumentation.d.ts +1 -1
  633. package/dist/server/internal.d.ts +50 -0
  634. package/dist/server/internal.d.ts.map +1 -0
  635. package/dist/server/internal.js +3859 -0
  636. package/dist/server/internal.js.map +1 -0
  637. package/dist/server/logger.d.ts +39 -7
  638. package/dist/server/logger.d.ts.map +1 -1
  639. package/dist/server/metadata-collector.d.ts +71 -0
  640. package/dist/server/metadata-collector.d.ts.map +1 -0
  641. package/dist/server/metadata-platform.d.ts +2 -2
  642. package/dist/server/metadata-render.d.ts +2 -2
  643. package/dist/server/metadata-render.d.ts.map +1 -1
  644. package/dist/server/metadata-routes.d.ts +60 -11
  645. package/dist/server/metadata-routes.d.ts.map +1 -1
  646. package/dist/server/metadata-social.d.ts +2 -2
  647. package/dist/server/metadata.d.ts +10 -2
  648. package/dist/server/metadata.d.ts.map +1 -1
  649. package/dist/server/middleware-runner.d.ts +20 -5
  650. package/dist/server/middleware-runner.d.ts.map +1 -1
  651. package/dist/server/node-stream-transforms.d.ts +105 -0
  652. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  653. package/dist/server/nuqs-ssr-provider.d.ts +7 -3
  654. package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
  655. package/dist/server/param-coercion.d.ts +78 -0
  656. package/dist/server/param-coercion.d.ts.map +1 -0
  657. package/dist/server/pipeline-helpers.d.ts +77 -0
  658. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  659. package/dist/server/pipeline-interception.d.ts +59 -9
  660. package/dist/server/pipeline-interception.d.ts.map +1 -1
  661. package/dist/server/pipeline-metadata.d.ts +7 -1
  662. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  663. package/dist/server/pipeline-outcome.d.ts +49 -0
  664. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  665. package/dist/server/pipeline-phases.d.ts +70 -0
  666. package/dist/server/pipeline-phases.d.ts.map +1 -0
  667. package/dist/server/pipeline.d.ts +161 -20
  668. package/dist/server/pipeline.d.ts.map +1 -1
  669. package/dist/server/port-resolution.d.ts +31 -0
  670. package/dist/server/port-resolution.d.ts.map +1 -0
  671. package/dist/server/prebuilt/cache-key.d.ts +63 -0
  672. package/dist/server/prebuilt/cache-key.d.ts.map +1 -0
  673. package/dist/server/prebuilt/capture-state.d.ts +57 -0
  674. package/dist/server/prebuilt/capture-state.d.ts.map +1 -0
  675. package/dist/server/prebuilt/key-discipline.d.ts +52 -0
  676. package/dist/server/prebuilt/key-discipline.d.ts.map +1 -0
  677. package/dist/server/prebuilt/manifest-tag-index.d.ts +27 -0
  678. package/dist/server/prebuilt/manifest-tag-index.d.ts.map +1 -0
  679. package/dist/server/prebuilt/overlay.d.ts +100 -0
  680. package/dist/server/prebuilt/overlay.d.ts.map +1 -0
  681. package/dist/server/prebuilt/payload-source.d.ts +79 -0
  682. package/dist/server/prebuilt/payload-source.d.ts.map +1 -0
  683. package/dist/server/prebuilt/slots.d.ts +99 -0
  684. package/dist/server/prebuilt/slots.d.ts.map +1 -0
  685. package/dist/server/prebuilt/synthetic-store.d.ts +67 -0
  686. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -0
  687. package/dist/server/prebuilt-builder.d.ts +121 -0
  688. package/dist/server/prebuilt-builder.d.ts.map +1 -0
  689. package/dist/server/prebuilt-runtime.d.ts +111 -0
  690. package/dist/server/prebuilt-runtime.d.ts.map +1 -0
  691. package/dist/server/primitives.d.ts +131 -45
  692. package/dist/server/primitives.d.ts.map +1 -1
  693. package/dist/server/publish-params.d.ts +33 -0
  694. package/dist/server/publish-params.d.ts.map +1 -0
  695. package/dist/server/render-timeout.d.ts +51 -0
  696. package/dist/server/render-timeout.d.ts.map +1 -0
  697. package/dist/server/render-utils.d.ts +26 -0
  698. package/dist/server/render-utils.d.ts.map +1 -0
  699. package/dist/server/request-context.d.ts +111 -107
  700. package/dist/server/request-context.d.ts.map +1 -1
  701. package/dist/server/request-dep.d.ts +15 -0
  702. package/dist/server/request-dep.d.ts.map +1 -0
  703. package/dist/server/response-cache-policy.d.ts +3 -0
  704. package/dist/server/response-cache-policy.d.ts.map +1 -0
  705. package/dist/server/route-element-builder.d.ts +57 -30
  706. package/dist/server/route-element-builder.d.ts.map +1 -1
  707. package/dist/server/route-element-helpers.d.ts +12 -0
  708. package/dist/server/route-element-helpers.d.ts.map +1 -0
  709. package/dist/server/route-handler.d.ts +1 -1
  710. package/dist/server/route-handler.d.ts.map +1 -1
  711. package/dist/server/route-matcher.d.ts +40 -38
  712. package/dist/server/route-matcher.d.ts.map +1 -1
  713. package/dist/server/route-module-loader.d.ts +37 -0
  714. package/dist/server/route-module-loader.d.ts.map +1 -0
  715. package/dist/server/rsc-cache-key-guard.d.ts +78 -0
  716. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -0
  717. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  718. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  719. package/dist/server/rsc-entry/api-handler.d.ts +12 -3
  720. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  721. package/dist/server/rsc-entry/deny-fallback.d.ts +29 -0
  722. package/dist/server/rsc-entry/deny-fallback.d.ts.map +1 -0
  723. package/dist/server/rsc-entry/error-renderer.d.ts +34 -13
  724. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  725. package/dist/server/rsc-entry/helpers.d.ts +47 -51
  726. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  727. package/dist/server/rsc-entry/index.d.ts +40 -6
  728. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  729. package/dist/server/rsc-entry/render-route.d.ts +52 -0
  730. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  731. package/dist/server/rsc-entry/revalidate-renderer.d.ts +108 -0
  732. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  733. package/dist/server/rsc-entry/rsc-payload.d.ts +26 -6
  734. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  735. package/dist/server/rsc-entry/rsc-stream.d.ts +36 -3
  736. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  737. package/dist/server/rsc-entry/ssr-bridge.d.ts +5 -1
  738. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  739. package/dist/server/rsc-entry/ssr-renderer.d.ts +38 -5
  740. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  741. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +89 -0
  742. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
  743. package/dist/server/rsc-error-envelope.d.ts +11 -0
  744. package/dist/server/rsc-error-envelope.d.ts.map +1 -0
  745. package/dist/server/safe-load.d.ts +46 -0
  746. package/dist/server/safe-load.d.ts.map +1 -0
  747. package/dist/server/sensitive-fields.d.ts +74 -0
  748. package/dist/server/sensitive-fields.d.ts.map +1 -0
  749. package/dist/server/sitemap-generator.d.ts +130 -0
  750. package/dist/server/sitemap-generator.d.ts.map +1 -0
  751. package/dist/server/sitemap-handler.d.ts +22 -0
  752. package/dist/server/sitemap-handler.d.ts.map +1 -0
  753. package/dist/server/skippable-prefix.d.ts +29 -0
  754. package/dist/server/skippable-prefix.d.ts.map +1 -0
  755. package/dist/server/slot-interception.d.ts +80 -0
  756. package/dist/server/slot-interception.d.ts.map +1 -0
  757. package/dist/server/slot-resolver.d.ts +137 -7
  758. package/dist/server/slot-resolver.d.ts.map +1 -1
  759. package/dist/server/slot-subtree-contain.d.ts +54 -0
  760. package/dist/server/slot-subtree-contain.d.ts.map +1 -0
  761. package/dist/server/ssr-bridge-types.d.ts +160 -0
  762. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  763. package/dist/server/ssr-entry.d.ts +1 -43
  764. package/dist/server/ssr-entry.d.ts.map +1 -1
  765. package/dist/server/ssr-render.d.ts +69 -22
  766. package/dist/server/ssr-render.d.ts.map +1 -1
  767. package/dist/server/ssr-wrappers.d.ts +93 -0
  768. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  769. package/dist/server/state-tree-diff.d.ts +44 -9
  770. package/dist/server/state-tree-diff.d.ts.map +1 -1
  771. package/dist/server/static-generator.d.ts +112 -0
  772. package/dist/server/static-generator.d.ts.map +1 -0
  773. package/dist/server/static-not-found.d.ts +52 -0
  774. package/dist/server/static-not-found.d.ts.map +1 -0
  775. package/dist/server/status-code-resolver.d.ts +26 -15
  776. package/dist/server/status-code-resolver.d.ts.map +1 -1
  777. package/dist/server/stream-utils.d.ts +47 -0
  778. package/dist/server/stream-utils.d.ts.map +1 -0
  779. package/dist/server/tracing.d.ts +46 -11
  780. package/dist/server/tracing.d.ts.map +1 -1
  781. package/dist/server/tree-match.d.ts +49 -0
  782. package/dist/server/tree-match.d.ts.map +1 -0
  783. package/dist/server/types.d.ts +88 -7
  784. package/dist/server/types.d.ts.map +1 -1
  785. package/dist/server/utils/element-type.d.ts +50 -0
  786. package/dist/server/utils/element-type.d.ts.map +1 -0
  787. package/dist/server/utils/escape-html.d.ts +14 -0
  788. package/dist/server/utils/escape-html.d.ts.map +1 -0
  789. package/dist/server/version-skew.d.ts +61 -0
  790. package/dist/server/version-skew.d.ts.map +1 -0
  791. package/dist/server/workers-cache-bridge.d.ts +26 -0
  792. package/dist/server/workers-cache-bridge.d.ts.map +1 -0
  793. package/dist/shared/als-slots.d.ts +42 -0
  794. package/dist/shared/als-slots.d.ts.map +1 -0
  795. package/dist/shared/base-path.d.ts +56 -0
  796. package/dist/shared/base-path.d.ts.map +1 -0
  797. package/dist/shared/href-validation.d.ts +49 -0
  798. package/dist/shared/href-validation.d.ts.map +1 -0
  799. package/dist/shared/merge-search-params.d.ts +22 -0
  800. package/dist/shared/merge-search-params.d.ts.map +1 -0
  801. package/dist/shared/param-value.d.ts +104 -0
  802. package/dist/shared/param-value.d.ts.map +1 -0
  803. package/dist/shared/payload-root.d.ts +109 -0
  804. package/dist/shared/payload-root.d.ts.map +1 -0
  805. package/dist/shared/redirect-type.d.ts +17 -0
  806. package/dist/shared/redirect-type.d.ts.map +1 -0
  807. package/dist/shared/rsc-cache-key.d.ts +163 -0
  808. package/dist/shared/rsc-cache-key.d.ts.map +1 -0
  809. package/dist/shared/rsc-error-envelope.d.ts +16 -0
  810. package/dist/shared/rsc-error-envelope.d.ts.map +1 -0
  811. package/dist/shared/rsc-manifest.d.ts +28 -0
  812. package/dist/shared/rsc-manifest.d.ts.map +1 -0
  813. package/dist/shared/rsc-media-type.d.ts +52 -0
  814. package/dist/shared/rsc-media-type.d.ts.map +1 -0
  815. package/dist/shared/rsc-payload-path.d.ts +42 -0
  816. package/dist/shared/rsc-payload-path.d.ts.map +1 -0
  817. package/dist/shared/segment-info.d.ts +66 -0
  818. package/dist/shared/segment-info.d.ts.map +1 -0
  819. package/dist/shared/slot-params.d.ts +52 -0
  820. package/dist/shared/slot-params.d.ts.map +1 -0
  821. package/dist/shared/static-platform-files.d.ts +71 -0
  822. package/dist/shared/static-platform-files.d.ts.map +1 -0
  823. package/dist/shared/status-reason-phrase.d.ts +26 -0
  824. package/dist/shared/status-reason-phrase.d.ts.map +1 -0
  825. package/dist/shims/font-google.d.ts +1 -1
  826. package/dist/shims/font-google.d.ts.map +1 -1
  827. package/dist/shims/font-google.js +42 -0
  828. package/dist/shims/font-google.js.map +1 -0
  829. package/dist/shims/font-local.d.ts +26 -0
  830. package/dist/shims/font-local.d.ts.map +1 -0
  831. package/dist/shims/font-local.js +20 -0
  832. package/dist/shims/font-local.js.map +1 -0
  833. package/dist/shims/headers.d.ts +53 -1
  834. package/dist/shims/headers.d.ts.map +1 -1
  835. package/dist/shims/image.d.ts +120 -120
  836. package/dist/shims/image.d.ts.map +1 -1
  837. package/dist/shims/navigation-client.d.ts +25 -12
  838. package/dist/shims/navigation-client.d.ts.map +1 -1
  839. package/dist/shims/navigation-rsc.d.ts +21 -0
  840. package/dist/shims/navigation-rsc.d.ts.map +1 -0
  841. package/dist/shims/navigation.d.ts +10 -5
  842. package/dist/shims/navigation.d.ts.map +1 -1
  843. package/dist/utils/state-machine.d.ts +80 -0
  844. package/dist/utils/state-machine.d.ts.map +1 -0
  845. package/docs/api/30-api-server.mdx +236 -0
  846. package/docs/api/31-api-client.mdx +167 -0
  847. package/docs/api/32-api-cache.mdx +311 -0
  848. package/docs/api/33-api-search-params.mdx +176 -0
  849. package/docs/api/34-api-config.mdx +329 -0
  850. package/docs/api/35-api-typescript.mdx +91 -0
  851. package/docs/api/36-cli.mdx +192 -0
  852. package/docs/learn/00-introduction.mdx +109 -0
  853. package/docs/learn/01-quick-start.mdx +94 -0
  854. package/docs/learn/02-pages-and-layouts.mdx +147 -0
  855. package/docs/learn/03-fetching-data.mdx +211 -0
  856. package/docs/learn/04-access-control.mdx +115 -0
  857. package/docs/learn/05-the-flush-point.mdx +175 -0
  858. package/docs/learn/06-typed-params.mdx +275 -0
  859. package/docs/learn/07-typed-routes.mdx +108 -0
  860. package/docs/learn/08-forms-and-actions.mdx +146 -0
  861. package/docs/learn/09-streaming.mdx +140 -0
  862. package/docs/learn/10-caching.mdx +252 -0
  863. package/docs/learn/11-middleware.mdx +158 -0
  864. package/docs/learn/12-error-handling.mdx +187 -0
  865. package/docs/learn/13-deploying.mdx +287 -0
  866. package/llms.txt +55 -0
  867. package/package.json +116 -30
  868. package/src/adapters/build-output-helper.ts +351 -0
  869. package/src/adapters/cloudflare-dev.ts +183 -0
  870. package/src/adapters/cloudflare-kv-cache.ts +207 -0
  871. package/src/adapters/cloudflare.ts +747 -130
  872. package/src/adapters/compress-module.ts +101 -88
  873. package/src/adapters/fs-identity.ts +156 -0
  874. package/src/adapters/nitro-presets.ts +139 -0
  875. package/src/adapters/nitro-preview.ts +340 -0
  876. package/src/adapters/nitro.ts +249 -426
  877. package/src/adapters/raw-imports.d.ts +5 -0
  878. package/src/adapters/shared.ts +274 -0
  879. package/src/adapters/types.ts +28 -7
  880. package/src/adapters/wrangler.d.ts +7 -0
  881. package/src/analyze/chains.ts +411 -0
  882. package/src/analyze/classify.ts +258 -0
  883. package/src/analyze/crawl-entry.ts +68 -0
  884. package/src/analyze/crawl.ts +500 -0
  885. package/src/analyze/graph-cache.ts +332 -0
  886. package/src/analyze/graph-command.ts +762 -0
  887. package/src/analyze/live-graph.ts +232 -0
  888. package/src/analyze/poison-rules.ts +165 -0
  889. package/src/analyze/poison-scan.ts +162 -0
  890. package/src/analyze/scan.ts +149 -0
  891. package/src/cache/cache-api.ts +107 -0
  892. package/src/cache/fast-hash.ts +5 -0
  893. package/src/cache/handler-store.ts +76 -0
  894. package/src/cache/index.ts +115 -22
  895. package/src/cache/invalidation-epoch.ts +93 -0
  896. package/src/cache/json-lossy-check.ts +75 -0
  897. package/src/cache/redis-handler.ts +198 -20
  898. package/src/cache/singleflight.ts +69 -6
  899. package/src/cache/sizeof.ts +33 -0
  900. package/src/cache/stable-stringify.ts +65 -2
  901. package/src/cache/store.ts +71 -0
  902. package/src/cache/stores/cloudflare-kv.ts +52 -0
  903. package/src/cache/stores/memory.ts +125 -0
  904. package/src/cache/stores/redis.ts +97 -0
  905. package/src/cache/stores/vercel.ts +59 -0
  906. package/src/cache/tag-aware-handler.ts +237 -0
  907. package/src/cache/timber-cache.ts +165 -40
  908. package/src/cdn/cloudflare-purge.ts +50 -0
  909. package/src/cdn/fastly-purge.ts +63 -0
  910. package/src/cdn/headers.ts +153 -0
  911. package/src/cdn/index.ts +23 -0
  912. package/src/cdn/purge-store.ts +34 -0
  913. package/src/cdn/workers-cache-purge.ts +34 -0
  914. package/src/cli-check.ts +507 -0
  915. package/src/cli-schema-sync.ts +401 -0
  916. package/src/cli.ts +323 -62
  917. package/src/client/browser-dev.ts +157 -2
  918. package/src/client/browser-entry/action-dispatch.ts +209 -0
  919. package/src/client/browser-entry/action-queue.ts +152 -0
  920. package/src/client/browser-entry/hmr.ts +70 -0
  921. package/src/client/browser-entry/hydrate.ts +148 -0
  922. package/src/client/browser-entry/index.ts +131 -0
  923. package/src/client/browser-entry/post-hydration.ts +123 -0
  924. package/src/client/browser-entry/router-init.ts +418 -0
  925. package/src/client/browser-entry/rsc-stream.ts +222 -0
  926. package/src/client/browser-entry/scroll.ts +50 -0
  927. package/src/client/deny-last-resort.tsx +54 -0
  928. package/src/client/error-boundary.tsx +289 -39
  929. package/src/client/error-reconstituter.tsx +79 -0
  930. package/src/client/form.tsx +36 -32
  931. package/src/client/global-context.ts +31 -0
  932. package/src/client/history.ts +81 -10
  933. package/src/client/index.ts +89 -53
  934. package/src/client/internal.ts +59 -0
  935. package/src/client/link.tsx +439 -151
  936. package/src/client/location-search.ts +15 -0
  937. package/src/client/navigation-api.ts +347 -0
  938. package/src/client/navigation-commit.ts +295 -0
  939. package/src/client/navigation-context.ts +67 -98
  940. package/src/client/navigation-root.tsx +224 -0
  941. package/src/client/navigation-transition.ts +327 -0
  942. package/src/client/nuqs-adapter.tsx +21 -9
  943. package/src/client/params-context.ts +187 -0
  944. package/src/client/react-root.ts +72 -0
  945. package/src/client/router-effects.ts +228 -0
  946. package/src/client/router-lifecycle.ts +354 -0
  947. package/src/client/router-pipeline.ts +490 -0
  948. package/src/client/router-ref.ts +3 -3
  949. package/src/client/router-skew.ts +30 -0
  950. package/src/client/router-types.ts +294 -0
  951. package/src/client/router.ts +435 -421
  952. package/src/client/rsc-fetch.ts +512 -73
  953. package/src/client/segment-cache.ts +327 -40
  954. package/src/client/segment-context.ts +7 -4
  955. package/src/client/segment-outlet.tsx +96 -0
  956. package/src/client/segment-update-context.ts +23 -0
  957. package/src/client/shallow-url.ts +22 -0
  958. package/src/client/slot-content-cache-context.ts +43 -0
  959. package/src/client/slot-context.ts +50 -0
  960. package/src/client/slot-outlet.tsx +22 -0
  961. package/src/client/slot-provider.tsx +32 -0
  962. package/src/client/ssr-data.ts +30 -9
  963. package/src/client/stale-client.ts +191 -0
  964. package/src/client/state.ts +29 -15
  965. package/src/client/status-page-marker.tsx +32 -0
  966. package/src/client/top-loader.tsx +13 -10
  967. package/src/client/unload-guard.ts +35 -3
  968. package/src/client/use-cookie.ts +70 -18
  969. package/src/client/use-link-status.ts +7 -7
  970. package/src/client/use-pathname.ts +22 -31
  971. package/src/client/use-pending-navigation.ts +40 -0
  972. package/src/client/use-query-states.ts +206 -36
  973. package/src/client/use-router.ts +6 -3
  974. package/src/client/use-search-params.ts +38 -49
  975. package/src/client/use-segment-params.ts +69 -0
  976. package/src/client/use-selected-layout-segment.ts +2 -2
  977. package/src/codec.ts +149 -0
  978. package/src/config-types.ts +322 -0
  979. package/src/config-validation.ts +347 -0
  980. package/src/cookies/define-cookie.ts +222 -53
  981. package/src/cookies/index.ts +13 -2
  982. package/src/cookies/json-cookie.ts +105 -0
  983. package/src/cookies/validation.ts +192 -0
  984. package/src/dev-tools/404-page.ts +286 -0
  985. package/src/dev-tools/browser-logs.ts +55 -0
  986. package/src/dev-tools/debug-channel.ts +151 -0
  987. package/src/dev-tools/dev-page-shell.ts +260 -0
  988. package/src/dev-tools/error-page.ts +331 -0
  989. package/src/dev-tools/holding-server.ts +185 -0
  990. package/src/dev-tools/hydration-overlay.ts +158 -0
  991. package/src/dev-tools/index.ts +83 -0
  992. package/src/dev-tools/instrumentation.ts +213 -0
  993. package/src/{server/dev-logger.ts → dev-tools/logger.ts} +33 -51
  994. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +122 -26
  995. package/src/dev-tools/overlay.ts +469 -0
  996. package/src/dev-tools/stack-classifier.ts +75 -0
  997. package/src/dev-tools/terminal.ts +182 -0
  998. package/src/fonts/ast-walk.ts +235 -0
  999. package/src/fonts/ast.ts +479 -128
  1000. package/src/fonts/bundle.ts +138 -0
  1001. package/src/fonts/css.ts +1 -1
  1002. package/src/fonts/dev-middleware.ts +85 -0
  1003. package/src/fonts/fallbacks.ts +0 -23
  1004. package/src/fonts/google.ts +101 -19
  1005. package/src/fonts/local.ts +12 -11
  1006. package/src/fonts/paths.ts +58 -0
  1007. package/src/fonts/pipeline.ts +348 -0
  1008. package/src/fonts/transform.ts +311 -0
  1009. package/src/fonts/types.ts +52 -1
  1010. package/src/fonts/virtual-modules.ts +179 -0
  1011. package/src/index.ts +482 -377
  1012. package/src/params/codec-registry.ts +34 -0
  1013. package/src/params/define-schema.ts +115 -0
  1014. package/src/params/index.ts +17 -0
  1015. package/src/params/resolve-schema.ts +84 -0
  1016. package/src/plugin-context.ts +503 -0
  1017. package/src/plugins/adapter-build.ts +229 -7
  1018. package/src/plugins/build-manifest.ts +201 -26
  1019. package/src/plugins/build-report.ts +259 -47
  1020. package/src/plugins/cache.ts +243 -0
  1021. package/src/plugins/callsite-ast.ts +472 -0
  1022. package/src/plugins/callsite-jsx.ts +243 -0
  1023. package/src/plugins/chunks.ts +74 -5
  1024. package/src/plugins/client-chunks.ts +185 -0
  1025. package/src/plugins/cloudflare-wasm.ts +141 -0
  1026. package/src/plugins/content.ts +5 -1
  1027. package/src/plugins/dev-discovery.ts +218 -0
  1028. package/src/plugins/dev-server.ts +418 -94
  1029. package/src/plugins/entries.ts +141 -16
  1030. package/src/plugins/fonts.ts +234 -659
  1031. package/src/plugins/graph-endpoint.ts +532 -0
  1032. package/src/plugins/mdx.ts +108 -35
  1033. package/src/plugins/prebuilt-capture.ts +217 -0
  1034. package/src/plugins/prebuilt-options-analysis.ts +175 -0
  1035. package/src/plugins/prebuilt.ts +655 -0
  1036. package/src/plugins/prerender-sugar.ts +320 -0
  1037. package/src/plugins/request-dep/analysis.ts +447 -0
  1038. package/src/plugins/request-dep/index.ts +376 -0
  1039. package/src/plugins/request-dep/origin.ts +310 -0
  1040. package/src/plugins/routing.ts +273 -277
  1041. package/src/plugins/server-bundle.ts +99 -14
  1042. package/src/plugins/shims.ts +259 -97
  1043. package/src/plugins/static-build.ts +708 -66
  1044. package/src/react-canary.d.ts +2 -0
  1045. package/src/routing/codegen-shared.ts +39 -0
  1046. package/src/routing/codegen-types.ts +62 -0
  1047. package/src/routing/codegen-write.ts +141 -0
  1048. package/src/routing/codegen.ts +349 -232
  1049. package/src/routing/collision-probe.ts +438 -0
  1050. package/src/routing/collision-spaces.ts +281 -0
  1051. package/src/routing/convention-lint.ts +516 -0
  1052. package/src/routing/export-detect.ts +448 -0
  1053. package/src/routing/file-cache.ts +23 -0
  1054. package/src/routing/index.ts +16 -7
  1055. package/src/routing/interception-overlap.ts +141 -0
  1056. package/src/routing/interception.ts +1044 -67
  1057. package/src/routing/link-codegen.ts +280 -0
  1058. package/src/routing/manifest-codegen.ts +226 -0
  1059. package/src/routing/scanner.ts +408 -223
  1060. package/src/routing/schema-validation.ts +155 -0
  1061. package/src/routing/segment-classify.ts +280 -0
  1062. package/src/routing/segment-codegen.ts +98 -0
  1063. package/src/routing/segment-keys.ts +186 -0
  1064. package/src/routing/slot-placement.ts +97 -0
  1065. package/src/routing/types.ts +75 -26
  1066. package/src/routing/walkers.ts +98 -0
  1067. package/src/rsc-runtime/rsc.ts +9 -0
  1068. package/src/rsc-runtime/ssr.ts +51 -0
  1069. package/src/rsc-runtime/transforms.ts +13 -0
  1070. package/src/rsc-runtime/vendor-types.d.ts +19 -0
  1071. package/src/schema-bridge.ts +380 -0
  1072. package/src/search-params/define.ts +677 -0
  1073. package/src/search-params/index.ts +14 -20
  1074. package/src/search-params/parse-total.ts +91 -0
  1075. package/src/search-params/serialize-equal.ts +14 -0
  1076. package/src/search-params/wrappers.ts +150 -0
  1077. package/src/server/access-gate.tsx +194 -56
  1078. package/src/server/action-client.ts +122 -31
  1079. package/src/server/action-encryption.ts +144 -0
  1080. package/src/server/action-handler.ts +256 -56
  1081. package/src/server/actions.ts +112 -68
  1082. package/src/server/als-registry.ts +160 -21
  1083. package/src/server/asset-headers.ts +15 -37
  1084. package/src/server/body-limits.ts +10 -2
  1085. package/src/server/build-manifest.ts +33 -57
  1086. package/src/server/canonicalize.ts +6 -3
  1087. package/src/server/chain-url-parts.ts +163 -0
  1088. package/src/server/children-interception.ts +115 -0
  1089. package/src/server/coalesce-tick.ts +75 -0
  1090. package/src/server/compress.ts +43 -8
  1091. package/src/server/cookie-context.ts +484 -0
  1092. package/src/server/cookie-parsing.ts +163 -0
  1093. package/src/server/csp-nonce.ts +70 -0
  1094. package/src/server/csrf.ts +39 -6
  1095. package/src/server/default-logger.ts +99 -0
  1096. package/src/server/default-status-page.ts +88 -0
  1097. package/src/server/deny-boundary.ts +515 -0
  1098. package/src/server/deny-renderer.ts +211 -113
  1099. package/src/server/dev-source-map.ts +31 -0
  1100. package/src/server/early-hints-sender.ts +4 -3
  1101. package/src/server/early-hints.ts +39 -29
  1102. package/src/server/error-boundary-wrapper.ts +157 -44
  1103. package/src/server/error-response-headers.ts +18 -0
  1104. package/src/server/fallback-error.ts +79 -102
  1105. package/src/server/flight-injection-state.ts +113 -0
  1106. package/src/server/flight-scripts.ts +67 -0
  1107. package/src/server/form-data.ts +124 -12
  1108. package/src/server/form-flash.ts +2 -2
  1109. package/src/server/head-response.ts +54 -0
  1110. package/src/server/html-injector-core.ts +512 -0
  1111. package/src/server/html-injectors.ts +272 -255
  1112. package/src/server/index.ts +40 -192
  1113. package/src/server/instrumentation.ts +1 -1
  1114. package/src/server/internal.ts +173 -0
  1115. package/src/server/logger.ts +73 -37
  1116. package/src/server/metadata-collector.ts +174 -0
  1117. package/src/server/metadata-platform.ts +2 -2
  1118. package/src/server/metadata-render.ts +30 -8
  1119. package/src/server/metadata-routes.ts +205 -24
  1120. package/src/server/metadata-social.ts +2 -2
  1121. package/src/server/metadata.ts +23 -2
  1122. package/src/server/middleware-runner.ts +32 -5
  1123. package/src/server/node-stream-transforms.ts +323 -0
  1124. package/src/server/nuqs-ssr-provider.tsx +8 -7
  1125. package/src/server/param-coercion.ts +198 -0
  1126. package/src/server/pipeline-helpers.ts +159 -0
  1127. package/src/server/pipeline-interception.ts +109 -33
  1128. package/src/server/pipeline-metadata.ts +15 -1
  1129. package/src/server/pipeline-outcome.ts +218 -0
  1130. package/src/server/pipeline-phases.ts +606 -0
  1131. package/src/server/pipeline.ts +333 -384
  1132. package/src/server/port-resolution.ts +53 -0
  1133. package/src/server/prebuilt/cache-key.ts +299 -0
  1134. package/src/server/prebuilt/capture-state.ts +89 -0
  1135. package/src/server/prebuilt/key-discipline.ts +122 -0
  1136. package/src/server/prebuilt/manifest-tag-index.ts +46 -0
  1137. package/src/server/prebuilt/overlay.ts +256 -0
  1138. package/src/server/prebuilt/payload-source.ts +202 -0
  1139. package/src/server/prebuilt/slots.ts +190 -0
  1140. package/src/server/prebuilt/synthetic-store.ts +122 -0
  1141. package/src/server/prebuilt-builder.ts +804 -0
  1142. package/src/server/prebuilt-runtime.ts +817 -0
  1143. package/src/server/primitives.ts +240 -98
  1144. package/src/server/publish-params.ts +42 -0
  1145. package/src/server/render-timeout.ts +108 -0
  1146. package/src/server/render-utils.ts +35 -0
  1147. package/src/server/request-context.ts +244 -334
  1148. package/src/server/request-dep.ts +37 -0
  1149. package/src/server/response-cache-policy.ts +45 -0
  1150. package/src/server/route-element-builder.ts +508 -355
  1151. package/src/server/route-element-helpers.ts +37 -0
  1152. package/src/server/route-handler.ts +40 -13
  1153. package/src/server/route-matcher.ts +165 -272
  1154. package/src/server/route-module-loader.ts +161 -0
  1155. package/src/server/rsc-cache-key-guard.ts +122 -0
  1156. package/src/server/rsc-entry/action-middleware-runner.ts +174 -0
  1157. package/src/server/rsc-entry/api-handler.ts +78 -34
  1158. package/src/server/rsc-entry/deny-fallback.ts +93 -0
  1159. package/src/server/rsc-entry/error-renderer.ts +341 -91
  1160. package/src/server/rsc-entry/helpers.ts +180 -106
  1161. package/src/server/rsc-entry/index.ts +371 -331
  1162. package/src/server/rsc-entry/render-route.ts +315 -0
  1163. package/src/server/rsc-entry/revalidate-renderer.ts +350 -0
  1164. package/src/server/rsc-entry/rsc-payload.ts +209 -55
  1165. package/src/server/rsc-entry/rsc-stream.ts +154 -26
  1166. package/src/server/rsc-entry/ssr-bridge.ts +18 -5
  1167. package/src/server/rsc-entry/ssr-renderer.ts +317 -60
  1168. package/src/server/rsc-entry/wrap-action-dispatch.ts +186 -0
  1169. package/src/server/rsc-error-envelope.ts +18 -0
  1170. package/src/server/rsc-prop-warnings.ts +1 -1
  1171. package/src/server/safe-load.ts +60 -0
  1172. package/src/server/sensitive-fields.ts +230 -0
  1173. package/src/server/server-only-guard-noop.js +3 -0
  1174. package/src/server/server-timing.ts +1 -1
  1175. package/src/server/sitemap-generator.ts +337 -0
  1176. package/src/server/sitemap-handler.ts +157 -0
  1177. package/src/server/skippable-prefix.ts +172 -0
  1178. package/src/server/slot-interception.ts +168 -0
  1179. package/src/server/slot-resolver.ts +707 -300
  1180. package/src/server/slot-subtree-contain.ts +255 -0
  1181. package/src/server/ssr-bridge-types.ts +165 -0
  1182. package/src/server/ssr-entry.ts +230 -85
  1183. package/src/server/ssr-render.ts +357 -85
  1184. package/src/server/ssr-wrappers.tsx +162 -0
  1185. package/src/server/state-tree-diff.ts +85 -30
  1186. package/src/server/static-generator.ts +715 -0
  1187. package/src/server/static-not-found.ts +134 -0
  1188. package/src/server/status-code-resolver.ts +107 -148
  1189. package/src/server/stream-utils.ts +292 -0
  1190. package/src/server/tracing.ts +128 -16
  1191. package/src/server/tree-match.ts +262 -0
  1192. package/src/server/types.ts +95 -10
  1193. package/src/server/utils/element-type.ts +88 -0
  1194. package/src/server/utils/escape-html.ts +20 -0
  1195. package/src/server/version-skew.ts +104 -0
  1196. package/src/server/waituntil-bridge.ts +1 -1
  1197. package/src/server/workers-cache-bridge.ts +33 -0
  1198. package/src/shared/als-slots.ts +74 -0
  1199. package/src/shared/base-path.ts +80 -0
  1200. package/src/shared/href-validation.ts +159 -0
  1201. package/src/shared/merge-search-params.ts +55 -0
  1202. package/src/shared/param-value.ts +281 -0
  1203. package/src/shared/payload-root.ts +152 -0
  1204. package/src/shared/redirect-type.ts +17 -0
  1205. package/src/shared/rsc-cache-key.ts +269 -0
  1206. package/src/shared/rsc-error-envelope.ts +16 -0
  1207. package/src/shared/rsc-manifest.ts +29 -0
  1208. package/src/shared/rsc-media-type.ts +59 -0
  1209. package/src/shared/rsc-payload-path.ts +45 -0
  1210. package/src/shared/segment-info.ts +67 -0
  1211. package/src/shared/slot-params.ts +109 -0
  1212. package/src/shared/static-platform-files.ts +75 -0
  1213. package/src/shared/status-reason-phrase.ts +61 -0
  1214. package/src/shims/font-google.ts +1 -1
  1215. package/src/shims/font-local.ts +34 -0
  1216. package/src/shims/headers.ts +122 -1
  1217. package/src/shims/navigation-client.ts +36 -32
  1218. package/src/shims/navigation-rsc.ts +47 -0
  1219. package/src/shims/navigation.ts +10 -7
  1220. package/src/utils/state-machine.ts +111 -0
  1221. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  1222. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  1223. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  1224. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  1225. package/dist/_chunks/format-RyoGQL74.js +0 -164
  1226. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  1227. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  1228. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  1229. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  1230. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  1231. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  1232. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  1233. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  1234. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  1235. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  1236. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  1237. package/dist/_chunks/use-query-states-D5KaffOK.js +0 -109
  1238. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  1239. package/dist/adapters/cloudflare.js.map +0 -1
  1240. package/dist/cache/index.js.map +0 -1
  1241. package/dist/cache/register-cached-function.d.ts +0 -17
  1242. package/dist/cache/register-cached-function.d.ts.map +0 -1
  1243. package/dist/client/browser-entry.d.ts +0 -21
  1244. package/dist/client/browser-entry.d.ts.map +0 -1
  1245. package/dist/client/error-boundary.js.map +0 -1
  1246. package/dist/client/head.d.ts +0 -16
  1247. package/dist/client/head.d.ts.map +0 -1
  1248. package/dist/client/link-status-provider.d.ts +0 -11
  1249. package/dist/client/link-status-provider.d.ts.map +0 -1
  1250. package/dist/client/segment-merger.d.ts +0 -119
  1251. package/dist/client/segment-merger.d.ts.map +0 -1
  1252. package/dist/client/stale-reload.d.ts +0 -44
  1253. package/dist/client/stale-reload.d.ts.map +0 -1
  1254. package/dist/client/transition-root.d.ts +0 -74
  1255. package/dist/client/transition-root.d.ts.map +0 -1
  1256. package/dist/client/use-navigation-pending.d.ts +0 -26
  1257. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  1258. package/dist/client/use-params.d.ts +0 -92
  1259. package/dist/client/use-params.d.ts.map +0 -1
  1260. package/dist/content/index.d.ts +0 -11
  1261. package/dist/content/index.d.ts.map +0 -1
  1262. package/dist/content/index.js +0 -2
  1263. package/dist/plugins/cache-transform.d.ts +0 -36
  1264. package/dist/plugins/cache-transform.d.ts.map +0 -1
  1265. package/dist/plugins/dev-error-overlay.d.ts +0 -60
  1266. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  1267. package/dist/plugins/dev-logs.d.ts.map +0 -1
  1268. package/dist/plugins/dynamic-transform.d.ts +0 -72
  1269. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  1270. package/dist/plugins/server-action-exports.d.ts +0 -26
  1271. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  1272. package/dist/routing/status-file-lint.d.ts +0 -33
  1273. package/dist/routing/status-file-lint.d.ts.map +0 -1
  1274. package/dist/search-params/analyze.d.ts +0 -54
  1275. package/dist/search-params/analyze.d.ts.map +0 -1
  1276. package/dist/search-params/builtin-codecs.d.ts +0 -105
  1277. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  1278. package/dist/search-params/codecs.d.ts +0 -53
  1279. package/dist/search-params/codecs.d.ts.map +0 -1
  1280. package/dist/search-params/create.d.ts +0 -106
  1281. package/dist/search-params/create.d.ts.map +0 -1
  1282. package/dist/search-params/registry.d.ts +0 -20
  1283. package/dist/search-params/registry.d.ts.map +0 -1
  1284. package/dist/server/client-module-map.d.ts +0 -47
  1285. package/dist/server/client-module-map.d.ts.map +0 -1
  1286. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  1287. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  1288. package/dist/server/dev-logger.d.ts.map +0 -1
  1289. package/dist/server/dev-span-processor.d.ts +0 -29
  1290. package/dist/server/dev-span-processor.d.ts.map +0 -1
  1291. package/dist/server/dev-warnings.d.ts +0 -129
  1292. package/dist/server/dev-warnings.d.ts.map +0 -1
  1293. package/dist/server/flush.d.ts +0 -74
  1294. package/dist/server/flush.d.ts.map +0 -1
  1295. package/dist/server/manifest-status-resolver.d.ts +0 -58
  1296. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  1297. package/dist/server/prerender.d.ts +0 -77
  1298. package/dist/server/prerender.d.ts.map +0 -1
  1299. package/dist/server/tree-builder.d.ts +0 -126
  1300. package/dist/server/tree-builder.d.ts.map +0 -1
  1301. package/dist/utils/directive-parser.d.ts +0 -70
  1302. package/dist/utils/directive-parser.d.ts.map +0 -1
  1303. package/src/cache/register-cached-function.ts +0 -103
  1304. package/src/client/browser-entry.ts +0 -678
  1305. package/src/client/head.ts +0 -61
  1306. package/src/client/link-status-provider.tsx +0 -30
  1307. package/src/client/segment-merger.ts +0 -339
  1308. package/src/client/stale-reload.ts +0 -87
  1309. package/src/client/transition-root.tsx +0 -166
  1310. package/src/client/use-navigation-pending.ts +0 -38
  1311. package/src/client/use-params.ts +0 -141
  1312. package/src/content/index.ts +0 -13
  1313. package/src/plugins/cache-transform.ts +0 -199
  1314. package/src/plugins/dev-error-overlay.ts +0 -230
  1315. package/src/plugins/dynamic-transform.ts +0 -161
  1316. package/src/plugins/server-action-exports.ts +0 -220
  1317. package/src/routing/status-file-lint.ts +0 -112
  1318. package/src/search-params/analyze.ts +0 -192
  1319. package/src/search-params/builtin-codecs.ts +0 -228
  1320. package/src/search-params/codecs.ts +0 -153
  1321. package/src/search-params/create.ts +0 -321
  1322. package/src/search-params/registry.ts +0 -31
  1323. package/src/server/client-module-map.ts +0 -58
  1324. package/src/server/dev-fetch-instrumentation.ts +0 -96
  1325. package/src/server/dev-span-processor.ts +0 -78
  1326. package/src/server/dev-warnings.ts +0 -283
  1327. package/src/server/flush.ts +0 -182
  1328. package/src/server/manifest-status-resolver.ts +0 -215
  1329. package/src/server/prerender.ts +0 -139
  1330. package/src/server/tree-builder.ts +0 -382
  1331. package/src/shims/server-only-noop.js +0 -6
  1332. package/src/utils/directive-parser.ts +0 -529
@@ -0,0 +1,3859 @@
1
+ import { a as timingAls, r as requestContextAls, t as earlyHintsSenderAls } from "../_chunks/als-registry-C6kcfprT.js";
2
+ import { A as getSegmentParams, B as isDebug, D as getHeader, E as applyRequestHeaderOverlay, F as setSegmentParams, G as getOtelTraceId, I as getCookie, J as replaceTraceId, M as runWithRequestContext, N as setMatchedSegmentPath, P as setMutableCookieContext, R as getSetCookieHeaders, W as generateTraceId, X as setSpanAttribute, Y as runWithTraceId, Z as withSpan, _ as RedirectSignal, a as logProxyError, b as isDenySignal, c as logRequestReceived, d as logSwrRefetchFailed, f as logWaitUntilRejected, g as DenySignal, h as swallow, i as logMiddlewareShortCircuit, j as markResponseFlushed, k as getSearchParams, l as logRouteError, m as setLogger, n as logCacheMiss, o as logRenderError, p as logWaitUntilUnsupported, r as logMiddlewareError, s as logRequestCompleted, t as getLogger, u as logSlowRequest, v as RenderError, x as isRedirectSignal, z as getWaitUntil } from "../_chunks/logger-DqJ2VoAY.js";
3
+ import { i as isRscCacheKeyShape, n as RSC_KEY_PARAM, s as rscCacheKey, t as RSC_KEY_HEADERS } from "../_chunks/rsc-cache-key-ClUiXQnK.js";
4
+ import { t as computeSegmentTreePaths } from "../_chunks/segment-keys-D5hu1hz4.js";
5
+ import { a as fireOnRequestError, c as callOnRequestError, i as cloneWithMutableHeaders, l as hasOnRequestError, n as applyCookieJar, o as makeProxyResolver, r as buildRedirectResponse, s as mergeMissingHeaders, t as requestCspNonce, u as loadInstrumentation } from "../_chunks/csp-nonce-hOGniaG4.js";
6
+ import { n as isRscContentType, r as isRscRequest } from "../_chunks/rsc-media-type-DDc7duTD.js";
7
+ import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-DSDjM_hJ.js";
8
+ import { r as canonicalize } from "../_chunks/canonicalize-CgHoscYO.js";
9
+ import { n as classifyUrlSegment, r as effectiveUrlSegment } from "../_chunks/segment-classify-C539Pa2O.js";
10
+ import { i as collectRouteModulepreloads, n as collectRouteCss, r as collectRouteFonts } from "../_chunks/build-manifest-DWppEdLB.js";
11
+ import { i as coerce, t as executeAction } from "../_chunks/actions-HUdJADAD.js";
12
+ import { a as getManifestEntry, b as wasInvalidatedSince, c as lookupPrebuiltPayload, d as checkVersionSkew, i as storeOverlayEntry, l as setPrebuiltPayloadSource, n as lookupOverlay, o as hasPrebuiltPayloadSource, r as overlayKey, s as isParamIndependent, u as applyReloadHeaders, v as currentInvalidationEpoch, y as lastInvalidationEpochFor } from "../_chunks/cache-api-CAPbZTga.js";
13
+ import { n as createSingleflight } from "../_chunks/singleflight-2lUWfcAk.js";
14
+ import { n as toBracketKey } from "../_chunks/resolve-schema-CBR6Lm4i.js";
15
+ import { t as normalizeParamValue } from "../_chunks/param-value-C8TNYchQ.js";
16
+ import { s as TIMBER_ERROR_HEADER, t as StatusPageMarker } from "../_chunks/status-page-marker-DwQBrLBz.js";
17
+ import { createHash } from "node:crypto";
18
+ import { readFile } from "node:fs/promises";
19
+ import React, { createElement, useContext } from "react";
20
+ //#region src/server/server-timing.ts
21
+ /**
22
+ * Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
23
+ *
24
+ * Collects timing entries per request using ALS. Each pipeline phase
25
+ * (proxy, middleware, render, SSR, access, fetch) records an entry.
26
+ * Before response flush, entries are formatted into a Server-Timing header.
27
+ *
28
+ * Only active in dev mode — zero overhead in production.
29
+ *
30
+ * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
31
+ * Task: LOCAL-290
32
+ */
33
+ /**
34
+ * Run a callback with a per-request timing collector.
35
+ * Must be called at the top of the request pipeline (wraps the full request).
36
+ */
37
+ function runWithTimingCollector(fn) {
38
+ return timingAls.run({ entries: [] }, fn);
39
+ }
40
+ /**
41
+ * Run a function and automatically record its duration as a timing entry.
42
+ * Returns the function's result. No-ops the recording if outside a collector.
43
+ */
44
+ async function withTiming(name, desc, fn) {
45
+ const store = timingAls.getStore();
46
+ if (!store) return fn();
47
+ const start = performance.now();
48
+ try {
49
+ return await fn();
50
+ } finally {
51
+ const dur = Math.round(performance.now() - start);
52
+ store.entries.push({
53
+ name,
54
+ dur,
55
+ desc
56
+ });
57
+ }
58
+ }
59
+ /**
60
+ * Get the Server-Timing header value for the current request.
61
+ * Returns null if no entries exist or outside a collector.
62
+ *
63
+ * Format: `name;dur=123;desc="description", name2;dur=456`
64
+ * See RFC 6797 / Server-Timing spec for format details.
65
+ */
66
+ function getServerTimingHeader() {
67
+ const store = timingAls.getStore();
68
+ if (!store || store.entries.length === 0) return null;
69
+ const nameCounts = /* @__PURE__ */ new Map();
70
+ const parts = store.entries.map((entry) => {
71
+ const count = nameCounts.get(entry.name) ?? 0;
72
+ nameCounts.set(entry.name, count + 1);
73
+ const uniqueName = count > 0 ? `${entry.name}-${count}` : entry.name;
74
+ return {
75
+ ...entry,
76
+ name: uniqueName
77
+ };
78
+ }).map((entry) => {
79
+ let part = `${entry.name};dur=${entry.dur}`;
80
+ if (entry.desc) {
81
+ const safeDesc = entry.desc.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
82
+ part += `;desc="${safeDesc}"`;
83
+ }
84
+ return part;
85
+ });
86
+ const MAX_HEADER_SIZE = 4096;
87
+ let result = "";
88
+ for (let i = 0; i < parts.length; i++) {
89
+ const candidate = result ? `${result}, ${parts[i]}` : parts[i];
90
+ if (candidate.length > MAX_HEADER_SIZE) break;
91
+ result = candidate;
92
+ }
93
+ return result || null;
94
+ }
95
+ //#endregion
96
+ //#region src/server/stream-utils.ts
97
+ /**
98
+ * Stream utilities for the RSC rendering pipeline.
99
+ *
100
+ * teeWithErrorPropagation — wraps native ReadableStream.tee() with:
101
+ * 1. Cross-branch error propagation (error on one branch cancels the other)
102
+ * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)
103
+ *
104
+ * This prevents two classes of bugs:
105
+ * - Silent stalls when one tee branch errors and the other hangs indefinitely
106
+ * - Unbounded memory growth when one consumer (SSR) is much slower than the other
107
+ *
108
+ * Design doc: 02-rendering-pipeline.md §"RSC → SSR → Client Hydration"
109
+ */
110
+ /**
111
+ * Wrap a response body with stream-lifecycle timing instrumentation.
112
+ *
113
+ * Logs firstChunk, lastChunk, close, maxGap (largest inter-chunk gap),
114
+ * chunk count, and byte count on stream termination (clean close OR
115
+ * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`.
116
+ *
117
+ * Uses a manual reader pump to guarantee logging on all termination
118
+ * paths — TransformStream.flush() is not called on cancellation.
119
+ */
120
+ function wrapResponseWithStreamTiming(body, startTime) {
121
+ let firstChunkMs = 0;
122
+ let lastChunkMs = 0;
123
+ let maxGapMs = 0;
124
+ let prevChunkTime = 0;
125
+ let chunks = 0;
126
+ let bytes = 0;
127
+ let cancelled = false;
128
+ function emitLog() {
129
+ const closeMs = Math.round(performance.now() - startTime);
130
+ getLogger().debug("stream-lifecycle", {
131
+ firstChunkMs,
132
+ lastChunkMs,
133
+ closeMs,
134
+ maxGapMs,
135
+ chunks,
136
+ bytes,
137
+ ...cancelled ? { cancelled: true } : {}
138
+ });
139
+ }
140
+ const reader = body.getReader();
141
+ return new ReadableStream({
142
+ async pull(controller) {
143
+ try {
144
+ const { done, value } = await reader.read();
145
+ if (done) {
146
+ emitLog();
147
+ controller.close();
148
+ return;
149
+ }
150
+ const now = performance.now();
151
+ const relativeMs = Math.round(now - startTime);
152
+ if (chunks === 0) firstChunkMs = relativeMs;
153
+ else {
154
+ const gap = Math.round(now - prevChunkTime);
155
+ if (gap > maxGapMs) maxGapMs = gap;
156
+ }
157
+ prevChunkTime = now;
158
+ lastChunkMs = relativeMs;
159
+ chunks++;
160
+ bytes += value.byteLength;
161
+ controller.enqueue(value);
162
+ } catch (err) {
163
+ emitLog();
164
+ controller.error(err);
165
+ }
166
+ },
167
+ cancel(reason) {
168
+ cancelled = true;
169
+ emitLog();
170
+ reader.cancel(reason).catch(() => {});
171
+ }
172
+ });
173
+ }
174
+ //#endregion
175
+ //#region src/server/proxy.ts
176
+ /**
177
+ * Run the proxy pipeline.
178
+ *
179
+ * @param proxyExport - The default export from proxy.ts (function or array)
180
+ * @param req - The incoming request
181
+ * @param next - The continuation that proceeds to route matching and rendering
182
+ * @returns The final response
183
+ */
184
+ async function runProxy(proxyExport, req, next) {
185
+ const fns = Array.isArray(proxyExport) ? proxyExport : [proxyExport];
186
+ let i = fns.length;
187
+ let composed = next;
188
+ while (i--) {
189
+ const fn = fns[i];
190
+ const downstream = composed;
191
+ composed = () => Promise.resolve(fn(req, downstream));
192
+ }
193
+ return composed();
194
+ }
195
+ //#endregion
196
+ //#region src/server/middleware-runner.ts
197
+ /**
198
+ * Run a route's middleware function.
199
+ *
200
+ * @param middlewareFn - The default export from the route's middleware.ts
201
+ * @param ctx - The middleware context (req, params, headers, requestHeaders, searchParams)
202
+ * @returns A Response if middleware short-circuited, or undefined to continue
203
+ */
204
+ async function runMiddleware(middlewareFn, ctx) {
205
+ const result = await middlewareFn(ctx);
206
+ if (result instanceof Response) return result;
207
+ }
208
+ /**
209
+ * Run all middleware functions in the segment chain, root to leaf.
210
+ *
211
+ * Execution is top-down: root middleware runs first, leaf middleware runs last.
212
+ * All middleware share the same MiddlewareContext — a parent that sets
213
+ * ctx.requestHeaders makes it visible to child middleware and downstream components.
214
+ *
215
+ * Short-circuits on the first middleware that returns a Response.
216
+ * Remaining middleware in the chain do not execute.
217
+ *
218
+ * @param chain - Middleware functions ordered root-to-leaf
219
+ * @param ctx - Shared middleware context
220
+ * @returns A Response if any middleware short-circuited, or undefined to continue
221
+ */
222
+ async function runMiddlewareChain(chain, ctx) {
223
+ for (const fn of chain) {
224
+ const result = await fn(ctx);
225
+ if (result instanceof Response) return result;
226
+ }
227
+ }
228
+ //#endregion
229
+ //#region src/server/param-coercion.ts
230
+ /**
231
+ * Thrown when an app/schema.ts segment-param codec's parse() fails.
232
+ * The pipeline catches this and responds with 404.
233
+ */
234
+ var ParamCoercionError = class extends Error {
235
+ constructor(message) {
236
+ super(message);
237
+ this.name = "ParamCoercionError";
238
+ }
239
+ };
240
+ /** Global schema codecs, set once at startup from virtual:timber-schema. */
241
+ var _globalCodecs = null;
242
+ /**
243
+ * Run segment param coercion on the matched route's segments.
244
+ *
245
+ * Codecs come from `app/schema.ts` and nowhere else (TIM-1342 completed
246
+ * design/41-global-params.md migration step 9). A route with no schema, or
247
+ * a param the schema does not declare, keeps its raw string — which is the
248
+ * honest type for an uninterpreted URL segment.
249
+ *
250
+ * Throws ParamCoercionError if any codec fails (→ 404).
251
+ *
252
+ * This runs BEFORE middleware, so ctx.segmentParams is already typed.
253
+ * See design/07-routing.md §"Where Coercion Runs"
254
+ * See design/41-global-params.md §"Pipeline Integration"
255
+ *
256
+ * Stays `async` with nothing to await: it is injected as a
257
+ * `CoerceSegmentParamsFn` into the revalidation renderer and the action
258
+ * middleware runner, both of which await it. Narrowing the return type to
259
+ * `void` would break those contracts and remove a microtask boundary the
260
+ * pipeline's ordering has always had, for no gain.
261
+ */
262
+ async function coerceSegmentParams(match) {
263
+ const globalCodecs = _globalCodecs;
264
+ const mergeTarget = Object.create(null);
265
+ for (const key of Object.keys(match.segmentParams)) if (key !== "__proto__") mergeTarget[key] = match.segmentParams[key];
266
+ match.segmentParams = mergeTarget;
267
+ if (globalCodecs) for (const node of match.segments) {
268
+ const segment = effectiveUrlSegment(node);
269
+ if (!segment.paramName) continue;
270
+ const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
271
+ const codec = globalCodecs[bracketKey];
272
+ if (!codec) continue;
273
+ const key = segment.paramName;
274
+ if (!(key in mergeTarget)) continue;
275
+ let parsed;
276
+ try {
277
+ parsed = codec.parse(mergeTarget[key]);
278
+ } catch (err) {
279
+ const message = err instanceof Error ? err.message : String(err);
280
+ if (isDebug()) console.warn(`[timber] Global schema codec rejected value for param "${key}"\n Error: ${message}\n Raw value: ${JSON.stringify(mergeTarget[key])}\n Hint: check the codec in app/schema.ts for key '${bracketKey}'.`);
281
+ throw new ParamCoercionError(message);
282
+ }
283
+ mergeTarget[key] = normalizeParamValue(parsed, key);
284
+ }
285
+ }
286
+ //#endregion
287
+ //#region src/server/pipeline-metadata.ts
288
+ /**
289
+ * Metadata route helpers for the request pipeline.
290
+ *
291
+ * Handles serving static metadata files and serializing sitemap responses.
292
+ * Extracted from pipeline.ts to keep files under 500 lines.
293
+ *
294
+ * See design/16-metadata.md §"Metadata Routes"
295
+ */
296
+ /**
297
+ * Content types that are text-based and should include charset=utf-8.
298
+ * Binary formats (images) should not include charset.
299
+ */
300
+ var TEXT_CONTENT_TYPES = /* @__PURE__ */ new Set([
301
+ "application/xml",
302
+ "text/plain",
303
+ "application/json",
304
+ "application/manifest+json",
305
+ "image/svg+xml"
306
+ ]);
307
+ /**
308
+ * Serve a static metadata file by reading it from disk.
309
+ *
310
+ * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
311
+ * are served as-is with the appropriate Content-Type header.
312
+ * Text files include charset=utf-8; binary files do not.
313
+ *
314
+ * See design/16-metadata.md §"Metadata Routes"
315
+ */
316
+ async function serveStaticMetadataFile(metaMatch) {
317
+ const { contentType, file } = metaMatch;
318
+ const isText = TEXT_CONTENT_TYPES.has(contentType);
319
+ const body = await readFile(file.filePath);
320
+ const headers = {
321
+ "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
322
+ "Content-Length": String(body.byteLength),
323
+ "Cache-Control": "public, max-age=14400, must-revalidate"
324
+ };
325
+ return new Response(body, {
326
+ status: 200,
327
+ headers
328
+ });
329
+ }
330
+ /**
331
+ * Serialize a sitemap array to XML.
332
+ * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
333
+ */
334
+ function serializeSitemap(entries) {
335
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
336
+ let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
337
+ if (e.lastModified) {
338
+ const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
339
+ xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
340
+ }
341
+ if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
342
+ if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
343
+ xml += "\n </url>";
344
+ return xml;
345
+ }).join("\n")}\n</urlset>`;
346
+ }
347
+ /** Escape special XML characters. */
348
+ function escapeXml(str) {
349
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
350
+ }
351
+ //#endregion
352
+ //#region src/server/safe-load.ts
353
+ /**
354
+ * Custom error class for module load failures.
355
+ *
356
+ * Preserves the original error as `cause` while providing a
357
+ * human-readable message with the file path.
358
+ */
359
+ var ModuleLoadError = class extends Error {
360
+ /** The file path that failed to load. */
361
+ filePath;
362
+ constructor(filePath, cause) {
363
+ const originalMessage = cause instanceof Error ? cause.message : String(cause);
364
+ super(`[timber] Failed to load module ${filePath}\n ${originalMessage}`, { cause });
365
+ this.name = "ModuleLoadError";
366
+ this.filePath = filePath;
367
+ }
368
+ };
369
+ /**
370
+ * Load a route manifest module with enriched error context.
371
+ *
372
+ * On success: returns the module object (same as `loader.load()`).
373
+ * On failure: throws `ModuleLoadError` with file path and original cause.
374
+ *
375
+ * For error rendering paths that need fallthrough instead of throwing,
376
+ * callers should catch at the call site:
377
+ *
378
+ * ```ts
379
+ * // Throwing (default) — route-element-builder, api-handler, etc.
380
+ * const mod = await loadModule(segment.page);
381
+ *
382
+ * // Fallthrough — error-renderer, error-boundary-wrapper
383
+ * const mod = await loadModule(segment.error).catch(() => null);
384
+ * ```
385
+ */
386
+ async function loadModule(loader) {
387
+ try {
388
+ return await loader.load();
389
+ } catch (error) {
390
+ throw new ModuleLoadError(loader.filePath, error);
391
+ }
392
+ }
393
+ //#endregion
394
+ //#region src/server/pipeline-interception.ts
395
+ /**
396
+ * Interception route matching for the request pipeline.
397
+ *
398
+ * Matches target URLs against interception rewrites to support the
399
+ * modal route pattern (soft navigation intercepts).
400
+ *
401
+ * Extracted from pipeline.ts to keep files under 500 lines.
402
+ *
403
+ * See design/07-routing.md §"Intercepting Routes"
404
+ */
405
+ /**
406
+ * Check if an intercepting route applies for this soft navigation.
407
+ *
408
+ * Two conditions must hold:
409
+ *
410
+ * 1. The **target** pathname matches the rewrite's intercepted pattern.
411
+ * 2. The **source** route — the page the user is navigating FROM, per the
412
+ * validated X-Timber-URL header — renders the segment that owns the slot
413
+ * holding the intercepting page (`interceptingScope`). Only then does that
414
+ * slot exist in the rendered tree, so only then can the intercepting page
415
+ * render.
416
+ *
417
+ * Condition 2 replaced a URL-prefix check (TIM-1279). A prefix cannot
418
+ * distinguish a route-group-scoped interception from a genuinely root-level
419
+ * one — route groups are invisible in `urlPath`, so both collapse to "/" and
420
+ * the guard degenerates to always-true. Tree paths carry group identity.
421
+ * The scope check also subsumes the old segment-boundary rule: a source route
422
+ * under /feed-private has no "/feed" in its chain.
423
+ *
424
+ * A third condition lives with the caller, which owns route matching, and it
425
+ * applies to the `'slot'` shape only: the route produced by re-matching
426
+ * `interceptingPrefix` must pass through the scope too. Conditions 1–2 are
427
+ * about the route the user is leaving; the slot has to exist in the tree that
428
+ * actually renders. The `'children'` shape resolves its owner from the scope
429
+ * directly rather than from a pathname, so it satisfies that by construction.
430
+ *
431
+ * `resolveSourceScopes` is a thunk so its inputs are only resolved when some
432
+ * rewrite's pattern actually matches the target — the common case is no match
433
+ * at all. It returns the two client-supplied answers to "what is on screen?"
434
+ * as **separate sets, most authoritative first**: the tree paths the client
435
+ * says it has mounted, then those of the route the departing URL matches. It
436
+ * returns null only when neither yields anything, which is not a soft
437
+ * navigation this can reason about.
438
+ *
439
+ * They are two sets rather than one union because ranking needs a chain
440
+ * (TIM-1318). Each channel describes a single rendered chain, so within one the
441
+ * scopes are strictly nested and the deepest is the innermost owner. Unioned
442
+ * they are not: once a modal is open the address bar holds the *intercepted*
443
+ * URL, so the second channel describes the canonical branch — possibly an
444
+ * exclusive route group the client never mounted — and a deeper scope from
445
+ * there would outrank the owner actually on screen. Trying the mounted channel
446
+ * to exhaustion first keeps the fallback the union was there to provide while
447
+ * ranking only within one chain.
448
+ *
449
+ * Returns the winning build-time rewrite, or null. Only build-time values ever
450
+ * reach the renderer: the client-supplied header selects a rewrite but never
451
+ * becomes a rendered route or pathname.
452
+ *
453
+ * The **first** matching rewrite wins, and the caller does not fall back to the
454
+ * next one when the winner fails to resolve. That is deliberate and pre-dates
455
+ * the two shapes: a rewrite that matched the target and the scope described the
456
+ * author's intent, and quietly rendering some other author's interception
457
+ * instead would be harder to explain than rendering the canonical route.
458
+ *
459
+ * "First" is meaningful because the list arrives **deepest scope first** —
460
+ * `collectInterceptionRewrites` sorts it at build time, so the deepest owner a
461
+ * single chain passes through wins and nothing here has to score (TIM-1318).
462
+ * Tree-walk order used to decide it, which meant renaming a route group flipped
463
+ * which modal opened. The precondition is a property of the manifest this reads
464
+ * rather than something it can re-derive, so it is asserted at its source:
465
+ * `tests/interception.test.ts` §"rewrite order is decided by scope depth".
466
+ */
467
+ function findInterceptionMatch(targetPathname, resolveSourceScopes, rewrites) {
468
+ const candidates = rewrites.filter((rewrite) => pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern));
469
+ if (candidates.length === 0) return null;
470
+ const scopes = resolveSourceScopes();
471
+ if (!scopes) return null;
472
+ for (const scope of scopes) for (const rewrite of candidates) if (scope.has(rewrite.interceptingScope)) return rewrite;
473
+ return null;
474
+ }
475
+ /**
476
+ * Check if a pathname matches a URL pattern with dynamic segments.
477
+ *
478
+ * Supports [param] (single segment) and [...param] (one or more segments).
479
+ * Static segments must match exactly.
480
+ */
481
+ function pathnameMatchesPattern(pathname, pattern) {
482
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
483
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
484
+ let pi = 0;
485
+ for (let i = 0; i < patternParts.length; i++) {
486
+ const seg = classifyUrlSegment(patternParts[i]);
487
+ switch (seg.kind) {
488
+ case "catch-all": return pi < pathParts.length;
489
+ case "optional-catch-all": return true;
490
+ case "dynamic": {
491
+ if (pi >= pathParts.length) return false;
492
+ const prefix = seg.prefix ?? "";
493
+ const suffix = seg.suffix ?? "";
494
+ const pathPart = pathParts[pi];
495
+ if (prefix || suffix) {
496
+ if (pathPart.length <= prefix.length + suffix.length || prefix && !pathPart.startsWith(prefix) || suffix && !pathPart.endsWith(suffix)) return false;
497
+ }
498
+ pi++;
499
+ continue;
500
+ }
501
+ case "static":
502
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
503
+ pi++;
504
+ continue;
505
+ }
506
+ }
507
+ return pi === pathParts.length;
508
+ }
509
+ //#endregion
510
+ //#region src/server/state-tree-diff.ts
511
+ /**
512
+ * State Tree Diffing — Server-side parsing and diffing of X-Timber-State-Tree.
513
+ *
514
+ * The client sends X-Timber-State-Tree on navigation requests, listing
515
+ * the sync segments it has cached. The server diffs this against the
516
+ * target route's segments to skip re-rendering unchanged sync layouts.
517
+ *
518
+ * This is a performance optimization only — NOT a security boundary.
519
+ * All access.ts files run regardless of the state tree content.
520
+ * A fabricated state tree can only cause extra rendering work or stale
521
+ * layouts — never auth bypass.
522
+ *
523
+ * See design/19-client-navigation.md §"X-Timber-State-Tree Header"
524
+ * See design/13-security.md §"State tree manipulation"
525
+ */
526
+ /**
527
+ * Parse the X-Timber-State-Tree header from a request.
528
+ *
529
+ * Returns a Set of segment paths the client has cached (with an
530
+ * additional `slots` property for cached slot paths), or null if
531
+ * the header is missing, malformed, or empty. Parsing happens before
532
+ * renderToReadableStream — not inside the React render pass.
533
+ *
534
+ * @returns ClientStateTree with segments and slots, or null if no valid state tree
535
+ */
536
+ function parseClientStateTree(req) {
537
+ const header = req.headers.get("X-Timber-State-Tree");
538
+ if (!header) return null;
539
+ try {
540
+ const parsed = JSON.parse(header);
541
+ const hasSegments = Array.isArray(parsed.segments) && parsed.segments.length > 0;
542
+ const hasSlots = Array.isArray(parsed.slots) && parsed.slots.length > 0;
543
+ const hasTreePaths = Array.isArray(parsed.treePaths) && parsed.treePaths.length > 0;
544
+ if (!hasSegments && !hasSlots && !hasTreePaths) return null;
545
+ const result = new Set(hasSegments ? parsed.segments : []);
546
+ result.slots = hasSlots ? new Set(parsed.slots) : null;
547
+ result.treePaths = hasTreePaths ? new Set(parsed.treePaths) : null;
548
+ return result;
549
+ } catch (err) {
550
+ swallow(err, "malformed X-Timber-State-Tree header");
551
+ return null;
552
+ }
553
+ }
554
+ //#endregion
555
+ //#region src/server/response-cache-policy.ts
556
+ /**
557
+ * Legacy shared-cache control fields that predate RFC 9213 and so do not
558
+ * follow the `<target>-Cache-Control` naming pattern — the one part of this
559
+ * rule that cannot be matched by shape. `X-Accel-Expires` is nginx
560
+ * `proxy_cache`, which gives it precedence over `Cache-Control`.
561
+ *
562
+ * A closed historical set, unlike the vendor `*-Cache-Control` names, which
563
+ * keep being minted and are handled by pattern below.
564
+ */
565
+ var LEGACY_CDN_CACHE_HEADERS = [
566
+ "Surrogate-Control",
567
+ "Edge-Control",
568
+ "X-Accel-Expires"
569
+ ];
570
+ /**
571
+ * Whether a response header overrides `Cache-Control` at a shared cache.
572
+ *
573
+ * Matched by *shape*, not by vendor name. RFC 9213 defines targeted fields
574
+ * as `<target>-Cache-Control`, and every CDN spells its own: `CDN-`,
575
+ * `Cloudflare-CDN-`, `Netlify-CDN-`, `Vercel-CDN-`, and whichever ships
576
+ * next. A vendor list here is a denylist with an unbounded tail — it was
577
+ * extended twice during review, each time by one name, which is the signal
578
+ * that enumeration is the wrong shape. The suffix rule is total.
579
+ *
580
+ * `Cache-Control` itself does not match (no `-` prefix) and is replaced
581
+ * separately.
582
+ */
583
+ function isSharedCacheOverride(name) {
584
+ const lowered = name.toLowerCase();
585
+ return lowered.endsWith("-cache-control") || LEGACY_CDN_CACHE_HEADERS.some((legacy) => legacy.toLowerCase() === lowered);
586
+ }
587
+ /** Disable caching, including CDN overrides that take precedence over Cache-Control. */
588
+ function preventResponseCaching(headers) {
589
+ const overrides = [];
590
+ for (const name of headers.keys()) if (isSharedCacheOverride(name)) overrides.push(name);
591
+ for (const name of overrides) headers.delete(name);
592
+ headers.set("Cache-Control", "private, no-store");
593
+ }
594
+ //#endregion
595
+ //#region src/server/error-response-headers.ts
596
+ /** Preserve request-wide metadata when replacing a failed response body. */
597
+ function errorResponseHeaders(responseHeaders) {
598
+ const headers = new Headers(responseHeaders);
599
+ headers.delete("Content-Length");
600
+ headers.delete("Content-Encoding");
601
+ headers.delete("Transfer-Encoding");
602
+ preventResponseCaching(headers);
603
+ headers.delete("ETag");
604
+ headers.delete("Last-Modified");
605
+ headers.delete("Expires");
606
+ headers.delete("Age");
607
+ return headers;
608
+ }
609
+ //#endregion
610
+ //#region src/server/rsc-error-envelope.ts
611
+ /**
612
+ * Build the hard-navigate envelope for a status code.
613
+ *
614
+ * Preserve middleware's request-wide headers and cookies, but discard the
615
+ * abandoned body's framing, validators, and cache policy. Every producer,
616
+ * including errors returned normally during render, gets this cleanup here.
617
+ * The input header bag is left intact. The body deliberately carries no message —
618
+ * only the status already on the wire (design/13-security.md principle 4).
619
+ */
620
+ function rscErrorEnvelope(status, responseHeaders) {
621
+ const headers = errorResponseHeaders(responseHeaders);
622
+ headers.set(TIMBER_ERROR_HEADER, "1");
623
+ headers.set("content-type", "application/json; charset=utf-8");
624
+ return new Response(JSON.stringify({
625
+ error: true,
626
+ status
627
+ }), {
628
+ status,
629
+ headers
630
+ });
631
+ }
632
+ //#endregion
633
+ //#region src/server/pipeline-outcome.ts
634
+ /**
635
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
636
+ * each phase function returns) into a final `Response`.
637
+ *
638
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
639
+ * catch logic and the terminal Response-building logic each live in
640
+ * their own file. The phases produce values; this module is the single
641
+ * source of truth for how those values become wire responses.
642
+ *
643
+ * See design/07-routing.md §"Request Lifecycle".
644
+ */
645
+ function rscErrorResponse(isRsc, status, headers) {
646
+ if (isRsc) return rscErrorEnvelope(status, headers);
647
+ return new Response(null, {
648
+ status,
649
+ headers: errorResponseHeaders(headers)
650
+ });
651
+ }
652
+ /**
653
+ * Resolve the header bag a signal/error outcome is written onto, with the
654
+ * cookie jar applied exactly once.
655
+ *
656
+ * Ownership rule (design/49 §P0b): the phase that owns `responseHeaders`
657
+ * applies the jar to it once; the translator applies it only for outcomes
658
+ * that arrive without it. Render-phase outcomes already carry the jar —
659
+ * `runRenderPhase()` applies it on entry, with or without a middleware
660
+ * chain — so re-applying here emitted every middleware `Set-Cookie` twice
661
+ * (TIM-1491).
662
+ *
663
+ * The guard is "not render", not "only middleware": proxy-phase signals
664
+ * reach the translator with no `responseHeaders` at all, and for a
665
+ * `proxy.ts` that awaits `next()` and then throws, this is the only place
666
+ * the cookies downstream middleware set can reach the wire
667
+ * (design/29-cookies.md §"proxy.ts Cookie Access"). Middleware-phase
668
+ * signals throw before that phase's own application, so they need it too.
669
+ */
670
+ function outcomeHeaders(outcome, ctx) {
671
+ const headers = ctx.responseHeaders ?? new Headers();
672
+ if (outcome.phase !== "render") applyCookieJar(headers);
673
+ return headers;
674
+ }
675
+ /**
676
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
677
+ * `Response`, applying cookies, building redirects, rendering deny pages
678
+ * and fallback error pages, and firing instrumentation hooks.
679
+ *
680
+ * This is the single source of truth for how phase outputs become wire
681
+ * responses; the per-phase try/catch blocks now produce values, not
682
+ * Responses, so the conversion logic lives in exactly one place.
683
+ */
684
+ async function outcomeToResponse(config, outcome, ctx) {
685
+ switch (outcome.kind) {
686
+ case "response": {
687
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
688
+ if (outcome.phase === "proxy") return finalResponse;
689
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
690
+ applyCookieJar(finalResponse.headers);
691
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
692
+ logMiddlewareShortCircuit({
693
+ method: ctx.method,
694
+ path: ctx.path,
695
+ status: finalResponse.status
696
+ });
697
+ }
698
+ if (outcome.phase === "render") markResponseFlushed();
699
+ return finalResponse;
700
+ }
701
+ case "redirect": {
702
+ const headers = outcomeHeaders(outcome, ctx);
703
+ return buildRedirectResponse(outcome.signal, ctx.req, headers);
704
+ }
705
+ case "deny": {
706
+ const headers = outcomeHeaders(outcome, ctx);
707
+ if (config.renderDenyFallback) try {
708
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
709
+ } catch (denyRenderError) {
710
+ logRenderError({
711
+ method: ctx.method,
712
+ path: ctx.path,
713
+ error: denyRenderError
714
+ });
715
+ await fireOnRequestError(denyRenderError, ctx.req, "render");
716
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
717
+ }
718
+ if (isDebug()) console.warn(`[timber] DenySignal(${outcome.signal.status}) from ${outcome.phase} phase — no renderDenyFallback configured, returning bare ${outcome.signal.status} response\n Request: ${ctx.method} ${ctx.path}\n Add a status-code file (e.g. 404.tsx) or error.tsx to render a custom deny page.`);
719
+ return new Response(null, {
720
+ status: outcome.signal.status,
721
+ headers
722
+ });
723
+ }
724
+ case "error": {
725
+ const isRsc = isRscRequest(ctx.req);
726
+ if (outcome.phase === "proxy") {
727
+ logProxyError({ error: outcome.error });
728
+ await fireOnRequestError(outcome.error, ctx.req, "proxy");
729
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "proxy");
730
+ return rscErrorResponse(isRsc, 500, outcomeHeaders(outcome, ctx));
731
+ }
732
+ if (outcome.phase === "middleware") {
733
+ logMiddlewareError({
734
+ method: ctx.method,
735
+ path: ctx.path,
736
+ error: outcome.error
737
+ });
738
+ await fireOnRequestError(outcome.error, ctx.req, "handler");
739
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "middleware");
740
+ return rscErrorResponse(isRsc, 500, outcomeHeaders(outcome, ctx));
741
+ }
742
+ const headers = outcomeHeaders(outcome, ctx);
743
+ logRenderError({
744
+ method: ctx.method,
745
+ path: ctx.path,
746
+ error: outcome.error
747
+ });
748
+ await fireOnRequestError(outcome.error, ctx.req, "render");
749
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "render");
750
+ if (isRsc) return rscErrorResponse(true, 500, headers);
751
+ if (config.renderFallbackError) try {
752
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, headers));
753
+ } catch (fallbackRenderError) {
754
+ logRenderError({
755
+ method: ctx.method,
756
+ path: ctx.path,
757
+ error: fallbackRenderError
758
+ });
759
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render");
760
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
761
+ }
762
+ return rscErrorResponse(false, 500, headers);
763
+ }
764
+ }
765
+ }
766
+ //#endregion
767
+ //#region src/server/pipeline-phases.ts
768
+ /**
769
+ * Pipeline phase functions — module-level free functions that take their
770
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
771
+ * (a discriminated union over response / redirect / deny / error) defined
772
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
773
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
774
+ *
775
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
776
+ * isolation. The lift is mechanical — these functions used to be closures
777
+ * over `config`; they now take `config` as an explicit parameter.
778
+ *
779
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
780
+ */
781
+ /**
782
+ * Validate and canonicalize the X-Timber-URL header value.
783
+ *
784
+ * Returns the canonical pathname if valid, or null if rejected:
785
+ * - Must start with '/' (relative pathname, no scheme/authority)
786
+ * - Must not contain control characters
787
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
788
+ */
789
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
790
+ if (!raw.startsWith("/")) return null;
791
+ if (raw.startsWith("//")) return null;
792
+ for (let i = 0; i < raw.length; i++) {
793
+ const code = raw.charCodeAt(i);
794
+ if (code <= 31 || code === 127) return null;
795
+ }
796
+ const result = canonicalize(raw, stripTrailingSlash);
797
+ if (!result.ok) return null;
798
+ return result.pathname;
799
+ }
800
+ /**
801
+ * Run the proxy.ts phase. Calls user proxy code with a `next()` continuation.
802
+ *
803
+ * When `next` is provided, it replaces the default `handleRequest` as the
804
+ * continuation — this lets the pipeline inject action dispatch between proxy
805
+ * and route matching (TIM-1213). The proxy resolver was picked at pipeline
806
+ * construction time so the hot path sees no per-request branching on the
807
+ * `ProxyConfig` discriminant.
808
+ */
809
+ async function runProxyPhase(config, getProxy, req, method, path, next) {
810
+ const detailed = config.serverTiming === "detailed";
811
+ try {
812
+ const proxyExport = await getProxy();
813
+ const continuation = next ?? (() => handleRequest(config, req, method, path, true));
814
+ const proxyFn = () => runProxy(proxyExport, req, continuation);
815
+ return {
816
+ kind: "response",
817
+ phase: "proxy",
818
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
819
+ };
820
+ } catch (error) {
821
+ if (isRedirectSignal(error)) return {
822
+ kind: "redirect",
823
+ phase: "proxy",
824
+ signal: error
825
+ };
826
+ if (isDenySignal(error)) return {
827
+ kind: "deny",
828
+ phase: "proxy",
829
+ signal: error
830
+ };
831
+ return {
832
+ kind: "error",
833
+ phase: "proxy",
834
+ error
835
+ };
836
+ }
837
+ }
838
+ /**
839
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
840
+ * returns it as a 'response' outcome. Otherwise applies the request header
841
+ * overlay and falls through to the render phase.
842
+ */
843
+ async function runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext) {
844
+ const detailed = config.serverTiming === "detailed";
845
+ const ctx = {
846
+ req,
847
+ requestHeaders: requestHeaderOverlay,
848
+ headers: responseHeaders,
849
+ segmentParams: match.segmentParams,
850
+ get nonce() {
851
+ return requestCspNonce();
852
+ },
853
+ earlyHints: (hints) => {
854
+ for (const hint of hints) {
855
+ let value;
856
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
857
+ else value = `<${hint.href}>; rel=${hint.rel}`;
858
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
859
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
860
+ responseHeaders.append("Link", value);
861
+ }
862
+ }
863
+ };
864
+ try {
865
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
866
+ const middlewareResponse = await (async () => {
867
+ setMutableCookieContext(true);
868
+ try {
869
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
870
+ } finally {
871
+ setMutableCookieContext(false);
872
+ }
873
+ })();
874
+ if (middlewareResponse) return {
875
+ kind: "response",
876
+ phase: "middleware",
877
+ response: middlewareResponse
878
+ };
879
+ applyRequestHeaderOverlay(requestHeaderOverlay);
880
+ return runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext);
881
+ } catch (error) {
882
+ if (isRedirectSignal(error)) return {
883
+ kind: "redirect",
884
+ phase: "middleware",
885
+ signal: error
886
+ };
887
+ if (isDenySignal(error)) return {
888
+ kind: "deny",
889
+ phase: "middleware",
890
+ signal: error
891
+ };
892
+ return {
893
+ kind: "error",
894
+ phase: "middleware",
895
+ error
896
+ };
897
+ }
898
+ }
899
+ /**
900
+ * Run the render phase. Wraps the configured renderer in a span and a
901
+ * timing scope, and translates thrown signals into outcome variants.
902
+ *
903
+ * The render phase owns `responseHeaders` from here on, so it is the one
904
+ * place the cookie jar is applied to that bag (design/29-cookies.md
905
+ * §"Applied Exactly Once"). Doing it here rather than in the middleware
906
+ * phase means every render-phase outcome — a 200, or a deny / redirect /
907
+ * error thrown from render — carries the jar whether or not a middleware
908
+ * chain ran, and `outcomeToResponse` can skip render-phase outcomes
909
+ * unconditionally (TIM-1491). Application precedes `config.render` so
910
+ * middleware cookie writes are visible to route-handler header merging,
911
+ * while handler `Set-Cookie` values still come after them and take
912
+ * precedence.
913
+ */
914
+ async function runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, { canonicalPathname, interception }) {
915
+ const detailed = config.serverTiming === "detailed";
916
+ applyCookieJar(responseHeaders);
917
+ try {
918
+ const renderFn = () => config.render(req, match, responseHeaders, requestHeaderOverlay, interception);
919
+ return {
920
+ kind: "response",
921
+ phase: "render",
922
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
923
+ };
924
+ } catch (error) {
925
+ if (isDenySignal(error)) return {
926
+ kind: "deny",
927
+ phase: "render",
928
+ signal: error
929
+ };
930
+ if (isRedirectSignal(error)) return {
931
+ kind: "redirect",
932
+ phase: "render",
933
+ signal: error
934
+ };
935
+ return {
936
+ kind: "error",
937
+ phase: "render",
938
+ error
939
+ };
940
+ }
941
+ }
942
+ /**
943
+ * Process a single request from canonicalization through phase dispatch.
944
+ *
945
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
946
+ * route match → interception → early hints → param coercion → middleware →
947
+ * render → outcome translation. Pre-routing short-circuits return Responses
948
+ * directly; post-match dispatch goes through `outcomeToResponse`.
949
+ *
950
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
951
+ * the `next()` continuation passed to `runProxy()`.
952
+ *
953
+ * @param pathIsCanonical When true, `path` has already been canonicalized by
954
+ * `createPipeline` — skip re-canonicalization to prevent double-decode.
955
+ * When false (default), runs canonicalize as a safety net for direct callers.
956
+ */
957
+ async function handleRequest(config, req, method, path, pathIsCanonical) {
958
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
959
+ let canonicalPathname;
960
+ if (pathIsCanonical) canonicalPathname = path;
961
+ else {
962
+ const result = canonicalize(path, stripTrailingSlash);
963
+ if (!result.ok) {
964
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${path} — responding with ${result.status}\n This usually means the URL contains encoded separators (%2f, %5c),\n null bytes (%00), path traversal (..), or malformed percent-encoding.`);
965
+ return new Response(null, { status: result.status });
966
+ }
967
+ canonicalPathname = result.pathname;
968
+ }
969
+ if (config.matchMetadataRoute) {
970
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
971
+ if (metaMatch) try {
972
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
973
+ setSegmentParams(metaMatch.segmentParams);
974
+ const mod = await loadModule(metaMatch.file);
975
+ if (typeof mod.default !== "function") {
976
+ if (isDebug()) console.warn(`[timber] Metadata route ${metaMatch.file} does not export a default function — responding with 500\n Metadata routes must export a default function that returns the metadata content.`);
977
+ return new Response("Metadata route must export a default function", { status: 500 });
978
+ }
979
+ const handlerResult = await mod.default();
980
+ if (handlerResult instanceof Response) return cloneWithMutableHeaders(handlerResult);
981
+ const contentType = metaMatch.contentType;
982
+ let body;
983
+ if (typeof handlerResult === "string") body = handlerResult;
984
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
985
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
986
+ else body = String(handlerResult);
987
+ return new Response(body, {
988
+ status: 200,
989
+ headers: {
990
+ "Content-Type": `${contentType}; charset=utf-8`,
991
+ "Cache-Control": "public, max-age=14400, must-revalidate"
992
+ }
993
+ });
994
+ } catch (error) {
995
+ if (isRedirectSignal(error)) return new Response(null, {
996
+ status: error.status,
997
+ headers: { Location: error.location }
998
+ });
999
+ if (isDenySignal(error)) return new Response(null, { status: error.status });
1000
+ logRenderError({
1001
+ method,
1002
+ path,
1003
+ error
1004
+ });
1005
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
1006
+ return new Response(null, { status: 500 });
1007
+ }
1008
+ }
1009
+ if (config.autoSitemapHandler) try {
1010
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
1011
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
1012
+ } catch (error) {
1013
+ logRenderError({
1014
+ method,
1015
+ path,
1016
+ error
1017
+ });
1018
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
1019
+ return new Response(null, { status: 500 });
1020
+ }
1021
+ const isRsc = isRscRequest(req);
1022
+ if (isRsc) {
1023
+ if (!checkVersionSkew(req).ok) {
1024
+ const reloadHeaders = new Headers();
1025
+ applyReloadHeaders(reloadHeaders);
1026
+ return new Response(null, {
1027
+ status: 204,
1028
+ headers: reloadHeaders
1029
+ });
1030
+ }
1031
+ }
1032
+ let match = config.matchRoute(canonicalPathname);
1033
+ let interception;
1034
+ if (isRsc && config.interceptionRewrites?.length) {
1035
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
1036
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
1037
+ if (validatedSourceUrl) {
1038
+ const resolveSourceScopes = () => {
1039
+ const mounted = new Set(parseClientStateTree(req)?.treePaths ?? []);
1040
+ const sourceRoute = config.matchRoute(validatedSourceUrl);
1041
+ const scopes = [mounted, new Set(sourceRoute ? computeSegmentTreePaths(sourceRoute.segments) : [])].filter((scope) => scope.size > 0);
1042
+ return scopes.length > 0 ? scopes : null;
1043
+ };
1044
+ const rewrite = findInterceptionMatch(canonicalPathname, resolveSourceScopes, config.interceptionRewrites);
1045
+ if (rewrite?.mode === "children") {
1046
+ const interceptedMatch = config.matchInterceptedRoute?.(canonicalPathname, rewrite.interceptingScope);
1047
+ if (interceptedMatch) match = interceptedMatch;
1048
+ } else if (rewrite) {
1049
+ const sourceMatch = config.matchRoute(rewrite.interceptingPrefix);
1050
+ if (sourceMatch !== null && computeSegmentTreePaths(sourceMatch.segments).includes(rewrite.interceptingScope)) {
1051
+ match = sourceMatch;
1052
+ interception = { targetPathname: canonicalPathname };
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ if (!match) {
1058
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
1059
+ if (config.renderNoMatch) {
1060
+ const responseHeaders = new Headers();
1061
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
1062
+ }
1063
+ return new Response(null, { status: 404 });
1064
+ }
1065
+ const responseHeaders = new Headers();
1066
+ const requestHeaderOverlay = new Headers();
1067
+ responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
1068
+ const leafSegment = match.segments[match.segments.length - 1];
1069
+ const isApiRoute = leafSegment?.route && !leafSegment?.page;
1070
+ if (config.earlyHints && !isRsc && !isApiRoute) try {
1071
+ await config.earlyHints(match, req, responseHeaders);
1072
+ } catch (err) {
1073
+ swallow(err, "early hints hook threw");
1074
+ }
1075
+ match.rawSegmentParams = { ...match.segmentParams };
1076
+ try {
1077
+ await coerceSegmentParams(match);
1078
+ } catch (error) {
1079
+ if (error instanceof ParamCoercionError) {
1080
+ if (isDebug()) {
1081
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
1082
+ console.warn(`[timber] Param coercion failed for ${method} ${canonicalPathname} — responding with 404\n Matched segments: ${segmentChain}\n Error: ${error.message}\n This usually means a codec in app/schema.ts rejected the URL value.\n Check the codec for the bracket key of the segment named above.`);
1083
+ }
1084
+ const leafSegment = match.segments[match.segments.length - 1];
1085
+ if (leafSegment.route && !leafSegment.page) return new Response(null, { status: 404 });
1086
+ if (config.renderNoMatch) return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
1087
+ return new Response(null, { status: 404 });
1088
+ }
1089
+ throw error;
1090
+ }
1091
+ setSegmentParams(match.segmentParams);
1092
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
1093
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
1094
+ return outcomeToResponse(config, match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, {
1095
+ canonicalPathname,
1096
+ interception
1097
+ }) : await runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, {
1098
+ canonicalPathname,
1099
+ interception
1100
+ }), {
1101
+ req,
1102
+ method,
1103
+ path,
1104
+ responseHeaders,
1105
+ match
1106
+ });
1107
+ }
1108
+ //#endregion
1109
+ //#region src/server/rsc-cache-key-guard.ts
1110
+ /**
1111
+ * Origin-side binding of the `_rsc` cache key to the request that produced
1112
+ * the response (TIM-1268).
1113
+ *
1114
+ * The key is deterministic, and deliberately so — that is what makes RSC
1115
+ * payloads cacheable. But deterministic also means *predictable*: anyone can
1116
+ * compute the key another client will request. Without this guard, a caller
1117
+ * could request `/about?_rsc=<victim's key>` while sending its own
1118
+ * `X-Timber-State-Tree`, and a shared cache that keys by URL — the exact
1119
+ * environment this feature targets — would store that variant under the
1120
+ * victim's key. Every subsequent legitimate navigation would then be served
1121
+ * a payload rendered for someone else's segment tree or deployment.
1122
+ *
1123
+ * The guard is a *storability* rule, not a rejection: if the claimed key
1124
+ * does not match the key derived from the received headers, the response
1125
+ * loses its shared-cache directives. Mismatched requests are still served
1126
+ * normally, they just cannot be stored for anyone else.
1127
+ *
1128
+ * Why not Next.js's 307 self-correction: a redirect is cacheable in its own
1129
+ * right, costs a round trip on every legitimate miss, and would make the
1130
+ * server's behaviour depend on a parameter it otherwise never reads. This
1131
+ * rule closes the same hole by making the poisoned entry unstorable at the
1132
+ * source, in the response the developer already has to opt into sharing.
1133
+ *
1134
+ * See design/19-client-navigation.md §"The `_rsc` cache key".
1135
+ */
1136
+ /**
1137
+ * Whether the request's `_rsc` parameter matches the key derived from its
1138
+ * own headers.
1139
+ *
1140
+ * Requests without the parameter are not claiming a key at all, so they are
1141
+ * left alone — the bare document URL is the developer's declared territory
1142
+ * (see design/32-response-caching.md, TIM-1264). Neither is a parameter
1143
+ * whose value could not be one of our digests: `_rsc` is not reserved, and
1144
+ * an application that already uses it for its own search state
1145
+ * (`/search?_rsc=foo`) must not have its cache policy silently revoked by a
1146
+ * guard that mistook that for a forgery.
1147
+ */
1148
+ async function hasValidRscCacheKey(req) {
1149
+ if (!req.url.includes("?")) return true;
1150
+ let values;
1151
+ try {
1152
+ values = new URL(req.url).searchParams.getAll(RSC_KEY_PARAM);
1153
+ } catch {
1154
+ return false;
1155
+ }
1156
+ const claims = values.filter(isRscCacheKeyShape);
1157
+ if (claims.length === 0) return true;
1158
+ const expected = await rscCacheKey((name) => req.headers.get(name));
1159
+ if (expected === null) return false;
1160
+ return claims.every((claim) => claim === expected);
1161
+ }
1162
+ /**
1163
+ * Ensure a Flight payload can never be interpreted as a document.
1164
+ *
1165
+ * Applied here, at the pipeline's single exit, rather than where each
1166
+ * payload response is built. Six places build one — the success path, three
1167
+ * in `deny-renderer.ts`, the action paths — and hardening them one at a time
1168
+ * is how you end up hardening five of six. The response is Flight if it says
1169
+ * it is; that is the only test that covers every producer, including ones
1170
+ * added later.
1171
+ *
1172
+ * Matters because the payload URL is observable and, on a shared-cache hit,
1173
+ * the origin is never consulted — so a top-level navigation can be handed
1174
+ * these bytes with no request-time check available. See design/13-security.md
1175
+ * #36c.
1176
+ */
1177
+ function hardenRscPayloadResponse(response) {
1178
+ if (!isRscContentType(response.headers.get("content-type"))) return;
1179
+ response.headers.set("X-Content-Type-Options", "nosniff");
1180
+ }
1181
+ /**
1182
+ * Make a response unstorable by any shared cache when its request claimed an
1183
+ * `_rsc` key that does not match its own headers.
1184
+ *
1185
+ * The end state is unconditional and therefore statable: **a mismatched
1186
+ * response is never stored by any cache.** Every targeted cache-control
1187
+ * field is removed and `Cache-Control` is replaced outright, rather than
1188
+ * downgrading only when a shared directive is spotted. Conditional variants
1189
+ * of this were tried and were wrong twice over — they missed the CDN-
1190
+ * specific headers, and leaving `Cache-Control` alone when it looked
1191
+ * harmless lets a CDN apply heuristic caching to a response that has none.
1192
+ *
1193
+ * The cost is that a mismatched request loses developer-chosen *browser*
1194
+ * caching too. That is a request no timber client ever makes.
1195
+ *
1196
+ * Purge tags (`Surrogate-Key`, `Cache-Tag`) are deliberately left alone:
1197
+ * they address stored entries, and this response is not stored.
1198
+ *
1199
+ * Mutates `response.headers` in place; the pipeline guarantees mutable
1200
+ * headers at this point (see TIM-866).
1201
+ */
1202
+ async function enforceRscCacheKey(req, response) {
1203
+ if (await hasValidRscCacheKey(req)) return;
1204
+ preventResponseCaching(response.headers);
1205
+ }
1206
+ //#endregion
1207
+ //#region src/server/head-response.ts
1208
+ /**
1209
+ * HEAD body stripping — RFC 9110 §9.3.2.
1210
+ *
1211
+ * "The HEAD method is identical to GET except that the server MUST NOT send
1212
+ * content in the response." The headers, however, must be the ones the
1213
+ * corresponding GET would have produced — which is why timber renders the
1214
+ * route in full and discards the body here rather than short-circuiting the
1215
+ * render. Content-Type, Content-Length, Set-Cookie, cache directives and
1216
+ * everything else ride through untouched.
1217
+ *
1218
+ * Node's `ServerResponse` happens to discard writes for HEAD, so the wire is
1219
+ * usually correct even without this. That is a property of one adapter, not of
1220
+ * the `Response` object: static generation, the Cloudflare and Nitro adapters,
1221
+ * tests, and anything calling the pipeline handler as a function all observe
1222
+ * the `Response` directly and saw the full body before TIM-1324.
1223
+ *
1224
+ * The pipeline applies this at its single exit so every response shape is
1225
+ * covered — page render, API route, metadata route, deny page, error page,
1226
+ * proxy short-circuit. The two unit-level producers that are also reachable as
1227
+ * standalone functions (`handleRouteRequest`, `handleApiRoute`) call it too, so
1228
+ * each honours HEAD on its own; they share this implementation rather than
1229
+ * repeating it, and applying it twice is a no-op.
1230
+ */
1231
+ /**
1232
+ * Return a bodyless copy of `response` when `method` is HEAD.
1233
+ *
1234
+ * A no-op for every other method and for responses that already carry no body
1235
+ * (204, 304, redirects), so callers do not need to pre-check either.
1236
+ *
1237
+ * The discarded stream is cancelled: an SSR render that reached this point has
1238
+ * a live producer attached, and dropping the reference without cancelling
1239
+ * leaks it for the lifetime of the render (design/13-security.md A4).
1240
+ */
1241
+ function stripHeadBody(response, method) {
1242
+ if (method.toUpperCase() !== "HEAD") return response;
1243
+ const body = response.body;
1244
+ if (body === null) return response;
1245
+ try {
1246
+ body.cancel().catch(() => {});
1247
+ } catch {}
1248
+ return new Response(null, {
1249
+ status: response.status,
1250
+ statusText: response.statusText,
1251
+ headers: response.headers
1252
+ });
1253
+ }
1254
+ //#endregion
1255
+ //#region src/server/pipeline.ts
1256
+ /**
1257
+ * Create the request handler from a pipeline configuration.
1258
+ *
1259
+ * Returns a function that processes an incoming Request through all pipeline
1260
+ * stages and produces a Response. This is the top-level entry point for the
1261
+ * server. The body is intentionally small — phase logic lives in
1262
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
1263
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
1264
+ * scope, Server-Timing header emission, and the active-request counter.
1265
+ */
1266
+ function createPipeline(config) {
1267
+ const proxyResolver = makeProxyResolver(config.proxy);
1268
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
1269
+ const serverTiming = config.serverTiming ?? "total";
1270
+ let activeRequests = 0;
1271
+ const pipelineFn = async (req) => {
1272
+ const url = new URL(req.url);
1273
+ const method = req.method;
1274
+ const path = url.pathname;
1275
+ const startTime = performance.now();
1276
+ activeRequests++;
1277
+ const traceIdValue = generateTraceId();
1278
+ return runWithTraceId(traceIdValue, async () => {
1279
+ return runWithRequestContext(req, async () => {
1280
+ const runRequest = async () => {
1281
+ logRequestReceived({
1282
+ method,
1283
+ path
1284
+ });
1285
+ const response = await withSpan("http.server.request", {
1286
+ "http.request.method": method,
1287
+ "url.path": path
1288
+ }, async () => {
1289
+ const otelIds = await getOtelTraceId();
1290
+ if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
1291
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1292
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
1293
+ if (!canonResult.ok) {
1294
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${url.pathname} — responding with ${canonResult.status}\n This usually means the URL contains encoded separators (%2f, %5c),\n null bytes (%00), path traversal (..), or malformed percent-encoding.`);
1295
+ return new Response(null, { status: canonResult.status });
1296
+ }
1297
+ const canonicalPath = canonResult.pathname;
1298
+ let canonicalReq = req;
1299
+ if (url.pathname !== canonicalPath) {
1300
+ const canonicalUrl = new URL(req.url);
1301
+ canonicalUrl.pathname = canonicalPath;
1302
+ canonicalReq = new Request(canonicalUrl.toString(), req);
1303
+ }
1304
+ const innerHandler = async () => {
1305
+ if (config.dispatchAction) {
1306
+ const actionResult = await config.dispatchAction(canonicalReq, canonicalPath, pipelineFn);
1307
+ if (actionResult) return actionResult;
1308
+ }
1309
+ return handleRequest(config, canonicalReq, method, canonicalPath, true);
1310
+ };
1311
+ let result;
1312
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath, innerHandler), {
1313
+ req: canonicalReq,
1314
+ method,
1315
+ path: canonicalPath
1316
+ });
1317
+ else result = await innerHandler();
1318
+ await setSpanAttribute("http.response.status_code", result.status);
1319
+ const varyTokens = [...RSC_KEY_HEADERS];
1320
+ const existingVary = result.headers.get("Vary");
1321
+ const existingTokens = existingVary ? existingVary.toLowerCase().split(",").map((t) => t.trim()) : [];
1322
+ const newTokens = varyTokens.filter((t) => !existingTokens.includes(t.toLowerCase()));
1323
+ if (newTokens.length > 0) result.headers.set("Vary", existingVary ? `${existingVary}, ${newTokens.join(", ")}` : newTokens.join(", "));
1324
+ await enforceRscCacheKey(canonicalReq, result);
1325
+ hardenRscPayloadResponse(result);
1326
+ result = stripHeadBody(result, method);
1327
+ if (serverTiming === "detailed") {
1328
+ const timingHeader = getServerTimingHeader();
1329
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
1330
+ } else if (serverTiming === "total") {
1331
+ const totalMs = Math.round(performance.now() - startTime);
1332
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
1333
+ }
1334
+ if (serverTiming === "detailed" && result.body) result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
1335
+ status: result.status,
1336
+ statusText: result.statusText,
1337
+ headers: result.headers
1338
+ });
1339
+ return result;
1340
+ });
1341
+ const durationMs = Math.round(performance.now() - startTime);
1342
+ const status = response.status;
1343
+ const concurrency = activeRequests;
1344
+ activeRequests--;
1345
+ logRequestCompleted({
1346
+ method,
1347
+ path,
1348
+ status,
1349
+ durationMs,
1350
+ concurrency
1351
+ });
1352
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
1353
+ method,
1354
+ path,
1355
+ durationMs,
1356
+ threshold: slowRequestMs,
1357
+ concurrency
1358
+ });
1359
+ return response;
1360
+ };
1361
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
1362
+ });
1363
+ });
1364
+ };
1365
+ return pipelineFn;
1366
+ }
1367
+ //#endregion
1368
+ //#region src/server/early-hints.ts
1369
+ /**
1370
+ * 103 Early Hints utilities.
1371
+ *
1372
+ * Early Hints are sent before the final response to let the browser
1373
+ * start fetching critical resources (CSS, fonts, JS) while the server
1374
+ * is still rendering.
1375
+ *
1376
+ * The framework collects hints from two sources:
1377
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
1378
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
1379
+ *
1380
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
1381
+ * Link headers into 103 Early Hints responses.
1382
+ *
1383
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
1384
+ */
1385
+ /**
1386
+ * Format a single EarlyHint as a Link header value.
1387
+ *
1388
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
1389
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
1390
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
1391
+ * attribute order differs from Cloudflare's cached copy, the browser
1392
+ * sees two preload headers for the same URL (different attribute order)
1393
+ * and warns "Preload was ignored." Matching the order ensures the
1394
+ * browser deduplicates them correctly.
1395
+ *
1396
+ * Examples:
1397
+ * `</styles/root.css>; as=style; rel=preload`
1398
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
1399
+ * `</_timber/client.js>; rel=modulepreload`
1400
+ * `<https://fonts.googleapis.com>; rel=preconnect`
1401
+ */
1402
+ function formatLinkHeader(hint) {
1403
+ if (hint.as !== void 0) {
1404
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
1405
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1406
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1407
+ return value;
1408
+ }
1409
+ let value = `<${hint.href}>; rel=${hint.rel}`;
1410
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1411
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1412
+ return value;
1413
+ }
1414
+ /**
1415
+ * Collect all Link header strings for a matched route's segment chain.
1416
+ *
1417
+ * Walks the build manifest to emit hints for:
1418
+ * - CSS stylesheets (as=style; rel=preload)
1419
+ * - Font assets (as=font; rel=preload; crossorigin)
1420
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
1421
+ *
1422
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
1423
+ * Returns an empty array in dev mode (manifest is empty).
1424
+ */
1425
+ function collectEarlyHintHeaders(segments, manifest, options) {
1426
+ const result = [];
1427
+ const seenUrls = /* @__PURE__ */ new Set();
1428
+ const add = (url, header) => {
1429
+ if (!seenUrls.has(url)) {
1430
+ seenUrls.add(url);
1431
+ result.push(header);
1432
+ }
1433
+ };
1434
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
1435
+ href: url,
1436
+ rel: "preload",
1437
+ as: "style"
1438
+ }));
1439
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
1440
+ href: font.href,
1441
+ rel: "preload",
1442
+ as: "font",
1443
+ crossOrigin: "anonymous"
1444
+ }));
1445
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
1446
+ href: url,
1447
+ rel: "modulepreload"
1448
+ }));
1449
+ return result;
1450
+ }
1451
+ //#endregion
1452
+ //#region src/server/early-hints-sender.ts
1453
+ /**
1454
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
1455
+ *
1456
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
1457
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
1458
+ * the adapter can send these as a 103 Early Hints interim response before
1459
+ * the final response is ready.
1460
+ *
1461
+ * This module provides an ALS-based bridge: the generated entry point
1462
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
1463
+ * binding a per-request sender function. The pipeline calls
1464
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
1465
+ *
1466
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
1467
+ * converts Link headers into 103 automatically), no sender is installed
1468
+ * and `sendEarlyHints103()` is a no-op.
1469
+ *
1470
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
1471
+ */
1472
+ /**
1473
+ * Run a function with a per-request early hints sender installed.
1474
+ *
1475
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
1476
+ * bind the platform's writeEarlyHints capability for the request duration.
1477
+ */
1478
+ function runWithEarlyHintsSender(sender, fn) {
1479
+ return earlyHintsSenderAls.run(sender, fn);
1480
+ }
1481
+ /**
1482
+ * Send collected Link headers as a 103 Early Hints response.
1483
+ *
1484
+ * No-op if no sender is installed for the current request (e.g., on
1485
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
1486
+ *
1487
+ * Non-fatal: errors from the sender are caught and silently ignored.
1488
+ */
1489
+ function sendEarlyHints103(links) {
1490
+ if (!links.length) return;
1491
+ const sender = earlyHintsSenderAls.getStore();
1492
+ if (!sender) return;
1493
+ try {
1494
+ sender(links);
1495
+ } catch (err) {
1496
+ swallow(err, "early hints 103 send failed");
1497
+ }
1498
+ }
1499
+ //#endregion
1500
+ //#region src/client/error-reconstituter.tsx
1501
+ /**
1502
+ * Reconstitutes a SerializableError into a real Error instance before
1503
+ * passing to the user's error component.
1504
+ *
1505
+ * TSX error pages are 'use client' components that receive { error: Error, digest, reset }.
1506
+ * Error objects are not RSC-serializable (React Flight throws "Only plain objects
1507
+ * can be passed to Client Components"). This wrapper receives the error as a plain
1508
+ * SerializableError object, reconstitutes a real Error instance, and passes it
1509
+ * to the user's error component — ensuring error instanceof Error works correctly.
1510
+ *
1511
+ * See design/spike-TIM-565-unify-error-pages.md §"Edge Case B"
1512
+ * See design/10-error-handling.md §"RSC → SSR for Error Pages via SerializableError"
1513
+ */
1514
+ /**
1515
+ * Reconstitute a SerializableError into a real Error instance and render
1516
+ * the user's error component with the proper props.
1517
+ */
1518
+ function ErrorReconstituter({ error: serialized, digest, reset, component, status, data }) {
1519
+ const error = Object.assign(new Error(serialized.message), {
1520
+ name: serialized.name,
1521
+ ...serialized.stack != null ? { stack: serialized.stack } : {}
1522
+ });
1523
+ return createElement(component, {
1524
+ error,
1525
+ digest,
1526
+ reset,
1527
+ ...status != null ? {
1528
+ status,
1529
+ data
1530
+ } : {}
1531
+ });
1532
+ }
1533
+ //#endregion
1534
+ //#region src/server/deny-boundary.ts
1535
+ /**
1536
+ * Deny boundary subsystem — the in-tree DenySignal flow.
1537
+ *
1538
+ * Three things live together here because they form a single flow:
1539
+ *
1540
+ * 1. **Chain construction** (`buildDenyPageChain`) — walks the matched
1541
+ * segment chain at element-tree build time and produces a list of
1542
+ * `DenyPageEntry` records ordered by specificity (specific status →
1543
+ * category catch-all → `error.tsx`).
1544
+ *
1545
+ * 2. **Runtime matching and placement** (`matchDenyEntry`, `placeDenyPage`,
1546
+ * `handleCaughtDeny`) — picks the first chain entry whose status filter
1547
+ * matches the thrown DenySignal, then decides whether the catch site may
1548
+ * render it where it stands. A chain spans the catcher outward to root,
1549
+ * so a match may belong to an ancestor segment; rendering it in place
1550
+ * would wrap it in every layout in between. Ancestor-owned matches are
1551
+ * re-thrown with `ownerKey` stamped on the signal so the error boundary
1552
+ * at the owning segment renders it. See TIM-1356.
1553
+ *
1554
+ * 3. **The page boundary itself** (`PageDenyBoundary`) — the async server
1555
+ * component that wraps a server-component page, calls it, and catches
1556
+ * `DenySignal` so the deny page renders in-tree (no throw reaches
1557
+ * React Flight, single render pass).
1558
+ *
1559
+ * Plus the ALS helpers (`setDenyStatus` / `getDenyStatus`) the boundary
1560
+ * uses to thread the matched status code back to the pipeline so the
1561
+ * HTTP status reflects the deny.
1562
+ *
1563
+ * Folded into one module from the former `deny-page-resolver.ts` and
1564
+ * `page-deny-boundary.tsx` (TIM-853) — the names were misleading and the
1565
+ * three pieces only made sense together.
1566
+ *
1567
+ * See design/04-authorization.md, design/10-error-handling.md, TIM-666.
1568
+ */
1569
+ /**
1570
+ * Find the first deny page in the chain whose status filter matches.
1571
+ * Returns null when nothing in the chain accepts this status.
1572
+ *
1573
+ * For 4xx statuses, the chain's stored order is correct: every status file
1574
+ * across all segments (inner→outer) before any error.tsx — so a root
1575
+ * `404.tsx` beats a leaf `error.tsx`. This matches `resolve4xx`.
1576
+ *
1577
+ * For 5xx statuses, the match walks per-segment (inner→outer): at each
1578
+ * segment, status files (`503.tsx` → `5xx.tsx`) then `error.tsx`, before
1579
+ * moving to the next segment outward. A leaf `error.tsx` therefore beats a
1580
+ * root `5xx.tsx` — the intentional inverse of the 4xx chain, matching
1581
+ * `resolve5xx`. See TIM-1360.
1582
+ */
1583
+ function matchDenyEntry(chain, status) {
1584
+ return matchDenyEntries(chain, status)[0] ?? null;
1585
+ }
1586
+ /**
1587
+ * Return ALL deny page entries whose status filter matches, in traversal
1588
+ * order (best match first). `matchDenyEntry` returns only the first;
1589
+ * late addressing (TIM-1450) needs the full list so the client can find
1590
+ * the first *reachable* owner via its ancestry context.
1591
+ */
1592
+ function matchDenyEntries(chain, status) {
1593
+ if (status >= 500) return matchDenyEntries5xx(chain, status);
1594
+ const matches = [];
1595
+ for (const entry of chain) if (entry.status === status) matches.push(entry);
1596
+ else if (entry.status === 400 && status >= 400 && status <= 499) matches.push(entry);
1597
+ else if (entry.status === null) matches.push(entry);
1598
+ return matches;
1599
+ }
1600
+ /**
1601
+ * 5xx per-segment walk: at each segment (inner→outer), check status files
1602
+ * then error.tsx before moving outward. Mirrors `resolve5xx`.
1603
+ */
1604
+ function matchDenyEntries5xx(chain, status) {
1605
+ const segmentIndices = [];
1606
+ for (const entry of chain) if (!segmentIndices.includes(entry.segmentIndex)) segmentIndices.push(entry.segmentIndex);
1607
+ segmentIndices.sort((a, b) => b - a);
1608
+ const matches = [];
1609
+ for (const seg of segmentIndices) {
1610
+ for (const entry of chain) {
1611
+ if (entry.segmentIndex !== seg || entry.kind === "error") continue;
1612
+ if (entry.status === status) matches.push(entry);
1613
+ else if (entry.status === 500 && status >= 500 && status <= 599) matches.push(entry);
1614
+ }
1615
+ for (const entry of chain) {
1616
+ if (entry.segmentIndex !== seg || entry.kind !== "error") continue;
1617
+ matches.push(entry);
1618
+ }
1619
+ }
1620
+ return matches;
1621
+ }
1622
+ /**
1623
+ * Decide where the deny page for `status` renders, from the perspective of
1624
+ * the catch site at `selfKey`.
1625
+ *
1626
+ * The match itself is unchanged — first entry in fallback order wins, so
1627
+ * every path picks the same file. What this adds is the position: a chain
1628
+ * built at segment i spans i outward to root, so a matched entry is owned
1629
+ * either by the catcher or by one of its ancestors.
1630
+ *
1631
+ * - Owned by the catcher → `render`. The catcher already sits at the
1632
+ * owning segment's position.
1633
+ * - Owned by an ancestor → `hoist`. Rendering here would wrap the deny page
1634
+ * in every layout between the owner and the catcher. The caller re-throws
1635
+ * with `ownerKey` stamped on the signal so the boundary at that segment
1636
+ * renders it instead — inside the owner's layout, outside the rest.
1637
+ *
1638
+ * Returns null when no entry matches; the caller re-throws unannotated and
1639
+ * the re-render fallback resolves it.
1640
+ *
1641
+ * See design/04-authorization.md §"Where a Deny Page Renders", TIM-1356.
1642
+ */
1643
+ function placeDenyPage(chain, status, data, selfKey) {
1644
+ const entry = matchDenyEntry(chain, status);
1645
+ if (!entry) return null;
1646
+ if (entry.ownerKey !== selfKey) return {
1647
+ kind: "hoist",
1648
+ ownerKey: entry.ownerKey
1649
+ };
1650
+ return {
1651
+ kind: "render",
1652
+ element: renderDenyEntry(entry, status, data)
1653
+ };
1654
+ }
1655
+ /**
1656
+ * Build the element for a matched deny chain entry with the props contract
1657
+ * the file's convention documents:
1658
+ *
1659
+ * - Status-code files: { status, data }
1660
+ * - error.tsx (TSX): { error, digest, reset } via ErrorReconstituter, plus
1661
+ * { status, data } for dual-shape implementations. Without
1662
+ * the Error prop, any error.tsx written per the docs (reading
1663
+ * error.message) crashes — turning a clean deny(404) into a 500. TIM-1081.
1664
+ * - error.mdx: plain { status } — server component, static content.
1665
+ */
1666
+ function renderDenyEntry(entry, status, data) {
1667
+ const h = createElement;
1668
+ return h(StatusPageMarker, null, renderDenyPage(entry, status, data, h));
1669
+ }
1670
+ function renderDenyPage(entry, status, data, h) {
1671
+ if (entry.kind !== "error") return h(entry.component, {
1672
+ status,
1673
+ data
1674
+ });
1675
+ return h(ErrorReconstituter, {
1676
+ error: {
1677
+ message: `Access denied with status ${status}`,
1678
+ name: "DenySignal"
1679
+ },
1680
+ digest: null,
1681
+ reset: void 0,
1682
+ component: entry.component,
1683
+ status,
1684
+ data
1685
+ });
1686
+ }
1687
+ /**
1688
+ * The whole of what an in-tree catch site does with a `DenySignal`, shared
1689
+ * by all three of them (`PageDenyBoundary`, `TracedLayout`, `AccessGate`).
1690
+ *
1691
+ * Returns the deny page element when this catch site owns the matched file.
1692
+ * Otherwise it throws — annotated with `ownerKey` when an ancestor owns the
1693
+ * file, bare when nothing matched at all.
1694
+ *
1695
+ * `setDenyStatus` runs on the hoist path too, and must run *before* the
1696
+ * throw: on the document path the hoisted row fails the Fizz shell and the
1697
+ * re-render fallback serves the page, and the ALS status is what the
1698
+ * pipeline commits for it. The RSC payload path never reads it — a Flight
1699
+ * payload response is always 200 and the row itself carries the deny (TIM-1495).
1700
+ *
1701
+ * Either branch leaves part of the matched chain unmounted — hoisting sends
1702
+ * the render to a boundary that discards everything below it, and a layout
1703
+ * that denies returns the deny page instead of its own child outlet. What the
1704
+ * client then learns about the tree is decided by the boundary that renders
1705
+ * the page, at the commit that puts it on screen (`navigation-commit.ts`).
1706
+ */
1707
+ function handleCaughtDeny(chain, error, selfKey) {
1708
+ const placement = chain ? placeDenyPage(chain, error.status, error.data, selfKey) : null;
1709
+ if (placement?.kind === "render") {
1710
+ setDenyStatus(error.status);
1711
+ return placement.element;
1712
+ }
1713
+ if (placement?.kind === "hoist") {
1714
+ setDenyStatus(error.status);
1715
+ error.owners = [placement.ownerKey];
1716
+ }
1717
+ throw error;
1718
+ }
1719
+ /**
1720
+ * Set the deny status in the request context ALS.
1721
+ * Called from AccessGate / PageDenyBoundary when a DenySignal is caught.
1722
+ * The document path reads this after render to set the HTTP status code.
1723
+ */
1724
+ function setDenyStatus(status) {
1725
+ const store = requestContextAls.getStore();
1726
+ if (store) store.denyStatus = status;
1727
+ }
1728
+ /**
1729
+ * Record the first denied segment index in the request context ALS.
1730
+ * Called from AccessGate when a DenySignal is caught during render.
1731
+ * Only the first (shallowest) denial is recorded — deeper denials are
1732
+ * unreachable because the gate short-circuits the subtree.
1733
+ * See TIM-1363.
1734
+ */
1735
+ function setFirstDeniedSegmentIndex(index) {
1736
+ const store = requestContextAls.getStore();
1737
+ if (store && store._firstDeniedSegmentIndex === void 0) store._firstDeniedSegmentIndex = index;
1738
+ }
1739
+ //#endregion
1740
+ //#region src/server/access-gate.tsx
1741
+ /**
1742
+ * AccessGate and SlotAccessGate — framework-injected async server components.
1743
+ *
1744
+ * AccessGate wraps each segment's layout in the element tree. It calls the
1745
+ * segment's access.ts before the layout renders. If access.ts calls deny()
1746
+ * or redirect(), the signal propagates as a render-phase throw — caught by
1747
+ * the flush controller to produce the correct HTTP status code.
1748
+ *
1749
+ * SlotAccessGate wraps parallel slot content. On denial, it renders the
1750
+ * graceful degradation chain: denied.tsx → default.tsx → null. Slot denial
1751
+ * does not affect the HTTP status code.
1752
+ *
1753
+ * See design/04-authorization.md and design/02-rendering-pipeline.md §"AccessGate"
1754
+ */
1755
+ /**
1756
+ * Framework-injected access gate for segments.
1757
+ *
1758
+ * Calls accessFn during render — inside `renderToReadableStream`, sharing
1759
+ * the same `React.cache` scope as layouts and pages. A `requireUser()`
1760
+ * call in access.ts populates the cache; the same call in any layout is
1761
+ * a free hit. Access executes exactly once per request. See TIM-1363.
1762
+ *
1763
+ * access.ts is a pure gate — return values are discarded. The layout below
1764
+ * gets the same data by calling the same cached functions (React.cache dedup).
1765
+ *
1766
+ * On denial the gate renders the matching deny page only when this segment
1767
+ * owns it. Because the gate is wrapped OUTSIDE its own layout, that render
1768
+ * omits the denying segment's layout — deliberate, and the one place the
1769
+ * in-tree path diverges from `renderDenyPage`'s inclusive slice: a layout
1770
+ * whose access.ts denied must never run and serialize protected data into
1771
+ * the Flight stream (TIM-1074). An ancestor-owned page is hoisted instead,
1772
+ * because the gate also sits inside every layout above it and rendering
1773
+ * here would wrap the deny page in all of them (TIM-1356).
1774
+ *
1775
+ * For skipped segments (skippedSegment=true), deny pages are NOT rendered
1776
+ * in-tree — the client's cached layout chrome would wrap them incorrectly.
1777
+ * Instead, the deny is recorded in ALS and rethrown so the response path
1778
+ * can return rscErrorEnvelope for a client hard-navigate.
1779
+ */
1780
+ function AccessGate(props) {
1781
+ const { accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children } = props;
1782
+ return accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, skippedSegment ? void 0 : denyPages, skippedSegment, children);
1783
+ }
1784
+ /**
1785
+ * Calls accessFn during render with OTEL instrumentation.
1786
+ * Records the first denied segment index in ALS for post-render consumers.
1787
+ */
1788
+ async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children) {
1789
+ try {
1790
+ await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
1791
+ try {
1792
+ await accessFn();
1793
+ await setSpanAttribute("timber.result", "pass");
1794
+ } catch (error) {
1795
+ if (isDenySignal(error)) {
1796
+ await setSpanAttribute("timber.result", "deny");
1797
+ await setSpanAttribute("timber.deny_status", error.status);
1798
+ if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
1799
+ } else if (isRedirectSignal(error)) await setSpanAttribute("timber.result", "redirect");
1800
+ throw error;
1801
+ }
1802
+ });
1803
+ } catch (error) {
1804
+ if (isDenySignal(error)) {
1805
+ if (segmentIndex !== void 0) setFirstDeniedSegmentIndex(segmentIndex);
1806
+ if (skippedSegment) {
1807
+ error._hardNavigate = true;
1808
+ throw error;
1809
+ }
1810
+ if (denyPages) return handleCaughtDeny(denyPages, error, segmentKey);
1811
+ }
1812
+ throw error;
1813
+ }
1814
+ return children;
1815
+ }
1816
+ /**
1817
+ * Framework-injected access gate for parallel slots.
1818
+ *
1819
+ * On denial, graceful degradation: denied.tsx → default.tsx → null.
1820
+ * The HTTP status code is unaffected — slot denial is a UI concern, not
1821
+ * a protocol concern. The parent layout and sibling slots still render.
1822
+ *
1823
+ * DeniedComponent is passed instead of a pre-built element so that
1824
+ * DenySignal.data can be forwarded as the data prop
1825
+ * and the slot name can be passed as the slot prop. See TIM-488.
1826
+ *
1827
+ * redirect() in slot access.ts is a dev-mode error — redirecting from a
1828
+ * slot doesn't make architectural sense.
1829
+ */
1830
+ async function SlotAccessGate(props) {
1831
+ const { accessFn, DeniedComponent, slotName, createElement, defaultFallback, children } = props;
1832
+ try {
1833
+ await accessFn();
1834
+ } catch (error) {
1835
+ if (isDenySignal(error)) return buildDeniedFallback(DeniedComponent, slotName, error.data, createElement) ?? defaultFallback ?? null;
1836
+ if (isRedirectSignal(error)) {
1837
+ if (isDebug()) console.error("[timber] redirect() is not allowed in slot access.ts. Slots use deny() for graceful degradation — denied.tsx → default.tsx → null. If you need to redirect, move the logic to the parent segment's access.ts.");
1838
+ return buildDeniedFallback(DeniedComponent, slotName, void 0, createElement) ?? defaultFallback ?? null;
1839
+ }
1840
+ if (isDebug()) console.warn("[timber] Unhandled error in slot access.ts. Use deny() for access control, not unhandled throws.", error);
1841
+ throw error;
1842
+ }
1843
+ return children;
1844
+ }
1845
+ /**
1846
+ * Build the denied fallback element dynamically with DenySignal data.
1847
+ * Returns null if no DeniedComponent is available.
1848
+ */
1849
+ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
1850
+ if (!DeniedComponent) return null;
1851
+ return createElement(DeniedComponent, {
1852
+ slot: slotName,
1853
+ data
1854
+ });
1855
+ }
1856
+ //#endregion
1857
+ //#region src/server/status-code-resolver.ts
1858
+ /**
1859
+ * Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
1860
+ * status-file group on a single segment. Shared by all three fallback
1861
+ * chains — the only structural difference between component 4xx,
1862
+ * component 5xx, and JSON resolution is *which* group is searched and
1863
+ * how the per-segment loop is layered around it.
1864
+ */
1865
+ function lookupInGroup(group, statusStr, categoryKey, segmentIndex, status) {
1866
+ if (!group) return null;
1867
+ const exact = group[statusStr];
1868
+ if (exact) return {
1869
+ file: exact,
1870
+ status,
1871
+ kind: "exact",
1872
+ segmentIndex
1873
+ };
1874
+ const category = group[categoryKey];
1875
+ if (category) return {
1876
+ file: category,
1877
+ status,
1878
+ kind: "category",
1879
+ segmentIndex
1880
+ };
1881
+ return null;
1882
+ }
1883
+ /**
1884
+ * Resolve the status-code file to render for a given HTTP status code.
1885
+ *
1886
+ * Walks the segment chain from leaf to root following the fallback chain
1887
+ * defined in design/10-error-handling.md. Returns null if no file is found
1888
+ * (caller should render the framework default).
1889
+ *
1890
+ * @param status - The HTTP status code (4xx or 5xx).
1891
+ * @param segments - The matched segment chain from root (index 0) to leaf (last).
1892
+ * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
1893
+ * @param maxIndex - Optional upper bound on the segment index to search.
1894
+ * When set, the resolver only considers segments `0..maxIndex` (inclusive),
1895
+ * skipping any segments deeper in the tree. Used by the deny renderers to
1896
+ * prevent resolving a status file below a denied segment — matching
1897
+ * `buildDenyPageChain`'s start-at-i semantics. The error renderers omit
1898
+ * this parameter, so the full chain is searched — a 500 from a leaf page
1899
+ * should use the leaf's own `5xx.tsx`. See TIM-1358.
1900
+ */
1901
+ function resolveStatusFile(status, segments, format = "component", maxIndex) {
1902
+ if (status < 400 || status > 599) return null;
1903
+ if (format === "json") return resolveJson(status, segments, maxIndex);
1904
+ if (status <= 499) return resolve4xx(status, segments, maxIndex);
1905
+ return resolve5xx(status, segments, maxIndex);
1906
+ }
1907
+ /**
1908
+ * 4xx component fallback chain — two separate full passes leaf→root.
1909
+ *
1910
+ * The passes must be separate (not interleaved per-segment) so that a
1911
+ * root-level `404.tsx` beats a leaf-level `error.tsx`. The 5xx chain
1912
+ * inverts this and is per-segment: a leaf's `error.tsx` beats a root's
1913
+ * `5xx.tsx`. This asymmetry is the only reason these two functions exist
1914
+ * separately.
1915
+ *
1916
+ * Pass 1 — {status}.tsx → 4xx.tsx (statusFiles)
1917
+ * Pass 2 — error.tsx (error)
1918
+ */
1919
+ function resolve4xx(status, segments, maxIndex) {
1920
+ const statusStr = String(status);
1921
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
1922
+ for (let i = start; i >= 0; i--) {
1923
+ const r = lookupInGroup(segments[i].statusFiles, statusStr, "4xx", i, status);
1924
+ if (r) return r;
1925
+ }
1926
+ for (let i = start; i >= 0; i--) {
1927
+ const errorFile = segments[i].error;
1928
+ if (errorFile) return {
1929
+ file: errorFile,
1930
+ status,
1931
+ kind: "error",
1932
+ segmentIndex: i
1933
+ };
1934
+ }
1935
+ return null;
1936
+ }
1937
+ /**
1938
+ * 5xx component fallback chain — single pass, per-segment leaf→root.
1939
+ *
1940
+ * At each segment: {status}.tsx → 5xx.tsx → error.tsx. A leaf's
1941
+ * `error.tsx` therefore beats a root's `5xx.tsx`, which is the
1942
+ * intentional inverse of the 4xx chain.
1943
+ */
1944
+ function resolve5xx(status, segments, maxIndex) {
1945
+ const statusStr = String(status);
1946
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
1947
+ for (let i = start; i >= 0; i--) {
1948
+ const segment = segments[i];
1949
+ const r = lookupInGroup(segment.statusFiles, statusStr, "5xx", i, status);
1950
+ if (r) return r;
1951
+ if (segment.error) return {
1952
+ file: segment.error,
1953
+ status,
1954
+ kind: "error",
1955
+ segmentIndex: i
1956
+ };
1957
+ }
1958
+ return null;
1959
+ }
1960
+ /**
1961
+ * JSON fallback chain (for both 4xx and 5xx) — single pass leaf→root.
1962
+ *
1963
+ * At each segment: {status}.json → {category}.json. No legacy compat,
1964
+ * no error.tsx — the JSON chain terminates at the category catch-all
1965
+ * and the caller falls back to a bare-JSON framework default.
1966
+ */
1967
+ function resolveJson(status, segments, maxIndex) {
1968
+ const statusStr = String(status);
1969
+ const categoryKey = status >= 500 ? "5xx" : "4xx";
1970
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
1971
+ for (let i = start; i >= 0; i--) {
1972
+ const r = lookupInGroup(segments[i].jsonStatusFiles, statusStr, categoryKey, i, status);
1973
+ if (r) return r;
1974
+ }
1975
+ return null;
1976
+ }
1977
+ /**
1978
+ * Resolve the denial file for a parallel route slot.
1979
+ *
1980
+ * Slot denial is graceful degradation — no HTTP status on the wire.
1981
+ * Fallback chain: denied.tsx → default.tsx → null.
1982
+ *
1983
+ * @param slotNode - The segment node for the slot (segmentType === 'slot').
1984
+ */
1985
+ function resolveSlotDenied(slotNode) {
1986
+ const slotName = slotNode.segmentName.replace(/^@/, "");
1987
+ if (slotNode.denied) return {
1988
+ file: slotNode.denied,
1989
+ slotName,
1990
+ kind: "denied"
1991
+ };
1992
+ if (slotNode.default) return {
1993
+ file: slotNode.default,
1994
+ slotName,
1995
+ kind: "default"
1996
+ };
1997
+ return null;
1998
+ }
1999
+ //#endregion
2000
+ //#region src/server/csrf.ts
2001
+ /** HTTP methods that are considered safe (no mutation). */
2002
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
2003
+ "GET",
2004
+ "HEAD",
2005
+ "OPTIONS"
2006
+ ]);
2007
+ /**
2008
+ * Derive the request's scheme from trusted sources.
2009
+ *
2010
+ * Priority:
2011
+ * 1. X-Forwarded-Proto (set by reverse proxies / load balancers)
2012
+ * 2. Request URL protocol
2013
+ *
2014
+ * Falls back to 'https' (fail closed) if neither is available.
2015
+ */
2016
+ function deriveRequestScheme(req) {
2017
+ const forwarded = req.headers.get("X-Forwarded-Proto");
2018
+ if (forwarded) {
2019
+ const proto = forwarded.split(",")[0].trim().toLowerCase();
2020
+ if (proto === "http" || proto === "https") return proto;
2021
+ }
2022
+ try {
2023
+ return new URL(req.url).protocol.replace(":", "");
2024
+ } catch {
2025
+ return "https";
2026
+ }
2027
+ }
2028
+ /**
2029
+ * Validate the Origin header against the request's full origin
2030
+ * (scheme + host + port).
2031
+ *
2032
+ * For mutation methods (POST, PUT, PATCH, DELETE):
2033
+ * - If `csrf: false`, skip validation.
2034
+ * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
2035
+ * - Otherwise, Origin must match the derived request origin.
2036
+ *
2037
+ * Safe methods (GET, HEAD, OPTIONS) always pass.
2038
+ */
2039
+ function validateCsrf(req, config) {
2040
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
2041
+ if (config.csrf === false) return { ok: true };
2042
+ const origin = req.headers.get("Origin");
2043
+ if (!origin) return {
2044
+ ok: false,
2045
+ status: 403
2046
+ };
2047
+ if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
2048
+ ok: false,
2049
+ status: 403
2050
+ };
2051
+ const host = req.headers.get("Host");
2052
+ if (!host) return {
2053
+ ok: false,
2054
+ status: 403
2055
+ };
2056
+ let originOrigin;
2057
+ try {
2058
+ originOrigin = new URL(origin).origin;
2059
+ } catch {
2060
+ return {
2061
+ ok: false,
2062
+ status: 403
2063
+ };
2064
+ }
2065
+ const scheme = deriveRequestScheme(req);
2066
+ let expectedOrigin;
2067
+ try {
2068
+ expectedOrigin = new URL(`${scheme}://${host}`).origin;
2069
+ } catch {
2070
+ return {
2071
+ ok: false,
2072
+ status: 403
2073
+ };
2074
+ }
2075
+ return originOrigin === expectedOrigin ? { ok: true } : {
2076
+ ok: false,
2077
+ status: 403
2078
+ };
2079
+ }
2080
+ //#endregion
2081
+ //#region src/server/body-limits.ts
2082
+ var KB = 1024;
2083
+ var MB = 1024 * KB;
2084
+ var GB = 1024 * MB;
2085
+ var DEFAULT_LIMITS = {
2086
+ actionBodySize: 1 * MB,
2087
+ uploadBodySize: 10 * MB,
2088
+ maxFields: 100
2089
+ };
2090
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2091
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2092
+ function parseBodySize(size) {
2093
+ const match = SIZE_PATTERN.exec(size.trim());
2094
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2095
+ const value = Number.parseFloat(match[1]);
2096
+ const unit = (match[2] ?? "").toLowerCase();
2097
+ switch (unit) {
2098
+ case "kb": return Math.floor(value * KB);
2099
+ case "mb": return Math.floor(value * MB);
2100
+ case "gb": return Math.floor(value * GB);
2101
+ case "": return Math.floor(value);
2102
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2103
+ }
2104
+ }
2105
+ /** Strict integer pattern: one or more digits, nothing else. */
2106
+ var STRICT_INTEGER_RE = /^\d+$/;
2107
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2108
+ function enforceBodyLimits(req, kind, config) {
2109
+ const contentLength = req.headers.get("Content-Length");
2110
+ if (!contentLength) return {
2111
+ ok: false,
2112
+ status: 411
2113
+ };
2114
+ const trimmed = contentLength.trim();
2115
+ if (!STRICT_INTEGER_RE.test(trimmed)) return {
2116
+ ok: false,
2117
+ status: 411
2118
+ };
2119
+ return Number.parseInt(trimmed, 10) <= resolveLimit(kind, config) ? { ok: true } : {
2120
+ ok: false,
2121
+ status: 413
2122
+ };
2123
+ }
2124
+ /**
2125
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2126
+ */
2127
+ function resolveLimit(kind, config) {
2128
+ const userLimits = config.limits;
2129
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2130
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2131
+ }
2132
+ //#endregion
2133
+ //#region src/server/metadata-social.ts
2134
+ /**
2135
+ * Render Open Graph metadata into head element descriptors.
2136
+ *
2137
+ * Handles og:title, og:description, og:image (with dimensions/alt),
2138
+ * og:video, og:audio, og:article:author, and other OG properties.
2139
+ */
2140
+ function renderOpenGraph(og, elements) {
2141
+ const simpleProps = [
2142
+ ["og:title", og.title],
2143
+ ["og:description", og.description],
2144
+ ["og:url", og.url],
2145
+ ["og:site_name", og.siteName],
2146
+ ["og:locale", og.locale],
2147
+ ["og:type", og.type],
2148
+ ["og:article:published_time", og.publishedTime],
2149
+ ["og:article:modified_time", og.modifiedTime]
2150
+ ];
2151
+ for (const [property, content] of simpleProps) if (content) elements.push({
2152
+ tag: "meta",
2153
+ attrs: {
2154
+ property,
2155
+ content
2156
+ }
2157
+ });
2158
+ if (og.images) {
2159
+ if (typeof og.images === "string") elements.push({
2160
+ tag: "meta",
2161
+ attrs: {
2162
+ property: "og:image",
2163
+ content: og.images
2164
+ }
2165
+ });
2166
+ else {
2167
+ const imgList = Array.isArray(og.images) ? og.images : [og.images];
2168
+ for (const img of imgList) {
2169
+ elements.push({
2170
+ tag: "meta",
2171
+ attrs: {
2172
+ property: "og:image",
2173
+ content: img.url
2174
+ }
2175
+ });
2176
+ if (img.width) elements.push({
2177
+ tag: "meta",
2178
+ attrs: {
2179
+ property: "og:image:width",
2180
+ content: String(img.width)
2181
+ }
2182
+ });
2183
+ if (img.height) elements.push({
2184
+ tag: "meta",
2185
+ attrs: {
2186
+ property: "og:image:height",
2187
+ content: String(img.height)
2188
+ }
2189
+ });
2190
+ if (img.alt) elements.push({
2191
+ tag: "meta",
2192
+ attrs: {
2193
+ property: "og:image:alt",
2194
+ content: img.alt
2195
+ }
2196
+ });
2197
+ }
2198
+ }
2199
+ }
2200
+ if (og.videos) for (const video of og.videos) elements.push({
2201
+ tag: "meta",
2202
+ attrs: {
2203
+ property: "og:video",
2204
+ content: video.url
2205
+ }
2206
+ });
2207
+ if (og.audio) for (const audio of og.audio) elements.push({
2208
+ tag: "meta",
2209
+ attrs: {
2210
+ property: "og:audio",
2211
+ content: audio.url
2212
+ }
2213
+ });
2214
+ if (og.authors) for (const author of og.authors) elements.push({
2215
+ tag: "meta",
2216
+ attrs: {
2217
+ property: "og:article:author",
2218
+ content: author
2219
+ }
2220
+ });
2221
+ }
2222
+ /**
2223
+ * Render Twitter Card metadata into head element descriptors.
2224
+ *
2225
+ * Handles twitter:card, twitter:site, twitter:title, twitter:image,
2226
+ * twitter:player, and twitter:app (per-platform name/id/url).
2227
+ */
2228
+ function renderTwitter(tw, elements) {
2229
+ const simpleProps = [
2230
+ ["twitter:card", tw.card],
2231
+ ["twitter:site", tw.site],
2232
+ ["twitter:site:id", tw.siteId],
2233
+ ["twitter:title", tw.title],
2234
+ ["twitter:description", tw.description],
2235
+ ["twitter:creator", tw.creator],
2236
+ ["twitter:creator:id", tw.creatorId]
2237
+ ];
2238
+ for (const [name, content] of simpleProps) if (content) elements.push({
2239
+ tag: "meta",
2240
+ attrs: {
2241
+ name,
2242
+ content
2243
+ }
2244
+ });
2245
+ if (tw.images) {
2246
+ if (typeof tw.images === "string") elements.push({
2247
+ tag: "meta",
2248
+ attrs: {
2249
+ name: "twitter:image",
2250
+ content: tw.images
2251
+ }
2252
+ });
2253
+ else {
2254
+ const imgList = Array.isArray(tw.images) ? tw.images : [tw.images];
2255
+ for (const img of imgList) {
2256
+ const url = typeof img === "string" ? img : img.url;
2257
+ elements.push({
2258
+ tag: "meta",
2259
+ attrs: {
2260
+ name: "twitter:image",
2261
+ content: url
2262
+ }
2263
+ });
2264
+ }
2265
+ }
2266
+ }
2267
+ if (tw.players) for (const player of tw.players) {
2268
+ elements.push({
2269
+ tag: "meta",
2270
+ attrs: {
2271
+ name: "twitter:player",
2272
+ content: player.playerUrl
2273
+ }
2274
+ });
2275
+ if (player.width) elements.push({
2276
+ tag: "meta",
2277
+ attrs: {
2278
+ name: "twitter:player:width",
2279
+ content: String(player.width)
2280
+ }
2281
+ });
2282
+ if (player.height) elements.push({
2283
+ tag: "meta",
2284
+ attrs: {
2285
+ name: "twitter:player:height",
2286
+ content: String(player.height)
2287
+ }
2288
+ });
2289
+ if (player.streamUrl) elements.push({
2290
+ tag: "meta",
2291
+ attrs: {
2292
+ name: "twitter:player:stream",
2293
+ content: player.streamUrl
2294
+ }
2295
+ });
2296
+ }
2297
+ if (tw.app) {
2298
+ const platforms = [
2299
+ ["iPhone", "iphone"],
2300
+ ["iPad", "ipad"],
2301
+ ["googlePlay", "googleplay"]
2302
+ ];
2303
+ if (tw.app.name) {
2304
+ for (const [key, tag] of platforms) if (tw.app.id?.[key]) elements.push({
2305
+ tag: "meta",
2306
+ attrs: {
2307
+ name: `twitter:app:name:${tag}`,
2308
+ content: tw.app.name
2309
+ }
2310
+ });
2311
+ }
2312
+ for (const [key, tag] of platforms) {
2313
+ const id = tw.app.id?.[key];
2314
+ if (id) elements.push({
2315
+ tag: "meta",
2316
+ attrs: {
2317
+ name: `twitter:app:id:${tag}`,
2318
+ content: id
2319
+ }
2320
+ });
2321
+ }
2322
+ for (const [key, tag] of platforms) {
2323
+ const url = tw.app.url?.[key];
2324
+ if (url) elements.push({
2325
+ tag: "meta",
2326
+ attrs: {
2327
+ name: `twitter:app:url:${tag}`,
2328
+ content: url
2329
+ }
2330
+ });
2331
+ }
2332
+ }
2333
+ }
2334
+ //#endregion
2335
+ //#region src/server/metadata-platform.ts
2336
+ /**
2337
+ * Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
2338
+ */
2339
+ function renderIcons(icons, elements) {
2340
+ if (icons.icon) {
2341
+ if (typeof icons.icon === "string") elements.push({
2342
+ tag: "link",
2343
+ attrs: {
2344
+ rel: "icon",
2345
+ href: icons.icon
2346
+ }
2347
+ });
2348
+ else if (Array.isArray(icons.icon)) for (const icon of icons.icon) {
2349
+ const attrs = {
2350
+ rel: "icon",
2351
+ href: icon.url
2352
+ };
2353
+ if (icon.sizes) attrs.sizes = icon.sizes;
2354
+ if (icon.type) attrs.type = icon.type;
2355
+ elements.push({
2356
+ tag: "link",
2357
+ attrs
2358
+ });
2359
+ }
2360
+ }
2361
+ if (icons.shortcut) {
2362
+ const urls = Array.isArray(icons.shortcut) ? icons.shortcut : [icons.shortcut];
2363
+ for (const url of urls) elements.push({
2364
+ tag: "link",
2365
+ attrs: {
2366
+ rel: "shortcut icon",
2367
+ href: url
2368
+ }
2369
+ });
2370
+ }
2371
+ if (icons.apple) {
2372
+ if (typeof icons.apple === "string") elements.push({
2373
+ tag: "link",
2374
+ attrs: {
2375
+ rel: "apple-touch-icon",
2376
+ href: icons.apple
2377
+ }
2378
+ });
2379
+ else if (Array.isArray(icons.apple)) for (const icon of icons.apple) {
2380
+ const attrs = {
2381
+ rel: "apple-touch-icon",
2382
+ href: icon.url
2383
+ };
2384
+ if (icon.sizes) attrs.sizes = icon.sizes;
2385
+ elements.push({
2386
+ tag: "link",
2387
+ attrs
2388
+ });
2389
+ }
2390
+ }
2391
+ if (icons.other) for (const icon of icons.other) {
2392
+ const attrs = {
2393
+ rel: icon.rel,
2394
+ href: icon.url
2395
+ };
2396
+ if (icon.sizes) attrs.sizes = icon.sizes;
2397
+ if (icon.type) attrs.type = icon.type;
2398
+ elements.push({
2399
+ tag: "link",
2400
+ attrs
2401
+ });
2402
+ }
2403
+ }
2404
+ /**
2405
+ * Render alternate link elements (canonical, hreflang, media, types).
2406
+ */
2407
+ function renderAlternates(alternates, elements) {
2408
+ if (alternates.canonical) elements.push({
2409
+ tag: "link",
2410
+ attrs: {
2411
+ rel: "canonical",
2412
+ href: alternates.canonical
2413
+ }
2414
+ });
2415
+ if (alternates.languages) for (const [lang, href] of Object.entries(alternates.languages)) elements.push({
2416
+ tag: "link",
2417
+ attrs: {
2418
+ rel: "alternate",
2419
+ hreflang: lang,
2420
+ href
2421
+ }
2422
+ });
2423
+ if (alternates.media) for (const [media, href] of Object.entries(alternates.media)) elements.push({
2424
+ tag: "link",
2425
+ attrs: {
2426
+ rel: "alternate",
2427
+ media,
2428
+ href
2429
+ }
2430
+ });
2431
+ if (alternates.types) for (const [type, href] of Object.entries(alternates.types)) elements.push({
2432
+ tag: "link",
2433
+ attrs: {
2434
+ rel: "alternate",
2435
+ type,
2436
+ href
2437
+ }
2438
+ });
2439
+ }
2440
+ /**
2441
+ * Render site verification meta tags (Google, Yahoo, Yandex, custom).
2442
+ */
2443
+ function renderVerification(verification, elements) {
2444
+ const verificationProps = [
2445
+ ["google-site-verification", verification.google],
2446
+ ["y_key", verification.yahoo],
2447
+ ["yandex-verification", verification.yandex]
2448
+ ];
2449
+ for (const [name, content] of verificationProps) if (content) elements.push({
2450
+ tag: "meta",
2451
+ attrs: {
2452
+ name,
2453
+ content
2454
+ }
2455
+ });
2456
+ if (verification.other) for (const [name, value] of Object.entries(verification.other)) {
2457
+ const content = Array.isArray(value) ? value.join(", ") : value;
2458
+ elements.push({
2459
+ tag: "meta",
2460
+ attrs: {
2461
+ name,
2462
+ content
2463
+ }
2464
+ });
2465
+ }
2466
+ }
2467
+ /**
2468
+ * Render Apple Web App meta tags and startup image links.
2469
+ */
2470
+ function renderAppleWebApp(appleWebApp, elements) {
2471
+ if (appleWebApp.capable) elements.push({
2472
+ tag: "meta",
2473
+ attrs: {
2474
+ name: "apple-mobile-web-app-capable",
2475
+ content: "yes"
2476
+ }
2477
+ });
2478
+ if (appleWebApp.title) elements.push({
2479
+ tag: "meta",
2480
+ attrs: {
2481
+ name: "apple-mobile-web-app-title",
2482
+ content: appleWebApp.title
2483
+ }
2484
+ });
2485
+ if (appleWebApp.statusBarStyle) elements.push({
2486
+ tag: "meta",
2487
+ attrs: {
2488
+ name: "apple-mobile-web-app-status-bar-style",
2489
+ content: appleWebApp.statusBarStyle
2490
+ }
2491
+ });
2492
+ if (appleWebApp.startupImage) {
2493
+ const images = Array.isArray(appleWebApp.startupImage) ? appleWebApp.startupImage : [{ url: appleWebApp.startupImage }];
2494
+ for (const img of images) {
2495
+ const attrs = {
2496
+ rel: "apple-touch-startup-image",
2497
+ href: typeof img === "string" ? img : img.url
2498
+ };
2499
+ if (typeof img === "object" && img.media) attrs.media = img.media;
2500
+ elements.push({
2501
+ tag: "link",
2502
+ attrs
2503
+ });
2504
+ }
2505
+ }
2506
+ }
2507
+ /**
2508
+ * Render App Links (al:*) meta tags for deep linking across platforms.
2509
+ */
2510
+ function renderAppLinks(appLinks, elements) {
2511
+ const platformEntries = [
2512
+ ["ios", appLinks.ios],
2513
+ ["android", appLinks.android],
2514
+ ["windows", appLinks.windows],
2515
+ ["windows_phone", appLinks.windowsPhone],
2516
+ ["windows_universal", appLinks.windowsUniversal]
2517
+ ];
2518
+ for (const [platform, entries] of platformEntries) {
2519
+ if (!entries) continue;
2520
+ for (const entry of entries) for (const [key, value] of Object.entries(entry)) if (value !== void 0 && value !== null) elements.push({
2521
+ tag: "meta",
2522
+ attrs: {
2523
+ property: `al:${platform}:${key}`,
2524
+ content: String(value)
2525
+ }
2526
+ });
2527
+ }
2528
+ if (appLinks.web) {
2529
+ if (appLinks.web.url) elements.push({
2530
+ tag: "meta",
2531
+ attrs: {
2532
+ property: "al:web:url",
2533
+ content: appLinks.web.url
2534
+ }
2535
+ });
2536
+ if (appLinks.web.shouldFallback !== void 0) elements.push({
2537
+ tag: "meta",
2538
+ attrs: {
2539
+ property: "al:web:should_fallback",
2540
+ content: appLinks.web.shouldFallback ? "true" : "false"
2541
+ }
2542
+ });
2543
+ }
2544
+ }
2545
+ /**
2546
+ * Render Apple iTunes smart banner meta tag.
2547
+ */
2548
+ function renderItunes(itunes, elements) {
2549
+ const parts = [`app-id=${itunes.appId}`];
2550
+ if (itunes.affiliateData) parts.push(`affiliate-data=${itunes.affiliateData}`);
2551
+ if (itunes.appArgument) parts.push(`app-argument=${itunes.appArgument}`);
2552
+ elements.push({
2553
+ tag: "meta",
2554
+ attrs: {
2555
+ name: "apple-itunes-app",
2556
+ content: parts.join(", ")
2557
+ }
2558
+ });
2559
+ }
2560
+ //#endregion
2561
+ //#region src/server/metadata-render.ts
2562
+ /**
2563
+ * Convert resolved metadata into an array of head element descriptors.
2564
+ *
2565
+ * Each descriptor has a `tag` ('title', 'meta', 'link') and either
2566
+ * `content` (for <title>) or `attrs` (for <meta>/<link>).
2567
+ *
2568
+ * The framework's MetadataResolver component consumes these descriptors
2569
+ * and renders them into the <head>.
2570
+ */
2571
+ function renderMetadataToElements(metadata) {
2572
+ const elements = [];
2573
+ if (typeof metadata.title === "string") elements.push({
2574
+ tag: "title",
2575
+ content: metadata.title
2576
+ });
2577
+ const simpleMetaProps = [
2578
+ ["description", metadata.description],
2579
+ ["generator", metadata.generator],
2580
+ ["application-name", metadata.applicationName],
2581
+ ["referrer", metadata.referrer],
2582
+ ["category", metadata.category],
2583
+ ["creator", metadata.creator],
2584
+ ["publisher", metadata.publisher]
2585
+ ];
2586
+ for (const [name, content] of simpleMetaProps) if (content) elements.push({
2587
+ tag: "meta",
2588
+ attrs: {
2589
+ name,
2590
+ content
2591
+ }
2592
+ });
2593
+ if (metadata.keywords) {
2594
+ const content = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
2595
+ elements.push({
2596
+ tag: "meta",
2597
+ attrs: {
2598
+ name: "keywords",
2599
+ content
2600
+ }
2601
+ });
2602
+ }
2603
+ if (metadata.robots) {
2604
+ const content = typeof metadata.robots === "string" ? metadata.robots : renderRobotsObject(metadata.robots);
2605
+ elements.push({
2606
+ tag: "meta",
2607
+ attrs: {
2608
+ name: "robots",
2609
+ content
2610
+ }
2611
+ });
2612
+ if (typeof metadata.robots === "object" && metadata.robots.googleBot) {
2613
+ const gbContent = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : renderRobotsObject(metadata.robots.googleBot);
2614
+ elements.push({
2615
+ tag: "meta",
2616
+ attrs: {
2617
+ name: "googlebot",
2618
+ content: gbContent
2619
+ }
2620
+ });
2621
+ }
2622
+ }
2623
+ if (metadata.openGraph) {
2624
+ const og = { ...metadata.openGraph };
2625
+ if (og.title === void 0 && typeof metadata.title === "string") og.title = metadata.title;
2626
+ if (og.description === void 0 && metadata.description) og.description = metadata.description;
2627
+ renderOpenGraph(og, elements);
2628
+ }
2629
+ if (metadata.twitter) {
2630
+ const tw = { ...metadata.twitter };
2631
+ if (tw.title === void 0) tw.title = metadata.openGraph?.title !== void 0 ? metadata.openGraph.title : typeof metadata.title === "string" ? metadata.title : void 0;
2632
+ if (tw.description === void 0) tw.description = metadata.openGraph?.description !== void 0 ? metadata.openGraph.description : metadata.description;
2633
+ renderTwitter(tw, elements);
2634
+ }
2635
+ if (metadata.icons) renderIcons(metadata.icons, elements);
2636
+ if (metadata.manifest) elements.push({
2637
+ tag: "link",
2638
+ attrs: {
2639
+ rel: "manifest",
2640
+ href: metadata.manifest
2641
+ }
2642
+ });
2643
+ if (metadata.alternates) renderAlternates(metadata.alternates, elements);
2644
+ if (metadata.verification) renderVerification(metadata.verification, elements);
2645
+ if (metadata.formatDetection) {
2646
+ const parts = [];
2647
+ if (metadata.formatDetection.telephone === false) parts.push("telephone=no");
2648
+ if (metadata.formatDetection.email === false) parts.push("email=no");
2649
+ if (metadata.formatDetection.address === false) parts.push("address=no");
2650
+ if (parts.length > 0) elements.push({
2651
+ tag: "meta",
2652
+ attrs: {
2653
+ name: "format-detection",
2654
+ content: parts.join(", ")
2655
+ }
2656
+ });
2657
+ }
2658
+ if (metadata.authors) {
2659
+ const authorList = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
2660
+ for (const author of authorList) {
2661
+ if (author.name) elements.push({
2662
+ tag: "meta",
2663
+ attrs: {
2664
+ name: "author",
2665
+ content: author.name
2666
+ }
2667
+ });
2668
+ if (author.url) elements.push({
2669
+ tag: "link",
2670
+ attrs: {
2671
+ rel: "author",
2672
+ href: author.url
2673
+ }
2674
+ });
2675
+ }
2676
+ }
2677
+ if (metadata.appleWebApp) renderAppleWebApp(metadata.appleWebApp, elements);
2678
+ if (metadata.appLinks) renderAppLinks(metadata.appLinks, elements);
2679
+ if (metadata.itunes) renderItunes(metadata.itunes, elements);
2680
+ if (metadata.other) for (const [name, value] of Object.entries(metadata.other)) {
2681
+ const content = Array.isArray(value) ? value.join(", ") : value;
2682
+ elements.push({
2683
+ tag: "meta",
2684
+ attrs: {
2685
+ name,
2686
+ content
2687
+ }
2688
+ });
2689
+ }
2690
+ return elements;
2691
+ }
2692
+ function renderRobotsObject(robots) {
2693
+ const parts = [];
2694
+ if (robots.index === true) parts.push("index");
2695
+ if (robots.index === false) parts.push("noindex");
2696
+ if (robots.follow === true) parts.push("follow");
2697
+ if (robots.follow === false) parts.push("nofollow");
2698
+ return parts.join(", ");
2699
+ }
2700
+ //#endregion
2701
+ //#region src/server/metadata.ts
2702
+ /**
2703
+ * Resolve a title value with an optional template.
2704
+ *
2705
+ * - string → apply template if present
2706
+ * - { absolute: '...' } → use as-is, skip template
2707
+ * - { default: '...' } → use as fallback (no template applied)
2708
+ * - undefined → undefined
2709
+ */
2710
+ function resolveTitle(title, template) {
2711
+ if (title === void 0 || title === null) return;
2712
+ if (typeof title === "string") return template ? template.replace("%s", title) : title;
2713
+ if (title.absolute !== void 0) return title.absolute;
2714
+ if (title.default !== void 0) return title.default;
2715
+ }
2716
+ /**
2717
+ * Resolve metadata from a segment chain.
2718
+ *
2719
+ * Processes entries from root layout to page (in segment order).
2720
+ * The merge algorithm:
2721
+ * 1. Shallow-merge all keys except title (later wins)
2722
+ * 2. Track the most recent title template
2723
+ * 3. Resolve the final title using the template
2724
+ *
2725
+ * In error state, the page entry is dropped and noindex is injected.
2726
+ *
2727
+ * See design/16-metadata.md §"Merge Algorithm"
2728
+ */
2729
+ function resolveMetadata(entries, options = {}) {
2730
+ const { errorState = false } = options;
2731
+ const merged = {};
2732
+ let titleTemplate;
2733
+ let lastDefault;
2734
+ let rawTitle;
2735
+ for (const { metadata, isPage } of entries) {
2736
+ if (errorState && isPage) continue;
2737
+ if (metadata.title !== void 0 && typeof metadata.title === "object") {
2738
+ if (metadata.title.template !== void 0) titleTemplate = metadata.title.template;
2739
+ if (metadata.title.default !== void 0) lastDefault = metadata.title.default;
2740
+ }
2741
+ for (const key of Object.keys(metadata)) {
2742
+ if (key === "title") continue;
2743
+ merged[key] = metadata[key];
2744
+ }
2745
+ if (metadata.title !== void 0) rawTitle = metadata.title;
2746
+ }
2747
+ if (errorState) {
2748
+ rawTitle = lastDefault !== void 0 ? { default: lastDefault } : rawTitle;
2749
+ titleTemplate = void 0;
2750
+ }
2751
+ const resolvedTitle = resolveTitle(rawTitle, titleTemplate);
2752
+ if (resolvedTitle !== void 0) merged.title = resolvedTitle;
2753
+ if (errorState) merged.robots = "noindex";
2754
+ return merged;
2755
+ }
2756
+ /**
2757
+ * Check if a string is an absolute URL.
2758
+ */
2759
+ function isAbsoluteUrl(url) {
2760
+ return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
2761
+ }
2762
+ /**
2763
+ * Resolve a relative URL against a base URL.
2764
+ */
2765
+ function resolveUrl(url, base) {
2766
+ if (isAbsoluteUrl(url)) return url;
2767
+ return new URL(url, base).toString();
2768
+ }
2769
+ /**
2770
+ * Resolve relative URLs in metadata fields against metadataBase.
2771
+ *
2772
+ * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
2773
+ * If metadataBase is not set, returns the metadata unchanged.
2774
+ */
2775
+ function resolveMetadataUrls(metadata) {
2776
+ const base = metadata.metadataBase;
2777
+ if (!base) return metadata;
2778
+ const result = { ...metadata };
2779
+ if (result.openGraph) {
2780
+ result.openGraph = { ...result.openGraph };
2781
+ if (typeof result.openGraph.images === "string") result.openGraph.images = resolveUrl(result.openGraph.images, base);
2782
+ else if (Array.isArray(result.openGraph.images)) result.openGraph.images = result.openGraph.images.map((img) => ({
2783
+ ...img,
2784
+ url: resolveUrl(img.url, base)
2785
+ }));
2786
+ else if (result.openGraph.images) result.openGraph.images = {
2787
+ ...result.openGraph.images,
2788
+ url: resolveUrl(result.openGraph.images.url, base)
2789
+ };
2790
+ if (result.openGraph.url && !isAbsoluteUrl(result.openGraph.url)) result.openGraph.url = resolveUrl(result.openGraph.url, base);
2791
+ }
2792
+ if (result.twitter) {
2793
+ result.twitter = { ...result.twitter };
2794
+ if (typeof result.twitter.images === "string") result.twitter.images = resolveUrl(result.twitter.images, base);
2795
+ else if (Array.isArray(result.twitter.images)) {
2796
+ const resolved = result.twitter.images.map((img) => typeof img === "string" ? resolveUrl(img, base) : {
2797
+ ...img,
2798
+ url: resolveUrl(img.url, base)
2799
+ });
2800
+ const allStrings = resolved.every((r) => typeof r === "string");
2801
+ result.twitter.images = allStrings ? resolved : resolved;
2802
+ } else if (result.twitter.images) result.twitter.images = {
2803
+ ...result.twitter.images,
2804
+ url: resolveUrl(result.twitter.images.url, base)
2805
+ };
2806
+ }
2807
+ if (result.alternates) {
2808
+ result.alternates = { ...result.alternates };
2809
+ if (result.alternates.canonical && !isAbsoluteUrl(result.alternates.canonical)) result.alternates.canonical = resolveUrl(result.alternates.canonical, base);
2810
+ if (result.alternates.languages) {
2811
+ const langs = {};
2812
+ for (const [lang, url] of Object.entries(result.alternates.languages)) langs[lang] = isAbsoluteUrl(url) ? url : resolveUrl(url, base);
2813
+ result.alternates.languages = langs;
2814
+ }
2815
+ }
2816
+ if (result.icons) {
2817
+ result.icons = { ...result.icons };
2818
+ if (typeof result.icons.icon === "string") result.icons.icon = resolveUrl(result.icons.icon, base);
2819
+ else if (Array.isArray(result.icons.icon)) result.icons.icon = result.icons.icon.map((i) => ({
2820
+ ...i,
2821
+ url: resolveUrl(i.url, base)
2822
+ }));
2823
+ if (typeof result.icons.apple === "string") result.icons.apple = resolveUrl(result.icons.apple, base);
2824
+ else if (Array.isArray(result.icons.apple)) result.icons.apple = result.icons.apple.map((i) => ({
2825
+ ...i,
2826
+ url: resolveUrl(i.url, base)
2827
+ }));
2828
+ }
2829
+ return result;
2830
+ }
2831
+ //#endregion
2832
+ //#region src/server/route-handler.ts
2833
+ /** All recognized HTTP method export names. */
2834
+ var HTTP_METHODS = [
2835
+ "GET",
2836
+ "POST",
2837
+ "PUT",
2838
+ "PATCH",
2839
+ "DELETE",
2840
+ "HEAD",
2841
+ "OPTIONS"
2842
+ ];
2843
+ /**
2844
+ * Resolve the full list of allowed methods for a route module.
2845
+ *
2846
+ * Includes:
2847
+ * - All explicitly exported methods
2848
+ * - HEAD (implicit when GET is exported)
2849
+ * - OPTIONS (always implicit)
2850
+ */
2851
+ function resolveAllowedMethods(mod) {
2852
+ const methods = [];
2853
+ for (const method of HTTP_METHODS) {
2854
+ if (method === "HEAD" || method === "OPTIONS") continue;
2855
+ if (mod[method]) methods.push(method);
2856
+ }
2857
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
2858
+ else if (mod.HEAD) methods.push("HEAD");
2859
+ if (!mod.OPTIONS) methods.push("OPTIONS");
2860
+ else methods.push("OPTIONS");
2861
+ return methods;
2862
+ }
2863
+ /**
2864
+ * Handle an incoming request against a route.ts module.
2865
+ *
2866
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
2867
+ * and merges response headers from ctx.headers.
2868
+ */
2869
+ async function handleRouteRequest(mod, ctx) {
2870
+ const method = ctx.req.method.toUpperCase();
2871
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
2872
+ if (method === "OPTIONS") {
2873
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
2874
+ return new Response(null, {
2875
+ status: 204,
2876
+ headers: { Allow: allowHeader }
2877
+ });
2878
+ }
2879
+ if (method === "HEAD") {
2880
+ if (mod.HEAD) return stripHeadBody(await runHandler(mod.HEAD, ctx), method);
2881
+ if (mod.GET) return stripHeadBody(await runHandler(mod.GET, ctx), method);
2882
+ }
2883
+ const handler = mod[method];
2884
+ if (!handler) return new Response(null, {
2885
+ status: 405,
2886
+ headers: { Allow: allowHeader }
2887
+ });
2888
+ return runHandler(handler, ctx);
2889
+ }
2890
+ /**
2891
+ * Run a handler, merge ctx.headers into the response, and catch errors.
2892
+ */
2893
+ async function runHandler(handler, ctx) {
2894
+ try {
2895
+ return mergeResponseHeaders(await handler(ctx), ctx.headers);
2896
+ } catch (error) {
2897
+ if (isDenySignal(error) || isRedirectSignal(error)) throw error;
2898
+ logRouteError({
2899
+ method: ctx.req.method,
2900
+ path: new URL(ctx.req.url).pathname,
2901
+ error
2902
+ });
2903
+ return new Response(null, { status: 500 });
2904
+ }
2905
+ }
2906
+ /**
2907
+ * Merge response headers from ctx.headers into the handler's response.
2908
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
2909
+ * Handler-set headers take precedence over ctx.headers.
2910
+ */
2911
+ function mergeResponseHeaders(res, ctxHeaders) {
2912
+ let hasCtxHeaders = false;
2913
+ ctxHeaders.forEach(() => {
2914
+ hasCtxHeaders = true;
2915
+ });
2916
+ if (!hasCtxHeaders) return res;
2917
+ const merged = new Headers();
2918
+ ctxHeaders.forEach((value, key) => {
2919
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
2920
+ else merged.set(key, value);
2921
+ });
2922
+ const resCookies = res.headers.getSetCookie();
2923
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
2924
+ res.headers.forEach((value, key) => {
2925
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
2926
+ });
2927
+ return new Response(res.body, {
2928
+ status: res.status,
2929
+ statusText: res.statusText,
2930
+ headers: merged
2931
+ });
2932
+ }
2933
+ //#endregion
2934
+ //#region src/server/render-timeout.ts
2935
+ /**
2936
+ * Render timeout utilities for SSR streaming pipeline.
2937
+ *
2938
+ * Provides a RenderTimeoutError class and a helper to create
2939
+ * timeout-guarded AbortSignals. Used to defend against hung RSC
2940
+ * streams and infinite SSR renders.
2941
+ *
2942
+ * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
2943
+ */
2944
+ /**
2945
+ * Error thrown when an SSR render or RSC stream read exceeds the
2946
+ * configured timeout. Callers can check `instanceof RenderTimeoutError`
2947
+ * to distinguish timeout from other errors and return a 504 or close
2948
+ * the connection cleanly.
2949
+ */
2950
+ var RenderTimeoutError = class extends Error {
2951
+ timeoutMs;
2952
+ constructor(timeoutMs, context) {
2953
+ const message = context ? `Render timeout after ${timeoutMs}ms: ${context}` : `Render timeout after ${timeoutMs}ms`;
2954
+ super(message);
2955
+ this.name = "RenderTimeoutError";
2956
+ this.timeoutMs = timeoutMs;
2957
+ }
2958
+ };
2959
+ //#endregion
2960
+ //#region src/server/prebuilt/cache-key.ts
2961
+ /**
2962
+ * Component cache-key hashing for prebuilt (cache.component) entries.
2963
+ *
2964
+ * Key: `sha256(canonicalJson({ props, params })).slice(0, 16)` — see
2965
+ * design/44-render-at-build-time.md §Cache Key. Both the request-time
2966
+ * lookup (prebuilt-runtime.ts) and the post-build capture pass (TIM-1119)
2967
+ * MUST use this exact function, or build artifacts become unaddressable.
2968
+ *
2969
+ * THE IDENTITY CONTRACT (design/44 §Cache Key): cache identity is **JSON
2970
+ * value semantics** — two inputs are the same entry iff they are the same
2971
+ * JSON value. This is an ALLOWLIST, not a denylist: a value participates
2972
+ * in caching iff it is plain JSON data — null, boolean, finite number,
2973
+ * string, dense array, or a plain `Object.prototype` object with only
2974
+ * enumerable string-keyed data properties — plus `undefined` and `-0`,
2975
+ * which hash as distinct sentinels because flight preserves them. Every
2976
+ * value outside that domain (functions, symbols, bigints, accessors,
2977
+ * hidden or symbol-keyed properties, non-`Object.prototype` prototypes
2978
+ * including null, aliased references, sparse arrays, cycles, non-finite
2979
+ * numbers) is UNKEYABLE by definition: `computeComponentCacheKey` returns
2980
+ * null and the caller renders live — slower, never wrong.
2981
+ *
2982
+ * The line between rejected and declared-out-of-domain: values are
2983
+ * REJECTED when the JSON projection itself would be ambiguous or lossy
2984
+ * (hidden/symbol/non-enumerable properties, accessors, exotic
2985
+ * prototypes). Observable state that leaves the projection intact — key
2986
+ * order, reference identity, descriptor metadata (writable/configurable,
2987
+ * frozen/sealed/extensible), proxy behavior — is DECLARED outside
2988
+ * cache.component's supported input domain rather than rejected:
2989
+ * key-order insensitivity is required for determinism, and rejecting
2990
+ * frozen objects would unkey ubiquitous legitimate inputs
2991
+ * (Object.freeze'd config props) to defend against components that
2992
+ * render differently based on property attributes.
2993
+ *
2994
+ * Two hard rules for this walk itself: it must be TOTAL (never throw
2995
+ * anything but UnkeyableValueError) and SIDE-EFFECT-FREE (descriptor
2996
+ * reads only; never invoke user code such as getters).
2997
+ *
2998
+ * Object keys sort recursively so `{a, b}` and `{b, a}` hash identically
2999
+ * (design/13-security.md checklist #14 — cache key determinism; key order
3000
+ * is deliberately NOT part of identity).
3001
+ */
3002
+ var UnkeyableValueError = class extends Error {};
3003
+ function canonicalize$1(value, seen) {
3004
+ if (value === null) return "null";
3005
+ switch (typeof value) {
3006
+ case "string": return JSON.stringify(value);
3007
+ case "boolean": return value ? "true" : "false";
3008
+ case "number":
3009
+ if (!Number.isFinite(value)) throw new UnkeyableValueError("non-finite number");
3010
+ return Object.is(value, -0) ? "-0" : String(value);
3011
+ case "object": break;
3012
+ case "undefined": return "undefined";
3013
+ default: throw new UnkeyableValueError(`unsupported type: ${typeof value}`);
3014
+ }
3015
+ const obj = value;
3016
+ if (seen.has(obj)) throw new UnkeyableValueError("repeated object reference (cycle or alias)");
3017
+ seen.add(obj);
3018
+ if (Object.getOwnPropertySymbols(obj).length > 0) throw new UnkeyableValueError("symbol-keyed property");
3019
+ {
3020
+ if (Array.isArray(obj)) {
3021
+ if (Object.getOwnPropertyNames(obj).length !== obj.length + 1) throw new UnkeyableValueError("non-index array property");
3022
+ const parts = [];
3023
+ for (let i = 0; i < obj.length; i++) {
3024
+ const desc = Object.getOwnPropertyDescriptor(obj, i);
3025
+ if (desc === void 0) throw new UnkeyableValueError("sparse array hole");
3026
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3027
+ if (!desc.enumerable) throw new UnkeyableValueError("non-enumerable array element");
3028
+ parts.push(canonicalize$1(desc.value, seen));
3029
+ }
3030
+ return "[" + parts.join(",") + "]";
3031
+ }
3032
+ if (Object.getPrototypeOf(obj) !== Object.prototype) throw new UnkeyableValueError("non-plain object");
3033
+ const keys = Object.keys(obj).sort();
3034
+ if (keys.length !== Object.getOwnPropertyNames(obj).length) throw new UnkeyableValueError("non-enumerable property");
3035
+ const parts = [];
3036
+ for (const key of keys) {
3037
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
3038
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3039
+ parts.push(JSON.stringify(key) + ":" + canonicalize$1(desc.value, seen));
3040
+ }
3041
+ return "{" + parts.join(",") + "}";
3042
+ }
3043
+ }
3044
+ /**
3045
+ * Canonicalize a single value, or null if it is unkeyable. The ONE
3046
+ * definition of "faithfully comparable" — every prebuilt code path that
3047
+ * needs value equality (cache keys, slot-param divergence) goes through
3048
+ * this, so the unkeyable rules (accessors, hidden props, aliases,
3049
+ * bigints, …) live in exactly one place.
3050
+ */
3051
+ function tryCanonicalize(value) {
3052
+ try {
3053
+ return canonicalize$1(value, /* @__PURE__ */ new Set());
3054
+ } catch (error) {
3055
+ return toUnkeyable(error);
3056
+ }
3057
+ }
3058
+ /**
3059
+ * Totality by construction: ANY throw from the walk means the input is
3060
+ * outside the keyable domain. The walk touches only user-controlled
3061
+ * values through reflection ops — and a Proxy trap can throw arbitrary
3062
+ * errors from any of them (codex review on PR #835) — so converting only
3063
+ * UnkeyableValueError would let hostile/exotic inputs abort a render
3064
+ * that plain live rendering would have served fine. Unexpected error
3065
+ * types are logged for visibility (they would indicate either a proxy
3066
+ * trap or a canonicalizer bug) but still degrade to unkeyable.
3067
+ */
3068
+ function toUnkeyable(error) {
3069
+ if (!(error instanceof UnkeyableValueError)) console.error("[timber] cache key canonicalization threw — treating input as unkeyable:", error);
3070
+ return null;
3071
+ }
3072
+ /**
3073
+ * Split a props record into data props (participate in the cache key) and
3074
+ * slot values (React-element holes, excluded from the key) per the
3075
+ * component's declared `slots` option (TIM-1173).
3076
+ *
3077
+ * Every DECLARED slot lands in `slotValues` — present or not — because the
3078
+ * capture render always injects a SlotOutlet placeholder for each declared
3079
+ * slot: the cached shell is identical whether the caller passed the slot
3080
+ * or omitted it, so slot presence must not vary the key. `dataProps` is
3081
+ * everything else and is what gets hashed.
3082
+ *
3083
+ * Returns null when the props OBJECT itself is outside the identity
3084
+ * contract at the top level — accessors, symbol-keyed or non-enumerable
3085
+ * properties, or a non-`Object.prototype` prototype. Splitting such an
3086
+ * object would normalize away observable state (and reading an accessor
3087
+ * would invoke user code, which this walk must never do) BEFORE
3088
+ * `computeComponentCacheKey` gets the chance to reject it — a cached
3089
+ * shell could then be served for inputs a live render distinguishes.
3090
+ * Null means unkeyable: the caller renders live with the original props.
3091
+ * The walk is descriptor-reads only; getters are never invoked. Nested
3092
+ * data-prop values still face the full allowlist when hashed.
3093
+ */
3094
+ /** Create an own enumerable data property — safe for keys like `__proto__`. */
3095
+ function defineOwn(target, key, value) {
3096
+ Object.defineProperty(target, key, {
3097
+ value,
3098
+ enumerable: true,
3099
+ writable: true,
3100
+ configurable: true
3101
+ });
3102
+ }
3103
+ function splitSlotProps(props, slots) {
3104
+ try {
3105
+ if (Object.getPrototypeOf(props) !== Object.prototype) return null;
3106
+ if (Object.getOwnPropertySymbols(props).length > 0) return null;
3107
+ const slotSet = new Set(slots);
3108
+ const dataProps = {};
3109
+ const slotValues = {};
3110
+ for (const key of Object.getOwnPropertyNames(props)) {
3111
+ const desc = Object.getOwnPropertyDescriptor(props, key);
3112
+ if (desc === void 0 || desc.get !== void 0 || desc.set !== void 0 || !desc.enumerable) return null;
3113
+ defineOwn(slotSet.has(key) ? slotValues : dataProps, key, desc.value);
3114
+ }
3115
+ for (const slot of slotSet) if (!Object.hasOwn(slotValues, slot)) defineOwn(slotValues, slot, void 0);
3116
+ return {
3117
+ dataProps,
3118
+ slotValues
3119
+ };
3120
+ } catch (error) {
3121
+ return toUnkeyable(error);
3122
+ }
3123
+ }
3124
+ /**
3125
+ * Compute the cache-entry hash for a component render:
3126
+ * `sha256({props, params}).slice(0, 16)` over canonical JSON.
3127
+ *
3128
+ * Returns null when props (or params) contain unkeyable values — the
3129
+ * caller must fall back to dynamic rendering.
3130
+ */
3131
+ function computeComponentCacheKey(props, params) {
3132
+ let canonical;
3133
+ try {
3134
+ const seen = /* @__PURE__ */ new Set();
3135
+ canonical = "{\"params\":" + canonicalize$1({ ...params }, seen) + ",\"props\":" + canonicalize$1(props, seen) + "}";
3136
+ } catch (error) {
3137
+ return toUnkeyable(error);
3138
+ }
3139
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
3140
+ }
3141
+ //#endregion
3142
+ //#region src/client/slot-context.ts
3143
+ /**
3144
+ * SlotContext — delivers live slot content to SlotOutlet holes inside
3145
+ * cached component shells (TIM-1173).
3146
+ *
3147
+ * A `cache.component(Fn, { slots: [...] })` shell is captured with a
3148
+ * stable <SlotOutlet slot={name} /> client reference in place of each
3149
+ * declared slot prop. At request time the revived shell is wrapped in a
3150
+ * SlotsProvider carrying the live slot values; each outlet reads its
3151
+ * value from this context by name.
3152
+ *
3153
+ * Providers MERGE per-key with their parent: an inner SlotsProvider
3154
+ * inherits the outer's values and overrides only the keys it declares.
3155
+ * Two sibling instances each have their own provider and resolve
3156
+ * independently. Layouts use a reserved slot name (LAYOUT_CHILDREN_SLOT)
3157
+ * that cannot collide with user-declared slot names (TIM-1191).
3158
+ *
3159
+ * Generalizes the original layout children pattern (TIM-1181) from a
3160
+ * single implicit `children` hole on layouts to explicitly declared,
3161
+ * named slot props on any cached component. Layouts use this same
3162
+ * context with the reserved LAYOUT_CHILDREN_SLOT key (TIM-1191).
3163
+ *
3164
+ * SINGLETON GUARANTEE: globalThis + Symbol.for — the RSC client bundler
3165
+ * can duplicate this module across chunks; globalThis guarantees a single
3166
+ * context instance.
3167
+ *
3168
+ * See design/45-cache-lifetimes.md §Slot Components.
3169
+ */
3170
+ var CTX_KEY = Symbol.for("__timber_slot_ctx");
3171
+ function getOrCreateContext() {
3172
+ const existing = globalThis[CTX_KEY];
3173
+ if (existing !== void 0) return existing;
3174
+ if (typeof React.createContext === "function") {
3175
+ const ctx = React.createContext(null);
3176
+ globalThis[CTX_KEY] = ctx;
3177
+ return ctx;
3178
+ }
3179
+ }
3180
+ var SlotContext = getOrCreateContext();
3181
+ //#endregion
3182
+ //#region src/client/slot-outlet.tsx
3183
+ /**
3184
+ * SlotOutlet — the hole in a cached component shell (TIM-1173).
3185
+ *
3186
+ * At capture time the prebuilt runtime renders the wrapped component with
3187
+ * <SlotOutlet slot={name} /> in place of each declared slot prop. Being a
3188
+ * client component, it serializes into the flight payload as a stable,
3189
+ * deterministic client reference — the same bytes regardless of what live
3190
+ * content will fill the hole. At request time the revived shell sits under
3191
+ * a SlotsProvider and each outlet reads its live value from SlotContext.
3192
+ *
3193
+ * See design/45-cache-lifetimes.md §Slot Components.
3194
+ */
3195
+ function SlotOutlet({ slot }) {
3196
+ const values = useContext(SlotContext);
3197
+ return values ? values[slot] ?? null : null;
3198
+ }
3199
+ //#endregion
3200
+ //#region src/client/slot-provider.tsx
3201
+ /**
3202
+ * SlotsProvider — wraps a revived cached shell to supply live slot content
3203
+ * to the SlotOutlet holes inside it (TIM-1173).
3204
+ *
3205
+ * Values MERGE with the nearest parent provider so that nesting a
3206
+ * cache.component SlotsProvider inside a layout SlotsProvider preserves
3207
+ * the layout's `children` slot while adding the component's own slots.
3208
+ * Inner values override outer ones with the same name (spread order).
3209
+ *
3210
+ * Tree structure per cached-component instance:
3211
+ * SlotsProvider(values={children: <Live />})
3212
+ * └── revived shell
3213
+ * └── SlotOutlet(slot="children") → reads context → <Live />
3214
+ *
3215
+ * See design/45-cache-lifetimes.md §Slot Components.
3216
+ */
3217
+ function SlotsProvider({ values, children }) {
3218
+ const parent = useContext(SlotContext);
3219
+ const merged = parent ? {
3220
+ ...parent,
3221
+ ...values
3222
+ } : values;
3223
+ return createElement(SlotContext.Provider, { value: merged }, children);
3224
+ }
3225
+ /**
3226
+ * Is this value the framework-injected layout children slot outlet
3227
+ * (`<SlotOutlet slot={LAYOUT_CHILDREN_SLOT} />`)? Layout components
3228
+ * receive this as their `children` prop — a stable client reference
3229
+ * whose cache key is stripped so layout `cache.component` hits work
3230
+ * (design/45 §Layout Propagation).
3231
+ *
3232
+ * Uses a framework-reserved slot name (LAYOUT_CHILDREN_SLOT) that
3233
+ * cannot collide with user-declared slot names, preventing context
3234
+ * shadowing when a cached component with its own SlotsProvider is
3235
+ * nested inside a layout. See TIM-1191.
3236
+ *
3237
+ * Total: the probes run against a user-controlled value, and a Proxy
3238
+ * trap can throw — that must classify as "not the outlet" (the
3239
+ * canonicalizer then rejects the value as unkeyable → live render), not
3240
+ * abort the request (codex P2 on PR #890).
3241
+ */
3242
+ function isChildrenSlotOutletElement(value) {
3243
+ try {
3244
+ if (value == null || typeof value !== "object") return false;
3245
+ if (!("type" in value)) return false;
3246
+ const el = value;
3247
+ return el.type === SlotOutlet && el.props?.slot === "\0timber:children";
3248
+ } catch {
3249
+ return false;
3250
+ }
3251
+ }
3252
+ /**
3253
+ * Dense array of non-empty strings — no holes, no non-string entries.
3254
+ * Total: the reads run against a user-controlled value at module load,
3255
+ * and a throwing Proxy trap must classify as invalid, not crash startup.
3256
+ */
3257
+ function isDenseStringArray(value) {
3258
+ try {
3259
+ if (!Array.isArray(value)) return false;
3260
+ for (let i = 0; i < value.length; i++) {
3261
+ if (!Object.hasOwn(value, i)) return false;
3262
+ const entry = value[i];
3263
+ if (typeof entry !== "string" || entry.length === 0) return false;
3264
+ }
3265
+ return true;
3266
+ } catch {
3267
+ return false;
3268
+ }
3269
+ }
3270
+ /**
3271
+ * Validate the `slots` option. Both the production and dev wrappers gate
3272
+ * on this — slot substitution is active in dev exactly when it would be
3273
+ * active in production, so the tree shape a component sees never
3274
+ * diverges between the two.
3275
+ */
3276
+ function resolveSlotNames(id, options) {
3277
+ const slots = options.slots;
3278
+ if (slots === void 0) return { kind: "none" };
3279
+ if (!isDenseStringArray(slots)) {
3280
+ console.warn(`[timber] cache.component "${id}": invalid slots declaration — expected an array of non-empty prop-name strings. Slot caching is disabled.`);
3281
+ return { kind: "disabled" };
3282
+ }
3283
+ if (slots.length === 0) return { kind: "none" };
3284
+ if (!(options.ttl !== void 0 || options.tags != null)) {
3285
+ console.warn(`[timber] cache.component "${id}": slots require a runtime lifetime (ttl and/or tags). Slot caching is disabled.`);
3286
+ return { kind: "disabled" };
3287
+ }
3288
+ return {
3289
+ kind: "active",
3290
+ slots
3291
+ };
3292
+ }
3293
+ /**
3294
+ * Split the live props into the cacheable shell render (data props plus a
3295
+ * deterministic SlotOutlet placeholder per declared slot — identical
3296
+ * whether or not the caller passed the slot) and the per-instance live
3297
+ * slot values.
3298
+ *
3299
+ * Null when the props object itself is unkeyable at the top level
3300
+ * (accessors, hidden properties, exotic prototype — see splitSlotProps):
3301
+ * the caller must render live with the original props.
3302
+ */
3303
+ function prepareSlotRender(props, slots) {
3304
+ const split = splitSlotProps(props ?? {}, slots);
3305
+ if (split === null) return null;
3306
+ const { dataProps, slotValues } = split;
3307
+ const shellProps = { ...dataProps };
3308
+ for (const slot of slots) Object.defineProperty(shellProps, slot, {
3309
+ value: createElement(SlotOutlet, { slot }),
3310
+ enumerable: true,
3311
+ writable: true,
3312
+ configurable: true
3313
+ });
3314
+ return {
3315
+ shellProps,
3316
+ dataProps,
3317
+ slotValues
3318
+ };
3319
+ }
3320
+ /**
3321
+ * Wrap a rendered shell (revived payload or live element) in a
3322
+ * per-instance SlotsProvider feeding the live values to its outlets.
3323
+ */
3324
+ function wrapInSlotsProvider(shell, slotValues) {
3325
+ return createElement(SlotsProvider, {
3326
+ values: slotValues,
3327
+ children: shell
3328
+ });
3329
+ }
3330
+ //#endregion
3331
+ //#region src/server/prebuilt/key-discipline.ts
3332
+ var REQUEST_CONTEXT_FIELDS = {
3333
+ headers: "headers()",
3334
+ parsedCookies: "cookies()",
3335
+ searchParams: "searchParams"
3336
+ };
3337
+ /** Rate-limit interval: one diagnostic per component per 60 seconds. */
3338
+ var RATE_LIMIT_MS = 6e4;
3339
+ /** Last emission timestamp per component ID. */
3340
+ var lastEmitted = /* @__PURE__ */ new Map();
3341
+ var strict = false;
3342
+ /**
3343
+ * Whether the proxy should be created for this component on this render.
3344
+ * Returns true when strict mode is on (always check) or enough time has
3345
+ * elapsed since the last diagnostic for this component.
3346
+ */
3347
+ function shouldCheckKeyDiscipline(id) {
3348
+ if (strict) return true;
3349
+ const last = lastEmitted.get(id);
3350
+ if (last === void 0) return true;
3351
+ return Date.now() - last >= RATE_LIMIT_MS;
3352
+ }
3353
+ /**
3354
+ * Wrap a store with a proxy that records per-request field access.
3355
+ * The proxy forwards all reads/writes transparently — it only observes.
3356
+ */
3357
+ function createKeyDisciplineProxy(store) {
3358
+ const accessedApis = /* @__PURE__ */ new Set();
3359
+ return {
3360
+ proxy: new Proxy(store, { get(target, prop, receiver) {
3361
+ const api = REQUEST_CONTEXT_FIELDS[prop];
3362
+ if (api) accessedApis.add(api);
3363
+ return Reflect.get(target, prop, receiver);
3364
+ } }),
3365
+ accessedApis
3366
+ };
3367
+ }
3368
+ /**
3369
+ * Emit the key-discipline diagnostic or throw in strict mode.
3370
+ *
3371
+ * In strict mode: throws an error so the tainted payload is never cached.
3372
+ * In default mode: emits a structured error-level diagnostic through the
3373
+ * logger (same path as render errors), rate-limited per component.
3374
+ */
3375
+ function emitKeyDisciplineWarning(id, apis) {
3376
+ const apiList = Array.from(apis).join(", ");
3377
+ if (strict) throw new Error(`[timber] cache.component key-discipline violation: "${id}" reads ${apiList} during a cache capture render. The cache key does not include request-derived values — caching this output would serve one user's data to another. Either pass request-derived values as props (included in the cache key) or remove the ${apiList} call. To downgrade this to a warning, set cache.strictKeyDiscipline: false in timber.config.ts.`);
3378
+ const now = Date.now();
3379
+ const last = lastEmitted.get(id);
3380
+ if (last !== void 0 && now - last < RATE_LIMIT_MS) return;
3381
+ lastEmitted.set(id, now);
3382
+ getLogger().error("cache.component cross-user data leak risk", {
3383
+ component: id,
3384
+ accessedApis: Array.from(apis),
3385
+ message: `cache.component "${id}" reads ${apiList} but the cache key is computed from props and segment params only. If the output varies by ${apiList}, different users may see each other's cached content. Either pass request-derived values as props (included in the cache key) or remove the ${apiList} call.`
3386
+ });
3387
+ }
3388
+ //#endregion
3389
+ //#region src/server/prebuilt/capture-state.ts
3390
+ /** Thrown by the wrapper when a capture renders its own component. */
3391
+ var PrebuiltCaptureCycleError = class extends Error {
3392
+ constructor(componentId) {
3393
+ super(`[timber] cache.component "${componentId}" renders itself (directly or through other components) — prerendering it would recurse forever. Remove the cycle or drop { prerender: true } on this component.`);
3394
+ this.name = "PrebuiltCaptureCycleError";
3395
+ }
3396
+ };
3397
+ var active = null;
3398
+ /**
3399
+ * Mark a capture as active. The builder calls this immediately before
3400
+ * rendering an entry and MUST pair it with `endCapture()` in a finally.
3401
+ */
3402
+ function beginCapture(outerId) {
3403
+ active = {
3404
+ outerId,
3405
+ nested: /* @__PURE__ */ new Map()
3406
+ };
3407
+ }
3408
+ /**
3409
+ * End the active capture and return the wrapped components that rendered
3410
+ * inside it (first options object wins per inner ID).
3411
+ */
3412
+ function endCapture() {
3413
+ const nested = active?.nested;
3414
+ active = null;
3415
+ if (!nested) return [];
3416
+ return Array.from(nested, ([innerId, options]) => ({
3417
+ innerId,
3418
+ options
3419
+ }));
3420
+ }
3421
+ /** Whether a build-time capture is currently rendering. */
3422
+ function isCaptureActive() {
3423
+ return active !== null;
3424
+ }
3425
+ /**
3426
+ * Called by the `__prebuilt` wrapper on every render. No-op unless a
3427
+ * capture is active. Throws `PrebuiltCaptureCycleError` when the wrapper
3428
+ * belongs to the component currently being captured.
3429
+ */
3430
+ function noteWrapperRender(innerId, options) {
3431
+ if (active === null) return;
3432
+ if (innerId === active.outerId) throw new PrebuiltCaptureCycleError(innerId);
3433
+ if (!active.nested.has(innerId)) active.nested.set(innerId, options);
3434
+ }
3435
+ //#endregion
3436
+ //#region src/server/prebuilt-runtime.ts
3437
+ /**
3438
+ * Prebuilt component runtime — registration target for the timber-prebuilt
3439
+ * transform (plugins/prebuilt.ts) and the request-time half of
3440
+ * cache.component (TIM-1140).
3441
+ *
3442
+ * `cache.component(fn, opts)` call sites are rewritten at build time to
3443
+ * `__prebuilt(stableId, fn, opts)` (production) or `__prebuiltDev(name, fn)`
3444
+ * (dev). Both are exported via #server-internal — they are framework
3445
+ * plumbing, never called by user code directly.
3446
+ *
3447
+ * Cache hits are served by FLIGHT REVIVAL: the cached `.flight` payload is
3448
+ * decoded back into React elements inside the RSC environment with
3449
+ * `createFromReadableStream` (the flight client running in the flight
3450
+ * server — plugin-rsc wires the server-decode manifest so client
3451
+ * references revive as re-serializable reference proxies). The revived
3452
+ * element is returned from the wrapper and the outer render re-serializes
3453
+ * it like any other subtree. This is the same mechanism as Next.js
3454
+ * `"use cache"` (next/src/server/use-cache/use-cache-wrapper.ts).
3455
+ *
3456
+ * What a hit skips: all user work — data fetching, MDX compilation, the
3457
+ * component function itself never runs. What it re-pays: React
3458
+ * re-serializes the already-resolved tree (cost proportional to payload
3459
+ * size, not to data latency). The alternative — splicing raw payload bytes
3460
+ * into the outer stream — avoids re-serialization but requires byte-level
3461
+ * coupling to the flight wire format (row framing, ID rebasing, marker
3462
+ * detection); it was implemented and reviewed on PR #835 and deliberately
3463
+ * replaced by revival. See design/44-render-at-build-time.md
3464
+ * §Request-Time Injection.
3465
+ *
3466
+ * Misses render the original component live via the wrapper's own closure,
3467
+ * inside the React pass — segment params from ALS, deny()/redirect()
3468
+ * signals, Suspense, and error boundaries behave exactly as an unwrapped
3469
+ * component. `fallbackOnMissingSegmentParams: false` throws instead.
3470
+ */
3471
+ /** Default timeout for component re-renders (overridden by renderTimeoutMs). */
3472
+ var DEFAULT_COMPONENT_TIMEOUT_MS = 3e4;
3473
+ /** Singleflight for component re-renders (inline and background). */
3474
+ var componentSingleflight = createSingleflight({ timeoutMs: DEFAULT_COMPONENT_TIMEOUT_MS });
3475
+ var componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
3476
+ var warnedNoWaitUntil = false;
3477
+ /**
3478
+ * Server-side component registry, keyed by stable component ID. Populated at
3479
+ * module load time by `__prebuilt` calls; consumed by the post-build capture
3480
+ * pass (TIM-1119). Never serialized — component functions are not
3481
+ * Flight-serializable.
3482
+ */
3483
+ var registry = /* @__PURE__ */ new Map();
3484
+ /**
3485
+ * Resolve the params the cache key may faithfully hash, or null if this
3486
+ * render is unkeyable.
3487
+ *
3488
+ * A wrapper rendered inside a parallel slot reads params merged with that
3489
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
3490
+ * — but the cache key hashes only the route-level params, and the wrapper
3491
+ * cannot know which slot it renders under. The route params are usable
3492
+ * only when every slot's merged view canonicalizes identically to them;
3493
+ * otherwise two renders with the same key could see different effective
3494
+ * inputs and a hit could serve the WRONG cached subtree — so the render
3495
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
3496
+ * params either, so a divergent request could never have a faithful
3497
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
3498
+ * if slot-scoped prebuilt is ever needed.)
3499
+ *
3500
+ * Comparison happens through `tryCanonicalize` — the same single
3501
+ * definition of value equality the cache key uses — so anything it
3502
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
3503
+ * aliases, …) is unkeyable here too, and this guard can never throw.
3504
+ */
3505
+ function resolveKeyParams(store) {
3506
+ const main = store.segmentParams ?? {};
3507
+ const slots = store.slotParams;
3508
+ if (!slots || Object.keys(slots).length === 0) return main;
3509
+ const mainCanonical = tryCanonicalize({ ...main });
3510
+ if (mainCanonical === null) return null;
3511
+ for (const slotParams of Object.values(slots)) {
3512
+ const merged = tryCanonicalize({
3513
+ ...main,
3514
+ ...slotParams
3515
+ });
3516
+ if (merged === null || merged !== mainCanonical) return null;
3517
+ }
3518
+ return main;
3519
+ }
3520
+ /**
3521
+ * Mirror the production cache-key decision for a slot render, with no
3522
+ * cache IO — used by the dev wrapper so slot substitution happens in dev
3523
+ * exactly when production would serve the cache path rather than the
3524
+ * live fallback (dev/prod parity, codex P2 on PR #890): requires an ALS
3525
+ * store, keyable params (slot-param divergence unkeys), and keyable data
3526
+ * props (after the children slot outlet strip).
3527
+ */
3528
+ function isSlotRenderKeyable(dataProps) {
3529
+ const store = requestContextAls.getStore();
3530
+ if (!store) return false;
3531
+ const keyParams = resolveKeyParams(store);
3532
+ if (keyParams === null) return false;
3533
+ let keyProps = dataProps;
3534
+ if (isChildrenSlotOutletElement(keyProps.children)) {
3535
+ const { children: _children, ...rest } = keyProps;
3536
+ keyProps = rest;
3537
+ }
3538
+ return computeComponentCacheKey(keyProps, keyParams) !== null;
3539
+ }
3540
+ /** Wrap payload bytes as a single-chunk ReadableStream for the decoder. */
3541
+ function bytesToStream(bytes) {
3542
+ return new ReadableStream({ start(controller) {
3543
+ controller.enqueue(bytes);
3544
+ controller.close();
3545
+ } });
3546
+ }
3547
+ /** Whether the component has a runtime lifetime (ttl or tags). */
3548
+ function hasRuntimeLifetime(options) {
3549
+ return options.ttl !== void 0 || options.tags !== void 0 && options.tags !== null;
3550
+ }
3551
+ /**
3552
+ * Resolve tags from options (may be static array or function of props).
3553
+ * Function-form tags receive DATA props only — slot props are excluded so
3554
+ * the tags fn never sees SlotOutlet placeholders (capture paths pass
3555
+ * placeholder-substituted props) and tags stay deterministic per key.
3556
+ */
3557
+ function resolveTags(options, props) {
3558
+ if (!options.tags) return [];
3559
+ if (Array.isArray(options.tags)) return options.tags;
3560
+ const slots = options.slots;
3561
+ const fnProps = slots && slots.length > 0 ? splitSlotProps(props, slots)?.dataProps ?? props : props;
3562
+ return options.tags(fnProps);
3563
+ }
3564
+ /**
3565
+ * Serve a slot component from the cache: split live slot values out of the
3566
+ * props, look up / capture the shell (data props + a deterministic
3567
+ * SlotOutlet placeholder per slot), and wrap the revived shell in a
3568
+ * per-instance SlotsProvider that feeds the live values to the outlets.
3569
+ *
3570
+ * Null on any miss — the caller renders live with the original props.
3571
+ */
3572
+ async function tryReviveSlotShell(id, options, slots, props) {
3573
+ const render = prepareSlotRender(props, slots);
3574
+ if (render === null) return null;
3575
+ const { shellProps, dataProps, slotValues } = render;
3576
+ const revived = await tryRevivePayload(id, options, shellProps, dataProps);
3577
+ if (revived === null) return null;
3578
+ return { element: wrapInSlotsProvider(revived.element, slotValues) };
3579
+ }
3580
+ var rscFns = null;
3581
+ function requireRscFunctions() {
3582
+ if (!rscFns) throw new Error("[timber] RSC functions not wired — setRscFunctions() must be called at boot");
3583
+ return rscFns;
3584
+ }
3585
+ /**
3586
+ * Revive flight payload bytes into a React element.
3587
+ * Returns null on any failure (corrupt payload, missing decoder).
3588
+ */
3589
+ async function revivePayload(id, payload, outcome) {
3590
+ try {
3591
+ const { createFromReadableStream } = requireRscFunctions();
3592
+ return { element: await createFromReadableStream(bytesToStream(payload)) };
3593
+ } catch (error) {
3594
+ console.error(`[timber] failed to revive prebuilt payload for "${id}" — ${outcome}:`, error);
3595
+ return null;
3596
+ }
3597
+ }
3598
+ /** Ceiling on component re-render capture (design/13 A2). Uses configured renderTimeoutMs. */
3599
+ function getCaptureTimeoutMs() {
3600
+ return componentTimeoutMs;
3601
+ }
3602
+ /**
3603
+ * Render a component in isolation and capture its flight payload bytes.
3604
+ * Used for inline re-renders (tombstone/miss) and SWR background re-renders.
3605
+ *
3606
+ * The stream read is timeout-guarded and the reader is cancelled on
3607
+ * expiry (design/13 A2, A3).
3608
+ */
3609
+ async function captureComponentPayload(id, component, props) {
3610
+ const { renderToReadableStream } = requireRscFunctions();
3611
+ const element = createElement(component, props);
3612
+ let renderErrored = false;
3613
+ const store = requestContextAls.getStore();
3614
+ const discipline = store && shouldCheckKeyDiscipline(id) ? createKeyDisciplineProxy(store) : null;
3615
+ const doCapture = async () => {
3616
+ beginCapture(id);
3617
+ try {
3618
+ const reader = renderToReadableStream(element, { onError() {
3619
+ renderErrored = true;
3620
+ return "";
3621
+ } }).getReader();
3622
+ const chunks = [];
3623
+ let totalLength = 0;
3624
+ const deadline = Date.now() + getCaptureTimeoutMs();
3625
+ try {
3626
+ for (;;) {
3627
+ const remaining = deadline - Date.now();
3628
+ if (remaining <= 0) throw new Error(`[timber] component re-render capture exceeded ${getCaptureTimeoutMs()}ms`);
3629
+ let timer;
3630
+ const { done, value } = await Promise.race([reader.read(), new Promise((_, reject) => {
3631
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`[timber] component re-render stream read timed out`)), remaining);
3632
+ })]);
3633
+ clearTimeout(timer);
3634
+ if (done) break;
3635
+ chunks.push(value);
3636
+ totalLength += value.byteLength;
3637
+ }
3638
+ } finally {
3639
+ reader.cancel().catch(() => {});
3640
+ }
3641
+ if (renderErrored) throw new Error("[timber] component re-render produced error rows — not caching");
3642
+ const result = new Uint8Array(totalLength);
3643
+ let offset = 0;
3644
+ for (const chunk of chunks) {
3645
+ result.set(chunk, offset);
3646
+ offset += chunk.byteLength;
3647
+ }
3648
+ return result;
3649
+ } finally {
3650
+ endCapture();
3651
+ }
3652
+ };
3653
+ const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
3654
+ if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
3655
+ return bytes;
3656
+ }
3657
+ /**
3658
+ * Inline re-render: capture flight bytes, store in overlay, revive for
3659
+ * the current request. Singleflight-coalesced by overlay key.
3660
+ */
3661
+ async function inlineRerender(id, component, props, cacheKey, options, hasSeed, outcome) {
3662
+ const tags = resolveTags(options, props);
3663
+ const oKey = overlayKey(id, cacheKey);
3664
+ const sfKey = `prebuilt:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3665
+ try {
3666
+ return await revivePayload(id, await componentSingleflight.do(sfKey, async (signal) => {
3667
+ const startEpoch = currentInvalidationEpoch();
3668
+ const bytes = await captureComponentPayload(id, component, props);
3669
+ if (!signal.aborted && hasRuntimeLifetime(options) && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3670
+ ttl: options.ttl,
3671
+ tags,
3672
+ hasSeed
3673
+ });
3674
+ return bytes;
3675
+ }), outcome);
3676
+ } catch (error) {
3677
+ console.error(`[timber] cache.component re-render failed for "${id}" — ${outcome}:`, error);
3678
+ return null;
3679
+ }
3680
+ }
3681
+ /**
3682
+ * Snapshot the request context values needed for a background re-render.
3683
+ * Creates a FRESH store with copied values — the original ALS store is
3684
+ * not referenced after capture.
3685
+ */
3686
+ function snapshotRequestContext(store) {
3687
+ return {
3688
+ headers: new Headers(store.headers),
3689
+ originalHeaders: new Headers(store.originalHeaders),
3690
+ cookieHeader: store.cookieHeader,
3691
+ parsedCookies: store.parsedCookies ? new Map(store.parsedCookies) : void 0,
3692
+ searchParams: new URLSearchParams(store.searchParams),
3693
+ searchString: store.searchString,
3694
+ segmentParams: store.segmentParams ? { ...store.segmentParams } : void 0,
3695
+ cookieJar: /* @__PURE__ */ new Map(),
3696
+ flushed: false,
3697
+ mutableContext: false
3698
+ };
3699
+ }
3700
+ /**
3701
+ * Kick off a background re-render via waitUntil. The re-render runs inside
3702
+ * a fresh ALS scope with snapshotted request context.
3703
+ */
3704
+ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, snapshot) {
3705
+ const waitUntil = getWaitUntil();
3706
+ const tags = resolveTags(options, props);
3707
+ const oKey = overlayKey(id, cacheKey);
3708
+ const startEpoch = currentInvalidationEpoch();
3709
+ const sfKey = `prebuilt-bg:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3710
+ const work = requestContextAls.run(snapshot, () => componentSingleflight.do(sfKey, async (signal) => {
3711
+ const bytes = await captureComponentPayload(id, component, props);
3712
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3713
+ ttl: options.ttl,
3714
+ tags,
3715
+ hasSeed
3716
+ });
3717
+ }).catch((error) => {
3718
+ console.error(`[timber] cache.component background re-render failed for "${id}":`, error);
3719
+ }));
3720
+ if (waitUntil) waitUntil(work);
3721
+ else if (!warnedNoWaitUntil) {
3722
+ warnedNoWaitUntil = true;
3723
+ console.warn("[timber] cache.component SWR background re-render has no waitUntil — the re-render may be killed when the handler returns on serverless platforms. Ensure the adapter wires runWithWaitUntil().");
3724
+ }
3725
+ }
3726
+ /**
3727
+ * Try to serve this render from the prebuilt cache: overlay → artifact →
3728
+ * live render. Handles ISR (SWR, tombstones, re-renders) per design/45.
3729
+ *
3730
+ * Null on any miss — the caller renders live.
3731
+ */
3732
+ async function tryRevivePayload(id, options, props, keyPropsOverride) {
3733
+ const hasSource = hasPrebuiltPayloadSource();
3734
+ const hasRuntime = hasRuntimeLifetime(options);
3735
+ if (!hasSource && !hasRuntime) return null;
3736
+ const store = requestContextAls.getStore();
3737
+ if (!store) return null;
3738
+ const keyParams = (options.prerender ? await isParamIndependent(id) : false) ? {} : resolveKeyParams(store);
3739
+ if (keyParams === null) return null;
3740
+ let keyProps = keyPropsOverride ?? props ?? {};
3741
+ if (isChildrenSlotOutletElement(keyProps.children)) {
3742
+ const { children: _children, ...rest } = keyProps;
3743
+ keyProps = rest;
3744
+ }
3745
+ const cacheKey = computeComponentCacheKey(keyProps, keyParams);
3746
+ if (cacheKey === null) return null;
3747
+ const outcome = options.fallbackOnMissingSegmentParams === false ? "failing the render (fallbackOnMissingSegmentParams: false)" : "rendering dynamically";
3748
+ const component = registry.get(id)?.component;
3749
+ if (hasRuntime) {
3750
+ const overlayResult = await lookupOverlay(id, cacheKey);
3751
+ if (overlayResult) {
3752
+ const overlayHasSeed = overlayResult.record?.s ?? false;
3753
+ if (overlayResult.kind === "tombstone") {
3754
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3755
+ return null;
3756
+ }
3757
+ if (overlayResult.kind === "fresh" && overlayResult.payload) return await revivePayload(id, overlayResult.payload, outcome);
3758
+ if (overlayResult.kind === "stale" && overlayResult.payload) {
3759
+ if (options.staleWhileRevalidate && component) {
3760
+ backgroundRerender(id, component, props, cacheKey, options, overlayHasSeed, snapshotRequestContext(store));
3761
+ return await revivePayload(id, overlayResult.payload, outcome);
3762
+ }
3763
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, overlayHasSeed, outcome);
3764
+ return null;
3765
+ }
3766
+ }
3767
+ }
3768
+ if (hasSource) {
3769
+ const artifactPayload = await lookupPrebuiltPayload(id, cacheKey);
3770
+ if (artifactPayload !== null) {
3771
+ if (options.ttl !== void 0) {
3772
+ const buildTs = (await getManifestEntry(id, cacheKey))?.buildTimestamp ?? 0;
3773
+ if ((Date.now() - buildTs) / 1e3 > options.ttl) {
3774
+ if (options.staleWhileRevalidate && component) {
3775
+ backgroundRerender(id, component, props, cacheKey, options, true, snapshotRequestContext(store));
3776
+ return await revivePayload(id, artifactPayload, outcome);
3777
+ }
3778
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3779
+ return null;
3780
+ }
3781
+ }
3782
+ return await revivePayload(id, artifactPayload, outcome);
3783
+ }
3784
+ if (options.prerender) console.warn(`[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(store.segmentParams ?? {})} — ${outcome}`);
3785
+ }
3786
+ if (hasRuntime && component && options.fallbackOnMissingSegmentParams !== false) return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
3787
+ return null;
3788
+ }
3789
+ /**
3790
+ * Production wrapper injected by the timber-prebuilt transform. Registers
3791
+ * the component under its stable ID and returns a wrapper component that
3792
+ * either revives the cached payload (hit) or renders the original
3793
+ * component live (miss).
3794
+ */
3795
+ function __prebuilt(id, component, options = {}) {
3796
+ const resolution = resolveSlotNames(id, options);
3797
+ const slots = resolution.kind === "active" ? resolution.slots : null;
3798
+ if (resolution.kind === "active" && options.prerender) {
3799
+ console.warn(`[timber] cache.component "${id}": slots are runtime-tier only — prerender is ignored (the build cannot enumerate slot content). Use ttl/tags for the cache lifetime.`);
3800
+ options = {
3801
+ ...options,
3802
+ prerender: void 0
3803
+ };
3804
+ }
3805
+ if (resolution.kind === "disabled") options = {
3806
+ ...options,
3807
+ slots: void 0
3808
+ };
3809
+ registry.set(id, {
3810
+ id,
3811
+ component,
3812
+ options
3813
+ });
3814
+ const wrapper = async (props) => {
3815
+ noteWrapperRender(id, options);
3816
+ if (isCaptureActive()) return createElement(component, props);
3817
+ const revived = slots ? await tryReviveSlotShell(id, options, slots, props) : await tryRevivePayload(id, options, props);
3818
+ if (revived !== null) return revived.element;
3819
+ if (options.fallbackOnMissingSegmentParams === false) throw new Error(`[timber] cache.component "${id}": no prebuilt payload for the current params and fallbackOnMissingSegmentParams is false`);
3820
+ return createElement(component, props);
3821
+ };
3822
+ Object.defineProperty(wrapper, "name", { value: `Prebuilt(${id})` });
3823
+ return wrapper;
3824
+ }
3825
+ /** Look up a registration by stable component ID. */
3826
+ function getPrebuiltRegistration(id) {
3827
+ return registry.get(id);
3828
+ }
3829
+ /** All registrations, for the post-build capture pass (TIM-1119). */
3830
+ function getPrebuiltRegistry() {
3831
+ return registry;
3832
+ }
3833
+ /**
3834
+ * Dev-mode wrapper injected by the timber-prebuilt transform: a no-op that
3835
+ * renders the component dynamically on every request, logging once per
3836
+ * component on first render so the production behavior difference is visible.
3837
+ * See design/44 §Dev Mode.
3838
+ */
3839
+ function __prebuiltDev(name, component, options = {}) {
3840
+ const resolution = resolveSlotNames(name, options);
3841
+ const slots = resolution.kind === "active" ? resolution.slots : null;
3842
+ let logged = false;
3843
+ const wrapper = (props) => {
3844
+ if (!logged) {
3845
+ logged = true;
3846
+ console.log(`[timber] cache.component: "${name}" — rendering dynamically (dev mode)`);
3847
+ }
3848
+ if (slots) {
3849
+ const render = prepareSlotRender(props, slots);
3850
+ if (render !== null && isSlotRenderKeyable(render.dataProps)) return wrapInSlotsProvider(createElement(component, render.shellProps), render.slotValues);
3851
+ }
3852
+ return createElement(component, props);
3853
+ };
3854
+ return wrapper;
3855
+ }
3856
+ //#endregion
3857
+ export { AccessGate, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RenderError, RenderTimeoutError, SlotAccessGate, __prebuilt, __prebuiltDev, callOnRequestError, canonicalize, classifyMetadataRoute, coerce, collectEarlyHintHeaders, computeComponentCacheKey, createPipeline, enforceBodyLimits, executeAction, formatLinkHeader, generateTraceId, getCookie, getHeader, getLogger, getMetadataRouteAutoLink, getMetadataRouteServePath, getPrebuiltRegistration, getPrebuiltRegistry, getSearchParams, getSegmentParams, getSetCookieHeaders, handleRouteRequest, hasOnRequestError, hasPrebuiltPayloadSource, loadInstrumentation, logCacheMiss, logMiddlewareError, logMiddlewareShortCircuit, logProxyError, logRenderError, logRequestCompleted, logRequestReceived, logSlowRequest, logSwrRefetchFailed, logWaitUntilRejected, logWaitUntilUnsupported, markResponseFlushed, parseBodySize, renderMetadataToElements, replaceTraceId, resolveAllowedMethods, resolveMetadata, resolveMetadataUrls, resolveSlotDenied, resolveStatusFile, resolveTitle, runMiddleware, runProxy, runWithEarlyHintsSender, runWithRequestContext, runWithTraceId, sendEarlyHints103, setLogger, setMutableCookieContext, setPrebuiltPayloadSource, setSegmentParams, validateCsrf };
3858
+
3859
+ //# sourceMappingURL=internal.js.map