@timber-js/app 0.2.0-alpha.13 → 0.2.0-alpha.132

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 (784) hide show
  1. package/dist/_chunks/actions-BNhpxrnV.js +1104 -0
  2. package/dist/_chunks/actions-BNhpxrnV.js.map +1 -0
  3. package/dist/_chunks/build-output-helper-K7oUCRqU.js +102 -0
  4. package/dist/_chunks/build-output-helper-K7oUCRqU.js.map +1 -0
  5. package/dist/_chunks/cli-schema-sync-CObqjGWF.js +2 -0
  6. package/dist/_chunks/cli-schema-sync-q-Ce6-iG.js +785 -0
  7. package/dist/_chunks/cli-schema-sync-q-Ce6-iG.js.map +1 -0
  8. package/dist/_chunks/codec-registry-DqkeAydt.js +21 -0
  9. package/dist/_chunks/codec-registry-DqkeAydt.js.map +1 -0
  10. package/dist/_chunks/define-DMq-Yjp7.js +112 -0
  11. package/dist/_chunks/define-DMq-Yjp7.js.map +1 -0
  12. package/dist/_chunks/define-jeHDXZGq.js +195 -0
  13. package/dist/_chunks/define-jeHDXZGq.js.map +1 -0
  14. package/dist/_chunks/format-BjN9HLu9.js +14 -0
  15. package/dist/_chunks/format-BjN9HLu9.js.map +1 -0
  16. package/dist/_chunks/handler-store-bIAstrxQ.js +54 -0
  17. package/dist/_chunks/handler-store-bIAstrxQ.js.map +1 -0
  18. package/dist/_chunks/logger-CMd9P1xQ.js +291 -0
  19. package/dist/_chunks/logger-CMd9P1xQ.js.map +1 -0
  20. package/dist/_chunks/merge-search-params-Cm1j99HC.js +41 -0
  21. package/dist/_chunks/merge-search-params-Cm1j99HC.js.map +1 -0
  22. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → metadata-routes-DESG8uk5.js} +32 -19
  23. package/dist/_chunks/metadata-routes-DESG8uk5.js.map +1 -0
  24. package/dist/_chunks/navigation-root-B5-RmsPi.js +103 -0
  25. package/dist/_chunks/navigation-root-B5-RmsPi.js.map +1 -0
  26. package/dist/_chunks/registry-BI9cgCt7.js +20 -0
  27. package/dist/_chunks/registry-BI9cgCt7.js.map +1 -0
  28. package/dist/_chunks/resolve-schema-DU2nbVOi.js +77 -0
  29. package/dist/_chunks/resolve-schema-DU2nbVOi.js.map +1 -0
  30. package/dist/_chunks/router-ref-B2-2kIIC.js +28 -0
  31. package/dist/_chunks/router-ref-B2-2kIIC.js.map +1 -0
  32. package/dist/_chunks/schema-bridge-o0SwFtXW.js +86 -0
  33. package/dist/_chunks/schema-bridge-o0SwFtXW.js.map +1 -0
  34. package/dist/_chunks/segment-classify-BjfuctV2.js +137 -0
  35. package/dist/_chunks/segment-classify-BjfuctV2.js.map +1 -0
  36. package/dist/_chunks/segment-context-Bg0pFbLT.js +34 -0
  37. package/dist/_chunks/segment-context-Bg0pFbLT.js.map +1 -0
  38. package/dist/_chunks/{ssr-data-MjmprTmO.js → ssr-data-DVX8S7vj.js} +1 -1
  39. package/dist/_chunks/ssr-data-DVX8S7vj.js.map +1 -0
  40. package/dist/_chunks/stale-reload-CCqb62Z3.js +84 -0
  41. package/dist/_chunks/stale-reload-CCqb62Z3.js.map +1 -0
  42. package/dist/_chunks/tracing-DP5djRq5.js +358 -0
  43. package/dist/_chunks/tracing-DP5djRq5.js.map +1 -0
  44. package/dist/_chunks/{use-query-states-D5KaffOK.js → use-query-states-C9G6LP0F.js} +7 -20
  45. package/dist/_chunks/use-query-states-C9G6LP0F.js.map +1 -0
  46. package/dist/_chunks/use-segment-params-CIeinIx2.js +151 -0
  47. package/dist/_chunks/use-segment-params-CIeinIx2.js.map +1 -0
  48. package/dist/_chunks/validation-AfEFM5ze.js +84 -0
  49. package/dist/_chunks/validation-AfEFM5ze.js.map +1 -0
  50. package/dist/_chunks/walkers-BbEu2_Pp.js +724 -0
  51. package/dist/_chunks/walkers-BbEu2_Pp.js.map +1 -0
  52. package/dist/_chunks/{format-DviM89f0.js → warnings-CAzunaGo.js} +6 -45
  53. package/dist/_chunks/warnings-CAzunaGo.js.map +1 -0
  54. package/dist/adapters/build-output-helper.d.ts +28 -0
  55. package/dist/adapters/build-output-helper.d.ts.map +1 -0
  56. package/dist/adapters/cloudflare-dev.d.ts +109 -0
  57. package/dist/adapters/cloudflare-dev.d.ts.map +1 -0
  58. package/dist/adapters/cloudflare-dev.js +73 -0
  59. package/dist/adapters/cloudflare-dev.js.map +1 -0
  60. package/dist/adapters/cloudflare-kv-cache.d.ts +64 -0
  61. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -0
  62. package/dist/adapters/cloudflare-kv-cache.js +95 -0
  63. package/dist/adapters/cloudflare-kv-cache.js.map +1 -0
  64. package/dist/adapters/cloudflare.d.ts +148 -12
  65. package/dist/adapters/cloudflare.d.ts.map +1 -1
  66. package/dist/adapters/cloudflare.js +142 -38
  67. package/dist/adapters/cloudflare.js.map +1 -1
  68. package/dist/adapters/compress-module.d.ts.map +1 -1
  69. package/dist/adapters/nitro.d.ts +17 -1
  70. package/dist/adapters/nitro.d.ts.map +1 -1
  71. package/dist/adapters/nitro.js +143 -45
  72. package/dist/adapters/nitro.js.map +1 -1
  73. package/dist/adapters/shared.d.ts +16 -0
  74. package/dist/adapters/shared.d.ts.map +1 -0
  75. package/dist/cache/cache-api.d.ts +24 -0
  76. package/dist/cache/cache-api.d.ts.map +1 -0
  77. package/dist/cache/handler-store.d.ts +31 -0
  78. package/dist/cache/handler-store.d.ts.map +1 -0
  79. package/dist/cache/index.d.ts +23 -7
  80. package/dist/cache/index.d.ts.map +1 -1
  81. package/dist/cache/index.js +151 -81
  82. package/dist/cache/index.js.map +1 -1
  83. package/dist/cache/singleflight.d.ts +18 -1
  84. package/dist/cache/singleflight.d.ts.map +1 -1
  85. package/dist/cache/sizeof.d.ts +22 -0
  86. package/dist/cache/sizeof.d.ts.map +1 -0
  87. package/dist/cache/timber-cache.d.ts +1 -1
  88. package/dist/cache/timber-cache.d.ts.map +1 -1
  89. package/dist/cli-schema-sync.d.ts +39 -0
  90. package/dist/cli-schema-sync.d.ts.map +1 -0
  91. package/dist/cli.d.ts +14 -2
  92. package/dist/cli.d.ts.map +1 -1
  93. package/dist/cli.js +48 -6
  94. package/dist/cli.js.map +1 -1
  95. package/dist/client/browser-dev.d.ts +34 -1
  96. package/dist/client/browser-dev.d.ts.map +1 -1
  97. package/dist/client/browser-entry/action-dispatch.d.ts +17 -0
  98. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  99. package/dist/client/browser-entry/hmr.d.ts +21 -0
  100. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  101. package/dist/client/browser-entry/hydrate.d.ts +46 -0
  102. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  103. package/dist/client/browser-entry/index.d.ts +30 -0
  104. package/dist/client/browser-entry/index.d.ts.map +1 -0
  105. package/dist/client/browser-entry/post-hydration.d.ts +26 -0
  106. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  107. package/dist/client/browser-entry/router-init.d.ts +26 -0
  108. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  109. package/dist/client/browser-entry/rsc-stream.d.ts +24 -0
  110. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  111. package/dist/client/browser-entry/scroll.d.ts +19 -0
  112. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  113. package/dist/client/error-boundary.d.ts +12 -5
  114. package/dist/client/error-boundary.d.ts.map +1 -1
  115. package/dist/client/error-boundary.js +29 -6
  116. package/dist/client/error-boundary.js.map +1 -1
  117. package/dist/client/error-reconstituter.d.ts +54 -0
  118. package/dist/client/error-reconstituter.d.ts.map +1 -0
  119. package/dist/client/form.d.ts +16 -27
  120. package/dist/client/form.d.ts.map +1 -1
  121. package/dist/client/history.d.ts +19 -4
  122. package/dist/client/history.d.ts.map +1 -1
  123. package/dist/client/index.d.ts +10 -24
  124. package/dist/client/index.d.ts.map +1 -1
  125. package/dist/client/index.js +180 -1119
  126. package/dist/client/index.js.map +1 -1
  127. package/dist/client/internal.d.ts +19 -0
  128. package/dist/client/internal.d.ts.map +1 -0
  129. package/dist/client/internal.js +845 -0
  130. package/dist/client/internal.js.map +1 -0
  131. package/dist/client/link-pending-store.d.ts +65 -0
  132. package/dist/client/link-pending-store.d.ts.map +1 -0
  133. package/dist/client/link.d.ts +67 -56
  134. package/dist/client/link.d.ts.map +1 -1
  135. package/dist/client/nav-link-store.d.ts +27 -0
  136. package/dist/client/nav-link-store.d.ts.map +1 -0
  137. package/dist/client/navigation-api-types.d.ts +90 -0
  138. package/dist/client/navigation-api-types.d.ts.map +1 -0
  139. package/dist/client/navigation-api.d.ts +115 -0
  140. package/dist/client/navigation-api.d.ts.map +1 -0
  141. package/dist/client/navigation-context.d.ts +14 -2
  142. package/dist/client/navigation-context.d.ts.map +1 -1
  143. package/dist/client/{transition-root.d.ts → navigation-root.d.ts} +46 -9
  144. package/dist/client/navigation-root.d.ts.map +1 -0
  145. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  146. package/dist/client/router-ref.d.ts +1 -1
  147. package/dist/client/router.d.ts +79 -10
  148. package/dist/client/router.d.ts.map +1 -1
  149. package/dist/client/rsc-fetch.d.ts +46 -3
  150. package/dist/client/rsc-fetch.d.ts.map +1 -1
  151. package/dist/client/segment-cache.d.ts +3 -1
  152. package/dist/client/segment-cache.d.ts.map +1 -1
  153. package/dist/client/segment-outlet.d.ts +49 -0
  154. package/dist/client/segment-outlet.d.ts.map +1 -0
  155. package/dist/client/segment-update-context.d.ts +21 -0
  156. package/dist/client/segment-update-context.d.ts.map +1 -0
  157. package/dist/client/shallow-url.d.ts +10 -0
  158. package/dist/client/shallow-url.d.ts.map +1 -0
  159. package/dist/client/ssr-data.d.ts +13 -4
  160. package/dist/client/ssr-data.d.ts.map +1 -1
  161. package/dist/client/stale-reload.d.ts +15 -0
  162. package/dist/client/stale-reload.d.ts.map +1 -1
  163. package/dist/client/state.d.ts +1 -1
  164. package/dist/client/top-loader.d.ts +5 -5
  165. package/dist/client/top-loader.d.ts.map +1 -1
  166. package/dist/client/use-cookie.d.ts +12 -0
  167. package/dist/client/use-cookie.d.ts.map +1 -1
  168. package/dist/client/use-link-status.d.ts +5 -5
  169. package/dist/client/use-link-status.d.ts.map +1 -1
  170. package/dist/client/use-pending-navigation.d.ts +23 -0
  171. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  172. package/dist/client/use-query-states.d.ts +1 -1
  173. package/dist/client/use-query-states.d.ts.map +1 -1
  174. package/dist/client/use-router.d.ts +1 -1
  175. package/dist/client/use-search-params.d.ts +7 -5
  176. package/dist/client/use-search-params.d.ts.map +1 -1
  177. package/dist/client/{use-params.d.ts → use-segment-params.d.ts} +8 -6
  178. package/dist/client/use-segment-params.d.ts.map +1 -0
  179. package/dist/codec.d.ts +69 -0
  180. package/dist/codec.d.ts.map +1 -0
  181. package/dist/codec.js +75 -0
  182. package/dist/codec.js.map +1 -0
  183. package/dist/config-types.d.ts +294 -0
  184. package/dist/config-types.d.ts.map +1 -0
  185. package/dist/config-validation.d.ts +51 -0
  186. package/dist/config-validation.d.ts.map +1 -0
  187. package/dist/content/index.d.ts +1 -10
  188. package/dist/content/index.d.ts.map +1 -1
  189. package/dist/content/index.js +0 -2
  190. package/dist/cookies/define-cookie.d.ts +58 -25
  191. package/dist/cookies/define-cookie.d.ts.map +1 -1
  192. package/dist/cookies/index.d.ts +2 -1
  193. package/dist/cookies/index.d.ts.map +1 -1
  194. package/dist/cookies/index.js +251 -36
  195. package/dist/cookies/index.js.map +1 -1
  196. package/dist/cookies/json-cookie.d.ts +64 -0
  197. package/dist/cookies/json-cookie.d.ts.map +1 -0
  198. package/dist/cookies/validation.d.ts +46 -0
  199. package/dist/cookies/validation.d.ts.map +1 -0
  200. package/dist/dev-tools/404-page.d.ts +46 -0
  201. package/dist/dev-tools/404-page.d.ts.map +1 -0
  202. package/dist/dev-tools/browser-logs.d.ts +84 -0
  203. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  204. package/dist/dev-tools/error-page.d.ts +58 -0
  205. package/dist/dev-tools/error-page.d.ts.map +1 -0
  206. package/dist/dev-tools/holding-server.d.ts +54 -0
  207. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  208. package/dist/dev-tools/index.d.ts +31 -0
  209. package/dist/dev-tools/index.d.ts.map +1 -0
  210. package/dist/{server/dev-span-processor.d.ts → dev-tools/instrumentation.d.ts} +26 -6
  211. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  212. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  213. package/dist/dev-tools/logger.d.ts.map +1 -0
  214. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +2 -2
  215. package/dist/dev-tools/logs.d.ts.map +1 -0
  216. package/dist/dev-tools/overlay.d.ts +91 -0
  217. package/dist/dev-tools/overlay.d.ts.map +1 -0
  218. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  219. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  220. package/dist/dev-tools/terminal.d.ts +28 -0
  221. package/dist/dev-tools/terminal.d.ts.map +1 -0
  222. package/dist/{server/dev-warnings.d.ts → dev-tools/warnings.d.ts} +2 -22
  223. package/dist/dev-tools/warnings.d.ts.map +1 -0
  224. package/dist/fonts/ast.d.ts +98 -6
  225. package/dist/fonts/ast.d.ts.map +1 -1
  226. package/dist/fonts/bundle.d.ts +48 -0
  227. package/dist/fonts/bundle.d.ts.map +1 -0
  228. package/dist/fonts/dev-middleware.d.ts +22 -0
  229. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  230. package/dist/fonts/local.d.ts +1 -1
  231. package/dist/fonts/pipeline.d.ts +167 -0
  232. package/dist/fonts/pipeline.d.ts.map +1 -0
  233. package/dist/fonts/transform.d.ts +78 -0
  234. package/dist/fonts/transform.d.ts.map +1 -0
  235. package/dist/fonts/types.d.ts +45 -1
  236. package/dist/fonts/types.d.ts.map +1 -1
  237. package/dist/fonts/virtual-modules.d.ts +94 -0
  238. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  239. package/dist/index.d.ts +46 -164
  240. package/dist/index.d.ts.map +1 -1
  241. package/dist/index.js +5584 -13386
  242. package/dist/index.js.map +1 -1
  243. package/dist/params/codec-registry.d.ts +26 -0
  244. package/dist/params/codec-registry.d.ts.map +1 -0
  245. package/dist/params/define-schema.d.ts +81 -0
  246. package/dist/params/define-schema.d.ts.map +1 -0
  247. package/dist/params/index.d.ts +5 -0
  248. package/dist/params/index.d.ts.map +1 -0
  249. package/dist/params/index.js +34 -0
  250. package/dist/params/index.js.map +1 -0
  251. package/dist/params/resolve-schema.d.ts +34 -0
  252. package/dist/params/resolve-schema.d.ts.map +1 -0
  253. package/dist/plugin-context.d.ts +107 -0
  254. package/dist/plugin-context.d.ts.map +1 -0
  255. package/dist/plugins/adapter-build.d.ts +1 -1
  256. package/dist/plugins/adapter-build.d.ts.map +1 -1
  257. package/dist/plugins/build-manifest.d.ts +2 -2
  258. package/dist/plugins/build-manifest.d.ts.map +1 -1
  259. package/dist/plugins/build-report.d.ts +9 -7
  260. package/dist/plugins/build-report.d.ts.map +1 -1
  261. package/dist/plugins/client-chunks.d.ts +32 -0
  262. package/dist/plugins/client-chunks.d.ts.map +1 -0
  263. package/dist/plugins/cloudflare-wasm.d.ts +18 -0
  264. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  265. package/dist/plugins/content.d.ts +1 -1
  266. package/dist/plugins/content.d.ts.map +1 -1
  267. package/dist/plugins/dev-server.d.ts +1 -1
  268. package/dist/plugins/dev-server.d.ts.map +1 -1
  269. package/dist/plugins/entries.d.ts +1 -1
  270. package/dist/plugins/entries.d.ts.map +1 -1
  271. package/dist/plugins/fonts.d.ts +17 -73
  272. package/dist/plugins/fonts.d.ts.map +1 -1
  273. package/dist/plugins/mdx.d.ts +1 -1
  274. package/dist/plugins/mdx.d.ts.map +1 -1
  275. package/dist/plugins/routing.d.ts +1 -1
  276. package/dist/plugins/routing.d.ts.map +1 -1
  277. package/dist/plugins/server-bundle.d.ts.map +1 -1
  278. package/dist/plugins/shims.d.ts +6 -5
  279. package/dist/plugins/shims.d.ts.map +1 -1
  280. package/dist/plugins/static-build.d.ts +5 -26
  281. package/dist/plugins/static-build.d.ts.map +1 -1
  282. package/dist/routing/codegen-shared.d.ts +67 -0
  283. package/dist/routing/codegen-shared.d.ts.map +1 -0
  284. package/dist/routing/codegen-types.d.ts +60 -0
  285. package/dist/routing/codegen-types.d.ts.map +1 -0
  286. package/dist/routing/codegen.d.ts +7 -2
  287. package/dist/routing/codegen.d.ts.map +1 -1
  288. package/dist/routing/convention-lint.d.ts +41 -0
  289. package/dist/routing/convention-lint.d.ts.map +1 -0
  290. package/dist/routing/index.d.ts +7 -1
  291. package/dist/routing/index.d.ts.map +1 -1
  292. package/dist/routing/index.js +4 -2
  293. package/dist/routing/link-codegen.d.ts +90 -0
  294. package/dist/routing/link-codegen.d.ts.map +1 -0
  295. package/dist/routing/scanner.d.ts +1 -10
  296. package/dist/routing/scanner.d.ts.map +1 -1
  297. package/dist/routing/schema-validation.d.ts +35 -0
  298. package/dist/routing/schema-validation.d.ts.map +1 -0
  299. package/dist/routing/segment-classify.d.ts +75 -0
  300. package/dist/routing/segment-classify.d.ts.map +1 -0
  301. package/dist/routing/segment-codegen.d.ts +38 -0
  302. package/dist/routing/segment-codegen.d.ts.map +1 -0
  303. package/dist/routing/types.d.ts +77 -25
  304. package/dist/routing/types.d.ts.map +1 -1
  305. package/dist/routing/walkers.d.ts +51 -0
  306. package/dist/routing/walkers.d.ts.map +1 -0
  307. package/dist/rsc-runtime/rsc.d.ts +1 -1
  308. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  309. package/dist/rsc-runtime/ssr.d.ts +12 -0
  310. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  311. package/dist/schema-bridge.d.ts +76 -0
  312. package/dist/schema-bridge.d.ts.map +1 -0
  313. package/dist/search-params/define.d.ts +157 -0
  314. package/dist/search-params/define.d.ts.map +1 -0
  315. package/dist/search-params/index.d.ts +4 -7
  316. package/dist/search-params/index.d.ts.map +1 -1
  317. package/dist/search-params/index.js +34 -441
  318. package/dist/search-params/index.js.map +1 -1
  319. package/dist/search-params/registry.d.ts +2 -2
  320. package/dist/search-params/registry.d.ts.map +1 -1
  321. package/dist/search-params/wrappers.d.ts +53 -0
  322. package/dist/search-params/wrappers.d.ts.map +1 -0
  323. package/dist/segment-params/define.d.ts +89 -0
  324. package/dist/segment-params/define.d.ts.map +1 -0
  325. package/dist/segment-params/index.d.ts +3 -0
  326. package/dist/segment-params/index.d.ts.map +1 -0
  327. package/dist/segment-params/index.js +2 -0
  328. package/dist/server/access-gate.d.ts +8 -3
  329. package/dist/server/access-gate.d.ts.map +1 -1
  330. package/dist/server/action-client.d.ts +41 -6
  331. package/dist/server/action-client.d.ts.map +1 -1
  332. package/dist/server/action-encryption.d.ts +76 -0
  333. package/dist/server/action-encryption.d.ts.map +1 -0
  334. package/dist/server/action-handler.d.ts +35 -1
  335. package/dist/server/action-handler.d.ts.map +1 -1
  336. package/dist/server/actions.d.ts +6 -14
  337. package/dist/server/actions.d.ts.map +1 -1
  338. package/dist/server/als-registry.d.ts +70 -11
  339. package/dist/server/als-registry.d.ts.map +1 -1
  340. package/dist/server/asset-headers.d.ts +1 -15
  341. package/dist/server/asset-headers.d.ts.map +1 -1
  342. package/dist/server/build-manifest.d.ts +8 -2
  343. package/dist/server/build-manifest.d.ts.map +1 -1
  344. package/dist/server/coalesce-tick.d.ts +40 -0
  345. package/dist/server/coalesce-tick.d.ts.map +1 -0
  346. package/dist/server/cookie-context.d.ts +170 -0
  347. package/dist/server/cookie-context.d.ts.map +1 -0
  348. package/dist/server/cookie-parsing.d.ts +51 -0
  349. package/dist/server/cookie-parsing.d.ts.map +1 -0
  350. package/dist/server/debug.d.ts +1 -1
  351. package/dist/server/default-logger.d.ts +22 -0
  352. package/dist/server/default-logger.d.ts.map +1 -0
  353. package/dist/server/deny-boundary.d.ts +90 -0
  354. package/dist/server/deny-boundary.d.ts.map +1 -0
  355. package/dist/server/deny-renderer.d.ts +1 -1
  356. package/dist/server/deny-renderer.d.ts.map +1 -1
  357. package/dist/server/dev-source-map.d.ts +22 -0
  358. package/dist/server/dev-source-map.d.ts.map +1 -0
  359. package/dist/server/early-hints-sender.d.ts.map +1 -1
  360. package/dist/server/early-hints.d.ts +13 -5
  361. package/dist/server/early-hints.d.ts.map +1 -1
  362. package/dist/server/error-boundary-wrapper.d.ts +7 -1
  363. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  364. package/dist/server/fallback-error.d.ts +12 -7
  365. package/dist/server/fallback-error.d.ts.map +1 -1
  366. package/dist/server/flight-injection-state.d.ts +66 -0
  367. package/dist/server/flight-injection-state.d.ts.map +1 -0
  368. package/dist/server/flight-scripts.d.ts +42 -0
  369. package/dist/server/flight-scripts.d.ts.map +1 -0
  370. package/dist/server/flush.d.ts.map +1 -1
  371. package/dist/server/form-data.d.ts +29 -0
  372. package/dist/server/form-data.d.ts.map +1 -1
  373. package/dist/server/html-injector-core.d.ts +213 -0
  374. package/dist/server/html-injector-core.d.ts.map +1 -0
  375. package/dist/server/html-injectors.d.ts +81 -41
  376. package/dist/server/html-injectors.d.ts.map +1 -1
  377. package/dist/server/index.d.ts +10 -46
  378. package/dist/server/index.d.ts.map +1 -1
  379. package/dist/server/index.js +155 -2905
  380. package/dist/server/index.js.map +1 -1
  381. package/dist/server/internal.d.ts +48 -0
  382. package/dist/server/internal.d.ts.map +1 -0
  383. package/dist/server/internal.js +3073 -0
  384. package/dist/server/internal.js.map +1 -0
  385. package/dist/server/logger.d.ts +39 -7
  386. package/dist/server/logger.d.ts.map +1 -1
  387. package/dist/server/metadata-routes.d.ts +23 -7
  388. package/dist/server/metadata-routes.d.ts.map +1 -1
  389. package/dist/server/middleware-runner.d.ts +36 -4
  390. package/dist/server/middleware-runner.d.ts.map +1 -1
  391. package/dist/server/node-stream-transforms.d.ts +112 -0
  392. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  393. package/dist/server/param-coercion.d.ts +54 -0
  394. package/dist/server/param-coercion.d.ts.map +1 -0
  395. package/dist/server/pipeline-helpers.d.ts +95 -0
  396. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  397. package/dist/server/pipeline-interception.d.ts +1 -1
  398. package/dist/server/pipeline-interception.d.ts.map +1 -1
  399. package/dist/server/pipeline-metadata.d.ts +6 -0
  400. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  401. package/dist/server/pipeline-outcome.d.ts +49 -0
  402. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  403. package/dist/server/pipeline-phases.d.ts +52 -0
  404. package/dist/server/pipeline-phases.d.ts.map +1 -0
  405. package/dist/server/pipeline.d.ts +118 -23
  406. package/dist/server/pipeline.d.ts.map +1 -1
  407. package/dist/server/port-resolution.d.ts +117 -0
  408. package/dist/server/port-resolution.d.ts.map +1 -0
  409. package/dist/server/primitives.d.ts +69 -18
  410. package/dist/server/primitives.d.ts.map +1 -1
  411. package/dist/server/render-timeout.d.ts +51 -0
  412. package/dist/server/render-timeout.d.ts.map +1 -0
  413. package/dist/server/request-context.d.ts +62 -107
  414. package/dist/server/request-context.d.ts.map +1 -1
  415. package/dist/server/route-element-builder.d.ts +28 -2
  416. package/dist/server/route-element-builder.d.ts.map +1 -1
  417. package/dist/server/route-handler.d.ts.map +1 -1
  418. package/dist/server/route-matcher.d.ts +25 -36
  419. package/dist/server/route-matcher.d.ts.map +1 -1
  420. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  421. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  422. package/dist/server/rsc-entry/api-handler.d.ts +2 -2
  423. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  424. package/dist/server/rsc-entry/error-renderer.d.ts +26 -13
  425. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  426. package/dist/server/rsc-entry/helpers.d.ts +50 -6
  427. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  428. package/dist/server/rsc-entry/index.d.ts +19 -8
  429. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  430. package/dist/server/rsc-entry/render-route.d.ts +50 -0
  431. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  432. package/dist/server/rsc-entry/rsc-payload.d.ts +3 -3
  433. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  434. package/dist/server/rsc-entry/rsc-stream.d.ts +17 -1
  435. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  436. package/dist/server/rsc-entry/ssr-bridge.d.ts +5 -1
  437. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  438. package/dist/server/rsc-entry/ssr-renderer.d.ts +19 -4
  439. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  440. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +119 -0
  441. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
  442. package/dist/server/safe-load.d.ts +46 -0
  443. package/dist/server/safe-load.d.ts.map +1 -0
  444. package/dist/server/sensitive-fields.d.ts +74 -0
  445. package/dist/server/sensitive-fields.d.ts.map +1 -0
  446. package/dist/server/sitemap-generator.d.ts +129 -0
  447. package/dist/server/sitemap-generator.d.ts.map +1 -0
  448. package/dist/server/sitemap-handler.d.ts +22 -0
  449. package/dist/server/sitemap-handler.d.ts.map +1 -0
  450. package/dist/server/slot-resolver.d.ts +1 -1
  451. package/dist/server/slot-resolver.d.ts.map +1 -1
  452. package/dist/server/ssr-bridge-types.d.ts +121 -0
  453. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  454. package/dist/server/ssr-entry.d.ts +2 -43
  455. package/dist/server/ssr-entry.d.ts.map +1 -1
  456. package/dist/server/ssr-render.d.ts +64 -21
  457. package/dist/server/ssr-render.d.ts.map +1 -1
  458. package/dist/server/ssr-wrappers.d.ts +50 -0
  459. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  460. package/dist/server/state-tree-diff.d.ts +12 -5
  461. package/dist/server/state-tree-diff.d.ts.map +1 -1
  462. package/dist/server/status-code-resolver.d.ts +16 -11
  463. package/dist/server/status-code-resolver.d.ts.map +1 -1
  464. package/dist/server/stream-utils.d.ts +36 -0
  465. package/dist/server/stream-utils.d.ts.map +1 -0
  466. package/dist/server/tracing.d.ts +5 -5
  467. package/dist/server/tracing.d.ts.map +1 -1
  468. package/dist/server/tree-builder.d.ts +62 -30
  469. package/dist/server/tree-builder.d.ts.map +1 -1
  470. package/dist/server/tree-match.d.ts +49 -0
  471. package/dist/server/tree-match.d.ts.map +1 -0
  472. package/dist/server/types.d.ts +49 -4
  473. package/dist/server/types.d.ts.map +1 -1
  474. package/dist/server/utils/escape-html.d.ts +14 -0
  475. package/dist/server/utils/escape-html.d.ts.map +1 -0
  476. package/dist/server/version-skew.d.ts +61 -0
  477. package/dist/server/version-skew.d.ts.map +1 -0
  478. package/dist/shared/merge-search-params.d.ts +22 -0
  479. package/dist/shared/merge-search-params.d.ts.map +1 -0
  480. package/dist/shims/font-google.d.ts +1 -1
  481. package/dist/shims/font-google.d.ts.map +1 -1
  482. package/dist/shims/font-google.js +42 -0
  483. package/dist/shims/font-google.js.map +1 -0
  484. package/dist/shims/font-local.d.ts +26 -0
  485. package/dist/shims/font-local.d.ts.map +1 -0
  486. package/dist/shims/font-local.js +20 -0
  487. package/dist/shims/font-local.js.map +1 -0
  488. package/dist/shims/headers.d.ts +2 -1
  489. package/dist/shims/headers.d.ts.map +1 -1
  490. package/dist/shims/navigation-client.d.ts +3 -1
  491. package/dist/shims/navigation-client.d.ts.map +1 -1
  492. package/dist/shims/navigation.d.ts +11 -5
  493. package/dist/shims/navigation.d.ts.map +1 -1
  494. package/dist/utils/state-machine.d.ts +80 -0
  495. package/dist/utils/state-machine.d.ts.map +1 -0
  496. package/package.json +56 -16
  497. package/src/adapters/build-output-helper.ts +139 -0
  498. package/src/adapters/cloudflare-dev.ts +177 -0
  499. package/src/adapters/cloudflare-kv-cache.ts +142 -0
  500. package/src/adapters/cloudflare.ts +350 -76
  501. package/src/adapters/compress-module.ts +24 -4
  502. package/src/adapters/nitro.ts +142 -59
  503. package/src/adapters/shared.ts +40 -0
  504. package/src/adapters/wrangler.d.ts +7 -0
  505. package/src/cache/cache-api.ts +38 -0
  506. package/src/cache/handler-store.ts +68 -0
  507. package/src/cache/index.ts +81 -18
  508. package/src/cache/singleflight.ts +62 -4
  509. package/src/cache/sizeof.ts +33 -0
  510. package/src/cache/timber-cache.ts +25 -20
  511. package/src/cli-schema-sync.ts +295 -0
  512. package/src/cli.ts +76 -8
  513. package/src/client/browser-dev.ts +153 -1
  514. package/src/client/browser-entry/action-dispatch.ts +125 -0
  515. package/src/client/browser-entry/hmr.ts +81 -0
  516. package/src/client/browser-entry/hydrate.ts +153 -0
  517. package/src/client/browser-entry/index.ts +151 -0
  518. package/src/client/browser-entry/post-hydration.ts +113 -0
  519. package/src/client/browser-entry/router-init.ts +219 -0
  520. package/src/client/browser-entry/rsc-stream.ts +157 -0
  521. package/src/client/browser-entry/scroll.ts +27 -0
  522. package/src/client/error-boundary.tsx +99 -22
  523. package/src/client/error-reconstituter.tsx +65 -0
  524. package/src/client/form.tsx +31 -32
  525. package/src/client/history.ts +26 -4
  526. package/src/client/index.ts +66 -45
  527. package/src/client/internal.ts +58 -0
  528. package/src/client/link-pending-store.ts +116 -0
  529. package/src/client/link.tsx +336 -119
  530. package/src/client/nav-link-store.ts +37 -0
  531. package/src/client/navigation-api-types.ts +112 -0
  532. package/src/client/navigation-api.ts +332 -0
  533. package/src/client/navigation-context.ts +33 -7
  534. package/src/client/navigation-root.tsx +347 -0
  535. package/src/client/nuqs-adapter.tsx +16 -3
  536. package/src/client/router-ref.ts +1 -1
  537. package/src/client/router.ts +418 -128
  538. package/src/client/rsc-fetch.ts +208 -10
  539. package/src/client/segment-cache.ts +6 -3
  540. package/src/client/segment-outlet.tsx +77 -0
  541. package/src/client/segment-update-context.ts +42 -0
  542. package/src/client/shallow-url.ts +22 -0
  543. package/src/client/ssr-data.ts +13 -5
  544. package/src/client/stale-reload.ts +72 -3
  545. package/src/client/state.ts +2 -2
  546. package/src/client/top-loader.tsx +11 -9
  547. package/src/client/use-cookie.ts +31 -2
  548. package/src/client/use-link-status.ts +7 -7
  549. package/src/client/use-pending-navigation.ts +40 -0
  550. package/src/client/use-query-states.ts +9 -3
  551. package/src/client/use-router.ts +1 -1
  552. package/src/client/use-search-params.ts +25 -44
  553. package/src/client/{use-params.ts → use-segment-params.ts} +8 -6
  554. package/src/codec.ts +147 -0
  555. package/src/config-types.ts +292 -0
  556. package/src/config-validation.ts +303 -0
  557. package/src/content/index.ts +5 -13
  558. package/src/cookies/define-cookie.ts +233 -53
  559. package/src/cookies/index.ts +12 -1
  560. package/src/cookies/json-cookie.ts +105 -0
  561. package/src/cookies/validation.ts +134 -0
  562. package/src/dev-tools/404-page.ts +387 -0
  563. package/src/dev-tools/browser-logs.ts +291 -0
  564. package/src/dev-tools/error-page.ts +506 -0
  565. package/src/dev-tools/holding-server.ts +187 -0
  566. package/src/dev-tools/index.ts +90 -0
  567. package/src/dev-tools/instrumentation.ts +176 -0
  568. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +9 -5
  569. package/src/dev-tools/overlay.ts +469 -0
  570. package/src/dev-tools/stack-classifier.ts +75 -0
  571. package/src/dev-tools/terminal.ts +183 -0
  572. package/src/{server/dev-warnings.ts → dev-tools/warnings.ts} +5 -50
  573. package/src/fonts/ast.ts +525 -16
  574. package/src/fonts/bundle.ts +142 -0
  575. package/src/fonts/dev-middleware.ts +74 -0
  576. package/src/fonts/local.ts +1 -1
  577. package/src/fonts/pipeline.ts +314 -0
  578. package/src/fonts/transform.ts +317 -0
  579. package/src/fonts/types.ts +50 -1
  580. package/src/fonts/virtual-modules.ts +233 -0
  581. package/src/index.ts +411 -329
  582. package/src/params/codec-registry.ts +34 -0
  583. package/src/params/define-schema.ts +114 -0
  584. package/src/params/index.ts +17 -0
  585. package/src/params/resolve-schema.ts +116 -0
  586. package/src/plugin-context.ts +240 -0
  587. package/src/plugins/adapter-build.ts +12 -4
  588. package/src/plugins/build-manifest.ts +69 -6
  589. package/src/plugins/build-report.ts +16 -25
  590. package/src/plugins/client-chunks.ts +65 -0
  591. package/src/plugins/cloudflare-wasm.ts +103 -0
  592. package/src/plugins/content.ts +1 -1
  593. package/src/plugins/dev-server.ts +179 -37
  594. package/src/plugins/entries.ts +111 -8
  595. package/src/plugins/fonts.ts +165 -654
  596. package/src/plugins/mdx.ts +47 -10
  597. package/src/plugins/routing.ts +386 -47
  598. package/src/plugins/server-bundle.ts +59 -3
  599. package/src/plugins/shims.ts +136 -35
  600. package/src/plugins/static-build.ts +15 -89
  601. package/src/routing/codegen-shared.ts +115 -0
  602. package/src/routing/codegen-types.ts +61 -0
  603. package/src/routing/codegen.ts +321 -177
  604. package/src/routing/convention-lint.ts +357 -0
  605. package/src/routing/index.ts +10 -1
  606. package/src/routing/interception.ts +1 -1
  607. package/src/routing/link-codegen.ts +308 -0
  608. package/src/routing/scanner.ts +165 -110
  609. package/src/routing/schema-validation.ts +149 -0
  610. package/src/routing/segment-classify.ts +188 -0
  611. package/src/routing/segment-codegen.ts +98 -0
  612. package/src/routing/types.ts +78 -25
  613. package/src/routing/walkers.ts +90 -0
  614. package/src/rsc-runtime/rsc.ts +2 -0
  615. package/src/rsc-runtime/ssr.ts +50 -0
  616. package/src/rsc-runtime/vendor-types.d.ts +7 -0
  617. package/src/{search-params/codecs.ts → schema-bridge.ts} +57 -20
  618. package/src/search-params/define.ts +538 -0
  619. package/src/search-params/index.ts +14 -20
  620. package/src/search-params/registry.ts +2 -2
  621. package/src/search-params/wrappers.ts +92 -0
  622. package/src/segment-params/define.ts +309 -0
  623. package/src/segment-params/index.ts +9 -0
  624. package/src/server/access-gate.tsx +76 -34
  625. package/src/server/action-client.ts +88 -15
  626. package/src/server/action-encryption.ts +144 -0
  627. package/src/server/action-handler.ts +112 -14
  628. package/src/server/actions.ts +14 -23
  629. package/src/server/als-registry.ts +108 -20
  630. package/src/server/asset-headers.ts +8 -34
  631. package/src/server/build-manifest.ts +17 -4
  632. package/src/server/coalesce-tick.ts +75 -0
  633. package/src/server/compress.ts +25 -7
  634. package/src/server/cookie-context.ts +468 -0
  635. package/src/server/cookie-parsing.ts +135 -0
  636. package/src/server/debug.ts +1 -1
  637. package/src/server/default-logger.ts +99 -0
  638. package/src/server/deny-boundary.ts +218 -0
  639. package/src/server/deny-renderer.ts +32 -51
  640. package/src/server/dev-source-map.ts +31 -0
  641. package/src/server/early-hints-sender.ts +3 -2
  642. package/src/server/early-hints.ts +36 -15
  643. package/src/server/error-boundary-wrapper.ts +74 -22
  644. package/src/server/fallback-error.ts +74 -102
  645. package/src/server/flight-injection-state.ts +113 -0
  646. package/src/server/flight-scripts.ts +62 -0
  647. package/src/server/flush.ts +2 -1
  648. package/src/server/form-data.ts +101 -5
  649. package/src/server/html-injector-core.ts +417 -0
  650. package/src/server/html-injectors.ts +235 -223
  651. package/src/server/index.ts +29 -183
  652. package/src/server/internal.ts +182 -0
  653. package/src/server/logger.ts +67 -36
  654. package/src/server/metadata-routes.ts +44 -19
  655. package/src/server/middleware-runner.ts +75 -4
  656. package/src/server/node-stream-transforms.ts +361 -0
  657. package/src/server/param-coercion.ts +206 -0
  658. package/src/server/pipeline-helpers.ts +204 -0
  659. package/src/server/pipeline-interception.ts +31 -18
  660. package/src/server/pipeline-metadata.ts +13 -0
  661. package/src/server/pipeline-outcome.ts +197 -0
  662. package/src/server/pipeline-phases.ts +497 -0
  663. package/src/server/pipeline.ts +194 -394
  664. package/src/server/port-resolution.ts +215 -0
  665. package/src/server/primitives.ts +111 -28
  666. package/src/server/render-timeout.ts +108 -0
  667. package/src/server/request-context.ts +168 -337
  668. package/src/server/route-element-builder.ts +435 -208
  669. package/src/server/route-handler.ts +24 -4
  670. package/src/server/route-matcher.ts +128 -277
  671. package/src/server/rsc-entry/action-middleware-runner.ts +167 -0
  672. package/src/server/rsc-entry/api-handler.ts +16 -17
  673. package/src/server/rsc-entry/error-renderer.ts +315 -89
  674. package/src/server/rsc-entry/helpers.ts +155 -26
  675. package/src/server/rsc-entry/index.ts +316 -327
  676. package/src/server/rsc-entry/render-route.ts +313 -0
  677. package/src/server/rsc-entry/rsc-payload.ts +65 -18
  678. package/src/server/rsc-entry/rsc-stream.ts +85 -13
  679. package/src/server/rsc-entry/ssr-bridge.ts +18 -5
  680. package/src/server/rsc-entry/ssr-renderer.ts +195 -41
  681. package/src/server/rsc-entry/wrap-action-dispatch.ts +449 -0
  682. package/src/server/safe-load.ts +60 -0
  683. package/src/server/sensitive-fields.ts +230 -0
  684. package/src/server/sitemap-generator.ts +338 -0
  685. package/src/server/sitemap-handler.ts +126 -0
  686. package/src/server/slot-resolver.ts +228 -246
  687. package/src/server/ssr-bridge-types.ts +124 -0
  688. package/src/server/ssr-entry.ts +217 -78
  689. package/src/server/ssr-render.ts +344 -71
  690. package/src/server/ssr-wrappers.tsx +139 -0
  691. package/src/server/state-tree-diff.ts +30 -23
  692. package/src/server/status-code-resolver.ts +112 -128
  693. package/src/server/stream-utils.ts +213 -0
  694. package/src/server/tracing.ts +21 -10
  695. package/src/server/tree-builder.ts +202 -90
  696. package/src/server/tree-match.ts +210 -0
  697. package/src/server/types.ts +55 -6
  698. package/src/server/utils/escape-html.ts +20 -0
  699. package/src/server/version-skew.ts +104 -0
  700. package/src/shared/merge-search-params.ts +55 -0
  701. package/src/shims/font-google.ts +1 -1
  702. package/src/shims/font-local.ts +34 -0
  703. package/src/shims/headers.ts +5 -1
  704. package/src/shims/navigation-client.ts +4 -3
  705. package/src/shims/navigation.ts +14 -7
  706. package/src/utils/state-machine.ts +111 -0
  707. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  708. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  709. package/dist/_chunks/debug-gwlJkDuf.js +0 -108
  710. package/dist/_chunks/debug-gwlJkDuf.js.map +0 -1
  711. package/dist/_chunks/format-DviM89f0.js.map +0 -1
  712. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  713. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  714. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  715. package/dist/_chunks/request-context-DIkVh_jG.js +0 -330
  716. package/dist/_chunks/request-context-DIkVh_jG.js.map +0 -1
  717. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  718. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  719. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  720. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  721. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  722. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  723. package/dist/cache/register-cached-function.d.ts +0 -17
  724. package/dist/cache/register-cached-function.d.ts.map +0 -1
  725. package/dist/client/browser-entry.d.ts +0 -21
  726. package/dist/client/browser-entry.d.ts.map +0 -1
  727. package/dist/client/link-status-provider.d.ts +0 -11
  728. package/dist/client/link-status-provider.d.ts.map +0 -1
  729. package/dist/client/segment-merger.d.ts +0 -119
  730. package/dist/client/segment-merger.d.ts.map +0 -1
  731. package/dist/client/transition-root.d.ts.map +0 -1
  732. package/dist/client/use-navigation-pending.d.ts +0 -26
  733. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  734. package/dist/client/use-params.d.ts.map +0 -1
  735. package/dist/plugins/cache-transform.d.ts +0 -36
  736. package/dist/plugins/cache-transform.d.ts.map +0 -1
  737. package/dist/plugins/dev-error-overlay.d.ts +0 -60
  738. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  739. package/dist/plugins/dev-logs.d.ts.map +0 -1
  740. package/dist/plugins/dynamic-transform.d.ts +0 -72
  741. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  742. package/dist/plugins/server-action-exports.d.ts +0 -26
  743. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  744. package/dist/routing/status-file-lint.d.ts +0 -33
  745. package/dist/routing/status-file-lint.d.ts.map +0 -1
  746. package/dist/search-params/analyze.d.ts +0 -54
  747. package/dist/search-params/analyze.d.ts.map +0 -1
  748. package/dist/search-params/builtin-codecs.d.ts +0 -105
  749. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  750. package/dist/search-params/codecs.d.ts +0 -53
  751. package/dist/search-params/codecs.d.ts.map +0 -1
  752. package/dist/search-params/create.d.ts +0 -106
  753. package/dist/search-params/create.d.ts.map +0 -1
  754. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  755. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  756. package/dist/server/dev-logger.d.ts.map +0 -1
  757. package/dist/server/dev-span-processor.d.ts.map +0 -1
  758. package/dist/server/dev-warnings.d.ts.map +0 -1
  759. package/dist/server/manifest-status-resolver.d.ts +0 -58
  760. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  761. package/dist/server/prerender.d.ts +0 -77
  762. package/dist/server/prerender.d.ts.map +0 -1
  763. package/dist/utils/directive-parser.d.ts +0 -70
  764. package/dist/utils/directive-parser.d.ts.map +0 -1
  765. package/src/cache/register-cached-function.ts +0 -103
  766. package/src/client/browser-entry.ts +0 -678
  767. package/src/client/link-status-provider.tsx +0 -30
  768. package/src/client/segment-merger.ts +0 -339
  769. package/src/client/transition-root.tsx +0 -166
  770. package/src/client/use-navigation-pending.ts +0 -38
  771. package/src/plugins/cache-transform.ts +0 -199
  772. package/src/plugins/dev-error-overlay.ts +0 -230
  773. package/src/plugins/dynamic-transform.ts +0 -161
  774. package/src/plugins/server-action-exports.ts +0 -220
  775. package/src/routing/status-file-lint.ts +0 -112
  776. package/src/search-params/analyze.ts +0 -192
  777. package/src/search-params/builtin-codecs.ts +0 -228
  778. package/src/search-params/create.ts +0 -321
  779. package/src/server/dev-fetch-instrumentation.ts +0 -96
  780. package/src/server/dev-span-processor.ts +0 -78
  781. package/src/server/manifest-status-resolver.ts +0 -215
  782. package/src/server/prerender.ts +0 -139
  783. package/src/utils/directive-parser.ts +0 -529
  784. /package/src/{server/dev-logger.ts → dev-tools/logger.ts} +0 -0
