@timber-js/app 0.2.0-alpha.22 → 0.2.0-alpha.221

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 (1484) hide show
  1. package/LICENSE +8 -0
  2. package/agent-skill.md +351 -0
  3. package/bin/timber.mjs +15 -1
  4. package/dist/_chunks/actions-BDqn4Oxj.js +1243 -0
  5. package/dist/_chunks/actions-BDqn4Oxj.js.map +1 -0
  6. package/dist/_chunks/als-registry-BZqHCtq-.js +43 -0
  7. package/dist/_chunks/als-registry-BZqHCtq-.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-RV_BRcF1.js +367 -0
  15. package/dist/_chunks/build-output-helper-RV_BRcF1.js.map +1 -0
  16. package/dist/_chunks/cache-api-GE4AOe2H.js +1061 -0
  17. package/dist/_chunks/cache-api-GE4AOe2H.js.map +1 -0
  18. package/dist/_chunks/canonicalize-BAWkWiKK.js +92 -0
  19. package/dist/_chunks/canonicalize-BAWkWiKK.js.map +1 -0
  20. package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
  21. package/dist/_chunks/chains-e_Buf9vg.js +267 -0
  22. package/dist/_chunks/chains-e_Buf9vg.js.map +1 -0
  23. package/dist/_chunks/classify-2Yp3xJY1.js +147 -0
  24. package/dist/_chunks/classify-2Yp3xJY1.js.map +1 -0
  25. package/dist/_chunks/cli-check-DDwCkeDY.js +252 -0
  26. package/dist/_chunks/cli-check-DDwCkeDY.js.map +1 -0
  27. package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
  28. package/dist/_chunks/cli-context-_mPttGGY.js +70 -0
  29. package/dist/_chunks/cli-context-_mPttGGY.js.map +1 -0
  30. package/dist/_chunks/cli-schema-sync-BdIebmk3.js +290 -0
  31. package/dist/_chunks/cli-schema-sync-BdIebmk3.js.map +1 -0
  32. package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
  33. package/dist/_chunks/client-dep-entries-BOkpKjj1.js +110 -0
  34. package/dist/_chunks/client-dep-entries-BOkpKjj1.js.map +1 -0
  35. package/dist/_chunks/cloudflare-Byxl8FWP.js +1333 -0
  36. package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -0
  37. package/dist/_chunks/codec-registry-oOUxugz3.js +21 -0
  38. package/dist/_chunks/codec-registry-oOUxugz3.js.map +1 -0
  39. package/dist/_chunks/codegen-Bps1sLKJ.js +432 -0
  40. package/dist/_chunks/codegen-Bps1sLKJ.js.map +1 -0
  41. package/dist/_chunks/convention-lint-ByKJ6aqD.js +590 -0
  42. package/dist/_chunks/convention-lint-ByKJ6aqD.js.map +1 -0
  43. package/dist/_chunks/dev-server-BiWNMBVU.js +1 -0
  44. package/dist/_chunks/dev-server-DIy-SY-J.js +2061 -0
  45. package/dist/_chunks/dev-server-DIy-SY-J.js.map +1 -0
  46. package/dist/_chunks/dev-store-BOa304m_.js +283 -0
  47. package/dist/_chunks/dev-store-BOa304m_.js.map +1 -0
  48. package/dist/_chunks/dist-DtrJyBbw.js +386 -0
  49. package/dist/_chunks/dist-DtrJyBbw.js.map +1 -0
  50. package/dist/_chunks/error-boundary-Bc8QPZuq.js +1107 -0
  51. package/dist/_chunks/error-boundary-Bc8QPZuq.js.map +1 -0
  52. package/dist/_chunks/fast-hash-C-tVYrLb.js +41 -0
  53. package/dist/_chunks/fast-hash-C-tVYrLb.js.map +1 -0
  54. package/dist/_chunks/flight-source-node-HptmGMT8.js +518 -0
  55. package/dist/_chunks/flight-source-node-HptmGMT8.js.map +1 -0
  56. package/dist/_chunks/format-BKclgVbk.js +14 -0
  57. package/dist/_chunks/format-BKclgVbk.js.map +1 -0
  58. package/dist/_chunks/fs-identity-BRKuL215.js +207 -0
  59. package/dist/_chunks/fs-identity-BRKuL215.js.map +1 -0
  60. package/dist/_chunks/graph-cache-CYiUS2aS.js +303 -0
  61. package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -0
  62. package/dist/_chunks/href-validation-BIrxavIy.js +213 -0
  63. package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
  64. package/dist/_chunks/json-lossy-check-C8zBY2uZ.js +66 -0
  65. package/dist/_chunks/json-lossy-check-C8zBY2uZ.js.map +1 -0
  66. package/dist/_chunks/live-graph-tSWrv8eH.js +151 -0
  67. package/dist/_chunks/live-graph-tSWrv8eH.js.map +1 -0
  68. package/dist/_chunks/logger-CbLdcy-W.js +662 -0
  69. package/dist/_chunks/logger-CbLdcy-W.js.map +1 -0
  70. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → metadata-routes-B3XJNyIH.js} +70 -27
  71. package/dist/_chunks/metadata-routes-B3XJNyIH.js.map +1 -0
  72. package/dist/_chunks/navigation-root-BQfo1-kG.js +126 -0
  73. package/dist/_chunks/navigation-root-BQfo1-kG.js.map +1 -0
  74. package/dist/_chunks/node-response-rkQqcFGq.js +233 -0
  75. package/dist/_chunks/node-response-rkQqcFGq.js.map +1 -0
  76. package/dist/_chunks/param-value-C8TNYchQ.js +66 -0
  77. package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
  78. package/dist/_chunks/plugin-context-DxMMvjUt.js +329 -0
  79. package/dist/_chunks/plugin-context-DxMMvjUt.js.map +1 -0
  80. package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
  81. package/dist/_chunks/poison-rules-DoEhbqaY.js +110 -0
  82. package/dist/_chunks/poison-rules-DoEhbqaY.js.map +1 -0
  83. package/dist/_chunks/poison-scan-C4FgMxFl.js +99 -0
  84. package/dist/_chunks/poison-scan-C4FgMxFl.js.map +1 -0
  85. package/dist/_chunks/purge-store-WZaxu-3m.js +14 -0
  86. package/dist/_chunks/purge-store-WZaxu-3m.js.map +1 -0
  87. package/dist/_chunks/render-timeout-joFhz4KH.js +37 -0
  88. package/dist/_chunks/render-timeout-joFhz4KH.js.map +1 -0
  89. package/dist/_chunks/resolve-schema-CBR6Lm4i.js +50 -0
  90. package/dist/_chunks/resolve-schema-CBR6Lm4i.js.map +1 -0
  91. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js +243 -0
  92. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js.map +1 -0
  93. package/dist/_chunks/rsc-media-type-DDc7duTD.js +61 -0
  94. package/dist/_chunks/rsc-media-type-DDc7duTD.js.map +1 -0
  95. package/dist/_chunks/rsc-payload-path-dffcs4jp.js +54 -0
  96. package/dist/_chunks/rsc-payload-path-dffcs4jp.js.map +1 -0
  97. package/dist/_chunks/scan-BoP17W3w.js +140 -0
  98. package/dist/_chunks/scan-BoP17W3w.js.map +1 -0
  99. package/dist/_chunks/scanner-Cb3fSjAC.js +2056 -0
  100. package/dist/_chunks/scanner-Cb3fSjAC.js.map +1 -0
  101. package/dist/_chunks/schema-bridge-C83xa9lT.js +199 -0
  102. package/dist/_chunks/schema-bridge-C83xa9lT.js.map +1 -0
  103. package/dist/_chunks/segment-classify-C539Pa2O.js +197 -0
  104. package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -0
  105. package/dist/_chunks/segment-context-xtPUGfdq.js +137 -0
  106. package/dist/_chunks/segment-context-xtPUGfdq.js.map +1 -0
  107. package/dist/_chunks/segment-keys-D5hu1hz4.js +62 -0
  108. package/dist/_chunks/segment-keys-D5hu1hz4.js.map +1 -0
  109. package/dist/_chunks/singleflight-BeVMMKi0.js +55 -0
  110. package/dist/_chunks/singleflight-BeVMMKi0.js.map +1 -0
  111. package/dist/_chunks/sizeof-QPE5nd3u.js +36 -0
  112. package/dist/_chunks/sizeof-QPE5nd3u.js.map +1 -0
  113. package/dist/_chunks/ssr-data-nA3I70_n.js +49 -0
  114. package/dist/_chunks/ssr-data-nA3I70_n.js.map +1 -0
  115. package/dist/_chunks/state-BhNGPsdi.js +50 -0
  116. package/dist/_chunks/state-BhNGPsdi.js.map +1 -0
  117. package/dist/_chunks/status-page-marker-BRX9Ib-d.js +564 -0
  118. package/dist/_chunks/status-page-marker-BRX9Ib-d.js.map +1 -0
  119. package/dist/_chunks/tree-match-6yihorhk.js +169 -0
  120. package/dist/_chunks/tree-match-6yihorhk.js.map +1 -0
  121. package/dist/_chunks/use-query-states-I3JMng6J.js +226 -0
  122. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -0
  123. package/dist/_chunks/walkers-qu8TpiLh.js +144 -0
  124. package/dist/_chunks/walkers-qu8TpiLh.js.map +1 -0
  125. package/dist/_chunks/write-file-atomic-D1qWqHb4.js +32 -0
  126. package/dist/_chunks/write-file-atomic-D1qWqHb4.js.map +1 -0
  127. package/dist/adapters/build-output-helper.d.ts +72 -0
  128. package/dist/adapters/build-output-helper.d.ts.map +1 -0
  129. package/dist/adapters/canonicalize-module.d.ts +8 -0
  130. package/dist/adapters/canonicalize-module.d.ts.map +1 -0
  131. package/dist/adapters/cloudflare-dev.d.ts +109 -0
  132. package/dist/adapters/cloudflare-dev.d.ts.map +1 -0
  133. package/dist/adapters/cloudflare-dev.js +74 -0
  134. package/dist/adapters/cloudflare-dev.js.map +1 -0
  135. package/dist/adapters/cloudflare-kv-cache.d.ts +65 -0
  136. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -0
  137. package/dist/adapters/cloudflare-kv-cache.js +123 -0
  138. package/dist/adapters/cloudflare-kv-cache.js.map +1 -0
  139. package/dist/adapters/cloudflare.d.ts +224 -24
  140. package/dist/adapters/cloudflare.d.ts.map +1 -1
  141. package/dist/adapters/cloudflare.js +1 -188
  142. package/dist/adapters/compress-module.d.ts +25 -4
  143. package/dist/adapters/compress-module.d.ts.map +1 -1
  144. package/dist/adapters/fs-identity.d.ts +63 -0
  145. package/dist/adapters/fs-identity.d.ts.map +1 -0
  146. package/dist/adapters/nitro-immutable-assets.d.ts +47 -0
  147. package/dist/adapters/nitro-immutable-assets.d.ts.map +1 -0
  148. package/dist/adapters/nitro-presets.d.ts +31 -0
  149. package/dist/adapters/nitro-presets.d.ts.map +1 -0
  150. package/dist/adapters/nitro-preview.d.ts +65 -0
  151. package/dist/adapters/nitro-preview.d.ts.map +1 -0
  152. package/dist/adapters/nitro.d.ts +69 -38
  153. package/dist/adapters/nitro.d.ts.map +1 -1
  154. package/dist/adapters/nitro.js +793 -341
  155. package/dist/adapters/nitro.js.map +1 -1
  156. package/dist/adapters/shared.d.ts +67 -0
  157. package/dist/adapters/shared.d.ts.map +1 -0
  158. package/dist/adapters/types.d.ts +124 -16
  159. package/dist/adapters/types.d.ts.map +1 -1
  160. package/dist/adapters/types.js +0 -0
  161. package/dist/analyze/chains.d.ts +124 -0
  162. package/dist/analyze/chains.d.ts.map +1 -0
  163. package/dist/analyze/classify.d.ts +153 -0
  164. package/dist/analyze/classify.d.ts.map +1 -0
  165. package/dist/analyze/crawl-entry.d.ts +17 -0
  166. package/dist/analyze/crawl-entry.d.ts.map +1 -0
  167. package/dist/analyze/crawl-entry.js +314 -0
  168. package/dist/analyze/crawl-entry.js.map +1 -0
  169. package/dist/analyze/crawl.d.ts +134 -0
  170. package/dist/analyze/crawl.d.ts.map +1 -0
  171. package/dist/analyze/graph-cache.d.ts +104 -0
  172. package/dist/analyze/graph-cache.d.ts.map +1 -0
  173. package/dist/analyze/graph-command.d.ts +43 -0
  174. package/dist/analyze/graph-command.d.ts.map +1 -0
  175. package/dist/analyze/graph-command.js +472 -0
  176. package/dist/analyze/graph-command.js.map +1 -0
  177. package/dist/analyze/live-graph.d.ts +81 -0
  178. package/dist/analyze/live-graph.d.ts.map +1 -0
  179. package/dist/analyze/poison-rules.d.ts +72 -0
  180. package/dist/analyze/poison-rules.d.ts.map +1 -0
  181. package/dist/analyze/poison-scan.d.ts +48 -0
  182. package/dist/analyze/poison-scan.d.ts.map +1 -0
  183. package/dist/analyze/scan.d.ts +73 -0
  184. package/dist/analyze/scan.d.ts.map +1 -0
  185. package/dist/cache/cache-api.d.ts +48 -0
  186. package/dist/cache/cache-api.d.ts.map +1 -0
  187. package/dist/cache/fast-hash.d.ts +5 -0
  188. package/dist/cache/fast-hash.d.ts.map +1 -1
  189. package/dist/cache/handler-store.d.ts +45 -0
  190. package/dist/cache/handler-store.d.ts.map +1 -0
  191. package/dist/cache/index.d.ts +32 -9
  192. package/dist/cache/index.d.ts.map +1 -1
  193. package/dist/cache/index.js +4 -326
  194. package/dist/cache/invalidation-epoch.d.ts +50 -0
  195. package/dist/cache/invalidation-epoch.d.ts.map +1 -0
  196. package/dist/cache/json-lossy-check.d.ts +11 -0
  197. package/dist/cache/json-lossy-check.d.ts.map +1 -0
  198. package/dist/cache/redis-handler.d.ts +141 -9
  199. package/dist/cache/redis-handler.d.ts.map +1 -1
  200. package/dist/cache/singleflight.d.ts +21 -2
  201. package/dist/cache/singleflight.d.ts.map +1 -1
  202. package/dist/cache/sizeof.d.ts +22 -0
  203. package/dist/cache/sizeof.d.ts.map +1 -0
  204. package/dist/cache/stable-stringify.d.ts +9 -0
  205. package/dist/cache/stable-stringify.d.ts.map +1 -1
  206. package/dist/cache/store.d.ts +53 -0
  207. package/dist/cache/store.d.ts.map +1 -0
  208. package/dist/cache/stores/cloudflare-kv.d.ts +38 -0
  209. package/dist/cache/stores/cloudflare-kv.d.ts.map +1 -0
  210. package/dist/cache/stores/cloudflare-kv.js +29 -0
  211. package/dist/cache/stores/cloudflare-kv.js.map +1 -0
  212. package/dist/cache/stores/memory.d.ts +42 -0
  213. package/dist/cache/stores/memory.d.ts.map +1 -0
  214. package/dist/cache/stores/memory.js +90 -0
  215. package/dist/cache/stores/memory.js.map +1 -0
  216. package/dist/cache/stores/redis.d.ts +69 -0
  217. package/dist/cache/stores/redis.d.ts.map +1 -0
  218. package/dist/cache/stores/redis.js +35 -0
  219. package/dist/cache/stores/redis.js.map +1 -0
  220. package/dist/cache/stores/vercel.d.ts +36 -0
  221. package/dist/cache/stores/vercel.d.ts.map +1 -0
  222. package/dist/cache/stores/vercel.js +33 -0
  223. package/dist/cache/stores/vercel.js.map +1 -0
  224. package/dist/cache/tag-aware-handler.d.ts +52 -0
  225. package/dist/cache/tag-aware-handler.d.ts.map +1 -0
  226. package/dist/cache/timber-cache.d.ts +21 -11
  227. package/dist/cache/timber-cache.d.ts.map +1 -1
  228. package/dist/cdn/cloudflare-purge.d.ts +23 -0
  229. package/dist/cdn/cloudflare-purge.d.ts.map +1 -0
  230. package/dist/cdn/cloudflare-purge.js +30 -0
  231. package/dist/cdn/cloudflare-purge.js.map +1 -0
  232. package/dist/cdn/fastly-purge.d.ts +25 -0
  233. package/dist/cdn/fastly-purge.d.ts.map +1 -0
  234. package/dist/cdn/fastly-purge.js +33 -0
  235. package/dist/cdn/fastly-purge.js.map +1 -0
  236. package/dist/cdn/headers.d.ts +97 -0
  237. package/dist/cdn/headers.d.ts.map +1 -0
  238. package/dist/cdn/index.d.ts +5 -0
  239. package/dist/cdn/index.d.ts.map +1 -0
  240. package/dist/cdn/index.js +94 -0
  241. package/dist/cdn/index.js.map +1 -0
  242. package/dist/cdn/purge-store.d.ts +32 -0
  243. package/dist/cdn/purge-store.d.ts.map +1 -0
  244. package/dist/cdn/workers-cache-purge.d.ts +20 -0
  245. package/dist/cdn/workers-cache-purge.d.ts.map +1 -0
  246. package/dist/cdn/workers-cache-purge.js +35 -0
  247. package/dist/cdn/workers-cache-purge.js.map +1 -0
  248. package/dist/cli-check.d.ts +133 -0
  249. package/dist/cli-check.d.ts.map +1 -0
  250. package/dist/cli-context.d.ts +54 -0
  251. package/dist/cli-context.d.ts.map +1 -0
  252. package/dist/cli-schema-sync.d.ts +59 -0
  253. package/dist/cli-schema-sync.d.ts.map +1 -0
  254. package/dist/cli.d.ts +88 -16
  255. package/dist/cli.d.ts.map +1 -1
  256. package/dist/cli.js +225 -63
  257. package/dist/cli.js.map +1 -1
  258. package/dist/client/browser-dev.d.ts +42 -2
  259. package/dist/client/browser-dev.d.ts.map +1 -1
  260. package/dist/client/browser-entry/action-dispatch.d.ts +19 -0
  261. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  262. package/dist/client/browser-entry/action-queue.d.ts +64 -0
  263. package/dist/client/browser-entry/action-queue.d.ts.map +1 -0
  264. package/dist/client/browser-entry/form-state.d.ts +22 -0
  265. package/dist/client/browser-entry/form-state.d.ts.map +1 -0
  266. package/dist/client/browser-entry/hmr.d.ts +21 -0
  267. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  268. package/dist/client/browser-entry/hydrate.d.ts +61 -0
  269. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  270. package/dist/client/browser-entry/index.d.ts +32 -0
  271. package/dist/client/browser-entry/index.d.ts.map +1 -0
  272. package/dist/client/browser-entry/post-hydration.d.ts +26 -0
  273. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  274. package/dist/client/browser-entry/router-init.d.ts +41 -0
  275. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  276. package/dist/client/browser-entry/rsc-stream.d.ts +35 -0
  277. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  278. package/dist/client/browser-entry/scroll.d.ts +28 -0
  279. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  280. package/dist/client/deny-last-resort.d.ts +29 -0
  281. package/dist/client/deny-last-resort.d.ts.map +1 -0
  282. package/dist/client/error-boundary.d.ts +58 -9
  283. package/dist/client/error-boundary.d.ts.map +1 -1
  284. package/dist/client/error-boundary.js +1 -126
  285. package/dist/client/error-reconstituter.d.ts +55 -0
  286. package/dist/client/error-reconstituter.d.ts.map +1 -0
  287. package/dist/client/form.d.ts +38 -99
  288. package/dist/client/form.d.ts.map +1 -1
  289. package/dist/client/global-context.d.ts +15 -0
  290. package/dist/client/global-context.d.ts.map +1 -0
  291. package/dist/client/history.d.ts +50 -9
  292. package/dist/client/history.d.ts.map +1 -1
  293. package/dist/client/index.d.ts +21 -33
  294. package/dist/client/index.d.ts.map +1 -1
  295. package/dist/client/index.js +423 -1227
  296. package/dist/client/index.js.map +1 -1
  297. package/dist/client/internal.d.ts +20 -0
  298. package/dist/client/internal.d.ts.map +1 -0
  299. package/dist/client/internal.js +781 -0
  300. package/dist/client/internal.js.map +1 -0
  301. package/dist/client/link.d.ts +85 -60
  302. package/dist/client/link.d.ts.map +1 -1
  303. package/dist/client/location-search.d.ts +12 -0
  304. package/dist/client/location-search.d.ts.map +1 -0
  305. package/dist/client/navigation-api.d.ts +95 -0
  306. package/dist/client/navigation-api.d.ts.map +1 -0
  307. package/dist/client/navigation-commit.d.ts +111 -0
  308. package/dist/client/navigation-commit.d.ts.map +1 -0
  309. package/dist/client/navigation-context.d.ts +54 -36
  310. package/dist/client/navigation-context.d.ts.map +1 -1
  311. package/dist/client/navigation-root.d.ts +106 -0
  312. package/dist/client/navigation-root.d.ts.map +1 -0
  313. package/dist/client/navigation-transition.d.ts +255 -0
  314. package/dist/client/navigation-transition.d.ts.map +1 -0
  315. package/dist/client/nuqs-adapter.d.ts +1 -1
  316. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  317. package/dist/client/params-context.d.ts +81 -0
  318. package/dist/client/params-context.d.ts.map +1 -0
  319. package/dist/client/react-root.d.ts +51 -0
  320. package/dist/client/react-root.d.ts.map +1 -0
  321. package/dist/client/router-effects.d.ts +203 -0
  322. package/dist/client/router-effects.d.ts.map +1 -0
  323. package/dist/client/router-lifecycle.d.ts +104 -0
  324. package/dist/client/router-lifecycle.d.ts.map +1 -0
  325. package/dist/client/router-pipeline.d.ts +81 -0
  326. package/dist/client/router-pipeline.d.ts.map +1 -0
  327. package/dist/client/router-ref.d.ts +2 -2
  328. package/dist/client/router-ref.d.ts.map +1 -1
  329. package/dist/client/router-skew.d.ts +21 -0
  330. package/dist/client/router-skew.d.ts.map +1 -0
  331. package/dist/client/router-types.d.ts +294 -0
  332. package/dist/client/router-types.d.ts.map +1 -0
  333. package/dist/client/router-url.d.ts +24 -0
  334. package/dist/client/router-url.d.ts.map +1 -0
  335. package/dist/client/router.d.ts +1 -97
  336. package/dist/client/router.d.ts.map +1 -1
  337. package/dist/client/rsc-fetch.d.ts +110 -28
  338. package/dist/client/rsc-fetch.d.ts.map +1 -1
  339. package/dist/client/segment-cache.d.ts +186 -25
  340. package/dist/client/segment-cache.d.ts.map +1 -1
  341. package/dist/client/segment-context.d.ts.map +1 -1
  342. package/dist/client/segment-outlet.d.ts +68 -0
  343. package/dist/client/segment-outlet.d.ts.map +1 -0
  344. package/dist/client/segment-update-context.d.ts +15 -0
  345. package/dist/client/segment-update-context.d.ts.map +1 -0
  346. package/dist/client/shallow-url.d.ts +10 -0
  347. package/dist/client/shallow-url.d.ts.map +1 -0
  348. package/dist/client/slot-content-cache-context.d.ts +35 -0
  349. package/dist/client/slot-content-cache-context.d.ts.map +1 -0
  350. package/dist/client/slot-context.d.ts +31 -0
  351. package/dist/client/slot-context.d.ts.map +1 -0
  352. package/dist/client/slot-outlet.d.ts +16 -0
  353. package/dist/client/slot-outlet.d.ts.map +1 -0
  354. package/dist/client/slot-provider.d.ts +25 -0
  355. package/dist/client/slot-provider.d.ts.map +1 -0
  356. package/dist/client/ssr-data.d.ts +26 -50
  357. package/dist/client/ssr-data.d.ts.map +1 -1
  358. package/dist/client/stale-client.d.ts +69 -0
  359. package/dist/client/stale-client.d.ts.map +1 -0
  360. package/dist/client/state.d.ts +21 -13
  361. package/dist/client/state.d.ts.map +1 -1
  362. package/dist/client/status-page-marker.d.ts +25 -0
  363. package/dist/client/status-page-marker.d.ts.map +1 -0
  364. package/dist/client/top-loader.d.ts +7 -6
  365. package/dist/client/top-loader.d.ts.map +1 -1
  366. package/dist/client/unload-guard.d.ts +5 -0
  367. package/dist/client/unload-guard.d.ts.map +1 -1
  368. package/dist/client/use-cookie.d.ts +12 -0
  369. package/dist/client/use-cookie.d.ts.map +1 -1
  370. package/dist/client/use-field-state.d.ts +42 -0
  371. package/dist/client/use-field-state.d.ts.map +1 -0
  372. package/dist/client/use-link-status.d.ts +5 -5
  373. package/dist/client/use-link-status.d.ts.map +1 -1
  374. package/dist/client/use-pathname.d.ts +13 -11
  375. package/dist/client/use-pathname.d.ts.map +1 -1
  376. package/dist/client/use-pending-navigation.d.ts +23 -0
  377. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  378. package/dist/client/use-query-states.d.ts +10 -4
  379. package/dist/client/use-query-states.d.ts.map +1 -1
  380. package/dist/client/use-router.d.ts +15 -8
  381. package/dist/client/use-router.d.ts.map +1 -1
  382. package/dist/client/use-search-params.d.ts +15 -8
  383. package/dist/client/use-search-params.d.ts.map +1 -1
  384. package/dist/client/use-segment-params.d.ts +55 -0
  385. package/dist/client/use-segment-params.d.ts.map +1 -0
  386. package/dist/codec.d.ts +69 -0
  387. package/dist/codec.d.ts.map +1 -0
  388. package/dist/codec.js +76 -0
  389. package/dist/codec.js.map +1 -0
  390. package/dist/config-types.d.ts +321 -0
  391. package/dist/config-types.d.ts.map +1 -0
  392. package/dist/config-validation.d.ts +68 -0
  393. package/dist/config-validation.d.ts.map +1 -0
  394. package/dist/cookies/define-cookie.d.ts +58 -25
  395. package/dist/cookies/define-cookie.d.ts.map +1 -1
  396. package/dist/cookies/index.d.ts +3 -2
  397. package/dist/cookies/index.d.ts.map +1 -1
  398. package/dist/cookies/index.js +256 -36
  399. package/dist/cookies/index.js.map +1 -1
  400. package/dist/cookies/json-cookie.d.ts +64 -0
  401. package/dist/cookies/json-cookie.d.ts.map +1 -0
  402. package/dist/cookies/validation.d.ts +34 -0
  403. package/dist/cookies/validation.d.ts.map +1 -0
  404. package/dist/dev-tools/404-page.d.ts +50 -0
  405. package/dist/dev-tools/404-page.d.ts.map +1 -0
  406. package/dist/dev-tools/browser-logs.d.ts +40 -0
  407. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  408. package/dist/dev-tools/dev-page-shell.d.ts +95 -0
  409. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  410. package/dist/dev-tools/error-page.d.ts +32 -0
  411. package/dist/dev-tools/error-page.d.ts.map +1 -0
  412. package/dist/dev-tools/holding-server.d.ts +46 -0
  413. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  414. package/dist/dev-tools/hydration-overlay.d.ts +11 -0
  415. package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
  416. package/dist/dev-tools/index.d.ts +31 -0
  417. package/dist/dev-tools/index.d.ts.map +1 -0
  418. package/dist/dev-tools/instrumentation.d.ts +74 -0
  419. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  420. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  421. package/dist/dev-tools/logger.d.ts.map +1 -0
  422. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +19 -5
  423. package/dist/dev-tools/logs.d.ts.map +1 -0
  424. package/dist/{plugins/dev-error-overlay.d.ts → dev-tools/overlay.d.ts} +15 -25
  425. package/dist/dev-tools/overlay.d.ts.map +1 -0
  426. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  427. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  428. package/dist/dev-tools/terminal.d.ts +28 -0
  429. package/dist/dev-tools/terminal.d.ts.map +1 -0
  430. package/dist/fonts/ast-walk.d.ts +68 -0
  431. package/dist/fonts/ast-walk.d.ts.map +1 -0
  432. package/dist/fonts/ast.d.ts +112 -8
  433. package/dist/fonts/ast.d.ts.map +1 -1
  434. package/dist/fonts/bundle.d.ts +50 -0
  435. package/dist/fonts/bundle.d.ts.map +1 -0
  436. package/dist/fonts/css.d.ts +1 -1
  437. package/dist/fonts/dev-middleware.d.ts +22 -0
  438. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  439. package/dist/fonts/fallbacks.d.ts +0 -7
  440. package/dist/fonts/fallbacks.d.ts.map +1 -1
  441. package/dist/fonts/google.d.ts +5 -3
  442. package/dist/fonts/google.d.ts.map +1 -1
  443. package/dist/fonts/local.d.ts +5 -5
  444. package/dist/fonts/local.d.ts.map +1 -1
  445. package/dist/fonts/paths.d.ts +43 -0
  446. package/dist/fonts/paths.d.ts.map +1 -0
  447. package/dist/fonts/pipeline.d.ts +177 -0
  448. package/dist/fonts/pipeline.d.ts.map +1 -0
  449. package/dist/fonts/transform.d.ts +82 -0
  450. package/dist/fonts/transform.d.ts.map +1 -0
  451. package/dist/fonts/types.d.ts +47 -1
  452. package/dist/fonts/types.d.ts.map +1 -1
  453. package/dist/fonts/virtual-modules.d.ts +77 -0
  454. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  455. package/dist/index.d.ts +35 -181
  456. package/dist/index.d.ts.map +1 -1
  457. package/dist/index.js +8972 -14234
  458. package/dist/index.js.map +1 -1
  459. package/dist/params/codec-registry.d.ts +26 -0
  460. package/dist/params/codec-registry.d.ts.map +1 -0
  461. package/dist/params/define-schema.d.ts +81 -0
  462. package/dist/params/define-schema.d.ts.map +1 -0
  463. package/dist/params/index.d.ts +5 -0
  464. package/dist/params/index.d.ts.map +1 -0
  465. package/dist/params/index.js +34 -0
  466. package/dist/params/index.js.map +1 -0
  467. package/dist/params/resolve-schema.d.ts +34 -0
  468. package/dist/params/resolve-schema.d.ts.map +1 -0
  469. package/dist/plugin-context.d.ts +262 -0
  470. package/dist/plugin-context.d.ts.map +1 -0
  471. package/dist/plugins/build-manifest.d.ts +7 -3
  472. package/dist/plugins/build-manifest.d.ts.map +1 -1
  473. package/dist/plugins/build-report.d.ts +61 -11
  474. package/dist/plugins/build-report.d.ts.map +1 -1
  475. package/dist/plugins/cache.d.ts +64 -0
  476. package/dist/plugins/cache.d.ts.map +1 -0
  477. package/dist/plugins/callsite-ast.d.ts +117 -0
  478. package/dist/plugins/callsite-ast.d.ts.map +1 -0
  479. package/dist/plugins/callsite-jsx.d.ts +35 -0
  480. package/dist/plugins/callsite-jsx.d.ts.map +1 -0
  481. package/dist/plugins/chunks.d.ts +11 -4
  482. package/dist/plugins/chunks.d.ts.map +1 -1
  483. package/dist/plugins/client-chunks.d.ts +40 -0
  484. package/dist/plugins/client-chunks.d.ts.map +1 -0
  485. package/dist/plugins/client-dep-entries.d.ts +80 -0
  486. package/dist/plugins/client-dep-entries.d.ts.map +1 -0
  487. package/dist/plugins/cloudflare-wasm.d.ts +21 -0
  488. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  489. package/dist/plugins/content.d.ts +1 -1
  490. package/dist/plugins/content.d.ts.map +1 -1
  491. package/dist/plugins/dev-discovery.d.ts +123 -0
  492. package/dist/plugins/dev-discovery.d.ts.map +1 -0
  493. package/dist/plugins/dev-server.d.ts +24 -1
  494. package/dist/plugins/dev-server.d.ts.map +1 -1
  495. package/dist/plugins/encryption-runtime.d.ts +13 -0
  496. package/dist/plugins/encryption-runtime.d.ts.map +1 -0
  497. package/dist/plugins/entries.d.ts +40 -4
  498. package/dist/plugins/entries.d.ts.map +1 -1
  499. package/dist/plugins/fonts.d.ts +35 -74
  500. package/dist/plugins/fonts.d.ts.map +1 -1
  501. package/dist/plugins/graph-endpoint.d.ts +112 -0
  502. package/dist/plugins/graph-endpoint.d.ts.map +1 -0
  503. package/dist/plugins/mdx.d.ts +18 -5
  504. package/dist/plugins/mdx.d.ts.map +1 -1
  505. package/dist/plugins/orphaned-modules.d.ts +57 -0
  506. package/dist/plugins/orphaned-modules.d.ts.map +1 -0
  507. package/dist/plugins/post-build.d.ts +110 -0
  508. package/dist/plugins/post-build.d.ts.map +1 -0
  509. package/dist/plugins/prebuilt-capture.d.ts +67 -0
  510. package/dist/plugins/prebuilt-capture.d.ts.map +1 -0
  511. package/dist/plugins/prebuilt-options-analysis.d.ts +40 -0
  512. package/dist/plugins/prebuilt-options-analysis.d.ts.map +1 -0
  513. package/dist/plugins/prebuilt.d.ts +98 -0
  514. package/dist/plugins/prebuilt.d.ts.map +1 -0
  515. package/dist/plugins/prerender-sugar.d.ts +39 -0
  516. package/dist/plugins/prerender-sugar.d.ts.map +1 -0
  517. package/dist/plugins/react-resolve.d.ts +49 -0
  518. package/dist/plugins/react-resolve.d.ts.map +1 -0
  519. package/dist/plugins/request-dep/analysis.d.ts +106 -0
  520. package/dist/plugins/request-dep/analysis.d.ts.map +1 -0
  521. package/dist/plugins/request-dep/index.d.ts +75 -0
  522. package/dist/plugins/request-dep/index.d.ts.map +1 -0
  523. package/dist/plugins/request-dep/origin.d.ts +61 -0
  524. package/dist/plugins/request-dep/origin.d.ts.map +1 -0
  525. package/dist/plugins/routing.d.ts +2 -2
  526. package/dist/plugins/routing.d.ts.map +1 -1
  527. package/dist/plugins/rsc-assets-manifest.d.ts +33 -0
  528. package/dist/plugins/rsc-assets-manifest.d.ts.map +1 -0
  529. package/dist/plugins/server-bundle.d.ts +1 -1
  530. package/dist/plugins/server-bundle.d.ts.map +1 -1
  531. package/dist/plugins/shims.d.ts +29 -5
  532. package/dist/plugins/shims.d.ts.map +1 -1
  533. package/dist/plugins/static-build.d.ts +246 -26
  534. package/dist/plugins/static-build.d.ts.map +1 -1
  535. package/dist/routing/codegen-shared.d.ts +26 -0
  536. package/dist/routing/codegen-shared.d.ts.map +1 -0
  537. package/dist/routing/codegen-types.d.ts +61 -0
  538. package/dist/routing/codegen-types.d.ts.map +1 -0
  539. package/dist/routing/codegen-write.d.ts +42 -0
  540. package/dist/routing/codegen-write.d.ts.map +1 -0
  541. package/dist/routing/codegen.d.ts +8 -3
  542. package/dist/routing/codegen.d.ts.map +1 -1
  543. package/dist/routing/collision-probe.d.ts +104 -0
  544. package/dist/routing/collision-probe.d.ts.map +1 -0
  545. package/dist/routing/collision-spaces.d.ts +26 -0
  546. package/dist/routing/collision-spaces.d.ts.map +1 -0
  547. package/dist/routing/convention-lint.d.ts +55 -0
  548. package/dist/routing/convention-lint.d.ts.map +1 -0
  549. package/dist/routing/export-detect.d.ts +91 -0
  550. package/dist/routing/export-detect.d.ts.map +1 -0
  551. package/dist/routing/file-cache.d.ts +8 -0
  552. package/dist/routing/file-cache.d.ts.map +1 -0
  553. package/dist/routing/index.d.ts +13 -7
  554. package/dist/routing/index.d.ts.map +1 -1
  555. package/dist/routing/index.js +5 -2
  556. package/dist/routing/interception-overlap.d.ts +35 -0
  557. package/dist/routing/interception-overlap.d.ts.map +1 -0
  558. package/dist/routing/interception.d.ts +234 -10
  559. package/dist/routing/interception.d.ts.map +1 -1
  560. package/dist/routing/link-codegen.d.ts +105 -0
  561. package/dist/routing/link-codegen.d.ts.map +1 -0
  562. package/dist/routing/manifest-codegen.d.ts +26 -0
  563. package/dist/routing/manifest-codegen.d.ts.map +1 -0
  564. package/dist/routing/scanner.d.ts +14 -10
  565. package/dist/routing/scanner.d.ts.map +1 -1
  566. package/dist/routing/schema-validation.d.ts +35 -0
  567. package/dist/routing/schema-validation.d.ts.map +1 -0
  568. package/dist/routing/segment-classify.d.ts +114 -0
  569. package/dist/routing/segment-classify.d.ts.map +1 -0
  570. package/dist/routing/segment-codegen.d.ts +38 -0
  571. package/dist/routing/segment-codegen.d.ts.map +1 -0
  572. package/dist/routing/segment-keys.d.ts +118 -0
  573. package/dist/routing/segment-keys.d.ts.map +1 -0
  574. package/dist/routing/slot-placement.d.ts +48 -0
  575. package/dist/routing/slot-placement.d.ts.map +1 -0
  576. package/dist/routing/types.d.ts +81 -26
  577. package/dist/routing/types.d.ts.map +1 -1
  578. package/dist/routing/walkers.d.ts +57 -0
  579. package/dist/routing/walkers.d.ts.map +1 -0
  580. package/dist/rsc-runtime/dev-reference-cache.d.ts +47 -0
  581. package/dist/rsc-runtime/dev-reference-cache.d.ts.map +1 -0
  582. package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
  583. package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
  584. package/dist/rsc-runtime/render-flight.d.ts +14 -0
  585. package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
  586. package/dist/rsc-runtime/rsc.d.ts +2 -13
  587. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  588. package/dist/rsc-runtime/ssr.d.ts +7 -10
  589. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  590. package/dist/rsc-runtime/transforms.d.ts +13 -0
  591. package/dist/rsc-runtime/transforms.d.ts.map +1 -0
  592. package/dist/schema-bridge.d.ts +145 -0
  593. package/dist/schema-bridge.d.ts.map +1 -0
  594. package/dist/search-params/define.d.ts +262 -0
  595. package/dist/search-params/define.d.ts.map +1 -0
  596. package/dist/search-params/index.d.ts +3 -7
  597. package/dist/search-params/index.d.ts.map +1 -1
  598. package/dist/search-params/index.js +179 -360
  599. package/dist/search-params/index.js.map +1 -1
  600. package/dist/search-params/parse-total.d.ts +81 -0
  601. package/dist/search-params/parse-total.d.ts.map +1 -0
  602. package/dist/search-params/serialize-equal.d.ts +9 -0
  603. package/dist/search-params/serialize-equal.d.ts.map +1 -0
  604. package/dist/search-params/wrappers.d.ts +76 -0
  605. package/dist/search-params/wrappers.d.ts.map +1 -0
  606. package/dist/server/abort-scope.d.ts +27 -0
  607. package/dist/server/abort-scope.d.ts.map +1 -0
  608. package/dist/server/access-gate.d.ts +98 -10
  609. package/dist/server/access-gate.d.ts.map +1 -1
  610. package/dist/server/action-client.d.ts +20 -133
  611. package/dist/server/action-client.d.ts.map +1 -1
  612. package/dist/server/action-encryption.d.ts +76 -0
  613. package/dist/server/action-encryption.d.ts.map +1 -0
  614. package/dist/server/action-handler.d.ts +58 -11
  615. package/dist/server/action-handler.d.ts.map +1 -1
  616. package/dist/server/action-schema.d.ts +126 -0
  617. package/dist/server/action-schema.d.ts.map +1 -0
  618. package/dist/server/action-types.d.ts +108 -0
  619. package/dist/server/action-types.d.ts.map +1 -0
  620. package/dist/server/actions.d.ts +78 -40
  621. package/dist/server/actions.d.ts.map +1 -1
  622. package/dist/server/als-registry.d.ts +189 -17
  623. package/dist/server/als-registry.d.ts.map +1 -1
  624. package/dist/server/body-limits.d.ts.map +1 -1
  625. package/dist/server/build-manifest.d.ts +25 -30
  626. package/dist/server/build-manifest.d.ts.map +1 -1
  627. package/dist/server/canonicalize.d.ts +32 -0
  628. package/dist/server/canonicalize.d.ts.map +1 -1
  629. package/dist/server/chain-url-parts.d.ts +82 -0
  630. package/dist/server/chain-url-parts.d.ts.map +1 -0
  631. package/dist/server/children-interception.d.ts +49 -0
  632. package/dist/server/children-interception.d.ts.map +1 -0
  633. package/dist/server/client-error-message.d.ts +12 -0
  634. package/dist/server/client-error-message.d.ts.map +1 -0
  635. package/dist/server/coalesce-tick.d.ts +40 -0
  636. package/dist/server/coalesce-tick.d.ts.map +1 -0
  637. package/dist/server/compress.d.ts +2 -0
  638. package/dist/server/compress.d.ts.map +1 -1
  639. package/dist/server/cookie-context.d.ts +149 -0
  640. package/dist/server/cookie-context.d.ts.map +1 -0
  641. package/dist/server/cookie-parsing.d.ts +65 -0
  642. package/dist/server/cookie-parsing.d.ts.map +1 -0
  643. package/dist/server/csp-nonce.d.ts +36 -0
  644. package/dist/server/csp-nonce.d.ts.map +1 -0
  645. package/dist/server/csrf.d.ts +58 -15
  646. package/dist/server/csrf.d.ts.map +1 -1
  647. package/dist/server/debug.d.ts +0 -1
  648. package/dist/server/debug.d.ts.map +1 -1
  649. package/dist/server/default-logger.d.ts +23 -0
  650. package/dist/server/default-logger.d.ts.map +1 -0
  651. package/dist/server/default-status-page.d.ts +45 -0
  652. package/dist/server/default-status-page.d.ts.map +1 -0
  653. package/dist/server/deny-boundary.d.ts +257 -0
  654. package/dist/server/deny-boundary.d.ts.map +1 -0
  655. package/dist/server/deny-renderer.d.ts +22 -15
  656. package/dist/server/deny-renderer.d.ts.map +1 -1
  657. package/dist/server/early-hints-sender.d.ts.map +1 -1
  658. package/dist/server/early-hints.d.ts +14 -12
  659. package/dist/server/early-hints.d.ts.map +1 -1
  660. package/dist/server/error-boundary-wrapper.d.ts +102 -10
  661. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  662. package/dist/server/error-response-headers.d.ts +3 -0
  663. package/dist/server/error-response-headers.d.ts.map +1 -0
  664. package/dist/server/fallback-error.d.ts +19 -7
  665. package/dist/server/fallback-error.d.ts.map +1 -1
  666. package/dist/server/flight-injection-state.d.ts +66 -0
  667. package/dist/server/flight-injection-state.d.ts.map +1 -0
  668. package/dist/server/flight-injector-core.d.ts +125 -0
  669. package/dist/server/flight-injector-core.d.ts.map +1 -0
  670. package/dist/server/flight-scripts.d.ts +63 -0
  671. package/dist/server/flight-scripts.d.ts.map +1 -0
  672. package/dist/server/flight-source-node.d.ts +105 -0
  673. package/dist/server/flight-source-node.d.ts.map +1 -0
  674. package/dist/server/flight-source.d.ts +136 -0
  675. package/dist/server/flight-source.d.ts.map +1 -0
  676. package/dist/server/form-data.d.ts +59 -2
  677. package/dist/server/form-data.d.ts.map +1 -1
  678. package/dist/server/form-state-flight.d.ts +32 -0
  679. package/dist/server/form-state-flight.d.ts.map +1 -0
  680. package/dist/server/head-response.d.ts +35 -0
  681. package/dist/server/head-response.d.ts.map +1 -0
  682. package/dist/server/html-injector-core.d.ts +169 -0
  683. package/dist/server/html-injector-core.d.ts.map +1 -0
  684. package/dist/server/html-injectors.d.ts +77 -47
  685. package/dist/server/html-injectors.d.ts.map +1 -1
  686. package/dist/server/index.d.ts +16 -54
  687. package/dist/server/index.d.ts.map +1 -1
  688. package/dist/server/index.js +638 -3021
  689. package/dist/server/index.js.map +1 -1
  690. package/dist/server/instrumentation.d.ts +13 -5
  691. package/dist/server/instrumentation.d.ts.map +1 -1
  692. package/dist/server/internal.d.ts +47 -0
  693. package/dist/server/internal.d.ts.map +1 -0
  694. package/dist/server/internal.js +4845 -0
  695. package/dist/server/internal.js.map +1 -0
  696. package/dist/server/json-status-response.d.ts +34 -0
  697. package/dist/server/json-status-response.d.ts.map +1 -0
  698. package/dist/server/logger.d.ts +79 -7
  699. package/dist/server/logger.d.ts.map +1 -1
  700. package/dist/server/metadata-collector.d.ts +75 -0
  701. package/dist/server/metadata-collector.d.ts.map +1 -0
  702. package/dist/server/metadata-platform.d.ts +2 -2
  703. package/dist/server/metadata-render.d.ts +2 -2
  704. package/dist/server/metadata-render.d.ts.map +1 -1
  705. package/dist/server/metadata-route-links.d.ts +70 -0
  706. package/dist/server/metadata-route-links.d.ts.map +1 -0
  707. package/dist/server/metadata-routes.d.ts +47 -11
  708. package/dist/server/metadata-routes.d.ts.map +1 -1
  709. package/dist/server/metadata-social.d.ts +2 -2
  710. package/dist/server/metadata.d.ts +10 -2
  711. package/dist/server/metadata.d.ts.map +1 -1
  712. package/dist/server/middleware-runner.d.ts +20 -5
  713. package/dist/server/middleware-runner.d.ts.map +1 -1
  714. package/dist/server/node-body-response.d.ts +55 -0
  715. package/dist/server/node-body-response.d.ts.map +1 -0
  716. package/dist/server/node-response.d.ts +62 -0
  717. package/dist/server/node-response.d.ts.map +1 -0
  718. package/dist/server/node-stream-transforms.d.ts +108 -0
  719. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  720. package/dist/server/node-streams-platform.d.ts +21 -0
  721. package/dist/server/node-streams-platform.d.ts.map +1 -0
  722. package/dist/server/nuqs-ssr-provider.d.ts +7 -3
  723. package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
  724. package/dist/server/param-coercion.d.ts +83 -0
  725. package/dist/server/param-coercion.d.ts.map +1 -0
  726. package/dist/server/pipeline-helpers.d.ts +224 -0
  727. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  728. package/dist/server/pipeline-interception.d.ts +70 -9
  729. package/dist/server/pipeline-interception.d.ts.map +1 -1
  730. package/dist/server/pipeline-metadata.d.ts +16 -1
  731. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  732. package/dist/server/pipeline-outcome.d.ts +59 -0
  733. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  734. package/dist/server/pipeline-phases.d.ts +70 -0
  735. package/dist/server/pipeline-phases.d.ts.map +1 -0
  736. package/dist/server/pipeline.d.ts +164 -23
  737. package/dist/server/pipeline.d.ts.map +1 -1
  738. package/dist/server/port-resolution.d.ts +22 -0
  739. package/dist/server/port-resolution.d.ts.map +1 -0
  740. package/dist/server/prebuilt/cache-key.d.ts +89 -0
  741. package/dist/server/prebuilt/cache-key.d.ts.map +1 -0
  742. package/dist/server/prebuilt/capture-render.d.ts +30 -0
  743. package/dist/server/prebuilt/capture-render.d.ts.map +1 -0
  744. package/dist/server/prebuilt/capture-routes.d.ts +37 -0
  745. package/dist/server/prebuilt/capture-routes.d.ts.map +1 -0
  746. package/dist/server/prebuilt/capture-state.d.ts +101 -0
  747. package/dist/server/prebuilt/capture-state.d.ts.map +1 -0
  748. package/dist/server/prebuilt/dev-store.d.ts +103 -0
  749. package/dist/server/prebuilt/dev-store.d.ts.map +1 -0
  750. package/dist/server/prebuilt/key-discipline.d.ts +52 -0
  751. package/dist/server/prebuilt/key-discipline.d.ts.map +1 -0
  752. package/dist/server/prebuilt/lifetime.d.ts +38 -0
  753. package/dist/server/prebuilt/lifetime.d.ts.map +1 -0
  754. package/dist/server/prebuilt/manifest-tag-index.d.ts +27 -0
  755. package/dist/server/prebuilt/manifest-tag-index.d.ts.map +1 -0
  756. package/dist/server/prebuilt/overlay.d.ts +105 -0
  757. package/dist/server/prebuilt/overlay.d.ts.map +1 -0
  758. package/dist/server/prebuilt/payload-source.d.ts +87 -0
  759. package/dist/server/prebuilt/payload-source.d.ts.map +1 -0
  760. package/dist/server/prebuilt/slots.d.ts +105 -0
  761. package/dist/server/prebuilt/slots.d.ts.map +1 -0
  762. package/dist/server/prebuilt/synthetic-store.d.ts +67 -0
  763. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -0
  764. package/dist/server/prebuilt-builder.d.ts +121 -0
  765. package/dist/server/prebuilt-builder.d.ts.map +1 -0
  766. package/dist/server/prebuilt-runtime.d.ts +105 -0
  767. package/dist/server/prebuilt-runtime.d.ts.map +1 -0
  768. package/dist/server/primitives.d.ts +101 -90
  769. package/dist/server/primitives.d.ts.map +1 -1
  770. package/dist/server/publish-params.d.ts +33 -0
  771. package/dist/server/publish-params.d.ts.map +1 -0
  772. package/dist/server/react-cache-bridge.d.ts +59 -0
  773. package/dist/server/react-cache-bridge.d.ts.map +1 -0
  774. package/dist/server/react-cache-scope.d.ts +49 -0
  775. package/dist/server/react-cache-scope.d.ts.map +1 -0
  776. package/dist/server/render-timeout.d.ts +66 -0
  777. package/dist/server/render-timeout.d.ts.map +1 -0
  778. package/dist/server/render-utils.d.ts +35 -0
  779. package/dist/server/render-utils.d.ts.map +1 -0
  780. package/dist/server/request-context.d.ts +153 -103
  781. package/dist/server/request-context.d.ts.map +1 -1
  782. package/dist/server/request-dep.d.ts +15 -0
  783. package/dist/server/request-dep.d.ts.map +1 -0
  784. package/dist/server/response-cache-policy.d.ts +3 -0
  785. package/dist/server/response-cache-policy.d.ts.map +1 -0
  786. package/dist/server/route-element-builder.d.ts +57 -30
  787. package/dist/server/route-element-builder.d.ts.map +1 -1
  788. package/dist/server/route-element-helpers.d.ts +12 -0
  789. package/dist/server/route-element-helpers.d.ts.map +1 -0
  790. package/dist/server/route-handler.d.ts +1 -1
  791. package/dist/server/route-handler.d.ts.map +1 -1
  792. package/dist/server/route-matcher.d.ts +62 -38
  793. package/dist/server/route-matcher.d.ts.map +1 -1
  794. package/dist/server/route-module-loader.d.ts +37 -0
  795. package/dist/server/route-module-loader.d.ts.map +1 -0
  796. package/dist/server/rsc-cache-key-guard.d.ts +78 -0
  797. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -0
  798. package/dist/server/rsc-entry/action-dispatcher.d.ts +65 -0
  799. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -0
  800. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  801. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  802. package/dist/server/rsc-entry/api-handler.d.ts +19 -3
  803. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  804. package/dist/server/rsc-entry/deny-fallback.d.ts +55 -0
  805. package/dist/server/rsc-entry/deny-fallback.d.ts.map +1 -0
  806. package/dist/server/rsc-entry/error-renderer.d.ts +35 -21
  807. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  808. package/dist/server/rsc-entry/helpers.d.ts +14 -59
  809. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  810. package/dist/server/rsc-entry/index.d.ts +30 -6
  811. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  812. package/dist/server/rsc-entry/render-route.d.ts +55 -0
  813. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  814. package/dist/server/rsc-entry/render-signals.d.ts +65 -0
  815. package/dist/server/rsc-entry/render-signals.d.ts.map +1 -0
  816. package/dist/server/rsc-entry/revalidate-renderer.d.ts +98 -0
  817. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  818. package/dist/server/rsc-entry/rsc-payload.d.ts +38 -11
  819. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  820. package/dist/server/rsc-entry/rsc-stream.d.ts +18 -31
  821. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  822. package/dist/server/rsc-entry/ssr-bridge.d.ts +7 -2
  823. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  824. package/dist/server/rsc-entry/ssr-renderer.d.ts +52 -8
  825. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  826. package/dist/server/rsc-error-envelope.d.ts +11 -0
  827. package/dist/server/rsc-error-envelope.d.ts.map +1 -0
  828. package/dist/server/safe-load.d.ts +39 -0
  829. package/dist/server/safe-load.d.ts.map +1 -0
  830. package/dist/server/schema-introspection.d.ts +68 -0
  831. package/dist/server/schema-introspection.d.ts.map +1 -0
  832. package/dist/server/sensitive-fields.d.ts +88 -0
  833. package/dist/server/sensitive-fields.d.ts.map +1 -0
  834. package/dist/server/signal-identity.d.ts +43 -0
  835. package/dist/server/signal-identity.d.ts.map +1 -0
  836. package/dist/server/sitemap-generator.d.ts +130 -0
  837. package/dist/server/sitemap-generator.d.ts.map +1 -0
  838. package/dist/server/sitemap-handler.d.ts +22 -0
  839. package/dist/server/sitemap-handler.d.ts.map +1 -0
  840. package/dist/server/skippable-prefix.d.ts +29 -0
  841. package/dist/server/skippable-prefix.d.ts.map +1 -0
  842. package/dist/server/slot-interception.d.ts +80 -0
  843. package/dist/server/slot-interception.d.ts.map +1 -0
  844. package/dist/server/slot-resolver.d.ts +138 -7
  845. package/dist/server/slot-resolver.d.ts.map +1 -1
  846. package/dist/server/slot-subtree-contain.d.ts +54 -0
  847. package/dist/server/slot-subtree-contain.d.ts.map +1 -0
  848. package/dist/server/ssr-bridge-types.d.ts +213 -0
  849. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  850. package/dist/server/ssr-entry.d.ts +15 -51
  851. package/dist/server/ssr-entry.d.ts.map +1 -1
  852. package/dist/server/ssr-form-state.d.ts +30 -0
  853. package/dist/server/ssr-form-state.d.ts.map +1 -0
  854. package/dist/server/ssr-render.d.ts +59 -32
  855. package/dist/server/ssr-render.d.ts.map +1 -1
  856. package/dist/server/ssr-wrappers.d.ts +93 -0
  857. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  858. package/dist/server/state-tree-diff.d.ts +44 -9
  859. package/dist/server/state-tree-diff.d.ts.map +1 -1
  860. package/dist/server/static-generator.d.ts +112 -0
  861. package/dist/server/static-generator.d.ts.map +1 -0
  862. package/dist/server/static-not-found.d.ts +52 -0
  863. package/dist/server/static-not-found.d.ts.map +1 -0
  864. package/dist/server/status-code-resolver.d.ts +26 -15
  865. package/dist/server/status-code-resolver.d.ts.map +1 -1
  866. package/dist/server/stream-utils.d.ts +93 -0
  867. package/dist/server/stream-utils.d.ts.map +1 -0
  868. package/dist/server/tracing.d.ts +57 -26
  869. package/dist/server/tracing.d.ts.map +1 -1
  870. package/dist/server/tree-match.d.ts +59 -0
  871. package/dist/server/tree-match.d.ts.map +1 -0
  872. package/dist/server/types.d.ts +89 -8
  873. package/dist/server/types.d.ts.map +1 -1
  874. package/dist/server/utils/element-type.d.ts +50 -0
  875. package/dist/server/utils/element-type.d.ts.map +1 -0
  876. package/dist/server/utils/escape-html.d.ts +14 -0
  877. package/dist/server/utils/escape-html.d.ts.map +1 -0
  878. package/dist/server/version-skew.d.ts +61 -0
  879. package/dist/server/version-skew.d.ts.map +1 -0
  880. package/dist/server/workers-cache-bridge.d.ts +26 -0
  881. package/dist/server/workers-cache-bridge.d.ts.map +1 -0
  882. package/dist/shared/als-slots.d.ts +42 -0
  883. package/dist/shared/als-slots.d.ts.map +1 -0
  884. package/dist/shared/base-path.d.ts +56 -0
  885. package/dist/shared/base-path.d.ts.map +1 -0
  886. package/dist/shared/csrf-reject.d.ts +16 -0
  887. package/dist/shared/csrf-reject.d.ts.map +1 -0
  888. package/dist/shared/error-digest.d.ts +28 -0
  889. package/dist/shared/error-digest.d.ts.map +1 -0
  890. package/dist/shared/flight-base64.d.ts +13 -0
  891. package/dist/shared/flight-base64.d.ts.map +1 -0
  892. package/dist/shared/flight-segment.d.ts +18 -0
  893. package/dist/shared/flight-segment.d.ts.map +1 -0
  894. package/dist/shared/form-state-flight.d.ts +32 -0
  895. package/dist/shared/form-state-flight.d.ts.map +1 -0
  896. package/dist/shared/href-validation.d.ts +49 -0
  897. package/dist/shared/href-validation.d.ts.map +1 -0
  898. package/dist/shared/merge-search-params.d.ts +22 -0
  899. package/dist/shared/merge-search-params.d.ts.map +1 -0
  900. package/dist/shared/param-value.d.ts +104 -0
  901. package/dist/shared/param-value.d.ts.map +1 -0
  902. package/dist/shared/payload-root.d.ts +110 -0
  903. package/dist/shared/payload-root.d.ts.map +1 -0
  904. package/dist/shared/redirect-type.d.ts +17 -0
  905. package/dist/shared/redirect-type.d.ts.map +1 -0
  906. package/dist/shared/rsc-cache-key.d.ts +163 -0
  907. package/dist/shared/rsc-cache-key.d.ts.map +1 -0
  908. package/dist/shared/rsc-error-envelope.d.ts +16 -0
  909. package/dist/shared/rsc-error-envelope.d.ts.map +1 -0
  910. package/dist/shared/rsc-manifest.d.ts +28 -0
  911. package/dist/shared/rsc-manifest.d.ts.map +1 -0
  912. package/dist/shared/rsc-media-type.d.ts +52 -0
  913. package/dist/shared/rsc-media-type.d.ts.map +1 -0
  914. package/dist/shared/rsc-payload-path.d.ts +48 -0
  915. package/dist/shared/rsc-payload-path.d.ts.map +1 -0
  916. package/dist/shared/segment-info.d.ts +66 -0
  917. package/dist/shared/segment-info.d.ts.map +1 -0
  918. package/dist/shared/slot-params.d.ts +52 -0
  919. package/dist/shared/slot-params.d.ts.map +1 -0
  920. package/dist/shared/static-platform-files.d.ts +71 -0
  921. package/dist/shared/static-platform-files.d.ts.map +1 -0
  922. package/dist/shared/status-reason-phrase.d.ts +26 -0
  923. package/dist/shared/status-reason-phrase.d.ts.map +1 -0
  924. package/dist/shims/font-google.d.ts +1 -1
  925. package/dist/shims/font-google.d.ts.map +1 -1
  926. package/dist/shims/font-google.js +42 -0
  927. package/dist/shims/font-google.js.map +1 -0
  928. package/dist/shims/font-local.d.ts +26 -0
  929. package/dist/shims/font-local.d.ts.map +1 -0
  930. package/dist/shims/font-local.js +20 -0
  931. package/dist/shims/font-local.js.map +1 -0
  932. package/dist/shims/headers.d.ts +53 -1
  933. package/dist/shims/headers.d.ts.map +1 -1
  934. package/dist/shims/image.d.ts +120 -120
  935. package/dist/shims/image.d.ts.map +1 -1
  936. package/dist/shims/navigation-client.d.ts +25 -12
  937. package/dist/shims/navigation-client.d.ts.map +1 -1
  938. package/dist/shims/navigation-rsc.d.ts +21 -0
  939. package/dist/shims/navigation-rsc.d.ts.map +1 -0
  940. package/dist/shims/navigation.d.ts +10 -5
  941. package/dist/shims/navigation.d.ts.map +1 -1
  942. package/dist/utils/state-machine.d.ts +80 -0
  943. package/dist/utils/state-machine.d.ts.map +1 -0
  944. package/dist/utils/write-file-atomic.d.ts +17 -0
  945. package/dist/utils/write-file-atomic.d.ts.map +1 -0
  946. package/docs/api/30-api-server.mdx +239 -0
  947. package/docs/api/31-api-client.mdx +199 -0
  948. package/docs/api/32-api-cache.mdx +341 -0
  949. package/docs/api/33-api-search-params.mdx +176 -0
  950. package/docs/api/34-api-config.mdx +359 -0
  951. package/docs/api/35-api-typescript.mdx +91 -0
  952. package/docs/api/36-cli.mdx +206 -0
  953. package/docs/learn/00-introduction.mdx +109 -0
  954. package/docs/learn/01-quick-start.mdx +94 -0
  955. package/docs/learn/02-pages-and-layouts.mdx +147 -0
  956. package/docs/learn/03-fetching-data.mdx +227 -0
  957. package/docs/learn/04-access-control.mdx +115 -0
  958. package/docs/learn/05-the-flush-point.mdx +175 -0
  959. package/docs/learn/06-typed-params.mdx +275 -0
  960. package/docs/learn/07-typed-routes.mdx +108 -0
  961. package/docs/learn/08-forms-and-actions.mdx +260 -0
  962. package/docs/learn/09-streaming.mdx +140 -0
  963. package/docs/learn/10-caching.mdx +282 -0
  964. package/docs/learn/11-middleware.mdx +166 -0
  965. package/docs/learn/12-error-handling.mdx +192 -0
  966. package/docs/learn/13-deploying.mdx +289 -0
  967. package/llms.txt +55 -0
  968. package/package.json +120 -29
  969. package/src/adapters/build-output-helper.ts +353 -0
  970. package/src/adapters/canonicalize-module.ts +29 -0
  971. package/src/adapters/cloudflare-dev.ts +183 -0
  972. package/src/adapters/cloudflare-kv-cache.ts +207 -0
  973. package/src/adapters/cloudflare.ts +809 -150
  974. package/src/adapters/compress-module.ts +110 -86
  975. package/src/adapters/fs-identity.ts +155 -0
  976. package/src/adapters/nitro-immutable-assets.ts +142 -0
  977. package/src/adapters/nitro-presets.ts +124 -0
  978. package/src/adapters/nitro-preview.ts +533 -0
  979. package/src/adapters/nitro.ts +331 -445
  980. package/src/adapters/raw-imports.d.ts +5 -0
  981. package/src/adapters/shared.ts +283 -0
  982. package/src/adapters/types.ts +129 -17
  983. package/src/adapters/wrangler.d.ts +7 -0
  984. package/src/analyze/chains.ts +411 -0
  985. package/src/analyze/classify.ts +259 -0
  986. package/src/analyze/crawl-entry.ts +68 -0
  987. package/src/analyze/crawl.ts +500 -0
  988. package/src/analyze/graph-cache.ts +331 -0
  989. package/src/analyze/graph-command.ts +762 -0
  990. package/src/analyze/live-graph.ts +232 -0
  991. package/src/analyze/poison-rules.ts +165 -0
  992. package/src/analyze/poison-scan.ts +159 -0
  993. package/src/analyze/scan.ts +149 -0
  994. package/src/cache/cache-api.ts +113 -0
  995. package/src/cache/fast-hash.ts +5 -0
  996. package/src/cache/handler-store.ts +113 -0
  997. package/src/cache/index.ts +115 -22
  998. package/src/cache/invalidation-epoch.ts +105 -0
  999. package/src/cache/json-lossy-check.ts +69 -0
  1000. package/src/cache/redis-handler.ts +198 -20
  1001. package/src/cache/singleflight.ts +72 -6
  1002. package/src/cache/sizeof.ts +35 -0
  1003. package/src/cache/stable-stringify.ts +65 -2
  1004. package/src/cache/store.ts +71 -0
  1005. package/src/cache/stores/cloudflare-kv.ts +52 -0
  1006. package/src/cache/stores/memory.ts +125 -0
  1007. package/src/cache/stores/redis.ts +97 -0
  1008. package/src/cache/stores/vercel.ts +59 -0
  1009. package/src/cache/tag-aware-handler.ts +254 -0
  1010. package/src/cache/timber-cache.ts +169 -40
  1011. package/src/cdn/cloudflare-purge.ts +50 -0
  1012. package/src/cdn/fastly-purge.ts +63 -0
  1013. package/src/cdn/headers.ts +153 -0
  1014. package/src/cdn/index.ts +23 -0
  1015. package/src/cdn/purge-store.ts +62 -0
  1016. package/src/cdn/workers-cache-purge.ts +34 -0
  1017. package/src/cli-check.ts +417 -0
  1018. package/src/cli-context.ts +119 -0
  1019. package/src/cli-schema-sync.ts +401 -0
  1020. package/src/cli.ts +334 -80
  1021. package/src/client/browser-dev.ts +192 -5
  1022. package/src/client/browser-entry/action-dispatch.ts +317 -0
  1023. package/src/client/browser-entry/action-queue.ts +152 -0
  1024. package/src/client/browser-entry/form-state.ts +49 -0
  1025. package/src/client/browser-entry/hmr.ts +70 -0
  1026. package/src/client/browser-entry/hydrate.ts +152 -0
  1027. package/src/client/browser-entry/index.ts +150 -0
  1028. package/src/client/browser-entry/post-hydration.ts +99 -0
  1029. package/src/client/browser-entry/router-init.ts +391 -0
  1030. package/src/client/browser-entry/rsc-stream.ts +145 -0
  1031. package/src/client/browser-entry/scroll.ts +50 -0
  1032. package/src/client/deny-last-resort.tsx +54 -0
  1033. package/src/client/error-boundary.tsx +279 -61
  1034. package/src/client/error-reconstituter.tsx +84 -0
  1035. package/src/client/form.tsx +61 -173
  1036. package/src/client/global-context.ts +31 -0
  1037. package/src/client/history.ts +74 -11
  1038. package/src/client/index.ts +90 -53
  1039. package/src/client/internal.ts +54 -0
  1040. package/src/client/link.tsx +464 -151
  1041. package/src/client/location-search.ts +15 -0
  1042. package/src/client/navigation-api.ts +254 -0
  1043. package/src/client/navigation-commit.ts +318 -0
  1044. package/src/client/navigation-context.ts +67 -134
  1045. package/src/client/navigation-root.tsx +236 -0
  1046. package/src/client/navigation-transition.ts +401 -0
  1047. package/src/client/nuqs-adapter.tsx +21 -9
  1048. package/src/client/params-context.ts +187 -0
  1049. package/src/client/react-root.ts +105 -0
  1050. package/src/client/router-effects.ts +349 -0
  1051. package/src/client/router-lifecycle.ts +374 -0
  1052. package/src/client/router-pipeline.ts +443 -0
  1053. package/src/client/router-ref.ts +3 -3
  1054. package/src/client/router-skew.ts +30 -0
  1055. package/src/client/router-types.ts +326 -0
  1056. package/src/client/router-url.ts +32 -0
  1057. package/src/client/router.ts +491 -421
  1058. package/src/client/rsc-fetch.ts +510 -109
  1059. package/src/client/segment-cache.ts +362 -41
  1060. package/src/client/segment-context.ts +7 -4
  1061. package/src/client/segment-outlet.tsx +96 -0
  1062. package/src/client/segment-update-context.ts +23 -0
  1063. package/src/client/shallow-url.ts +22 -0
  1064. package/src/client/slot-content-cache-context.ts +43 -0
  1065. package/src/client/slot-context.ts +50 -0
  1066. package/src/client/slot-outlet.tsx +22 -0
  1067. package/src/client/slot-provider.tsx +32 -0
  1068. package/src/client/ssr-data.ts +27 -67
  1069. package/src/client/stale-client.ts +191 -0
  1070. package/src/client/state.ts +31 -24
  1071. package/src/client/status-page-marker.tsx +32 -0
  1072. package/src/client/top-loader.tsx +13 -10
  1073. package/src/client/unload-guard.ts +35 -3
  1074. package/src/client/use-cookie.ts +70 -18
  1075. package/src/client/use-field-state.ts +144 -0
  1076. package/src/client/use-link-status.ts +7 -7
  1077. package/src/client/use-pathname.ts +22 -31
  1078. package/src/client/use-pending-navigation.ts +40 -0
  1079. package/src/client/use-query-states.ts +206 -36
  1080. package/src/client/use-router.ts +31 -9
  1081. package/src/client/use-search-params.ts +38 -49
  1082. package/src/client/use-segment-params.ts +69 -0
  1083. package/src/client/use-selected-layout-segment.ts +2 -2
  1084. package/src/codec.ts +149 -0
  1085. package/src/config-types.ts +321 -0
  1086. package/src/config-validation.ts +464 -0
  1087. package/src/cookies/define-cookie.ts +222 -53
  1088. package/src/cookies/index.ts +13 -2
  1089. package/src/cookies/json-cookie.ts +105 -0
  1090. package/src/cookies/validation.ts +192 -0
  1091. package/src/dev-tools/404-page.ts +286 -0
  1092. package/src/dev-tools/browser-logs.ts +55 -0
  1093. package/src/dev-tools/dev-page-shell.ts +278 -0
  1094. package/src/dev-tools/error-page.ts +331 -0
  1095. package/src/dev-tools/holding-server.ts +185 -0
  1096. package/src/dev-tools/hydration-overlay.ts +158 -0
  1097. package/src/dev-tools/index.ts +79 -0
  1098. package/src/dev-tools/instrumentation.ts +261 -0
  1099. package/src/{server/dev-logger.ts → dev-tools/logger.ts} +33 -51
  1100. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +147 -25
  1101. package/src/{plugins/dev-error-overlay.ts → dev-tools/overlay.ts} +25 -80
  1102. package/src/dev-tools/stack-classifier.ts +75 -0
  1103. package/src/dev-tools/terminal.ts +182 -0
  1104. package/src/fonts/ast-walk.ts +235 -0
  1105. package/src/fonts/ast.ts +479 -128
  1106. package/src/fonts/bundle.ts +138 -0
  1107. package/src/fonts/css.ts +1 -1
  1108. package/src/fonts/dev-middleware.ts +85 -0
  1109. package/src/fonts/fallbacks.ts +0 -23
  1110. package/src/fonts/google.ts +101 -19
  1111. package/src/fonts/local.ts +12 -11
  1112. package/src/fonts/paths.ts +58 -0
  1113. package/src/fonts/pipeline.ts +348 -0
  1114. package/src/fonts/transform.ts +311 -0
  1115. package/src/fonts/types.ts +52 -1
  1116. package/src/fonts/virtual-modules.ts +179 -0
  1117. package/src/index.ts +492 -380
  1118. package/src/params/codec-registry.ts +34 -0
  1119. package/src/params/define-schema.ts +115 -0
  1120. package/src/params/index.ts +17 -0
  1121. package/src/params/resolve-schema.ts +84 -0
  1122. package/src/plugin-context.ts +502 -0
  1123. package/src/plugins/build-manifest.ts +189 -36
  1124. package/src/plugins/build-report.ts +299 -87
  1125. package/src/plugins/cache.ts +243 -0
  1126. package/src/plugins/callsite-ast.ts +472 -0
  1127. package/src/plugins/callsite-jsx.ts +243 -0
  1128. package/src/plugins/chunks.ts +74 -5
  1129. package/src/plugins/client-chunks.ts +185 -0
  1130. package/src/plugins/client-dep-entries.ts +124 -0
  1131. package/src/plugins/cloudflare-wasm.ts +141 -0
  1132. package/src/plugins/content.ts +31 -2
  1133. package/src/plugins/dev-discovery.ts +218 -0
  1134. package/src/plugins/dev-server.ts +376 -98
  1135. package/src/plugins/encryption-runtime.ts +31 -0
  1136. package/src/plugins/entries.ts +156 -17
  1137. package/src/plugins/fonts.ts +260 -657
  1138. package/src/plugins/graph-endpoint.ts +532 -0
  1139. package/src/plugins/mdx.ts +108 -35
  1140. package/src/plugins/orphaned-modules.ts +78 -0
  1141. package/src/plugins/post-build.ts +327 -0
  1142. package/src/plugins/prebuilt-capture.ts +213 -0
  1143. package/src/plugins/prebuilt-options-analysis.ts +175 -0
  1144. package/src/plugins/prebuilt.ts +670 -0
  1145. package/src/plugins/prerender-sugar.ts +348 -0
  1146. package/src/plugins/react-resolve.ts +149 -0
  1147. package/src/plugins/request-dep/analysis.ts +447 -0
  1148. package/src/plugins/request-dep/index.ts +376 -0
  1149. package/src/plugins/request-dep/origin.ts +310 -0
  1150. package/src/plugins/routing.ts +296 -278
  1151. package/src/plugins/rsc-assets-manifest.ts +251 -0
  1152. package/src/plugins/server-bundle.ts +115 -15
  1153. package/src/plugins/shims.ts +257 -97
  1154. package/src/plugins/static-build.ts +681 -71
  1155. package/src/react-canary.d.ts +2 -0
  1156. package/src/routing/codegen-shared.ts +39 -0
  1157. package/src/routing/codegen-types.ts +62 -0
  1158. package/src/routing/codegen-write.ts +163 -0
  1159. package/src/routing/codegen.ts +349 -232
  1160. package/src/routing/collision-probe.ts +438 -0
  1161. package/src/routing/collision-spaces.ts +281 -0
  1162. package/src/routing/convention-lint.ts +651 -0
  1163. package/src/routing/export-detect.ts +536 -0
  1164. package/src/routing/file-cache.ts +23 -0
  1165. package/src/routing/index.ts +16 -7
  1166. package/src/routing/interception-overlap.ts +141 -0
  1167. package/src/routing/interception.ts +1044 -67
  1168. package/src/routing/link-codegen.ts +280 -0
  1169. package/src/routing/manifest-codegen.ts +232 -0
  1170. package/src/routing/scanner.ts +417 -223
  1171. package/src/routing/schema-validation.ts +155 -0
  1172. package/src/routing/segment-classify.ts +280 -0
  1173. package/src/routing/segment-codegen.ts +99 -0
  1174. package/src/routing/segment-keys.ts +186 -0
  1175. package/src/routing/slot-placement.ts +97 -0
  1176. package/src/routing/types.ts +82 -26
  1177. package/src/routing/walkers.ts +98 -0
  1178. package/src/rsc-runtime/dev-reference-cache.ts +115 -0
  1179. package/src/rsc-runtime/encryption-runtime.ts +78 -0
  1180. package/src/rsc-runtime/render-flight.ts +26 -0
  1181. package/src/rsc-runtime/rsc.ts +27 -2
  1182. package/src/rsc-runtime/ssr.ts +23 -0
  1183. package/src/rsc-runtime/transforms.ts +13 -0
  1184. package/src/rsc-runtime/vendor-types.d.ts +70 -0
  1185. package/src/schema-bridge.ts +382 -0
  1186. package/src/search-params/define.ts +677 -0
  1187. package/src/search-params/index.ts +14 -20
  1188. package/src/search-params/parse-total.ts +91 -0
  1189. package/src/search-params/serialize-equal.ts +14 -0
  1190. package/src/search-params/wrappers.ts +150 -0
  1191. package/src/server/abort-scope.ts +49 -0
  1192. package/src/server/access-gate.tsx +195 -56
  1193. package/src/server/action-client.ts +175 -294
  1194. package/src/server/action-encryption.ts +144 -0
  1195. package/src/server/action-handler.ts +492 -150
  1196. package/src/server/action-schema.ts +203 -0
  1197. package/src/server/action-types.ts +145 -0
  1198. package/src/server/actions.ts +172 -85
  1199. package/src/server/als-registry.ts +245 -30
  1200. package/src/server/body-limits.ts +10 -2
  1201. package/src/server/build-manifest.ts +33 -57
  1202. package/src/server/canonicalize.ts +35 -3
  1203. package/src/server/chain-url-parts.ts +163 -0
  1204. package/src/server/children-interception.ts +116 -0
  1205. package/src/server/client-error-message.ts +18 -0
  1206. package/src/server/coalesce-tick.ts +75 -0
  1207. package/src/server/compress.ts +91 -19
  1208. package/src/server/cookie-context.ts +454 -0
  1209. package/src/server/cookie-parsing.ts +163 -0
  1210. package/src/server/csp-nonce.ts +58 -0
  1211. package/src/server/csrf.ts +228 -35
  1212. package/src/server/debug.ts +0 -1
  1213. package/src/server/default-logger.ts +100 -0
  1214. package/src/server/default-status-page.ts +88 -0
  1215. package/src/server/deny-boundary.ts +527 -0
  1216. package/src/server/deny-renderer.ts +210 -181
  1217. package/src/server/early-hints-sender.ts +4 -3
  1218. package/src/server/early-hints.ts +39 -29
  1219. package/src/server/error-boundary-wrapper.ts +160 -44
  1220. package/src/server/error-response-headers.ts +18 -0
  1221. package/src/server/fallback-error.ts +88 -104
  1222. package/src/server/flight-injection-state.ts +113 -0
  1223. package/src/server/flight-injector-core.ts +328 -0
  1224. package/src/server/flight-scripts.ts +92 -0
  1225. package/src/server/flight-source-node.ts +431 -0
  1226. package/src/server/flight-source.ts +288 -0
  1227. package/src/server/form-data.ts +191 -20
  1228. package/src/server/form-state-flight.ts +67 -0
  1229. package/src/server/head-response.ts +50 -0
  1230. package/src/server/html-injector-core.ts +320 -0
  1231. package/src/server/html-injectors.ts +241 -285
  1232. package/src/server/index.ts +37 -195
  1233. package/src/server/instrumentation.ts +42 -11
  1234. package/src/server/internal.ts +163 -0
  1235. package/src/server/json-status-response.ts +105 -0
  1236. package/src/server/logger.ts +131 -38
  1237. package/src/server/metadata-collector.ts +175 -0
  1238. package/src/server/metadata-platform.ts +2 -2
  1239. package/src/server/metadata-render.ts +30 -8
  1240. package/src/server/metadata-route-links.ts +200 -0
  1241. package/src/server/metadata-routes.ts +114 -24
  1242. package/src/server/metadata-social.ts +2 -2
  1243. package/src/server/metadata.ts +23 -2
  1244. package/src/server/middleware-runner.ts +32 -5
  1245. package/src/server/node-body-response.ts +236 -0
  1246. package/src/server/node-response.ts +93 -0
  1247. package/src/server/node-stream-transforms.ts +340 -0
  1248. package/src/server/node-streams-platform.ts +23 -0
  1249. package/src/server/nuqs-ssr-provider.tsx +8 -7
  1250. package/src/server/param-coercion.ts +201 -0
  1251. package/src/server/pipeline-helpers.ts +550 -0
  1252. package/src/server/pipeline-interception.ts +241 -32
  1253. package/src/server/pipeline-metadata.ts +25 -1
  1254. package/src/server/pipeline-outcome.ts +290 -0
  1255. package/src/server/pipeline-phases.ts +503 -0
  1256. package/src/server/pipeline.ts +435 -427
  1257. package/src/server/port-resolution.ts +43 -0
  1258. package/src/server/prebuilt/cache-key.ts +340 -0
  1259. package/src/server/prebuilt/capture-render.ts +122 -0
  1260. package/src/server/prebuilt/capture-routes.ts +104 -0
  1261. package/src/server/prebuilt/capture-state.ts +196 -0
  1262. package/src/server/prebuilt/dev-store.ts +173 -0
  1263. package/src/server/prebuilt/key-discipline.ts +122 -0
  1264. package/src/server/prebuilt/lifetime.ts +151 -0
  1265. package/src/server/prebuilt/manifest-tag-index.ts +46 -0
  1266. package/src/server/prebuilt/overlay.ts +262 -0
  1267. package/src/server/prebuilt/payload-source.ts +221 -0
  1268. package/src/server/prebuilt/slots.ts +201 -0
  1269. package/src/server/prebuilt/synthetic-store.ts +125 -0
  1270. package/src/server/prebuilt-builder.ts +515 -0
  1271. package/src/server/prebuilt-runtime.ts +808 -0
  1272. package/src/server/primitives.ts +153 -171
  1273. package/src/server/publish-params.ts +42 -0
  1274. package/src/server/react-cache-bridge.ts +124 -0
  1275. package/src/server/react-cache-scope.ts +104 -0
  1276. package/src/server/render-timeout.ts +123 -0
  1277. package/src/server/render-utils.ts +45 -0
  1278. package/src/server/request-context.ts +298 -324
  1279. package/src/server/request-dep.ts +37 -0
  1280. package/src/server/response-cache-policy.ts +45 -0
  1281. package/src/server/route-element-builder.ts +526 -355
  1282. package/src/server/route-element-helpers.ts +37 -0
  1283. package/src/server/route-handler.ts +67 -27
  1284. package/src/server/route-matcher.ts +238 -267
  1285. package/src/server/route-module-loader.ts +161 -0
  1286. package/src/server/rsc-cache-key-guard.ts +122 -0
  1287. package/src/server/rsc-entry/action-dispatcher.ts +146 -0
  1288. package/src/server/rsc-entry/action-middleware-runner.ts +130 -0
  1289. package/src/server/rsc-entry/api-handler.ts +49 -81
  1290. package/src/server/rsc-entry/deny-fallback.ts +151 -0
  1291. package/src/server/rsc-entry/error-renderer.ts +306 -113
  1292. package/src/server/rsc-entry/helpers.ts +90 -115
  1293. package/src/server/rsc-entry/index.ts +405 -349
  1294. package/src/server/rsc-entry/render-route.ts +248 -0
  1295. package/src/server/rsc-entry/render-signals.ts +108 -0
  1296. package/src/server/rsc-entry/revalidate-renderer.ts +349 -0
  1297. package/src/server/rsc-entry/rsc-payload.ts +212 -113
  1298. package/src/server/rsc-entry/rsc-stream.ts +137 -135
  1299. package/src/server/rsc-entry/ssr-bridge.ts +43 -8
  1300. package/src/server/rsc-entry/ssr-renderer.ts +311 -140
  1301. package/src/server/rsc-error-envelope.ts +18 -0
  1302. package/src/server/rsc-prop-warnings.ts +1 -1
  1303. package/src/server/safe-load.ts +53 -0
  1304. package/src/server/schema-introspection.ts +393 -0
  1305. package/src/server/sensitive-fields.ts +287 -0
  1306. package/src/server/server-only-guard-noop.js +3 -0
  1307. package/src/server/server-timing.ts +1 -1
  1308. package/src/server/signal-identity.ts +112 -0
  1309. package/src/server/sitemap-generator.ts +337 -0
  1310. package/src/server/sitemap-handler.ts +150 -0
  1311. package/src/server/skippable-prefix.ts +172 -0
  1312. package/src/server/slot-interception.ts +168 -0
  1313. package/src/server/slot-resolver.ts +707 -300
  1314. package/src/server/slot-subtree-contain.ts +273 -0
  1315. package/src/server/ssr-bridge-types.ts +217 -0
  1316. package/src/server/ssr-entry.ts +248 -109
  1317. package/src/server/ssr-form-state.ts +58 -0
  1318. package/src/server/ssr-render.ts +332 -101
  1319. package/src/server/ssr-wrappers.tsx +162 -0
  1320. package/src/server/state-tree-diff.ts +85 -30
  1321. package/src/server/static-generator.ts +680 -0
  1322. package/src/server/static-not-found.ts +134 -0
  1323. package/src/server/status-code-resolver.ts +107 -148
  1324. package/src/server/stream-utils.ts +398 -0
  1325. package/src/server/tracing.ts +163 -68
  1326. package/src/server/tree-match.ts +494 -0
  1327. package/src/server/types.ts +96 -11
  1328. package/src/server/utils/element-type.ts +88 -0
  1329. package/src/server/utils/escape-html.ts +20 -0
  1330. package/src/server/version-skew.ts +104 -0
  1331. package/src/server/waituntil-bridge.ts +1 -1
  1332. package/src/server/workers-cache-bridge.ts +33 -0
  1333. package/src/shared/als-slots.ts +74 -0
  1334. package/src/shared/base-path.ts +80 -0
  1335. package/src/shared/csrf-reject.ts +15 -0
  1336. package/src/shared/error-digest.ts +46 -0
  1337. package/src/shared/flight-base64.ts +23 -0
  1338. package/src/shared/flight-segment.ts +35 -0
  1339. package/src/shared/form-state-flight.ts +59 -0
  1340. package/src/shared/href-validation.ts +159 -0
  1341. package/src/shared/merge-search-params.ts +55 -0
  1342. package/src/shared/param-value.ts +281 -0
  1343. package/src/shared/payload-root.ts +153 -0
  1344. package/src/shared/redirect-type.ts +17 -0
  1345. package/src/shared/rsc-cache-key.ts +269 -0
  1346. package/src/shared/rsc-error-envelope.ts +16 -0
  1347. package/src/shared/rsc-manifest.ts +29 -0
  1348. package/src/shared/rsc-media-type.ts +59 -0
  1349. package/src/shared/rsc-payload-path.ts +52 -0
  1350. package/src/shared/segment-info.ts +67 -0
  1351. package/src/shared/slot-params.ts +109 -0
  1352. package/src/shared/static-platform-files.ts +75 -0
  1353. package/src/shared/status-reason-phrase.ts +61 -0
  1354. package/src/shims/font-google.ts +1 -1
  1355. package/src/shims/font-local.ts +34 -0
  1356. package/src/shims/headers.ts +122 -1
  1357. package/src/shims/navigation-client.ts +36 -32
  1358. package/src/shims/navigation-rsc.ts +47 -0
  1359. package/src/shims/navigation.ts +10 -7
  1360. package/src/utils/state-machine.ts +111 -0
  1361. package/src/utils/write-file-atomic.ts +32 -0
  1362. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  1363. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  1364. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  1365. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  1366. package/dist/_chunks/format-RyoGQL74.js +0 -164
  1367. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  1368. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  1369. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  1370. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  1371. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  1372. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  1373. package/dist/_chunks/ssr-data-MjmprTmO.js +0 -88
  1374. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  1375. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  1376. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  1377. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  1378. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  1379. package/dist/_chunks/use-query-states-D5KaffOK.js +0 -109
  1380. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  1381. package/dist/adapters/cloudflare.js.map +0 -1
  1382. package/dist/cache/index.js.map +0 -1
  1383. package/dist/cache/register-cached-function.d.ts +0 -17
  1384. package/dist/cache/register-cached-function.d.ts.map +0 -1
  1385. package/dist/client/browser-entry.d.ts +0 -21
  1386. package/dist/client/browser-entry.d.ts.map +0 -1
  1387. package/dist/client/error-boundary.js.map +0 -1
  1388. package/dist/client/head.d.ts +0 -16
  1389. package/dist/client/head.d.ts.map +0 -1
  1390. package/dist/client/link-status-provider.d.ts +0 -11
  1391. package/dist/client/link-status-provider.d.ts.map +0 -1
  1392. package/dist/client/segment-merger.d.ts +0 -119
  1393. package/dist/client/segment-merger.d.ts.map +0 -1
  1394. package/dist/client/stale-reload.d.ts +0 -44
  1395. package/dist/client/stale-reload.d.ts.map +0 -1
  1396. package/dist/client/transition-root.d.ts +0 -74
  1397. package/dist/client/transition-root.d.ts.map +0 -1
  1398. package/dist/client/types.d.ts +0 -14
  1399. package/dist/client/types.d.ts.map +0 -1
  1400. package/dist/client/use-navigation-pending.d.ts +0 -26
  1401. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  1402. package/dist/client/use-params.d.ts +0 -92
  1403. package/dist/client/use-params.d.ts.map +0 -1
  1404. package/dist/content/index.d.ts +0 -11
  1405. package/dist/content/index.d.ts.map +0 -1
  1406. package/dist/content/index.js +0 -2
  1407. package/dist/plugins/adapter-build.d.ts +0 -18
  1408. package/dist/plugins/adapter-build.d.ts.map +0 -1
  1409. package/dist/plugins/cache-transform.d.ts +0 -36
  1410. package/dist/plugins/cache-transform.d.ts.map +0 -1
  1411. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  1412. package/dist/plugins/dev-logs.d.ts.map +0 -1
  1413. package/dist/plugins/dynamic-transform.d.ts +0 -72
  1414. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  1415. package/dist/plugins/server-action-exports.d.ts +0 -26
  1416. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  1417. package/dist/routing/status-file-lint.d.ts +0 -33
  1418. package/dist/routing/status-file-lint.d.ts.map +0 -1
  1419. package/dist/search-params/analyze.d.ts +0 -54
  1420. package/dist/search-params/analyze.d.ts.map +0 -1
  1421. package/dist/search-params/builtin-codecs.d.ts +0 -105
  1422. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  1423. package/dist/search-params/codecs.d.ts +0 -53
  1424. package/dist/search-params/codecs.d.ts.map +0 -1
  1425. package/dist/search-params/create.d.ts +0 -106
  1426. package/dist/search-params/create.d.ts.map +0 -1
  1427. package/dist/search-params/registry.d.ts +0 -20
  1428. package/dist/search-params/registry.d.ts.map +0 -1
  1429. package/dist/server/asset-headers.d.ts +0 -42
  1430. package/dist/server/asset-headers.d.ts.map +0 -1
  1431. package/dist/server/client-module-map.d.ts +0 -47
  1432. package/dist/server/client-module-map.d.ts.map +0 -1
  1433. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  1434. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  1435. package/dist/server/dev-logger.d.ts.map +0 -1
  1436. package/dist/server/dev-span-processor.d.ts +0 -29
  1437. package/dist/server/dev-span-processor.d.ts.map +0 -1
  1438. package/dist/server/dev-warnings.d.ts +0 -129
  1439. package/dist/server/dev-warnings.d.ts.map +0 -1
  1440. package/dist/server/flush.d.ts +0 -74
  1441. package/dist/server/flush.d.ts.map +0 -1
  1442. package/dist/server/form-flash.d.ts +0 -78
  1443. package/dist/server/form-flash.d.ts.map +0 -1
  1444. package/dist/server/manifest-status-resolver.d.ts +0 -58
  1445. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  1446. package/dist/server/prerender.d.ts +0 -77
  1447. package/dist/server/prerender.d.ts.map +0 -1
  1448. package/dist/server/tree-builder.d.ts +0 -126
  1449. package/dist/server/tree-builder.d.ts.map +0 -1
  1450. package/dist/utils/directive-parser.d.ts +0 -70
  1451. package/dist/utils/directive-parser.d.ts.map +0 -1
  1452. package/src/cache/register-cached-function.ts +0 -103
  1453. package/src/client/browser-entry.ts +0 -678
  1454. package/src/client/head.ts +0 -61
  1455. package/src/client/link-status-provider.tsx +0 -30
  1456. package/src/client/segment-merger.ts +0 -339
  1457. package/src/client/stale-reload.ts +0 -87
  1458. package/src/client/transition-root.tsx +0 -166
  1459. package/src/client/types.ts +0 -21
  1460. package/src/client/use-navigation-pending.ts +0 -38
  1461. package/src/client/use-params.ts +0 -141
  1462. package/src/content/index.ts +0 -13
  1463. package/src/plugins/adapter-build.ts +0 -118
  1464. package/src/plugins/cache-transform.ts +0 -199
  1465. package/src/plugins/dynamic-transform.ts +0 -161
  1466. package/src/plugins/server-action-exports.ts +0 -220
  1467. package/src/routing/status-file-lint.ts +0 -112
  1468. package/src/search-params/analyze.ts +0 -192
  1469. package/src/search-params/builtin-codecs.ts +0 -228
  1470. package/src/search-params/codecs.ts +0 -153
  1471. package/src/search-params/create.ts +0 -321
  1472. package/src/search-params/registry.ts +0 -31
  1473. package/src/server/asset-headers.ts +0 -81
  1474. package/src/server/client-module-map.ts +0 -58
  1475. package/src/server/dev-fetch-instrumentation.ts +0 -96
  1476. package/src/server/dev-span-processor.ts +0 -78
  1477. package/src/server/dev-warnings.ts +0 -283
  1478. package/src/server/flush.ts +0 -182
  1479. package/src/server/form-flash.ts +0 -89
  1480. package/src/server/manifest-status-resolver.ts +0 -215
  1481. package/src/server/prerender.ts +0 -139
  1482. package/src/server/tree-builder.ts +0 -382
  1483. package/src/shims/server-only-noop.js +0 -6
  1484. package/src/utils/directive-parser.ts +0 -529
