@timber-js/app 0.2.0-alpha.14 → 0.2.0-alpha.141

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 (801) hide show
  1. package/dist/_chunks/actions-DzFMnUAR.js +1147 -0
  2. package/dist/_chunks/actions-DzFMnUAR.js.map +1 -0
  3. package/dist/_chunks/build-output-helper-B20ZuTSA.js +102 -0
  4. package/dist/_chunks/build-output-helper-B20ZuTSA.js.map +1 -0
  5. package/dist/_chunks/cli-schema-sync-D2IpXicg.js +785 -0
  6. package/dist/_chunks/cli-schema-sync-D2IpXicg.js.map +1 -0
  7. package/dist/_chunks/cli-schema-sync-DH-M8Poy.js +2 -0
  8. package/dist/_chunks/codec-registry-oOUxugz3.js +21 -0
  9. package/dist/_chunks/codec-registry-oOUxugz3.js.map +1 -0
  10. package/dist/_chunks/define-C3RvHQPK.js +195 -0
  11. package/dist/_chunks/define-C3RvHQPK.js.map +1 -0
  12. package/dist/_chunks/define-DMVhsipD.js +112 -0
  13. package/dist/_chunks/define-DMVhsipD.js.map +1 -0
  14. package/dist/_chunks/fast-hash-D6hIVt1Y.js +36 -0
  15. package/dist/_chunks/fast-hash-D6hIVt1Y.js.map +1 -0
  16. package/dist/_chunks/format-CfwjgPz9.js +14 -0
  17. package/dist/_chunks/format-CfwjgPz9.js.map +1 -0
  18. package/dist/_chunks/handler-store-DjISKYEB.js +54 -0
  19. package/dist/_chunks/handler-store-DjISKYEB.js.map +1 -0
  20. package/dist/_chunks/href-validation-EZktELp8.js +124 -0
  21. package/dist/_chunks/href-validation-EZktELp8.js.map +1 -0
  22. package/dist/_chunks/logger-Dt-jQaBO.js +291 -0
  23. package/dist/_chunks/logger-Dt-jQaBO.js.map +1 -0
  24. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → metadata-routes-BjepjefT.js} +32 -19
  25. package/dist/_chunks/metadata-routes-BjepjefT.js.map +1 -0
  26. package/dist/_chunks/navigation-root-DLc4s4ZC.js +103 -0
  27. package/dist/_chunks/navigation-root-DLc4s4ZC.js.map +1 -0
  28. package/dist/_chunks/registry-DbJPKoBp.js +20 -0
  29. package/dist/_chunks/registry-DbJPKoBp.js.map +1 -0
  30. package/dist/_chunks/resolve-schema-Dj8tQloi.js +77 -0
  31. package/dist/_chunks/resolve-schema-Dj8tQloi.js.map +1 -0
  32. package/dist/_chunks/router-ref-CtmF-aPv.js +28 -0
  33. package/dist/_chunks/router-ref-CtmF-aPv.js.map +1 -0
  34. package/dist/_chunks/schema-bridge-DK_89h8O.js +86 -0
  35. package/dist/_chunks/schema-bridge-DK_89h8O.js.map +1 -0
  36. package/dist/_chunks/segment-classify-CDDRVKs7.js +137 -0
  37. package/dist/_chunks/segment-classify-CDDRVKs7.js.map +1 -0
  38. package/dist/_chunks/segment-context-ZDnXDkbz.js +34 -0
  39. package/dist/_chunks/segment-context-ZDnXDkbz.js.map +1 -0
  40. package/dist/_chunks/{ssr-data-MjmprTmO.js → ssr-data-BOWsq18U.js} +1 -1
  41. package/dist/_chunks/ssr-data-BOWsq18U.js.map +1 -0
  42. package/dist/_chunks/tracing-M_zKubhk.js +358 -0
  43. package/dist/_chunks/tracing-M_zKubhk.js.map +1 -0
  44. package/dist/_chunks/{use-query-states-D5KaffOK.js → use-query-states-CbeQmext.js} +7 -20
  45. package/dist/_chunks/use-query-states-CbeQmext.js.map +1 -0
  46. package/dist/_chunks/use-segment-params-D1CzlgBo.js +151 -0
  47. package/dist/_chunks/use-segment-params-D1CzlgBo.js.map +1 -0
  48. package/dist/_chunks/validation-taUkvA4Q.js +113 -0
  49. package/dist/_chunks/validation-taUkvA4Q.js.map +1 -0
  50. package/dist/_chunks/walkers-7FBPM-hX.js +724 -0
  51. package/dist/_chunks/walkers-7FBPM-hX.js.map +1 -0
  52. package/dist/_chunks/{format-RyoGQL74.js → warnings-CNPXaypM.js} +6 -45
  53. package/dist/_chunks/warnings-CNPXaypM.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 +154 -48
  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 +165 -117
  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 +183 -1134
  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 +925 -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 +69 -60
  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-pathname.d.ts.map +1 -1
  171. package/dist/client/use-pending-navigation.d.ts +23 -0
  172. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  173. package/dist/client/use-query-states.d.ts +1 -1
  174. package/dist/client/use-query-states.d.ts.map +1 -1
  175. package/dist/client/use-router.d.ts +1 -1
  176. package/dist/client/use-router.d.ts.map +1 -1
  177. package/dist/client/use-search-params.d.ts +7 -5
  178. package/dist/client/use-search-params.d.ts.map +1 -1
  179. package/dist/client/{use-params.d.ts → use-segment-params.d.ts} +8 -6
  180. package/dist/client/use-segment-params.d.ts.map +1 -0
  181. package/dist/codec.d.ts +69 -0
  182. package/dist/codec.d.ts.map +1 -0
  183. package/dist/codec.js +75 -0
  184. package/dist/codec.js.map +1 -0
  185. package/dist/config-types.d.ts +294 -0
  186. package/dist/config-types.d.ts.map +1 -0
  187. package/dist/config-validation.d.ts +51 -0
  188. package/dist/config-validation.d.ts.map +1 -0
  189. package/dist/content/index.d.ts +1 -10
  190. package/dist/content/index.d.ts.map +1 -1
  191. package/dist/content/index.js +0 -2
  192. package/dist/cookies/define-cookie.d.ts +58 -25
  193. package/dist/cookies/define-cookie.d.ts.map +1 -1
  194. package/dist/cookies/index.d.ts +2 -1
  195. package/dist/cookies/index.d.ts.map +1 -1
  196. package/dist/cookies/index.js +251 -36
  197. package/dist/cookies/index.js.map +1 -1
  198. package/dist/cookies/json-cookie.d.ts +64 -0
  199. package/dist/cookies/json-cookie.d.ts.map +1 -0
  200. package/dist/cookies/validation.d.ts +34 -0
  201. package/dist/cookies/validation.d.ts.map +1 -0
  202. package/dist/dev-tools/404-page.d.ts +46 -0
  203. package/dist/dev-tools/404-page.d.ts.map +1 -0
  204. package/dist/dev-tools/browser-logs.d.ts +84 -0
  205. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  206. package/dist/dev-tools/error-page.d.ts +58 -0
  207. package/dist/dev-tools/error-page.d.ts.map +1 -0
  208. package/dist/dev-tools/holding-server.d.ts +54 -0
  209. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  210. package/dist/dev-tools/index.d.ts +31 -0
  211. package/dist/dev-tools/index.d.ts.map +1 -0
  212. package/dist/{server/dev-span-processor.d.ts → dev-tools/instrumentation.d.ts} +26 -6
  213. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  214. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  215. package/dist/dev-tools/logger.d.ts.map +1 -0
  216. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +2 -2
  217. package/dist/dev-tools/logs.d.ts.map +1 -0
  218. package/dist/dev-tools/overlay.d.ts +91 -0
  219. package/dist/dev-tools/overlay.d.ts.map +1 -0
  220. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  221. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  222. package/dist/dev-tools/terminal.d.ts +28 -0
  223. package/dist/dev-tools/terminal.d.ts.map +1 -0
  224. package/dist/{server/dev-warnings.d.ts → dev-tools/warnings.d.ts} +2 -22
  225. package/dist/dev-tools/warnings.d.ts.map +1 -0
  226. package/dist/fonts/ast.d.ts +98 -6
  227. package/dist/fonts/ast.d.ts.map +1 -1
  228. package/dist/fonts/bundle.d.ts +48 -0
  229. package/dist/fonts/bundle.d.ts.map +1 -0
  230. package/dist/fonts/dev-middleware.d.ts +22 -0
  231. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  232. package/dist/fonts/local.d.ts +1 -1
  233. package/dist/fonts/pipeline.d.ts +172 -0
  234. package/dist/fonts/pipeline.d.ts.map +1 -0
  235. package/dist/fonts/transform.d.ts +78 -0
  236. package/dist/fonts/transform.d.ts.map +1 -0
  237. package/dist/fonts/types.d.ts +47 -1
  238. package/dist/fonts/types.d.ts.map +1 -1
  239. package/dist/fonts/virtual-modules.d.ts +94 -0
  240. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  241. package/dist/index.d.ts +46 -180
  242. package/dist/index.d.ts.map +1 -1
  243. package/dist/index.js +5315 -12687
  244. package/dist/index.js.map +1 -1
  245. package/dist/params/codec-registry.d.ts +26 -0
  246. package/dist/params/codec-registry.d.ts.map +1 -0
  247. package/dist/params/define-schema.d.ts +81 -0
  248. package/dist/params/define-schema.d.ts.map +1 -0
  249. package/dist/params/index.d.ts +5 -0
  250. package/dist/params/index.d.ts.map +1 -0
  251. package/dist/params/index.js +34 -0
  252. package/dist/params/index.js.map +1 -0
  253. package/dist/params/resolve-schema.d.ts +34 -0
  254. package/dist/params/resolve-schema.d.ts.map +1 -0
  255. package/dist/plugin-context.d.ts +114 -0
  256. package/dist/plugin-context.d.ts.map +1 -0
  257. package/dist/plugins/adapter-build.d.ts +20 -1
  258. package/dist/plugins/adapter-build.d.ts.map +1 -1
  259. package/dist/plugins/build-manifest.d.ts +7 -3
  260. package/dist/plugins/build-manifest.d.ts.map +1 -1
  261. package/dist/plugins/build-report.d.ts +9 -7
  262. package/dist/plugins/build-report.d.ts.map +1 -1
  263. package/dist/plugins/cache.d.ts +31 -0
  264. package/dist/plugins/cache.d.ts.map +1 -0
  265. package/dist/plugins/client-chunks.d.ts +39 -0
  266. package/dist/plugins/client-chunks.d.ts.map +1 -0
  267. package/dist/plugins/cloudflare-wasm.d.ts +18 -0
  268. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  269. package/dist/plugins/content.d.ts +1 -1
  270. package/dist/plugins/content.d.ts.map +1 -1
  271. package/dist/plugins/dev-server.d.ts +1 -1
  272. package/dist/plugins/dev-server.d.ts.map +1 -1
  273. package/dist/plugins/entries.d.ts +1 -1
  274. package/dist/plugins/entries.d.ts.map +1 -1
  275. package/dist/plugins/fonts.d.ts +17 -73
  276. package/dist/plugins/fonts.d.ts.map +1 -1
  277. package/dist/plugins/mdx.d.ts +1 -1
  278. package/dist/plugins/mdx.d.ts.map +1 -1
  279. package/dist/plugins/routing.d.ts +1 -1
  280. package/dist/plugins/routing.d.ts.map +1 -1
  281. package/dist/plugins/server-bundle.d.ts.map +1 -1
  282. package/dist/plugins/shims.d.ts +6 -5
  283. package/dist/plugins/shims.d.ts.map +1 -1
  284. package/dist/plugins/static-build.d.ts +5 -26
  285. package/dist/plugins/static-build.d.ts.map +1 -1
  286. package/dist/routing/codegen-shared.d.ts +67 -0
  287. package/dist/routing/codegen-shared.d.ts.map +1 -0
  288. package/dist/routing/codegen-types.d.ts +60 -0
  289. package/dist/routing/codegen-types.d.ts.map +1 -0
  290. package/dist/routing/codegen.d.ts +7 -2
  291. package/dist/routing/codegen.d.ts.map +1 -1
  292. package/dist/routing/convention-lint.d.ts +41 -0
  293. package/dist/routing/convention-lint.d.ts.map +1 -0
  294. package/dist/routing/index.d.ts +7 -1
  295. package/dist/routing/index.d.ts.map +1 -1
  296. package/dist/routing/index.js +4 -2
  297. package/dist/routing/link-codegen.d.ts +90 -0
  298. package/dist/routing/link-codegen.d.ts.map +1 -0
  299. package/dist/routing/scanner.d.ts +1 -10
  300. package/dist/routing/scanner.d.ts.map +1 -1
  301. package/dist/routing/schema-validation.d.ts +35 -0
  302. package/dist/routing/schema-validation.d.ts.map +1 -0
  303. package/dist/routing/segment-classify.d.ts +75 -0
  304. package/dist/routing/segment-classify.d.ts.map +1 -0
  305. package/dist/routing/segment-codegen.d.ts +38 -0
  306. package/dist/routing/segment-codegen.d.ts.map +1 -0
  307. package/dist/routing/types.d.ts +77 -25
  308. package/dist/routing/types.d.ts.map +1 -1
  309. package/dist/routing/walkers.d.ts +51 -0
  310. package/dist/routing/walkers.d.ts.map +1 -0
  311. package/dist/rsc-runtime/rsc.d.ts +1 -1
  312. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  313. package/dist/rsc-runtime/ssr.d.ts +12 -0
  314. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  315. package/dist/schema-bridge.d.ts +76 -0
  316. package/dist/schema-bridge.d.ts.map +1 -0
  317. package/dist/search-params/define.d.ts +157 -0
  318. package/dist/search-params/define.d.ts.map +1 -0
  319. package/dist/search-params/index.d.ts +4 -7
  320. package/dist/search-params/index.d.ts.map +1 -1
  321. package/dist/search-params/index.js +34 -441
  322. package/dist/search-params/index.js.map +1 -1
  323. package/dist/search-params/registry.d.ts +2 -2
  324. package/dist/search-params/registry.d.ts.map +1 -1
  325. package/dist/search-params/wrappers.d.ts +53 -0
  326. package/dist/search-params/wrappers.d.ts.map +1 -0
  327. package/dist/segment-params/define.d.ts +89 -0
  328. package/dist/segment-params/define.d.ts.map +1 -0
  329. package/dist/segment-params/index.d.ts +3 -0
  330. package/dist/segment-params/index.d.ts.map +1 -0
  331. package/dist/segment-params/index.js +2 -0
  332. package/dist/server/access-gate.d.ts +8 -3
  333. package/dist/server/access-gate.d.ts.map +1 -1
  334. package/dist/server/action-client.d.ts +41 -6
  335. package/dist/server/action-client.d.ts.map +1 -1
  336. package/dist/server/action-encryption.d.ts +76 -0
  337. package/dist/server/action-encryption.d.ts.map +1 -0
  338. package/dist/server/action-handler.d.ts +35 -1
  339. package/dist/server/action-handler.d.ts.map +1 -1
  340. package/dist/server/actions.d.ts +6 -14
  341. package/dist/server/actions.d.ts.map +1 -1
  342. package/dist/server/als-registry.d.ts +70 -11
  343. package/dist/server/als-registry.d.ts.map +1 -1
  344. package/dist/server/asset-headers.d.ts +1 -15
  345. package/dist/server/asset-headers.d.ts.map +1 -1
  346. package/dist/server/body-limits.d.ts.map +1 -1
  347. package/dist/server/build-manifest.d.ts +8 -2
  348. package/dist/server/build-manifest.d.ts.map +1 -1
  349. package/dist/server/coalesce-tick.d.ts +40 -0
  350. package/dist/server/coalesce-tick.d.ts.map +1 -0
  351. package/dist/server/cookie-context.d.ts +170 -0
  352. package/dist/server/cookie-context.d.ts.map +1 -0
  353. package/dist/server/cookie-parsing.d.ts +51 -0
  354. package/dist/server/cookie-parsing.d.ts.map +1 -0
  355. package/dist/server/csrf.d.ts +3 -2
  356. package/dist/server/csrf.d.ts.map +1 -1
  357. package/dist/server/default-logger.d.ts +22 -0
  358. package/dist/server/default-logger.d.ts.map +1 -0
  359. package/dist/server/deny-boundary.d.ts +90 -0
  360. package/dist/server/deny-boundary.d.ts.map +1 -0
  361. package/dist/server/deny-renderer.d.ts +1 -1
  362. package/dist/server/deny-renderer.d.ts.map +1 -1
  363. package/dist/server/dev-source-map.d.ts +22 -0
  364. package/dist/server/dev-source-map.d.ts.map +1 -0
  365. package/dist/server/early-hints-sender.d.ts.map +1 -1
  366. package/dist/server/early-hints.d.ts +13 -11
  367. package/dist/server/early-hints.d.ts.map +1 -1
  368. package/dist/server/error-boundary-wrapper.d.ts +7 -1
  369. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  370. package/dist/server/fallback-error.d.ts +12 -7
  371. package/dist/server/fallback-error.d.ts.map +1 -1
  372. package/dist/server/flight-injection-state.d.ts +66 -0
  373. package/dist/server/flight-injection-state.d.ts.map +1 -0
  374. package/dist/server/flight-scripts.d.ts +42 -0
  375. package/dist/server/flight-scripts.d.ts.map +1 -0
  376. package/dist/server/flush.d.ts.map +1 -1
  377. package/dist/server/form-data.d.ts +29 -0
  378. package/dist/server/form-data.d.ts.map +1 -1
  379. package/dist/server/html-injector-core.d.ts +213 -0
  380. package/dist/server/html-injector-core.d.ts.map +1 -0
  381. package/dist/server/html-injectors.d.ts +81 -41
  382. package/dist/server/html-injectors.d.ts.map +1 -1
  383. package/dist/server/index.d.ts +10 -46
  384. package/dist/server/index.d.ts.map +1 -1
  385. package/dist/server/index.js +170 -2911
  386. package/dist/server/index.js.map +1 -1
  387. package/dist/server/internal.d.ts +48 -0
  388. package/dist/server/internal.d.ts.map +1 -0
  389. package/dist/server/internal.js +3126 -0
  390. package/dist/server/internal.js.map +1 -0
  391. package/dist/server/logger.d.ts +39 -7
  392. package/dist/server/logger.d.ts.map +1 -1
  393. package/dist/server/metadata-routes.d.ts +23 -7
  394. package/dist/server/metadata-routes.d.ts.map +1 -1
  395. package/dist/server/middleware-runner.d.ts +36 -4
  396. package/dist/server/middleware-runner.d.ts.map +1 -1
  397. package/dist/server/node-stream-transforms.d.ts +112 -0
  398. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  399. package/dist/server/param-coercion.d.ts +54 -0
  400. package/dist/server/param-coercion.d.ts.map +1 -0
  401. package/dist/server/pipeline-helpers.d.ts +95 -0
  402. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  403. package/dist/server/pipeline-interception.d.ts +1 -1
  404. package/dist/server/pipeline-interception.d.ts.map +1 -1
  405. package/dist/server/pipeline-metadata.d.ts +6 -0
  406. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  407. package/dist/server/pipeline-outcome.d.ts +49 -0
  408. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  409. package/dist/server/pipeline-phases.d.ts +56 -0
  410. package/dist/server/pipeline-phases.d.ts.map +1 -0
  411. package/dist/server/pipeline.d.ts +111 -19
  412. package/dist/server/pipeline.d.ts.map +1 -1
  413. package/dist/server/port-resolution.d.ts +117 -0
  414. package/dist/server/port-resolution.d.ts.map +1 -0
  415. package/dist/server/primitives.d.ts +74 -20
  416. package/dist/server/primitives.d.ts.map +1 -1
  417. package/dist/server/render-timeout.d.ts +51 -0
  418. package/dist/server/render-timeout.d.ts.map +1 -0
  419. package/dist/server/request-context.d.ts +62 -107
  420. package/dist/server/request-context.d.ts.map +1 -1
  421. package/dist/server/route-element-builder.d.ts +28 -2
  422. package/dist/server/route-element-builder.d.ts.map +1 -1
  423. package/dist/server/route-handler.d.ts.map +1 -1
  424. package/dist/server/route-matcher.d.ts +25 -36
  425. package/dist/server/route-matcher.d.ts.map +1 -1
  426. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  427. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  428. package/dist/server/rsc-entry/api-handler.d.ts +12 -3
  429. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  430. package/dist/server/rsc-entry/error-renderer.d.ts +26 -13
  431. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  432. package/dist/server/rsc-entry/helpers.d.ts +50 -6
  433. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  434. package/dist/server/rsc-entry/index.d.ts +19 -8
  435. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  436. package/dist/server/rsc-entry/render-route.d.ts +50 -0
  437. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  438. package/dist/server/rsc-entry/revalidate-renderer.d.ts +108 -0
  439. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  440. package/dist/server/rsc-entry/rsc-payload.d.ts +3 -3
  441. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  442. package/dist/server/rsc-entry/rsc-stream.d.ts +17 -1
  443. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  444. package/dist/server/rsc-entry/ssr-bridge.d.ts +5 -1
  445. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  446. package/dist/server/rsc-entry/ssr-renderer.d.ts +34 -4
  447. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  448. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +119 -0
  449. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
  450. package/dist/server/safe-load.d.ts +46 -0
  451. package/dist/server/safe-load.d.ts.map +1 -0
  452. package/dist/server/sensitive-fields.d.ts +74 -0
  453. package/dist/server/sensitive-fields.d.ts.map +1 -0
  454. package/dist/server/sitemap-generator.d.ts +129 -0
  455. package/dist/server/sitemap-generator.d.ts.map +1 -0
  456. package/dist/server/sitemap-handler.d.ts +22 -0
  457. package/dist/server/sitemap-handler.d.ts.map +1 -0
  458. package/dist/server/slot-resolver.d.ts +1 -1
  459. package/dist/server/slot-resolver.d.ts.map +1 -1
  460. package/dist/server/ssr-bridge-types.d.ts +121 -0
  461. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  462. package/dist/server/ssr-entry.d.ts +2 -43
  463. package/dist/server/ssr-entry.d.ts.map +1 -1
  464. package/dist/server/ssr-render.d.ts +64 -21
  465. package/dist/server/ssr-render.d.ts.map +1 -1
  466. package/dist/server/ssr-wrappers.d.ts +50 -0
  467. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  468. package/dist/server/state-tree-diff.d.ts +12 -5
  469. package/dist/server/state-tree-diff.d.ts.map +1 -1
  470. package/dist/server/status-code-resolver.d.ts +16 -11
  471. package/dist/server/status-code-resolver.d.ts.map +1 -1
  472. package/dist/server/stream-utils.d.ts +36 -0
  473. package/dist/server/stream-utils.d.ts.map +1 -0
  474. package/dist/server/tracing.d.ts +5 -5
  475. package/dist/server/tracing.d.ts.map +1 -1
  476. package/dist/server/tree-builder.d.ts +62 -30
  477. package/dist/server/tree-builder.d.ts.map +1 -1
  478. package/dist/server/tree-match.d.ts +49 -0
  479. package/dist/server/tree-match.d.ts.map +1 -0
  480. package/dist/server/types.d.ts +71 -6
  481. package/dist/server/types.d.ts.map +1 -1
  482. package/dist/server/utils/escape-html.d.ts +14 -0
  483. package/dist/server/utils/escape-html.d.ts.map +1 -0
  484. package/dist/server/version-skew.d.ts +61 -0
  485. package/dist/server/version-skew.d.ts.map +1 -0
  486. package/dist/shared/href-validation.d.ts +38 -0
  487. package/dist/shared/href-validation.d.ts.map +1 -0
  488. package/dist/shared/merge-search-params.d.ts +22 -0
  489. package/dist/shared/merge-search-params.d.ts.map +1 -0
  490. package/dist/shims/font-google.d.ts +1 -1
  491. package/dist/shims/font-google.d.ts.map +1 -1
  492. package/dist/shims/font-google.js +42 -0
  493. package/dist/shims/font-google.js.map +1 -0
  494. package/dist/shims/font-local.d.ts +26 -0
  495. package/dist/shims/font-local.d.ts.map +1 -0
  496. package/dist/shims/font-local.js +20 -0
  497. package/dist/shims/font-local.js.map +1 -0
  498. package/dist/shims/headers.d.ts +2 -1
  499. package/dist/shims/headers.d.ts.map +1 -1
  500. package/dist/shims/image.d.ts +1 -1
  501. package/dist/shims/navigation-client.d.ts +3 -1
  502. package/dist/shims/navigation-client.d.ts.map +1 -1
  503. package/dist/shims/navigation.d.ts +11 -5
  504. package/dist/shims/navigation.d.ts.map +1 -1
  505. package/dist/utils/state-machine.d.ts +80 -0
  506. package/dist/utils/state-machine.d.ts.map +1 -0
  507. package/package.json +63 -22
  508. package/src/adapters/build-output-helper.ts +139 -0
  509. package/src/adapters/cloudflare-dev.ts +177 -0
  510. package/src/adapters/cloudflare-kv-cache.ts +142 -0
  511. package/src/adapters/cloudflare.ts +350 -76
  512. package/src/adapters/compress-module.ts +24 -4
  513. package/src/adapters/nitro.ts +147 -60
  514. package/src/adapters/shared.ts +40 -0
  515. package/src/adapters/wrangler.d.ts +7 -0
  516. package/src/cache/cache-api.ts +39 -0
  517. package/src/cache/handler-store.ts +68 -0
  518. package/src/cache/index.ts +81 -18
  519. package/src/cache/singleflight.ts +62 -4
  520. package/src/cache/sizeof.ts +33 -0
  521. package/src/cache/timber-cache.ts +52 -24
  522. package/src/cli-schema-sync.ts +295 -0
  523. package/src/cli.ts +76 -8
  524. package/src/client/browser-dev.ts +153 -1
  525. package/src/client/browser-entry/action-dispatch.ts +125 -0
  526. package/src/client/browser-entry/hmr.ts +81 -0
  527. package/src/client/browser-entry/hydrate.ts +153 -0
  528. package/src/client/browser-entry/index.ts +151 -0
  529. package/src/client/browser-entry/post-hydration.ts +113 -0
  530. package/src/client/browser-entry/router-init.ts +219 -0
  531. package/src/client/browser-entry/rsc-stream.ts +157 -0
  532. package/src/client/browser-entry/scroll.ts +27 -0
  533. package/src/client/error-boundary.tsx +99 -22
  534. package/src/client/error-reconstituter.tsx +65 -0
  535. package/src/client/form.tsx +31 -32
  536. package/src/client/history.ts +26 -4
  537. package/src/client/index.ts +67 -45
  538. package/src/client/internal.ts +58 -0
  539. package/src/client/link-pending-store.ts +116 -0
  540. package/src/client/link.tsx +343 -150
  541. package/src/client/nav-link-store.ts +37 -0
  542. package/src/client/navigation-api-types.ts +112 -0
  543. package/src/client/navigation-api.ts +338 -0
  544. package/src/client/navigation-context.ts +35 -7
  545. package/src/client/navigation-root.tsx +347 -0
  546. package/src/client/nuqs-adapter.tsx +16 -3
  547. package/src/client/router-ref.ts +1 -1
  548. package/src/client/router.ts +418 -128
  549. package/src/client/rsc-fetch.ts +208 -10
  550. package/src/client/segment-cache.ts +6 -3
  551. package/src/client/segment-outlet.tsx +77 -0
  552. package/src/client/segment-update-context.ts +42 -0
  553. package/src/client/shallow-url.ts +22 -0
  554. package/src/client/ssr-data.ts +13 -5
  555. package/src/client/stale-reload.ts +72 -3
  556. package/src/client/state.ts +2 -2
  557. package/src/client/top-loader.tsx +11 -9
  558. package/src/client/use-cookie.ts +31 -2
  559. package/src/client/use-link-status.ts +7 -7
  560. package/src/client/use-pathname.ts +1 -0
  561. package/src/client/use-pending-navigation.ts +40 -0
  562. package/src/client/use-query-states.ts +9 -3
  563. package/src/client/use-router.ts +4 -1
  564. package/src/client/use-search-params.ts +26 -44
  565. package/src/client/{use-params.ts → use-segment-params.ts} +9 -6
  566. package/src/codec.ts +147 -0
  567. package/src/config-types.ts +292 -0
  568. package/src/config-validation.ts +303 -0
  569. package/src/content/index.ts +5 -13
  570. package/src/cookies/define-cookie.ts +233 -53
  571. package/src/cookies/index.ts +12 -1
  572. package/src/cookies/json-cookie.ts +105 -0
  573. package/src/cookies/validation.ts +192 -0
  574. package/src/dev-tools/404-page.ts +387 -0
  575. package/src/dev-tools/browser-logs.ts +291 -0
  576. package/src/dev-tools/error-page.ts +507 -0
  577. package/src/dev-tools/holding-server.ts +187 -0
  578. package/src/dev-tools/index.ts +90 -0
  579. package/src/dev-tools/instrumentation.ts +176 -0
  580. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +9 -5
  581. package/src/dev-tools/overlay.ts +469 -0
  582. package/src/dev-tools/stack-classifier.ts +75 -0
  583. package/src/dev-tools/terminal.ts +183 -0
  584. package/src/{server/dev-warnings.ts → dev-tools/warnings.ts} +5 -50
  585. package/src/fonts/ast.ts +525 -16
  586. package/src/fonts/bundle.ts +131 -0
  587. package/src/fonts/dev-middleware.ts +74 -0
  588. package/src/fonts/local.ts +3 -3
  589. package/src/fonts/pipeline.ts +337 -0
  590. package/src/fonts/transform.ts +317 -0
  591. package/src/fonts/types.ts +52 -1
  592. package/src/fonts/virtual-modules.ts +235 -0
  593. package/src/index.ts +415 -345
  594. package/src/params/codec-registry.ts +34 -0
  595. package/src/params/define-schema.ts +115 -0
  596. package/src/params/index.ts +17 -0
  597. package/src/params/resolve-schema.ts +116 -0
  598. package/src/plugin-context.ts +247 -0
  599. package/src/plugins/adapter-build.ts +98 -4
  600. package/src/plugins/build-manifest.ts +168 -23
  601. package/src/plugins/build-report.ts +16 -25
  602. package/src/plugins/cache.ts +180 -0
  603. package/src/plugins/client-chunks.ts +113 -0
  604. package/src/plugins/cloudflare-wasm.ts +103 -0
  605. package/src/plugins/content.ts +1 -1
  606. package/src/plugins/dev-server.ts +179 -37
  607. package/src/plugins/entries.ts +110 -8
  608. package/src/plugins/fonts.ts +167 -655
  609. package/src/plugins/mdx.ts +47 -10
  610. package/src/plugins/routing.ts +386 -47
  611. package/src/plugins/server-bundle.ts +59 -3
  612. package/src/plugins/shims.ts +136 -35
  613. package/src/plugins/static-build.ts +15 -89
  614. package/src/routing/codegen-shared.ts +115 -0
  615. package/src/routing/codegen-types.ts +61 -0
  616. package/src/routing/codegen.ts +321 -177
  617. package/src/routing/convention-lint.ts +357 -0
  618. package/src/routing/index.ts +10 -1
  619. package/src/routing/interception.ts +1 -1
  620. package/src/routing/link-codegen.ts +310 -0
  621. package/src/routing/scanner.ts +165 -110
  622. package/src/routing/schema-validation.ts +149 -0
  623. package/src/routing/segment-classify.ts +188 -0
  624. package/src/routing/segment-codegen.ts +98 -0
  625. package/src/routing/types.ts +78 -25
  626. package/src/routing/walkers.ts +90 -0
  627. package/src/rsc-runtime/rsc.ts +2 -0
  628. package/src/rsc-runtime/ssr.ts +50 -0
  629. package/src/rsc-runtime/vendor-types.d.ts +7 -0
  630. package/src/{search-params/codecs.ts → schema-bridge.ts} +60 -22
  631. package/src/search-params/define.ts +538 -0
  632. package/src/search-params/index.ts +14 -20
  633. package/src/search-params/registry.ts +2 -2
  634. package/src/search-params/wrappers.ts +92 -0
  635. package/src/segment-params/define.ts +309 -0
  636. package/src/segment-params/index.ts +9 -0
  637. package/src/server/access-gate.tsx +76 -34
  638. package/src/server/action-client.ts +119 -28
  639. package/src/server/action-encryption.ts +144 -0
  640. package/src/server/action-handler.ts +112 -14
  641. package/src/server/actions.ts +34 -26
  642. package/src/server/als-registry.ts +108 -20
  643. package/src/server/asset-headers.ts +8 -34
  644. package/src/server/body-limits.ts +10 -2
  645. package/src/server/build-manifest.ts +17 -4
  646. package/src/server/coalesce-tick.ts +75 -0
  647. package/src/server/compress.ts +25 -7
  648. package/src/server/cookie-context.ts +473 -0
  649. package/src/server/cookie-parsing.ts +135 -0
  650. package/src/server/csrf.ts +39 -6
  651. package/src/server/default-logger.ts +99 -0
  652. package/src/server/deny-boundary.ts +218 -0
  653. package/src/server/deny-renderer.ts +32 -52
  654. package/src/server/dev-source-map.ts +31 -0
  655. package/src/server/early-hints-sender.ts +3 -2
  656. package/src/server/early-hints.ts +35 -27
  657. package/src/server/error-boundary-wrapper.ts +74 -22
  658. package/src/server/fallback-error.ts +74 -102
  659. package/src/server/flight-injection-state.ts +113 -0
  660. package/src/server/flight-scripts.ts +62 -0
  661. package/src/server/flush.ts +2 -1
  662. package/src/server/form-data.ts +101 -5
  663. package/src/server/html-injector-core.ts +418 -0
  664. package/src/server/html-injectors.ts +238 -223
  665. package/src/server/index.ts +29 -183
  666. package/src/server/internal.ts +182 -0
  667. package/src/server/logger.ts +67 -36
  668. package/src/server/metadata-routes.ts +44 -19
  669. package/src/server/middleware-runner.ts +75 -4
  670. package/src/server/node-stream-transforms.ts +361 -0
  671. package/src/server/param-coercion.ts +206 -0
  672. package/src/server/pipeline-helpers.ts +204 -0
  673. package/src/server/pipeline-interception.ts +32 -18
  674. package/src/server/pipeline-metadata.ts +13 -0
  675. package/src/server/pipeline-outcome.ts +197 -0
  676. package/src/server/pipeline-phases.ts +527 -0
  677. package/src/server/pipeline.ts +201 -382
  678. package/src/server/port-resolution.ts +215 -0
  679. package/src/server/primitives.ts +130 -46
  680. package/src/server/render-timeout.ts +108 -0
  681. package/src/server/request-context.ts +168 -337
  682. package/src/server/route-element-builder.ts +437 -208
  683. package/src/server/route-handler.ts +31 -4
  684. package/src/server/route-matcher.ts +128 -277
  685. package/src/server/rsc-entry/action-middleware-runner.ts +167 -0
  686. package/src/server/rsc-entry/api-handler.ts +69 -32
  687. package/src/server/rsc-entry/error-renderer.ts +316 -89
  688. package/src/server/rsc-entry/helpers.ts +155 -26
  689. package/src/server/rsc-entry/index.ts +283 -329
  690. package/src/server/rsc-entry/render-route.ts +313 -0
  691. package/src/server/rsc-entry/revalidate-renderer.ts +344 -0
  692. package/src/server/rsc-entry/rsc-payload.ts +65 -22
  693. package/src/server/rsc-entry/rsc-stream.ts +85 -13
  694. package/src/server/rsc-entry/ssr-bridge.ts +18 -5
  695. package/src/server/rsc-entry/ssr-renderer.ts +271 -41
  696. package/src/server/rsc-entry/wrap-action-dispatch.ts +449 -0
  697. package/src/server/safe-load.ts +60 -0
  698. package/src/server/sensitive-fields.ts +230 -0
  699. package/src/server/sitemap-generator.ts +338 -0
  700. package/src/server/sitemap-handler.ts +148 -0
  701. package/src/server/slot-resolver.ts +234 -246
  702. package/src/server/ssr-bridge-types.ts +124 -0
  703. package/src/server/ssr-entry.ts +217 -78
  704. package/src/server/ssr-render.ts +344 -71
  705. package/src/server/ssr-wrappers.tsx +141 -0
  706. package/src/server/state-tree-diff.ts +30 -23
  707. package/src/server/status-code-resolver.ts +112 -128
  708. package/src/server/stream-utils.ts +213 -0
  709. package/src/server/tracing.ts +21 -10
  710. package/src/server/tree-builder.ts +204 -90
  711. package/src/server/tree-match.ts +210 -0
  712. package/src/server/types.ts +78 -9
  713. package/src/server/utils/escape-html.ts +20 -0
  714. package/src/server/version-skew.ts +104 -0
  715. package/src/shared/href-validation.ts +127 -0
  716. package/src/shared/merge-search-params.ts +55 -0
  717. package/src/shims/font-google.ts +1 -1
  718. package/src/shims/font-local.ts +34 -0
  719. package/src/shims/headers.ts +5 -1
  720. package/src/shims/navigation-client.ts +4 -3
  721. package/src/shims/navigation.ts +14 -7
  722. package/src/utils/state-machine.ts +111 -0
  723. package/LICENSE +0 -8
  724. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  725. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  726. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  727. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  728. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  729. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  730. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  731. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  732. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  733. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  734. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  735. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  736. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  737. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  738. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  739. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  740. package/dist/cache/register-cached-function.d.ts +0 -17
  741. package/dist/cache/register-cached-function.d.ts.map +0 -1
  742. package/dist/client/browser-entry.d.ts +0 -21
  743. package/dist/client/browser-entry.d.ts.map +0 -1
  744. package/dist/client/link-status-provider.d.ts +0 -11
  745. package/dist/client/link-status-provider.d.ts.map +0 -1
  746. package/dist/client/segment-merger.d.ts +0 -119
  747. package/dist/client/segment-merger.d.ts.map +0 -1
  748. package/dist/client/transition-root.d.ts.map +0 -1
  749. package/dist/client/use-navigation-pending.d.ts +0 -26
  750. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  751. package/dist/client/use-params.d.ts.map +0 -1
  752. package/dist/plugins/cache-transform.d.ts +0 -36
  753. package/dist/plugins/cache-transform.d.ts.map +0 -1
  754. package/dist/plugins/dev-error-overlay.d.ts +0 -60
  755. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  756. package/dist/plugins/dev-logs.d.ts.map +0 -1
  757. package/dist/plugins/dynamic-transform.d.ts +0 -72
  758. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  759. package/dist/plugins/server-action-exports.d.ts +0 -26
  760. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  761. package/dist/routing/status-file-lint.d.ts +0 -33
  762. package/dist/routing/status-file-lint.d.ts.map +0 -1
  763. package/dist/search-params/analyze.d.ts +0 -54
  764. package/dist/search-params/analyze.d.ts.map +0 -1
  765. package/dist/search-params/builtin-codecs.d.ts +0 -105
  766. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  767. package/dist/search-params/codecs.d.ts +0 -53
  768. package/dist/search-params/codecs.d.ts.map +0 -1
  769. package/dist/search-params/create.d.ts +0 -106
  770. package/dist/search-params/create.d.ts.map +0 -1
  771. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  772. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  773. package/dist/server/dev-logger.d.ts.map +0 -1
  774. package/dist/server/dev-span-processor.d.ts.map +0 -1
  775. package/dist/server/dev-warnings.d.ts.map +0 -1
  776. package/dist/server/manifest-status-resolver.d.ts +0 -58
  777. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  778. package/dist/server/prerender.d.ts +0 -77
  779. package/dist/server/prerender.d.ts.map +0 -1
  780. package/dist/utils/directive-parser.d.ts +0 -70
  781. package/dist/utils/directive-parser.d.ts.map +0 -1
  782. package/src/cache/register-cached-function.ts +0 -103
  783. package/src/client/browser-entry.ts +0 -678
  784. package/src/client/link-status-provider.tsx +0 -30
  785. package/src/client/segment-merger.ts +0 -339
  786. package/src/client/transition-root.tsx +0 -166
  787. package/src/client/use-navigation-pending.ts +0 -38
  788. package/src/plugins/cache-transform.ts +0 -199
  789. package/src/plugins/dev-error-overlay.ts +0 -230
  790. package/src/plugins/dynamic-transform.ts +0 -161
  791. package/src/plugins/server-action-exports.ts +0 -220
  792. package/src/routing/status-file-lint.ts +0 -112
  793. package/src/search-params/analyze.ts +0 -192
  794. package/src/search-params/builtin-codecs.ts +0 -228
  795. package/src/search-params/create.ts +0 -321
  796. package/src/server/dev-fetch-instrumentation.ts +0 -96
  797. package/src/server/dev-span-processor.ts +0 -78
  798. package/src/server/manifest-status-resolver.ts +0 -215
  799. package/src/server/prerender.ts +0 -139
  800. package/src/utils/directive-parser.ts +0 -529
  801. /package/src/{server/dev-logger.ts → dev-tools/logger.ts} +0 -0