@@ -0,0 +1,3073 @@
1
+ import { c as replaceTraceId, d as withSpan, f as earlyHintsSenderAls, g as timingAls, i as getOtelTraceId, l as runWithTraceId, m as requestContextAls, o as getTraceId, r as generateTraceId, u as setSpanAttribute, v as isDebug } from "../_chunks/tracing-DP5djRq5.js";
2
+ import { a as warnRedirectInSuspense, c as warnSuspenseWrappingChildren, i as warnRedirectInAccess, n as setViteServer, o as warnSlowSlotWithoutSuspense, r as warnDenyInSuspense, s as warnStaticRequestApi, t as WarningId } from "../_chunks/warnings-CAzunaGo.js";
3
+ import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-DESG8uk5.js";
4
+ import { n as classifyUrlSegment } from "../_chunks/segment-classify-BjfuctV2.js";
5
+ import { a as logProxyError, c as logRequestReceived, d as logSwrRefetchFailed, f as logWaitUntilRejected, h as swallow, i as logMiddlewareShortCircuit, l as logRouteError, m as setLogger, n as logCacheMiss, o as logRenderError, p as logWaitUntilUnsupported, r as logMiddlewareError, s as logRequestCompleted, t as getLogger, u as logSlowRequest } from "../_chunks/logger-CMd9P1xQ.js";
6
+ import { C as setMatchedSegmentPath, E as getCookie, O as getSetCookieHeaders, S as runWithRequestContext, T as setSegmentParams, _ as getHeader, b as getSegmentParams, c as DenySignal, d as RenderError, g as applyRequestHeaderOverlay, l as RedirectSignal, n as executeAction, o as coerce, r as isRscActionRequest, t as buildNoJsResponse, w as setMutableCookieContext, x as markResponseFlushed, y as getSearchParams } from "../_chunks/actions-BNhpxrnV.js";
7
+ import "../client/error-boundary.js";
8
+ import { n as toBracketKey } from "../_chunks/resolve-schema-DU2nbVOi.js";
9
+ import "../_chunks/segment-context-Bg0pFbLT.js";
10
+ import { readFile } from "node:fs/promises";
11
+ import "node:crypto";
12
+ import React, { createElement } from "react";
13
+ //#region src/server/server-timing.ts
14
+ /**
15
+ * Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
16
+ *
17
+ * Collects timing entries per request using ALS. Each pipeline phase
18
+ * (proxy, middleware, render, SSR, access, fetch) records an entry.
19
+ * Before response flush, entries are formatted into a Server-Timing header.
20
+ *
21
+ * Only active in dev mode — zero overhead in production.
22
+ *
23
+ * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
24
+ * Task: LOCAL-290
25
+ */
26
+ /**
27
+ * Run a callback with a per-request timing collector.
28
+ * Must be called at the top of the request pipeline (wraps the full request).
29
+ */
30
+ function runWithTimingCollector(fn) {
31
+ return timingAls.run({ entries: [] }, fn);
32
+ }
33
+ /**
34
+ * Run a function and automatically record its duration as a timing entry.
35
+ * Returns the function's result. No-ops the recording if outside a collector.
36
+ */
37
+ async function withTiming(name, desc, fn) {
38
+ const store = timingAls.getStore();
39
+ if (!store) return fn();
40
+ const start = performance.now();
41
+ try {
42
+ return await fn();
43
+ } finally {
44
+ const dur = Math.round(performance.now() - start);
45
+ store.entries.push({
46
+ name,
47
+ dur,
48
+ desc
49
+ });
50
+ }
51
+ }
52
+ /**
53
+ * Get the Server-Timing header value for the current request.
54
+ * Returns null if no entries exist or outside a collector.
55
+ *
56
+ * Format: `name;dur=123;desc="description", name2;dur=456`
57
+ * See RFC 6797 / Server-Timing spec for format details.
58
+ */
59
+ function getServerTimingHeader() {
60
+ const store = timingAls.getStore();
61
+ if (!store || store.entries.length === 0) return null;
62
+ const nameCounts = /* @__PURE__ */ new Map();
63
+ const parts = store.entries.map((entry) => {
64
+ const count = nameCounts.get(entry.name) ?? 0;
65
+ nameCounts.set(entry.name, count + 1);
66
+ const uniqueName = count > 0 ? `${entry.name}-${count}` : entry.name;
67
+ return {
68
+ ...entry,
69
+ name: uniqueName
70
+ };
71
+ }).map((entry) => {
72
+ let part = `${entry.name};dur=${entry.dur}`;
73
+ if (entry.desc) {
74
+ const safeDesc = entry.desc.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
75
+ part += `;desc="${safeDesc}"`;
76
+ }
77
+ return part;
78
+ });
79
+ const MAX_HEADER_SIZE = 4096;
80
+ let result = "";
81
+ for (let i = 0; i < parts.length; i++) {
82
+ const candidate = result ? `${result}, ${parts[i]}` : parts[i];
83
+ if (candidate.length > MAX_HEADER_SIZE) break;
84
+ result = candidate;
85
+ }
86
+ return result || null;
87
+ }
88
+ //#endregion
89
+ //#region src/server/instrumentation.ts
90
+ /**
91
+ * Instrumentation — loads and runs the user's instrumentation.ts file.
92
+ *
93
+ * instrumentation.ts is a file convention at the project root that exports:
94
+ * - register() — called once at server startup, before the first request
95
+ * - onRequestError() — called for every unhandled server error
96
+ * - logger — any object with info/warn/error/debug methods
97
+ *
98
+ * See design/17-logging.md §"instrumentation.ts — The Entry Point"
99
+ */
100
+ var _initialized = false;
101
+ var _onRequestError = null;
102
+ /**
103
+ * Load and initialize the user's instrumentation.ts module.
104
+ *
105
+ * - Awaits register() before returning (server blocks on this).
106
+ * - Picks up the logger export and wires it into the framework logger.
107
+ * - Stores onRequestError for later invocation.
108
+ *
109
+ * @param loader - Function that dynamically imports the user's instrumentation module.
110
+ * Returns null if no instrumentation.ts exists.
111
+ */
112
+ async function loadInstrumentation(loader) {
113
+ if (_initialized) return;
114
+ _initialized = true;
115
+ let mod;
116
+ try {
117
+ mod = await loader();
118
+ } catch (error) {
119
+ console.error("[timber] Failed to load instrumentation.ts:", error);
120
+ return;
121
+ }
122
+ if (!mod) return;
123
+ if (mod.logger && typeof mod.logger.info === "function") setLogger(mod.logger);
124
+ if (typeof mod.onRequestError === "function") _onRequestError = mod.onRequestError;
125
+ if (typeof mod.register === "function") try {
126
+ await mod.register();
127
+ } catch (error) {
128
+ console.error("[timber] instrumentation.ts register() threw:", error);
129
+ throw error;
130
+ }
131
+ }
132
+ /**
133
+ * Call the user's onRequestError hook. Catches and logs any errors thrown
134
+ * by the hook itself — it must not affect the response.
135
+ */
136
+ async function callOnRequestError(error, request, context) {
137
+ if (!_onRequestError) return;
138
+ try {
139
+ await _onRequestError(error, request, context);
140
+ } catch (hookError) {
141
+ console.error("[timber] onRequestError hook threw:", hookError);
142
+ }
143
+ }
144
+ /**
145
+ * Check if onRequestError is registered.
146
+ */
147
+ function hasOnRequestError() {
148
+ return _onRequestError !== null;
149
+ }
150
+ //#endregion
151
+ //#region src/server/pipeline-helpers.ts
152
+ /**
153
+ * Only __proto__ needs stripping — it has a language-level setter that
154
+ * changes the prototype chain of spread copies. constructor and prototype
155
+ * are harmless own properties on null-prototype objects.
156
+ */
157
+ var DANGEROUS_KEYS = new Set(["__proto__"]);
158
+ /**
159
+ * Deep-walk a value returned by a segment param codec, producing a
160
+ * sanitized copy where every plain object is null-prototype and
161
+ * dangerous keys (__proto__, constructor, prototype) are stripped at
162
+ * every depth.
163
+ *
164
+ * Non-plain objects (Date, Map, class instances, etc.) are returned
165
+ * as-is — they cannot be poisoned by `{...x}` spread and may carry
166
+ * author-intended prototype methods.
167
+ *
168
+ * Arrays are walked element-wise.
169
+ *
170
+ * Performance: URL params are bounded by URL length (~8 KB). Realistic
171
+ * trees are <1 KB. The recursive walk is sub-microsecond.
172
+ *
173
+ * See TIM-655, TIM-855, TIM-873, design/13-security.md
174
+ */
175
+ function sanitizeParamValue(value) {
176
+ if (value === null || typeof value !== "object") return value;
177
+ if (Array.isArray(value)) return value.map(sanitizeParamValue);
178
+ const proto = Object.getPrototypeOf(value);
179
+ if (proto !== Object.prototype && proto !== null) return value;
180
+ const out = Object.create(null);
181
+ for (const key of Object.keys(value)) if (!DANGEROUS_KEYS.has(key)) out[key] = sanitizeParamValue(value[key]);
182
+ return out;
183
+ }
184
+ /**
185
+ * Build a proxy resolver closure from the declared source. Called exactly
186
+ * once at `createPipeline` setup time, so the hot path sees only the branch
187
+ * that corresponds to this pipeline's configured variant.
188
+ *
189
+ * Returns `null` when the app has no proxy.ts — the hot path short-circuits
190
+ * around `runProxyPhase` entirely in that case.
191
+ *
192
+ * Accepts the sugar form (a bare `ProxyExport` — function or function array)
193
+ * and normalises it to the static variant. Functions and arrays are
194
+ * structurally distinct from the tagged `{ kind: 'lazy', loader }` object,
195
+ * so discrimination is unambiguous.
196
+ */
197
+ function makeProxyResolver(proxy) {
198
+ if (proxy === void 0) return null;
199
+ if (typeof proxy === "function" || Array.isArray(proxy)) {
200
+ const exp = proxy;
201
+ return () => exp;
202
+ }
203
+ if (proxy.kind === "static") {
204
+ const exp = proxy.export;
205
+ return () => exp;
206
+ }
207
+ const loader = proxy.loader;
208
+ return async () => (await loader()).default;
209
+ }
210
+ /**
211
+ * Apply all Set-Cookie headers from the cookie jar to a Headers object.
212
+ * Each cookie gets its own Set-Cookie header per RFC 6265 §4.1.
213
+ */
214
+ function applyCookieJar(headers) {
215
+ for (const value of getSetCookieHeaders()) headers.append("Set-Cookie", value);
216
+ }
217
+ /**
218
+ * Merge framework-managed response headers onto a terminal response without
219
+ * overwriting headers the terminal response already set itself.
220
+ */
221
+ function mergeMissingHeaders(target, source) {
222
+ const existingKeys = new Set([...target.keys()].map((key) => key.toLowerCase()));
223
+ for (const [key, value] of source.entries()) if (!existingKeys.has(key.toLowerCase())) target.append(key, value);
224
+ }
225
+ /**
226
+ * Clone a Response into a fresh one whose header bag is guaranteed mutable.
227
+ *
228
+ * `Response.redirect()` and some platform-level passthrough responses (notably
229
+ * on Cloudflare Workers) return objects with frozen header bags. Calling
230
+ * `.set()` or `.append()` on them throws `TypeError: immutable`, which the
231
+ * pipeline can hit when it appends Set-Cookie or Server-Timing entries.
232
+ *
233
+ * The pipeline calls this at the producer sites where user-controlled
234
+ * responses enter the framework — `outcomeToResponse` for all phase outcomes,
235
+ * and `handleRequest` for metadata-route and auto-sitemap user handlers — so
236
+ * downstream code can write headers without runtime feature-detection.
237
+ *
238
+ * The clone is unconditional. This is a deliberate trade: we avoid a
239
+ * try/catch + thrown `TypeError` on every request (the previous probe-based
240
+ * approach paid that cost on the hot path) and accept one cheap Response
241
+ * rewrap at the framework boundary instead.
242
+ */
243
+ function cloneWithMutableHeaders(response) {
244
+ return new Response(response.body, {
245
+ status: response.status,
246
+ statusText: response.statusText,
247
+ headers: new Headers(response.headers)
248
+ });
249
+ }
250
+ /**
251
+ * Build a redirect Response from a RedirectSignal.
252
+ *
253
+ * For RSC payload requests (client navigation), returns 204 + X-Timber-Redirect
254
+ * so the client router can perform a soft SPA redirect. A raw 302 would be
255
+ * turned into an opaque redirect by fetch({redirect:'manual'}), crashing
256
+ * createFromFetch. See design/19-client-navigation.md.
257
+ */
258
+ function buildRedirectResponse(signal, req, headers) {
259
+ if ((req.headers.get("Accept") ?? "").includes("text/x-component")) {
260
+ headers.set("X-Timber-Redirect", signal.location);
261
+ return new Response(null, {
262
+ status: 204,
263
+ headers
264
+ });
265
+ }
266
+ headers.set("Location", signal.location);
267
+ return new Response(null, {
268
+ status: signal.status,
269
+ headers
270
+ });
271
+ }
272
+ /**
273
+ * Fire the user's onRequestError hook with request context.
274
+ * Extracts request info from the Request object and calls the instrumentation hook.
275
+ */
276
+ async function fireOnRequestError(error, req, phase) {
277
+ const url = new URL(req.url);
278
+ const headersObj = {};
279
+ req.headers.forEach((v, k) => {
280
+ headersObj[k] = v;
281
+ });
282
+ await callOnRequestError(error, {
283
+ method: req.method,
284
+ path: url.pathname,
285
+ headers: headersObj
286
+ }, {
287
+ phase,
288
+ routePath: url.pathname,
289
+ routeType: "page",
290
+ traceId: getTraceId()
291
+ });
292
+ }
293
+ //#endregion
294
+ //#region src/server/canonicalize.ts
295
+ /**
296
+ * Encoded separators that produce a 400 rejection.
297
+ * %2f (/) and %5c (\) cause path-confusion attacks.
298
+ */
299
+ var ENCODED_SEPARATOR_RE = /%2f|%5c/i;
300
+ /** Null byte — rejected. */
301
+ var NULL_BYTE_RE = /%00/i;
302
+ /**
303
+ * Canonicalize a URL pathname.
304
+ *
305
+ * 1. Reject encoded separators (%2f, %5c) and null bytes (%00)
306
+ * 2. Single percent-decode
307
+ * 3. Collapse // → /
308
+ * 4. Resolve .. segments (reject if escaping root)
309
+ * 5. Strip trailing slash (except root "/")
310
+ *
311
+ * @param rawPathname - The raw pathname from the request URL (percent-encoded)
312
+ * @param stripTrailingSlash - Whether to strip trailing slashes. Default: true.
313
+ */
314
+ function canonicalize(rawPathname, stripTrailingSlash = true) {
315
+ if (ENCODED_SEPARATOR_RE.test(rawPathname)) return {
316
+ ok: false,
317
+ status: 400
318
+ };
319
+ if (NULL_BYTE_RE.test(rawPathname)) return {
320
+ ok: false,
321
+ status: 400
322
+ };
323
+ let decoded;
324
+ try {
325
+ decoded = decodeURIComponent(rawPathname);
326
+ } catch {
327
+ return {
328
+ ok: false,
329
+ status: 400
330
+ };
331
+ }
332
+ if (decoded.includes("\0")) return {
333
+ ok: false,
334
+ status: 400
335
+ };
336
+ let pathname = decoded.replace(/\/\/+/g, "/");
337
+ const segments = pathname.split("/");
338
+ const resolved = [];
339
+ for (const seg of segments) if (seg === "..") {
340
+ if (resolved.length <= 1) return {
341
+ ok: false,
342
+ status: 400
343
+ };
344
+ resolved.pop();
345
+ } else if (seg !== ".") resolved.push(seg);
346
+ pathname = resolved.join("/") || "/";
347
+ if (stripTrailingSlash && pathname.length > 1 && pathname.endsWith("/")) pathname = pathname.slice(0, -1);
348
+ return {
349
+ ok: true,
350
+ pathname
351
+ };
352
+ }
353
+ //#endregion
354
+ //#region src/server/proxy.ts
355
+ /**
356
+ * Run the proxy pipeline.
357
+ *
358
+ * @param proxyExport - The default export from proxy.ts (function or array)
359
+ * @param req - The incoming request
360
+ * @param next - The continuation that proceeds to route matching and rendering
361
+ * @returns The final response
362
+ */
363
+ async function runProxy(proxyExport, req, next) {
364
+ const fns = Array.isArray(proxyExport) ? proxyExport : [proxyExport];
365
+ let i = fns.length;
366
+ let composed = next;
367
+ while (i--) {
368
+ const fn = fns[i];
369
+ const downstream = composed;
370
+ composed = () => Promise.resolve(fn(req, downstream));
371
+ }
372
+ return composed();
373
+ }
374
+ //#endregion
375
+ //#region src/server/middleware-runner.ts
376
+ /**
377
+ * Run a route's middleware function.
378
+ *
379
+ * @param middlewareFn - The default export from the route's middleware.ts
380
+ * @param ctx - The middleware context (req, params, headers, requestHeaders, searchParams)
381
+ * @returns A Response if middleware short-circuited, or undefined to continue
382
+ */
383
+ async function runMiddleware(middlewareFn, ctx) {
384
+ const result = await middlewareFn(ctx);
385
+ if (result instanceof Response) return result;
386
+ }
387
+ /**
388
+ * Run all middleware functions in the segment chain, root to leaf.
389
+ *
390
+ * Execution is top-down: root middleware runs first, leaf middleware runs last.
391
+ * All middleware share the same MiddlewareContext — a parent that sets
392
+ * ctx.requestHeaders makes it visible to child middleware and downstream components.
393
+ *
394
+ * Short-circuits on the first middleware that returns a Response.
395
+ * Remaining middleware in the chain do not execute.
396
+ *
397
+ * @param chain - Middleware functions ordered root-to-leaf
398
+ * @param ctx - Shared middleware context
399
+ * @returns A Response if any middleware short-circuited, or undefined to continue
400
+ */
401
+ async function runMiddlewareChain(chain, ctx) {
402
+ for (const fn of chain) {
403
+ const result = await fn(ctx);
404
+ if (result instanceof Response) return result;
405
+ }
406
+ }
407
+ /**
408
+ * Per-request marker for synthetic re-render requests that should NOT
409
+ * re-execute `middleware.ts`. The action-dispatch wrapper runs middleware
410
+ * once on the inbound action POST; when validation fails on the no-JS
411
+ * path, it builds a synthetic GET that flows through the normal pipeline
412
+ * to render the page with `getFormFlash()` data. Without this marker, the
413
+ * pipeline would run middleware a second time on that synthetic GET.
414
+ *
415
+ * The set is keyed by the synthetic Request object itself, so the entry
416
+ * lives exactly as long as the request and is garbage-collected with it.
417
+ * Cannot be set or detected by user code — there is no header, no URL
418
+ * parameter, nothing on the wire that an attacker could spoof.
419
+ *
420
+ * See TIM-871.
421
+ *
422
+ * @internal — framework use only.
423
+ */
424
+ var middlewareBypassRequests = /* @__PURE__ */ new WeakSet();
425
+ /**
426
+ * Check whether a request was marked to bypass middleware.
427
+ *
428
+ * Called by `handleRequest` in pipeline-phases.ts before invoking the
429
+ * middleware phase. Returns false for any request not explicitly marked.
430
+ *
431
+ * @internal
432
+ */
433
+ function shouldBypassMiddleware(req) {
434
+ return middlewareBypassRequests.has(req);
435
+ }
436
+ //#endregion
437
+ //#region src/server/metadata-social.ts
438
+ /**
439
+ * Render Open Graph metadata into head element descriptors.
440
+ *
441
+ * Handles og:title, og:description, og:image (with dimensions/alt),
442
+ * og:video, og:audio, og:article:author, and other OG properties.
443
+ */
444
+ function renderOpenGraph(og, elements) {
445
+ const simpleProps = [
446
+ ["og:title", og.title],
447
+ ["og:description", og.description],
448
+ ["og:url", og.url],
449
+ ["og:site_name", og.siteName],
450
+ ["og:locale", og.locale],
451
+ ["og:type", og.type],
452
+ ["og:article:published_time", og.publishedTime],
453
+ ["og:article:modified_time", og.modifiedTime]
454
+ ];
455
+ for (const [property, content] of simpleProps) if (content) elements.push({
456
+ tag: "meta",
457
+ attrs: {
458
+ property,
459
+ content
460
+ }
461
+ });
462
+ if (og.images) if (typeof og.images === "string") elements.push({
463
+ tag: "meta",
464
+ attrs: {
465
+ property: "og:image",
466
+ content: og.images
467
+ }
468
+ });
469
+ else {
470
+ const imgList = Array.isArray(og.images) ? og.images : [og.images];
471
+ for (const img of imgList) {
472
+ elements.push({
473
+ tag: "meta",
474
+ attrs: {
475
+ property: "og:image",
476
+ content: img.url
477
+ }
478
+ });
479
+ if (img.width) elements.push({
480
+ tag: "meta",
481
+ attrs: {
482
+ property: "og:image:width",
483
+ content: String(img.width)
484
+ }
485
+ });
486
+ if (img.height) elements.push({
487
+ tag: "meta",
488
+ attrs: {
489
+ property: "og:image:height",
490
+ content: String(img.height)
491
+ }
492
+ });
493
+ if (img.alt) elements.push({
494
+ tag: "meta",
495
+ attrs: {
496
+ property: "og:image:alt",
497
+ content: img.alt
498
+ }
499
+ });
500
+ }
501
+ }
502
+ if (og.videos) for (const video of og.videos) elements.push({
503
+ tag: "meta",
504
+ attrs: {
505
+ property: "og:video",
506
+ content: video.url
507
+ }
508
+ });
509
+ if (og.audio) for (const audio of og.audio) elements.push({
510
+ tag: "meta",
511
+ attrs: {
512
+ property: "og:audio",
513
+ content: audio.url
514
+ }
515
+ });
516
+ if (og.authors) for (const author of og.authors) elements.push({
517
+ tag: "meta",
518
+ attrs: {
519
+ property: "og:article:author",
520
+ content: author
521
+ }
522
+ });
523
+ }
524
+ /**
525
+ * Render Twitter Card metadata into head element descriptors.
526
+ *
527
+ * Handles twitter:card, twitter:site, twitter:title, twitter:image,
528
+ * twitter:player, and twitter:app (per-platform name/id/url).
529
+ */
530
+ function renderTwitter(tw, elements) {
531
+ const simpleProps = [
532
+ ["twitter:card", tw.card],
533
+ ["twitter:site", tw.site],
534
+ ["twitter:site:id", tw.siteId],
535
+ ["twitter:title", tw.title],
536
+ ["twitter:description", tw.description],
537
+ ["twitter:creator", tw.creator],
538
+ ["twitter:creator:id", tw.creatorId]
539
+ ];
540
+ for (const [name, content] of simpleProps) if (content) elements.push({
541
+ tag: "meta",
542
+ attrs: {
543
+ name,
544
+ content
545
+ }
546
+ });
547
+ if (tw.images) if (typeof tw.images === "string") elements.push({
548
+ tag: "meta",
549
+ attrs: {
550
+ name: "twitter:image",
551
+ content: tw.images
552
+ }
553
+ });
554
+ else {
555
+ const imgList = Array.isArray(tw.images) ? tw.images : [tw.images];
556
+ for (const img of imgList) {
557
+ const url = typeof img === "string" ? img : img.url;
558
+ elements.push({
559
+ tag: "meta",
560
+ attrs: {
561
+ name: "twitter:image",
562
+ content: url
563
+ }
564
+ });
565
+ }
566
+ }
567
+ if (tw.players) for (const player of tw.players) {
568
+ elements.push({
569
+ tag: "meta",
570
+ attrs: {
571
+ name: "twitter:player",
572
+ content: player.playerUrl
573
+ }
574
+ });
575
+ if (player.width) elements.push({
576
+ tag: "meta",
577
+ attrs: {
578
+ name: "twitter:player:width",
579
+ content: String(player.width)
580
+ }
581
+ });
582
+ if (player.height) elements.push({
583
+ tag: "meta",
584
+ attrs: {
585
+ name: "twitter:player:height",
586
+ content: String(player.height)
587
+ }
588
+ });
589
+ if (player.streamUrl) elements.push({
590
+ tag: "meta",
591
+ attrs: {
592
+ name: "twitter:player:stream",
593
+ content: player.streamUrl
594
+ }
595
+ });
596
+ }
597
+ if (tw.app) {
598
+ const platforms = [
599
+ ["iPhone", "iphone"],
600
+ ["iPad", "ipad"],
601
+ ["googlePlay", "googleplay"]
602
+ ];
603
+ if (tw.app.name) {
604
+ for (const [key, tag] of platforms) if (tw.app.id?.[key]) elements.push({
605
+ tag: "meta",
606
+ attrs: {
607
+ name: `twitter:app:name:${tag}`,
608
+ content: tw.app.name
609
+ }
610
+ });
611
+ }
612
+ for (const [key, tag] of platforms) {
613
+ const id = tw.app.id?.[key];
614
+ if (id) elements.push({
615
+ tag: "meta",
616
+ attrs: {
617
+ name: `twitter:app:id:${tag}`,
618
+ content: id
619
+ }
620
+ });
621
+ }
622
+ for (const [key, tag] of platforms) {
623
+ const url = tw.app.url?.[key];
624
+ if (url) elements.push({
625
+ tag: "meta",
626
+ attrs: {
627
+ name: `twitter:app:url:${tag}`,
628
+ content: url
629
+ }
630
+ });
631
+ }
632
+ }
633
+ }
634
+ //#endregion
635
+ //#region src/server/metadata-platform.ts
636
+ /**
637
+ * Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
638
+ */
639
+ function renderIcons(icons, elements) {
640
+ if (icons.icon) {
641
+ if (typeof icons.icon === "string") elements.push({
642
+ tag: "link",
643
+ attrs: {
644
+ rel: "icon",
645
+ href: icons.icon
646
+ }
647
+ });
648
+ else if (Array.isArray(icons.icon)) for (const icon of icons.icon) {
649
+ const attrs = {
650
+ rel: "icon",
651
+ href: icon.url
652
+ };
653
+ if (icon.sizes) attrs.sizes = icon.sizes;
654
+ if (icon.type) attrs.type = icon.type;
655
+ elements.push({
656
+ tag: "link",
657
+ attrs
658
+ });
659
+ }
660
+ }
661
+ if (icons.shortcut) {
662
+ const urls = Array.isArray(icons.shortcut) ? icons.shortcut : [icons.shortcut];
663
+ for (const url of urls) elements.push({
664
+ tag: "link",
665
+ attrs: {
666
+ rel: "shortcut icon",
667
+ href: url
668
+ }
669
+ });
670
+ }
671
+ if (icons.apple) {
672
+ if (typeof icons.apple === "string") elements.push({
673
+ tag: "link",
674
+ attrs: {
675
+ rel: "apple-touch-icon",
676
+ href: icons.apple
677
+ }
678
+ });
679
+ else if (Array.isArray(icons.apple)) for (const icon of icons.apple) {
680
+ const attrs = {
681
+ rel: "apple-touch-icon",
682
+ href: icon.url
683
+ };
684
+ if (icon.sizes) attrs.sizes = icon.sizes;
685
+ elements.push({
686
+ tag: "link",
687
+ attrs
688
+ });
689
+ }
690
+ }
691
+ if (icons.other) for (const icon of icons.other) {
692
+ const attrs = {
693
+ rel: icon.rel,
694
+ href: icon.url
695
+ };
696
+ if (icon.sizes) attrs.sizes = icon.sizes;
697
+ if (icon.type) attrs.type = icon.type;
698
+ elements.push({
699
+ tag: "link",
700
+ attrs
701
+ });
702
+ }
703
+ }
704
+ /**
705
+ * Render alternate link elements (canonical, hreflang, media, types).
706
+ */
707
+ function renderAlternates(alternates, elements) {
708
+ if (alternates.canonical) elements.push({
709
+ tag: "link",
710
+ attrs: {
711
+ rel: "canonical",
712
+ href: alternates.canonical
713
+ }
714
+ });
715
+ if (alternates.languages) for (const [lang, href] of Object.entries(alternates.languages)) elements.push({
716
+ tag: "link",
717
+ attrs: {
718
+ rel: "alternate",
719
+ hreflang: lang,
720
+ href
721
+ }
722
+ });
723
+ if (alternates.media) for (const [media, href] of Object.entries(alternates.media)) elements.push({
724
+ tag: "link",
725
+ attrs: {
726
+ rel: "alternate",
727
+ media,
728
+ href
729
+ }
730
+ });
731
+ if (alternates.types) for (const [type, href] of Object.entries(alternates.types)) elements.push({
732
+ tag: "link",
733
+ attrs: {
734
+ rel: "alternate",
735
+ type,
736
+ href
737
+ }
738
+ });
739
+ }
740
+ /**
741
+ * Render site verification meta tags (Google, Yahoo, Yandex, custom).
742
+ */
743
+ function renderVerification(verification, elements) {
744
+ const verificationProps = [
745
+ ["google-site-verification", verification.google],
746
+ ["y_key", verification.yahoo],
747
+ ["yandex-verification", verification.yandex]
748
+ ];
749
+ for (const [name, content] of verificationProps) if (content) elements.push({
750
+ tag: "meta",
751
+ attrs: {
752
+ name,
753
+ content
754
+ }
755
+ });
756
+ if (verification.other) for (const [name, value] of Object.entries(verification.other)) {
757
+ const content = Array.isArray(value) ? value.join(", ") : value;
758
+ elements.push({
759
+ tag: "meta",
760
+ attrs: {
761
+ name,
762
+ content
763
+ }
764
+ });
765
+ }
766
+ }
767
+ /**
768
+ * Render Apple Web App meta tags and startup image links.
769
+ */
770
+ function renderAppleWebApp(appleWebApp, elements) {
771
+ if (appleWebApp.capable) elements.push({
772
+ tag: "meta",
773
+ attrs: {
774
+ name: "apple-mobile-web-app-capable",
775
+ content: "yes"
776
+ }
777
+ });
778
+ if (appleWebApp.title) elements.push({
779
+ tag: "meta",
780
+ attrs: {
781
+ name: "apple-mobile-web-app-title",
782
+ content: appleWebApp.title
783
+ }
784
+ });
785
+ if (appleWebApp.statusBarStyle) elements.push({
786
+ tag: "meta",
787
+ attrs: {
788
+ name: "apple-mobile-web-app-status-bar-style",
789
+ content: appleWebApp.statusBarStyle
790
+ }
791
+ });
792
+ if (appleWebApp.startupImage) {
793
+ const images = Array.isArray(appleWebApp.startupImage) ? appleWebApp.startupImage : [{ url: appleWebApp.startupImage }];
794
+ for (const img of images) {
795
+ const attrs = {
796
+ rel: "apple-touch-startup-image",
797
+ href: typeof img === "string" ? img : img.url
798
+ };
799
+ if (typeof img === "object" && img.media) attrs.media = img.media;
800
+ elements.push({
801
+ tag: "link",
802
+ attrs
803
+ });
804
+ }
805
+ }
806
+ }
807
+ /**
808
+ * Render App Links (al:*) meta tags for deep linking across platforms.
809
+ */
810
+ function renderAppLinks(appLinks, elements) {
811
+ const platformEntries = [
812
+ ["ios", appLinks.ios],
813
+ ["android", appLinks.android],
814
+ ["windows", appLinks.windows],
815
+ ["windows_phone", appLinks.windowsPhone],
816
+ ["windows_universal", appLinks.windowsUniversal]
817
+ ];
818
+ for (const [platform, entries] of platformEntries) {
819
+ if (!entries) continue;
820
+ for (const entry of entries) for (const [key, value] of Object.entries(entry)) if (value !== void 0 && value !== null) elements.push({
821
+ tag: "meta",
822
+ attrs: {
823
+ property: `al:${platform}:${key}`,
824
+ content: String(value)
825
+ }
826
+ });
827
+ }
828
+ if (appLinks.web) {
829
+ if (appLinks.web.url) elements.push({
830
+ tag: "meta",
831
+ attrs: {
832
+ property: "al:web:url",
833
+ content: appLinks.web.url
834
+ }
835
+ });
836
+ if (appLinks.web.shouldFallback !== void 0) elements.push({
837
+ tag: "meta",
838
+ attrs: {
839
+ property: "al:web:should_fallback",
840
+ content: appLinks.web.shouldFallback ? "true" : "false"
841
+ }
842
+ });
843
+ }
844
+ }
845
+ /**
846
+ * Render Apple iTunes smart banner meta tag.
847
+ */
848
+ function renderItunes(itunes, elements) {
849
+ const parts = [`app-id=${itunes.appId}`];
850
+ if (itunes.affiliateData) parts.push(`affiliate-data=${itunes.affiliateData}`);
851
+ if (itunes.appArgument) parts.push(`app-argument=${itunes.appArgument}`);
852
+ elements.push({
853
+ tag: "meta",
854
+ attrs: {
855
+ name: "apple-itunes-app",
856
+ content: parts.join(", ")
857
+ }
858
+ });
859
+ }
860
+ //#endregion
861
+ //#region src/server/metadata-render.ts
862
+ /**
863
+ * Convert resolved metadata into an array of head element descriptors.
864
+ *
865
+ * Each descriptor has a `tag` ('title', 'meta', 'link') and either
866
+ * `content` (for <title>) or `attrs` (for <meta>/<link>).
867
+ *
868
+ * The framework's MetadataResolver component consumes these descriptors
869
+ * and renders them into the <head>.
870
+ */
871
+ function renderMetadataToElements(metadata) {
872
+ const elements = [];
873
+ if (typeof metadata.title === "string") elements.push({
874
+ tag: "title",
875
+ content: metadata.title
876
+ });
877
+ const simpleMetaProps = [
878
+ ["description", metadata.description],
879
+ ["generator", metadata.generator],
880
+ ["application-name", metadata.applicationName],
881
+ ["referrer", metadata.referrer],
882
+ ["category", metadata.category],
883
+ ["creator", metadata.creator],
884
+ ["publisher", metadata.publisher]
885
+ ];
886
+ for (const [name, content] of simpleMetaProps) if (content) elements.push({
887
+ tag: "meta",
888
+ attrs: {
889
+ name,
890
+ content
891
+ }
892
+ });
893
+ if (metadata.keywords) {
894
+ const content = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
895
+ elements.push({
896
+ tag: "meta",
897
+ attrs: {
898
+ name: "keywords",
899
+ content
900
+ }
901
+ });
902
+ }
903
+ if (metadata.robots) {
904
+ const content = typeof metadata.robots === "string" ? metadata.robots : renderRobotsObject(metadata.robots);
905
+ elements.push({
906
+ tag: "meta",
907
+ attrs: {
908
+ name: "robots",
909
+ content
910
+ }
911
+ });
912
+ if (typeof metadata.robots === "object" && metadata.robots.googleBot) {
913
+ const gbContent = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : renderRobotsObject(metadata.robots.googleBot);
914
+ elements.push({
915
+ tag: "meta",
916
+ attrs: {
917
+ name: "googlebot",
918
+ content: gbContent
919
+ }
920
+ });
921
+ }
922
+ }
923
+ if (metadata.openGraph) renderOpenGraph(metadata.openGraph, elements);
924
+ if (metadata.twitter) renderTwitter(metadata.twitter, elements);
925
+ if (metadata.icons) renderIcons(metadata.icons, elements);
926
+ if (metadata.manifest) elements.push({
927
+ tag: "link",
928
+ attrs: {
929
+ rel: "manifest",
930
+ href: metadata.manifest
931
+ }
932
+ });
933
+ if (metadata.alternates) renderAlternates(metadata.alternates, elements);
934
+ if (metadata.verification) renderVerification(metadata.verification, elements);
935
+ if (metadata.formatDetection) {
936
+ const parts = [];
937
+ if (metadata.formatDetection.telephone === false) parts.push("telephone=no");
938
+ if (metadata.formatDetection.email === false) parts.push("email=no");
939
+ if (metadata.formatDetection.address === false) parts.push("address=no");
940
+ if (parts.length > 0) elements.push({
941
+ tag: "meta",
942
+ attrs: {
943
+ name: "format-detection",
944
+ content: parts.join(", ")
945
+ }
946
+ });
947
+ }
948
+ if (metadata.authors) {
949
+ const authorList = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
950
+ for (const author of authorList) {
951
+ if (author.name) elements.push({
952
+ tag: "meta",
953
+ attrs: {
954
+ name: "author",
955
+ content: author.name
956
+ }
957
+ });
958
+ if (author.url) elements.push({
959
+ tag: "link",
960
+ attrs: {
961
+ rel: "author",
962
+ href: author.url
963
+ }
964
+ });
965
+ }
966
+ }
967
+ if (metadata.appleWebApp) renderAppleWebApp(metadata.appleWebApp, elements);
968
+ if (metadata.appLinks) renderAppLinks(metadata.appLinks, elements);
969
+ if (metadata.itunes) renderItunes(metadata.itunes, elements);
970
+ if (metadata.other) for (const [name, value] of Object.entries(metadata.other)) {
971
+ const content = Array.isArray(value) ? value.join(", ") : value;
972
+ elements.push({
973
+ tag: "meta",
974
+ attrs: {
975
+ name,
976
+ content
977
+ }
978
+ });
979
+ }
980
+ return elements;
981
+ }
982
+ function renderRobotsObject(robots) {
983
+ const parts = [];
984
+ if (robots.index === true) parts.push("index");
985
+ if (robots.index === false) parts.push("noindex");
986
+ if (robots.follow === true) parts.push("follow");
987
+ if (robots.follow === false) parts.push("nofollow");
988
+ return parts.join(", ");
989
+ }
990
+ //#endregion
991
+ //#region src/server/metadata.ts
992
+ /**
993
+ * Resolve a title value with an optional template.
994
+ *
995
+ * - string → apply template if present
996
+ * - { absolute: '...' } → use as-is, skip template
997
+ * - { default: '...' } → use as fallback (no template applied)
998
+ * - undefined → undefined
999
+ */
1000
+ function resolveTitle(title, template) {
1001
+ if (title === void 0 || title === null) return;
1002
+ if (typeof title === "string") return template ? template.replace("%s", title) : title;
1003
+ if (title.absolute !== void 0) return title.absolute;
1004
+ if (title.default !== void 0) return title.default;
1005
+ }
1006
+ /**
1007
+ * Resolve metadata from a segment chain.
1008
+ *
1009
+ * Processes entries from root layout to page (in segment order).
1010
+ * The merge algorithm:
1011
+ * 1. Shallow-merge all keys except title (later wins)
1012
+ * 2. Track the most recent title template
1013
+ * 3. Resolve the final title using the template
1014
+ *
1015
+ * In error state, the page entry is dropped and noindex is injected.
1016
+ *
1017
+ * See design/16-metadata.md §"Merge Algorithm"
1018
+ */
1019
+ function resolveMetadata(entries, options = {}) {
1020
+ const { errorState = false } = options;
1021
+ const merged = {};
1022
+ let titleTemplate;
1023
+ let lastDefault;
1024
+ let rawTitle;
1025
+ for (const { metadata, isPage } of entries) {
1026
+ if (errorState && isPage) continue;
1027
+ if (metadata.title !== void 0 && typeof metadata.title === "object") {
1028
+ if (metadata.title.template !== void 0) titleTemplate = metadata.title.template;
1029
+ if (metadata.title.default !== void 0) lastDefault = metadata.title.default;
1030
+ }
1031
+ for (const key of Object.keys(metadata)) {
1032
+ if (key === "title") continue;
1033
+ merged[key] = metadata[key];
1034
+ }
1035
+ if (metadata.title !== void 0) rawTitle = metadata.title;
1036
+ }
1037
+ if (errorState) {
1038
+ rawTitle = lastDefault !== void 0 ? { default: lastDefault } : rawTitle;
1039
+ titleTemplate = void 0;
1040
+ }
1041
+ const resolvedTitle = resolveTitle(rawTitle, titleTemplate);
1042
+ if (resolvedTitle !== void 0) merged.title = resolvedTitle;
1043
+ if (errorState) merged.robots = "noindex";
1044
+ return merged;
1045
+ }
1046
+ /**
1047
+ * Check if a string is an absolute URL.
1048
+ */
1049
+ function isAbsoluteUrl(url) {
1050
+ return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
1051
+ }
1052
+ /**
1053
+ * Resolve a relative URL against a base URL.
1054
+ */
1055
+ function resolveUrl(url, base) {
1056
+ if (isAbsoluteUrl(url)) return url;
1057
+ return new URL(url, base).toString();
1058
+ }
1059
+ /**
1060
+ * Resolve relative URLs in metadata fields against metadataBase.
1061
+ *
1062
+ * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
1063
+ * If metadataBase is not set, returns the metadata unchanged.
1064
+ */
1065
+ function resolveMetadataUrls(metadata) {
1066
+ const base = metadata.metadataBase;
1067
+ if (!base) return metadata;
1068
+ const result = { ...metadata };
1069
+ if (result.openGraph) {
1070
+ result.openGraph = { ...result.openGraph };
1071
+ if (typeof result.openGraph.images === "string") result.openGraph.images = resolveUrl(result.openGraph.images, base);
1072
+ else if (Array.isArray(result.openGraph.images)) result.openGraph.images = result.openGraph.images.map((img) => ({
1073
+ ...img,
1074
+ url: resolveUrl(img.url, base)
1075
+ }));
1076
+ else if (result.openGraph.images) result.openGraph.images = {
1077
+ ...result.openGraph.images,
1078
+ url: resolveUrl(result.openGraph.images.url, base)
1079
+ };
1080
+ if (result.openGraph.url && !isAbsoluteUrl(result.openGraph.url)) result.openGraph.url = resolveUrl(result.openGraph.url, base);
1081
+ }
1082
+ if (result.twitter) {
1083
+ result.twitter = { ...result.twitter };
1084
+ if (typeof result.twitter.images === "string") result.twitter.images = resolveUrl(result.twitter.images, base);
1085
+ else if (Array.isArray(result.twitter.images)) {
1086
+ const resolved = result.twitter.images.map((img) => typeof img === "string" ? resolveUrl(img, base) : {
1087
+ ...img,
1088
+ url: resolveUrl(img.url, base)
1089
+ });
1090
+ const allStrings = resolved.every((r) => typeof r === "string");
1091
+ result.twitter.images = allStrings ? resolved : resolved;
1092
+ } else if (result.twitter.images) result.twitter.images = {
1093
+ ...result.twitter.images,
1094
+ url: resolveUrl(result.twitter.images.url, base)
1095
+ };
1096
+ }
1097
+ if (result.alternates) {
1098
+ result.alternates = { ...result.alternates };
1099
+ if (result.alternates.canonical && !isAbsoluteUrl(result.alternates.canonical)) result.alternates.canonical = resolveUrl(result.alternates.canonical, base);
1100
+ if (result.alternates.languages) {
1101
+ const langs = {};
1102
+ for (const [lang, url] of Object.entries(result.alternates.languages)) langs[lang] = isAbsoluteUrl(url) ? url : resolveUrl(url, base);
1103
+ result.alternates.languages = langs;
1104
+ }
1105
+ }
1106
+ if (result.icons) {
1107
+ result.icons = { ...result.icons };
1108
+ if (typeof result.icons.icon === "string") result.icons.icon = resolveUrl(result.icons.icon, base);
1109
+ else if (Array.isArray(result.icons.icon)) result.icons.icon = result.icons.icon.map((i) => ({
1110
+ ...i,
1111
+ url: resolveUrl(i.url, base)
1112
+ }));
1113
+ if (typeof result.icons.apple === "string") result.icons.apple = resolveUrl(result.icons.apple, base);
1114
+ else if (Array.isArray(result.icons.apple)) result.icons.apple = result.icons.apple.map((i) => ({
1115
+ ...i,
1116
+ url: resolveUrl(i.url, base)
1117
+ }));
1118
+ }
1119
+ return result;
1120
+ }
1121
+ //#endregion
1122
+ //#region src/server/safe-load.ts
1123
+ /**
1124
+ * Custom error class for module load failures.
1125
+ *
1126
+ * Preserves the original error as `cause` while providing a
1127
+ * human-readable message with the file path.
1128
+ */
1129
+ var ModuleLoadError = class extends Error {
1130
+ /** The file path that failed to load. */
1131
+ filePath;
1132
+ constructor(filePath, cause) {
1133
+ const originalMessage = cause instanceof Error ? cause.message : String(cause);
1134
+ super(`[timber] Failed to load module ${filePath}\n ${originalMessage}`, { cause });
1135
+ this.name = "ModuleLoadError";
1136
+ this.filePath = filePath;
1137
+ }
1138
+ };
1139
+ /**
1140
+ * Load a route manifest module with enriched error context.
1141
+ *
1142
+ * On success: returns the module object (same as `loader.load()`).
1143
+ * On failure: throws `ModuleLoadError` with file path and original cause.
1144
+ *
1145
+ * For error rendering paths that need fallthrough instead of throwing,
1146
+ * callers should catch at the call site:
1147
+ *
1148
+ * ```ts
1149
+ * // Throwing (default) — route-element-builder, api-handler, etc.
1150
+ * const mod = await loadModule(segment.page);
1151
+ *
1152
+ * // Fallthrough — error-renderer, error-boundary-wrapper
1153
+ * const mod = await loadModule(segment.error).catch(() => null);
1154
+ * ```
1155
+ */
1156
+ async function loadModule(loader) {
1157
+ try {
1158
+ return await loader.load();
1159
+ } catch (error) {
1160
+ throw new ModuleLoadError(loader.filePath, error);
1161
+ }
1162
+ }
1163
+ //#endregion
1164
+ //#region src/server/deny-boundary.ts
1165
+ /**
1166
+ * Deny boundary subsystem — the in-tree DenySignal flow.
1167
+ *
1168
+ * Three things live together here because they form a single flow:
1169
+ *
1170
+ * 1. **Chain construction** (`buildDenyPageChain`) — walks the matched
1171
+ * segment chain at element-tree build time and produces a list of
1172
+ * `DenyPageEntry` records ordered by specificity (specific status →
1173
+ * category catch-all → `error.tsx`).
1174
+ *
1175
+ * 2. **Runtime matching** (`renderMatchingDenyPage`) — picks the first
1176
+ * chain entry whose status filter matches the thrown DenySignal and
1177
+ * returns a React element for the matching component. Used by
1178
+ * `AccessGate` and `PageDenyBoundary` when they catch a deny.
1179
+ *
1180
+ * 3. **The page boundary itself** (`PageDenyBoundary`) — the async server
1181
+ * component that wraps a server-component page, calls it, and catches
1182
+ * `DenySignal` so the deny page renders in-tree (no throw reaches
1183
+ * React Flight, single render pass).
1184
+ *
1185
+ * Plus the ALS helpers (`setDenyStatus` / `getDenyStatus`) the boundary
1186
+ * uses to thread the matched status code back to the pipeline so the
1187
+ * HTTP status reflects the deny.
1188
+ *
1189
+ * Folded into one module from the former `deny-page-resolver.ts` and
1190
+ * `page-deny-boundary.tsx` (TIM-853) — the names were misleading and the
1191
+ * three pieces only made sense together.
1192
+ *
1193
+ * See design/04-authorization.md, design/10-error-handling.md, TIM-666.
1194
+ */
1195
+ /**
1196
+ * Find the first deny page in the chain that matches the given status code.
1197
+ * Returns a React element for the matching component, or null if no match.
1198
+ */
1199
+ function renderMatchingDenyPage(chain, status, data) {
1200
+ const h = createElement;
1201
+ for (const entry of chain) {
1202
+ if (entry.status === status) return h(entry.component, {
1203
+ status,
1204
+ dangerouslyPassData: data
1205
+ });
1206
+ if (entry.status === 400 && status >= 400 && status <= 499) return h(entry.component, {
1207
+ status,
1208
+ dangerouslyPassData: data
1209
+ });
1210
+ if (entry.status === 500 && status >= 500 && status <= 599) return h(entry.component, {
1211
+ status,
1212
+ dangerouslyPassData: data
1213
+ });
1214
+ if (entry.status === null) return h(entry.component, {
1215
+ status,
1216
+ dangerouslyPassData: data
1217
+ });
1218
+ }
1219
+ return null;
1220
+ }
1221
+ /**
1222
+ * Set the deny status in the request context ALS.
1223
+ * Called from AccessGate / PageDenyBoundary when a DenySignal is caught.
1224
+ * The pipeline reads this after render to set the HTTP status code.
1225
+ */
1226
+ function setDenyStatus(status) {
1227
+ const store = requestContextAls.getStore();
1228
+ if (store) store.denyStatus = status;
1229
+ }
1230
+ //#endregion
1231
+ //#region src/server/access-gate.tsx
1232
+ /**
1233
+ * AccessGate and SlotAccessGate — framework-injected async server components.
1234
+ *
1235
+ * AccessGate wraps each segment's layout in the element tree. It calls the
1236
+ * segment's access.ts before the layout renders. If access.ts calls deny()
1237
+ * or redirect(), the signal propagates as a render-phase throw — caught by
1238
+ * the flush controller to produce the correct HTTP status code.
1239
+ *
1240
+ * SlotAccessGate wraps parallel slot content. On denial, it renders the
1241
+ * graceful degradation chain: denied.tsx → default.tsx → null. Slot denial
1242
+ * does not affect the HTTP status code.
1243
+ *
1244
+ * See design/04-authorization.md and design/02-rendering-pipeline.md §"AccessGate"
1245
+ */
1246
+ /**
1247
+ * Framework-injected access gate for segments.
1248
+ *
1249
+ * When a pre-computed `verdict` prop is provided (from the pre-render pass
1250
+ * in route-element-builder.ts), AccessGate replays it synchronously — no
1251
+ * async, no re-execution of access.ts, immune to Suspense timing. The OTEL
1252
+ * span was already emitted during the pre-render pass.
1253
+ *
1254
+ * When no verdict is provided (backward compat with tree-builder.ts),
1255
+ * AccessGate calls accessFn directly with OTEL instrumentation.
1256
+ *
1257
+ * access.ts is a pure gate — return values are discarded. The layout below
1258
+ * gets the same data by calling the same cached functions (React.cache dedup).
1259
+ */
1260
+ function AccessGate(props) {
1261
+ const { accessFn, segmentName, verdict, denyPages, children } = props;
1262
+ if (verdict !== void 0) {
1263
+ if (verdict === "pass") return children;
1264
+ throw verdict;
1265
+ }
1266
+ return accessGateFallback(accessFn, segmentName, denyPages, children);
1267
+ }
1268
+ /**
1269
+ * Async fallback for AccessGate when no pre-computed verdict is available.
1270
+ * Calls accessFn with OTEL instrumentation.
1271
+ */
1272
+ async function accessGateFallback(accessFn, segmentName, denyPages, children) {
1273
+ try {
1274
+ await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
1275
+ try {
1276
+ await accessFn();
1277
+ await setSpanAttribute("timber.result", "pass");
1278
+ } catch (error) {
1279
+ if (error instanceof DenySignal) {
1280
+ await setSpanAttribute("timber.result", "deny");
1281
+ await setSpanAttribute("timber.deny_status", error.status);
1282
+ if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
1283
+ } else if (error instanceof RedirectSignal) await setSpanAttribute("timber.result", "redirect");
1284
+ throw error;
1285
+ }
1286
+ });
1287
+ } catch (error) {
1288
+ if (error instanceof DenySignal && denyPages) {
1289
+ const denyElement = renderMatchingDenyPage(denyPages, error.status, error.data);
1290
+ if (denyElement) {
1291
+ setDenyStatus(error.status);
1292
+ return denyElement;
1293
+ }
1294
+ }
1295
+ throw error;
1296
+ }
1297
+ return children;
1298
+ }
1299
+ /**
1300
+ * Framework-injected access gate for parallel slots.
1301
+ *
1302
+ * On denial, graceful degradation: denied.tsx → default.tsx → null.
1303
+ * The HTTP status code is unaffected — slot denial is a UI concern, not
1304
+ * a protocol concern. The parent layout and sibling slots still render.
1305
+ *
1306
+ * DeniedComponent is passed instead of a pre-built element so that
1307
+ * DenySignal.data can be forwarded as the dangerouslyPassData prop
1308
+ * and the slot name can be passed as the slot prop. See TIM-488.
1309
+ *
1310
+ * redirect() in slot access.ts is a dev-mode error — redirecting from a
1311
+ * slot doesn't make architectural sense.
1312
+ */
1313
+ async function SlotAccessGate(props) {
1314
+ const { accessFn, DeniedComponent, slotName, createElement, defaultFallback, children } = props;
1315
+ try {
1316
+ await accessFn();
1317
+ } catch (error) {
1318
+ if (error instanceof DenySignal) return buildDeniedFallback(DeniedComponent, slotName, error.data, createElement) ?? defaultFallback ?? null;
1319
+ if (error instanceof RedirectSignal) {
1320
+ 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.");
1321
+ return buildDeniedFallback(DeniedComponent, slotName, void 0, createElement) ?? defaultFallback ?? null;
1322
+ }
1323
+ if (isDebug()) console.warn("[timber] Unhandled error in slot access.ts. Use deny() for access control, not unhandled throws.", error);
1324
+ throw error;
1325
+ }
1326
+ return children;
1327
+ }
1328
+ /**
1329
+ * Build the denied fallback element dynamically with DenySignal data.
1330
+ * Returns null if no DeniedComponent is available.
1331
+ */
1332
+ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
1333
+ if (!DeniedComponent) return null;
1334
+ return createElement(DeniedComponent, {
1335
+ slot: slotName,
1336
+ dangerouslyPassData: data
1337
+ });
1338
+ }
1339
+ //#endregion
1340
+ //#region src/server/param-coercion.ts
1341
+ /** Global schema codecs, set once at startup from virtual:timber-schema. */
1342
+ var _globalCodecs = null;
1343
+ /**
1344
+ * Run segment param coercion on the matched route's segments.
1345
+ *
1346
+ * When `globalCodecs` is provided (from app/schema.ts), uses the global
1347
+ * codec map keyed by bare param name. Otherwise falls back to loading
1348
+ * per-segment params.ts modules.
1349
+ *
1350
+ * Throws ParamCoercionError if any codec fails (→ 404).
1351
+ *
1352
+ * This runs BEFORE middleware, so ctx.segmentParams is already typed.
1353
+ * See design/07-routing.md §"Where Coercion Runs"
1354
+ * See design/41-global-params.md §"Pipeline Integration"
1355
+ */
1356
+ async function coerceSegmentParams(match) {
1357
+ const globalCodecs = _globalCodecs;
1358
+ const mergeTarget = Object.create(null);
1359
+ for (const key of Object.keys(match.segmentParams)) if (key !== "__proto__") mergeTarget[key] = match.segmentParams[key];
1360
+ match.segmentParams = mergeTarget;
1361
+ if (globalCodecs) {
1362
+ for (const segment of match.segments) {
1363
+ if (!segment.paramName) continue;
1364
+ const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
1365
+ const codec = globalCodecs[bracketKey];
1366
+ if (!codec) continue;
1367
+ const key = segment.paramName;
1368
+ try {
1369
+ mergeTarget[key] = sanitizeParamValue(codec.parse(mergeTarget[key]));
1370
+ } catch (err) {
1371
+ const message = err instanceof Error ? err.message : String(err);
1372
+ 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}'.`);
1373
+ throw new ParamCoercionError(message);
1374
+ }
1375
+ }
1376
+ return;
1377
+ }
1378
+ for (const segment of match.segments) {
1379
+ if (!segment.params) continue;
1380
+ let mod;
1381
+ try {
1382
+ mod = await loadModule(segment.params);
1383
+ } catch (err) {
1384
+ const message = `Failed to load params module for segment "${segment.segmentName}": ${err instanceof Error ? err.message : String(err)}`;
1385
+ if (isDebug()) console.warn(`[timber] Param coercion error: ${message}\n Segment: ${segment.segmentName}\n Params file: ${segment.params}`);
1386
+ throw new ParamCoercionError(message);
1387
+ }
1388
+ const segmentParamsDef = mod.segmentParams;
1389
+ if (!segmentParamsDef || typeof segmentParamsDef.parse !== "function") continue;
1390
+ try {
1391
+ const coerced = segmentParamsDef.parse(match.segmentParams);
1392
+ for (const key of Object.keys(coerced)) if (key !== "__proto__") mergeTarget[key] = sanitizeParamValue(coerced[key]);
1393
+ } catch (err) {
1394
+ const message = err instanceof Error ? err.message : String(err);
1395
+ if (isDebug()) {
1396
+ const rawKeys = Object.keys(match.segmentParams).join(", ");
1397
+ console.warn(`[timber] Param codec rejected values for segment "${segment.segmentName}"\n Error: ${message}\n Available raw params: { ${rawKeys} }\n Params file: ${segment.params}\n Hint: this usually means a codec threw for the raw URL value.\n Check that the regex/schema accepts the actual path segment string.`);
1398
+ }
1399
+ throw new ParamCoercionError(message);
1400
+ }
1401
+ }
1402
+ }
1403
+ //#endregion
1404
+ //#region src/client/segment-update-context.ts
1405
+ /**
1406
+ * SegmentUpdateContext — React context for partial navigation updates.
1407
+ *
1408
+ * During partial navigation (server skips unchanged sync layouts), the
1409
+ * router builds a Map of segment path → ReactNode updates and passes it
1410
+ * as the context value. Mounted SegmentOutlet components read from this
1411
+ * context to decide whether to render the update or their cached content.
1412
+ *
1413
+ * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as
1414
+ * NavigationContext. The RSC client bundler can duplicate this module
1415
+ * across chunks (browser-entry graph + client-reference graph). With
1416
+ * ESM output, each chunk gets its own module scope — a bare createContext
1417
+ * at module level would create separate instances per chunk. globalThis
1418
+ * guarantees a single instance regardless of duplication.
1419
+ *
1420
+ * See design/19-client-navigation.md §"Singleton Guarantee via globalThis"
1421
+ */
1422
+ var EMPTY_SEGMENT_UPDATES = /* @__PURE__ */ new Map();
1423
+ var CTX_KEY = Symbol.for("__timber_segment_update_ctx");
1424
+ function getOrCreateContext() {
1425
+ const existing = globalThis[CTX_KEY];
1426
+ if (existing !== void 0) return existing;
1427
+ if (typeof React.createContext === "function") {
1428
+ const ctx = React.createContext(EMPTY_SEGMENT_UPDATES);
1429
+ globalThis[CTX_KEY] = ctx;
1430
+ return ctx;
1431
+ }
1432
+ }
1433
+ getOrCreateContext();
1434
+ //#endregion
1435
+ //#region src/client/segment-outlet.tsx
1436
+ /**
1437
+ * SegmentOutlet — client component boundary at each layout segment.
1438
+ *
1439
+ * Each layout in the segment tree is wrapped with a SegmentOutlet that:
1440
+ * 1. Knows its segment path (prop from the server)
1441
+ * 2. Reads from SegmentUpdateContext for partial navigation updates
1442
+ * 3. Caches its rendered content in a ref across navigations
1443
+ *
1444
+ * On full navigation: receives new children via props, caches and renders them.
1445
+ * On partial navigation (this segment skipped): the context map has no entry
1446
+ * for this path, so the outlet returns cached content — preserving layout state.
1447
+ * On partial navigation (this segment updated): the context map has content
1448
+ * for this path, so the outlet renders the update.
1449
+ *
1450
+ * Uses React context instead of useSyncExternalStore to stay compatible
1451
+ * with concurrent rendering (transitions). All outlets re-render when the
1452
+ * context value changes, but each bails out quickly if its segment has
1453
+ * no update — same approach as Next.js LayoutRouter.
1454
+ *
1455
+ * Security: performance optimization only. The server always runs all
1456
+ * access.ts files regardless of segment skipping.
1457
+ * See design/13-security.md §"State tree manipulation".
1458
+ */
1459
+ //#endregion
1460
+ //#region src/server/route-element-builder.ts
1461
+ /**
1462
+ * Thrown when a defineSegmentParams codec's parse() fails.
1463
+ * The pipeline catches this and responds with 404.
1464
+ */
1465
+ var ParamCoercionError = class extends Error {
1466
+ constructor(message) {
1467
+ super(message);
1468
+ this.name = "ParamCoercionError";
1469
+ }
1470
+ };
1471
+ //#endregion
1472
+ //#region src/server/version-skew.ts
1473
+ /**
1474
+ * Version Skew Detection — graceful recovery when stale clients hit new deployments.
1475
+ *
1476
+ * When a new version of the app is deployed, clients with open tabs still have
1477
+ * the old JavaScript bundle. Without version skew handling, these stale clients
1478
+ * will experience:
1479
+ *
1480
+ * 1. Server action calls that crash (action IDs are content-hashed)
1481
+ * 2. Chunk load failures (old filenames gone from CDN)
1482
+ * 3. RSC payload mismatches (component references differ between builds)
1483
+ *
1484
+ * This module implements deployment ID comparison:
1485
+ * - A per-build deployment ID is generated at build time (see build-manifest.ts)
1486
+ * - The client sends it via `X-Timber-Deployment-Id` header on every RSC/action request
1487
+ * - The server compares it against the current build's ID
1488
+ * - On mismatch: signal the client to reload (not crash)
1489
+ *
1490
+ * The deployment ID is always-on in production. Dev mode skips the check
1491
+ * (HMR handles code updates without full reloads).
1492
+ *
1493
+ * See design/25-production-deployments.md, TIM-446
1494
+ */
1495
+ /** Header sent by the client with every RSC/action request. */
1496
+ var DEPLOYMENT_ID_HEADER = "X-Timber-Deployment-Id";
1497
+ /** Response header that signals the client to do a full page reload. */
1498
+ var RELOAD_HEADER = "X-Timber-Reload";
1499
+ /**
1500
+ * The current build's deployment ID. Set at startup from the manifest init
1501
+ * module (globalThis.__TIMBER_DEPLOYMENT_ID__). Null in dev mode.
1502
+ */
1503
+ var currentDeploymentId = null;
1504
+ /**
1505
+ * Check if a request's deployment ID matches the current build.
1506
+ *
1507
+ * Returns `{ ok: true }` when:
1508
+ * - Dev mode (no deployment ID set — HMR handles updates)
1509
+ * - No deployment ID header (initial page load, non-RSC request)
1510
+ * - Deployment IDs match
1511
+ *
1512
+ * Returns `{ ok: false }` when:
1513
+ * - Client sends a deployment ID that differs from the current build
1514
+ */
1515
+ function checkVersionSkew(req) {
1516
+ if (!currentDeploymentId) return {
1517
+ ok: true,
1518
+ clientId: null
1519
+ };
1520
+ const clientId = req.headers.get(DEPLOYMENT_ID_HEADER);
1521
+ if (!clientId) return {
1522
+ ok: true,
1523
+ clientId: null
1524
+ };
1525
+ if (clientId === currentDeploymentId) return {
1526
+ ok: true,
1527
+ clientId
1528
+ };
1529
+ return {
1530
+ ok: false,
1531
+ clientId
1532
+ };
1533
+ }
1534
+ /**
1535
+ * Apply version skew reload headers to a response.
1536
+ * Sets X-Timber-Reload: 1 to signal the client to do a full page reload.
1537
+ */
1538
+ function applyReloadHeaders(headers) {
1539
+ headers.set(RELOAD_HEADER, "1");
1540
+ }
1541
+ //#endregion
1542
+ //#region src/server/pipeline-metadata.ts
1543
+ /**
1544
+ * Metadata route helpers for the request pipeline.
1545
+ *
1546
+ * Handles serving static metadata files and serializing sitemap responses.
1547
+ * Extracted from pipeline.ts to keep files under 500 lines.
1548
+ *
1549
+ * See design/16-metadata.md §"Metadata Routes"
1550
+ */
1551
+ /**
1552
+ * Content types that are text-based and should include charset=utf-8.
1553
+ * Binary formats (images) should not include charset.
1554
+ */
1555
+ var TEXT_CONTENT_TYPES = new Set([
1556
+ "application/xml",
1557
+ "text/plain",
1558
+ "application/json",
1559
+ "application/manifest+json",
1560
+ "image/svg+xml"
1561
+ ]);
1562
+ /**
1563
+ * Serve a static metadata file by reading it from disk.
1564
+ *
1565
+ * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
1566
+ * are served as-is with the appropriate Content-Type header.
1567
+ * Text files include charset=utf-8; binary files do not.
1568
+ *
1569
+ * See design/16-metadata.md §"Metadata Routes"
1570
+ */
1571
+ async function serveStaticMetadataFile(metaMatch) {
1572
+ const { contentType, file } = metaMatch;
1573
+ const isText = TEXT_CONTENT_TYPES.has(contentType);
1574
+ const body = await readFile(file.filePath);
1575
+ const headers = {
1576
+ "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
1577
+ "Content-Length": String(body.byteLength)
1578
+ };
1579
+ return new Response(body, {
1580
+ status: 200,
1581
+ headers
1582
+ });
1583
+ }
1584
+ /**
1585
+ * Serialize a sitemap array to XML.
1586
+ * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
1587
+ */
1588
+ function serializeSitemap(entries) {
1589
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
1590
+ let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
1591
+ if (e.lastModified) {
1592
+ const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
1593
+ xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
1594
+ }
1595
+ if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
1596
+ if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
1597
+ xml += "\n </url>";
1598
+ return xml;
1599
+ }).join("\n")}\n</urlset>`;
1600
+ }
1601
+ /** Escape special XML characters. */
1602
+ function escapeXml(str) {
1603
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1604
+ }
1605
+ //#endregion
1606
+ //#region src/server/pipeline-interception.ts
1607
+ /**
1608
+ * Interception route matching for the request pipeline.
1609
+ *
1610
+ * Matches target URLs against interception rewrites to support the
1611
+ * modal route pattern (soft navigation intercepts).
1612
+ *
1613
+ * Extracted from pipeline.ts to keep files under 500 lines.
1614
+ *
1615
+ * See design/07-routing.md §"Intercepting Routes"
1616
+ */
1617
+ /**
1618
+ * Check if a pathname starts with a prefix on a segment boundary.
1619
+ *
1620
+ * Prevents /feed from matching /feed-private — the prefix must be
1621
+ * followed by '/' or be an exact match.
1622
+ */
1623
+ function hasSegmentPrefix(pathname, prefix) {
1624
+ if (!pathname.startsWith(prefix)) return false;
1625
+ return pathname.length === prefix.length || pathname[prefix.length] === "/";
1626
+ }
1627
+ /**
1628
+ * Check if an intercepting route applies for this soft navigation.
1629
+ *
1630
+ * Matches the target pathname against interception rewrites, constrained
1631
+ * by the source URL (X-Timber-URL header — where the user navigates FROM).
1632
+ *
1633
+ * Returns the source pathname to re-match if interception applies, or null.
1634
+ */
1635
+ function findInterceptionMatch(targetPathname, sourceUrl, rewrites) {
1636
+ for (const rewrite of rewrites) {
1637
+ if (!hasSegmentPrefix(sourceUrl, rewrite.interceptingPrefix)) continue;
1638
+ if (pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern)) return { sourcePathname: rewrite.interceptingPrefix };
1639
+ }
1640
+ return null;
1641
+ }
1642
+ /**
1643
+ * Check if a pathname matches a URL pattern with dynamic segments.
1644
+ *
1645
+ * Supports [param] (single segment) and [...param] (one or more segments).
1646
+ * Static segments must match exactly.
1647
+ */
1648
+ function pathnameMatchesPattern(pathname, pattern) {
1649
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
1650
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
1651
+ let pi = 0;
1652
+ for (let i = 0; i < patternParts.length; i++) {
1653
+ const seg = classifyUrlSegment(patternParts[i]);
1654
+ switch (seg.kind) {
1655
+ case "catch-all": return pi < pathParts.length;
1656
+ case "optional-catch-all": return true;
1657
+ case "dynamic":
1658
+ if (pi >= pathParts.length) return false;
1659
+ pi++;
1660
+ continue;
1661
+ case "static":
1662
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
1663
+ pi++;
1664
+ continue;
1665
+ }
1666
+ }
1667
+ return pi === pathParts.length;
1668
+ }
1669
+ //#endregion
1670
+ //#region src/server/pipeline-outcome.ts
1671
+ /**
1672
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
1673
+ * each phase function returns) into a final `Response`.
1674
+ *
1675
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
1676
+ * catch logic and the terminal Response-building logic each live in
1677
+ * their own file. The phases produce values; this module is the single
1678
+ * source of truth for how those values become wire responses.
1679
+ *
1680
+ * See design/07-routing.md §"Request Lifecycle".
1681
+ */
1682
+ function rscErrorResponse(isRsc, status, headers) {
1683
+ if (!isRsc) return new Response(null, { status });
1684
+ const h = headers ?? new Headers();
1685
+ h.set("X-Timber-Error", "1");
1686
+ h.set("content-type", "application/json; charset=utf-8");
1687
+ return new Response(JSON.stringify({
1688
+ error: true,
1689
+ status
1690
+ }), {
1691
+ status,
1692
+ headers: h
1693
+ });
1694
+ }
1695
+ /**
1696
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
1697
+ * `Response`, applying cookies, building redirects, rendering deny pages
1698
+ * and fallback error pages, and firing instrumentation hooks.
1699
+ *
1700
+ * This is the single source of truth for how phase outputs become wire
1701
+ * responses; the per-phase try/catch blocks now produce values, not
1702
+ * Responses, so the conversion logic lives in exactly one place.
1703
+ */
1704
+ async function outcomeToResponse(config, outcome, ctx) {
1705
+ switch (outcome.kind) {
1706
+ case "response": {
1707
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
1708
+ if (outcome.phase === "proxy") return finalResponse;
1709
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
1710
+ applyCookieJar(finalResponse.headers);
1711
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
1712
+ logMiddlewareShortCircuit({
1713
+ method: ctx.method,
1714
+ path: ctx.path,
1715
+ status: finalResponse.status
1716
+ });
1717
+ }
1718
+ if (outcome.phase === "render") markResponseFlushed();
1719
+ return finalResponse;
1720
+ }
1721
+ case "redirect": {
1722
+ const headers = ctx.responseHeaders ?? new Headers();
1723
+ applyCookieJar(headers);
1724
+ return buildRedirectResponse(outcome.signal, ctx.req, headers);
1725
+ }
1726
+ case "deny": {
1727
+ const headers = ctx.responseHeaders ?? new Headers();
1728
+ applyCookieJar(headers);
1729
+ if (config.renderDenyFallback) try {
1730
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
1731
+ } catch (denyRenderError) {
1732
+ logRenderError({
1733
+ method: ctx.method,
1734
+ path: ctx.path,
1735
+ error: denyRenderError
1736
+ });
1737
+ await fireOnRequestError(denyRenderError, ctx.req, "render");
1738
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
1739
+ }
1740
+ 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 not-found.tsx or error.tsx to render a custom deny page.`);
1741
+ return new Response(null, {
1742
+ status: outcome.signal.status,
1743
+ headers
1744
+ });
1745
+ }
1746
+ case "error": {
1747
+ const isRsc = (ctx.req.headers.get("Accept") ?? "").includes("text/x-component");
1748
+ if (outcome.phase === "proxy") {
1749
+ logProxyError({ error: outcome.error });
1750
+ await fireOnRequestError(outcome.error, ctx.req, "proxy");
1751
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "proxy");
1752
+ return rscErrorResponse(isRsc, 500);
1753
+ }
1754
+ if (outcome.phase === "middleware") {
1755
+ logMiddlewareError({
1756
+ method: ctx.method,
1757
+ path: ctx.path,
1758
+ error: outcome.error
1759
+ });
1760
+ await fireOnRequestError(outcome.error, ctx.req, "handler");
1761
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "middleware");
1762
+ return rscErrorResponse(isRsc, 500);
1763
+ }
1764
+ const headers = ctx.responseHeaders ?? new Headers();
1765
+ applyCookieJar(headers);
1766
+ logRenderError({
1767
+ method: ctx.method,
1768
+ path: ctx.path,
1769
+ error: outcome.error
1770
+ });
1771
+ await fireOnRequestError(outcome.error, ctx.req, "render");
1772
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "render");
1773
+ if (isRsc) return rscErrorResponse(true, 500, headers);
1774
+ if (config.renderFallbackError) try {
1775
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, headers));
1776
+ } catch (fallbackRenderError) {
1777
+ logRenderError({
1778
+ method: ctx.method,
1779
+ path: ctx.path,
1780
+ error: fallbackRenderError
1781
+ });
1782
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render");
1783
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
1784
+ }
1785
+ return new Response(null, { status: 500 });
1786
+ }
1787
+ }
1788
+ }
1789
+ //#endregion
1790
+ //#region src/server/pipeline-phases.ts
1791
+ /**
1792
+ * Pipeline phase functions — module-level free functions that take their
1793
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
1794
+ * (a discriminated union over response / redirect / deny / error) defined
1795
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
1796
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
1797
+ *
1798
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
1799
+ * isolation. The lift is mechanical — these functions used to be closures
1800
+ * over `config`; they now take `config` as an explicit parameter.
1801
+ *
1802
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
1803
+ */
1804
+ /**
1805
+ * Validate and canonicalize the X-Timber-URL header value.
1806
+ *
1807
+ * Returns the canonical pathname if valid, or null if rejected:
1808
+ * - Must start with '/' (relative pathname, no scheme/authority)
1809
+ * - Must not contain control characters
1810
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
1811
+ */
1812
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
1813
+ if (!raw.startsWith("/")) return null;
1814
+ if (raw.startsWith("//")) return null;
1815
+ for (let i = 0; i < raw.length; i++) {
1816
+ const code = raw.charCodeAt(i);
1817
+ if (code <= 31 || code === 127) return null;
1818
+ }
1819
+ const result = canonicalize(raw, stripTrailingSlash);
1820
+ if (!result.ok) return null;
1821
+ return result.pathname;
1822
+ }
1823
+ /**
1824
+ * Run the proxy.ts phase. Calls user proxy code and uses `handleRequest` as
1825
+ * the inner `next()` continuation. The proxy resolver was picked at pipeline
1826
+ * construction time so the hot path sees no per-request branching on the
1827
+ * `ProxyConfig` discriminant.
1828
+ */
1829
+ async function runProxyPhase(config, getProxy, req, method, path) {
1830
+ const detailed = config.serverTiming === "detailed";
1831
+ try {
1832
+ const proxyExport = await getProxy();
1833
+ const proxyFn = () => runProxy(proxyExport, req, () => handleRequest(config, req, method, path));
1834
+ return {
1835
+ kind: "response",
1836
+ phase: "proxy",
1837
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
1838
+ };
1839
+ } catch (error) {
1840
+ return {
1841
+ kind: "error",
1842
+ phase: "proxy",
1843
+ error
1844
+ };
1845
+ }
1846
+ }
1847
+ /**
1848
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
1849
+ * returns it as a 'response' outcome. Otherwise applies the request header
1850
+ * overlay and falls through to the render phase.
1851
+ */
1852
+ async function runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext) {
1853
+ const detailed = config.serverTiming === "detailed";
1854
+ const ctx = {
1855
+ req,
1856
+ requestHeaders: requestHeaderOverlay,
1857
+ headers: responseHeaders,
1858
+ segmentParams: match.segmentParams,
1859
+ earlyHints: (hints) => {
1860
+ for (const hint of hints) {
1861
+ let value;
1862
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
1863
+ else value = `<${hint.href}>; rel=${hint.rel}`;
1864
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1865
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1866
+ responseHeaders.append("Link", value);
1867
+ }
1868
+ }
1869
+ };
1870
+ try {
1871
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
1872
+ const middlewareResponse = await (async () => {
1873
+ setMutableCookieContext(true);
1874
+ try {
1875
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
1876
+ } finally {
1877
+ setMutableCookieContext(false);
1878
+ }
1879
+ })();
1880
+ if (middlewareResponse) return {
1881
+ kind: "response",
1882
+ phase: "middleware",
1883
+ response: middlewareResponse
1884
+ };
1885
+ applyRequestHeaderOverlay(requestHeaderOverlay);
1886
+ applyCookieJar(responseHeaders);
1887
+ return runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext);
1888
+ } catch (error) {
1889
+ if (error instanceof RedirectSignal) return {
1890
+ kind: "redirect",
1891
+ phase: "middleware",
1892
+ signal: error
1893
+ };
1894
+ if (error instanceof DenySignal) return {
1895
+ kind: "deny",
1896
+ phase: "middleware",
1897
+ signal: error
1898
+ };
1899
+ return {
1900
+ kind: "error",
1901
+ phase: "middleware",
1902
+ error
1903
+ };
1904
+ }
1905
+ }
1906
+ /**
1907
+ * Run the render phase. Wraps the configured renderer in a span and a
1908
+ * timing scope, and translates thrown signals into outcome variants.
1909
+ */
1910
+ async function runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, { canonicalPathname, interception }) {
1911
+ const detailed = config.serverTiming === "detailed";
1912
+ try {
1913
+ const renderFn = () => config.render(req, match, responseHeaders, requestHeaderOverlay, interception);
1914
+ return {
1915
+ kind: "response",
1916
+ phase: "render",
1917
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
1918
+ };
1919
+ } catch (error) {
1920
+ if (error instanceof DenySignal) return {
1921
+ kind: "deny",
1922
+ phase: "render",
1923
+ signal: error
1924
+ };
1925
+ if (error instanceof RedirectSignal) return {
1926
+ kind: "redirect",
1927
+ phase: "render",
1928
+ signal: error
1929
+ };
1930
+ return {
1931
+ kind: "error",
1932
+ phase: "render",
1933
+ error
1934
+ };
1935
+ }
1936
+ }
1937
+ /**
1938
+ * Process a single request from canonicalization through phase dispatch.
1939
+ *
1940
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
1941
+ * route match → interception → early hints → param coercion → middleware →
1942
+ * render → outcome translation. Pre-routing short-circuits return Responses
1943
+ * directly; post-match dispatch goes through `outcomeToResponse`.
1944
+ *
1945
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
1946
+ * the `next()` continuation passed to `runProxy()`.
1947
+ */
1948
+ async function handleRequest(config, req, method, path) {
1949
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1950
+ const url = new URL(req.url);
1951
+ const result = canonicalize(url.pathname, stripTrailingSlash);
1952
+ if (!result.ok) {
1953
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${url.pathname} — 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.`);
1954
+ return new Response(null, { status: result.status });
1955
+ }
1956
+ const canonicalPathname = result.pathname;
1957
+ if (config.matchMetadataRoute) {
1958
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
1959
+ if (metaMatch) try {
1960
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
1961
+ setSegmentParams(metaMatch.segmentParams);
1962
+ const mod = await loadModule(metaMatch.file);
1963
+ if (typeof mod.default !== "function") {
1964
+ 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.`);
1965
+ return new Response("Metadata route must export a default function", { status: 500 });
1966
+ }
1967
+ const handlerResult = await mod.default();
1968
+ if (handlerResult instanceof Response) {
1969
+ if (method === "HEAD") return new Response(null, {
1970
+ status: handlerResult.status,
1971
+ statusText: handlerResult.statusText,
1972
+ headers: new Headers(handlerResult.headers)
1973
+ });
1974
+ return cloneWithMutableHeaders(handlerResult);
1975
+ }
1976
+ const contentType = metaMatch.contentType;
1977
+ let body;
1978
+ if (typeof handlerResult === "string") body = handlerResult;
1979
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
1980
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
1981
+ else body = String(handlerResult);
1982
+ return new Response(body, {
1983
+ status: 200,
1984
+ headers: { "Content-Type": `${contentType}; charset=utf-8` }
1985
+ });
1986
+ } catch (error) {
1987
+ logRenderError({
1988
+ method,
1989
+ path,
1990
+ error
1991
+ });
1992
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
1993
+ return new Response(null, { status: 500 });
1994
+ }
1995
+ }
1996
+ if (config.autoSitemapHandler) try {
1997
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
1998
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
1999
+ } catch (error) {
2000
+ logRenderError({
2001
+ method,
2002
+ path,
2003
+ error
2004
+ });
2005
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
2006
+ return new Response(null, { status: 500 });
2007
+ }
2008
+ const isRscRequest = (req.headers.get("Accept") ?? "").includes("text/x-component");
2009
+ if (isRscRequest) {
2010
+ if (!checkVersionSkew(req).ok) {
2011
+ const reloadHeaders = new Headers();
2012
+ applyReloadHeaders(reloadHeaders);
2013
+ return new Response(null, {
2014
+ status: 204,
2015
+ headers: reloadHeaders
2016
+ });
2017
+ }
2018
+ }
2019
+ let match = config.matchRoute(canonicalPathname);
2020
+ let interception;
2021
+ if (isRscRequest && config.interceptionRewrites?.length) {
2022
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
2023
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
2024
+ if (validatedSourceUrl) {
2025
+ const intercepted = findInterceptionMatch(canonicalPathname, validatedSourceUrl, config.interceptionRewrites);
2026
+ if (intercepted) {
2027
+ const sourceMatch = config.matchRoute(intercepted.sourcePathname);
2028
+ if (sourceMatch) {
2029
+ match = sourceMatch;
2030
+ interception = { targetPathname: canonicalPathname };
2031
+ }
2032
+ }
2033
+ }
2034
+ }
2035
+ if (!match) {
2036
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Raw URL: ${url.pathname}\n Method: ${method}`);
2037
+ if (config.renderNoMatch) {
2038
+ const responseHeaders = new Headers();
2039
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2040
+ }
2041
+ return new Response(null, { status: 404 });
2042
+ }
2043
+ const responseHeaders = new Headers();
2044
+ const requestHeaderOverlay = new Headers();
2045
+ responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
2046
+ if (config.earlyHints) try {
2047
+ await config.earlyHints(match, req, responseHeaders);
2048
+ } catch (err) {
2049
+ swallow(err, "early hints hook threw");
2050
+ }
2051
+ match.rawSegmentParams = { ...match.segmentParams };
2052
+ try {
2053
+ await coerceSegmentParams(match);
2054
+ } catch (error) {
2055
+ if (error instanceof ParamCoercionError) {
2056
+ if (isDebug()) {
2057
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
2058
+ 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 params.ts codec rejected the URL params.\n Check that all fields in defineSegmentParams() are optional for params\n that don't appear at every route depth (e.g. year, month, day).`);
2059
+ }
2060
+ const leafSegment = match.segments[match.segments.length - 1];
2061
+ if (leafSegment.route && !leafSegment.page) return new Response(null, { status: 404 });
2062
+ if (config.renderNoMatch) return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2063
+ return new Response(null, { status: 404 });
2064
+ }
2065
+ throw error;
2066
+ }
2067
+ setSegmentParams(match.segmentParams);
2068
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
2069
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
2070
+ return outcomeToResponse(config, !shouldBypassMiddleware(req) && match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2071
+ canonicalPathname,
2072
+ interception
2073
+ }) : await runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2074
+ canonicalPathname,
2075
+ interception
2076
+ }), {
2077
+ req,
2078
+ method,
2079
+ path,
2080
+ responseHeaders,
2081
+ match
2082
+ });
2083
+ }
2084
+ //#endregion
2085
+ //#region src/server/pipeline.ts
2086
+ /**
2087
+ * Create the request handler from a pipeline configuration.
2088
+ *
2089
+ * Returns a function that processes an incoming Request through all pipeline
2090
+ * stages and produces a Response. This is the top-level entry point for the
2091
+ * server. The body is intentionally small — phase logic lives in
2092
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
2093
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
2094
+ * scope, Server-Timing header emission, and the active-request counter.
2095
+ */
2096
+ function createPipeline(config) {
2097
+ const proxyResolver = makeProxyResolver(config.proxy);
2098
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
2099
+ const serverTiming = config.serverTiming ?? "total";
2100
+ let activeRequests = 0;
2101
+ return async (req) => {
2102
+ const url = new URL(req.url);
2103
+ const method = req.method;
2104
+ const path = url.pathname;
2105
+ const startTime = performance.now();
2106
+ activeRequests++;
2107
+ return runWithTraceId(generateTraceId(), async () => {
2108
+ return runWithRequestContext(req, async () => {
2109
+ const runRequest = async () => {
2110
+ logRequestReceived({
2111
+ method,
2112
+ path
2113
+ });
2114
+ const response = await withSpan("http.server.request", {
2115
+ "http.request.method": method,
2116
+ "url.path": path
2117
+ }, async () => {
2118
+ const otelIds = await getOtelTraceId();
2119
+ if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
2120
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2121
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
2122
+ if (!canonResult.ok) {
2123
+ 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.`);
2124
+ return new Response(null, { status: canonResult.status });
2125
+ }
2126
+ const canonicalPath = canonResult.pathname;
2127
+ let canonicalReq = req;
2128
+ if (url.pathname !== canonicalPath) {
2129
+ const canonicalUrl = new URL(req.url);
2130
+ canonicalUrl.pathname = canonicalPath;
2131
+ canonicalReq = new Request(canonicalUrl.toString(), req);
2132
+ }
2133
+ let result;
2134
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath), {
2135
+ req: canonicalReq,
2136
+ method,
2137
+ path: canonicalPath
2138
+ });
2139
+ else result = await handleRequest(config, canonicalReq, method, canonicalPath);
2140
+ await setSpanAttribute("http.response.status_code", result.status);
2141
+ if (serverTiming === "detailed") {
2142
+ const timingHeader = getServerTimingHeader();
2143
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
2144
+ } else if (serverTiming === "total") {
2145
+ const totalMs = Math.round(performance.now() - startTime);
2146
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
2147
+ }
2148
+ return result;
2149
+ });
2150
+ const durationMs = Math.round(performance.now() - startTime);
2151
+ const status = response.status;
2152
+ const concurrency = activeRequests;
2153
+ activeRequests--;
2154
+ logRequestCompleted({
2155
+ method,
2156
+ path,
2157
+ status,
2158
+ durationMs,
2159
+ concurrency
2160
+ });
2161
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
2162
+ method,
2163
+ path,
2164
+ durationMs,
2165
+ threshold: slowRequestMs,
2166
+ concurrency
2167
+ });
2168
+ return response;
2169
+ };
2170
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
2171
+ });
2172
+ });
2173
+ };
2174
+ }
2175
+ //#endregion
2176
+ //#region src/server/build-manifest.ts
2177
+ /**
2178
+ * Collect all CSS files needed for a matched route's segment chain.
2179
+ *
2180
+ * Walks segments root → leaf, collecting CSS for each layout and page.
2181
+ * Deduplicates while preserving order (root layout CSS first).
2182
+ */
2183
+ function collectRouteCss(segments, manifest) {
2184
+ const seen = /* @__PURE__ */ new Set();
2185
+ const result = [];
2186
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2187
+ if (!file) continue;
2188
+ const cssFiles = manifest.css[file.filePath];
2189
+ if (!cssFiles) continue;
2190
+ for (const url of cssFiles) if (!seen.has(url)) {
2191
+ seen.add(url);
2192
+ result.push(url);
2193
+ }
2194
+ }
2195
+ return result;
2196
+ }
2197
+ /**
2198
+ * Collect all font entries needed for a matched route's segment chain.
2199
+ *
2200
+ * Walks segments root → leaf, collecting fonts for each layout and page.
2201
+ * Deduplicates by href while preserving order.
2202
+ */
2203
+ function collectRouteFonts(segments, manifest) {
2204
+ const seen = /* @__PURE__ */ new Set();
2205
+ const result = [];
2206
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2207
+ if (!file) continue;
2208
+ const fonts = manifest.fonts[file.filePath];
2209
+ if (!fonts) continue;
2210
+ for (const entry of fonts) if (!seen.has(entry.href)) {
2211
+ seen.add(entry.href);
2212
+ result.push(entry);
2213
+ }
2214
+ }
2215
+ return result;
2216
+ }
2217
+ /**
2218
+ * Collect modulepreload URLs for a matched route's segment chain.
2219
+ *
2220
+ * Walks segments root → leaf, collecting transitive JS dependencies
2221
+ * for each layout and page. Deduplicates across segments.
2222
+ */
2223
+ function collectRouteModulepreloads(segments, manifest) {
2224
+ const seen = /* @__PURE__ */ new Set();
2225
+ const result = [];
2226
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2227
+ if (!file) continue;
2228
+ const preloads = manifest.modulepreload[file.filePath];
2229
+ if (!preloads) continue;
2230
+ for (const url of preloads) if (!seen.has(url)) {
2231
+ seen.add(url);
2232
+ result.push(url);
2233
+ }
2234
+ }
2235
+ return result;
2236
+ }
2237
+ //#endregion
2238
+ //#region src/server/early-hints.ts
2239
+ /**
2240
+ * 103 Early Hints utilities.
2241
+ *
2242
+ * Early Hints are sent before the final response to let the browser
2243
+ * start fetching critical resources (CSS, fonts, JS) while the server
2244
+ * is still rendering.
2245
+ *
2246
+ * The framework collects hints from two sources:
2247
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
2248
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
2249
+ *
2250
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
2251
+ * Link headers into 103 Early Hints responses.
2252
+ *
2253
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
2254
+ */
2255
+ /**
2256
+ * Format a single EarlyHint as a Link header value.
2257
+ *
2258
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
2259
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
2260
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
2261
+ * attribute order differs from Cloudflare's cached copy, the browser
2262
+ * sees two preload headers for the same URL (different attribute order)
2263
+ * and warns "Preload was ignored." Matching the order ensures the
2264
+ * browser deduplicates them correctly.
2265
+ *
2266
+ * Examples:
2267
+ * `</styles/root.css>; as=style; rel=preload`
2268
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
2269
+ * `</_timber/client.js>; rel=modulepreload`
2270
+ * `<https://fonts.googleapis.com>; rel=preconnect`
2271
+ */
2272
+ function formatLinkHeader(hint) {
2273
+ if (hint.as !== void 0) {
2274
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2275
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2276
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2277
+ return value;
2278
+ }
2279
+ let value = `<${hint.href}>; rel=${hint.rel}`;
2280
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2281
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2282
+ return value;
2283
+ }
2284
+ /**
2285
+ * Collect all Link header strings for a matched route's segment chain.
2286
+ *
2287
+ * Walks the build manifest to emit hints for:
2288
+ * - CSS stylesheets (as=style; rel=preload)
2289
+ * - Font assets (as=font; rel=preload; crossorigin)
2290
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
2291
+ *
2292
+ * Also emits global CSS from the `_global` manifest key. Route files
2293
+ * are server components that don't appear in the client bundle, so
2294
+ * per-route CSS keying doesn't work with the RSC plugin. The `_global`
2295
+ * key contains all CSS assets from the client build — fine for early
2296
+ * hints since they're just prefetch signals.
2297
+ *
2298
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
2299
+ * Returns an empty array in dev mode (manifest is empty).
2300
+ */
2301
+ function collectEarlyHintHeaders(segments, manifest, options) {
2302
+ const result = [];
2303
+ const seenUrls = /* @__PURE__ */ new Set();
2304
+ const add = (url, header) => {
2305
+ if (!seenUrls.has(url)) {
2306
+ seenUrls.add(url);
2307
+ result.push(header);
2308
+ }
2309
+ };
2310
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
2311
+ href: url,
2312
+ rel: "preload",
2313
+ as: "style"
2314
+ }));
2315
+ for (const url of manifest.css["_global"] ?? []) add(url, formatLinkHeader({
2316
+ href: url,
2317
+ rel: "preload",
2318
+ as: "style"
2319
+ }));
2320
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
2321
+ href: font.href,
2322
+ rel: "preload",
2323
+ as: "font",
2324
+ crossOrigin: "anonymous"
2325
+ }));
2326
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
2327
+ href: url,
2328
+ rel: "modulepreload"
2329
+ }));
2330
+ return result;
2331
+ }
2332
+ //#endregion
2333
+ //#region src/server/early-hints-sender.ts
2334
+ /**
2335
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
2336
+ *
2337
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
2338
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
2339
+ * the adapter can send these as a 103 Early Hints interim response before
2340
+ * the final response is ready.
2341
+ *
2342
+ * This module provides an ALS-based bridge: the generated entry point
2343
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
2344
+ * binding a per-request sender function. The pipeline calls
2345
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
2346
+ *
2347
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
2348
+ * converts Link headers into 103 automatically), no sender is installed
2349
+ * and `sendEarlyHints103()` is a no-op.
2350
+ *
2351
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
2352
+ */
2353
+ /**
2354
+ * Run a function with a per-request early hints sender installed.
2355
+ *
2356
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
2357
+ * bind the platform's writeEarlyHints capability for the request duration.
2358
+ */
2359
+ function runWithEarlyHintsSender(sender, fn) {
2360
+ return earlyHintsSenderAls.run(sender, fn);
2361
+ }
2362
+ /**
2363
+ * Send collected Link headers as a 103 Early Hints response.
2364
+ *
2365
+ * No-op if no sender is installed for the current request (e.g., on
2366
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
2367
+ *
2368
+ * Non-fatal: errors from the sender are caught and silently ignored.
2369
+ */
2370
+ function sendEarlyHints103(links) {
2371
+ if (!links.length) return;
2372
+ const sender = earlyHintsSenderAls.getStore();
2373
+ if (!sender) return;
2374
+ try {
2375
+ sender(links);
2376
+ } catch (err) {
2377
+ swallow(err, "early hints 103 send failed");
2378
+ }
2379
+ }
2380
+ //#endregion
2381
+ //#region src/server/tree-builder.ts
2382
+ var REACT_COMPONENT_TYPE_MARKERS = new Set([
2383
+ Symbol.for("react.forward_ref"),
2384
+ Symbol.for("react.memo"),
2385
+ Symbol.for("react.lazy"),
2386
+ Symbol.for("react.provider"),
2387
+ Symbol.for("react.context"),
2388
+ Symbol.for("react.suspense"),
2389
+ Symbol.for("react.suspense_list"),
2390
+ Symbol.for("react.client.reference")
2391
+ ]);
2392
+ /**
2393
+ * Validate that a loaded module's `default` export is something React
2394
+ * accepts as the first argument to `createElement` — i.e. a valid component
2395
+ * type. React doesn't export `isValidElementType` (only `isValidElement`,
2396
+ * which checks for *elements*, not *component types*), so this mirrors
2397
+ * React's internal check:
2398
+ *
2399
+ * - functions → function or class components
2400
+ * - objects with a `$$typeof` matching one of React's known component
2401
+ * markers → exotic components (`memo`, `forwardRef`, `lazy`, context,
2402
+ * suspense, client references via `@vitejs/plugin-rsc`)
2403
+ *
2404
+ * Strings (HTML tag names) are valid for `createElement` but never appear
2405
+ * as a route module's default export, so they're not recognized here.
2406
+ *
2407
+ * Anything else (numbers, plain config objects, JSON, etc.) is rejected so
2408
+ * the boundary wrapper is skipped rather than crashing inside React.
2409
+ */
2410
+ function isValidElementType(value) {
2411
+ if (typeof value === "function") return true;
2412
+ if (typeof value !== "object" || value === null) return false;
2413
+ const marker = value.$$typeof;
2414
+ return typeof marker === "symbol" && REACT_COMPONENT_TYPE_MARKERS.has(marker);
2415
+ }
2416
+ /**
2417
+ * Build the unified element tree from a matched segment chain.
2418
+ *
2419
+ * Construction is bottom-up:
2420
+ * 1. Start with the page component (leaf segment)
2421
+ * 2. Wrap in status-code error boundaries (fallback chain)
2422
+ * 3. Wrap in AccessGate (if segment has access.ts)
2423
+ * 4. Pass as children to the segment's layout
2424
+ * 5. Repeat up the segment chain to root
2425
+ *
2426
+ * Parallel slots are resolved at each layout level and composed as named props.
2427
+ */
2428
+ async function buildElementTree(config) {
2429
+ const { segments, loadModule, createElement, errorBoundaryComponent } = config;
2430
+ if (segments.length === 0) throw new Error("[timber] buildElementTree: empty segment chain");
2431
+ const leaf = segments[segments.length - 1];
2432
+ if (leaf.route && !leaf.page) return {
2433
+ tree: null,
2434
+ isApiRoute: true
2435
+ };
2436
+ const PageComponent = (leaf.page ? await loadModule(leaf.page) : null)?.default;
2437
+ if (!PageComponent) throw new Error(`[timber] No page component found for route at ${leaf.urlPath}. Each route must have a page.tsx or route.ts.`);
2438
+ let element = createElement(PageComponent, {});
2439
+ for (let i = segments.length - 1; i >= 0; i--) {
2440
+ const segment = segments[i];
2441
+ element = await wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent);
2442
+ if (segment.access) {
2443
+ const accessFn = (await loadModule(segment.access)).default;
2444
+ element = createElement("timber:access-gate", {
2445
+ accessFn,
2446
+ segmentName: segment.segmentName,
2447
+ children: element
2448
+ });
2449
+ }
2450
+ if (segment.layout) {
2451
+ const LayoutComponent = (await loadModule(segment.layout)).default;
2452
+ if (LayoutComponent) {
2453
+ const slotProps = {};
2454
+ const slotNames = Object.keys(segment.slots);
2455
+ if (slotNames.length > 0) for (const slotName of slotNames) {
2456
+ const slotNode = segment.slots[slotName];
2457
+ slotProps[slotName] = await buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent);
2458
+ }
2459
+ element = createElement(LayoutComponent, {
2460
+ ...slotProps,
2461
+ children: element
2462
+ });
2463
+ }
2464
+ }
2465
+ }
2466
+ return {
2467
+ tree: element,
2468
+ isApiRoute: false
2469
+ };
2470
+ }
2471
+ /**
2472
+ * Build the element tree for a parallel slot.
2473
+ *
2474
+ * Slots have their own access.ts (SlotAccessGate) and error boundaries.
2475
+ * On access denial: denied.tsx → default.tsx → null (graceful degradation).
2476
+ */
2477
+ async function buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent) {
2478
+ const PageComponent = (slotNode.page ? await loadModule(slotNode.page) : null)?.default;
2479
+ const DefaultComponent = (slotNode.default ? await loadModule(slotNode.default) : null)?.default;
2480
+ if (!PageComponent) return DefaultComponent ? createElement(DefaultComponent, {}) : null;
2481
+ let element = createElement(PageComponent, {});
2482
+ element = await wrapWithErrorBoundaries(slotNode, element, loadModule, createElement, errorBoundaryComponent);
2483
+ if (slotNode.access) {
2484
+ const accessFn = (await loadModule(slotNode.access)).default;
2485
+ const DeniedComponent = (slotNode.denied ? await loadModule(slotNode.denied) : null)?.default ?? null;
2486
+ const defaultFallback = DefaultComponent ? createElement(DefaultComponent, {}) : null;
2487
+ element = createElement("timber:slot-access-gate", {
2488
+ accessFn,
2489
+ DeniedComponent,
2490
+ slotName: slotNode.segmentName.replace(/^@/, ""),
2491
+ createElement,
2492
+ defaultFallback,
2493
+ children: element
2494
+ });
2495
+ }
2496
+ return element;
2497
+ }
2498
+ /** MDX/markdown extensions — these are server components that cannot be passed as function props. */
2499
+ var MDX_EXTENSIONS = new Set(["mdx", "md"]);
2500
+ /**
2501
+ * Check if a route file is an MDX/markdown file based on its extension.
2502
+ * MDX components are server components by default and cannot cross the
2503
+ * RSC→client boundary as function props. They must be pre-rendered as
2504
+ * elements and passed as fallbackElement instead of fallbackComponent.
2505
+ */
2506
+ function isMdxFile(file) {
2507
+ return MDX_EXTENSIONS.has(file.extension);
2508
+ }
2509
+ /**
2510
+ * Wrap an element with error boundaries from a segment's status-code files.
2511
+ *
2512
+ * Wrapping order (innermost to outermost):
2513
+ * 1. Specific status files (503.tsx, 429.tsx, etc.)
2514
+ * 2. Category catch-alls (4xx.tsx, 5xx.tsx)
2515
+ * 3. error.tsx (general error boundary)
2516
+ *
2517
+ * This creates the fallback chain described in design/10-error-handling.md.
2518
+ *
2519
+ * MDX status files are server components and cannot be passed as function
2520
+ * props to TimberErrorBoundary (a 'use client' component). Instead, they
2521
+ * are pre-rendered as elements and passed as fallbackElement. The error
2522
+ * boundary renders the element directly when an error is caught.
2523
+ * See TIM-503.
2524
+ */
2525
+ async function wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent) {
2526
+ if (segment.statusFiles) {
2527
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key !== "4xx" && key !== "5xx") {
2528
+ const status = parseInt(key, 10);
2529
+ if (!isNaN(status)) {
2530
+ const mod = await loadModule(file);
2531
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2532
+ if (Component) element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2533
+ fallbackElement: createElement(Component, { status }),
2534
+ status,
2535
+ children: element
2536
+ } : {
2537
+ fallbackComponent: Component,
2538
+ status,
2539
+ children: element
2540
+ });
2541
+ }
2542
+ }
2543
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key === "4xx" || key === "5xx") {
2544
+ const mod = await loadModule(file);
2545
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2546
+ if (Component) {
2547
+ const categoryStatus = key === "4xx" ? 400 : 500;
2548
+ element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2549
+ fallbackElement: createElement(Component, {}),
2550
+ status: categoryStatus,
2551
+ children: element
2552
+ } : {
2553
+ fallbackComponent: Component,
2554
+ status: categoryStatus,
2555
+ children: element
2556
+ });
2557
+ }
2558
+ }
2559
+ }
2560
+ if (segment.error) {
2561
+ const errorModule = await loadModule(segment.error);
2562
+ const ErrorComponent = isValidElementType(errorModule.default) ? errorModule.default : null;
2563
+ if (ErrorComponent) element = createElement(errorBoundaryComponent, isMdxFile(segment.error) ? {
2564
+ fallbackElement: createElement(ErrorComponent, {}),
2565
+ children: element
2566
+ } : {
2567
+ fallbackComponent: ErrorComponent,
2568
+ children: element
2569
+ });
2570
+ }
2571
+ return element;
2572
+ }
2573
+ //#endregion
2574
+ //#region src/server/status-code-resolver.ts
2575
+ /** Reverse index: status code → legacy file name. Built once at module load. */
2576
+ var STATUS_TO_LEGACY_FILE = Object.fromEntries(Object.entries({
2577
+ "not-found": 404,
2578
+ "forbidden": 403,
2579
+ "unauthorized": 401
2580
+ }).map(([name, status]) => [status, name]));
2581
+ /**
2582
+ * Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
2583
+ * status-file group on a single segment. Shared by all three fallback
2584
+ * chains — the only structural difference between component 4xx,
2585
+ * component 5xx, and JSON resolution is *which* group is searched and
2586
+ * how the per-segment loop is layered around it.
2587
+ */
2588
+ function lookupInGroup(group, statusStr, categoryKey, segmentIndex, status) {
2589
+ if (!group) return null;
2590
+ const exact = group[statusStr];
2591
+ if (exact) return {
2592
+ file: exact,
2593
+ status,
2594
+ kind: "exact",
2595
+ segmentIndex
2596
+ };
2597
+ const category = group[categoryKey];
2598
+ if (category) return {
2599
+ file: category,
2600
+ status,
2601
+ kind: "category",
2602
+ segmentIndex
2603
+ };
2604
+ return null;
2605
+ }
2606
+ /**
2607
+ * Look up the legacy convention file (`not-found.tsx` / `forbidden.tsx` /
2608
+ * `unauthorized.tsx`) for `status` on a single segment. Returns null if
2609
+ * `status` has no legacy mapping or the file isn't present.
2610
+ */
2611
+ function lookupLegacy(group, status, segmentIndex) {
2612
+ if (!group) return null;
2613
+ const name = STATUS_TO_LEGACY_FILE[status];
2614
+ if (!name) return null;
2615
+ const file = group[name];
2616
+ return file ? {
2617
+ file,
2618
+ status,
2619
+ kind: "legacy",
2620
+ segmentIndex
2621
+ } : null;
2622
+ }
2623
+ /**
2624
+ * Resolve the status-code file to render for a given HTTP status code.
2625
+ *
2626
+ * Walks the segment chain from leaf to root following the fallback chain
2627
+ * defined in design/10-error-handling.md. Returns null if no file is found
2628
+ * (caller should render the framework default).
2629
+ *
2630
+ * @param status - The HTTP status code (4xx or 5xx).
2631
+ * @param segments - The matched segment chain from root (index 0) to leaf (last).
2632
+ * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
2633
+ */
2634
+ function resolveStatusFile(status, segments, format = "component") {
2635
+ if (status < 400 || status > 599) return null;
2636
+ if (format === "json") return resolveJson(status, segments);
2637
+ if (status <= 499) return resolve4xx(status, segments);
2638
+ return resolve5xx(status, segments);
2639
+ }
2640
+ /**
2641
+ * 4xx component fallback chain — three separate full passes leaf→root.
2642
+ *
2643
+ * The passes must be separate (not interleaved per-segment) so that a
2644
+ * root-level `404.tsx` beats a leaf-level `error.tsx`. The 5xx chain
2645
+ * inverts this and is per-segment: a leaf's `error.tsx` beats a root's
2646
+ * `5xx.tsx`. This asymmetry is the only reason these two functions exist
2647
+ * separately.
2648
+ *
2649
+ * Pass 1 — {status}.tsx → 4xx.tsx (statusFiles)
2650
+ * Pass 2 — not-found / forbidden / unauthorized (legacyStatusFiles)
2651
+ * Pass 3 — error.tsx (error)
2652
+ */
2653
+ function resolve4xx(status, segments) {
2654
+ const statusStr = String(status);
2655
+ for (let i = segments.length - 1; i >= 0; i--) {
2656
+ const r = lookupInGroup(segments[i].statusFiles, statusStr, "4xx", i, status);
2657
+ if (r) return r;
2658
+ }
2659
+ for (let i = segments.length - 1; i >= 0; i--) {
2660
+ const r = lookupLegacy(segments[i].legacyStatusFiles, status, i);
2661
+ if (r) return r;
2662
+ }
2663
+ for (let i = segments.length - 1; i >= 0; i--) {
2664
+ const errorFile = segments[i].error;
2665
+ if (errorFile) return {
2666
+ file: errorFile,
2667
+ status,
2668
+ kind: "error",
2669
+ segmentIndex: i
2670
+ };
2671
+ }
2672
+ return null;
2673
+ }
2674
+ /**
2675
+ * 5xx component fallback chain — single pass, per-segment leaf→root.
2676
+ *
2677
+ * At each segment: {status}.tsx → 5xx.tsx → error.tsx. A leaf's
2678
+ * `error.tsx` therefore beats a root's `5xx.tsx`, which is the
2679
+ * intentional inverse of the 4xx chain.
2680
+ */
2681
+ function resolve5xx(status, segments) {
2682
+ const statusStr = String(status);
2683
+ for (let i = segments.length - 1; i >= 0; i--) {
2684
+ const segment = segments[i];
2685
+ const r = lookupInGroup(segment.statusFiles, statusStr, "5xx", i, status);
2686
+ if (r) return r;
2687
+ if (segment.error) return {
2688
+ file: segment.error,
2689
+ status,
2690
+ kind: "error",
2691
+ segmentIndex: i
2692
+ };
2693
+ }
2694
+ return null;
2695
+ }
2696
+ /**
2697
+ * JSON fallback chain (for both 4xx and 5xx) — single pass leaf→root.
2698
+ *
2699
+ * At each segment: {status}.json → {category}.json. No legacy compat,
2700
+ * no error.tsx — the JSON chain terminates at the category catch-all
2701
+ * and the caller falls back to a bare-JSON framework default.
2702
+ */
2703
+ function resolveJson(status, segments) {
2704
+ const statusStr = String(status);
2705
+ const categoryKey = status >= 500 ? "5xx" : "4xx";
2706
+ for (let i = segments.length - 1; i >= 0; i--) {
2707
+ const r = lookupInGroup(segments[i].jsonStatusFiles, statusStr, categoryKey, i, status);
2708
+ if (r) return r;
2709
+ }
2710
+ return null;
2711
+ }
2712
+ /**
2713
+ * Resolve the denial file for a parallel route slot.
2714
+ *
2715
+ * Slot denial is graceful degradation — no HTTP status on the wire.
2716
+ * Fallback chain: denied.tsx → default.tsx → null.
2717
+ *
2718
+ * @param slotNode - The segment node for the slot (segmentType === 'slot').
2719
+ */
2720
+ function resolveSlotDenied(slotNode) {
2721
+ const slotName = slotNode.segmentName.replace(/^@/, "");
2722
+ if (slotNode.denied) return {
2723
+ file: slotNode.denied,
2724
+ slotName,
2725
+ kind: "denied"
2726
+ };
2727
+ if (slotNode.default) return {
2728
+ file: slotNode.default,
2729
+ slotName,
2730
+ kind: "default"
2731
+ };
2732
+ return null;
2733
+ }
2734
+ //#endregion
2735
+ //#region src/server/flush.ts
2736
+ /**
2737
+ * Flush controller for timber.js rendering.
2738
+ *
2739
+ * Holds the response until `onShellReady` fires, then commits the HTTP status
2740
+ * code and flushes the shell. Render-phase signals (deny, redirect, unhandled
2741
+ * throws) caught before flush produce correct HTTP status codes.
2742
+ *
2743
+ * See design/02-rendering-pipeline.md §"The Flush Point" and §"The Hold Window"
2744
+ */
2745
+ /**
2746
+ * Execute a render and hold the response until the shell is ready.
2747
+ *
2748
+ * The flush controller:
2749
+ * 1. Calls the render function to start renderToReadableStream
2750
+ * 2. Waits for shellReady (onShellReady)
2751
+ * 3. If a render-phase signal was thrown (deny, redirect, error), produces
2752
+ * the correct HTTP status code
2753
+ * 4. If the shell rendered successfully, commits the status and streams
2754
+ *
2755
+ * Render-phase signals caught before flush:
2756
+ * - `DenySignal` → HTTP 4xx with appropriate status code
2757
+ * - `RedirectSignal` → HTTP 3xx with Location header
2758
+ * - `RenderError` → HTTP status from error (default 500)
2759
+ * - Unhandled error → HTTP 500
2760
+ *
2761
+ * @param renderFn - Function that starts the React render.
2762
+ * @param options - Flush configuration.
2763
+ * @returns The committed HTTP Response.
2764
+ */
2765
+ async function flushResponse(renderFn, options = {}) {
2766
+ const { responseHeaders = new Headers(), defaultStatus = 200 } = options;
2767
+ let renderResult;
2768
+ try {
2769
+ renderResult = await renderFn();
2770
+ } catch (error) {
2771
+ return handleSignal(error, responseHeaders);
2772
+ }
2773
+ try {
2774
+ await renderResult.shellReady;
2775
+ } catch (error) {
2776
+ return handleSignal(error, responseHeaders);
2777
+ }
2778
+ responseHeaders.set("Content-Type", "text/html; charset=utf-8");
2779
+ return {
2780
+ response: new Response(renderResult.stream, {
2781
+ status: defaultStatus,
2782
+ headers: responseHeaders
2783
+ }),
2784
+ status: defaultStatus,
2785
+ isRedirect: false,
2786
+ isDenial: false
2787
+ };
2788
+ }
2789
+ /**
2790
+ * Handle a render-phase signal and produce the correct HTTP response.
2791
+ */
2792
+ function handleSignal(error, responseHeaders) {
2793
+ if (error instanceof RedirectSignal) {
2794
+ responseHeaders.set("Location", error.location);
2795
+ return {
2796
+ response: new Response(null, {
2797
+ status: error.status,
2798
+ headers: responseHeaders
2799
+ }),
2800
+ status: error.status,
2801
+ isRedirect: true,
2802
+ isDenial: false
2803
+ };
2804
+ }
2805
+ if (error instanceof DenySignal) return {
2806
+ response: new Response(null, {
2807
+ status: error.status,
2808
+ headers: responseHeaders
2809
+ }),
2810
+ status: error.status,
2811
+ isRedirect: false,
2812
+ isDenial: true
2813
+ };
2814
+ if (error instanceof RenderError) return {
2815
+ response: new Response(null, {
2816
+ status: error.status,
2817
+ headers: responseHeaders
2818
+ }),
2819
+ status: error.status,
2820
+ isRedirect: false,
2821
+ isDenial: false
2822
+ };
2823
+ logRenderError({
2824
+ method: "",
2825
+ path: "",
2826
+ error
2827
+ });
2828
+ return {
2829
+ response: new Response(null, {
2830
+ status: 500,
2831
+ headers: responseHeaders
2832
+ }),
2833
+ status: 500,
2834
+ isRedirect: false,
2835
+ isDenial: false
2836
+ };
2837
+ }
2838
+ //#endregion
2839
+ //#region src/server/csrf.ts
2840
+ /** HTTP methods that are considered safe (no mutation). */
2841
+ var SAFE_METHODS = new Set([
2842
+ "GET",
2843
+ "HEAD",
2844
+ "OPTIONS"
2845
+ ]);
2846
+ /**
2847
+ * Validate the Origin header against the request's Host.
2848
+ *
2849
+ * For mutation methods (POST, PUT, PATCH, DELETE):
2850
+ * - If `csrf: false`, skip validation.
2851
+ * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
2852
+ * - Otherwise, Origin's host must match the request's Host header.
2853
+ *
2854
+ * Safe methods (GET, HEAD, OPTIONS) always pass.
2855
+ */
2856
+ function validateCsrf(req, config) {
2857
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
2858
+ if (config.csrf === false) return { ok: true };
2859
+ const origin = req.headers.get("Origin");
2860
+ if (!origin) return {
2861
+ ok: false,
2862
+ status: 403
2863
+ };
2864
+ if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
2865
+ ok: false,
2866
+ status: 403
2867
+ };
2868
+ const host = req.headers.get("Host");
2869
+ if (!host) return {
2870
+ ok: false,
2871
+ status: 403
2872
+ };
2873
+ let originHost;
2874
+ try {
2875
+ originHost = new URL(origin).host;
2876
+ } catch {
2877
+ return {
2878
+ ok: false,
2879
+ status: 403
2880
+ };
2881
+ }
2882
+ return originHost === host ? { ok: true } : {
2883
+ ok: false,
2884
+ status: 403
2885
+ };
2886
+ }
2887
+ //#endregion
2888
+ //#region src/server/body-limits.ts
2889
+ var KB = 1024;
2890
+ var MB = 1024 * KB;
2891
+ var GB = 1024 * MB;
2892
+ var DEFAULT_LIMITS = {
2893
+ actionBodySize: 1 * MB,
2894
+ uploadBodySize: 10 * MB,
2895
+ maxFields: 100
2896
+ };
2897
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2898
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2899
+ function parseBodySize(size) {
2900
+ const match = SIZE_PATTERN.exec(size.trim());
2901
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2902
+ const value = Number.parseFloat(match[1]);
2903
+ const unit = (match[2] ?? "").toLowerCase();
2904
+ switch (unit) {
2905
+ case "kb": return Math.floor(value * KB);
2906
+ case "mb": return Math.floor(value * MB);
2907
+ case "gb": return Math.floor(value * GB);
2908
+ case "": return Math.floor(value);
2909
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2910
+ }
2911
+ }
2912
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2913
+ function enforceBodyLimits(req, kind, config) {
2914
+ const contentLength = req.headers.get("Content-Length");
2915
+ if (!contentLength) return {
2916
+ ok: false,
2917
+ status: 411
2918
+ };
2919
+ const bodySize = Number.parseInt(contentLength, 10);
2920
+ if (Number.isNaN(bodySize)) return {
2921
+ ok: false,
2922
+ status: 411
2923
+ };
2924
+ return bodySize <= resolveLimit(kind, config) ? { ok: true } : {
2925
+ ok: false,
2926
+ status: 413
2927
+ };
2928
+ }
2929
+ /**
2930
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2931
+ */
2932
+ function resolveLimit(kind, config) {
2933
+ const userLimits = config.limits;
2934
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2935
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2936
+ }
2937
+ //#endregion
2938
+ //#region src/server/route-handler.ts
2939
+ /** All recognized HTTP method export names. */
2940
+ var HTTP_METHODS = [
2941
+ "GET",
2942
+ "POST",
2943
+ "PUT",
2944
+ "PATCH",
2945
+ "DELETE",
2946
+ "HEAD",
2947
+ "OPTIONS"
2948
+ ];
2949
+ /**
2950
+ * Resolve the full list of allowed methods for a route module.
2951
+ *
2952
+ * Includes:
2953
+ * - All explicitly exported methods
2954
+ * - HEAD (implicit when GET is exported)
2955
+ * - OPTIONS (always implicit)
2956
+ */
2957
+ function resolveAllowedMethods(mod) {
2958
+ const methods = [];
2959
+ for (const method of HTTP_METHODS) {
2960
+ if (method === "HEAD" || method === "OPTIONS") continue;
2961
+ if (mod[method]) methods.push(method);
2962
+ }
2963
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
2964
+ else if (mod.HEAD) methods.push("HEAD");
2965
+ if (!mod.OPTIONS) methods.push("OPTIONS");
2966
+ else methods.push("OPTIONS");
2967
+ return methods;
2968
+ }
2969
+ /**
2970
+ * Handle an incoming request against a route.ts module.
2971
+ *
2972
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
2973
+ * and merges response headers from ctx.headers.
2974
+ */
2975
+ async function handleRouteRequest(mod, ctx) {
2976
+ const method = ctx.req.method.toUpperCase();
2977
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
2978
+ if (method === "OPTIONS") {
2979
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
2980
+ return new Response(null, {
2981
+ status: 204,
2982
+ headers: { Allow: allowHeader }
2983
+ });
2984
+ }
2985
+ if (method === "HEAD") {
2986
+ if (mod.HEAD) return runHandler(mod.HEAD, ctx);
2987
+ if (mod.GET) {
2988
+ const res = await runHandler(mod.GET, ctx);
2989
+ return new Response(null, {
2990
+ status: res.status,
2991
+ headers: res.headers
2992
+ });
2993
+ }
2994
+ }
2995
+ const handler = mod[method];
2996
+ if (!handler) return new Response(null, {
2997
+ status: 405,
2998
+ headers: { Allow: allowHeader }
2999
+ });
3000
+ return runHandler(handler, ctx);
3001
+ }
3002
+ /**
3003
+ * Run a handler, merge ctx.headers into the response, and catch errors.
3004
+ */
3005
+ async function runHandler(handler, ctx) {
3006
+ try {
3007
+ return mergeResponseHeaders(await handler(ctx), ctx.headers);
3008
+ } catch (error) {
3009
+ logRouteError({
3010
+ method: ctx.req.method,
3011
+ path: new URL(ctx.req.url).pathname,
3012
+ error
3013
+ });
3014
+ return new Response(null, { status: 500 });
3015
+ }
3016
+ }
3017
+ /**
3018
+ * Merge response headers from ctx.headers into the handler's response.
3019
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
3020
+ * Handler-set headers take precedence over ctx.headers.
3021
+ */
3022
+ function mergeResponseHeaders(res, ctxHeaders) {
3023
+ let hasCtxHeaders = false;
3024
+ ctxHeaders.forEach(() => {
3025
+ hasCtxHeaders = true;
3026
+ });
3027
+ if (!hasCtxHeaders) return res;
3028
+ const merged = new Headers();
3029
+ ctxHeaders.forEach((value, key) => {
3030
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
3031
+ else merged.set(key, value);
3032
+ });
3033
+ const resCookies = res.headers.getSetCookie();
3034
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
3035
+ res.headers.forEach((value, key) => {
3036
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
3037
+ });
3038
+ return new Response(res.body, {
3039
+ status: res.status,
3040
+ statusText: res.statusText,
3041
+ headers: merged
3042
+ });
3043
+ }
3044
+ //#endregion
3045
+ //#region src/server/render-timeout.ts
3046
+ /**
3047
+ * Render timeout utilities for SSR streaming pipeline.
3048
+ *
3049
+ * Provides a RenderTimeoutError class and a helper to create
3050
+ * timeout-guarded AbortSignals. Used to defend against hung RSC
3051
+ * streams and infinite SSR renders.
3052
+ *
3053
+ * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
3054
+ */
3055
+ /**
3056
+ * Error thrown when an SSR render or RSC stream read exceeds the
3057
+ * configured timeout. Callers can check `instanceof RenderTimeoutError`
3058
+ * to distinguish timeout from other errors and return a 504 or close
3059
+ * the connection cleanly.
3060
+ */
3061
+ var RenderTimeoutError = class extends Error {
3062
+ timeoutMs;
3063
+ constructor(timeoutMs, context) {
3064
+ const message = context ? `Render timeout after ${timeoutMs}ms: ${context}` : `Render timeout after ${timeoutMs}ms`;
3065
+ super(message);
3066
+ this.name = "RenderTimeoutError";
3067
+ this.timeoutMs = timeoutMs;
3068
+ }
3069
+ };
3070
+ //#endregion
3071
+ export { AccessGate, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RenderError, RenderTimeoutError, SlotAccessGate, WarningId, buildElementTree, buildNoJsResponse, callOnRequestError, canonicalize, classifyMetadataRoute, coerce, collectEarlyHintHeaders, createPipeline, enforceBodyLimits, executeAction, flushResponse, formatLinkHeader, generateTraceId, getCookie, getHeader, getLogger, getMetadataRouteAutoLink, getMetadataRouteServePath, getSearchParams, getSegmentParams, getSetCookieHeaders, handleRouteRequest, hasOnRequestError, isRscActionRequest, 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, setSegmentParams, setViteServer, validateCsrf, warnDenyInSuspense, warnRedirectInAccess, warnRedirectInSuspense, warnSlowSlotWithoutSuspense, warnStaticRequestApi, warnSuspenseWrappingChildren };
3072
+
3073
+ //# sourceMappingURL=internal.js.map