@@ -0,0 +1,4845 @@
1
+ import { c as drainWithDeadline, d as onAbortUntil, i as withResponseInit, n as discardResponseBody, o as concatBytes, r as nodeBodyOps, u as wrapResponseWithStreamTiming } from "../_chunks/node-response-rkQqcFGq.js";
2
+ import { r as RenderTimeoutError, t as DEFAULT_RENDER_TIMEOUT_MS } from "../_chunks/render-timeout-joFhz4KH.js";
3
+ import { n as isRscContentType, r as isRscRequest } from "../_chunks/rsc-media-type-DDc7duTD.js";
4
+ import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-B3XJNyIH.js";
5
+ import { i as canonicalize, r as canonicalRequestPath } from "../_chunks/canonicalize-BAWkWiKK.js";
6
+ import { a as discardDevEntry, c as isDevPrebuiltCacheBypassed, d as setDevSeed, f as currentInvalidationEpoch, h as wasInvalidatedSince, l as isDevPrebuiltStoreActive, n as clearDevPrebuiltStore, o as getDevSeed, p as lastInvalidationEpochFor, u as isHardReload } from "../_chunks/dev-store-BOa304m_.js";
7
+ import { n as classifyUrlSegment, r as effectiveUrlSegment } from "../_chunks/segment-classify-C539Pa2O.js";
8
+ import { t as computeSegmentTreePaths } from "../_chunks/segment-keys-D5hu1hz4.js";
9
+ import { i as requestContextAls, n as prebuiltCaptureAls, o as timingAls, t as earlyHintsSenderAls } from "../_chunks/als-registry-BZqHCtq-.js";
10
+ import { C as isRedirectSignal, F as withSpan, M as replaceTraceId, N as runWithTraceId, O as generateTraceId, P as setSpanAttribute, S as isDenySignal, _ as setLogger, a as logMiddlewareError, c as logRenderError, d as logRouteError, f as logRouteSetupError, g as logWaitUntilUnsupported, h as logWaitUntilRejected, j as getTraceId, k as getOtelTraceId, l as logRequestCompleted, m as logSwrRefetchFailed, n as logCacheMiss, o as logMiddlewareShortCircuit, p as logSlowRequest, r as logCsrfRejected, s as logProxyError, t as getLogger, u as logRequestReceived, v as swallow, w as isDebug, x as isControlFlowSignal } from "../_chunks/logger-CbLdcy-W.js";
11
+ import { i as collectRouteModulepreloads, n as collectRouteCss, r as collectRouteFonts } from "../_chunks/build-manifest-DWppEdLB.js";
12
+ import { i as isRscCacheKeyShape, n as RSC_KEY_PARAM, r as appVisibleSearch, s as rscCacheKey, t as RSC_KEY_HEADERS } from "../_chunks/rsc-cache-key-ClUiXQnK.js";
13
+ import { C as setMutableCookieContext, S as setMatchedSegmentPath, T as runOutsideReactCacheScope, b as markResponseFlushed, f as getCookie, g as getHeader, h as applyRequestHeaderOverlay, i as coerce, m as getSetCookieHeaders, o as DenySignal, s as RedirectSignal, t as executeAction, v as getSearchParams, w as setSegmentParams, x as runWithRequestContext, y as getSegmentParams } from "../_chunks/actions-BDqn4Oxj.js";
14
+ import { a as hasPrebuiltPayloadSource, c as setPrebuiltPayloadSource, h as getWaitUntil, i as storeOverlayEntry, l as applyReloadHeaders, n as lookupOverlay, o as isParamIndependent, r as overlayKey, s as lookupArtifactSeed, u as checkVersionSkew } from "../_chunks/cache-api-GE4AOe2H.js";
15
+ import { n as createSingleflight } from "../_chunks/singleflight-BeVMMKi0.js";
16
+ import { n as toBracketKey } from "../_chunks/resolve-schema-CBR6Lm4i.js";
17
+ import { t as normalizeParamValue } from "../_chunks/param-value-C8TNYchQ.js";
18
+ import { l as TIMBER_ERROR_HEADER, t as StatusPageMarker } from "../_chunks/status-page-marker-BRX9Ib-d.js";
19
+ import { createHash } from "node:crypto";
20
+ import { readFile } from "node:fs/promises";
21
+ import React, { createElement, useContext } from "react";
22
+ //#region src/server/render-utils.ts
23
+ /**
24
+ * Check if an error is an abort error (connection closed by client).
25
+ *
26
+ * When the browser aborts a request (page refresh, navigation away),
27
+ * the AbortSignal fires and React/streams throw an AbortError. This
28
+ * is not an application error — suppress it from error boundaries and logs.
29
+ */
30
+ function isAbortError(error) {
31
+ if (error instanceof DOMException && error.name === "AbortError") return true;
32
+ if (error instanceof Error && error.name === "AbortError") return true;
33
+ return false;
34
+ }
35
+ //#endregion
36
+ //#region src/server/server-timing.ts
37
+ /**
38
+ * Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
39
+ *
40
+ * Collects timing entries per request using ALS. Each pipeline phase
41
+ * (proxy, middleware, render, SSR, access, fetch) records an entry.
42
+ * Before response flush, entries are formatted into a Server-Timing header.
43
+ *
44
+ * Only active in dev mode — zero overhead in production.
45
+ *
46
+ * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
47
+ * Task: LOCAL-290
48
+ */
49
+ /**
50
+ * Run a callback with a per-request timing collector.
51
+ * Must be called at the top of the request pipeline (wraps the full request).
52
+ */
53
+ function runWithTimingCollector(fn) {
54
+ return timingAls.run({ entries: [] }, fn);
55
+ }
56
+ /**
57
+ * Run a function and automatically record its duration as a timing entry.
58
+ * Returns the function's result. No-ops the recording if outside a collector.
59
+ */
60
+ async function withTiming(name, desc, fn) {
61
+ const store = timingAls.getStore();
62
+ if (!store) return fn();
63
+ const start = performance.now();
64
+ try {
65
+ return await fn();
66
+ } finally {
67
+ const dur = Math.round(performance.now() - start);
68
+ store.entries.push({
69
+ name,
70
+ dur,
71
+ desc
72
+ });
73
+ }
74
+ }
75
+ /**
76
+ * Get the Server-Timing header value for the current request.
77
+ * Returns null if no entries exist or outside a collector.
78
+ *
79
+ * Format: `name;dur=123;desc="description", name2;dur=456`
80
+ * See RFC 6797 / Server-Timing spec for format details.
81
+ */
82
+ function getServerTimingHeader() {
83
+ const store = timingAls.getStore();
84
+ if (!store || store.entries.length === 0) return null;
85
+ const nameCounts = /* @__PURE__ */ new Map();
86
+ const parts = store.entries.map((entry) => {
87
+ const count = nameCounts.get(entry.name) ?? 0;
88
+ nameCounts.set(entry.name, count + 1);
89
+ const uniqueName = count > 0 ? `${entry.name}-${count}` : entry.name;
90
+ return {
91
+ ...entry,
92
+ name: uniqueName
93
+ };
94
+ }).map((entry) => {
95
+ let part = `${entry.name};dur=${entry.dur}`;
96
+ if (entry.desc) {
97
+ const safeDesc = entry.desc.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
98
+ part += `;desc="${safeDesc}"`;
99
+ }
100
+ return part;
101
+ });
102
+ const MAX_HEADER_SIZE = 4096;
103
+ let result = "";
104
+ for (let i = 0; i < parts.length; i++) {
105
+ const candidate = result ? `${result}, ${parts[i]}` : parts[i];
106
+ if (candidate.length > MAX_HEADER_SIZE) break;
107
+ result = candidate;
108
+ }
109
+ return result || null;
110
+ }
111
+ //#endregion
112
+ //#region src/server/instrumentation.ts
113
+ /**
114
+ * Instrumentation — loads and runs the user's instrumentation.ts file.
115
+ *
116
+ * instrumentation.ts is a file convention at the project root that exports:
117
+ * - register() — called once at server startup, before the first request
118
+ * - onRequestError() — called for every unhandled server error
119
+ * - logger — any object with info/warn/error/debug methods
120
+ *
121
+ * See design/17-logging.md §"instrumentation.ts — The Entry Point"
122
+ */
123
+ /**
124
+ * The loader the current hooks came from. One app passes one loader
125
+ * (`virtual:timber-instrumentation`), so a second call with it is a no-op.
126
+ * In dev a new loader means instrumentation.ts changed: the RSC entry is an
127
+ * HMR boundary (design/21 §HMR Wiring), so editing instrumentation.ts
128
+ * re-executes the virtual loader module and the entry, while this module
129
+ * keeps its state. The new module then replaces the old one's hooks.
130
+ */
131
+ var _loadedFrom = null;
132
+ /** The framework logger before any instrumentation module replaced it. */
133
+ var _loggerBeforeLoad = null;
134
+ var _onRequestError = null;
135
+ /**
136
+ * Load and initialize the user's instrumentation.ts module.
137
+ *
138
+ * - Awaits register() before returning (server blocks on this).
139
+ * - Picks up the logger export and wires it into the framework logger.
140
+ * - Stores onRequestError for later invocation.
141
+ *
142
+ * @param loader - Function that dynamically imports the user's instrumentation module.
143
+ * Returns null if no instrumentation.ts exists.
144
+ */
145
+ async function loadInstrumentation(loader) {
146
+ if (_loadedFrom === loader) return;
147
+ if (_loadedFrom === null) _loggerBeforeLoad = getLogger();
148
+ else {
149
+ _onRequestError = null;
150
+ setLogger(_loggerBeforeLoad);
151
+ }
152
+ _loadedFrom = loader;
153
+ let mod;
154
+ try {
155
+ mod = await loader();
156
+ } catch (error) {
157
+ console.error("[timber] Failed to load instrumentation.ts:", error);
158
+ return;
159
+ }
160
+ if (!mod) return;
161
+ if (mod.logger && typeof mod.logger.info === "function") setLogger(mod.logger);
162
+ if (typeof mod.onRequestError === "function") _onRequestError = mod.onRequestError;
163
+ if (typeof mod.register === "function") try {
164
+ await mod.register();
165
+ } catch (error) {
166
+ console.error("[timber] instrumentation.ts register() threw:", error);
167
+ _onRequestError = null;
168
+ if (_loggerBeforeLoad) setLogger(_loggerBeforeLoad);
169
+ _loadedFrom = null;
170
+ throw error;
171
+ }
172
+ }
173
+ /**
174
+ * Call the user's onRequestError hook. Catches and logs any errors thrown
175
+ * by the hook itself — it must not affect the response.
176
+ */
177
+ async function callOnRequestError(error, request, context) {
178
+ if (!_onRequestError) return;
179
+ try {
180
+ await _onRequestError(error, request, context);
181
+ } catch (hookError) {
182
+ console.error("[timber] onRequestError hook threw:", hookError);
183
+ }
184
+ }
185
+ /**
186
+ * Check if onRequestError is registered.
187
+ */
188
+ function hasOnRequestError() {
189
+ return _onRequestError !== null;
190
+ }
191
+ //#endregion
192
+ //#region src/server/safe-load.ts
193
+ /**
194
+ * Custom error class for module load failures.
195
+ *
196
+ * Preserves the original error as `cause` while providing a
197
+ * human-readable message with the file path.
198
+ */
199
+ var ModuleLoadError = class extends Error {
200
+ /** The file path that failed to load. */
201
+ filePath;
202
+ constructor(filePath, cause) {
203
+ const originalMessage = cause instanceof Error ? cause.message : String(cause);
204
+ super(`[timber] Failed to load module ${filePath}\n ${originalMessage}`, { cause });
205
+ this.name = "ModuleLoadError";
206
+ this.filePath = filePath;
207
+ }
208
+ };
209
+ /**
210
+ * Load a route manifest module with enriched error context.
211
+ *
212
+ * On success: returns the module object (same as `loader.load()`).
213
+ * On failure: throws `ModuleLoadError` with file path and original cause.
214
+ *
215
+ * Error rendering paths that need fallthrough use `loadFallbackModule()`.
216
+ */
217
+ async function loadModule(loader) {
218
+ try {
219
+ return await loader.load();
220
+ } catch (error) {
221
+ throw new ModuleLoadError(loader.filePath, error);
222
+ }
223
+ }
224
+ //#endregion
225
+ //#region src/server/route-matcher.ts
226
+ /**
227
+ * Whether a matched chain renders as an API route: its leaf has a
228
+ * `route.ts` and no `page.tsx`. The same test `renderRoute` dispatches on,
229
+ * so every answer about a route's format — early hints, deny format, error
230
+ * format, error reporting — agrees with what actually ran.
231
+ */
232
+ function isApiRouteChain(segments) {
233
+ const leaf = segments[segments.length - 1];
234
+ return !!leaf?.route && !leaf.page;
235
+ }
236
+ /**
237
+ * Whether a matched chain is a route.ts handler that opted out of the CSRF
238
+ * check with `export const csrf = false`. Keyed on the same leaf
239
+ * `isApiRouteChain` dispatches on, so the exemption can only ever apply to
240
+ * the route.ts that will actually run — never to a page, and so never to a
241
+ * server action. See design/08-forms-and-actions.md §"Per-route exemption".
242
+ */
243
+ function isCsrfExemptRoute(segments) {
244
+ return isApiRouteChain(segments) && segments[segments.length - 1]?.csrfExempt === true;
245
+ }
246
+ var SERVE_PATH_TO_CONVENTION = /* @__PURE__ */ new Map();
247
+ for (const [baseName, convention] of Object.entries(METADATA_ROUTE_CONVENTIONS)) if (convention.serveExtension) for (const ext of [...convention.staticExtensions, convention.serveExtension]) SERVE_PATH_TO_CONVENTION.set(`${convention.servePath}.${ext}`, baseName);
248
+ else SERVE_PATH_TO_CONVENTION.set(convention.servePath, baseName);
249
+ //#endregion
250
+ //#region src/shared/csrf-reject.ts
251
+ /**
252
+ * Marker header on CSRF rejections.
253
+ *
254
+ * A CSRF rejection is a 403, the same status as an access-control denial.
255
+ * The server stamps this header on every CSRF 403 so callers — the browser
256
+ * action runtime, a same-origin `fetch` in user code, a curl session — can
257
+ * tell the two apart without parsing the body. A cross-origin `fetch` cannot
258
+ * read it: the rejection returns before proxy.ts, so no CORS headers are set
259
+ * and the browser reports a network error instead. Shared so the server writer and the client
260
+ * reader cannot drift.
261
+ *
262
+ * See design/08-forms-and-actions.md §"CSRF Protection" (TIM-1459).
263
+ */
264
+ var CSRF_REJECT_HEADER = "X-Timber-Reject";
265
+ var CSRF_REJECT_VALUE = "csrf";
266
+ //#endregion
267
+ //#region src/server/csrf.ts
268
+ /**
269
+ * CSRF protection — Fetch Metadata first, Origin as the fallback.
270
+ *
271
+ * CSRF needs a victim's browser to attach cookies, and browsers mark the
272
+ * requests they send: `Sec-Fetch-Site` on HTTPS (and localhost) pages in
273
+ * every current browser, `Origin` on cross-site POSTs everywhere else. So
274
+ * the check trusts those two headers in that order, and lets a request
275
+ * carrying neither through — a webhook, curl, or a server-to-server
276
+ * `fetch`. The residual risk is browsers old enough to send neither on a
277
+ * form POST (Firefox < 70, IE11); SameSite cookies are the defense there.
278
+ * See design/08-forms-and-actions.md §"CSRF Protection".
279
+ *
280
+ * Prior art: Go's `net/http.CrossOriginProtection` (Go 1.25) and the OWASP
281
+ * CSRF cheat sheet (Fetch Metadata as a primary defense).
282
+ *
283
+ * The per-route exemption (`export const csrf = false` in route.ts) is not
284
+ * decided here: the caller owns route matching and applies it to a
285
+ * rejection. Disable globally with csrf: false (not recommended).
286
+ *
287
+ * See design/08-forms-and-actions.md §"CSRF Protection"
288
+ * See design/13-security.md §"Security Testing Checklist" #6
289
+ */
290
+ /** HTTP methods that are considered safe (no mutation). */
291
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
292
+ "GET",
293
+ "HEAD",
294
+ "OPTIONS"
295
+ ]);
296
+ /**
297
+ * `Sec-Fetch-Site` values that mean the browser itself vouches for the
298
+ * request: `same-origin`, or `none` (user-initiated — typed URL, bookmark).
299
+ * Every other value, including ones no browser sends, is not same-origin.
300
+ * The header is forbidden to page scripts, so a page cannot forge it.
301
+ */
302
+ var TRUSTED_FETCH_SITES = /* @__PURE__ */ new Set(["same-origin", "none"]);
303
+ /**
304
+ * Derive the request's scheme from trusted sources.
305
+ *
306
+ * Priority:
307
+ * 1. X-Forwarded-Proto (set by reverse proxies / load balancers)
308
+ * 2. Request URL protocol
309
+ *
310
+ * Falls back to 'https' (fail closed) if neither is available.
311
+ */
312
+ function deriveRequestScheme(req) {
313
+ const forwarded = req.headers.get("X-Forwarded-Proto");
314
+ if (forwarded) {
315
+ const proto = forwarded.split(",")[0].trim().toLowerCase();
316
+ if (proto === "http" || proto === "https") return proto;
317
+ }
318
+ try {
319
+ return new URL(req.url).protocol.replace(":", "");
320
+ } catch {
321
+ return "https";
322
+ }
323
+ }
324
+ /**
325
+ * Decide whether an unsafe-method request may proceed.
326
+ *
327
+ * In order:
328
+ * 1. `Sec-Fetch-Site` is `same-origin` or `none` → allow.
329
+ * 2. `Sec-Fetch-Site` has any other value → allow only if `Origin` is in
330
+ * `allowedOrigins`.
331
+ * 3. No `Sec-Fetch-Site`, `Origin` present (a plain-HTTP page, or an
332
+ * older browser) → `Origin` must be in `allowedOrigins` or equal the
333
+ * origin derived from the scheme and `Host`.
334
+ * 4. Neither header → allow: not a browser, so no ambient cookies to abuse.
335
+ *
336
+ * Safe methods (GET, HEAD, OPTIONS) and `csrf: false` always pass.
337
+ */
338
+ function validateCsrf(req, config) {
339
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
340
+ if (config.csrf === false) return { ok: true };
341
+ const fetchSite = req.headers.get("Sec-Fetch-Site");
342
+ const origin = req.headers.get("Origin");
343
+ const rejection = (reason, expected) => ({
344
+ ok: false,
345
+ status: 403,
346
+ reason,
347
+ origin,
348
+ fetchSite,
349
+ expected
350
+ });
351
+ if (fetchSite !== null) {
352
+ if (TRUSTED_FETCH_SITES.has(fetchSite)) return { ok: true };
353
+ if (origin !== null && config.allowedOrigins?.includes(origin)) return { ok: true };
354
+ return rejection("cross-origin", config.allowedOrigins ?? []);
355
+ }
356
+ if (origin === null) return { ok: true };
357
+ const allowed = config.allowedOrigins ?? [];
358
+ if (allowed.includes(origin)) return { ok: true };
359
+ const host = req.headers.get("Host");
360
+ if (!host) return rejection("missing-host", allowed);
361
+ let originOrigin;
362
+ try {
363
+ originOrigin = new URL(origin).origin;
364
+ } catch {
365
+ return rejection("invalid-origin", allowed);
366
+ }
367
+ let expectedOrigin;
368
+ try {
369
+ expectedOrigin = new URL(`${deriveRequestScheme(req)}://${host}`).origin;
370
+ } catch {
371
+ return rejection("invalid-host", allowed);
372
+ }
373
+ return originOrigin === expectedOrigin ? { ok: true } : rejection("origin-mismatch", [expectedOrigin, ...allowed]);
374
+ }
375
+ /**
376
+ * Longest request-derived value echoed into the server log. Origin, Host,
377
+ * Sec-Fetch-Site, and the path are attacker-controlled; a request can carry
378
+ * kilobytes in each, and every rejection writes a log line. Real values are
379
+ * far shorter.
380
+ */
381
+ var MAX_LOGGED_VALUE = 200;
382
+ function clip(value) {
383
+ return value.length > MAX_LOGGED_VALUE ? `${value.slice(0, MAX_LOGGED_VALUE)}…` : value;
384
+ }
385
+ /**
386
+ * Clip and quote a request-derived value for the log. JSON quoting escapes
387
+ * quotes and control characters, so a crafted header cannot close the quote
388
+ * and forge `key=value` fields or a second line.
389
+ */
390
+ function quote(value) {
391
+ return JSON.stringify(clip(value));
392
+ }
393
+ var PROXY_HINT = "If the app runs behind a proxy that rewrites Host or terminates TLS, forward the original Host and X-Forwarded-Proto, or list the public origin in allowedOrigins in timber.config.ts.";
394
+ var EXEMPTION_HINT = "If this route.ts must accept cross-site browser requests (OIDC form_post, SAML, 3-D Secure returns), add `export const csrf = false` to it.";
395
+ /**
396
+ * Browsers send `Origin: null` from opaque contexts: sandboxed iframes, a POST
397
+ * redirected across origins, file: pages. Every such context shares the one
398
+ * value — an attacker's `<iframe sandbox>` included — so config validation
399
+ * refuses it in `allowedOrigins` and the hint points at the exemption instead.
400
+ */
401
+ var OPAQUE_ORIGIN_DETAIL = `origin "null" is an opaque origin (sandboxed iframe, a POST redirected across origins, or a file: page). allowedOrigins cannot admit it: every opaque context sends "null", including an attacker's sandboxed iframe. ${EXEMPTION_HINT}`;
402
+ /** One sentence per rejection path: what was observed, and what to change. */
403
+ function describeRejection(r, host) {
404
+ const opaque = r.origin === "null";
405
+ const origin = quote(r.origin ?? "");
406
+ const expected = r.expected.map(quote).join(", ");
407
+ switch (r.reason) {
408
+ case "cross-origin": {
409
+ if (opaque) return OPAQUE_ORIGIN_DETAIL;
410
+ const from = r.origin === null ? "with no Origin header" : `from origin ${origin}`;
411
+ const allowed = r.expected.length > 0 ? ` and is not in allowedOrigins [${expected}]` : "";
412
+ return `Sec-Fetch-Site ${quote(r.fetchSite ?? "")} request ${from}: the browser reports it is not same-origin${allowed}. If this origin is legitimate, add it to allowedOrigins in timber.config.ts. ${EXEMPTION_HINT}`;
413
+ }
414
+ case "missing-host": return `origin ${origin} could not be checked: request has no Host header. ${PROXY_HINT}`;
415
+ case "invalid-host": return `origin ${origin} could not be checked: Host header ${quote(host ?? "")} is not a valid host. ${PROXY_HINT}`;
416
+ case "invalid-origin":
417
+ if (opaque) return OPAQUE_ORIGIN_DETAIL;
418
+ return `Origin header ${origin} is not a valid origin.`;
419
+ case "origin-mismatch": {
420
+ const [own, ...listed] = r.expected.map(quote);
421
+ return `origin ${origin} does not match the request origin ${own}${listed.length > 0 ? ` or allowedOrigins [${listed.join(", ")}]` : ""}. ${PROXY_HINT}`;
422
+ }
423
+ }
424
+ }
425
+ /**
426
+ * Turn a failed check into the response the client sees, and log why.
427
+ *
428
+ * The response is a 403 marked as a CSRF rejection (header + plain-text
429
+ * body) so it cannot be mistaken for an access-control 403. It never
430
+ * carries the observed or expected origins — `allowedOrigins` is server
431
+ * configuration, and a Host-derived origin can be an internal hostname
432
+ * behind a proxy. The server log gets the full diagnosis.
433
+ */
434
+ function csrfRejectionResponse(req, rejection) {
435
+ logCsrfRejected(describeRejection(rejection, req.headers.get("Host")), {
436
+ method: req.method,
437
+ path: clip(new URL(req.url).pathname),
438
+ reason: rejection.reason
439
+ });
440
+ return new Response("Forbidden: CSRF origin check failed\n", {
441
+ status: rejection.status,
442
+ headers: {
443
+ "Content-Type": "text/plain; charset=utf-8",
444
+ [CSRF_REJECT_HEADER]: CSRF_REJECT_VALUE
445
+ }
446
+ });
447
+ }
448
+ //#endregion
449
+ //#region src/server/pipeline-helpers.ts
450
+ /**
451
+ * The pipeline-boundary CSRF gate: the 403 to answer with, or null to go on.
452
+ *
453
+ * Runs on every request after canonicalization and before proxy.ts, so it
454
+ * covers route.ts handlers and server actions alike, and no user code has
455
+ * run when it decides. The per-route exemption is looked up only for a
456
+ * request the check would reject — the common accepted request never pays
457
+ * for a match. The lookup uses the pipeline's own matcher on the canonical
458
+ * path, the same match `handleRequest` dispatches on, and reads a flag the
459
+ * scanner took from route.ts source, so deciding it loads no module.
460
+ *
461
+ * A matcher that throws leaves the request unexempted: fail closed.
462
+ *
463
+ * See design/08-forms-and-actions.md §"CSRF Protection".
464
+ */
465
+ function csrfGate(req, canonicalPath, csrf, matchRoute) {
466
+ const result = validateCsrf(req, csrf);
467
+ if (result.ok) return null;
468
+ let exempt = false;
469
+ try {
470
+ const match = matchRoute(canonicalPath);
471
+ exempt = match !== null && isCsrfExemptRoute(match.segments);
472
+ } catch (err) {
473
+ swallow(err, "csrf gate: route match for exemption lookup threw");
474
+ }
475
+ return exempt ? null : csrfRejectionResponse(req, result);
476
+ }
477
+ /**
478
+ * The redirect for a safe request whose URL is not canonical, or null to
479
+ * serve it.
480
+ *
481
+ * A GET for `/admin/` used to render with a 200 at that URL. The server
482
+ * rendered with the canonical `/admin` while the browser hydrated with the
483
+ * raw `/admin/`, so anything branching on `usePathname()` hydrated
484
+ * mismatched (TIM-1571). Redirecting makes the address bar — the client's
485
+ * copy of the URL — the canonical one, and leaves one URL per page for
486
+ * caches and crawlers.
487
+ *
488
+ * Only GET and HEAD are redirected. Every other method — an action's POST,
489
+ * a CORS preflight — is served at the canonical path, as before: a
490
+ * redirected POST is re-sent by the browser, which an action must not
491
+ * depend on.
492
+ *
493
+ * Runs inside proxy.ts's `next()`, not before it, so proxy.ts still runs
494
+ * on every request and its headers land on the redirect. A cross-origin
495
+ * `GET /api/items/` needs proxy.ts's CORS headers on the 308 itself:
496
+ * browsers apply the CORS check to a redirect response.
497
+ *
498
+ * A document request gets a relative 308 (never built from `Host`). A page
499
+ * navigation gets the router's soft redirect, decided exactly as for a
500
+ * `redirect()` outcome: an RSC request that does not match a route.ts
501
+ * handler (`buildRedirectResponse`). The framework's `_rsc` cache key is
502
+ * dropped from the soft target; the router appends a fresh one when it
503
+ * fetches the canonical URL.
504
+ *
505
+ * See design/07-routing.md §"Non-Canonical URLs Redirect".
506
+ */
507
+ function canonicalRedirect(req, canonicalPath, stripTrailingSlash, matchRoute) {
508
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
509
+ const url = new URL(req.url);
510
+ const target = canonicalRequestPath(url.pathname, stripTrailingSlash);
511
+ if (target === url.pathname) return null;
512
+ const navigation = isRscRequest(req) && !isApiRoutePath(canonicalPath, matchRoute);
513
+ const search = navigation ? appVisibleSearch(url).search : url.search;
514
+ return buildRedirectResponse(new RedirectSignal(target + search, 308), new Headers(), navigation);
515
+ }
516
+ /** Whether `path` matches a route.ts handler. A matcher that throws: no. */
517
+ function isApiRoutePath(path, matchRoute) {
518
+ try {
519
+ const match = matchRoute(path);
520
+ return match !== null && isApiRouteChain(match.segments);
521
+ } catch (err) {
522
+ swallow(err, "canonical redirect: route match for route.ts lookup threw");
523
+ return false;
524
+ }
525
+ }
526
+ /**
527
+ * Build a proxy resolver closure from the declared source. Called exactly
528
+ * once at `createPipeline` setup time, so the hot path sees only the branch
529
+ * that corresponds to this pipeline's configured variant.
530
+ *
531
+ * Returns `null` when the app has no proxy.ts — the hot path short-circuits
532
+ * around `runProxyPhase` entirely in that case.
533
+ *
534
+ * Accepts the sugar form (a bare `ProxyExport` — function or function array)
535
+ * and normalises it to the static variant. Functions and arrays are
536
+ * structurally distinct from the tagged `{ kind: 'lazy', loader }` object,
537
+ * so discrimination is unambiguous.
538
+ */
539
+ function makeProxyResolver(proxy) {
540
+ if (proxy === void 0) return null;
541
+ if (typeof proxy === "function" || Array.isArray(proxy)) {
542
+ const exp = proxy;
543
+ return () => exp;
544
+ }
545
+ if (proxy.kind === "static") {
546
+ const exp = proxy.export;
547
+ return () => exp;
548
+ }
549
+ const loader = proxy.loader;
550
+ return async () => (await loader()).default;
551
+ }
552
+ /**
553
+ * Apply all Set-Cookie headers from the cookie jar to a Headers object.
554
+ * Each cookie gets its own Set-Cookie header per RFC 6265 §4.1.
555
+ */
556
+ function applyCookieJar(headers) {
557
+ for (const value of getSetCookieHeaders()) headers.append("Set-Cookie", value);
558
+ }
559
+ /**
560
+ * Bring a bag the jar was already applied to up to date with the jar.
561
+ *
562
+ * `applied` is what `getSetCookieHeaders()` returned when the jar was
563
+ * applied to `headers`. Values the jar no longer holds (a later write to the
564
+ * same name replaced them) are removed, and values it gained are appended.
565
+ * Every cookie then appears once, with its last write (design/29-cookies.md
566
+ * §"Last-Write-Wins for Same Name"). `Set-Cookie` values that did not come
567
+ * from the jar, such as a middleware appending to `ctx.headers` directly,
568
+ * are left alone.
569
+ */
570
+ function syncCookieJar(headers, applied) {
571
+ const current = getSetCookieHeaders();
572
+ const stale = applied.filter((value) => !current.includes(value));
573
+ const added = current.filter((value) => !applied.includes(value));
574
+ if (stale.length === 0 && added.length === 0) return;
575
+ const kept = headers.getSetCookie();
576
+ for (const value of stale) {
577
+ const index = kept.indexOf(value);
578
+ if (index !== -1) kept.splice(index, 1);
579
+ }
580
+ headers.delete("Set-Cookie");
581
+ for (const value of [...kept, ...added]) headers.append("Set-Cookie", value);
582
+ }
583
+ /**
584
+ * Merge framework-managed response headers onto a terminal response without
585
+ * overwriting headers the terminal response already set itself.
586
+ */
587
+ function mergeMissingHeaders(target, source) {
588
+ const existingKeys = new Set([...target.keys()].map((key) => key.toLowerCase()));
589
+ for (const [key, value] of source.entries()) if (!existingKeys.has(key.toLowerCase())) target.append(key, value);
590
+ }
591
+ /**
592
+ * Clone a Response into a fresh one whose header bag is guaranteed mutable.
593
+ *
594
+ * `Response.redirect()` and some platform-level passthrough responses (notably
595
+ * on Cloudflare Workers) return objects with frozen header bags. Calling
596
+ * `.set()` or `.append()` on them throws `TypeError: immutable`, which the
597
+ * pipeline can hit when it appends Set-Cookie or Server-Timing entries.
598
+ *
599
+ * The pipeline calls this at the producer sites where user-controlled
600
+ * responses enter the framework — `outcomeToResponse` for all phase outcomes,
601
+ * and `handleRequest` for metadata-route and auto-sitemap user handlers — so
602
+ * downstream code can write headers without runtime feature-detection.
603
+ *
604
+ * The clone is unconditional. This is a deliberate trade: we avoid a
605
+ * try/catch + thrown `TypeError` on every request (the previous probe-based
606
+ * approach paid that cost on the hot path) and accept one cheap Response
607
+ * rewrap at the framework boundary instead.
608
+ */
609
+ function cloneWithMutableHeaders(response) {
610
+ return withResponseInit(response, {
611
+ status: response.status,
612
+ statusText: response.statusText,
613
+ headers: new Headers(response.headers)
614
+ });
615
+ }
616
+ /**
617
+ * A fresh response header bag for a page the pipeline renders, seeded with
618
+ * the default dynamic-page cache policy.
619
+ *
620
+ * Without a Cache-Control header, CDNs (particularly Cloudflare) may attempt
621
+ * to buffer/process the response differently, causing intermittent
622
+ * multi-second delays. This matches Next.js's default behavior. Every bag a
623
+ * rendered page can be written onto starts here — a matched route, the
624
+ * no-match 404, and a deny page for a proxy-phase signal — so none of them
625
+ * leaves without a cache policy. Middleware and route handlers may replace it.
626
+ */
627
+ function dynamicResponseHeaders() {
628
+ return new Headers({ "Cache-Control": "private, no-cache, no-store, max-age=0, must-revalidate" });
629
+ }
630
+ /**
631
+ * Build a redirect Response from a RedirectSignal.
632
+ *
633
+ * For a client navigation (an RSC payload request for a page), returns 204 +
634
+ * X-Timber-Redirect so the client router can perform a soft SPA redirect. A
635
+ * raw 302 would be turned into an opaque redirect by
636
+ * fetch({redirect:'manual'}), crashing createFromFetch. See
637
+ * design/19-client-navigation.md. The caller decides what counts as a
638
+ * navigation: a route.ts match answers with a real 3xx whatever it accepts.
639
+ */
640
+ function buildRedirectResponse(signal, headers, navigation) {
641
+ if (navigation) {
642
+ headers.set("X-Timber-Redirect", signal.location);
643
+ return new Response(null, {
644
+ status: 204,
645
+ headers
646
+ });
647
+ }
648
+ headers.set("Location", signal.location);
649
+ return new Response(null, {
650
+ status: signal.status,
651
+ headers
652
+ });
653
+ }
654
+ /**
655
+ * Fire the user's onRequestError hook with request context.
656
+ *
657
+ * The one place a pipeline phase becomes the `phase` / `routeType` the hook
658
+ * reports, so every caller agrees. A render-phase error on a route.ts match
659
+ * is phase `'route'`, because the handler is what ran. Middleware reports
660
+ * as `'handler'`, its public name.
661
+ */
662
+ async function fireOnRequestError(error, req, source, segments) {
663
+ if (!isReportableError(error) || req.signal?.aborted) return;
664
+ if (isRepeatedLoadFailure(error)) return;
665
+ await callHook(error, req, source, segments);
666
+ }
667
+ /**
668
+ * Module evaluations whose failure was already reported. A module that fails
669
+ * to evaluate rethrows the same error on every later import, and
670
+ * `loadModule()` wraps each one in a new `ModuleLoadError` with that error
671
+ * as its `cause`. One broken module is one bug until it changes, however many
672
+ * loads trip over it in a request or across requests: the page's boundaries,
673
+ * then the fallback page, then the next request. A WeakSet, so a module that
674
+ * is re-evaluated (an HMR edit) gets a new cause and is reported again.
675
+ */
676
+ var reportedLoadFailures = /* @__PURE__ */ new WeakSet();
677
+ /**
678
+ * The same for a module that threw a primitive (`throw 'broken'`), which a
679
+ * WeakSet cannot hold. Keyed on the file and the value instead, so a module
680
+ * re-broken after an edit with the very same value is not reported again.
681
+ * It grows with the number of broken modules, not with requests.
682
+ */
683
+ var reportedPrimitiveLoadFailures = /* @__PURE__ */ new Set();
684
+ function isRepeatedLoadFailure(error) {
685
+ if (!(error instanceof ModuleLoadError)) return false;
686
+ const cause = error.cause;
687
+ if (typeof cause === "object" && cause !== null) {
688
+ if (reportedLoadFailures.has(cause)) return true;
689
+ reportedLoadFailures.add(cause);
690
+ return false;
691
+ }
692
+ const key = `${error.filePath}\0${typeof cause}\0${String(cause)}`;
693
+ if (reportedPrimitiveLoadFailures.has(key)) return true;
694
+ reportedPrimitiveLoadFailures.add(key);
695
+ return false;
696
+ }
697
+ /**
698
+ * Call the hook with request context, with no filtering. Only
699
+ * `fireOnRequestError()` and background reporting call it: background work
700
+ * runs after the response, so its request having aborted says nothing about
701
+ * the failure.
702
+ */
703
+ async function callHook(error, req, source, segments) {
704
+ if (!hasOnRequestError()) return;
705
+ const url = new URL(req.url);
706
+ const headersObj = {};
707
+ req.headers.forEach((v, k) => {
708
+ headersObj[k] = v;
709
+ });
710
+ const apiRoute = source === "route" || segments !== void 0 && isApiRouteChain(segments);
711
+ await callOnRequestError(error, {
712
+ method: req.method,
713
+ path: url.pathname,
714
+ headers: headersObj
715
+ }, {
716
+ phase: reportedPhase(source, apiRoute),
717
+ routePath: url.pathname,
718
+ routeType: source === "action" ? "action" : apiRoute ? "route" : "page",
719
+ traceId: getTraceId()
720
+ });
721
+ }
722
+ /**
723
+ * Whether an error is a failure `onRequestError` should hear about.
724
+ *
725
+ * Control-flow signals are outcomes the code chose — a `deny()` picks the
726
+ * page's status and data — and an abort is the client leaving. Callers answering
727
+ * a live request also skip everything once `req.signal` has aborted: a
728
+ * driver that throws "connection closed" after a disconnect is not a bug.
729
+ */
730
+ function isReportableError(error) {
731
+ return !isControlFlowSignal(error) && !isAbortError(error);
732
+ }
733
+ /**
734
+ * Fire the hook without making the caller wait, for callers that cannot:
735
+ * Flight's `onError` is synchronous, and background work has no caller.
736
+ * The promise is registered with the request's `waitUntil` so platforms
737
+ * that stop work when the response ends (Workers, Lambda) let the hook
738
+ * finish. The hook's own failures are caught in `callOnRequestError()`.
739
+ */
740
+ function fireInBackground(report) {
741
+ getWaitUntil()?.(report.catch((hookError) => swallow(hookError, "onRequestError could not be called")));
742
+ }
743
+ /**
744
+ * Run a `cache.component` stale-while-revalidate re-render as a singleflight
745
+ * body, and log and report its failure once for the flight. The stale
746
+ * payload already answered, so nothing else sees the failure.
747
+ *
748
+ * - **Once per flight.** A `.catch` on the flight's promise would run once
749
+ * per request that joined it, so the report happens inside the body. A
750
+ * body still running when the singleflight times out is reported then,
751
+ * with the timeout error (the signal's reason), and its later rejection
752
+ * is dropped.
753
+ * - **Against the request whose stale read started it**, read from the
754
+ * request context the work runs in. With no request (the build-time
755
+ * capture store) it is only logged.
756
+ * - **As phase `'render'`, route type `'page`.** A `cache.component` is a
757
+ * server component, so the read that started this was a page render (a
758
+ * revalidated page tree included). The request's own abort does not
759
+ * suppress the report: the work runs after the response either way.
760
+ */
761
+ async function runBackgroundFlight(signal, work, log) {
762
+ const failed = (error) => {
763
+ log(error);
764
+ const request = requestContextAls.getStore()?.request;
765
+ if (request && isReportableError(error)) fireInBackground(callHook(error, request, "render"));
766
+ };
767
+ const settled = new AbortController();
768
+ onAbortUntil(signal, () => failed(signal.reason), settled.signal);
769
+ try {
770
+ await work();
771
+ } catch (error) {
772
+ if (!signal.aborted) failed(error);
773
+ } finally {
774
+ settled.abort();
775
+ }
776
+ }
777
+ function reportedPhase(source, apiRoute) {
778
+ switch (source) {
779
+ case "middleware": return "handler";
780
+ case "render": return apiRoute ? "route" : "render";
781
+ default: return source;
782
+ }
783
+ }
784
+ //#endregion
785
+ //#region src/server/proxy.ts
786
+ /**
787
+ * Run the proxy pipeline.
788
+ *
789
+ * @param proxyExport - The default export from proxy.ts (function or array)
790
+ * @param req - The incoming request
791
+ * @param next - The continuation that proceeds to route matching and rendering
792
+ * @returns The final response
793
+ */
794
+ async function runProxy(proxyExport, req, next) {
795
+ const fns = Array.isArray(proxyExport) ? proxyExport : [proxyExport];
796
+ let i = fns.length;
797
+ let composed = next;
798
+ while (i--) {
799
+ const fn = fns[i];
800
+ const downstream = composed;
801
+ composed = () => Promise.resolve(fn(req, downstream));
802
+ }
803
+ return composed();
804
+ }
805
+ //#endregion
806
+ //#region src/server/middleware-runner.ts
807
+ /**
808
+ * Run a route's middleware function.
809
+ *
810
+ * @param middlewareFn - The default export from the route's middleware.ts
811
+ * @param ctx - The middleware context (req, params, headers, requestHeaders, searchParams)
812
+ * @returns A Response if middleware short-circuited, or undefined to continue
813
+ */
814
+ async function runMiddleware(middlewareFn, ctx) {
815
+ const result = await middlewareFn(ctx);
816
+ if (result instanceof Response) return result;
817
+ }
818
+ /**
819
+ * Run all middleware functions in the segment chain, root to leaf.
820
+ *
821
+ * Execution is top-down: root middleware runs first, leaf middleware runs last.
822
+ * All middleware share the same MiddlewareContext — a parent that sets
823
+ * ctx.requestHeaders makes it visible to child middleware and downstream components.
824
+ *
825
+ * Short-circuits on the first middleware that returns a Response.
826
+ * Remaining middleware in the chain do not execute.
827
+ *
828
+ * @param chain - Middleware functions ordered root-to-leaf
829
+ * @param ctx - Shared middleware context
830
+ * @returns A Response if any middleware short-circuited, or undefined to continue
831
+ */
832
+ async function runMiddlewareChain(chain, ctx) {
833
+ for (const fn of chain) {
834
+ const result = await fn(ctx);
835
+ if (result instanceof Response) return result;
836
+ }
837
+ }
838
+ //#endregion
839
+ //#region src/server/csp-nonce.ts
840
+ /**
841
+ * CSP nonce — per-request, generated on demand.
842
+ *
843
+ * timber emits several inline `<script>` tags per HTML response — React's
844
+ * bootstrap script and Fizz runtime, the Flight init/chunk scripts, the
845
+ * segment-tree script, and the post-flush noindex script. Under a strict
846
+ * `Content-Security-Policy` (`script-src 'nonce-…' 'strict-dynamic'`) every
847
+ * one of them needs the request's nonce or the browser refuses to run it.
848
+ *
849
+ * The app opts in by reading `ctx.nonce` in `middleware.ts` and putting it
850
+ * in the CSP header it sets through `ctx.headers`. The first read generates
851
+ * the value and stores it on the request context; the render pipeline reads
852
+ * it back with `getCspNonce()` and stamps it on every inline script. A
853
+ * request whose middleware never reads `ctx.nonce` has no nonce, and its
854
+ * markup is byte-identical to a render without this feature. timber does
855
+ * not parse the CSP header — the app owns the policy, timber owns the
856
+ * markup, and `ctx.nonce` is the one value both are built from.
857
+ *
858
+ * `proxy.ts` cannot participate: it only sees the finished response from
859
+ * `next()`, after the markup exists.
860
+ *
861
+ * See design/13-security.md §"Content Security Policy" (TIM-1414).
862
+ */
863
+ /**
864
+ * Generate a CSP nonce: 128 random bits, base64. Matches CSP's
865
+ * `base64-value` grammar, so it is valid in the header verbatim and safe
866
+ * inside a double-quoted HTML attribute without escaping.
867
+ */
868
+ function generateNonce() {
869
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
870
+ let binary = "";
871
+ for (const b of bytes) binary += String.fromCharCode(b);
872
+ return btoa(binary);
873
+ }
874
+ /**
875
+ * The request's CSP nonce, creating it on first call. Backs the
876
+ * `ctx.nonce` getter on `MiddlewareContext`. Outside a request context
877
+ * (tests, build-time rendering) a fresh value is returned but not
878
+ * retained, since there is no request for it to belong to.
879
+ */
880
+ function requestCspNonce() {
881
+ const store = requestContextAls.getStore();
882
+ if (!store) return generateNonce();
883
+ store.cspNonce ??= generateNonce();
884
+ return store.cspNonce;
885
+ }
886
+ //#endregion
887
+ //#region src/server/param-coercion.ts
888
+ /**
889
+ * Thrown when an app/schema.ts segment-param codec's parse() fails.
890
+ * The pipeline catches this and responds with 404.
891
+ */
892
+ var ParamCoercionError = class extends Error {
893
+ constructor(message) {
894
+ super(message);
895
+ this.name = "ParamCoercionError";
896
+ }
897
+ };
898
+ /** Global schema codecs, set once at startup from virtual:timber-schema. */
899
+ var _globalCodecs = null;
900
+ /**
901
+ * Coerce the matched route's raw segment params and return the result.
902
+ *
903
+ * Reads `match.rawSegmentParams` and never writes to `match`: the caller
904
+ * decides where the coerced params go. Reading the raw record makes the call
905
+ * repeatable — coercing a match twice runs every codec on the URL value both
906
+ * times, never on its own output.
907
+ *
908
+ * Codecs come from `app/schema.ts` and nowhere else (TIM-1342 completed
909
+ * design/41-global-params.md migration step 9). A route with no schema, or
910
+ * a param the schema does not declare, keeps its raw string — which is the
911
+ * honest type for an uninterpreted URL segment.
912
+ *
913
+ * Throws ParamCoercionError if any codec fails (→ 404).
914
+ *
915
+ * This runs BEFORE middleware, so ctx.segmentParams is already typed.
916
+ * See design/07-routing.md §"Where Coercion Runs"
917
+ * See design/41-global-params.md §"Pipeline Integration"
918
+ *
919
+ * Stays `async` with nothing to await: it is injected as a
920
+ * `CoerceSegmentParamsFn` into the revalidation renderer, which awaits
921
+ * it. Making it synchronous would
922
+ * change that contract and remove a microtask boundary the pipeline's
923
+ * ordering has always had, for no gain.
924
+ */
925
+ async function coerceSegmentParams(match) {
926
+ const globalCodecs = _globalCodecs;
927
+ const mergeTarget = Object.create(null);
928
+ for (const key of Object.keys(match.rawSegmentParams)) if (key !== "__proto__") mergeTarget[key] = match.rawSegmentParams[key];
929
+ if (globalCodecs) for (const node of match.segments) {
930
+ const segment = effectiveUrlSegment(node);
931
+ if (!segment.paramName) continue;
932
+ const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
933
+ const codec = globalCodecs[bracketKey];
934
+ if (!codec) continue;
935
+ const key = segment.paramName;
936
+ if (!(key in mergeTarget)) continue;
937
+ let parsed;
938
+ try {
939
+ parsed = codec.parse(mergeTarget[key]);
940
+ } catch (err) {
941
+ const message = err instanceof Error ? err.message : String(err);
942
+ 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}'.`);
943
+ throw new ParamCoercionError(message);
944
+ }
945
+ mergeTarget[key] = normalizeParamValue(parsed, key);
946
+ }
947
+ return mergeTarget;
948
+ }
949
+ //#endregion
950
+ //#region src/server/pipeline-metadata.ts
951
+ /**
952
+ * Metadata route helpers for the request pipeline.
953
+ *
954
+ * Handles serving static metadata files and serializing sitemap responses.
955
+ * Extracted from pipeline.ts to keep files under 500 lines.
956
+ *
957
+ * See design/16-metadata.md §"Metadata Routes"
958
+ */
959
+ /**
960
+ * Cache-Control the framework sets on metadata route responses it produces:
961
+ * static files, serialized handler results (sitemap, robots, manifest) and
962
+ * the auto-generated sitemap. A Response a handler returns is sent with its
963
+ * own headers only — the framework adds no default to it.
964
+ *
965
+ * See design/16-metadata.md §"Caching" (under "Metadata Routes")
966
+ */
967
+ var METADATA_CACHE_CONTROL = "public, max-age=14400, must-revalidate";
968
+ /**
969
+ * Content types that are text-based and should include charset=utf-8.
970
+ * Binary formats (images) should not include charset.
971
+ */
972
+ var TEXT_CONTENT_TYPES = /* @__PURE__ */ new Set([
973
+ "application/xml",
974
+ "text/plain",
975
+ "application/json",
976
+ "application/manifest+json",
977
+ "image/svg+xml"
978
+ ]);
979
+ /**
980
+ * Serve a static metadata file by reading it from disk.
981
+ *
982
+ * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
983
+ * are served as-is with the appropriate Content-Type header.
984
+ * Text files include charset=utf-8; binary files do not.
985
+ *
986
+ * See design/16-metadata.md §"Metadata Routes"
987
+ */
988
+ async function serveStaticMetadataFile(metaMatch) {
989
+ const { contentType, file } = metaMatch;
990
+ const isText = TEXT_CONTENT_TYPES.has(contentType);
991
+ const body = await readFile(file.filePath);
992
+ const headers = {
993
+ "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
994
+ "Content-Length": String(body.byteLength),
995
+ "Cache-Control": METADATA_CACHE_CONTROL
996
+ };
997
+ return new Response(body, {
998
+ status: 200,
999
+ headers
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Serialize a sitemap array to XML.
1004
+ * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
1005
+ */
1006
+ function serializeSitemap(entries) {
1007
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
1008
+ let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
1009
+ if (e.lastModified) {
1010
+ const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
1011
+ xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
1012
+ }
1013
+ if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
1014
+ if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
1015
+ xml += "\n </url>";
1016
+ return xml;
1017
+ }).join("\n")}\n</urlset>`;
1018
+ }
1019
+ /** Escape special XML characters. */
1020
+ function escapeXml(str) {
1021
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1022
+ }
1023
+ //#endregion
1024
+ //#region src/server/state-tree-diff.ts
1025
+ /**
1026
+ * State Tree Diffing — Server-side parsing and diffing of X-Timber-State-Tree.
1027
+ *
1028
+ * The client sends X-Timber-State-Tree on navigation requests, listing
1029
+ * the sync segments it has cached. The server diffs this against the
1030
+ * target route's segments to skip re-rendering unchanged sync layouts.
1031
+ *
1032
+ * This is a performance optimization only — NOT a security boundary.
1033
+ * All access.ts files run regardless of the state tree content.
1034
+ * A fabricated state tree can only cause extra rendering work or stale
1035
+ * layouts — never auth bypass.
1036
+ *
1037
+ * See design/19-client-navigation.md §"X-Timber-State-Tree Header"
1038
+ * See design/13-security.md §"State tree manipulation"
1039
+ */
1040
+ /**
1041
+ * Parse the X-Timber-State-Tree header from a request.
1042
+ *
1043
+ * Returns a Set of segment paths the client has cached (with an
1044
+ * additional `slots` property for cached slot paths), or null if
1045
+ * the header is missing, malformed, or empty. Parsing happens before
1046
+ * renderToReadableStream — not inside the React render pass.
1047
+ *
1048
+ * @returns ClientStateTree with segments and slots, or null if no valid state tree
1049
+ */
1050
+ function parseClientStateTree(req) {
1051
+ const header = req.headers.get("X-Timber-State-Tree");
1052
+ if (!header) return null;
1053
+ try {
1054
+ const parsed = JSON.parse(header);
1055
+ const hasSegments = Array.isArray(parsed.segments) && parsed.segments.length > 0;
1056
+ const hasSlots = Array.isArray(parsed.slots) && parsed.slots.length > 0;
1057
+ const hasTreePaths = Array.isArray(parsed.treePaths) && parsed.treePaths.length > 0;
1058
+ if (!hasSegments && !hasSlots && !hasTreePaths) return null;
1059
+ const result = new Set(hasSegments ? parsed.segments : []);
1060
+ result.slots = hasSlots ? new Set(parsed.slots) : null;
1061
+ result.treePaths = hasTreePaths ? new Set(parsed.treePaths) : null;
1062
+ return result;
1063
+ } catch (err) {
1064
+ swallow(err, "malformed X-Timber-State-Tree header");
1065
+ return null;
1066
+ }
1067
+ }
1068
+ //#endregion
1069
+ //#region src/server/pipeline-interception.ts
1070
+ /**
1071
+ * Interception route matching for the request pipeline.
1072
+ *
1073
+ * Matches target URLs against interception rewrites to support the
1074
+ * modal route pattern (soft navigation intercepts).
1075
+ *
1076
+ * Extracted from pipeline.ts to keep files under 500 lines.
1077
+ *
1078
+ * See design/07-routing.md §"Intercepting Routes"
1079
+ */
1080
+ /**
1081
+ * Check if an intercepting route applies for this soft navigation.
1082
+ *
1083
+ * Two conditions must hold:
1084
+ *
1085
+ * 1. The **target** pathname matches the rewrite's intercepted pattern.
1086
+ * 2. The **source** route — the page the user is navigating FROM, per the
1087
+ * validated X-Timber-URL header — renders the segment that owns the slot
1088
+ * holding the intercepting page (`interceptingScope`). Only then does that
1089
+ * slot exist in the rendered tree, so only then can the intercepting page
1090
+ * render.
1091
+ *
1092
+ * Condition 2 replaced a URL-prefix check (TIM-1279). A prefix cannot
1093
+ * distinguish a route-group-scoped interception from a genuinely root-level
1094
+ * one — route groups are invisible in `urlPath`, so both collapse to "/" and
1095
+ * the guard degenerates to always-true. Tree paths carry group identity.
1096
+ * The scope check also subsumes the old segment-boundary rule: a source route
1097
+ * under /feed-private has no "/feed" in its chain.
1098
+ *
1099
+ * A third condition lives with the caller, which owns route matching, and it
1100
+ * applies to the `'slot'` shape only: the route produced by re-matching
1101
+ * `interceptingPrefix` must pass through the scope too. Conditions 1–2 are
1102
+ * about the route the user is leaving; the slot has to exist in the tree that
1103
+ * actually renders. The `'children'` shape resolves its owner from the scope
1104
+ * directly rather than from a pathname, so it satisfies that by construction.
1105
+ *
1106
+ * `resolveSourceScopes` is a thunk so its inputs are only resolved when some
1107
+ * rewrite's pattern actually matches the target — the common case is no match
1108
+ * at all. It returns the two client-supplied answers to "what is on screen?"
1109
+ * as **separate sets, most authoritative first**: the tree paths the client
1110
+ * says it has mounted, then those of the route the departing URL matches. It
1111
+ * returns null only when neither yields anything, which is not a soft
1112
+ * navigation this can reason about.
1113
+ *
1114
+ * They are two sets rather than one union because ranking needs a chain
1115
+ * (TIM-1318). Each channel describes a single rendered chain, so within one the
1116
+ * scopes are strictly nested and the deepest is the innermost owner. Unioned
1117
+ * they are not: once a modal is open the address bar holds the *intercepted*
1118
+ * URL, so the second channel describes the canonical branch — possibly an
1119
+ * exclusive route group the client never mounted — and a deeper scope from
1120
+ * there would outrank the owner actually on screen. Trying the mounted channel
1121
+ * to exhaustion first keeps the fallback the union was there to provide while
1122
+ * ranking only within one chain.
1123
+ *
1124
+ * Returns the winning build-time rewrite, or null. Only build-time values ever
1125
+ * reach the renderer: the client-supplied header selects a rewrite but never
1126
+ * becomes a rendered route or pathname.
1127
+ *
1128
+ * The **first** matching rewrite wins, and the caller does not fall back to the
1129
+ * next one when the winner fails to resolve. That is deliberate and pre-dates
1130
+ * the two shapes: a rewrite that matched the target and the scope described the
1131
+ * author's intent, and quietly rendering some other author's interception
1132
+ * instead would be harder to explain than rendering the canonical route.
1133
+ *
1134
+ * "First" is meaningful because the list arrives **deepest scope first** —
1135
+ * `collectInterceptionRewrites` sorts it at build time, so the deepest owner a
1136
+ * single chain passes through wins and nothing here has to score (TIM-1318).
1137
+ * Tree-walk order used to decide it, which meant renaming a route group flipped
1138
+ * which modal opened. The precondition is a property of the manifest this reads
1139
+ * rather than something it can re-derive, so it is asserted at its source:
1140
+ * `tests/interception.test.ts` §"rewrite order is decided by scope depth".
1141
+ */
1142
+ function findInterceptionMatch(targetPathname, resolveSourceScopes, rewrites) {
1143
+ const candidates = rewrites.filter((rewrite) => pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern));
1144
+ if (candidates.length === 0) return null;
1145
+ const scopes = resolveSourceScopes();
1146
+ if (!scopes) return null;
1147
+ for (const scope of scopes) for (const rewrite of candidates) if (scope.has(rewrite.interceptingScope)) return rewrite;
1148
+ return null;
1149
+ }
1150
+ /**
1151
+ * Check if a pathname matches a URL pattern with dynamic segments.
1152
+ *
1153
+ * Supports [param] (single segment) and [...param] (one or more segments).
1154
+ * Static segments must match exactly.
1155
+ */
1156
+ function pathnameMatchesPattern(pathname, pattern) {
1157
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
1158
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
1159
+ let pi = 0;
1160
+ for (let i = 0; i < patternParts.length; i++) {
1161
+ const seg = classifyUrlSegment(patternParts[i]);
1162
+ switch (seg.kind) {
1163
+ case "catch-all": return pi < pathParts.length;
1164
+ case "optional-catch-all": return true;
1165
+ case "dynamic": {
1166
+ if (pi >= pathParts.length) return false;
1167
+ const prefix = seg.prefix ?? "";
1168
+ const suffix = seg.suffix ?? "";
1169
+ const pathPart = pathParts[pi];
1170
+ if (prefix || suffix) {
1171
+ if (pathPart.length <= prefix.length + suffix.length || prefix && !pathPart.startsWith(prefix) || suffix && !pathPart.endsWith(suffix)) return false;
1172
+ }
1173
+ pi++;
1174
+ continue;
1175
+ }
1176
+ case "static":
1177
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
1178
+ pi++;
1179
+ continue;
1180
+ }
1181
+ }
1182
+ return pi === pathParts.length;
1183
+ }
1184
+ /**
1185
+ * Resolve which route renders a soft navigation that an intercepting route
1186
+ * may claim. Returns the canonical match unchanged when no rewrite applies.
1187
+ *
1188
+ * Runs during route setup, so anything it throws is a `'setup'` outcome.
1189
+ */
1190
+ function resolveInterceptedRoute(config, req, canonicalPathname, canonicalMatch) {
1191
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1192
+ let match = canonicalMatch;
1193
+ let interception;
1194
+ if (isRscRequest(req) && config.interceptionRewrites?.length) {
1195
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
1196
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
1197
+ if (validatedSourceUrl) {
1198
+ const resolveSourceScopes = () => {
1199
+ const mounted = new Set(parseClientStateTree(req)?.treePaths ?? []);
1200
+ const sourceRoute = config.matchRoute(validatedSourceUrl);
1201
+ const scopes = [mounted, new Set(sourceRoute ? computeSegmentTreePaths(sourceRoute.segments) : [])].filter((scope) => scope.size > 0);
1202
+ return scopes.length > 0 ? scopes : null;
1203
+ };
1204
+ const rewrite = findInterceptionMatch(canonicalPathname, resolveSourceScopes, config.interceptionRewrites);
1205
+ if (rewrite?.mode === "children") {
1206
+ const interceptedMatch = config.matchInterceptedRoute?.(canonicalPathname, rewrite.interceptingScope);
1207
+ if (interceptedMatch) match = interceptedMatch;
1208
+ } else if (rewrite) {
1209
+ const sourceMatch = config.matchRoute(rewrite.interceptingPrefix);
1210
+ if (sourceMatch !== null && computeSegmentTreePaths(sourceMatch.segments).includes(rewrite.interceptingScope)) {
1211
+ match = sourceMatch;
1212
+ interception = { targetPathname: canonicalPathname };
1213
+ }
1214
+ }
1215
+ }
1216
+ }
1217
+ return {
1218
+ match,
1219
+ interception
1220
+ };
1221
+ }
1222
+ /**
1223
+ * Validate and canonicalize the X-Timber-URL header value.
1224
+ *
1225
+ * Returns the canonical pathname if valid, or null if rejected:
1226
+ * - Must start with '/' (relative pathname, no scheme/authority)
1227
+ * - Must not contain control characters
1228
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
1229
+ */
1230
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
1231
+ if (!raw.startsWith("/")) return null;
1232
+ if (raw.startsWith("//")) return null;
1233
+ for (let i = 0; i < raw.length; i++) {
1234
+ const code = raw.charCodeAt(i);
1235
+ if (code <= 31 || code === 127) return null;
1236
+ }
1237
+ const result = canonicalize(raw, stripTrailingSlash);
1238
+ if (!result.ok) return null;
1239
+ return result.pathname;
1240
+ }
1241
+ //#endregion
1242
+ //#region src/server/response-cache-policy.ts
1243
+ /**
1244
+ * Legacy shared-cache control fields that predate RFC 9213 and so do not
1245
+ * follow the `<target>-Cache-Control` naming pattern — the one part of this
1246
+ * rule that cannot be matched by shape. `X-Accel-Expires` is nginx
1247
+ * `proxy_cache`, which gives it precedence over `Cache-Control`.
1248
+ *
1249
+ * A closed historical set, unlike the vendor `*-Cache-Control` names, which
1250
+ * keep being minted and are handled by pattern below.
1251
+ */
1252
+ var LEGACY_CDN_CACHE_HEADERS = [
1253
+ "Surrogate-Control",
1254
+ "Edge-Control",
1255
+ "X-Accel-Expires"
1256
+ ];
1257
+ /**
1258
+ * Whether a response header overrides `Cache-Control` at a shared cache.
1259
+ *
1260
+ * Matched by *shape*, not by vendor name. RFC 9213 defines targeted fields
1261
+ * as `<target>-Cache-Control`, and every CDN spells its own: `CDN-`,
1262
+ * `Cloudflare-CDN-`, `Netlify-CDN-`, `Vercel-CDN-`, and whichever ships
1263
+ * next. A vendor list here is a denylist with an unbounded tail — it was
1264
+ * extended twice during review, each time by one name, which is the signal
1265
+ * that enumeration is the wrong shape. The suffix rule is total.
1266
+ *
1267
+ * `Cache-Control` itself does not match (no `-` prefix) and is replaced
1268
+ * separately.
1269
+ */
1270
+ function isSharedCacheOverride(name) {
1271
+ const lowered = name.toLowerCase();
1272
+ return lowered.endsWith("-cache-control") || LEGACY_CDN_CACHE_HEADERS.some((legacy) => legacy.toLowerCase() === lowered);
1273
+ }
1274
+ /** Disable caching, including CDN overrides that take precedence over Cache-Control. */
1275
+ function preventResponseCaching(headers) {
1276
+ const overrides = [];
1277
+ for (const name of headers.keys()) if (isSharedCacheOverride(name)) overrides.push(name);
1278
+ for (const name of overrides) headers.delete(name);
1279
+ headers.set("Cache-Control", "private, no-store");
1280
+ }
1281
+ //#endregion
1282
+ //#region src/server/error-response-headers.ts
1283
+ /** Preserve request-wide metadata when replacing a failed response body. */
1284
+ function errorResponseHeaders(responseHeaders) {
1285
+ const headers = new Headers(responseHeaders);
1286
+ headers.delete("Content-Length");
1287
+ headers.delete("Content-Encoding");
1288
+ headers.delete("Transfer-Encoding");
1289
+ preventResponseCaching(headers);
1290
+ headers.delete("ETag");
1291
+ headers.delete("Last-Modified");
1292
+ headers.delete("Expires");
1293
+ headers.delete("Age");
1294
+ return headers;
1295
+ }
1296
+ //#endregion
1297
+ //#region src/server/rsc-error-envelope.ts
1298
+ /**
1299
+ * Build the hard-navigate envelope for a status code.
1300
+ *
1301
+ * Preserve middleware's request-wide headers and cookies, but discard the
1302
+ * abandoned body's framing, validators, and cache policy. Every producer,
1303
+ * including errors returned normally during render, gets this cleanup here.
1304
+ * The input header bag is left intact. The body deliberately carries no message —
1305
+ * only the status already on the wire (design/13-security.md principle 4).
1306
+ */
1307
+ function rscErrorEnvelope(status, responseHeaders) {
1308
+ const headers = errorResponseHeaders(responseHeaders);
1309
+ headers.set(TIMBER_ERROR_HEADER, "1");
1310
+ headers.set("content-type", "application/json; charset=utf-8");
1311
+ return new Response(JSON.stringify({
1312
+ error: true,
1313
+ status
1314
+ }), {
1315
+ status,
1316
+ headers
1317
+ });
1318
+ }
1319
+ //#endregion
1320
+ //#region src/server/pipeline-outcome.ts
1321
+ /**
1322
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
1323
+ * each phase function returns) into a final `Response`.
1324
+ *
1325
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
1326
+ * catch logic and the terminal Response-building logic each live in
1327
+ * their own file. The phases produce values; this module is the single
1328
+ * source of truth for how those values become wire responses.
1329
+ *
1330
+ * See design/07-routing.md §"Request Lifecycle".
1331
+ */
1332
+ function rscErrorResponse(isRsc, status, headers) {
1333
+ if (isRsc) return rscErrorEnvelope(status, headers);
1334
+ return new Response(null, {
1335
+ status,
1336
+ headers: errorResponseHeaders(headers)
1337
+ });
1338
+ }
1339
+ /**
1340
+ * Resolve the header bag a signal/error outcome is written onto, with the
1341
+ * cookie jar applied exactly once.
1342
+ *
1343
+ * Ownership rule (design/49 §P0b): the phase that owns `responseHeaders`
1344
+ * applies the jar to it once; the translator applies it only for outcomes
1345
+ * that arrive without it. Render-phase outcomes already carry the jar —
1346
+ * `runRenderPhase()` applies it on entry, with or without a middleware
1347
+ * chain — so re-applying here emitted every middleware `Set-Cookie` twice
1348
+ * (TIM-1491).
1349
+ *
1350
+ * The guard is "not render", not "only middleware": proxy-phase signals
1351
+ * reach the translator with no `responseHeaders` at all, and for a
1352
+ * `proxy.ts` that awaits `next()` and then throws, this is the only place
1353
+ * the cookies downstream middleware set can reach the wire
1354
+ * (design/29-cookies.md §"proxy.ts Cookie Access"). Middleware-phase
1355
+ * signals throw before that phase's own application, so they need it too,
1356
+ * and so do setup-phase outcomes, which come before any phase applied it.
1357
+ *
1358
+ * `fresh` creates the bag for an outcome that arrives without one.
1359
+ */
1360
+ function outcomeHeaders(outcome, ctx, fresh = () => new Headers()) {
1361
+ const headers = ctx.responseHeaders ?? fresh();
1362
+ if (outcome.phase !== "render") applyCookieJar(headers);
1363
+ return headers;
1364
+ }
1365
+ /** Whether the outcome is for a route.ts match, which answers in its own format. */
1366
+ function isApiRouteMatch(ctx) {
1367
+ return ctx.match !== void 0 && isApiRouteChain(ctx.match.segments);
1368
+ }
1369
+ /**
1370
+ * Report an error outcome once: log it under its phase, fire
1371
+ * `onRequestError`, and hand it to the dev overlay. An error from a
1372
+ * route.ts handler — or anything else in its render phase — logs as a route
1373
+ * error and reports as phase `'route'`.
1374
+ */
1375
+ async function reportError(config, error, phase, ctx) {
1376
+ const { method, path } = ctx;
1377
+ switch (phase) {
1378
+ case "proxy":
1379
+ logProxyError({ error });
1380
+ break;
1381
+ case "setup":
1382
+ logRouteSetupError({
1383
+ method,
1384
+ path,
1385
+ error
1386
+ });
1387
+ break;
1388
+ case "middleware":
1389
+ logMiddlewareError({
1390
+ method,
1391
+ path,
1392
+ error
1393
+ });
1394
+ break;
1395
+ case "render": if (isApiRouteMatch(ctx)) logRouteError({
1396
+ method,
1397
+ path,
1398
+ error
1399
+ });
1400
+ else logRenderError({
1401
+ method,
1402
+ path,
1403
+ error
1404
+ });
1405
+ }
1406
+ await fireOnRequestError(error, ctx.req, phase, ctx.match?.segments);
1407
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, phase);
1408
+ }
1409
+ /** The outcome for a value a phase threw: a signal, or an error. */
1410
+ function thrownOutcome(phase, thrown) {
1411
+ if (isRedirectSignal(thrown)) return {
1412
+ kind: "redirect",
1413
+ phase,
1414
+ signal: thrown
1415
+ };
1416
+ if (isDenySignal(thrown)) return {
1417
+ kind: "deny",
1418
+ phase,
1419
+ signal: thrown
1420
+ };
1421
+ return {
1422
+ kind: "error",
1423
+ phase,
1424
+ error: thrown
1425
+ };
1426
+ }
1427
+ /**
1428
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
1429
+ * `Response`, applying cookies, building redirects, rendering deny pages
1430
+ * and fallback error pages, and firing instrumentation hooks.
1431
+ *
1432
+ * This is the single source of truth for how phase outputs become wire
1433
+ * responses; the per-phase try/catch blocks now produce values, not
1434
+ * Responses, so the conversion logic lives in exactly one place.
1435
+ */
1436
+ async function outcomeToResponse(config, outcome, ctx) {
1437
+ switch (outcome.kind) {
1438
+ case "response": {
1439
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
1440
+ if (outcome.phase === "proxy") return finalResponse;
1441
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
1442
+ applyCookieJar(finalResponse.headers);
1443
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
1444
+ logMiddlewareShortCircuit({
1445
+ method: ctx.method,
1446
+ path: ctx.path,
1447
+ status: finalResponse.status
1448
+ });
1449
+ }
1450
+ if (outcome.phase === "render") markResponseFlushed();
1451
+ return finalResponse;
1452
+ }
1453
+ case "redirect": {
1454
+ const headers = outcomeHeaders(outcome, ctx);
1455
+ const navigation = isRscRequest(ctx.req) && !isApiRouteMatch(ctx);
1456
+ return buildRedirectResponse(outcome.signal, headers, navigation);
1457
+ }
1458
+ case "deny": {
1459
+ const headers = outcomeHeaders(outcome, ctx, dynamicResponseHeaders);
1460
+ if (config.renderDenyFallback) try {
1461
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
1462
+ } catch (denyRenderError) {
1463
+ logRenderError({
1464
+ method: ctx.method,
1465
+ path: ctx.path,
1466
+ error: denyRenderError
1467
+ });
1468
+ await fireOnRequestError(denyRenderError, ctx.req, "render", ctx.match?.segments);
1469
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
1470
+ if (isRscRequest(ctx.req)) return rscErrorEnvelope(outcome.signal.status, headers);
1471
+ }
1472
+ 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.`);
1473
+ return new Response(null, {
1474
+ status: outcome.signal.status,
1475
+ headers
1476
+ });
1477
+ }
1478
+ case "error": {
1479
+ const isRsc = isRscRequest(ctx.req);
1480
+ const headers = outcomeHeaders(outcome, ctx);
1481
+ await reportError(config, outcome.error, outcome.phase, ctx);
1482
+ if (outcome.phase === "proxy" || outcome.phase === "middleware") return rscErrorResponse(isRsc, 500, headers);
1483
+ if (isRsc && !isApiRouteMatch(ctx)) return rscErrorResponse(true, 500, headers);
1484
+ if (config.renderFallbackError) try {
1485
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, errorResponseHeaders(headers), ctx.match));
1486
+ } catch (fallbackRenderError) {
1487
+ logRenderError({
1488
+ method: ctx.method,
1489
+ path: ctx.path,
1490
+ error: fallbackRenderError
1491
+ });
1492
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render", ctx.match?.segments);
1493
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
1494
+ }
1495
+ return rscErrorResponse(false, 500, headers);
1496
+ }
1497
+ }
1498
+ }
1499
+ //#endregion
1500
+ //#region src/server/pipeline-phases.ts
1501
+ /**
1502
+ * Pipeline phase functions — module-level free functions that take their
1503
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
1504
+ * (a discriminated union over response / redirect / deny / error) defined
1505
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
1506
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
1507
+ *
1508
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
1509
+ * isolation. The lift is mechanical — these functions used to be closures
1510
+ * over `config`; they now take `config` as an explicit parameter.
1511
+ *
1512
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
1513
+ */
1514
+ /**
1515
+ * Run the proxy.ts phase. Calls user proxy code with a `next()` continuation.
1516
+ *
1517
+ * When `next` is provided, it replaces the default `handleRequest` as the
1518
+ * continuation — this lets the pipeline inject action dispatch between proxy
1519
+ * and route matching (TIM-1213). The proxy resolver was picked at pipeline
1520
+ * construction time so the hot path sees no per-request branching on the
1521
+ * `ProxyConfig` discriminant.
1522
+ */
1523
+ async function runProxyPhase(config, getProxy, req, method, path, next) {
1524
+ const detailed = config.serverTiming === "detailed";
1525
+ try {
1526
+ const proxyExport = await getProxy();
1527
+ const continuation = next ?? (() => handleRequest(config, req, method, path, true));
1528
+ const proxyFn = () => runProxy(proxyExport, req, continuation);
1529
+ return {
1530
+ kind: "response",
1531
+ phase: "proxy",
1532
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
1533
+ };
1534
+ } catch (error) {
1535
+ return thrownOutcome("proxy", error);
1536
+ }
1537
+ }
1538
+ /**
1539
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
1540
+ * returns it as a 'response' outcome. Otherwise applies the request header
1541
+ * overlay and falls through to the render phase.
1542
+ */
1543
+ async function runMiddlewarePhase(config, req, match, responseHeaders, renderContext) {
1544
+ const detailed = config.serverTiming === "detailed";
1545
+ const requestHeaderOverlay = new Headers();
1546
+ const ctx = {
1547
+ req,
1548
+ requestHeaders: requestHeaderOverlay,
1549
+ headers: responseHeaders,
1550
+ segmentParams: match.segmentParams,
1551
+ get nonce() {
1552
+ return requestCspNonce();
1553
+ },
1554
+ earlyHints: (hints) => {
1555
+ for (const hint of hints) {
1556
+ let value;
1557
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
1558
+ else value = `<${hint.href}>; rel=${hint.rel}`;
1559
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1560
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1561
+ responseHeaders.append("Link", value);
1562
+ }
1563
+ }
1564
+ };
1565
+ try {
1566
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
1567
+ const middlewareResponse = await (async () => {
1568
+ setMutableCookieContext(true);
1569
+ try {
1570
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
1571
+ } finally {
1572
+ setMutableCookieContext(false);
1573
+ }
1574
+ })();
1575
+ if (middlewareResponse) return {
1576
+ kind: "response",
1577
+ phase: "middleware",
1578
+ response: middlewareResponse
1579
+ };
1580
+ applyRequestHeaderOverlay(requestHeaderOverlay);
1581
+ return runRenderPhase(config, req, match, responseHeaders, renderContext);
1582
+ } catch (error) {
1583
+ return thrownOutcome("middleware", error);
1584
+ }
1585
+ }
1586
+ /**
1587
+ * Run the render phase. Wraps the configured renderer in a span and a
1588
+ * timing scope, and translates thrown signals into outcome variants.
1589
+ *
1590
+ * The render phase owns `responseHeaders` from here on, so it is the one
1591
+ * place the cookie jar is applied to that bag (design/29-cookies.md
1592
+ * §"Applied Exactly Once"). Doing it here rather than in the middleware
1593
+ * phase means every render-phase outcome — a 200, or a deny / redirect /
1594
+ * error thrown from render — carries the jar whether or not a middleware
1595
+ * chain ran, and `outcomeToResponse` can skip render-phase outcomes
1596
+ * unconditionally (TIM-1491). Application precedes `config.render` so
1597
+ * middleware cookie writes are visible to route-handler header merging,
1598
+ * while handler `Set-Cookie` values still come after them and take
1599
+ * precedence.
1600
+ */
1601
+ async function runRenderPhase(config, req, match, responseHeaders, { canonicalPathname, interception }) {
1602
+ const detailed = config.serverTiming === "detailed";
1603
+ applyCookieJar(responseHeaders);
1604
+ try {
1605
+ const renderFn = () => config.render(req, match, responseHeaders, interception);
1606
+ return {
1607
+ kind: "response",
1608
+ phase: "render",
1609
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
1610
+ };
1611
+ } catch (error) {
1612
+ return thrownOutcome("render", error);
1613
+ }
1614
+ }
1615
+ /**
1616
+ * Process a single request from canonicalization through phase dispatch.
1617
+ *
1618
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
1619
+ * route match → interception → early hints → param coercion → middleware →
1620
+ * render → outcome translation. Pre-routing short-circuits return Responses
1621
+ * directly; post-match dispatch goes through `outcomeToResponse`.
1622
+ *
1623
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
1624
+ * the `next()` continuation passed to `runProxy()`.
1625
+ *
1626
+ * @param pathIsCanonical When true, `path` has already been canonicalized by
1627
+ * `createPipeline` — skip re-canonicalization to prevent double-decode.
1628
+ * When false (default), runs canonicalize as a safety net for direct callers.
1629
+ */
1630
+ async function handleRequest(config, req, method, path, pathIsCanonical) {
1631
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1632
+ let canonicalPathname;
1633
+ if (pathIsCanonical) canonicalPathname = path;
1634
+ else {
1635
+ const result = canonicalize(path, stripTrailingSlash);
1636
+ if (!result.ok) {
1637
+ 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.`);
1638
+ return new Response(null, { status: result.status });
1639
+ }
1640
+ canonicalPathname = result.pathname;
1641
+ }
1642
+ if (config.matchMetadataRoute) {
1643
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
1644
+ if (metaMatch) try {
1645
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
1646
+ setSegmentParams(metaMatch.segmentParams);
1647
+ const mod = await loadModule(metaMatch.file);
1648
+ if (typeof mod.default !== "function") {
1649
+ 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.`);
1650
+ return new Response("Metadata route must export a default function", { status: 500 });
1651
+ }
1652
+ const handlerResult = await mod.default();
1653
+ if (handlerResult instanceof Response) return cloneWithMutableHeaders(handlerResult);
1654
+ const contentType = metaMatch.contentType;
1655
+ let body;
1656
+ if (typeof handlerResult === "string") body = handlerResult;
1657
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
1658
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
1659
+ else body = String(handlerResult);
1660
+ return new Response(body, {
1661
+ status: 200,
1662
+ headers: {
1663
+ "Content-Type": `${contentType}; charset=utf-8`,
1664
+ "Cache-Control": METADATA_CACHE_CONTROL
1665
+ }
1666
+ });
1667
+ } catch (error) {
1668
+ if (isRedirectSignal(error)) return new Response(null, {
1669
+ status: error.status,
1670
+ headers: { Location: error.location }
1671
+ });
1672
+ if (isDenySignal(error)) return new Response(null, { status: error.status });
1673
+ logRenderError({
1674
+ method,
1675
+ path,
1676
+ error
1677
+ });
1678
+ await fireOnRequestError(error, req, "route");
1679
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
1680
+ return new Response(null, { status: 500 });
1681
+ }
1682
+ }
1683
+ if (config.autoSitemapHandler) try {
1684
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
1685
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
1686
+ } catch (error) {
1687
+ logRenderError({
1688
+ method,
1689
+ path,
1690
+ error
1691
+ });
1692
+ await fireOnRequestError(error, req, "route");
1693
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
1694
+ return new Response(null, { status: 500 });
1695
+ }
1696
+ const isRsc = isRscRequest(req);
1697
+ if (isRsc) {
1698
+ if (!checkVersionSkew(req).ok) {
1699
+ const reloadHeaders = new Headers();
1700
+ applyReloadHeaders(reloadHeaders);
1701
+ return new Response(null, {
1702
+ status: 204,
1703
+ headers: reloadHeaders
1704
+ });
1705
+ }
1706
+ }
1707
+ const responseHeaders = dynamicResponseHeaders();
1708
+ const renderNotFound = async (headers) => {
1709
+ if (!config.renderNoMatch) return new Response(null, { status: 404 });
1710
+ try {
1711
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, headers));
1712
+ } catch (error) {
1713
+ return outcomeToResponse(config, thrownOutcome("render", error), {
1714
+ req,
1715
+ method,
1716
+ path,
1717
+ responseHeaders: headers
1718
+ });
1719
+ }
1720
+ };
1721
+ let match = null;
1722
+ let interception;
1723
+ try {
1724
+ match = config.matchRoute(canonicalPathname);
1725
+ ({match, interception} = resolveInterceptedRoute(config, req, canonicalPathname, match));
1726
+ if (!match) {
1727
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
1728
+ return await renderNotFound(responseHeaders);
1729
+ }
1730
+ if (config.earlyHints && !isRsc && !isApiRouteChain(match.segments)) try {
1731
+ await config.earlyHints(match, req, responseHeaders);
1732
+ } catch (err) {
1733
+ swallow(err, "early hints hook threw");
1734
+ }
1735
+ try {
1736
+ match = {
1737
+ ...match,
1738
+ segmentParams: await coerceSegmentParams(match)
1739
+ };
1740
+ } catch (error) {
1741
+ if (error instanceof ParamCoercionError) {
1742
+ if (isDebug()) {
1743
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
1744
+ 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.`);
1745
+ }
1746
+ if (isApiRouteChain(match.segments)) return new Response(null, { status: 404 });
1747
+ return await renderNotFound(responseHeaders);
1748
+ }
1749
+ throw error;
1750
+ }
1751
+ setSegmentParams(match.segmentParams);
1752
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
1753
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
1754
+ } catch (error) {
1755
+ return outcomeToResponse(config, thrownOutcome("setup", error), {
1756
+ req,
1757
+ method,
1758
+ path,
1759
+ responseHeaders,
1760
+ match: match ?? void 0
1761
+ });
1762
+ }
1763
+ return outcomeToResponse(config, match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, {
1764
+ canonicalPathname,
1765
+ interception
1766
+ }) : await runRenderPhase(config, req, match, responseHeaders, {
1767
+ canonicalPathname,
1768
+ interception
1769
+ }), {
1770
+ req,
1771
+ method,
1772
+ path,
1773
+ responseHeaders,
1774
+ match
1775
+ });
1776
+ }
1777
+ //#endregion
1778
+ //#region src/server/rsc-cache-key-guard.ts
1779
+ /**
1780
+ * Origin-side binding of the `_rsc` cache key to the request that produced
1781
+ * the response (TIM-1268).
1782
+ *
1783
+ * The key is deterministic, and deliberately so — that is what makes RSC
1784
+ * payloads cacheable. But deterministic also means *predictable*: anyone can
1785
+ * compute the key another client will request. Without this guard, a caller
1786
+ * could request `/about?_rsc=<victim's key>` while sending its own
1787
+ * `X-Timber-State-Tree`, and a shared cache that keys by URL — the exact
1788
+ * environment this feature targets — would store that variant under the
1789
+ * victim's key. Every subsequent legitimate navigation would then be served
1790
+ * a payload rendered for someone else's segment tree or deployment.
1791
+ *
1792
+ * The guard is a *storability* rule, not a rejection: if the claimed key
1793
+ * does not match the key derived from the received headers, the response
1794
+ * loses its shared-cache directives. Mismatched requests are still served
1795
+ * normally, they just cannot be stored for anyone else.
1796
+ *
1797
+ * Why not Next.js's 307 self-correction: a redirect is cacheable in its own
1798
+ * right, costs a round trip on every legitimate miss, and would make the
1799
+ * server's behaviour depend on a parameter it otherwise never reads. This
1800
+ * rule closes the same hole by making the poisoned entry unstorable at the
1801
+ * source, in the response the developer already has to opt into sharing.
1802
+ *
1803
+ * See design/19-client-navigation.md §"The `_rsc` cache key".
1804
+ */
1805
+ /**
1806
+ * Whether the request's `_rsc` parameter matches the key derived from its
1807
+ * own headers.
1808
+ *
1809
+ * Requests without the parameter are not claiming a key at all, so they are
1810
+ * left alone — the bare document URL is the developer's declared territory
1811
+ * (see design/32-response-caching.md, TIM-1264). Neither is a parameter
1812
+ * whose value could not be one of our digests: `_rsc` is not reserved, and
1813
+ * an application that already uses it for its own search state
1814
+ * (`/search?_rsc=foo`) must not have its cache policy silently revoked by a
1815
+ * guard that mistook that for a forgery.
1816
+ */
1817
+ async function hasValidRscCacheKey(req) {
1818
+ if (!req.url.includes("?")) return true;
1819
+ let values;
1820
+ try {
1821
+ values = new URL(req.url).searchParams.getAll(RSC_KEY_PARAM);
1822
+ } catch {
1823
+ return false;
1824
+ }
1825
+ const claims = values.filter(isRscCacheKeyShape);
1826
+ if (claims.length === 0) return true;
1827
+ const expected = await rscCacheKey((name) => req.headers.get(name));
1828
+ if (expected === null) return false;
1829
+ return claims.every((claim) => claim === expected);
1830
+ }
1831
+ /**
1832
+ * Ensure a Flight payload can never be interpreted as a document.
1833
+ *
1834
+ * Applied here, at the pipeline's single exit, rather than where each
1835
+ * payload response is built. Six places build one — the success path, three
1836
+ * in `deny-renderer.ts`, the action paths — and hardening them one at a time
1837
+ * is how you end up hardening five of six. The response is Flight if it says
1838
+ * it is; that is the only test that covers every producer, including ones
1839
+ * added later.
1840
+ *
1841
+ * Matters because the payload URL is observable and, on a shared-cache hit,
1842
+ * the origin is never consulted — so a top-level navigation can be handed
1843
+ * these bytes with no request-time check available. See design/13-security.md
1844
+ * #36c.
1845
+ */
1846
+ function hardenRscPayloadResponse(response) {
1847
+ if (!isRscContentType(response.headers.get("content-type"))) return;
1848
+ response.headers.set("X-Content-Type-Options", "nosniff");
1849
+ }
1850
+ /**
1851
+ * Make a response unstorable by any shared cache when its request claimed an
1852
+ * `_rsc` key that does not match its own headers.
1853
+ *
1854
+ * The end state is unconditional and therefore statable: **a mismatched
1855
+ * response is never stored by any cache.** Every targeted cache-control
1856
+ * field is removed and `Cache-Control` is replaced outright, rather than
1857
+ * downgrading only when a shared directive is spotted. Conditional variants
1858
+ * of this were tried and were wrong twice over — they missed the CDN-
1859
+ * specific headers, and leaving `Cache-Control` alone when it looked
1860
+ * harmless lets a CDN apply heuristic caching to a response that has none.
1861
+ *
1862
+ * The cost is that a mismatched request loses developer-chosen *browser*
1863
+ * caching too. That is a request no timber client ever makes.
1864
+ *
1865
+ * Purge tags (`Surrogate-Key`, `Cache-Tag`) are deliberately left alone:
1866
+ * they address stored entries, and this response is not stored.
1867
+ *
1868
+ * Mutates `response.headers` in place; the pipeline guarantees mutable
1869
+ * headers at this point (see TIM-866).
1870
+ */
1871
+ async function enforceRscCacheKey(req, response) {
1872
+ if (await hasValidRscCacheKey(req)) return;
1873
+ preventResponseCaching(response.headers);
1874
+ }
1875
+ //#endregion
1876
+ //#region src/server/head-response.ts
1877
+ /**
1878
+ * HEAD body stripping — RFC 9110 §9.3.2.
1879
+ *
1880
+ * "The HEAD method is identical to GET except that the server MUST NOT send
1881
+ * content in the response." The headers, however, must be the ones the
1882
+ * corresponding GET would have produced — which is why timber renders the
1883
+ * route in full and discards the body here rather than short-circuiting the
1884
+ * render. Content-Type, Content-Length, Set-Cookie, cache directives and
1885
+ * everything else ride through untouched.
1886
+ *
1887
+ * Node's `ServerResponse` happens to discard writes for HEAD, so the wire is
1888
+ * usually correct even without this. That is a property of one adapter, not of
1889
+ * the `Response` object: static generation, the Cloudflare and Nitro adapters,
1890
+ * tests, and anything calling the pipeline handler as a function all observe
1891
+ * the `Response` directly and saw the full body before TIM-1324.
1892
+ *
1893
+ * The pipeline applies this at its single exit so every response shape is
1894
+ * covered — page render, API route, metadata route, deny page, error page,
1895
+ * proxy short-circuit. The unit-level producer that is also reachable as a
1896
+ * standalone function (`handleRouteRequest`) calls it too, so it honours HEAD
1897
+ * on its own; it shares this implementation rather than repeating it, and
1898
+ * applying it twice is a no-op.
1899
+ */
1900
+ /**
1901
+ * Return a bodyless copy of `response` when `method` is HEAD.
1902
+ *
1903
+ * A no-op for every other method and for responses that already carry no body
1904
+ * (204, 304, redirects), so callers do not need to pre-check either.
1905
+ *
1906
+ * The discarded stream is cancelled: an SSR render that reached this point has
1907
+ * a live producer attached, and dropping the reference without cancelling
1908
+ * leaks it for the lifetime of the render (design/13-security.md A4).
1909
+ */
1910
+ function stripHeadBody(response, method) {
1911
+ if (method.toUpperCase() !== "HEAD") return response;
1912
+ const nodeBody = nodeBodyOps(response);
1913
+ if (nodeBody ? !nodeBody.hasBody : response.body === null) return response;
1914
+ discardResponseBody(response);
1915
+ return new Response(null, {
1916
+ status: response.status,
1917
+ statusText: response.statusText,
1918
+ headers: response.headers
1919
+ });
1920
+ }
1921
+ //#endregion
1922
+ //#region src/server/pipeline.ts
1923
+ /**
1924
+ * Create the request handler from a pipeline configuration.
1925
+ *
1926
+ * Returns a function that processes an incoming Request through all pipeline
1927
+ * stages and produces a Response. This is the top-level entry point for the
1928
+ * server. The body is intentionally small — phase logic lives in
1929
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
1930
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
1931
+ * scope, Server-Timing header emission, and the active-request counter.
1932
+ */
1933
+ function createPipeline(config) {
1934
+ const proxyResolver = makeProxyResolver(config.proxy);
1935
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
1936
+ const serverTiming = config.serverTiming ?? "total";
1937
+ let activeRequests = 0;
1938
+ return async (req) => {
1939
+ const url = new URL(req.url);
1940
+ const method = req.method;
1941
+ const path = url.pathname;
1942
+ const startTime = performance.now();
1943
+ const traceIdValue = generateTraceId();
1944
+ return runWithTraceId(traceIdValue, async () => {
1945
+ const inRequestContext = async () => {
1946
+ const runRequest = async () => {
1947
+ logRequestReceived({
1948
+ method,
1949
+ path
1950
+ });
1951
+ activeRequests++;
1952
+ let concurrency = activeRequests;
1953
+ let response;
1954
+ try {
1955
+ response = await withSpan("http.server.request", {
1956
+ "http.request.method": method,
1957
+ "url.path": path
1958
+ }, async () => {
1959
+ const otelTraceId = await getOtelTraceId();
1960
+ if (otelTraceId) replaceTraceId(otelTraceId);
1961
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1962
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
1963
+ if (!canonResult.ok) {
1964
+ 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.`);
1965
+ await setSpanAttribute("http.response.status_code", canonResult.status);
1966
+ return new Response(null, { status: canonResult.status });
1967
+ }
1968
+ const canonicalPath = canonResult.pathname;
1969
+ let canonicalReq = req;
1970
+ if (url.pathname !== canonicalPath) {
1971
+ const canonicalUrl = new URL(req.url);
1972
+ canonicalUrl.pathname = canonicalPath;
1973
+ canonicalReq = new Request(canonicalUrl.toString(), req);
1974
+ }
1975
+ const csrfRejection = csrfGate(canonicalReq, canonicalPath, config.csrf ?? {}, config.matchRoute);
1976
+ if (csrfRejection) {
1977
+ await setSpanAttribute("http.response.status_code", csrfRejection.status);
1978
+ return csrfRejection;
1979
+ }
1980
+ const innerHandler = async () => {
1981
+ const redirect = canonicalRedirect(req, canonicalPath, stripTrailingSlash, config.matchRoute);
1982
+ if (redirect) return redirect;
1983
+ if (config.dispatchAction) {
1984
+ const reenter = (rerenderReq, reentry) => runWithRequestContext(rerenderReq, () => handleRequest(config, rerenderReq, rerenderReq.method, canonicalPath, true), reentry);
1985
+ const actionResult = await config.dispatchAction(canonicalReq, canonicalPath, reenter);
1986
+ if (actionResult) return actionResult;
1987
+ }
1988
+ return handleRequest(config, canonicalReq, method, canonicalPath, true);
1989
+ };
1990
+ let result;
1991
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath, innerHandler), {
1992
+ req: canonicalReq,
1993
+ method,
1994
+ path: canonicalPath
1995
+ });
1996
+ else result = await innerHandler();
1997
+ await setSpanAttribute("http.response.status_code", result.status);
1998
+ const varyTokens = [...RSC_KEY_HEADERS];
1999
+ const existingVary = result.headers.get("Vary");
2000
+ const existingTokens = existingVary ? existingVary.toLowerCase().split(",").map((t) => t.trim()) : [];
2001
+ const newTokens = varyTokens.filter((t) => !existingTokens.includes(t.toLowerCase()));
2002
+ if (newTokens.length > 0) result.headers.set("Vary", existingVary ? `${existingVary}, ${newTokens.join(", ")}` : newTokens.join(", "));
2003
+ await enforceRscCacheKey(canonicalReq, result);
2004
+ hardenRscPayloadResponse(result);
2005
+ result = stripHeadBody(result, method);
2006
+ if (serverTiming === "detailed") {
2007
+ const timingHeader = getServerTimingHeader();
2008
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
2009
+ } else if (serverTiming === "total") {
2010
+ const totalMs = Math.round(performance.now() - startTime);
2011
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
2012
+ }
2013
+ if (serverTiming === "detailed") {
2014
+ const nodeBody = nodeBodyOps(result);
2015
+ if (nodeBody) result = nodeBody.timed(startTime);
2016
+ else if (result.body) result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
2017
+ status: result.status,
2018
+ statusText: result.statusText,
2019
+ headers: result.headers
2020
+ });
2021
+ }
2022
+ return result;
2023
+ });
2024
+ } finally {
2025
+ concurrency = activeRequests;
2026
+ activeRequests--;
2027
+ }
2028
+ const durationMs = Math.round(performance.now() - startTime);
2029
+ const status = response.status;
2030
+ logRequestCompleted({
2031
+ method,
2032
+ path,
2033
+ status,
2034
+ durationMs,
2035
+ concurrency
2036
+ });
2037
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
2038
+ method,
2039
+ path,
2040
+ durationMs,
2041
+ threshold: slowRequestMs,
2042
+ concurrency
2043
+ });
2044
+ return response;
2045
+ };
2046
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
2047
+ };
2048
+ return runWithRequestContext(req, inRequestContext);
2049
+ });
2050
+ };
2051
+ }
2052
+ //#endregion
2053
+ //#region src/server/early-hints.ts
2054
+ /**
2055
+ * 103 Early Hints utilities.
2056
+ *
2057
+ * Early Hints are sent before the final response to let the browser
2058
+ * start fetching critical resources (CSS, fonts, JS) while the server
2059
+ * is still rendering.
2060
+ *
2061
+ * The framework collects hints from two sources:
2062
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
2063
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
2064
+ *
2065
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
2066
+ * Link headers into 103 Early Hints responses.
2067
+ *
2068
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
2069
+ */
2070
+ /**
2071
+ * Format a single EarlyHint as a Link header value.
2072
+ *
2073
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
2074
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
2075
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
2076
+ * attribute order differs from Cloudflare's cached copy, the browser
2077
+ * sees two preload headers for the same URL (different attribute order)
2078
+ * and warns "Preload was ignored." Matching the order ensures the
2079
+ * browser deduplicates them correctly.
2080
+ *
2081
+ * Examples:
2082
+ * `</styles/root.css>; as=style; rel=preload`
2083
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
2084
+ * `</_timber/client.js>; rel=modulepreload`
2085
+ * `<https://fonts.googleapis.com>; rel=preconnect`
2086
+ */
2087
+ function formatLinkHeader(hint) {
2088
+ if (hint.as !== void 0) {
2089
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2090
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2091
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2092
+ return value;
2093
+ }
2094
+ let value = `<${hint.href}>; rel=${hint.rel}`;
2095
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2096
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2097
+ return value;
2098
+ }
2099
+ /**
2100
+ * Collect all Link header strings for a matched route's segment chain.
2101
+ *
2102
+ * Walks the build manifest to emit hints for:
2103
+ * - CSS stylesheets (as=style; rel=preload)
2104
+ * - Font assets (as=font; rel=preload; crossorigin)
2105
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
2106
+ *
2107
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
2108
+ * Returns an empty array in dev mode (manifest is empty).
2109
+ */
2110
+ function collectEarlyHintHeaders(segments, manifest, options) {
2111
+ const result = [];
2112
+ const seenUrls = /* @__PURE__ */ new Set();
2113
+ const add = (url, header) => {
2114
+ if (!seenUrls.has(url)) {
2115
+ seenUrls.add(url);
2116
+ result.push(header);
2117
+ }
2118
+ };
2119
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
2120
+ href: url,
2121
+ rel: "preload",
2122
+ as: "style"
2123
+ }));
2124
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
2125
+ href: font.href,
2126
+ rel: "preload",
2127
+ as: "font",
2128
+ crossOrigin: "anonymous"
2129
+ }));
2130
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
2131
+ href: url,
2132
+ rel: "modulepreload"
2133
+ }));
2134
+ return result;
2135
+ }
2136
+ //#endregion
2137
+ //#region src/server/early-hints-sender.ts
2138
+ /**
2139
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
2140
+ *
2141
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
2142
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
2143
+ * the adapter can send these as a 103 Early Hints interim response before
2144
+ * the final response is ready.
2145
+ *
2146
+ * This module provides an ALS-based bridge: the generated entry point
2147
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
2148
+ * binding a per-request sender function. The pipeline calls
2149
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
2150
+ *
2151
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
2152
+ * converts Link headers into 103 automatically), no sender is installed
2153
+ * and `sendEarlyHints103()` is a no-op.
2154
+ *
2155
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
2156
+ */
2157
+ /**
2158
+ * Run a function with a per-request early hints sender installed.
2159
+ *
2160
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
2161
+ * bind the platform's writeEarlyHints capability for the request duration.
2162
+ */
2163
+ function runWithEarlyHintsSender(sender, fn) {
2164
+ return earlyHintsSenderAls.run(sender, fn);
2165
+ }
2166
+ /**
2167
+ * Send collected Link headers as a 103 Early Hints response.
2168
+ *
2169
+ * No-op if no sender is installed for the current request (e.g., on
2170
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
2171
+ *
2172
+ * Non-fatal: errors from the sender are caught and silently ignored.
2173
+ */
2174
+ function sendEarlyHints103(links) {
2175
+ if (!links.length) return;
2176
+ const sender = earlyHintsSenderAls.getStore();
2177
+ if (!sender) return;
2178
+ try {
2179
+ sender(links);
2180
+ } catch (err) {
2181
+ swallow(err, "early hints 103 send failed");
2182
+ }
2183
+ }
2184
+ //#endregion
2185
+ //#region src/client/error-reconstituter.tsx
2186
+ /**
2187
+ * Reconstitutes a SerializableError into a real Error instance before
2188
+ * passing to the user's error component.
2189
+ *
2190
+ * TSX error pages are 'use client' components that receive { error: Error, digest, reset }.
2191
+ * Error objects are not RSC-serializable (React Flight throws "Only plain objects
2192
+ * can be passed to Client Components"). This wrapper receives the error as a plain
2193
+ * SerializableError object, reconstitutes a real Error instance, and passes it
2194
+ * to the user's error component — ensuring error instanceof Error works correctly.
2195
+ *
2196
+ * See design/spike-TIM-565-unify-error-pages.md §"Edge Case B"
2197
+ * See design/10-error-handling.md §"RSC → SSR for Error Pages via SerializableError"
2198
+ */
2199
+ /**
2200
+ * Reconstitute a SerializableError into a real Error instance and render
2201
+ * the user's error component with the proper props.
2202
+ */
2203
+ function ErrorReconstituter({ error: serialized, digest, reset, component, status, data }) {
2204
+ const error = Object.assign(new Error(serialized.message), {
2205
+ name: serialized.name,
2206
+ stack: serialized.stack ?? `${serialized.name}: ${serialized.message}`
2207
+ });
2208
+ return createElement(component, {
2209
+ error,
2210
+ digest,
2211
+ reset,
2212
+ ...status != null ? {
2213
+ status,
2214
+ data
2215
+ } : {}
2216
+ });
2217
+ }
2218
+ //#endregion
2219
+ //#region src/server/deny-boundary.ts
2220
+ /**
2221
+ * Deny boundary subsystem — the in-tree DenySignal flow.
2222
+ *
2223
+ * Three things live together here because they form a single flow:
2224
+ *
2225
+ * 1. **Chain construction** (`buildDenyPageChain`) — walks the matched
2226
+ * segment chain at element-tree build time and produces a list of
2227
+ * `DenyPageEntry` records ordered by specificity (specific status →
2228
+ * category catch-all → `error.tsx`).
2229
+ *
2230
+ * 2. **Runtime matching and placement** (`matchDenyEntry`, `placeDenyPage`,
2231
+ * `handleCaughtDeny`) — picks the first chain entry whose status filter
2232
+ * matches the thrown DenySignal, then decides whether the catch site may
2233
+ * render it where it stands. A chain spans the catcher outward to root,
2234
+ * so a match may belong to an ancestor segment; rendering it in place
2235
+ * would wrap it in every layout in between. Ancestor-owned matches are
2236
+ * re-thrown with `ownerKey` stamped on the signal so the error boundary
2237
+ * at the owning segment renders it. See TIM-1356.
2238
+ *
2239
+ * 3. **The page boundary itself** (`PageDenyBoundary`) — the async server
2240
+ * component that wraps a server-component page, calls it, and catches
2241
+ * `DenySignal` so the deny page renders in-tree (no throw reaches
2242
+ * React Flight, single render pass).
2243
+ *
2244
+ * Plus the ALS helpers (`setDenyStatus` / `getDenyStatus`) the boundary
2245
+ * uses to thread the matched status code back to the pipeline so the
2246
+ * HTTP status reflects the deny.
2247
+ *
2248
+ * Folded into one module from the former `deny-page-resolver.ts` and
2249
+ * `page-deny-boundary.tsx` (TIM-853) — the names were misleading and the
2250
+ * three pieces only made sense together.
2251
+ *
2252
+ * See design/04-authorization.md, design/10-error-handling.md, TIM-666.
2253
+ */
2254
+ /**
2255
+ * Find the first deny page in the chain whose status filter matches.
2256
+ * Returns null when nothing in the chain accepts this status.
2257
+ *
2258
+ * For 4xx statuses, the chain's stored order is correct: every status file
2259
+ * across all segments (inner→outer) before any error.tsx — so a root
2260
+ * `404.tsx` beats a leaf `error.tsx`. This matches `resolve4xx`.
2261
+ *
2262
+ * For 5xx statuses, the match walks per-segment (inner→outer): at each
2263
+ * segment, status files (`503.tsx` → `5xx.tsx`) then `error.tsx`, before
2264
+ * moving to the next segment outward. A leaf `error.tsx` therefore beats a
2265
+ * root `5xx.tsx` — the intentional inverse of the 4xx chain, matching
2266
+ * `resolve5xx`. See TIM-1360.
2267
+ */
2268
+ function matchDenyEntry(chain, status) {
2269
+ return matchDenyEntries(chain, status)[0] ?? null;
2270
+ }
2271
+ /**
2272
+ * Return ALL deny page entries whose status filter matches, in traversal
2273
+ * order (best match first). `matchDenyEntry` returns only the first;
2274
+ * late addressing (TIM-1450) needs the full list so the client can find
2275
+ * the first *reachable* owner via its ancestry context.
2276
+ */
2277
+ function matchDenyEntries(chain, status) {
2278
+ if (status >= 500) return matchDenyEntries5xx(chain, status);
2279
+ const matches = [];
2280
+ for (const entry of chain) if (entry.status === status) matches.push(entry);
2281
+ else if (entry.status === 400 && status >= 400 && status <= 499) matches.push(entry);
2282
+ else if (entry.status === null) matches.push(entry);
2283
+ return matches;
2284
+ }
2285
+ /**
2286
+ * 5xx per-segment walk: at each segment (inner→outer), check status files
2287
+ * then error.tsx before moving outward. Mirrors `resolve5xx`.
2288
+ */
2289
+ function matchDenyEntries5xx(chain, status) {
2290
+ const segmentIndices = [];
2291
+ for (const entry of chain) if (!segmentIndices.includes(entry.segmentIndex)) segmentIndices.push(entry.segmentIndex);
2292
+ segmentIndices.sort((a, b) => b - a);
2293
+ const matches = [];
2294
+ for (const seg of segmentIndices) {
2295
+ for (const entry of chain) {
2296
+ if (entry.segmentIndex !== seg || entry.kind === "error") continue;
2297
+ if (entry.status === status) matches.push(entry);
2298
+ else if (entry.status === 500 && status >= 500 && status <= 599) matches.push(entry);
2299
+ }
2300
+ for (const entry of chain) {
2301
+ if (entry.segmentIndex !== seg || entry.kind !== "error") continue;
2302
+ matches.push(entry);
2303
+ }
2304
+ }
2305
+ return matches;
2306
+ }
2307
+ /**
2308
+ * Decide where the deny page for `status` renders, from the perspective of
2309
+ * the catch site at `selfKey`.
2310
+ *
2311
+ * The match itself is unchanged — first entry in fallback order wins, so
2312
+ * every path picks the same file. What this adds is the position: a chain
2313
+ * built at segment i spans i outward to root, so a matched entry is owned
2314
+ * either by the catcher or by one of its ancestors.
2315
+ *
2316
+ * - Owned by the catcher → `render`. The catcher already sits at the
2317
+ * owning segment's position.
2318
+ * - Owned by an ancestor → `hoist`. Rendering here would wrap the deny page
2319
+ * in every layout between the owner and the catcher. The caller re-throws
2320
+ * with `ownerKey` stamped on the signal so the boundary at that segment
2321
+ * renders it instead — inside the owner's layout, outside the rest.
2322
+ *
2323
+ * Returns null when no entry matches; the caller re-throws unannotated and
2324
+ * the re-render fallback resolves it.
2325
+ *
2326
+ * See design/04-authorization.md §"Where a Deny Page Renders", TIM-1356.
2327
+ */
2328
+ function placeDenyPage(chain, status, data, selfKey) {
2329
+ const entry = matchDenyEntry(chain, status);
2330
+ if (!entry) return null;
2331
+ if (entry.ownerKey !== selfKey) return {
2332
+ kind: "hoist",
2333
+ ownerKey: entry.ownerKey
2334
+ };
2335
+ return {
2336
+ kind: "render",
2337
+ element: renderDenyEntry(entry, status, data)
2338
+ };
2339
+ }
2340
+ /**
2341
+ * Build the element for a matched deny chain entry with the props contract
2342
+ * the file's convention documents:
2343
+ *
2344
+ * - Status-code files: { status, data }
2345
+ * - error.tsx (TSX): { error, digest, reset } via ErrorReconstituter, plus
2346
+ * { status, data } for dual-shape implementations. Without
2347
+ * the Error prop, any error.tsx written per the docs (reading
2348
+ * error.message) crashes — turning a clean deny(404) into a 500. TIM-1081.
2349
+ * - error.mdx: plain { status } — server component, static content.
2350
+ */
2351
+ function renderDenyEntry(entry, status, data) {
2352
+ const h = createElement;
2353
+ return h(StatusPageMarker, null, renderDenyPage(entry, status, data, h));
2354
+ }
2355
+ function renderDenyPage(entry, status, data, h) {
2356
+ if (entry.kind !== "error") return h(entry.component, {
2357
+ status,
2358
+ data
2359
+ });
2360
+ return h(ErrorReconstituter, {
2361
+ error: {
2362
+ message: `Access denied with status ${status}`,
2363
+ name: "DenySignal"
2364
+ },
2365
+ digest: null,
2366
+ reset: void 0,
2367
+ component: entry.component,
2368
+ status,
2369
+ data
2370
+ });
2371
+ }
2372
+ /**
2373
+ * The whole of what an in-tree catch site does with a `DenySignal`, shared
2374
+ * by all three of them (`PageDenyBoundary`, `TracedLayout`, `AccessGate`).
2375
+ *
2376
+ * Returns the deny page element when this catch site owns the matched file.
2377
+ * Otherwise it throws — annotated with `ownerKey` when an ancestor owns the
2378
+ * file, bare when nothing matched at all.
2379
+ *
2380
+ * `setDenyStatus` runs on the hoist path too, *before* the throw, for one
2381
+ * case. Normally Flight's `onError` captures the rethrown signal within the
2382
+ * renderer's promotion cap, and the pipeline renders the deny page with
2383
+ * `deny.status` — the recorded status goes unread. When the signal lands
2384
+ * after the cap but within the detection window that follows, the renderer
2385
+ * discards it (never promoted) and streams the document it already has;
2386
+ * `getDenyStatus()`, read once as the renderer returns, gives that document
2387
+ * the deny's 4xx instead of a 200. A deny later than that commits 200. Pinned by
2388
+ * `tests/late-hoisted-deny-status.test.ts`. The RSC payload path never
2389
+ * reads it — a Flight payload response is always 200 and the row itself
2390
+ * carries the deny (TIM-1495).
2391
+ *
2392
+ * Either branch leaves part of the matched chain unmounted — hoisting sends
2393
+ * the render to a boundary that discards everything below it, and a layout
2394
+ * that denies returns the deny page instead of its own child outlet. What the
2395
+ * client then learns about the tree is decided by the boundary that renders
2396
+ * the page, at the commit that puts it on screen (`navigation-commit.ts`).
2397
+ */
2398
+ function handleCaughtDeny(chain, error, selfKey) {
2399
+ const placement = chain ? placeDenyPage(chain, error.status, error.data, selfKey) : null;
2400
+ if (placement?.kind === "render") {
2401
+ setDenyStatus(error.status);
2402
+ return placement.element;
2403
+ }
2404
+ if (placement?.kind === "hoist") {
2405
+ setDenyStatus(error.status);
2406
+ error.owners = [placement.ownerKey];
2407
+ }
2408
+ throw error;
2409
+ }
2410
+ /**
2411
+ * Set the deny status in the request context ALS.
2412
+ * Called from AccessGate / PageDenyBoundary when a DenySignal is caught.
2413
+ * The document path reads this after render to set the HTTP status code.
2414
+ */
2415
+ function setDenyStatus(status) {
2416
+ const store = requestContextAls.getStore();
2417
+ if (store) store.denyStatus = status;
2418
+ }
2419
+ /**
2420
+ * Record the first denied segment index in the request context ALS.
2421
+ * Called from AccessGate when a DenySignal is caught during render.
2422
+ * Only the first (shallowest) denial is recorded — deeper denials are
2423
+ * unreachable because the gate short-circuits the subtree.
2424
+ * See TIM-1363.
2425
+ */
2426
+ function setFirstDeniedSegmentIndex(index) {
2427
+ const store = requestContextAls.getStore();
2428
+ if (store && store._firstDeniedSegmentIndex === void 0) store._firstDeniedSegmentIndex = index;
2429
+ }
2430
+ //#endregion
2431
+ //#region src/server/access-gate.tsx
2432
+ /**
2433
+ * Framework-injected access gate for segments.
2434
+ *
2435
+ * Calls accessFn during render — inside `renderToReadableStream`, sharing
2436
+ * the same `React.cache` scope as layouts and pages. A `requireUser()`
2437
+ * call in access.ts populates the cache; the same call in any layout is
2438
+ * a free hit. Access executes exactly once per request. See TIM-1363.
2439
+ *
2440
+ * access.ts is a pure gate — return values are discarded. The layout below
2441
+ * gets the same data by calling the same cached functions (React.cache dedup).
2442
+ *
2443
+ * On denial the gate renders the matching deny page only when this segment
2444
+ * owns it. Because the gate is wrapped OUTSIDE its own layout, that render
2445
+ * omits the denying segment's layout — deliberate, and the one place the
2446
+ * in-tree path diverges from `renderDenyPage`'s inclusive slice: a layout
2447
+ * whose access.ts denied must never run and serialize protected data into
2448
+ * the Flight stream (TIM-1074). An ancestor-owned page is hoisted instead,
2449
+ * because the gate also sits inside every layout above it and rendering
2450
+ * here would wrap the deny page in all of them (TIM-1356).
2451
+ *
2452
+ * For skipped segments (skippedSegment=true), deny pages are NOT rendered
2453
+ * in-tree — the client's cached layout chrome would wrap them incorrectly.
2454
+ * Instead, the deny is recorded in ALS and rethrown so the response path
2455
+ * can return rscErrorEnvelope for a client hard-navigate.
2456
+ */
2457
+ function AccessGate(props) {
2458
+ const { accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children } = props;
2459
+ return accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, skippedSegment ? void 0 : denyPages, skippedSegment, children);
2460
+ }
2461
+ /**
2462
+ * Calls accessFn during render with OTEL instrumentation.
2463
+ * Records the first denied segment index in ALS for post-render consumers.
2464
+ */
2465
+ async function accessGateFallback(accessFn, segmentName, segmentKey, segmentIndex, denyPages, skippedSegment, children) {
2466
+ try {
2467
+ await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
2468
+ try {
2469
+ await accessFn();
2470
+ await setSpanAttribute("timber.result", "pass");
2471
+ } catch (error) {
2472
+ if (isDenySignal(error)) {
2473
+ await setSpanAttribute("timber.result", "deny");
2474
+ await setSpanAttribute("timber.deny_status", error.status);
2475
+ if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
2476
+ } else if (isRedirectSignal(error)) await setSpanAttribute("timber.result", "redirect");
2477
+ throw error;
2478
+ }
2479
+ });
2480
+ } catch (error) {
2481
+ if (isDenySignal(error)) {
2482
+ if (segmentIndex !== void 0) setFirstDeniedSegmentIndex(segmentIndex);
2483
+ if (skippedSegment) {
2484
+ error._hardNavigate = true;
2485
+ throw error;
2486
+ }
2487
+ if (denyPages) return handleCaughtDeny(denyPages, error, segmentKey);
2488
+ }
2489
+ throw error;
2490
+ }
2491
+ return children;
2492
+ }
2493
+ /**
2494
+ * Framework-injected access gate for parallel slots.
2495
+ *
2496
+ * On denial, graceful degradation: denied.tsx → default.tsx → null.
2497
+ * The HTTP status code is unaffected — slot denial is a UI concern, not
2498
+ * a protocol concern. The parent layout and sibling slots still render.
2499
+ *
2500
+ * DeniedComponent is passed instead of a pre-built element so that
2501
+ * DenySignal.data can be forwarded as the data prop
2502
+ * and the slot name can be passed as the slot prop. See TIM-488.
2503
+ *
2504
+ * redirect() in slot access.ts is a dev-mode error — redirecting from a
2505
+ * slot doesn't make architectural sense.
2506
+ */
2507
+ async function SlotAccessGate(props) {
2508
+ const { accessFn, DeniedComponent, slotName, createElement, defaultFallback, children } = props;
2509
+ try {
2510
+ await accessFn();
2511
+ } catch (error) {
2512
+ if (isDenySignal(error)) return buildDeniedFallback(DeniedComponent, slotName, error.data, createElement) ?? defaultFallback ?? null;
2513
+ if (isRedirectSignal(error)) {
2514
+ 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.");
2515
+ return buildDeniedFallback(DeniedComponent, slotName, void 0, createElement) ?? defaultFallback ?? null;
2516
+ }
2517
+ if (isDebug()) console.warn("[timber] Unhandled error in slot access.ts. Use deny() for access control, not unhandled throws.", error);
2518
+ throw error;
2519
+ }
2520
+ return children;
2521
+ }
2522
+ /**
2523
+ * Build the denied fallback element dynamically with DenySignal data.
2524
+ * Returns null if no DeniedComponent is available.
2525
+ */
2526
+ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
2527
+ if (!DeniedComponent) return null;
2528
+ return createElement(DeniedComponent, {
2529
+ slot: slotName,
2530
+ data
2531
+ });
2532
+ }
2533
+ //#endregion
2534
+ //#region src/server/status-code-resolver.ts
2535
+ /**
2536
+ * Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
2537
+ * status-file group on a single segment. Shared by all three fallback
2538
+ * chains — the only structural difference between component 4xx,
2539
+ * component 5xx, and JSON resolution is *which* group is searched and
2540
+ * how the per-segment loop is layered around it.
2541
+ */
2542
+ function lookupInGroup(group, statusStr, categoryKey, segmentIndex, status) {
2543
+ if (!group) return null;
2544
+ const exact = group[statusStr];
2545
+ if (exact) return {
2546
+ file: exact,
2547
+ status,
2548
+ kind: "exact",
2549
+ segmentIndex
2550
+ };
2551
+ const category = group[categoryKey];
2552
+ if (category) return {
2553
+ file: category,
2554
+ status,
2555
+ kind: "category",
2556
+ segmentIndex
2557
+ };
2558
+ return null;
2559
+ }
2560
+ /**
2561
+ * Resolve the status-code file to render for a given HTTP status code.
2562
+ *
2563
+ * Walks the segment chain from leaf to root following the fallback chain
2564
+ * defined in design/10-error-handling.md. Returns null if no file is found
2565
+ * (caller should render the framework default).
2566
+ *
2567
+ * @param status - The HTTP status code (4xx or 5xx).
2568
+ * @param segments - The matched segment chain from root (index 0) to leaf (last).
2569
+ * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
2570
+ * @param maxIndex - Optional upper bound on the segment index to search.
2571
+ * When set, the resolver only considers segments `0..maxIndex` (inclusive),
2572
+ * skipping any segments deeper in the tree. Used by the deny renderers to
2573
+ * prevent resolving a status file below a denied segment — matching
2574
+ * `buildDenyPageChain`'s start-at-i semantics. The error renderers omit
2575
+ * this parameter, so the full chain is searched — a 500 from a leaf page
2576
+ * should use the leaf's own `5xx.tsx`. See TIM-1358.
2577
+ */
2578
+ function resolveStatusFile(status, segments, format = "component", maxIndex) {
2579
+ if (status < 400 || status > 599) return null;
2580
+ if (format === "json") return resolveJson(status, segments, maxIndex);
2581
+ if (status <= 499) return resolve4xx(status, segments, maxIndex);
2582
+ return resolve5xx(status, segments, maxIndex);
2583
+ }
2584
+ /**
2585
+ * 4xx component fallback chain — two separate full passes leaf→root.
2586
+ *
2587
+ * The passes must be separate (not interleaved per-segment) so that a
2588
+ * root-level `404.tsx` beats a leaf-level `error.tsx`. The 5xx chain
2589
+ * inverts this and is per-segment: a leaf's `error.tsx` beats a root's
2590
+ * `5xx.tsx`. This asymmetry is the only reason these two functions exist
2591
+ * separately.
2592
+ *
2593
+ * Pass 1 — {status}.tsx → 4xx.tsx (statusFiles)
2594
+ * Pass 2 — error.tsx (error)
2595
+ */
2596
+ function resolve4xx(status, segments, maxIndex) {
2597
+ const statusStr = String(status);
2598
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
2599
+ for (let i = start; i >= 0; i--) {
2600
+ const r = lookupInGroup(segments[i].statusFiles, statusStr, "4xx", i, status);
2601
+ if (r) return r;
2602
+ }
2603
+ for (let i = start; i >= 0; i--) {
2604
+ const errorFile = segments[i].error;
2605
+ if (errorFile) return {
2606
+ file: errorFile,
2607
+ status,
2608
+ kind: "error",
2609
+ segmentIndex: i
2610
+ };
2611
+ }
2612
+ return null;
2613
+ }
2614
+ /**
2615
+ * 5xx component fallback chain — single pass, per-segment leaf→root.
2616
+ *
2617
+ * At each segment: {status}.tsx → 5xx.tsx → error.tsx. A leaf's
2618
+ * `error.tsx` therefore beats a root's `5xx.tsx`, which is the
2619
+ * intentional inverse of the 4xx chain.
2620
+ */
2621
+ function resolve5xx(status, segments, maxIndex) {
2622
+ const statusStr = String(status);
2623
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
2624
+ for (let i = start; i >= 0; i--) {
2625
+ const segment = segments[i];
2626
+ const r = lookupInGroup(segment.statusFiles, statusStr, "5xx", i, status);
2627
+ if (r) return r;
2628
+ if (segment.error) return {
2629
+ file: segment.error,
2630
+ status,
2631
+ kind: "error",
2632
+ segmentIndex: i
2633
+ };
2634
+ }
2635
+ return null;
2636
+ }
2637
+ /**
2638
+ * JSON fallback chain (for both 4xx and 5xx) — single pass leaf→root.
2639
+ *
2640
+ * At each segment: {status}.json → {category}.json. No legacy compat,
2641
+ * no error.tsx — the JSON chain terminates at the category catch-all
2642
+ * and the caller falls back to a bare-JSON framework default.
2643
+ */
2644
+ function resolveJson(status, segments, maxIndex) {
2645
+ const statusStr = String(status);
2646
+ const categoryKey = status >= 500 ? "5xx" : "4xx";
2647
+ const start = maxIndex !== void 0 ? Math.min(segments.length - 1, maxIndex) : segments.length - 1;
2648
+ for (let i = start; i >= 0; i--) {
2649
+ const r = lookupInGroup(segments[i].jsonStatusFiles, statusStr, categoryKey, i, status);
2650
+ if (r) return r;
2651
+ }
2652
+ return null;
2653
+ }
2654
+ /**
2655
+ * Resolve the denial file for a parallel route slot.
2656
+ *
2657
+ * Slot denial is graceful degradation — no HTTP status on the wire.
2658
+ * Fallback chain: denied.tsx → default.tsx → null.
2659
+ *
2660
+ * @param slotNode - The segment node for the slot (segmentType === 'slot').
2661
+ */
2662
+ function resolveSlotDenied(slotNode) {
2663
+ const slotName = slotNode.segmentName.replace(/^@/, "");
2664
+ if (slotNode.denied) return {
2665
+ file: slotNode.denied,
2666
+ slotName,
2667
+ kind: "denied"
2668
+ };
2669
+ if (slotNode.default) return {
2670
+ file: slotNode.default,
2671
+ slotName,
2672
+ kind: "default"
2673
+ };
2674
+ return null;
2675
+ }
2676
+ //#endregion
2677
+ //#region src/server/body-limits.ts
2678
+ var KB = 1024;
2679
+ var MB = 1024 * KB;
2680
+ var GB = 1024 * MB;
2681
+ var DEFAULT_LIMITS = {
2682
+ actionBodySize: 1 * MB,
2683
+ uploadBodySize: 10 * MB,
2684
+ maxFields: 100
2685
+ };
2686
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2687
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2688
+ function parseBodySize(size) {
2689
+ const match = SIZE_PATTERN.exec(size.trim());
2690
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2691
+ const value = Number.parseFloat(match[1]);
2692
+ const unit = (match[2] ?? "").toLowerCase();
2693
+ switch (unit) {
2694
+ case "kb": return Math.floor(value * KB);
2695
+ case "mb": return Math.floor(value * MB);
2696
+ case "gb": return Math.floor(value * GB);
2697
+ case "": return Math.floor(value);
2698
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2699
+ }
2700
+ }
2701
+ /** Strict integer pattern: one or more digits, nothing else. */
2702
+ var STRICT_INTEGER_RE = /^\d+$/;
2703
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2704
+ function enforceBodyLimits(req, kind, config) {
2705
+ const contentLength = req.headers.get("Content-Length");
2706
+ if (!contentLength) return {
2707
+ ok: false,
2708
+ status: 411
2709
+ };
2710
+ const trimmed = contentLength.trim();
2711
+ if (!STRICT_INTEGER_RE.test(trimmed)) return {
2712
+ ok: false,
2713
+ status: 411
2714
+ };
2715
+ return Number.parseInt(trimmed, 10) <= resolveLimit(kind, config) ? { ok: true } : {
2716
+ ok: false,
2717
+ status: 413
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2722
+ */
2723
+ function resolveLimit(kind, config) {
2724
+ const userLimits = config.limits;
2725
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2726
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2727
+ }
2728
+ //#endregion
2729
+ //#region src/server/metadata-social.ts
2730
+ /**
2731
+ * Render Open Graph metadata into head element descriptors.
2732
+ *
2733
+ * Handles og:title, og:description, og:image (with dimensions/alt),
2734
+ * og:video, og:audio, og:article:author, and other OG properties.
2735
+ */
2736
+ function renderOpenGraph(og, elements) {
2737
+ const simpleProps = [
2738
+ ["og:title", og.title],
2739
+ ["og:description", og.description],
2740
+ ["og:url", og.url],
2741
+ ["og:site_name", og.siteName],
2742
+ ["og:locale", og.locale],
2743
+ ["og:type", og.type],
2744
+ ["og:article:published_time", og.publishedTime],
2745
+ ["og:article:modified_time", og.modifiedTime]
2746
+ ];
2747
+ for (const [property, content] of simpleProps) if (content) elements.push({
2748
+ tag: "meta",
2749
+ attrs: {
2750
+ property,
2751
+ content
2752
+ }
2753
+ });
2754
+ if (og.images) {
2755
+ if (typeof og.images === "string") elements.push({
2756
+ tag: "meta",
2757
+ attrs: {
2758
+ property: "og:image",
2759
+ content: og.images
2760
+ }
2761
+ });
2762
+ else {
2763
+ const imgList = Array.isArray(og.images) ? og.images : [og.images];
2764
+ for (const img of imgList) {
2765
+ elements.push({
2766
+ tag: "meta",
2767
+ attrs: {
2768
+ property: "og:image",
2769
+ content: img.url
2770
+ }
2771
+ });
2772
+ if (img.width) elements.push({
2773
+ tag: "meta",
2774
+ attrs: {
2775
+ property: "og:image:width",
2776
+ content: String(img.width)
2777
+ }
2778
+ });
2779
+ if (img.height) elements.push({
2780
+ tag: "meta",
2781
+ attrs: {
2782
+ property: "og:image:height",
2783
+ content: String(img.height)
2784
+ }
2785
+ });
2786
+ if (img.alt) elements.push({
2787
+ tag: "meta",
2788
+ attrs: {
2789
+ property: "og:image:alt",
2790
+ content: img.alt
2791
+ }
2792
+ });
2793
+ }
2794
+ }
2795
+ }
2796
+ if (og.videos) for (const video of og.videos) elements.push({
2797
+ tag: "meta",
2798
+ attrs: {
2799
+ property: "og:video",
2800
+ content: video.url
2801
+ }
2802
+ });
2803
+ if (og.audio) for (const audio of og.audio) elements.push({
2804
+ tag: "meta",
2805
+ attrs: {
2806
+ property: "og:audio",
2807
+ content: audio.url
2808
+ }
2809
+ });
2810
+ if (og.authors) for (const author of og.authors) elements.push({
2811
+ tag: "meta",
2812
+ attrs: {
2813
+ property: "og:article:author",
2814
+ content: author
2815
+ }
2816
+ });
2817
+ }
2818
+ /**
2819
+ * Render Twitter Card metadata into head element descriptors.
2820
+ *
2821
+ * Handles twitter:card, twitter:site, twitter:title, twitter:image,
2822
+ * twitter:player, and twitter:app (per-platform name/id/url).
2823
+ */
2824
+ function renderTwitter(tw, elements) {
2825
+ const simpleProps = [
2826
+ ["twitter:card", tw.card],
2827
+ ["twitter:site", tw.site],
2828
+ ["twitter:site:id", tw.siteId],
2829
+ ["twitter:title", tw.title],
2830
+ ["twitter:description", tw.description],
2831
+ ["twitter:creator", tw.creator],
2832
+ ["twitter:creator:id", tw.creatorId]
2833
+ ];
2834
+ for (const [name, content] of simpleProps) if (content) elements.push({
2835
+ tag: "meta",
2836
+ attrs: {
2837
+ name,
2838
+ content
2839
+ }
2840
+ });
2841
+ if (tw.images) {
2842
+ if (typeof tw.images === "string") elements.push({
2843
+ tag: "meta",
2844
+ attrs: {
2845
+ name: "twitter:image",
2846
+ content: tw.images
2847
+ }
2848
+ });
2849
+ else {
2850
+ const imgList = Array.isArray(tw.images) ? tw.images : [tw.images];
2851
+ for (const img of imgList) {
2852
+ const url = typeof img === "string" ? img : img.url;
2853
+ elements.push({
2854
+ tag: "meta",
2855
+ attrs: {
2856
+ name: "twitter:image",
2857
+ content: url
2858
+ }
2859
+ });
2860
+ }
2861
+ }
2862
+ }
2863
+ if (tw.players) for (const player of tw.players) {
2864
+ elements.push({
2865
+ tag: "meta",
2866
+ attrs: {
2867
+ name: "twitter:player",
2868
+ content: player.playerUrl
2869
+ }
2870
+ });
2871
+ if (player.width) elements.push({
2872
+ tag: "meta",
2873
+ attrs: {
2874
+ name: "twitter:player:width",
2875
+ content: String(player.width)
2876
+ }
2877
+ });
2878
+ if (player.height) elements.push({
2879
+ tag: "meta",
2880
+ attrs: {
2881
+ name: "twitter:player:height",
2882
+ content: String(player.height)
2883
+ }
2884
+ });
2885
+ if (player.streamUrl) elements.push({
2886
+ tag: "meta",
2887
+ attrs: {
2888
+ name: "twitter:player:stream",
2889
+ content: player.streamUrl
2890
+ }
2891
+ });
2892
+ }
2893
+ if (tw.app) {
2894
+ const platforms = [
2895
+ ["iPhone", "iphone"],
2896
+ ["iPad", "ipad"],
2897
+ ["googlePlay", "googleplay"]
2898
+ ];
2899
+ if (tw.app.name) {
2900
+ for (const [key, tag] of platforms) if (tw.app.id?.[key]) elements.push({
2901
+ tag: "meta",
2902
+ attrs: {
2903
+ name: `twitter:app:name:${tag}`,
2904
+ content: tw.app.name
2905
+ }
2906
+ });
2907
+ }
2908
+ for (const [key, tag] of platforms) {
2909
+ const id = tw.app.id?.[key];
2910
+ if (id) elements.push({
2911
+ tag: "meta",
2912
+ attrs: {
2913
+ name: `twitter:app:id:${tag}`,
2914
+ content: id
2915
+ }
2916
+ });
2917
+ }
2918
+ for (const [key, tag] of platforms) {
2919
+ const url = tw.app.url?.[key];
2920
+ if (url) elements.push({
2921
+ tag: "meta",
2922
+ attrs: {
2923
+ name: `twitter:app:url:${tag}`,
2924
+ content: url
2925
+ }
2926
+ });
2927
+ }
2928
+ }
2929
+ }
2930
+ //#endregion
2931
+ //#region src/server/metadata-platform.ts
2932
+ /**
2933
+ * Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
2934
+ */
2935
+ function renderIcons(icons, elements) {
2936
+ if (icons.icon) {
2937
+ if (typeof icons.icon === "string") elements.push({
2938
+ tag: "link",
2939
+ attrs: {
2940
+ rel: "icon",
2941
+ href: icons.icon
2942
+ }
2943
+ });
2944
+ else if (Array.isArray(icons.icon)) for (const icon of icons.icon) {
2945
+ const attrs = {
2946
+ rel: "icon",
2947
+ href: icon.url
2948
+ };
2949
+ if (icon.sizes) attrs.sizes = icon.sizes;
2950
+ if (icon.type) attrs.type = icon.type;
2951
+ elements.push({
2952
+ tag: "link",
2953
+ attrs
2954
+ });
2955
+ }
2956
+ }
2957
+ if (icons.shortcut) {
2958
+ const urls = Array.isArray(icons.shortcut) ? icons.shortcut : [icons.shortcut];
2959
+ for (const url of urls) elements.push({
2960
+ tag: "link",
2961
+ attrs: {
2962
+ rel: "shortcut icon",
2963
+ href: url
2964
+ }
2965
+ });
2966
+ }
2967
+ if (icons.apple) {
2968
+ if (typeof icons.apple === "string") elements.push({
2969
+ tag: "link",
2970
+ attrs: {
2971
+ rel: "apple-touch-icon",
2972
+ href: icons.apple
2973
+ }
2974
+ });
2975
+ else if (Array.isArray(icons.apple)) for (const icon of icons.apple) {
2976
+ const attrs = {
2977
+ rel: "apple-touch-icon",
2978
+ href: icon.url
2979
+ };
2980
+ if (icon.sizes) attrs.sizes = icon.sizes;
2981
+ elements.push({
2982
+ tag: "link",
2983
+ attrs
2984
+ });
2985
+ }
2986
+ }
2987
+ if (icons.other) for (const icon of icons.other) {
2988
+ const attrs = {
2989
+ rel: icon.rel,
2990
+ href: icon.url
2991
+ };
2992
+ if (icon.sizes) attrs.sizes = icon.sizes;
2993
+ if (icon.type) attrs.type = icon.type;
2994
+ elements.push({
2995
+ tag: "link",
2996
+ attrs
2997
+ });
2998
+ }
2999
+ }
3000
+ /**
3001
+ * Render alternate link elements (canonical, hreflang, media, types).
3002
+ */
3003
+ function renderAlternates(alternates, elements) {
3004
+ if (alternates.canonical) elements.push({
3005
+ tag: "link",
3006
+ attrs: {
3007
+ rel: "canonical",
3008
+ href: alternates.canonical
3009
+ }
3010
+ });
3011
+ if (alternates.languages) for (const [lang, href] of Object.entries(alternates.languages)) elements.push({
3012
+ tag: "link",
3013
+ attrs: {
3014
+ rel: "alternate",
3015
+ hreflang: lang,
3016
+ href
3017
+ }
3018
+ });
3019
+ if (alternates.media) for (const [media, href] of Object.entries(alternates.media)) elements.push({
3020
+ tag: "link",
3021
+ attrs: {
3022
+ rel: "alternate",
3023
+ media,
3024
+ href
3025
+ }
3026
+ });
3027
+ if (alternates.types) for (const [type, href] of Object.entries(alternates.types)) elements.push({
3028
+ tag: "link",
3029
+ attrs: {
3030
+ rel: "alternate",
3031
+ type,
3032
+ href
3033
+ }
3034
+ });
3035
+ }
3036
+ /**
3037
+ * Render site verification meta tags (Google, Yahoo, Yandex, custom).
3038
+ */
3039
+ function renderVerification(verification, elements) {
3040
+ const verificationProps = [
3041
+ ["google-site-verification", verification.google],
3042
+ ["y_key", verification.yahoo],
3043
+ ["yandex-verification", verification.yandex]
3044
+ ];
3045
+ for (const [name, content] of verificationProps) if (content) elements.push({
3046
+ tag: "meta",
3047
+ attrs: {
3048
+ name,
3049
+ content
3050
+ }
3051
+ });
3052
+ if (verification.other) for (const [name, value] of Object.entries(verification.other)) {
3053
+ const content = Array.isArray(value) ? value.join(", ") : value;
3054
+ elements.push({
3055
+ tag: "meta",
3056
+ attrs: {
3057
+ name,
3058
+ content
3059
+ }
3060
+ });
3061
+ }
3062
+ }
3063
+ /**
3064
+ * Render Apple Web App meta tags and startup image links.
3065
+ */
3066
+ function renderAppleWebApp(appleWebApp, elements) {
3067
+ if (appleWebApp.capable) elements.push({
3068
+ tag: "meta",
3069
+ attrs: {
3070
+ name: "apple-mobile-web-app-capable",
3071
+ content: "yes"
3072
+ }
3073
+ });
3074
+ if (appleWebApp.title) elements.push({
3075
+ tag: "meta",
3076
+ attrs: {
3077
+ name: "apple-mobile-web-app-title",
3078
+ content: appleWebApp.title
3079
+ }
3080
+ });
3081
+ if (appleWebApp.statusBarStyle) elements.push({
3082
+ tag: "meta",
3083
+ attrs: {
3084
+ name: "apple-mobile-web-app-status-bar-style",
3085
+ content: appleWebApp.statusBarStyle
3086
+ }
3087
+ });
3088
+ if (appleWebApp.startupImage) {
3089
+ const images = Array.isArray(appleWebApp.startupImage) ? appleWebApp.startupImage : [{ url: appleWebApp.startupImage }];
3090
+ for (const img of images) {
3091
+ const attrs = {
3092
+ rel: "apple-touch-startup-image",
3093
+ href: typeof img === "string" ? img : img.url
3094
+ };
3095
+ if (typeof img === "object" && img.media) attrs.media = img.media;
3096
+ elements.push({
3097
+ tag: "link",
3098
+ attrs
3099
+ });
3100
+ }
3101
+ }
3102
+ }
3103
+ /**
3104
+ * Render App Links (al:*) meta tags for deep linking across platforms.
3105
+ */
3106
+ function renderAppLinks(appLinks, elements) {
3107
+ const platformEntries = [
3108
+ ["ios", appLinks.ios],
3109
+ ["android", appLinks.android],
3110
+ ["windows", appLinks.windows],
3111
+ ["windows_phone", appLinks.windowsPhone],
3112
+ ["windows_universal", appLinks.windowsUniversal]
3113
+ ];
3114
+ for (const [platform, entries] of platformEntries) {
3115
+ if (!entries) continue;
3116
+ for (const entry of entries) for (const [key, value] of Object.entries(entry)) if (value !== void 0 && value !== null) elements.push({
3117
+ tag: "meta",
3118
+ attrs: {
3119
+ property: `al:${platform}:${key}`,
3120
+ content: String(value)
3121
+ }
3122
+ });
3123
+ }
3124
+ if (appLinks.web) {
3125
+ if (appLinks.web.url) elements.push({
3126
+ tag: "meta",
3127
+ attrs: {
3128
+ property: "al:web:url",
3129
+ content: appLinks.web.url
3130
+ }
3131
+ });
3132
+ if (appLinks.web.shouldFallback !== void 0) elements.push({
3133
+ tag: "meta",
3134
+ attrs: {
3135
+ property: "al:web:should_fallback",
3136
+ content: appLinks.web.shouldFallback ? "true" : "false"
3137
+ }
3138
+ });
3139
+ }
3140
+ }
3141
+ /**
3142
+ * Render Apple iTunes smart banner meta tag.
3143
+ */
3144
+ function renderItunes(itunes, elements) {
3145
+ const parts = [`app-id=${itunes.appId}`];
3146
+ if (itunes.affiliateData) parts.push(`affiliate-data=${itunes.affiliateData}`);
3147
+ if (itunes.appArgument) parts.push(`app-argument=${itunes.appArgument}`);
3148
+ elements.push({
3149
+ tag: "meta",
3150
+ attrs: {
3151
+ name: "apple-itunes-app",
3152
+ content: parts.join(", ")
3153
+ }
3154
+ });
3155
+ }
3156
+ //#endregion
3157
+ //#region src/server/metadata-render.ts
3158
+ /**
3159
+ * Convert resolved metadata into an array of head element descriptors.
3160
+ *
3161
+ * Each descriptor has a `tag` ('title', 'meta', 'link') and either
3162
+ * `content` (for <title>) or `attrs` (for <meta>/<link>).
3163
+ *
3164
+ * The framework's MetadataResolver component consumes these descriptors
3165
+ * and renders them into the <head>.
3166
+ */
3167
+ function renderMetadataToElements(metadata) {
3168
+ const elements = [];
3169
+ if (typeof metadata.title === "string") elements.push({
3170
+ tag: "title",
3171
+ content: metadata.title
3172
+ });
3173
+ const simpleMetaProps = [
3174
+ ["description", metadata.description],
3175
+ ["generator", metadata.generator],
3176
+ ["application-name", metadata.applicationName],
3177
+ ["referrer", metadata.referrer],
3178
+ ["category", metadata.category],
3179
+ ["creator", metadata.creator],
3180
+ ["publisher", metadata.publisher]
3181
+ ];
3182
+ for (const [name, content] of simpleMetaProps) if (content) elements.push({
3183
+ tag: "meta",
3184
+ attrs: {
3185
+ name,
3186
+ content
3187
+ }
3188
+ });
3189
+ if (metadata.keywords) {
3190
+ const content = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
3191
+ elements.push({
3192
+ tag: "meta",
3193
+ attrs: {
3194
+ name: "keywords",
3195
+ content
3196
+ }
3197
+ });
3198
+ }
3199
+ if (metadata.robots) {
3200
+ const content = typeof metadata.robots === "string" ? metadata.robots : renderRobotsObject(metadata.robots);
3201
+ elements.push({
3202
+ tag: "meta",
3203
+ attrs: {
3204
+ name: "robots",
3205
+ content
3206
+ }
3207
+ });
3208
+ if (typeof metadata.robots === "object" && metadata.robots.googleBot) {
3209
+ const gbContent = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : renderRobotsObject(metadata.robots.googleBot);
3210
+ elements.push({
3211
+ tag: "meta",
3212
+ attrs: {
3213
+ name: "googlebot",
3214
+ content: gbContent
3215
+ }
3216
+ });
3217
+ }
3218
+ }
3219
+ if (metadata.openGraph) {
3220
+ const og = { ...metadata.openGraph };
3221
+ if (og.title === void 0 && typeof metadata.title === "string") og.title = metadata.title;
3222
+ if (og.description === void 0 && metadata.description) og.description = metadata.description;
3223
+ renderOpenGraph(og, elements);
3224
+ }
3225
+ if (metadata.twitter) {
3226
+ const tw = { ...metadata.twitter };
3227
+ if (tw.title === void 0) tw.title = metadata.openGraph?.title !== void 0 ? metadata.openGraph.title : typeof metadata.title === "string" ? metadata.title : void 0;
3228
+ if (tw.description === void 0) tw.description = metadata.openGraph?.description !== void 0 ? metadata.openGraph.description : metadata.description;
3229
+ renderTwitter(tw, elements);
3230
+ }
3231
+ if (metadata.icons) renderIcons(metadata.icons, elements);
3232
+ if (metadata.manifest) elements.push({
3233
+ tag: "link",
3234
+ attrs: {
3235
+ rel: "manifest",
3236
+ href: metadata.manifest
3237
+ }
3238
+ });
3239
+ if (metadata.alternates) renderAlternates(metadata.alternates, elements);
3240
+ if (metadata.verification) renderVerification(metadata.verification, elements);
3241
+ if (metadata.formatDetection) {
3242
+ const parts = [];
3243
+ if (metadata.formatDetection.telephone === false) parts.push("telephone=no");
3244
+ if (metadata.formatDetection.email === false) parts.push("email=no");
3245
+ if (metadata.formatDetection.address === false) parts.push("address=no");
3246
+ if (parts.length > 0) elements.push({
3247
+ tag: "meta",
3248
+ attrs: {
3249
+ name: "format-detection",
3250
+ content: parts.join(", ")
3251
+ }
3252
+ });
3253
+ }
3254
+ if (metadata.authors) {
3255
+ const authorList = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
3256
+ for (const author of authorList) {
3257
+ if (author.name) elements.push({
3258
+ tag: "meta",
3259
+ attrs: {
3260
+ name: "author",
3261
+ content: author.name
3262
+ }
3263
+ });
3264
+ if (author.url) elements.push({
3265
+ tag: "link",
3266
+ attrs: {
3267
+ rel: "author",
3268
+ href: author.url
3269
+ }
3270
+ });
3271
+ }
3272
+ }
3273
+ if (metadata.appleWebApp) renderAppleWebApp(metadata.appleWebApp, elements);
3274
+ if (metadata.appLinks) renderAppLinks(metadata.appLinks, elements);
3275
+ if (metadata.itunes) renderItunes(metadata.itunes, elements);
3276
+ if (metadata.other) for (const [name, value] of Object.entries(metadata.other)) {
3277
+ const content = Array.isArray(value) ? value.join(", ") : value;
3278
+ elements.push({
3279
+ tag: "meta",
3280
+ attrs: {
3281
+ name,
3282
+ content
3283
+ }
3284
+ });
3285
+ }
3286
+ return elements;
3287
+ }
3288
+ function renderRobotsObject(robots) {
3289
+ const parts = [];
3290
+ if (robots.index === true) parts.push("index");
3291
+ if (robots.index === false) parts.push("noindex");
3292
+ if (robots.follow === true) parts.push("follow");
3293
+ if (robots.follow === false) parts.push("nofollow");
3294
+ return parts.join(", ");
3295
+ }
3296
+ //#endregion
3297
+ //#region src/server/metadata.ts
3298
+ /**
3299
+ * Resolve a title value with an optional template.
3300
+ *
3301
+ * - string → apply template if present
3302
+ * - { absolute: '...' } → use as-is, skip template
3303
+ * - { default: '...' } → use as fallback (no template applied)
3304
+ * - undefined → undefined
3305
+ */
3306
+ function resolveTitle(title, template) {
3307
+ if (title === void 0 || title === null) return;
3308
+ if (typeof title === "string") return template ? template.replace("%s", title) : title;
3309
+ if (title.absolute !== void 0) return title.absolute;
3310
+ if (title.default !== void 0) return title.default;
3311
+ }
3312
+ /**
3313
+ * Resolve metadata from a segment chain.
3314
+ *
3315
+ * Processes entries from root layout to page (in segment order).
3316
+ * The merge algorithm:
3317
+ * 1. Shallow-merge all keys except title (later wins)
3318
+ * 2. Track the most recent title template
3319
+ * 3. Resolve the final title using the template
3320
+ *
3321
+ * In error state, the page entry is dropped and noindex is injected.
3322
+ *
3323
+ * See design/16-metadata.md §"Merge Algorithm"
3324
+ */
3325
+ function resolveMetadata(entries, options = {}) {
3326
+ const { errorState = false } = options;
3327
+ const merged = {};
3328
+ let titleTemplate;
3329
+ let lastDefault;
3330
+ let rawTitle;
3331
+ for (const { metadata, isPage } of entries) {
3332
+ if (errorState && isPage) continue;
3333
+ if (metadata.title !== void 0 && typeof metadata.title === "object") {
3334
+ if (metadata.title.template !== void 0) titleTemplate = metadata.title.template;
3335
+ if (metadata.title.default !== void 0) lastDefault = metadata.title.default;
3336
+ }
3337
+ for (const key of Object.keys(metadata)) {
3338
+ if (key === "title") continue;
3339
+ merged[key] = metadata[key];
3340
+ }
3341
+ if (metadata.title !== void 0) rawTitle = metadata.title;
3342
+ }
3343
+ if (errorState) {
3344
+ rawTitle = lastDefault !== void 0 ? { default: lastDefault } : rawTitle;
3345
+ titleTemplate = void 0;
3346
+ }
3347
+ const resolvedTitle = resolveTitle(rawTitle, titleTemplate);
3348
+ if (resolvedTitle !== void 0) merged.title = resolvedTitle;
3349
+ if (errorState) merged.robots = "noindex";
3350
+ return merged;
3351
+ }
3352
+ /**
3353
+ * Check if a string is an absolute URL.
3354
+ */
3355
+ function isAbsoluteUrl(url) {
3356
+ return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
3357
+ }
3358
+ /**
3359
+ * Resolve a relative URL against a base URL.
3360
+ */
3361
+ function resolveUrl(url, base) {
3362
+ if (isAbsoluteUrl(url)) return url;
3363
+ return new URL(url, base).toString();
3364
+ }
3365
+ /**
3366
+ * Resolve relative URLs in metadata fields against metadataBase.
3367
+ *
3368
+ * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
3369
+ * If metadataBase is not set, returns the metadata unchanged.
3370
+ */
3371
+ function resolveMetadataUrls(metadata) {
3372
+ const base = metadata.metadataBase;
3373
+ if (!base) return metadata;
3374
+ const result = { ...metadata };
3375
+ if (result.openGraph) {
3376
+ result.openGraph = { ...result.openGraph };
3377
+ if (typeof result.openGraph.images === "string") result.openGraph.images = resolveUrl(result.openGraph.images, base);
3378
+ else if (Array.isArray(result.openGraph.images)) result.openGraph.images = result.openGraph.images.map((img) => ({
3379
+ ...img,
3380
+ url: resolveUrl(img.url, base)
3381
+ }));
3382
+ else if (result.openGraph.images) result.openGraph.images = {
3383
+ ...result.openGraph.images,
3384
+ url: resolveUrl(result.openGraph.images.url, base)
3385
+ };
3386
+ if (result.openGraph.url && !isAbsoluteUrl(result.openGraph.url)) result.openGraph.url = resolveUrl(result.openGraph.url, base);
3387
+ }
3388
+ if (result.twitter) {
3389
+ result.twitter = { ...result.twitter };
3390
+ if (typeof result.twitter.images === "string") result.twitter.images = resolveUrl(result.twitter.images, base);
3391
+ else if (Array.isArray(result.twitter.images)) {
3392
+ const resolved = result.twitter.images.map((img) => typeof img === "string" ? resolveUrl(img, base) : {
3393
+ ...img,
3394
+ url: resolveUrl(img.url, base)
3395
+ });
3396
+ const allStrings = resolved.every((r) => typeof r === "string");
3397
+ result.twitter.images = allStrings ? resolved : resolved;
3398
+ } else if (result.twitter.images) result.twitter.images = {
3399
+ ...result.twitter.images,
3400
+ url: resolveUrl(result.twitter.images.url, base)
3401
+ };
3402
+ }
3403
+ if (result.alternates) {
3404
+ result.alternates = { ...result.alternates };
3405
+ if (result.alternates.canonical && !isAbsoluteUrl(result.alternates.canonical)) result.alternates.canonical = resolveUrl(result.alternates.canonical, base);
3406
+ if (result.alternates.languages) {
3407
+ const langs = {};
3408
+ for (const [lang, url] of Object.entries(result.alternates.languages)) langs[lang] = isAbsoluteUrl(url) ? url : resolveUrl(url, base);
3409
+ result.alternates.languages = langs;
3410
+ }
3411
+ }
3412
+ if (result.icons) {
3413
+ result.icons = { ...result.icons };
3414
+ if (typeof result.icons.icon === "string") result.icons.icon = resolveUrl(result.icons.icon, base);
3415
+ else if (Array.isArray(result.icons.icon)) result.icons.icon = result.icons.icon.map((i) => ({
3416
+ ...i,
3417
+ url: resolveUrl(i.url, base)
3418
+ }));
3419
+ if (typeof result.icons.apple === "string") result.icons.apple = resolveUrl(result.icons.apple, base);
3420
+ else if (Array.isArray(result.icons.apple)) result.icons.apple = result.icons.apple.map((i) => ({
3421
+ ...i,
3422
+ url: resolveUrl(i.url, base)
3423
+ }));
3424
+ }
3425
+ return result;
3426
+ }
3427
+ //#endregion
3428
+ //#region src/server/route-handler.ts
3429
+ /** All recognized HTTP method export names. */
3430
+ var HTTP_METHODS = [
3431
+ "GET",
3432
+ "POST",
3433
+ "PUT",
3434
+ "PATCH",
3435
+ "DELETE",
3436
+ "HEAD",
3437
+ "OPTIONS"
3438
+ ];
3439
+ /**
3440
+ * Resolve the full list of allowed methods for a route module.
3441
+ *
3442
+ * Includes:
3443
+ * - All explicitly exported methods
3444
+ * - HEAD (implicit when GET is exported)
3445
+ * - OPTIONS (always implicit)
3446
+ */
3447
+ function resolveAllowedMethods(mod) {
3448
+ const methods = [];
3449
+ for (const method of HTTP_METHODS) {
3450
+ if (method === "HEAD" || method === "OPTIONS") continue;
3451
+ if (mod[method]) methods.push(method);
3452
+ }
3453
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
3454
+ else if (mod.HEAD) methods.push("HEAD");
3455
+ if (!mod.OPTIONS) methods.push("OPTIONS");
3456
+ else methods.push("OPTIONS");
3457
+ return methods;
3458
+ }
3459
+ /**
3460
+ * Handle an incoming request against a route.ts module.
3461
+ *
3462
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
3463
+ * and merges response headers from ctx.headers.
3464
+ */
3465
+ async function handleRouteRequest(mod, ctx) {
3466
+ const method = ctx.req.method.toUpperCase();
3467
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
3468
+ if (method === "OPTIONS") {
3469
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
3470
+ return mergeResponseHeaders(new Response(null, {
3471
+ status: 204,
3472
+ headers: { Allow: allowHeader }
3473
+ }), ctx.headers);
3474
+ }
3475
+ if (method === "HEAD") {
3476
+ if (mod.HEAD) return stripHeadBody(await runHandler(mod.HEAD, ctx), method);
3477
+ if (mod.GET) return stripHeadBody(await runHandler(mod.GET, ctx), method);
3478
+ }
3479
+ const handler = mod[method];
3480
+ if (!handler) return mergeResponseHeaders(new Response(null, {
3481
+ status: 405,
3482
+ headers: { Allow: allowHeader }
3483
+ }), ctx.headers);
3484
+ return runHandler(handler, ctx);
3485
+ }
3486
+ /**
3487
+ * Run a handler with cookie writes enabled and merge ctx.headers into its
3488
+ * response.
3489
+ *
3490
+ * Cookies (design/29-cookies.md §"Where Cookies Can Be Set"): the render
3491
+ * phase applied the jar to `ctx.headers` before the handler ran, so on the
3492
+ * way out only what the handler changed is synced onto that bag. It happens
3493
+ * whether the handler returns or throws, so a cookie set before `redirect()`
3494
+ * rides the redirect, and the pipeline's 500 for a throw carries the same
3495
+ * bag.
3496
+ *
3497
+ * Nothing is caught. A signal goes to the pipeline, whose deny fallback
3498
+ * answers a route.ts match in JSON and whose redirect outcome sends the 3xx
3499
+ * (TIM-1533). Any other error goes to the pipeline, which logs it,
3500
+ * reports it to `onRequestError` as phase `'route'`, and answers it in the
3501
+ * same format as every other route.ts error (TIM-1537).
3502
+ */
3503
+ async function runHandler(handler, ctx) {
3504
+ const applied = getSetCookieHeaders();
3505
+ setMutableCookieContext(true);
3506
+ let res;
3507
+ try {
3508
+ res = await handler(ctx);
3509
+ } finally {
3510
+ setMutableCookieContext(false);
3511
+ syncCookieJar(ctx.headers, applied);
3512
+ }
3513
+ return mergeResponseHeaders(res, ctx.headers);
3514
+ }
3515
+ /**
3516
+ * Merge response headers from ctx.headers into the handler's response.
3517
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
3518
+ * Handler-set headers take precedence over ctx.headers.
3519
+ */
3520
+ function mergeResponseHeaders(res, ctxHeaders) {
3521
+ let hasCtxHeaders = false;
3522
+ ctxHeaders.forEach(() => {
3523
+ hasCtxHeaders = true;
3524
+ });
3525
+ if (!hasCtxHeaders) return res;
3526
+ const merged = new Headers();
3527
+ ctxHeaders.forEach((value, key) => {
3528
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
3529
+ else merged.set(key, value);
3530
+ });
3531
+ const resCookies = res.headers.getSetCookie();
3532
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
3533
+ res.headers.forEach((value, key) => {
3534
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
3535
+ });
3536
+ return new Response(res.body, {
3537
+ status: res.status,
3538
+ statusText: res.statusText,
3539
+ headers: merged
3540
+ });
3541
+ }
3542
+ //#endregion
3543
+ //#region src/server/prebuilt/cache-key.ts
3544
+ /**
3545
+ * Component cache-key hashing for prebuilt (cache.component) entries.
3546
+ *
3547
+ * Key: `sha256(canonicalJson({ props, params })).slice(0, 16)` — see
3548
+ * design/44-render-at-build-time.md §Cache Key. Both the request-time
3549
+ * lookup (prebuilt-runtime.ts) and the post-build capture pass (TIM-1119)
3550
+ * MUST use this exact function, or build artifacts become unaddressable.
3551
+ *
3552
+ * THE IDENTITY CONTRACT (design/44 §Cache Key): cache identity is **JSON
3553
+ * value semantics** — two inputs are the same entry iff they are the same
3554
+ * JSON value. This is an ALLOWLIST, not a denylist: a value participates
3555
+ * in caching iff it is plain JSON data — null, boolean, finite number,
3556
+ * string, dense array, or a plain `Object.prototype` object with only
3557
+ * enumerable string-keyed data properties — plus `undefined` and `-0`,
3558
+ * which hash as distinct sentinels because flight preserves them. Every
3559
+ * value outside that domain (functions, symbols, bigints, accessors,
3560
+ * hidden or symbol-keyed properties, non-`Object.prototype` prototypes
3561
+ * including null, aliased references, sparse arrays, cycles, non-finite
3562
+ * numbers) is UNKEYABLE by definition: `computeComponentCacheKey` returns
3563
+ * null and the caller renders live — slower, never wrong.
3564
+ *
3565
+ * The line between rejected and declared-out-of-domain: values are
3566
+ * REJECTED when the JSON projection itself would be ambiguous or lossy
3567
+ * (hidden/symbol/non-enumerable properties, accessors, exotic
3568
+ * prototypes). Observable state that leaves the projection intact — key
3569
+ * order, reference identity, descriptor metadata (writable/configurable,
3570
+ * frozen/sealed/extensible), proxy behavior — is DECLARED outside
3571
+ * cache.component's supported input domain rather than rejected:
3572
+ * key-order insensitivity is required for determinism, and rejecting
3573
+ * frozen objects would unkey ubiquitous legitimate inputs
3574
+ * (Object.freeze'd config props) to defend against components that
3575
+ * render differently based on property attributes.
3576
+ *
3577
+ * Two hard rules for this walk itself: it must be TOTAL (never throw
3578
+ * anything but UnkeyableValueError) and SIDE-EFFECT-FREE (descriptor
3579
+ * reads only; never invoke user code such as getters).
3580
+ *
3581
+ * Object keys sort recursively so `{a, b}` and `{b, a}` hash identically
3582
+ * (design/13-security.md checklist #14 — cache key determinism; key order
3583
+ * is deliberately NOT part of identity).
3584
+ */
3585
+ var UnkeyableValueError = class extends Error {};
3586
+ function canonicalize$1(value, seen) {
3587
+ if (value === null) return "null";
3588
+ switch (typeof value) {
3589
+ case "string": return JSON.stringify(value);
3590
+ case "boolean": return value ? "true" : "false";
3591
+ case "number":
3592
+ if (!Number.isFinite(value)) throw new UnkeyableValueError("non-finite number");
3593
+ return Object.is(value, -0) ? "-0" : String(value);
3594
+ case "object": break;
3595
+ case "undefined": return "undefined";
3596
+ default: throw new UnkeyableValueError(`unsupported type: ${typeof value}`);
3597
+ }
3598
+ const obj = value;
3599
+ if (seen.has(obj)) throw new UnkeyableValueError("repeated object reference (cycle or alias)");
3600
+ seen.add(obj);
3601
+ if (Object.getOwnPropertySymbols(obj).length > 0) throw new UnkeyableValueError("symbol-keyed property");
3602
+ {
3603
+ if (Array.isArray(obj)) {
3604
+ if (Object.getOwnPropertyNames(obj).length !== obj.length + 1) throw new UnkeyableValueError("non-index array property");
3605
+ const parts = [];
3606
+ for (let i = 0; i < obj.length; i++) {
3607
+ const desc = Object.getOwnPropertyDescriptor(obj, i);
3608
+ if (desc === void 0) throw new UnkeyableValueError("sparse array hole");
3609
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3610
+ if (!desc.enumerable) throw new UnkeyableValueError("non-enumerable array element");
3611
+ parts.push(canonicalize$1(desc.value, seen));
3612
+ }
3613
+ return "[" + parts.join(",") + "]";
3614
+ }
3615
+ if (Object.getPrototypeOf(obj) !== Object.prototype) throw new UnkeyableValueError("non-plain object");
3616
+ const keys = Object.keys(obj).sort();
3617
+ if (keys.length !== Object.getOwnPropertyNames(obj).length) throw new UnkeyableValueError("non-enumerable property");
3618
+ const parts = [];
3619
+ for (const key of keys) {
3620
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
3621
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3622
+ parts.push(JSON.stringify(key) + ":" + canonicalize$1(desc.value, seen));
3623
+ }
3624
+ return "{" + parts.join(",") + "}";
3625
+ }
3626
+ }
3627
+ /**
3628
+ * Canonicalize a single value, or null if it is unkeyable. The ONE
3629
+ * definition of "faithfully comparable" — every prebuilt code path that
3630
+ * needs value equality (cache keys, slot-param divergence) goes through
3631
+ * this, so the unkeyable rules (accessors, hidden props, aliases,
3632
+ * bigints, …) live in exactly one place.
3633
+ */
3634
+ function tryCanonicalize(value) {
3635
+ try {
3636
+ return canonicalize$1(value, /* @__PURE__ */ new Set());
3637
+ } catch (error) {
3638
+ return toUnkeyable(error);
3639
+ }
3640
+ }
3641
+ /**
3642
+ * Totality by construction: ANY throw from the walk means the input is
3643
+ * outside the keyable domain. The walk touches only user-controlled
3644
+ * values through reflection ops — and a Proxy trap can throw arbitrary
3645
+ * errors from any of them (codex review on PR #835) — so converting only
3646
+ * UnkeyableValueError would let hostile/exotic inputs abort a render
3647
+ * that plain live rendering would have served fine. Unexpected error
3648
+ * types are logged for visibility (they would indicate either a proxy
3649
+ * trap or a canonicalizer bug) but still degrade to unkeyable.
3650
+ */
3651
+ function toUnkeyable(error) {
3652
+ if (!(error instanceof UnkeyableValueError)) console.error("[timber] cache key canonicalization threw — treating input as unkeyable:", error);
3653
+ return null;
3654
+ }
3655
+ /**
3656
+ * Split a props record into data props (participate in the cache key) and
3657
+ * slot values (React-element holes, excluded from the key) per the
3658
+ * component's declared `slots` option (TIM-1173).
3659
+ *
3660
+ * Every DECLARED slot lands in `slotValues` — present or not — because the
3661
+ * capture render always injects a SlotOutlet placeholder for each declared
3662
+ * slot: the cached shell is identical whether the caller passed the slot
3663
+ * or omitted it, so slot presence must not vary the key. `dataProps` is
3664
+ * everything else and is what gets hashed.
3665
+ *
3666
+ * Returns null when the props OBJECT itself is outside the identity
3667
+ * contract at the top level — accessors, symbol-keyed or non-enumerable
3668
+ * properties, or a non-`Object.prototype` prototype. Splitting such an
3669
+ * object would normalize away observable state (and reading an accessor
3670
+ * would invoke user code, which this walk must never do) BEFORE
3671
+ * `computeComponentCacheKey` gets the chance to reject it — a cached
3672
+ * shell could then be served for inputs a live render distinguishes.
3673
+ * Null means unkeyable: the caller renders live with the original props.
3674
+ * The walk is descriptor-reads only; getters are never invoked. Nested
3675
+ * data-prop values still face the full allowlist when hashed.
3676
+ */
3677
+ /** Create an own enumerable data property — safe for keys like `__proto__`. */
3678
+ function defineOwn(target, key, value) {
3679
+ Object.defineProperty(target, key, {
3680
+ value,
3681
+ enumerable: true,
3682
+ writable: true,
3683
+ configurable: true
3684
+ });
3685
+ }
3686
+ function splitSlotProps(props, slots) {
3687
+ try {
3688
+ if (Object.getPrototypeOf(props) !== Object.prototype) return null;
3689
+ if (Object.getOwnPropertySymbols(props).length > 0) return null;
3690
+ const slotSet = new Set(slots);
3691
+ const dataProps = {};
3692
+ const slotValues = {};
3693
+ for (const key of Object.getOwnPropertyNames(props)) {
3694
+ const desc = Object.getOwnPropertyDescriptor(props, key);
3695
+ if (desc === void 0 || desc.get !== void 0 || desc.set !== void 0 || !desc.enumerable) return null;
3696
+ defineOwn(slotSet.has(key) ? slotValues : dataProps, key, desc.value);
3697
+ }
3698
+ for (const slot of slotSet) if (!Object.hasOwn(slotValues, slot)) defineOwn(slotValues, slot, void 0);
3699
+ return {
3700
+ dataProps,
3701
+ slotValues
3702
+ };
3703
+ } catch (error) {
3704
+ return toUnkeyable(error);
3705
+ }
3706
+ }
3707
+ /**
3708
+ * Compute the cache-entry hash for a component render:
3709
+ * `sha256({props, params}).slice(0, 16)` over canonical JSON.
3710
+ *
3711
+ * Returns null when props (or params) contain unkeyable values — the
3712
+ * caller must fall back to dynamic rendering.
3713
+ */
3714
+ function computeComponentCacheKey(props, params) {
3715
+ let canonical;
3716
+ try {
3717
+ const seen = /* @__PURE__ */ new Set();
3718
+ canonical = "{\"params\":" + canonicalize$1({ ...params }, seen) + ",\"props\":" + canonicalize$1(props, seen) + "}";
3719
+ } catch (error) {
3720
+ return toUnkeyable(error);
3721
+ }
3722
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
3723
+ }
3724
+ /**
3725
+ * Resolve the params the cache key may faithfully hash, or null if this
3726
+ * render is unkeyable.
3727
+ *
3728
+ * A wrapper rendered inside a parallel slot reads params merged with that
3729
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
3730
+ * — but the cache key hashes only the route-level params, and the wrapper
3731
+ * cannot know which slot it renders under. The route params are usable
3732
+ * only when every slot's merged view canonicalizes identically to them;
3733
+ * otherwise two renders with the same key could see different effective
3734
+ * inputs and a hit could serve the WRONG cached subtree — so the render
3735
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
3736
+ * params either, so a divergent request could never have a faithful
3737
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
3738
+ * if slot-scoped prebuilt is ever needed.)
3739
+ *
3740
+ * Comparison happens through `tryCanonicalize` — the same single
3741
+ * definition of value equality the cache key uses — so anything it
3742
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
3743
+ * aliases, …) is unkeyable here too, and this guard can never throw.
3744
+ */
3745
+ function resolveKeyParams(store) {
3746
+ const main = store.segmentParams ?? {};
3747
+ const slots = store.slotParams;
3748
+ if (!slots || Object.keys(slots).length === 0) return main;
3749
+ const mainCanonical = tryCanonicalize({ ...main });
3750
+ if (mainCanonical === null) return null;
3751
+ for (const slotParams of Object.values(slots)) {
3752
+ const merged = tryCanonicalize({
3753
+ ...main,
3754
+ ...slotParams
3755
+ });
3756
+ if (merged === null || merged !== mainCanonical) return null;
3757
+ }
3758
+ return main;
3759
+ }
3760
+ //#endregion
3761
+ //#region src/client/slot-context.ts
3762
+ /**
3763
+ * SlotContext — delivers live slot content to SlotOutlet holes inside
3764
+ * cached component shells (TIM-1173).
3765
+ *
3766
+ * A `cache.component(Fn, { slots: [...] })` shell is captured with a
3767
+ * stable <SlotOutlet slot={name} /> client reference in place of each
3768
+ * declared slot prop. At request time the revived shell is wrapped in a
3769
+ * SlotsProvider carrying the live slot values; each outlet reads its
3770
+ * value from this context by name.
3771
+ *
3772
+ * Providers MERGE per-key with their parent: an inner SlotsProvider
3773
+ * inherits the outer's values and overrides only the keys it declares.
3774
+ * Two sibling instances each have their own provider and resolve
3775
+ * independently. Layouts use a reserved slot name (LAYOUT_CHILDREN_SLOT)
3776
+ * that cannot collide with user-declared slot names (TIM-1191).
3777
+ *
3778
+ * Generalizes the original layout children pattern (TIM-1181) from a
3779
+ * single implicit `children` hole on layouts to explicitly declared,
3780
+ * named slot props on any cached component. Layouts use this same
3781
+ * context with the reserved LAYOUT_CHILDREN_SLOT key (TIM-1191).
3782
+ *
3783
+ * SINGLETON GUARANTEE: globalThis + Symbol.for — the RSC client bundler
3784
+ * can duplicate this module across chunks; globalThis guarantees a single
3785
+ * context instance.
3786
+ *
3787
+ * See design/45-cache-lifetimes.md §Slot Components.
3788
+ */
3789
+ var CTX_KEY = Symbol.for("__timber_slot_ctx");
3790
+ function getOrCreateContext() {
3791
+ const existing = globalThis[CTX_KEY];
3792
+ if (existing !== void 0) return existing;
3793
+ if (typeof React.createContext === "function") {
3794
+ const ctx = React.createContext(null);
3795
+ globalThis[CTX_KEY] = ctx;
3796
+ return ctx;
3797
+ }
3798
+ }
3799
+ var SlotContext = getOrCreateContext();
3800
+ //#endregion
3801
+ //#region src/client/slot-outlet.tsx
3802
+ /**
3803
+ * SlotOutlet — the hole in a cached component shell (TIM-1173).
3804
+ *
3805
+ * At capture time the prebuilt runtime renders the wrapped component with
3806
+ * <SlotOutlet slot={name} /> in place of each declared slot prop. Being a
3807
+ * client component, it serializes into the flight payload as a stable,
3808
+ * deterministic client reference — the same bytes regardless of what live
3809
+ * content will fill the hole. At request time the revived shell sits under
3810
+ * a SlotsProvider and each outlet reads its live value from SlotContext.
3811
+ *
3812
+ * See design/45-cache-lifetimes.md §Slot Components.
3813
+ */
3814
+ function SlotOutlet({ slot }) {
3815
+ const values = useContext(SlotContext);
3816
+ return values ? values[slot] ?? null : null;
3817
+ }
3818
+ //#endregion
3819
+ //#region src/client/slot-provider.tsx
3820
+ /**
3821
+ * SlotsProvider — wraps a revived cached shell to supply live slot content
3822
+ * to the SlotOutlet holes inside it (TIM-1173).
3823
+ *
3824
+ * Values MERGE with the nearest parent provider so that nesting a
3825
+ * cache.component SlotsProvider inside a layout SlotsProvider preserves
3826
+ * the layout's `children` slot while adding the component's own slots.
3827
+ * Inner values override outer ones with the same name (spread order).
3828
+ *
3829
+ * Tree structure per cached-component instance:
3830
+ * SlotsProvider(values={children: <Live />})
3831
+ * └── revived shell
3832
+ * └── SlotOutlet(slot="children") → reads context → <Live />
3833
+ *
3834
+ * See design/45-cache-lifetimes.md §Slot Components.
3835
+ */
3836
+ function SlotsProvider({ values, children }) {
3837
+ const parent = useContext(SlotContext);
3838
+ const merged = parent ? {
3839
+ ...parent,
3840
+ ...values
3841
+ } : values;
3842
+ return createElement(SlotContext.Provider, { value: merged }, children);
3843
+ }
3844
+ //#endregion
3845
+ //#region src/server/prebuilt/lifetime.ts
3846
+ /**
3847
+ * Lifetime declarations of a `cache.component` — `prerender`, `ttl`,
3848
+ * `tags` (design/45-cache-lifetimes.md) — and the nesting clamp between
3849
+ * two of them (§Nesting Semantics, TIM-1136).
3850
+ *
3851
+ * The clamp rule lives here once, for both places a capture can embed one
3852
+ * wrapped component in another: the post-build capture pass
3853
+ * (server/prebuilt-builder.ts) and request-time re-renders
3854
+ * (`captureComponentPayload()` in server/prebuilt-runtime.ts, TIM-1545).
3855
+ */
3856
+ /** Whether the component has a runtime lifetime (ttl or tags). */
3857
+ function hasRuntimeLifetime(options) {
3858
+ return options.ttl !== void 0 || options.tags != null;
3859
+ }
3860
+ /**
3861
+ * Resolve tags from options (may be static array or function of props).
3862
+ * Function-form tags receive DATA props only — slot props are excluded so
3863
+ * the tags fn never sees SlotOutlet placeholders (capture paths pass
3864
+ * placeholder-substituted props) and tags stay deterministic per key.
3865
+ */
3866
+ function resolveTags(options, props) {
3867
+ if (!options.tags) return [];
3868
+ if (Array.isArray(options.tags)) return options.tags;
3869
+ const slots = options.slots;
3870
+ const fnProps = slots && slots.length > 0 ? splitSlotProps(props, slots)?.dataProps ?? props : props;
3871
+ return options.tags(fnProps);
3872
+ }
3873
+ /**
3874
+ * Why an embedded copy of `inner` goes stale inside `outer`, or null when
3875
+ * the outer's refreshes cover every refresh channel the inner declares:
3876
+ *
3877
+ * - `shorterTtl`: the inner's ttl is shorter than the outer's effective
3878
+ * lifetime (its ttl, or deploy-long without one).
3879
+ * - `missingTags`: tags the inner resolved to that the outer lacks —
3880
+ * `revalidateTag` on them refreshes the inner's own entries, never the
3881
+ * copy. `null` inner tags (a tags function threw) cannot be proven a
3882
+ * subset, so they count as missing.
3883
+ *
3884
+ * Declaring the inner's tags on the outer is the documented fix, and it
3885
+ * silences the tag half by construction.
3886
+ */
3887
+ function clampReasons(outer, inner) {
3888
+ const outerTtl = outer.options.ttl ?? Infinity;
3889
+ const shorterTtl = inner.options.ttl !== void 0 && inner.options.ttl < outerTtl;
3890
+ const missingTags = inner.tags === null ? null : inner.tags.filter((t) => !outer.tags.includes(t));
3891
+ if (!shorterTtl && missingTags !== null && missingTags.length === 0) return null;
3892
+ return {
3893
+ shorterTtl,
3894
+ missingTags
3895
+ };
3896
+ }
3897
+ /** Render a lifetime declaration for the clamp warning. */
3898
+ function describeLifetime(options, tags) {
3899
+ const parts = [];
3900
+ if (options.prerender) parts.push("prerender");
3901
+ if (options.ttl !== void 0) parts.push(`ttl: ${options.ttl}`);
3902
+ if (tags === null) parts.push("tags: fn");
3903
+ else if (tags.length > 0) parts.push(`tags: ${JSON.stringify(tags)}`);
3904
+ return parts.join(", ") || "no lifetime";
3905
+ }
3906
+ /** When the outer entry — and so every copy embedded in it — refreshes. */
3907
+ function describeRefresh(outer) {
3908
+ const parts = [];
3909
+ if (outer.options.ttl !== void 0) parts.push(`every ${outer.options.ttl}s`);
3910
+ if (outer.tags.length > 0) parts.push(`on revalidateTag of its own tags`);
3911
+ parts.push("on redeploy");
3912
+ return parts.join(", or ");
3913
+ }
3914
+ /**
3915
+ * Warn for each wrapped component embedded in `outer`'s captured payload
3916
+ * whose refresh channels the outer cannot honor. Once per (outer, inner)
3917
+ * pair for the lifetime of `warnedPairs` — the builder passes one per
3918
+ * build, the runtime one per process, since re-renders repeat. The key is
3919
+ * the pair alone, not the reason: resolved tags vary with props, and a key
3920
+ * that included them would grow with the data. So the first clamp found
3921
+ * for a pair is the one reported. Returns the number of warnings emitted.
3922
+ */
3923
+ function warnNestingClamps(outer, nested, warnedPairs, log) {
3924
+ let count = 0;
3925
+ for (const inner of nested) {
3926
+ const reasons = clampReasons(outer, inner);
3927
+ if (reasons === null) continue;
3928
+ const pairKey = `${outer.id}\0${inner.innerId}`;
3929
+ if (warnedPairs.has(pairKey)) continue;
3930
+ warnedPairs.add(pairKey);
3931
+ count++;
3932
+ const outerLifetime = describeLifetime(outer.options, outer.tags);
3933
+ const innerLifetime = describeLifetime(inner.options, inner.tags);
3934
+ const consequences = [];
3935
+ if (reasons.missingTags === null) consequences.push(`${inner.innerId}'s tags could not be resolved during the capture (its tags function threw or needed request context), so revalidating them may NOT update the embedded copy.`);
3936
+ else if (reasons.missingTags.length > 0) {
3937
+ const calls = reasons.missingTags.map((t) => `revalidateTag(${JSON.stringify(t)})`);
3938
+ consequences.push(`${calls.join(", ")} will NOT update the embedded copy; tag ${outer.id} itself if you need that.`);
3939
+ }
3940
+ if (reasons.shorterTtl) consequences.push(`${inner.innerId}'s ttl: ${inner.options.ttl} does not apply to the embedded copy.`);
3941
+ log(`[timber] ${inner.innerId} (${innerLifetime}) is embedded in ${outer.options.prerender ? "prerendered" : "cached"} ${outer.id} — the embedded copy refreshes only when ${outer.id} does (${describeRefresh(outer)}). ${consequences.join(" ")} Chain: ${outer.id} (${outerLifetime}) → ${inner.innerId} (${innerLifetime})`);
3942
+ }
3943
+ return count;
3944
+ }
3945
+ //#endregion
3946
+ //#region src/server/prebuilt/slots.ts
3947
+ /**
3948
+ * Slot-component helpers for cache.component (TIM-1173).
3949
+ *
3950
+ * A `slots: ['children', ...]` declaration caches the component's output
3951
+ * as a shell with a stable <SlotOutlet slot={name} /> client-reference
3952
+ * hole per declared slot prop; live slot content composes in per instance
3953
+ * at request time via SlotsProvider/SlotContext. This generalizes the
3954
+ * TIM-1181 layout mechanism to explicitly declared, named slots on any
3955
+ * cached component. Layouts use the same mechanism with a `children` slot.
3956
+ *
3957
+ * The `__prebuilt` wrapper builds its slot render from these helpers, in
3958
+ * dev and production alike. See design/45-cache-lifetimes.md §Slot
3959
+ * Components.
3960
+ */
3961
+ /**
3962
+ * Framework-internal slot name for layout children. Uses a prefix that
3963
+ * cannot collide with user-declared slot names (which are React prop
3964
+ * names). Layout children flow through SlotsProvider/SlotOutlet with
3965
+ * this key instead of the bare "children" key, so a cached component
3966
+ * with `slots: ['children']` inside a layout never shadows the layout's
3967
+ * own children delivery.
3968
+ *
3969
+ * Defined here (a server module) rather than in `client/slot-context.ts`
3970
+ * (`'use client'`) because RSC's client-reference proxying would replace
3971
+ * the string value with a proxy object in the server environment. The
3972
+ * client-side SlotOutlet receives this value via props, so it doesn't
3973
+ * need the constant. See TIM-1191.
3974
+ */
3975
+ var LAYOUT_CHILDREN_SLOT = "\0timber:children";
3976
+ /**
3977
+ * Is this value the framework-injected layout children slot outlet
3978
+ * (`<SlotOutlet slot={LAYOUT_CHILDREN_SLOT} />`)? Layout components
3979
+ * receive this as their `children` prop — a stable client reference
3980
+ * whose cache key is stripped so layout `cache.component` hits work
3981
+ * (design/45 §Layout Propagation).
3982
+ *
3983
+ * Uses a framework-reserved slot name (LAYOUT_CHILDREN_SLOT) that
3984
+ * cannot collide with user-declared slot names, preventing context
3985
+ * shadowing when a cached component with its own SlotsProvider is
3986
+ * nested inside a layout. See TIM-1191.
3987
+ *
3988
+ * Total: the probes run against a user-controlled value, and a Proxy
3989
+ * trap can throw — that must classify as "not the outlet" (the
3990
+ * canonicalizer then rejects the value as unkeyable → live render), not
3991
+ * abort the request (codex P2 on PR #890).
3992
+ */
3993
+ function isChildrenSlotOutletElement(value) {
3994
+ try {
3995
+ if (value == null || typeof value !== "object") return false;
3996
+ if (!("type" in value)) return false;
3997
+ const el = value;
3998
+ return el.type === SlotOutlet && el.props?.slot === "\0timber:children";
3999
+ } catch {
4000
+ return false;
4001
+ }
4002
+ }
4003
+ /**
4004
+ * `props` without the framework-injected children outlet — the key props
4005
+ * of a render. The outlet is the same client reference on every request,
4006
+ * so it never varies the cache key; user-provided children stay (and
4007
+ * leave the props unkeyable). See design/45 §Layout Propagation, TIM-1181.
4008
+ */
4009
+ function withoutChildrenOutlet(props) {
4010
+ if (!isChildrenSlotOutletElement(props.children)) return props;
4011
+ const { children: _children, ...rest } = props;
4012
+ return rest;
4013
+ }
4014
+ /**
4015
+ * Dense array of non-empty strings — no holes, no non-string entries.
4016
+ * Total: the reads run against a user-controlled value at module load,
4017
+ * and a throwing Proxy trap must classify as invalid, not crash startup.
4018
+ */
4019
+ function isDenseStringArray(value) {
4020
+ try {
4021
+ if (!Array.isArray(value)) return false;
4022
+ for (let i = 0; i < value.length; i++) {
4023
+ if (!Object.hasOwn(value, i)) return false;
4024
+ const entry = value[i];
4025
+ if (typeof entry !== "string" || entry.length === 0) return false;
4026
+ }
4027
+ return true;
4028
+ } catch {
4029
+ return false;
4030
+ }
4031
+ }
4032
+ /**
4033
+ * Validate the `slots` option. The `__prebuilt` wrapper gates on this in
4034
+ * dev and production alike, so the tree shape a component sees never
4035
+ * diverges between the two.
4036
+ */
4037
+ function resolveSlotNames(id, options) {
4038
+ const slots = options.slots;
4039
+ if (slots === void 0) return { kind: "none" };
4040
+ if (!isDenseStringArray(slots)) {
4041
+ console.warn(`[timber] cache.component "${id}": invalid slots declaration — expected an array of non-empty prop-name strings. Slot caching is disabled.`);
4042
+ return { kind: "disabled" };
4043
+ }
4044
+ if (slots.length === 0) return { kind: "none" };
4045
+ if (!hasRuntimeLifetime(options)) {
4046
+ console.warn(`[timber] cache.component "${id}": slots require a runtime lifetime (ttl and/or tags). Slot caching is disabled.`);
4047
+ return { kind: "disabled" };
4048
+ }
4049
+ return {
4050
+ kind: "active",
4051
+ slots
4052
+ };
4053
+ }
4054
+ /**
4055
+ * Split the live props into the cacheable shell render (data props plus a
4056
+ * deterministic SlotOutlet placeholder per declared slot — identical
4057
+ * whether or not the caller passed the slot) and the per-instance live
4058
+ * slot values.
4059
+ *
4060
+ * Null when the props object itself is unkeyable at the top level
4061
+ * (accessors, hidden properties, exotic prototype — see splitSlotProps):
4062
+ * the caller must render live with the original props.
4063
+ */
4064
+ function prepareSlotRender(props, slots) {
4065
+ const split = splitSlotProps(props ?? {}, slots);
4066
+ if (split === null) return null;
4067
+ const { dataProps, slotValues } = split;
4068
+ const shellProps = { ...dataProps };
4069
+ for (const slot of slots) Object.defineProperty(shellProps, slot, {
4070
+ value: createElement(SlotOutlet, { slot }),
4071
+ enumerable: true,
4072
+ writable: true,
4073
+ configurable: true
4074
+ });
4075
+ return {
4076
+ shellProps,
4077
+ dataProps,
4078
+ slotValues
4079
+ };
4080
+ }
4081
+ /**
4082
+ * Wrap a rendered shell (revived payload or live element) in a
4083
+ * per-instance SlotsProvider feeding the live values to its outlets.
4084
+ */
4085
+ function wrapInSlotsProvider(shell, slotValues) {
4086
+ return createElement(SlotsProvider, {
4087
+ values: slotValues,
4088
+ children: shell
4089
+ });
4090
+ }
4091
+ //#endregion
4092
+ //#region src/server/prebuilt/key-discipline.ts
4093
+ var REQUEST_CONTEXT_FIELDS = {
4094
+ headers: "headers()",
4095
+ parsedCookies: "cookies()",
4096
+ searchParams: "searchParams"
4097
+ };
4098
+ /** Rate-limit interval: one diagnostic per component per 60 seconds. */
4099
+ var RATE_LIMIT_MS = 6e4;
4100
+ /** Last emission timestamp per component ID. */
4101
+ var lastEmitted = /* @__PURE__ */ new Map();
4102
+ var strict = false;
4103
+ /**
4104
+ * Whether the proxy should be created for this component on this render.
4105
+ * Returns true when strict mode is on (always check) or enough time has
4106
+ * elapsed since the last diagnostic for this component.
4107
+ */
4108
+ function shouldCheckKeyDiscipline(id) {
4109
+ if (strict) return true;
4110
+ const last = lastEmitted.get(id);
4111
+ if (last === void 0) return true;
4112
+ return Date.now() - last >= RATE_LIMIT_MS;
4113
+ }
4114
+ /**
4115
+ * Wrap a store with a proxy that records per-request field access.
4116
+ * The proxy forwards all reads/writes transparently — it only observes.
4117
+ */
4118
+ function createKeyDisciplineProxy(store) {
4119
+ const accessedApis = /* @__PURE__ */ new Set();
4120
+ return {
4121
+ proxy: new Proxy(store, { get(target, prop, receiver) {
4122
+ const api = REQUEST_CONTEXT_FIELDS[prop];
4123
+ if (api) accessedApis.add(api);
4124
+ return Reflect.get(target, prop, receiver);
4125
+ } }),
4126
+ accessedApis
4127
+ };
4128
+ }
4129
+ /**
4130
+ * Emit the key-discipline diagnostic or throw in strict mode.
4131
+ *
4132
+ * In strict mode: throws an error so the tainted payload is never cached.
4133
+ * In default mode: emits a structured error-level diagnostic through the
4134
+ * logger (same path as render errors), rate-limited per component.
4135
+ */
4136
+ function emitKeyDisciplineWarning(id, apis) {
4137
+ const apiList = Array.from(apis).join(", ");
4138
+ 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.`);
4139
+ const now = Date.now();
4140
+ const last = lastEmitted.get(id);
4141
+ if (last !== void 0 && now - last < RATE_LIMIT_MS) return;
4142
+ lastEmitted.set(id, now);
4143
+ getLogger().error("cache.component cross-user data leak risk", {
4144
+ component: id,
4145
+ accessedApis: Array.from(apis),
4146
+ 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.`
4147
+ });
4148
+ }
4149
+ //#endregion
4150
+ //#region src/server/prebuilt/capture-state.ts
4151
+ /**
4152
+ * Capture state — the channel between a payload capture and the
4153
+ * `__prebuilt` wrappers that render inside it (server/prebuilt-runtime.ts).
4154
+ *
4155
+ * Two callers capture a wrapped component's flight payload:
4156
+ *
4157
+ * - **Build time**: the post-build capture pass (server/prebuilt-builder.ts)
4158
+ * renders each registry entry in turn.
4159
+ * - **Request time**: `captureComponentPayload()` in prebuilt-runtime.ts
4160
+ * renders a component in isolation for an inline re-render (full miss,
4161
+ * stale entry, tombstone) or an SWR background re-render. These run
4162
+ * concurrently with other requests' renders — and with each other.
4163
+ *
4164
+ * During a capture, the component's subtree may render OTHER wrapped
4165
+ * components. Those inner wrappers render live and their output is baked
4166
+ * flat into the outer entry — the nesting clamp of
4167
+ * design/45-cache-lifetimes.md §Nesting Semantics (TIM-1136). The wrapper
4168
+ * reports every render that happens inside a capture:
4169
+ *
4170
+ * - **Cycle**: the inner render IS the entry being captured — same
4171
+ * component id AND same props key (TIM-1547). Left alone this recurses
4172
+ * until the render times out; instead the wrapper throws
4173
+ * `PrebuiltCaptureCycleError`, failing that entry with an error naming
4174
+ * the cycle (build continues per doc 44 skip-and-report policy; at
4175
+ * request time the re-render fails and is not cached, and the wrapper
4176
+ * falls back as for any failed re-render). A component that renders
4177
+ * itself with different props (a comment thread, a tree) is legitimate
4178
+ * recursion with a base case and bakes flat like any other nesting.
4179
+ * - **Nesting**: any other wrapper render is recorded per inner component
4180
+ * with the tags it resolved to. Both capture callers run the clamp rule
4181
+ * over those records when the entry completes (prebuilt/lifetime.ts).
4182
+ *
4183
+ * Identity is the capture ROOT only. A wrapper cannot see the wrappers
4184
+ * between it and the root: Flight renders a component's children after
4185
+ * the wrapper has returned, in Flight's own async context, not in a frame
4186
+ * the wrapper could enter. So a same-key cycle that closes below the root
4187
+ * (`A(p1) → A(p2) → A(p2) → …`) is not detected here; it is also an
4188
+ * infinite recursion without caching, and the capture's render timeout
4189
+ * fails it.
4190
+ *
4191
+ * The props key is the props half of the cache key (data props only,
4192
+ * framework children outlet stripped — the same inputs the cache key
4193
+ * hashes). The params half is left out: every render inside one capture
4194
+ * reads the same segment params, so props decide identity. Unkeyable props
4195
+ * (live React elements, …) cannot be proven identical and are never a
4196
+ * cycle.
4197
+ *
4198
+ * Each capture's state lives in an AsyncLocalStorage store entered by
4199
+ * `CaptureScope.run()`, so it is visible only to renders started inside
4200
+ * that capture — including work Flight resumes after an await, which runs
4201
+ * in the context the awaited promise was created in. A concurrent request
4202
+ * rendering the same component is not a cycle, and a concurrent request
4203
+ * rendering a different cached component still revives it from cache
4204
+ * instead of baking it live (TIM-1536). Outside any capture
4205
+ * `noteWrapperRender` is a single store lookup.
4206
+ */
4207
+ /** Thrown by the wrapper when a capture renders its own entry. */
4208
+ var PrebuiltCaptureCycleError = class extends Error {
4209
+ constructor(componentId) {
4210
+ super(`[timber] cache.component "${componentId}" renders itself with the same props (directly or through other components) — capturing its payload would recurse forever. Remove the cycle or stop caching this component with cache.component.`);
4211
+ this.name = "PrebuiltCaptureCycleError";
4212
+ }
4213
+ };
4214
+ /**
4215
+ * The props half of a render's cache key, or null when unkeyable. Same
4216
+ * inputs `tryRevivePayload` hashes: data props only for slot components,
4217
+ * the framework-injected children outlet stripped.
4218
+ */
4219
+ function propsKey(options, props) {
4220
+ let keyProps = props;
4221
+ if (options.slots && options.slots.length > 0) {
4222
+ const split = splitSlotProps(props, options.slots);
4223
+ if (split === null) return null;
4224
+ keyProps = split.dataProps;
4225
+ }
4226
+ return computeComponentCacheKey(withoutChildrenOutlet(keyProps), {});
4227
+ }
4228
+ /**
4229
+ * Open a capture of component `outerId` rendered with `props`. Its state
4230
+ * ends with the scope object.
4231
+ */
4232
+ function createCaptureScope(outerId, options, props) {
4233
+ const store = {
4234
+ outerId,
4235
+ outerPropsKey: propsKey(options, props),
4236
+ nested: /* @__PURE__ */ new Map()
4237
+ };
4238
+ return {
4239
+ run: (fn) => prebuiltCaptureAls.run(store, fn),
4240
+ nestedRenders: () => Array.from(store.nested, ([innerId, record]) => ({
4241
+ innerId,
4242
+ options: record.options,
4243
+ tags: record.tags && Array.from(record.tags)
4244
+ }))
4245
+ };
4246
+ }
4247
+ /** Whether the current render is inside a capture. */
4248
+ function isCaptureActive() {
4249
+ return prebuiltCaptureAls.getStore() !== void 0;
4250
+ }
4251
+ /**
4252
+ * Called by the `__prebuilt` wrapper on every render. No-op outside a
4253
+ * capture. Throws `PrebuiltCaptureCycleError` when the render is the
4254
+ * entry the enclosing capture is producing.
4255
+ */
4256
+ function noteWrapperRender(innerId, options, props) {
4257
+ const capture = prebuiltCaptureAls.getStore();
4258
+ if (capture === void 0) return;
4259
+ if (innerId === capture.outerId && capture.outerPropsKey !== null) {
4260
+ if (propsKey(options, props) === capture.outerPropsKey) throw new PrebuiltCaptureCycleError(innerId);
4261
+ }
4262
+ let record = capture.nested.get(innerId);
4263
+ if (record === void 0) {
4264
+ record = {
4265
+ options,
4266
+ tags: /* @__PURE__ */ new Set()
4267
+ };
4268
+ capture.nested.set(innerId, record);
4269
+ }
4270
+ if (record.tags !== null && options.tags) {
4271
+ const tags = record.tags;
4272
+ try {
4273
+ for (const tag of requestContextAls.exit(() => resolveTags(options, props))) tags.add(tag);
4274
+ } catch {
4275
+ record.tags = null;
4276
+ }
4277
+ }
4278
+ }
4279
+ //#endregion
4280
+ //#region src/server/flight-source.ts
4281
+ var nodeFlight = typeof process !== "undefined" && process.release?.name === "node" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") ? await import("../_chunks/flight-source-node-HptmGMT8.js") : null;
4282
+ /** The Node helpers, which a `kind: 'node'` source can only exist alongside. */
4283
+ function requireNodeFlight() {
4284
+ if (!nodeFlight) throw new Error("[timber] a Node Flight source reached a runtime without node:stream");
4285
+ return nodeFlight;
4286
+ }
4287
+ /**
4288
+ * A pull reader over either kind. `read()` is unguarded: every caller races
4289
+ * it against a timeout (design/02 §"Always Timeout-Guard Stream Reads").
4290
+ * `cancel()` releases the source, which aborts the render.
4291
+ */
4292
+ function openFlightReader(source) {
4293
+ if (source.kind === "web") {
4294
+ const reader = source.stream.getReader();
4295
+ return {
4296
+ read: () => reader.read(),
4297
+ takeBuffered: () => [],
4298
+ cancel: (reason) => void reader.cancel(reason).catch(() => {})
4299
+ };
4300
+ }
4301
+ const { destroyNodeFlight } = requireNodeFlight();
4302
+ const stream = source.stream;
4303
+ const iterator = stream[Symbol.asyncIterator]();
4304
+ return {
4305
+ read: async () => {
4306
+ const result = await iterator.next();
4307
+ return result.done ? {
4308
+ done: true,
4309
+ value: void 0
4310
+ } : {
4311
+ done: false,
4312
+ value: result.value
4313
+ };
4314
+ },
4315
+ takeBuffered: () => {
4316
+ const chunks = [];
4317
+ while (stream.readableLength > 0 && !stream.destroyed) {
4318
+ const chunk = stream.read();
4319
+ if (chunk === null) break;
4320
+ chunks.push(chunk);
4321
+ }
4322
+ return chunks;
4323
+ },
4324
+ cancel: (reason) => destroyNodeFlight(stream, reason)
4325
+ };
4326
+ }
4327
+ /** A chunk as bytes. */
4328
+ function flightChunkBytes(chunk) {
4329
+ return typeof chunk === "string" ? encoder.encode(chunk) : chunk;
4330
+ }
4331
+ var encoder = new TextEncoder();
4332
+ /**
4333
+ * Read a whole Flight source into bytes under one overall deadline, cancelling
4334
+ * it on every exit (`drainWithDeadline`). For renders whose payload is stored
4335
+ * rather than streamed: the no-JS form state and both prebuilt captures.
4336
+ */
4337
+ async function collectFlightBytes(source, timeoutMs, label) {
4338
+ const chunks = await drainWithDeadline(openFlightReader(source), timeoutMs, label);
4339
+ return concatBytes(chunks.map(flightChunkBytes));
4340
+ }
4341
+ //#endregion
4342
+ //#region src/server/prebuilt/synthetic-store.ts
4343
+ /**
4344
+ * Thrown when a prerendered component touches per-request context at
4345
+ * build time. The capture pass treats this as a HARD build error —
4346
+ * it indicates a design mistake, not transient bad data (design/44
4347
+ * §Build-Phase Error Handling).
4348
+ */
4349
+ var BuildTimeContextError = class extends Error {
4350
+ /** The per-request API that was called (e.g. "cookies()"). */
4351
+ api;
4352
+ constructor(componentId, api) {
4353
+ super(`[timber] cache.component "${componentId}": ${api} cannot be used in a prerendered component — there is no request at build time. Prerendered components may read segment params and timber.cache data only. Remove the ${api} call, or drop { prerender: true } and render this component per-request. (design/44-render-at-build-time.md §Param Injection)`);
4354
+ this.name = "BuildTimeContextError";
4355
+ this.api = api;
4356
+ }
4357
+ };
4358
+ /**
4359
+ * Create the synthetic per-combo store. `segmentParams` must already be
4360
+ * coerced through the route's codecs — cache-key parity with request time
4361
+ * depends on hashing the exact record `coerceSegmentParams` produces.
4362
+ */
4363
+ function createBuildTimeStore(componentId, segmentParams) {
4364
+ const violations = [];
4365
+ const handle = {
4366
+ store: null,
4367
+ violations,
4368
+ segmentParamsRead: false
4369
+ };
4370
+ const store = {
4371
+ request: null,
4372
+ headers: new Headers(),
4373
+ originalHeaders: new Headers(),
4374
+ cookieHeader: "",
4375
+ searchParams: new URLSearchParams(),
4376
+ searchString: "",
4377
+ segmentParams,
4378
+ cookieJar: /* @__PURE__ */ new Map(),
4379
+ flushed: false,
4380
+ mutableContext: false
4381
+ };
4382
+ const violate = (api) => {
4383
+ const error = new BuildTimeContextError(componentId, api);
4384
+ violations.push(error);
4385
+ throw error;
4386
+ };
4387
+ Object.defineProperties(store, {
4388
+ headers: { get: () => violate("headers()") },
4389
+ parsedCookies: { get: () => violate("cookies()") },
4390
+ searchParams: { get: () => violate("searchParams") },
4391
+ mutableContext: { get: () => violate("cookies()") },
4392
+ segmentParams: {
4393
+ get: () => {
4394
+ handle.segmentParamsRead = true;
4395
+ return segmentParams;
4396
+ },
4397
+ enumerable: true
4398
+ }
4399
+ });
4400
+ handle.store = store;
4401
+ return handle;
4402
+ }
4403
+ //#endregion
4404
+ //#region src/server/prebuilt/capture-render.ts
4405
+ /**
4406
+ * One build-time capture entry: render a registered component in isolation
4407
+ * under the synthetic build store and drain its flight payload under a
4408
+ * deadline. Run by the post-build capture pass (server/prebuilt-builder.ts)
4409
+ * and, in dev, by the first request for a prerender entry
4410
+ * (server/prebuilt-runtime.ts, TIM-1588) — which is why the flight renderer
4411
+ * is a parameter: the request-time runtime renders through the functions
4412
+ * the RSC entry injected.
4413
+ */
4414
+ /**
4415
+ * Render one (component, props, coerced-params) entry in isolation and drain
4416
+ * its flight payload. Any `onError` during serialization fails the entry —
4417
+ * a payload with an embedded error row would replay that error on every
4418
+ * future request, so only fully clean renders are captured.
4419
+ */
4420
+ async function renderEntry(registration, props, coercedParams, timeoutMs, isLayout, renderFlight) {
4421
+ const storeHandle = createBuildTimeStore(registration.id, coercedParams);
4422
+ const { store, violations } = storeHandle;
4423
+ let failure = null;
4424
+ const capture = createCaptureScope(registration.id, registration.options, props);
4425
+ let bytes = null;
4426
+ let resolvedTags;
4427
+ try {
4428
+ const renderProps = isLayout && !("children" in props) ? {
4429
+ ...props,
4430
+ children: createElement(SlotOutlet, { slot: LAYOUT_CHILDREN_SLOT })
4431
+ } : props;
4432
+ bytes = await capture.run(() => requestContextAls.run(store, async () => {
4433
+ const drained = await collectFlightBytes(renderFlight(createElement(registration.component, renderProps), { onError(error) {
4434
+ failure ??= error ?? /* @__PURE__ */ new Error("unknown render error");
4435
+ return "timber-prebuilt-capture-error";
4436
+ } }), timeoutMs, "render");
4437
+ const tags = resolveTags(registration.options, props);
4438
+ resolvedTags = tags.length > 0 ? tags : void 0;
4439
+ return drained;
4440
+ }));
4441
+ } catch (error) {
4442
+ failure ??= error;
4443
+ }
4444
+ const nested = capture.nestedRenders();
4445
+ const { segmentParamsRead } = storeHandle;
4446
+ if (violations.length > 0) return {
4447
+ bytes: null,
4448
+ failure: violations[0],
4449
+ nested,
4450
+ resolvedTags,
4451
+ segmentParamsRead
4452
+ };
4453
+ if (failure !== null) return {
4454
+ bytes: null,
4455
+ failure,
4456
+ nested,
4457
+ resolvedTags,
4458
+ segmentParamsRead
4459
+ };
4460
+ return {
4461
+ bytes,
4462
+ failure: null,
4463
+ nested,
4464
+ resolvedTags,
4465
+ segmentParamsRead
4466
+ };
4467
+ }
4468
+ //#endregion
4469
+ //#region src/server/prebuilt-runtime.ts
4470
+ /**
4471
+ * Prebuilt component runtime — registration target for the timber-prebuilt
4472
+ * transform (plugins/prebuilt.ts) and the request-time half of
4473
+ * cache.component (TIM-1140).
4474
+ *
4475
+ * `cache.component(fn, opts)` call sites are rewritten at build time to
4476
+ * `__prebuilt(stableId, fn, opts)`, in dev and production alike. It is
4477
+ * exported via #server-internal — framework plumbing, never called by user
4478
+ * code directly. In dev the build artifact is replaced by the in-memory dev
4479
+ * store (prebuilt/dev-store.ts): a prerender entry is captured on its first
4480
+ * request and served until a watched file changes (TIM-1588).
4481
+ *
4482
+ * Cache hits are served by FLIGHT REVIVAL: the cached `.flight` payload is
4483
+ * decoded back into React elements inside the RSC environment with
4484
+ * `createFromReadableStream` (the flight client running in the flight
4485
+ * server — plugin-rsc wires the server-decode manifest so client
4486
+ * references revive as re-serializable reference proxies). The revived
4487
+ * element is returned from the wrapper and the outer render re-serializes
4488
+ * it like any other subtree. This is the same mechanism as Next.js
4489
+ * `"use cache"` (next/src/server/use-cache/use-cache-wrapper.ts).
4490
+ *
4491
+ * What a hit skips: all user work — data fetching, MDX compilation, the
4492
+ * component function itself never runs. What it re-pays: React
4493
+ * re-serializes the already-resolved tree (cost proportional to payload
4494
+ * size, not to data latency). The alternative — splicing raw payload bytes
4495
+ * into the outer stream — avoids re-serialization but requires byte-level
4496
+ * coupling to the flight wire format (row framing, ID rebasing, marker
4497
+ * detection); it was implemented and reviewed on PR #835 and deliberately
4498
+ * replaced by revival. See design/44-render-at-build-time.md
4499
+ * §Request-Time Injection.
4500
+ *
4501
+ * Misses render the original component live via the wrapper's own closure,
4502
+ * inside the React pass — segment params from ALS, deny()/redirect()
4503
+ * signals, Suspense, and error boundaries behave exactly as an unwrapped
4504
+ * component. `fallbackOnMissingSegmentParams: false` throws instead.
4505
+ */
4506
+ /** Default timeout for component re-renders (overridden by renderTimeoutMs). */
4507
+ var DEFAULT_COMPONENT_TIMEOUT_MS = DEFAULT_RENDER_TIMEOUT_MS;
4508
+ /** Singleflight for component re-renders (inline and background). */
4509
+ var componentSingleflight = createSingleflight({ timeoutMs: DEFAULT_COMPONENT_TIMEOUT_MS });
4510
+ var componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
4511
+ var warnedNoWaitUntil = false;
4512
+ /**
4513
+ * (outer, inner) pairs already warned about by request-time captures.
4514
+ * Process-wide: re-renders of a hot component repeat, and the warning is
4515
+ * about the code, not the request. Bounded by the number of wrapped
4516
+ * components in the app.
4517
+ */
4518
+ var warnedNestingPairs = /* @__PURE__ */ new Set();
4519
+ /**
4520
+ * Server-side component registry, keyed by stable component ID. Populated at
4521
+ * module load time by `__prebuilt` calls; consumed by the post-build capture
4522
+ * pass (TIM-1119). Not written in dev, where nothing walks it. Never serialized — component functions are not
4523
+ * Flight-serializable.
4524
+ */
4525
+ var registry = /* @__PURE__ */ new Map();
4526
+ /** Dev: IDs registered so far, to detect a module re-evaluating (no functions held). */
4527
+ var devRegisteredIds = /* @__PURE__ */ new Set();
4528
+ /** Wrap payload bytes as a single-chunk ReadableStream for the decoder. */
4529
+ function bytesToStream(bytes) {
4530
+ return new ReadableStream({ start(controller) {
4531
+ controller.enqueue(bytes);
4532
+ controller.close();
4533
+ } });
4534
+ }
4535
+ /**
4536
+ * Serve a slot component from the cache: split live slot values out of the
4537
+ * props, look up / capture the shell (data props + a deterministic
4538
+ * SlotOutlet placeholder per slot), and wrap the revived shell in a
4539
+ * per-instance SlotsProvider that feeds the live values to the outlets.
4540
+ *
4541
+ * Null on any miss — the caller renders live with the original props.
4542
+ */
4543
+ async function tryReviveSlotShell(registration, slots, props) {
4544
+ const render = prepareSlotRender(props, slots);
4545
+ if (render === null) return null;
4546
+ const { shellProps, dataProps, slotValues } = render;
4547
+ const revived = await tryRevivePayload(registration, shellProps, dataProps);
4548
+ if (revived === null) return null;
4549
+ return { element: wrapInSlotsProvider(revived.element, slotValues) };
4550
+ }
4551
+ var rscFns = null;
4552
+ function requireRscFunctions() {
4553
+ if (!rscFns) throw new Error("[timber] RSC functions not wired — setRscFunctions() must be called at boot");
4554
+ return rscFns;
4555
+ }
4556
+ /**
4557
+ * Revive flight payload bytes into a React element.
4558
+ * Returns null on any failure (corrupt payload, missing decoder).
4559
+ */
4560
+ async function revivePayload(id, payload, outcome) {
4561
+ try {
4562
+ const { createFromReadableStream } = requireRscFunctions();
4563
+ return { element: await createFromReadableStream(bytesToStream(payload)) };
4564
+ } catch (error) {
4565
+ console.error(`[timber] failed to revive prebuilt payload for "${id}" — ${outcome}:`, error);
4566
+ return null;
4567
+ }
4568
+ }
4569
+ /** Ceiling on component re-render capture (design/13 A2). Uses configured renderTimeoutMs. */
4570
+ function getCaptureTimeoutMs() {
4571
+ return componentTimeoutMs;
4572
+ }
4573
+ /**
4574
+ * Render a component in isolation and capture its flight payload bytes.
4575
+ * Used for inline re-renders (tombstone/miss) and SWR background re-renders.
4576
+ *
4577
+ * The stream read is timeout-guarded and the reader is cancelled on
4578
+ * expiry (design/13 A2, A3).
4579
+ */
4580
+ async function captureComponentPayload(id, component, props, options) {
4581
+ const { renderFlight } = requireRscFunctions();
4582
+ const element = createElement(component, props);
4583
+ const capture = createCaptureScope(id, options, props);
4584
+ let renderError;
4585
+ const store = requestContextAls.getStore();
4586
+ const discipline = store && shouldCheckKeyDiscipline(id) ? createKeyDisciplineProxy(store) : null;
4587
+ const doCapture = () => capture.run(async () => {
4588
+ const bytes = await collectFlightBytes(runOutsideReactCacheScope(() => renderFlight(element, { onError(error) {
4589
+ renderError ??= { error };
4590
+ return "";
4591
+ } })), getCaptureTimeoutMs(), "[timber] component re-render capture");
4592
+ if (renderError) throw renderError.error;
4593
+ return bytes;
4594
+ });
4595
+ const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
4596
+ if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
4597
+ return {
4598
+ bytes,
4599
+ nested: capture.nestedRenders()
4600
+ };
4601
+ }
4602
+ /**
4603
+ * Store a captured entry in the overlay, then say which embedded
4604
+ * components it clamps (design/45 §Nesting Semantics, TIM-1545). The
4605
+ * warning follows the store: a capture that is discarded (aborted,
4606
+ * invalidated mid-render, failed store) holds no clamped copy, and must
4607
+ * not spend the pair's one warning.
4608
+ */
4609
+ async function storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed) {
4610
+ await storeOverlayEntry(id, cacheKey, captured.bytes, {
4611
+ ttl: options.ttl,
4612
+ tags,
4613
+ hasSeed
4614
+ });
4615
+ warnNestingClamps({
4616
+ id,
4617
+ options,
4618
+ tags
4619
+ }, captured.nested, warnedNestingPairs, (m) => console.warn(m));
4620
+ }
4621
+ /**
4622
+ * Inline re-render: capture flight bytes, store in overlay, revive for
4623
+ * the current request. Singleflight-coalesced by overlay key.
4624
+ */
4625
+ async function inlineRerender(id, component, props, cacheKey, options, hasSeed, outcome) {
4626
+ const tags = resolveTags(options, props);
4627
+ const oKey = overlayKey(id, cacheKey);
4628
+ const sfKey = `prebuilt:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
4629
+ try {
4630
+ return await revivePayload(id, await componentSingleflight.do(sfKey, async (signal) => {
4631
+ const startEpoch = currentInvalidationEpoch();
4632
+ const captured = await captureComponentPayload(id, component, props, options);
4633
+ if (!signal.aborted && hasRuntimeLifetime(options) && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
4634
+ return captured.bytes;
4635
+ }), outcome);
4636
+ } catch (error) {
4637
+ console.error(`[timber] cache.component re-render failed for "${id}" — ${outcome}:`, error);
4638
+ return null;
4639
+ }
4640
+ }
4641
+ /**
4642
+ * Snapshot the request context values needed for a background re-render.
4643
+ * Creates a FRESH store with copied values — the original ALS store is
4644
+ * not referenced after capture. The `Request` itself is shared, not
4645
+ * copied: the re-render reports its failure against it.
4646
+ */
4647
+ function snapshotRequestContext(store) {
4648
+ return {
4649
+ request: store.request,
4650
+ headers: new Headers(store.headers),
4651
+ originalHeaders: new Headers(store.originalHeaders),
4652
+ cookieHeader: store.cookieHeader,
4653
+ parsedCookies: store.parsedCookies ? new Map(store.parsedCookies) : void 0,
4654
+ searchParams: new URLSearchParams(store.searchParams),
4655
+ searchString: store.searchString,
4656
+ segmentParams: store.segmentParams ? { ...store.segmentParams } : void 0,
4657
+ cookieJar: /* @__PURE__ */ new Map(),
4658
+ flushed: false,
4659
+ mutableContext: false
4660
+ };
4661
+ }
4662
+ /**
4663
+ * Kick off a background re-render via waitUntil. The re-render runs inside
4664
+ * a fresh ALS scope with snapshotted request context.
4665
+ */
4666
+ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, snapshot) {
4667
+ const waitUntil = getWaitUntil();
4668
+ const tags = resolveTags(options, props);
4669
+ const oKey = overlayKey(id, cacheKey);
4670
+ const startEpoch = currentInvalidationEpoch();
4671
+ const sfKey = `prebuilt-bg:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
4672
+ const work = requestContextAls.run(snapshot, () => componentSingleflight.do(sfKey, (signal) => runBackgroundFlight(signal, async () => {
4673
+ const captured = await captureComponentPayload(id, component, props, options);
4674
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
4675
+ }, (error) => console.error(`[timber] cache.component background re-render failed for "${id}":`, error))).catch(() => {}));
4676
+ if (waitUntil) waitUntil(work);
4677
+ else if (!warnedNoWaitUntil) {
4678
+ warnedNoWaitUntil = true;
4679
+ 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().");
4680
+ }
4681
+ }
4682
+ /** Components already announced by the one-time dev log. */
4683
+ var devLoggedIds = /* @__PURE__ */ new Set();
4684
+ /**
4685
+ * Dev: the seed for a prerender entry — the stored capture, or a new one
4686
+ * rendered exactly as the build would render it (synthetic store, isolated
4687
+ * render, nested wrappers baked flat) and stored until the next source
4688
+ * change (prebuilt/dev-store.ts).
4689
+ *
4690
+ * Throws the BuildTimeContextError when the component read request
4691
+ * context: `pnpm build` would fail on it, so dev fails too. Null on any
4692
+ * other capture failure — the live render that follows reproduces the
4693
+ * error, deny(), or redirect() with its normal semantics.
4694
+ */
4695
+ async function resolveDevSeed(registration, props, keyParams, cacheKey) {
4696
+ const { id, options } = registration;
4697
+ const stored = getDevSeed(id, cacheKey);
4698
+ if (stored) return {
4699
+ payload: stored.bytes,
4700
+ capturedAt: stored.capturedAt
4701
+ };
4702
+ const tags = resolveTags(options, props);
4703
+ const oKey = overlayKey(id, cacheKey);
4704
+ const sfKey = `prebuilt-dev:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
4705
+ try {
4706
+ return await componentSingleflight.do(sfKey, async (signal) => {
4707
+ const startEpoch = currentInvalidationEpoch();
4708
+ const capturedAt = Date.now();
4709
+ const { renderFlight } = requireRscFunctions();
4710
+ const outcome = await runOutsideReactCacheScope(() => renderEntry(registration, props, keyParams, getCaptureTimeoutMs(), false, renderFlight));
4711
+ if (outcome.failure instanceof BuildTimeContextError) throw outcome.failure;
4712
+ if (outcome.bytes === null) return null;
4713
+ if (await revivePayload(id, outcome.bytes, "not storing the dev capture") === null) return null;
4714
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) {
4715
+ setDevSeed(id, cacheKey, {
4716
+ bytes: outcome.bytes,
4717
+ tags,
4718
+ capturedAt
4719
+ });
4720
+ warnNestingClamps({
4721
+ id,
4722
+ options,
4723
+ tags
4724
+ }, outcome.nested, warnedNestingPairs, (m) => console.warn(m));
4725
+ if (!devLoggedIds.has(id)) {
4726
+ devLoggedIds.add(id);
4727
+ console.log(`[timber] cache.component "${id}": prerendered in dev — served from memory until a file changes. A hard reload (Cache-Control: no-cache) renders it again.`);
4728
+ }
4729
+ }
4730
+ return {
4731
+ payload: outcome.bytes,
4732
+ capturedAt
4733
+ };
4734
+ });
4735
+ } catch (error) {
4736
+ if (error instanceof BuildTimeContextError) throw error;
4737
+ console.error(`[timber] cache.component dev capture failed for "${id}":`, error);
4738
+ return null;
4739
+ }
4740
+ }
4741
+ /**
4742
+ * Try to serve this render from the prebuilt cache: overlay → seed →
4743
+ * live render. Handles ISR (SWR, tombstones, re-renders) per design/45.
4744
+ *
4745
+ * Null on any miss — the caller renders live.
4746
+ */
4747
+ async function tryRevivePayload(registration, props, keyPropsOverride) {
4748
+ const { id, options, component } = registration;
4749
+ const hasSource = hasPrebuiltPayloadSource();
4750
+ const devStore = isDevPrebuiltStoreActive();
4751
+ const hasRuntime = hasRuntimeLifetime(options);
4752
+ if (!hasSource && !devStore && !hasRuntime) return null;
4753
+ const store = requestContextAls.getStore();
4754
+ if (!store) return null;
4755
+ const keyParams = (options.prerender ? await isParamIndependent(id) : false) ? {} : resolveKeyParams(store);
4756
+ if (keyParams === null) return null;
4757
+ const cacheKey = computeComponentCacheKey(withoutChildrenOutlet(keyPropsOverride ?? props ?? {}), keyParams);
4758
+ if (cacheKey === null) return null;
4759
+ const outcome = options.fallbackOnMissingSegmentParams === false ? "failing the render (fallbackOnMissingSegmentParams: false)" : "rendering dynamically";
4760
+ if (devStore && isHardReload(store.originalHeaders)) await discardDevEntry(id, cacheKey, overlayKey(id, cacheKey));
4761
+ if (hasRuntime) {
4762
+ const overlayResult = await lookupOverlay(id, cacheKey);
4763
+ if (overlayResult) {
4764
+ const overlayHasSeed = overlayResult.record?.s ?? false;
4765
+ if (overlayResult.kind === "tombstone") return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
4766
+ if (overlayResult.kind === "fresh" && overlayResult.payload) return await revivePayload(id, overlayResult.payload, outcome);
4767
+ if (overlayResult.kind === "stale" && overlayResult.payload) {
4768
+ if (options.staleWhileRevalidate) {
4769
+ backgroundRerender(id, component, props, cacheKey, options, overlayHasSeed, snapshotRequestContext(store));
4770
+ return await revivePayload(id, overlayResult.payload, outcome);
4771
+ }
4772
+ return await inlineRerender(id, component, props, cacheKey, options, overlayHasSeed, outcome);
4773
+ }
4774
+ }
4775
+ }
4776
+ const seed = devStore ? options.prerender ? await resolveDevSeed(registration, props, keyParams, cacheKey) : null : hasSource ? await lookupArtifactSeed(id, cacheKey, options.ttl !== void 0) : null;
4777
+ if (seed !== null) {
4778
+ if (options.ttl !== void 0) {
4779
+ if ((Date.now() - seed.capturedAt) / 1e3 > options.ttl) {
4780
+ if (options.staleWhileRevalidate) {
4781
+ backgroundRerender(id, component, props, cacheKey, options, true, snapshotRequestContext(store));
4782
+ return await revivePayload(id, seed.payload, outcome);
4783
+ }
4784
+ return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
4785
+ }
4786
+ }
4787
+ return await revivePayload(id, seed.payload, outcome);
4788
+ }
4789
+ if (hasSource && options.prerender) console.warn(`[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(store.segmentParams ?? {})} — ${outcome}`);
4790
+ if (hasRuntime && options.fallbackOnMissingSegmentParams !== false) return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
4791
+ return null;
4792
+ }
4793
+ /**
4794
+ * Production wrapper injected by the timber-prebuilt transform. Registers
4795
+ * the component under its stable ID and returns a wrapper component that
4796
+ * either revives the cached payload (hit) or renders the original
4797
+ * component live (miss).
4798
+ */
4799
+ function __prebuilt(id, component, options = {}) {
4800
+ const resolution = resolveSlotNames(id, options);
4801
+ const slots = resolution.kind === "active" ? resolution.slots : null;
4802
+ if (resolution.kind === "active" && options.prerender) {
4803
+ 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.`);
4804
+ options = {
4805
+ ...options,
4806
+ prerender: void 0
4807
+ };
4808
+ }
4809
+ if (resolution.kind === "disabled") options = {
4810
+ ...options,
4811
+ slots: void 0
4812
+ };
4813
+ const registration = {
4814
+ id,
4815
+ component,
4816
+ options
4817
+ };
4818
+ if (isDevPrebuiltStoreActive()) {
4819
+ if (devRegisteredIds.has(id)) clearDevPrebuiltStore();
4820
+ devRegisteredIds.add(id);
4821
+ } else registry.set(id, registration);
4822
+ const wrapper = async (props) => {
4823
+ noteWrapperRender(id, options, props);
4824
+ if (isCaptureActive()) return createElement(component, props);
4825
+ if (isDevPrebuiltCacheBypassed()) return createElement(component, props);
4826
+ const revived = slots ? await tryReviveSlotShell(registration, slots, props) : await tryRevivePayload(registration, props);
4827
+ if (revived !== null) return revived.element;
4828
+ if (options.fallbackOnMissingSegmentParams === false) throw new Error(`[timber] cache.component "${id}": no prebuilt payload for the current params and fallbackOnMissingSegmentParams is false`);
4829
+ return createElement(component, props);
4830
+ };
4831
+ Object.defineProperty(wrapper, "name", { value: `Prebuilt(${id})` });
4832
+ return wrapper;
4833
+ }
4834
+ /** Look up a registration by stable component ID. */
4835
+ function getPrebuiltRegistration(id) {
4836
+ return registry.get(id);
4837
+ }
4838
+ /** All registrations, for the post-build capture pass (TIM-1119). */
4839
+ function getPrebuiltRegistry() {
4840
+ return registry;
4841
+ }
4842
+ //#endregion
4843
+ export { AccessGate, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RenderTimeoutError, SlotAccessGate, __prebuilt, 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 };
4844
+
4845
+ //# sourceMappingURL=internal.js.map