@@ -0,0 +1,3126 @@
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-M_zKubhk.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-CNPXaypM.js";
3
+ import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-BjepjefT.js";
4
+ import { n as classifyUrlSegment } from "../_chunks/segment-classify-CDDRVKs7.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-Dt-jQaBO.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-DzFMnUAR.js";
7
+ import "../client/error-boundary.js";
8
+ import { n as toBracketKey } from "../_chunks/resolve-schema-Dj8tQloi.js";
9
+ import "../_chunks/segment-context-ZDnXDkbz.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 (prefix === "/") return true;
1625
+ if (!pathname.startsWith(prefix)) return false;
1626
+ return pathname.length === prefix.length || pathname[prefix.length] === "/";
1627
+ }
1628
+ /**
1629
+ * Check if an intercepting route applies for this soft navigation.
1630
+ *
1631
+ * Matches the target pathname against interception rewrites, constrained
1632
+ * by the source URL (X-Timber-URL header — where the user navigates FROM).
1633
+ *
1634
+ * Returns the source pathname to re-match if interception applies, or null.
1635
+ */
1636
+ function findInterceptionMatch(targetPathname, sourceUrl, rewrites) {
1637
+ for (const rewrite of rewrites) {
1638
+ if (!hasSegmentPrefix(sourceUrl, rewrite.interceptingPrefix)) continue;
1639
+ if (pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern)) return { sourcePathname: rewrite.interceptingPrefix };
1640
+ }
1641
+ return null;
1642
+ }
1643
+ /**
1644
+ * Check if a pathname matches a URL pattern with dynamic segments.
1645
+ *
1646
+ * Supports [param] (single segment) and [...param] (one or more segments).
1647
+ * Static segments must match exactly.
1648
+ */
1649
+ function pathnameMatchesPattern(pathname, pattern) {
1650
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
1651
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
1652
+ let pi = 0;
1653
+ for (let i = 0; i < patternParts.length; i++) {
1654
+ const seg = classifyUrlSegment(patternParts[i]);
1655
+ switch (seg.kind) {
1656
+ case "catch-all": return pi < pathParts.length;
1657
+ case "optional-catch-all": return true;
1658
+ case "dynamic":
1659
+ if (pi >= pathParts.length) return false;
1660
+ pi++;
1661
+ continue;
1662
+ case "static":
1663
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
1664
+ pi++;
1665
+ continue;
1666
+ }
1667
+ }
1668
+ return pi === pathParts.length;
1669
+ }
1670
+ //#endregion
1671
+ //#region src/server/pipeline-outcome.ts
1672
+ /**
1673
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
1674
+ * each phase function returns) into a final `Response`.
1675
+ *
1676
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
1677
+ * catch logic and the terminal Response-building logic each live in
1678
+ * their own file. The phases produce values; this module is the single
1679
+ * source of truth for how those values become wire responses.
1680
+ *
1681
+ * See design/07-routing.md §"Request Lifecycle".
1682
+ */
1683
+ function rscErrorResponse(isRsc, status, headers) {
1684
+ if (!isRsc) return new Response(null, { status });
1685
+ const h = headers ?? new Headers();
1686
+ h.set("X-Timber-Error", "1");
1687
+ h.set("content-type", "application/json; charset=utf-8");
1688
+ return new Response(JSON.stringify({
1689
+ error: true,
1690
+ status
1691
+ }), {
1692
+ status,
1693
+ headers: h
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
1698
+ * `Response`, applying cookies, building redirects, rendering deny pages
1699
+ * and fallback error pages, and firing instrumentation hooks.
1700
+ *
1701
+ * This is the single source of truth for how phase outputs become wire
1702
+ * responses; the per-phase try/catch blocks now produce values, not
1703
+ * Responses, so the conversion logic lives in exactly one place.
1704
+ */
1705
+ async function outcomeToResponse(config, outcome, ctx) {
1706
+ switch (outcome.kind) {
1707
+ case "response": {
1708
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
1709
+ if (outcome.phase === "proxy") return finalResponse;
1710
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
1711
+ applyCookieJar(finalResponse.headers);
1712
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
1713
+ logMiddlewareShortCircuit({
1714
+ method: ctx.method,
1715
+ path: ctx.path,
1716
+ status: finalResponse.status
1717
+ });
1718
+ }
1719
+ if (outcome.phase === "render") markResponseFlushed();
1720
+ return finalResponse;
1721
+ }
1722
+ case "redirect": {
1723
+ const headers = ctx.responseHeaders ?? new Headers();
1724
+ applyCookieJar(headers);
1725
+ return buildRedirectResponse(outcome.signal, ctx.req, headers);
1726
+ }
1727
+ case "deny": {
1728
+ const headers = ctx.responseHeaders ?? new Headers();
1729
+ applyCookieJar(headers);
1730
+ if (config.renderDenyFallback) try {
1731
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
1732
+ } catch (denyRenderError) {
1733
+ logRenderError({
1734
+ method: ctx.method,
1735
+ path: ctx.path,
1736
+ error: denyRenderError
1737
+ });
1738
+ await fireOnRequestError(denyRenderError, ctx.req, "render");
1739
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
1740
+ }
1741
+ 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.`);
1742
+ return new Response(null, {
1743
+ status: outcome.signal.status,
1744
+ headers
1745
+ });
1746
+ }
1747
+ case "error": {
1748
+ const isRsc = (ctx.req.headers.get("Accept") ?? "").includes("text/x-component");
1749
+ if (outcome.phase === "proxy") {
1750
+ logProxyError({ error: outcome.error });
1751
+ await fireOnRequestError(outcome.error, ctx.req, "proxy");
1752
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "proxy");
1753
+ return rscErrorResponse(isRsc, 500);
1754
+ }
1755
+ if (outcome.phase === "middleware") {
1756
+ logMiddlewareError({
1757
+ method: ctx.method,
1758
+ path: ctx.path,
1759
+ error: outcome.error
1760
+ });
1761
+ await fireOnRequestError(outcome.error, ctx.req, "handler");
1762
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "middleware");
1763
+ return rscErrorResponse(isRsc, 500);
1764
+ }
1765
+ const headers = ctx.responseHeaders ?? new Headers();
1766
+ applyCookieJar(headers);
1767
+ logRenderError({
1768
+ method: ctx.method,
1769
+ path: ctx.path,
1770
+ error: outcome.error
1771
+ });
1772
+ await fireOnRequestError(outcome.error, ctx.req, "render");
1773
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "render");
1774
+ if (isRsc) return rscErrorResponse(true, 500, headers);
1775
+ if (config.renderFallbackError) try {
1776
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, headers));
1777
+ } catch (fallbackRenderError) {
1778
+ logRenderError({
1779
+ method: ctx.method,
1780
+ path: ctx.path,
1781
+ error: fallbackRenderError
1782
+ });
1783
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render");
1784
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
1785
+ }
1786
+ return new Response(null, { status: 500 });
1787
+ }
1788
+ }
1789
+ }
1790
+ //#endregion
1791
+ //#region src/server/pipeline-phases.ts
1792
+ /**
1793
+ * Pipeline phase functions — module-level free functions that take their
1794
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
1795
+ * (a discriminated union over response / redirect / deny / error) defined
1796
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
1797
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
1798
+ *
1799
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
1800
+ * isolation. The lift is mechanical — these functions used to be closures
1801
+ * over `config`; they now take `config` as an explicit parameter.
1802
+ *
1803
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
1804
+ */
1805
+ /**
1806
+ * Validate and canonicalize the X-Timber-URL header value.
1807
+ *
1808
+ * Returns the canonical pathname if valid, or null if rejected:
1809
+ * - Must start with '/' (relative pathname, no scheme/authority)
1810
+ * - Must not contain control characters
1811
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
1812
+ */
1813
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
1814
+ if (!raw.startsWith("/")) return null;
1815
+ if (raw.startsWith("//")) return null;
1816
+ for (let i = 0; i < raw.length; i++) {
1817
+ const code = raw.charCodeAt(i);
1818
+ if (code <= 31 || code === 127) return null;
1819
+ }
1820
+ const result = canonicalize(raw, stripTrailingSlash);
1821
+ if (!result.ok) return null;
1822
+ return result.pathname;
1823
+ }
1824
+ /**
1825
+ * Run the proxy.ts phase. Calls user proxy code and uses `handleRequest` as
1826
+ * the inner `next()` continuation. The proxy resolver was picked at pipeline
1827
+ * construction time so the hot path sees no per-request branching on the
1828
+ * `ProxyConfig` discriminant.
1829
+ */
1830
+ async function runProxyPhase(config, getProxy, req, method, path) {
1831
+ const detailed = config.serverTiming === "detailed";
1832
+ try {
1833
+ const proxyExport = await getProxy();
1834
+ const proxyFn = () => runProxy(proxyExport, req, () => handleRequest(config, req, method, path, true));
1835
+ return {
1836
+ kind: "response",
1837
+ phase: "proxy",
1838
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
1839
+ };
1840
+ } catch (error) {
1841
+ if (error instanceof RedirectSignal) return {
1842
+ kind: "redirect",
1843
+ phase: "proxy",
1844
+ signal: error
1845
+ };
1846
+ if (error instanceof DenySignal) return {
1847
+ kind: "deny",
1848
+ phase: "proxy",
1849
+ signal: error
1850
+ };
1851
+ return {
1852
+ kind: "error",
1853
+ phase: "proxy",
1854
+ error
1855
+ };
1856
+ }
1857
+ }
1858
+ /**
1859
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
1860
+ * returns it as a 'response' outcome. Otherwise applies the request header
1861
+ * overlay and falls through to the render phase.
1862
+ */
1863
+ async function runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext) {
1864
+ const detailed = config.serverTiming === "detailed";
1865
+ const ctx = {
1866
+ req,
1867
+ requestHeaders: requestHeaderOverlay,
1868
+ headers: responseHeaders,
1869
+ segmentParams: match.segmentParams,
1870
+ earlyHints: (hints) => {
1871
+ for (const hint of hints) {
1872
+ let value;
1873
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
1874
+ else value = `<${hint.href}>; rel=${hint.rel}`;
1875
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1876
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1877
+ responseHeaders.append("Link", value);
1878
+ }
1879
+ }
1880
+ };
1881
+ try {
1882
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
1883
+ const middlewareResponse = await (async () => {
1884
+ setMutableCookieContext(true);
1885
+ try {
1886
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
1887
+ } finally {
1888
+ setMutableCookieContext(false);
1889
+ }
1890
+ })();
1891
+ if (middlewareResponse) return {
1892
+ kind: "response",
1893
+ phase: "middleware",
1894
+ response: middlewareResponse
1895
+ };
1896
+ applyRequestHeaderOverlay(requestHeaderOverlay);
1897
+ applyCookieJar(responseHeaders);
1898
+ return runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext);
1899
+ } catch (error) {
1900
+ if (error instanceof RedirectSignal) return {
1901
+ kind: "redirect",
1902
+ phase: "middleware",
1903
+ signal: error
1904
+ };
1905
+ if (error instanceof DenySignal) return {
1906
+ kind: "deny",
1907
+ phase: "middleware",
1908
+ signal: error
1909
+ };
1910
+ return {
1911
+ kind: "error",
1912
+ phase: "middleware",
1913
+ error
1914
+ };
1915
+ }
1916
+ }
1917
+ /**
1918
+ * Run the render phase. Wraps the configured renderer in a span and a
1919
+ * timing scope, and translates thrown signals into outcome variants.
1920
+ */
1921
+ async function runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, { canonicalPathname, interception }) {
1922
+ const detailed = config.serverTiming === "detailed";
1923
+ try {
1924
+ const renderFn = () => config.render(req, match, responseHeaders, requestHeaderOverlay, interception);
1925
+ return {
1926
+ kind: "response",
1927
+ phase: "render",
1928
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
1929
+ };
1930
+ } catch (error) {
1931
+ if (error instanceof DenySignal) return {
1932
+ kind: "deny",
1933
+ phase: "render",
1934
+ signal: error
1935
+ };
1936
+ if (error instanceof RedirectSignal) return {
1937
+ kind: "redirect",
1938
+ phase: "render",
1939
+ signal: error
1940
+ };
1941
+ return {
1942
+ kind: "error",
1943
+ phase: "render",
1944
+ error
1945
+ };
1946
+ }
1947
+ }
1948
+ /**
1949
+ * Process a single request from canonicalization through phase dispatch.
1950
+ *
1951
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
1952
+ * route match → interception → early hints → param coercion → middleware →
1953
+ * render → outcome translation. Pre-routing short-circuits return Responses
1954
+ * directly; post-match dispatch goes through `outcomeToResponse`.
1955
+ *
1956
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
1957
+ * the `next()` continuation passed to `runProxy()`.
1958
+ *
1959
+ * @param pathIsCanonical When true, `path` has already been canonicalized by
1960
+ * `createPipeline` — skip re-canonicalization to prevent double-decode.
1961
+ * When false (default), runs canonicalize as a safety net for direct callers.
1962
+ */
1963
+ async function handleRequest(config, req, method, path, pathIsCanonical) {
1964
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
1965
+ let canonicalPathname;
1966
+ if (pathIsCanonical) canonicalPathname = path;
1967
+ else {
1968
+ const result = canonicalize(path, stripTrailingSlash);
1969
+ if (!result.ok) {
1970
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${path} — responding with ${result.status}\n This usually means the URL contains encoded separators (%2f, %5c),\n null bytes (%00), path traversal (..), or malformed percent-encoding.`);
1971
+ return new Response(null, { status: result.status });
1972
+ }
1973
+ canonicalPathname = result.pathname;
1974
+ }
1975
+ if (config.matchMetadataRoute) {
1976
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
1977
+ if (metaMatch) try {
1978
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
1979
+ setSegmentParams(metaMatch.segmentParams);
1980
+ const mod = await loadModule(metaMatch.file);
1981
+ if (typeof mod.default !== "function") {
1982
+ 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.`);
1983
+ return new Response("Metadata route must export a default function", { status: 500 });
1984
+ }
1985
+ const handlerResult = await mod.default();
1986
+ if (handlerResult instanceof Response) {
1987
+ if (method === "HEAD") return new Response(null, {
1988
+ status: handlerResult.status,
1989
+ statusText: handlerResult.statusText,
1990
+ headers: new Headers(handlerResult.headers)
1991
+ });
1992
+ return cloneWithMutableHeaders(handlerResult);
1993
+ }
1994
+ const contentType = metaMatch.contentType;
1995
+ let body;
1996
+ if (typeof handlerResult === "string") body = handlerResult;
1997
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
1998
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
1999
+ else body = String(handlerResult);
2000
+ return new Response(body, {
2001
+ status: 200,
2002
+ headers: { "Content-Type": `${contentType}; charset=utf-8` }
2003
+ });
2004
+ } catch (error) {
2005
+ if (error instanceof RedirectSignal) return new Response(null, {
2006
+ status: error.status,
2007
+ headers: { Location: error.location }
2008
+ });
2009
+ if (error instanceof DenySignal) return new Response(null, { status: error.status });
2010
+ logRenderError({
2011
+ method,
2012
+ path,
2013
+ error
2014
+ });
2015
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
2016
+ return new Response(null, { status: 500 });
2017
+ }
2018
+ }
2019
+ if (config.autoSitemapHandler) try {
2020
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
2021
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
2022
+ } catch (error) {
2023
+ logRenderError({
2024
+ method,
2025
+ path,
2026
+ error
2027
+ });
2028
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
2029
+ return new Response(null, { status: 500 });
2030
+ }
2031
+ const isRscRequest = (req.headers.get("Accept") ?? "").includes("text/x-component");
2032
+ if (isRscRequest) {
2033
+ if (!checkVersionSkew(req).ok) {
2034
+ const reloadHeaders = new Headers();
2035
+ applyReloadHeaders(reloadHeaders);
2036
+ return new Response(null, {
2037
+ status: 204,
2038
+ headers: reloadHeaders
2039
+ });
2040
+ }
2041
+ }
2042
+ let match = config.matchRoute(canonicalPathname);
2043
+ let interception;
2044
+ if (isRscRequest && config.interceptionRewrites?.length) {
2045
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
2046
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
2047
+ if (validatedSourceUrl) {
2048
+ const intercepted = findInterceptionMatch(canonicalPathname, validatedSourceUrl, config.interceptionRewrites);
2049
+ if (intercepted) {
2050
+ const sourceMatch = config.matchRoute(intercepted.sourcePathname);
2051
+ if (sourceMatch) {
2052
+ match = sourceMatch;
2053
+ interception = { targetPathname: canonicalPathname };
2054
+ }
2055
+ }
2056
+ }
2057
+ }
2058
+ if (!match) {
2059
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
2060
+ if (config.renderNoMatch) {
2061
+ const responseHeaders = new Headers();
2062
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2063
+ }
2064
+ return new Response(null, { status: 404 });
2065
+ }
2066
+ const responseHeaders = new Headers();
2067
+ const requestHeaderOverlay = new Headers();
2068
+ responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
2069
+ if (config.earlyHints) try {
2070
+ await config.earlyHints(match, req, responseHeaders);
2071
+ } catch (err) {
2072
+ swallow(err, "early hints hook threw");
2073
+ }
2074
+ match.rawSegmentParams = { ...match.segmentParams };
2075
+ try {
2076
+ await coerceSegmentParams(match);
2077
+ } catch (error) {
2078
+ if (error instanceof ParamCoercionError) {
2079
+ if (isDebug()) {
2080
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
2081
+ 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).`);
2082
+ }
2083
+ const leafSegment = match.segments[match.segments.length - 1];
2084
+ if (leafSegment.route && !leafSegment.page) return new Response(null, { status: 404 });
2085
+ if (config.renderNoMatch) return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2086
+ return new Response(null, { status: 404 });
2087
+ }
2088
+ throw error;
2089
+ }
2090
+ setSegmentParams(match.segmentParams);
2091
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
2092
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
2093
+ return outcomeToResponse(config, !shouldBypassMiddleware(req) && match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2094
+ canonicalPathname,
2095
+ interception
2096
+ }) : await runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2097
+ canonicalPathname,
2098
+ interception
2099
+ }), {
2100
+ req,
2101
+ method,
2102
+ path,
2103
+ responseHeaders,
2104
+ match
2105
+ });
2106
+ }
2107
+ //#endregion
2108
+ //#region src/server/pipeline.ts
2109
+ /**
2110
+ * Create the request handler from a pipeline configuration.
2111
+ *
2112
+ * Returns a function that processes an incoming Request through all pipeline
2113
+ * stages and produces a Response. This is the top-level entry point for the
2114
+ * server. The body is intentionally small — phase logic lives in
2115
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
2116
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
2117
+ * scope, Server-Timing header emission, and the active-request counter.
2118
+ */
2119
+ function createPipeline(config) {
2120
+ const proxyResolver = makeProxyResolver(config.proxy);
2121
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
2122
+ const serverTiming = config.serverTiming ?? "total";
2123
+ let activeRequests = 0;
2124
+ return async (req) => {
2125
+ const url = new URL(req.url);
2126
+ const method = req.method;
2127
+ const path = url.pathname;
2128
+ const startTime = performance.now();
2129
+ activeRequests++;
2130
+ return runWithTraceId(generateTraceId(), async () => {
2131
+ return runWithRequestContext(req, async () => {
2132
+ const runRequest = async () => {
2133
+ logRequestReceived({
2134
+ method,
2135
+ path
2136
+ });
2137
+ const response = await withSpan("http.server.request", {
2138
+ "http.request.method": method,
2139
+ "url.path": path
2140
+ }, async () => {
2141
+ const otelIds = await getOtelTraceId();
2142
+ if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
2143
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2144
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
2145
+ if (!canonResult.ok) {
2146
+ 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.`);
2147
+ return new Response(null, { status: canonResult.status });
2148
+ }
2149
+ const canonicalPath = canonResult.pathname;
2150
+ let canonicalReq = req;
2151
+ if (url.pathname !== canonicalPath) {
2152
+ const canonicalUrl = new URL(req.url);
2153
+ canonicalUrl.pathname = canonicalPath;
2154
+ canonicalReq = new Request(canonicalUrl.toString(), req);
2155
+ }
2156
+ let result;
2157
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath), {
2158
+ req: canonicalReq,
2159
+ method,
2160
+ path: canonicalPath
2161
+ });
2162
+ else result = await handleRequest(config, canonicalReq, method, canonicalPath, true);
2163
+ await setSpanAttribute("http.response.status_code", result.status);
2164
+ const varyTokens = ["Accept"];
2165
+ if (config.interceptionRewrites?.length) varyTokens.push("X-Timber-URL");
2166
+ const existingVary = result.headers.get("Vary");
2167
+ const existingTokens = existingVary ? existingVary.toLowerCase().split(",").map((t) => t.trim()) : [];
2168
+ const newTokens = varyTokens.filter((t) => !existingTokens.includes(t.toLowerCase()));
2169
+ if (newTokens.length > 0) result.headers.set("Vary", existingVary ? `${existingVary}, ${newTokens.join(", ")}` : newTokens.join(", "));
2170
+ if (serverTiming === "detailed") {
2171
+ const timingHeader = getServerTimingHeader();
2172
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
2173
+ } else if (serverTiming === "total") {
2174
+ const totalMs = Math.round(performance.now() - startTime);
2175
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
2176
+ }
2177
+ return result;
2178
+ });
2179
+ const durationMs = Math.round(performance.now() - startTime);
2180
+ const status = response.status;
2181
+ const concurrency = activeRequests;
2182
+ activeRequests--;
2183
+ logRequestCompleted({
2184
+ method,
2185
+ path,
2186
+ status,
2187
+ durationMs,
2188
+ concurrency
2189
+ });
2190
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
2191
+ method,
2192
+ path,
2193
+ durationMs,
2194
+ threshold: slowRequestMs,
2195
+ concurrency
2196
+ });
2197
+ return response;
2198
+ };
2199
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
2200
+ });
2201
+ });
2202
+ };
2203
+ }
2204
+ //#endregion
2205
+ //#region src/server/build-manifest.ts
2206
+ /**
2207
+ * Collect all CSS files needed for a matched route's segment chain.
2208
+ *
2209
+ * Walks segments root → leaf, collecting CSS for each layout and page.
2210
+ * Deduplicates while preserving order (root layout CSS first).
2211
+ */
2212
+ function collectRouteCss(segments, manifest) {
2213
+ const seen = /* @__PURE__ */ new Set();
2214
+ const result = [];
2215
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2216
+ if (!file) continue;
2217
+ const cssFiles = manifest.css[file.filePath];
2218
+ if (!cssFiles) continue;
2219
+ for (const url of cssFiles) if (!seen.has(url)) {
2220
+ seen.add(url);
2221
+ result.push(url);
2222
+ }
2223
+ }
2224
+ return result;
2225
+ }
2226
+ /**
2227
+ * Collect all font entries needed for a matched route's segment chain.
2228
+ *
2229
+ * Walks segments root → leaf, collecting fonts for each layout and page.
2230
+ * Deduplicates by href while preserving order.
2231
+ */
2232
+ function collectRouteFonts(segments, manifest) {
2233
+ const seen = /* @__PURE__ */ new Set();
2234
+ const result = [];
2235
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2236
+ if (!file) continue;
2237
+ const fonts = manifest.fonts[file.filePath];
2238
+ if (!fonts) continue;
2239
+ for (const entry of fonts) if (!seen.has(entry.href)) {
2240
+ seen.add(entry.href);
2241
+ result.push(entry);
2242
+ }
2243
+ }
2244
+ return result;
2245
+ }
2246
+ /**
2247
+ * Collect modulepreload URLs for a matched route's segment chain.
2248
+ *
2249
+ * Walks segments root → leaf, collecting transitive JS dependencies
2250
+ * for each layout and page. Deduplicates across segments.
2251
+ */
2252
+ function collectRouteModulepreloads(segments, manifest) {
2253
+ const seen = /* @__PURE__ */ new Set();
2254
+ const result = [];
2255
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2256
+ if (!file) continue;
2257
+ const preloads = manifest.modulepreload[file.filePath];
2258
+ if (!preloads) continue;
2259
+ for (const url of preloads) if (!seen.has(url)) {
2260
+ seen.add(url);
2261
+ result.push(url);
2262
+ }
2263
+ }
2264
+ return result;
2265
+ }
2266
+ //#endregion
2267
+ //#region src/server/early-hints.ts
2268
+ /**
2269
+ * 103 Early Hints utilities.
2270
+ *
2271
+ * Early Hints are sent before the final response to let the browser
2272
+ * start fetching critical resources (CSS, fonts, JS) while the server
2273
+ * is still rendering.
2274
+ *
2275
+ * The framework collects hints from two sources:
2276
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
2277
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
2278
+ *
2279
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
2280
+ * Link headers into 103 Early Hints responses.
2281
+ *
2282
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
2283
+ */
2284
+ /**
2285
+ * Format a single EarlyHint as a Link header value.
2286
+ *
2287
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
2288
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
2289
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
2290
+ * attribute order differs from Cloudflare's cached copy, the browser
2291
+ * sees two preload headers for the same URL (different attribute order)
2292
+ * and warns "Preload was ignored." Matching the order ensures the
2293
+ * browser deduplicates them correctly.
2294
+ *
2295
+ * Examples:
2296
+ * `</styles/root.css>; as=style; rel=preload`
2297
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
2298
+ * `</_timber/client.js>; rel=modulepreload`
2299
+ * `<https://fonts.googleapis.com>; rel=preconnect`
2300
+ */
2301
+ function formatLinkHeader(hint) {
2302
+ if (hint.as !== void 0) {
2303
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2304
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2305
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2306
+ return value;
2307
+ }
2308
+ let value = `<${hint.href}>; rel=${hint.rel}`;
2309
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2310
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2311
+ return value;
2312
+ }
2313
+ /**
2314
+ * Collect all Link header strings for a matched route's segment chain.
2315
+ *
2316
+ * Walks the build manifest to emit hints for:
2317
+ * - CSS stylesheets (as=style; rel=preload)
2318
+ * - Font assets (as=font; rel=preload; crossorigin)
2319
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
2320
+ *
2321
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
2322
+ * Returns an empty array in dev mode (manifest is empty).
2323
+ */
2324
+ function collectEarlyHintHeaders(segments, manifest, options) {
2325
+ const result = [];
2326
+ const seenUrls = /* @__PURE__ */ new Set();
2327
+ const add = (url, header) => {
2328
+ if (!seenUrls.has(url)) {
2329
+ seenUrls.add(url);
2330
+ result.push(header);
2331
+ }
2332
+ };
2333
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
2334
+ href: url,
2335
+ rel: "preload",
2336
+ as: "style"
2337
+ }));
2338
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
2339
+ href: font.href,
2340
+ rel: "preload",
2341
+ as: "font",
2342
+ crossOrigin: "anonymous"
2343
+ }));
2344
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
2345
+ href: url,
2346
+ rel: "modulepreload"
2347
+ }));
2348
+ return result;
2349
+ }
2350
+ //#endregion
2351
+ //#region src/server/early-hints-sender.ts
2352
+ /**
2353
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
2354
+ *
2355
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
2356
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
2357
+ * the adapter can send these as a 103 Early Hints interim response before
2358
+ * the final response is ready.
2359
+ *
2360
+ * This module provides an ALS-based bridge: the generated entry point
2361
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
2362
+ * binding a per-request sender function. The pipeline calls
2363
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
2364
+ *
2365
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
2366
+ * converts Link headers into 103 automatically), no sender is installed
2367
+ * and `sendEarlyHints103()` is a no-op.
2368
+ *
2369
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
2370
+ */
2371
+ /**
2372
+ * Run a function with a per-request early hints sender installed.
2373
+ *
2374
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
2375
+ * bind the platform's writeEarlyHints capability for the request duration.
2376
+ */
2377
+ function runWithEarlyHintsSender(sender, fn) {
2378
+ return earlyHintsSenderAls.run(sender, fn);
2379
+ }
2380
+ /**
2381
+ * Send collected Link headers as a 103 Early Hints response.
2382
+ *
2383
+ * No-op if no sender is installed for the current request (e.g., on
2384
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
2385
+ *
2386
+ * Non-fatal: errors from the sender are caught and silently ignored.
2387
+ */
2388
+ function sendEarlyHints103(links) {
2389
+ if (!links.length) return;
2390
+ const sender = earlyHintsSenderAls.getStore();
2391
+ if (!sender) return;
2392
+ try {
2393
+ sender(links);
2394
+ } catch (err) {
2395
+ swallow(err, "early hints 103 send failed");
2396
+ }
2397
+ }
2398
+ //#endregion
2399
+ //#region src/server/tree-builder.ts
2400
+ var REACT_COMPONENT_TYPE_MARKERS = new Set([
2401
+ Symbol.for("react.forward_ref"),
2402
+ Symbol.for("react.memo"),
2403
+ Symbol.for("react.lazy"),
2404
+ Symbol.for("react.provider"),
2405
+ Symbol.for("react.context"),
2406
+ Symbol.for("react.suspense"),
2407
+ Symbol.for("react.suspense_list"),
2408
+ Symbol.for("react.client.reference")
2409
+ ]);
2410
+ /**
2411
+ * Validate that a loaded module's `default` export is something React
2412
+ * accepts as the first argument to `createElement` — i.e. a valid component
2413
+ * type. React doesn't export `isValidElementType` (only `isValidElement`,
2414
+ * which checks for *elements*, not *component types*), so this mirrors
2415
+ * React's internal check:
2416
+ *
2417
+ * - functions → function or class components
2418
+ * - objects with a `$$typeof` matching one of React's known component
2419
+ * markers → exotic components (`memo`, `forwardRef`, `lazy`, context,
2420
+ * suspense, client references via `@vitejs/plugin-rsc`)
2421
+ *
2422
+ * Strings (HTML tag names) are valid for `createElement` but never appear
2423
+ * as a route module's default export, so they're not recognized here.
2424
+ *
2425
+ * Anything else (numbers, plain config objects, JSON, etc.) is rejected so
2426
+ * the boundary wrapper is skipped rather than crashing inside React.
2427
+ */
2428
+ function isValidElementType(value) {
2429
+ if (typeof value === "function") return true;
2430
+ if (typeof value !== "object" || value === null) return false;
2431
+ const marker = value.$$typeof;
2432
+ return typeof marker === "symbol" && REACT_COMPONENT_TYPE_MARKERS.has(marker);
2433
+ }
2434
+ /**
2435
+ * Build the unified element tree from a matched segment chain.
2436
+ *
2437
+ * Construction is bottom-up:
2438
+ * 1. Start with the page component (leaf segment)
2439
+ * 2. Wrap in status-code error boundaries (fallback chain)
2440
+ * 3. Wrap in AccessGate (if segment has access.ts)
2441
+ * 4. Pass as children to the segment's layout
2442
+ * 5. Repeat up the segment chain to root
2443
+ *
2444
+ * Parallel slots are resolved at each layout level and composed as named props.
2445
+ */
2446
+ async function buildElementTree(config) {
2447
+ const { segments, loadModule, createElement, errorBoundaryComponent } = config;
2448
+ if (segments.length === 0) throw new Error("[timber] buildElementTree: empty segment chain");
2449
+ const leaf = segments[segments.length - 1];
2450
+ if (leaf.route && !leaf.page) return {
2451
+ tree: null,
2452
+ isApiRoute: true
2453
+ };
2454
+ const PageComponent = (leaf.page ? await loadModule(leaf.page) : null)?.default;
2455
+ 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.`);
2456
+ let element = createElement(PageComponent, {});
2457
+ for (let i = segments.length - 1; i >= 0; i--) {
2458
+ const segment = segments[i];
2459
+ element = await wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent);
2460
+ if (segment.access) {
2461
+ const accessFn = (await loadModule(segment.access)).default;
2462
+ element = createElement("timber:access-gate", {
2463
+ accessFn,
2464
+ segmentName: segment.segmentName,
2465
+ children: element
2466
+ });
2467
+ }
2468
+ if (segment.layout) {
2469
+ const LayoutComponent = (await loadModule(segment.layout)).default;
2470
+ if (LayoutComponent) {
2471
+ const slotProps = {};
2472
+ const slotNames = Object.keys(segment.slots);
2473
+ if (slotNames.length > 0) for (const slotName of slotNames) {
2474
+ const slotNode = segment.slots[slotName];
2475
+ slotProps[slotName] = await buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent);
2476
+ }
2477
+ element = createElement(LayoutComponent, {
2478
+ ...slotProps,
2479
+ children: element
2480
+ });
2481
+ }
2482
+ }
2483
+ }
2484
+ return {
2485
+ tree: element,
2486
+ isApiRoute: false
2487
+ };
2488
+ }
2489
+ /**
2490
+ * Build the element tree for a parallel slot.
2491
+ *
2492
+ * Slots have their own access.ts (SlotAccessGate) and error boundaries.
2493
+ * On access denial: denied.tsx → default.tsx → null (graceful degradation).
2494
+ */
2495
+ async function buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent) {
2496
+ const PageComponent = (slotNode.page ? await loadModule(slotNode.page) : null)?.default;
2497
+ const DefaultComponent = (slotNode.default ? await loadModule(slotNode.default) : null)?.default;
2498
+ if (!PageComponent) return DefaultComponent ? createElement(DefaultComponent, {}) : null;
2499
+ let element = createElement(PageComponent, {});
2500
+ element = await wrapWithErrorBoundaries(slotNode, element, loadModule, createElement, errorBoundaryComponent);
2501
+ if (slotNode.access) {
2502
+ const accessFn = (await loadModule(slotNode.access)).default;
2503
+ const DeniedComponent = (slotNode.denied ? await loadModule(slotNode.denied) : null)?.default ?? null;
2504
+ const defaultFallback = DefaultComponent ? createElement(DefaultComponent, {}) : null;
2505
+ element = createElement("timber:slot-access-gate", {
2506
+ accessFn,
2507
+ DeniedComponent,
2508
+ slotName: slotNode.segmentName.replace(/^@/, ""),
2509
+ createElement,
2510
+ defaultFallback,
2511
+ children: element
2512
+ });
2513
+ }
2514
+ return element;
2515
+ }
2516
+ /** MDX/markdown extensions — these are server components that cannot be passed as function props. */
2517
+ var MDX_EXTENSIONS = new Set(["mdx", "md"]);
2518
+ /**
2519
+ * Check if a route file is an MDX/markdown file based on its extension.
2520
+ * MDX components are server components by default and cannot cross the
2521
+ * RSC→client boundary as function props. They must be pre-rendered as
2522
+ * elements and passed as fallbackElement instead of fallbackComponent.
2523
+ */
2524
+ function isMdxFile(file) {
2525
+ return MDX_EXTENSIONS.has(file.extension);
2526
+ }
2527
+ /**
2528
+ * Wrap an element with error boundaries from a segment's status-code files.
2529
+ *
2530
+ * Wrapping order (innermost to outermost):
2531
+ * 1. Specific status files (503.tsx, 429.tsx, etc.)
2532
+ * 2. Category catch-alls (4xx.tsx, 5xx.tsx)
2533
+ * 3. error.tsx (general error boundary)
2534
+ *
2535
+ * This creates the fallback chain described in design/10-error-handling.md.
2536
+ *
2537
+ * MDX status files are server components and cannot be passed as function
2538
+ * props to TimberErrorBoundary (a 'use client' component). Instead, they
2539
+ * are pre-rendered as elements and passed as fallbackElement. The error
2540
+ * boundary renders the element directly when an error is caught.
2541
+ * See TIM-503.
2542
+ */
2543
+ async function wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent) {
2544
+ if (segment.statusFiles) {
2545
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key !== "4xx" && key !== "5xx") {
2546
+ const status = parseInt(key, 10);
2547
+ if (!isNaN(status)) {
2548
+ const mod = await loadModule(file);
2549
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2550
+ if (Component) element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2551
+ fallbackElement: createElement(Component, { status }),
2552
+ status,
2553
+ children: element
2554
+ } : {
2555
+ fallbackComponent: Component,
2556
+ status,
2557
+ children: element
2558
+ });
2559
+ }
2560
+ }
2561
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key === "4xx" || key === "5xx") {
2562
+ const mod = await loadModule(file);
2563
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2564
+ if (Component) {
2565
+ const categoryStatus = key === "4xx" ? 400 : 500;
2566
+ element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2567
+ fallbackElement: createElement(Component, {}),
2568
+ status: categoryStatus,
2569
+ children: element
2570
+ } : {
2571
+ fallbackComponent: Component,
2572
+ status: categoryStatus,
2573
+ children: element
2574
+ });
2575
+ }
2576
+ }
2577
+ }
2578
+ if (segment.error) {
2579
+ const errorModule = await loadModule(segment.error);
2580
+ const ErrorComponent = isValidElementType(errorModule.default) ? errorModule.default : null;
2581
+ if (ErrorComponent) element = createElement(errorBoundaryComponent, isMdxFile(segment.error) ? {
2582
+ fallbackElement: createElement(ErrorComponent, {}),
2583
+ children: element
2584
+ } : {
2585
+ fallbackComponent: ErrorComponent,
2586
+ children: element
2587
+ });
2588
+ }
2589
+ return element;
2590
+ }
2591
+ //#endregion
2592
+ //#region src/server/status-code-resolver.ts
2593
+ /** Reverse index: status code → legacy file name. Built once at module load. */
2594
+ var STATUS_TO_LEGACY_FILE = Object.fromEntries(Object.entries({
2595
+ "not-found": 404,
2596
+ "forbidden": 403,
2597
+ "unauthorized": 401
2598
+ }).map(([name, status]) => [status, name]));
2599
+ /**
2600
+ * Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
2601
+ * status-file group on a single segment. Shared by all three fallback
2602
+ * chains — the only structural difference between component 4xx,
2603
+ * component 5xx, and JSON resolution is *which* group is searched and
2604
+ * how the per-segment loop is layered around it.
2605
+ */
2606
+ function lookupInGroup(group, statusStr, categoryKey, segmentIndex, status) {
2607
+ if (!group) return null;
2608
+ const exact = group[statusStr];
2609
+ if (exact) return {
2610
+ file: exact,
2611
+ status,
2612
+ kind: "exact",
2613
+ segmentIndex
2614
+ };
2615
+ const category = group[categoryKey];
2616
+ if (category) return {
2617
+ file: category,
2618
+ status,
2619
+ kind: "category",
2620
+ segmentIndex
2621
+ };
2622
+ return null;
2623
+ }
2624
+ /**
2625
+ * Look up the legacy convention file (`not-found.tsx` / `forbidden.tsx` /
2626
+ * `unauthorized.tsx`) for `status` on a single segment. Returns null if
2627
+ * `status` has no legacy mapping or the file isn't present.
2628
+ */
2629
+ function lookupLegacy(group, status, segmentIndex) {
2630
+ if (!group) return null;
2631
+ const name = STATUS_TO_LEGACY_FILE[status];
2632
+ if (!name) return null;
2633
+ const file = group[name];
2634
+ return file ? {
2635
+ file,
2636
+ status,
2637
+ kind: "legacy",
2638
+ segmentIndex
2639
+ } : null;
2640
+ }
2641
+ /**
2642
+ * Resolve the status-code file to render for a given HTTP status code.
2643
+ *
2644
+ * Walks the segment chain from leaf to root following the fallback chain
2645
+ * defined in design/10-error-handling.md. Returns null if no file is found
2646
+ * (caller should render the framework default).
2647
+ *
2648
+ * @param status - The HTTP status code (4xx or 5xx).
2649
+ * @param segments - The matched segment chain from root (index 0) to leaf (last).
2650
+ * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
2651
+ */
2652
+ function resolveStatusFile(status, segments, format = "component") {
2653
+ if (status < 400 || status > 599) return null;
2654
+ if (format === "json") return resolveJson(status, segments);
2655
+ if (status <= 499) return resolve4xx(status, segments);
2656
+ return resolve5xx(status, segments);
2657
+ }
2658
+ /**
2659
+ * 4xx component fallback chain — three separate full passes leaf→root.
2660
+ *
2661
+ * The passes must be separate (not interleaved per-segment) so that a
2662
+ * root-level `404.tsx` beats a leaf-level `error.tsx`. The 5xx chain
2663
+ * inverts this and is per-segment: a leaf's `error.tsx` beats a root's
2664
+ * `5xx.tsx`. This asymmetry is the only reason these two functions exist
2665
+ * separately.
2666
+ *
2667
+ * Pass 1 — {status}.tsx → 4xx.tsx (statusFiles)
2668
+ * Pass 2 — not-found / forbidden / unauthorized (legacyStatusFiles)
2669
+ * Pass 3 — error.tsx (error)
2670
+ */
2671
+ function resolve4xx(status, segments) {
2672
+ const statusStr = String(status);
2673
+ for (let i = segments.length - 1; i >= 0; i--) {
2674
+ const r = lookupInGroup(segments[i].statusFiles, statusStr, "4xx", i, status);
2675
+ if (r) return r;
2676
+ }
2677
+ for (let i = segments.length - 1; i >= 0; i--) {
2678
+ const r = lookupLegacy(segments[i].legacyStatusFiles, status, i);
2679
+ if (r) return r;
2680
+ }
2681
+ for (let i = segments.length - 1; i >= 0; i--) {
2682
+ const errorFile = segments[i].error;
2683
+ if (errorFile) return {
2684
+ file: errorFile,
2685
+ status,
2686
+ kind: "error",
2687
+ segmentIndex: i
2688
+ };
2689
+ }
2690
+ return null;
2691
+ }
2692
+ /**
2693
+ * 5xx component fallback chain — single pass, per-segment leaf→root.
2694
+ *
2695
+ * At each segment: {status}.tsx → 5xx.tsx → error.tsx. A leaf's
2696
+ * `error.tsx` therefore beats a root's `5xx.tsx`, which is the
2697
+ * intentional inverse of the 4xx chain.
2698
+ */
2699
+ function resolve5xx(status, segments) {
2700
+ const statusStr = String(status);
2701
+ for (let i = segments.length - 1; i >= 0; i--) {
2702
+ const segment = segments[i];
2703
+ const r = lookupInGroup(segment.statusFiles, statusStr, "5xx", i, status);
2704
+ if (r) return r;
2705
+ if (segment.error) return {
2706
+ file: segment.error,
2707
+ status,
2708
+ kind: "error",
2709
+ segmentIndex: i
2710
+ };
2711
+ }
2712
+ return null;
2713
+ }
2714
+ /**
2715
+ * JSON fallback chain (for both 4xx and 5xx) — single pass leaf→root.
2716
+ *
2717
+ * At each segment: {status}.json → {category}.json. No legacy compat,
2718
+ * no error.tsx — the JSON chain terminates at the category catch-all
2719
+ * and the caller falls back to a bare-JSON framework default.
2720
+ */
2721
+ function resolveJson(status, segments) {
2722
+ const statusStr = String(status);
2723
+ const categoryKey = status >= 500 ? "5xx" : "4xx";
2724
+ for (let i = segments.length - 1; i >= 0; i--) {
2725
+ const r = lookupInGroup(segments[i].jsonStatusFiles, statusStr, categoryKey, i, status);
2726
+ if (r) return r;
2727
+ }
2728
+ return null;
2729
+ }
2730
+ /**
2731
+ * Resolve the denial file for a parallel route slot.
2732
+ *
2733
+ * Slot denial is graceful degradation — no HTTP status on the wire.
2734
+ * Fallback chain: denied.tsx → default.tsx → null.
2735
+ *
2736
+ * @param slotNode - The segment node for the slot (segmentType === 'slot').
2737
+ */
2738
+ function resolveSlotDenied(slotNode) {
2739
+ const slotName = slotNode.segmentName.replace(/^@/, "");
2740
+ if (slotNode.denied) return {
2741
+ file: slotNode.denied,
2742
+ slotName,
2743
+ kind: "denied"
2744
+ };
2745
+ if (slotNode.default) return {
2746
+ file: slotNode.default,
2747
+ slotName,
2748
+ kind: "default"
2749
+ };
2750
+ return null;
2751
+ }
2752
+ //#endregion
2753
+ //#region src/server/flush.ts
2754
+ /**
2755
+ * Flush controller for timber.js rendering.
2756
+ *
2757
+ * Holds the response until `onShellReady` fires, then commits the HTTP status
2758
+ * code and flushes the shell. Render-phase signals (deny, redirect, unhandled
2759
+ * throws) caught before flush produce correct HTTP status codes.
2760
+ *
2761
+ * See design/02-rendering-pipeline.md §"The Flush Point" and §"The Hold Window"
2762
+ */
2763
+ /**
2764
+ * Execute a render and hold the response until the shell is ready.
2765
+ *
2766
+ * The flush controller:
2767
+ * 1. Calls the render function to start renderToReadableStream
2768
+ * 2. Waits for shellReady (onShellReady)
2769
+ * 3. If a render-phase signal was thrown (deny, redirect, error), produces
2770
+ * the correct HTTP status code
2771
+ * 4. If the shell rendered successfully, commits the status and streams
2772
+ *
2773
+ * Render-phase signals caught before flush:
2774
+ * - `DenySignal` → HTTP 4xx with appropriate status code
2775
+ * - `RedirectSignal` → HTTP 3xx with Location header
2776
+ * - `RenderError` → HTTP status from error (default 500)
2777
+ * - Unhandled error → HTTP 500
2778
+ *
2779
+ * @param renderFn - Function that starts the React render.
2780
+ * @param options - Flush configuration.
2781
+ * @returns The committed HTTP Response.
2782
+ */
2783
+ async function flushResponse(renderFn, options = {}) {
2784
+ const { responseHeaders = new Headers(), defaultStatus = 200 } = options;
2785
+ let renderResult;
2786
+ try {
2787
+ renderResult = await renderFn();
2788
+ } catch (error) {
2789
+ return handleSignal(error, responseHeaders);
2790
+ }
2791
+ try {
2792
+ await renderResult.shellReady;
2793
+ } catch (error) {
2794
+ return handleSignal(error, responseHeaders);
2795
+ }
2796
+ responseHeaders.set("Content-Type", "text/html; charset=utf-8");
2797
+ return {
2798
+ response: new Response(renderResult.stream, {
2799
+ status: defaultStatus,
2800
+ headers: responseHeaders
2801
+ }),
2802
+ status: defaultStatus,
2803
+ isRedirect: false,
2804
+ isDenial: false
2805
+ };
2806
+ }
2807
+ /**
2808
+ * Handle a render-phase signal and produce the correct HTTP response.
2809
+ */
2810
+ function handleSignal(error, responseHeaders) {
2811
+ if (error instanceof RedirectSignal) {
2812
+ responseHeaders.set("Location", error.location);
2813
+ return {
2814
+ response: new Response(null, {
2815
+ status: error.status,
2816
+ headers: responseHeaders
2817
+ }),
2818
+ status: error.status,
2819
+ isRedirect: true,
2820
+ isDenial: false
2821
+ };
2822
+ }
2823
+ if (error instanceof DenySignal) return {
2824
+ response: new Response(null, {
2825
+ status: error.status,
2826
+ headers: responseHeaders
2827
+ }),
2828
+ status: error.status,
2829
+ isRedirect: false,
2830
+ isDenial: true
2831
+ };
2832
+ if (error instanceof RenderError) return {
2833
+ response: new Response(null, {
2834
+ status: error.status,
2835
+ headers: responseHeaders
2836
+ }),
2837
+ status: error.status,
2838
+ isRedirect: false,
2839
+ isDenial: false
2840
+ };
2841
+ logRenderError({
2842
+ method: "",
2843
+ path: "",
2844
+ error
2845
+ });
2846
+ return {
2847
+ response: new Response(null, {
2848
+ status: 500,
2849
+ headers: responseHeaders
2850
+ }),
2851
+ status: 500,
2852
+ isRedirect: false,
2853
+ isDenial: false
2854
+ };
2855
+ }
2856
+ //#endregion
2857
+ //#region src/server/csrf.ts
2858
+ /** HTTP methods that are considered safe (no mutation). */
2859
+ var SAFE_METHODS = new Set([
2860
+ "GET",
2861
+ "HEAD",
2862
+ "OPTIONS"
2863
+ ]);
2864
+ /**
2865
+ * Derive the request's scheme from trusted sources.
2866
+ *
2867
+ * Priority:
2868
+ * 1. X-Forwarded-Proto (set by reverse proxies / load balancers)
2869
+ * 2. Request URL protocol
2870
+ *
2871
+ * Falls back to 'https' (fail closed) if neither is available.
2872
+ */
2873
+ function deriveRequestScheme(req) {
2874
+ const forwarded = req.headers.get("X-Forwarded-Proto");
2875
+ if (forwarded) {
2876
+ const proto = forwarded.split(",")[0].trim().toLowerCase();
2877
+ if (proto === "http" || proto === "https") return proto;
2878
+ }
2879
+ try {
2880
+ return new URL(req.url).protocol.replace(":", "");
2881
+ } catch {
2882
+ return "https";
2883
+ }
2884
+ }
2885
+ /**
2886
+ * Validate the Origin header against the request's full origin
2887
+ * (scheme + host + port).
2888
+ *
2889
+ * For mutation methods (POST, PUT, PATCH, DELETE):
2890
+ * - If `csrf: false`, skip validation.
2891
+ * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
2892
+ * - Otherwise, Origin must match the derived request origin.
2893
+ *
2894
+ * Safe methods (GET, HEAD, OPTIONS) always pass.
2895
+ */
2896
+ function validateCsrf(req, config) {
2897
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
2898
+ if (config.csrf === false) return { ok: true };
2899
+ const origin = req.headers.get("Origin");
2900
+ if (!origin) return {
2901
+ ok: false,
2902
+ status: 403
2903
+ };
2904
+ if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
2905
+ ok: false,
2906
+ status: 403
2907
+ };
2908
+ const host = req.headers.get("Host");
2909
+ if (!host) return {
2910
+ ok: false,
2911
+ status: 403
2912
+ };
2913
+ let originOrigin;
2914
+ try {
2915
+ originOrigin = new URL(origin).origin;
2916
+ } catch {
2917
+ return {
2918
+ ok: false,
2919
+ status: 403
2920
+ };
2921
+ }
2922
+ const scheme = deriveRequestScheme(req);
2923
+ let expectedOrigin;
2924
+ try {
2925
+ expectedOrigin = new URL(`${scheme}://${host}`).origin;
2926
+ } catch {
2927
+ return {
2928
+ ok: false,
2929
+ status: 403
2930
+ };
2931
+ }
2932
+ return originOrigin === expectedOrigin ? { ok: true } : {
2933
+ ok: false,
2934
+ status: 403
2935
+ };
2936
+ }
2937
+ //#endregion
2938
+ //#region src/server/body-limits.ts
2939
+ var KB = 1024;
2940
+ var MB = 1024 * KB;
2941
+ var GB = 1024 * MB;
2942
+ var DEFAULT_LIMITS = {
2943
+ actionBodySize: 1 * MB,
2944
+ uploadBodySize: 10 * MB,
2945
+ maxFields: 100
2946
+ };
2947
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2948
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2949
+ function parseBodySize(size) {
2950
+ const match = SIZE_PATTERN.exec(size.trim());
2951
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2952
+ const value = Number.parseFloat(match[1]);
2953
+ const unit = (match[2] ?? "").toLowerCase();
2954
+ switch (unit) {
2955
+ case "kb": return Math.floor(value * KB);
2956
+ case "mb": return Math.floor(value * MB);
2957
+ case "gb": return Math.floor(value * GB);
2958
+ case "": return Math.floor(value);
2959
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2960
+ }
2961
+ }
2962
+ /** Strict integer pattern: one or more digits, nothing else. */
2963
+ var STRICT_INTEGER_RE = /^\d+$/;
2964
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2965
+ function enforceBodyLimits(req, kind, config) {
2966
+ const contentLength = req.headers.get("Content-Length");
2967
+ if (!contentLength) return {
2968
+ ok: false,
2969
+ status: 411
2970
+ };
2971
+ const trimmed = contentLength.trim();
2972
+ if (!STRICT_INTEGER_RE.test(trimmed)) return {
2973
+ ok: false,
2974
+ status: 411
2975
+ };
2976
+ return Number.parseInt(trimmed, 10) <= resolveLimit(kind, config) ? { ok: true } : {
2977
+ ok: false,
2978
+ status: 413
2979
+ };
2980
+ }
2981
+ /**
2982
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2983
+ */
2984
+ function resolveLimit(kind, config) {
2985
+ const userLimits = config.limits;
2986
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2987
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2988
+ }
2989
+ //#endregion
2990
+ //#region src/server/route-handler.ts
2991
+ /** All recognized HTTP method export names. */
2992
+ var HTTP_METHODS = [
2993
+ "GET",
2994
+ "POST",
2995
+ "PUT",
2996
+ "PATCH",
2997
+ "DELETE",
2998
+ "HEAD",
2999
+ "OPTIONS"
3000
+ ];
3001
+ /**
3002
+ * Resolve the full list of allowed methods for a route module.
3003
+ *
3004
+ * Includes:
3005
+ * - All explicitly exported methods
3006
+ * - HEAD (implicit when GET is exported)
3007
+ * - OPTIONS (always implicit)
3008
+ */
3009
+ function resolveAllowedMethods(mod) {
3010
+ const methods = [];
3011
+ for (const method of HTTP_METHODS) {
3012
+ if (method === "HEAD" || method === "OPTIONS") continue;
3013
+ if (mod[method]) methods.push(method);
3014
+ }
3015
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
3016
+ else if (mod.HEAD) methods.push("HEAD");
3017
+ if (!mod.OPTIONS) methods.push("OPTIONS");
3018
+ else methods.push("OPTIONS");
3019
+ return methods;
3020
+ }
3021
+ /**
3022
+ * Handle an incoming request against a route.ts module.
3023
+ *
3024
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
3025
+ * and merges response headers from ctx.headers.
3026
+ */
3027
+ async function handleRouteRequest(mod, ctx) {
3028
+ const method = ctx.req.method.toUpperCase();
3029
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
3030
+ if (method === "OPTIONS") {
3031
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
3032
+ return new Response(null, {
3033
+ status: 204,
3034
+ headers: { Allow: allowHeader }
3035
+ });
3036
+ }
3037
+ if (method === "HEAD") {
3038
+ if (mod.HEAD) return runHandler(mod.HEAD, ctx);
3039
+ if (mod.GET) {
3040
+ const res = await runHandler(mod.GET, ctx);
3041
+ return new Response(null, {
3042
+ status: res.status,
3043
+ headers: res.headers
3044
+ });
3045
+ }
3046
+ }
3047
+ const handler = mod[method];
3048
+ if (!handler) return new Response(null, {
3049
+ status: 405,
3050
+ headers: { Allow: allowHeader }
3051
+ });
3052
+ return runHandler(handler, ctx);
3053
+ }
3054
+ /**
3055
+ * Run a handler, merge ctx.headers into the response, and catch errors.
3056
+ */
3057
+ async function runHandler(handler, ctx) {
3058
+ try {
3059
+ return mergeResponseHeaders(await handler(ctx), ctx.headers);
3060
+ } catch (error) {
3061
+ if (error instanceof DenySignal || error instanceof RedirectSignal) throw error;
3062
+ logRouteError({
3063
+ method: ctx.req.method,
3064
+ path: new URL(ctx.req.url).pathname,
3065
+ error
3066
+ });
3067
+ return new Response(null, { status: 500 });
3068
+ }
3069
+ }
3070
+ /**
3071
+ * Merge response headers from ctx.headers into the handler's response.
3072
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
3073
+ * Handler-set headers take precedence over ctx.headers.
3074
+ */
3075
+ function mergeResponseHeaders(res, ctxHeaders) {
3076
+ let hasCtxHeaders = false;
3077
+ ctxHeaders.forEach(() => {
3078
+ hasCtxHeaders = true;
3079
+ });
3080
+ if (!hasCtxHeaders) return res;
3081
+ const merged = new Headers();
3082
+ ctxHeaders.forEach((value, key) => {
3083
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
3084
+ else merged.set(key, value);
3085
+ });
3086
+ const resCookies = res.headers.getSetCookie();
3087
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
3088
+ res.headers.forEach((value, key) => {
3089
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
3090
+ });
3091
+ return new Response(res.body, {
3092
+ status: res.status,
3093
+ statusText: res.statusText,
3094
+ headers: merged
3095
+ });
3096
+ }
3097
+ //#endregion
3098
+ //#region src/server/render-timeout.ts
3099
+ /**
3100
+ * Render timeout utilities for SSR streaming pipeline.
3101
+ *
3102
+ * Provides a RenderTimeoutError class and a helper to create
3103
+ * timeout-guarded AbortSignals. Used to defend against hung RSC
3104
+ * streams and infinite SSR renders.
3105
+ *
3106
+ * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
3107
+ */
3108
+ /**
3109
+ * Error thrown when an SSR render or RSC stream read exceeds the
3110
+ * configured timeout. Callers can check `instanceof RenderTimeoutError`
3111
+ * to distinguish timeout from other errors and return a 504 or close
3112
+ * the connection cleanly.
3113
+ */
3114
+ var RenderTimeoutError = class extends Error {
3115
+ timeoutMs;
3116
+ constructor(timeoutMs, context) {
3117
+ const message = context ? `Render timeout after ${timeoutMs}ms: ${context}` : `Render timeout after ${timeoutMs}ms`;
3118
+ super(message);
3119
+ this.name = "RenderTimeoutError";
3120
+ this.timeoutMs = timeoutMs;
3121
+ }
3122
+ };
3123
+ //#endregion
3124
+ 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 };
3125
+
3126
+ //# sourceMappingURL=internal.js.map