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

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 (1470) hide show
  1. package/LICENSE +8 -0
  2. package/agent-skill.md +351 -0
  3. package/bin/timber.mjs +15 -1
  4. package/dist/_chunks/actions-BwkmAYXq.js +1243 -0
  5. package/dist/_chunks/actions-BwkmAYXq.js.map +1 -0
  6. package/dist/_chunks/als-registry-BZqHCtq-.js +43 -0
  7. package/dist/_chunks/als-registry-BZqHCtq-.js.map +1 -0
  8. package/dist/_chunks/als-slots-BEEIPKYm.js +26 -0
  9. package/dist/_chunks/als-slots-BEEIPKYm.js.map +1 -0
  10. package/dist/_chunks/base-path-DaQrzbez.js +80 -0
  11. package/dist/_chunks/base-path-DaQrzbez.js.map +1 -0
  12. package/dist/_chunks/build-manifest-DWppEdLB.js +86 -0
  13. package/dist/_chunks/build-manifest-DWppEdLB.js.map +1 -0
  14. package/dist/_chunks/build-output-helper-RV_BRcF1.js +367 -0
  15. package/dist/_chunks/build-output-helper-RV_BRcF1.js.map +1 -0
  16. package/dist/_chunks/cache-api-LA3sBpUS.js +1182 -0
  17. package/dist/_chunks/cache-api-LA3sBpUS.js.map +1 -0
  18. package/dist/_chunks/canonicalize-BAWkWiKK.js +92 -0
  19. package/dist/_chunks/canonicalize-BAWkWiKK.js.map +1 -0
  20. package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
  21. package/dist/_chunks/chains-e_Buf9vg.js +267 -0
  22. package/dist/_chunks/chains-e_Buf9vg.js.map +1 -0
  23. package/dist/_chunks/classify-2Yp3xJY1.js +147 -0
  24. package/dist/_chunks/classify-2Yp3xJY1.js.map +1 -0
  25. package/dist/_chunks/cli-check-DDwCkeDY.js +252 -0
  26. package/dist/_chunks/cli-check-DDwCkeDY.js.map +1 -0
  27. package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
  28. package/dist/_chunks/cli-context-_mPttGGY.js +70 -0
  29. package/dist/_chunks/cli-context-_mPttGGY.js.map +1 -0
  30. package/dist/_chunks/cli-schema-sync-BdIebmk3.js +290 -0
  31. package/dist/_chunks/cli-schema-sync-BdIebmk3.js.map +1 -0
  32. package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
  33. package/dist/_chunks/client-dep-entries-BOkpKjj1.js +110 -0
  34. package/dist/_chunks/client-dep-entries-BOkpKjj1.js.map +1 -0
  35. package/dist/_chunks/cloudflare-Byxl8FWP.js +1333 -0
  36. package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -0
  37. package/dist/_chunks/codec-registry-oOUxugz3.js +21 -0
  38. package/dist/_chunks/codec-registry-oOUxugz3.js.map +1 -0
  39. package/dist/_chunks/codegen-Bps1sLKJ.js +432 -0
  40. package/dist/_chunks/codegen-Bps1sLKJ.js.map +1 -0
  41. package/dist/_chunks/convention-lint-ByKJ6aqD.js +590 -0
  42. package/dist/_chunks/convention-lint-ByKJ6aqD.js.map +1 -0
  43. package/dist/_chunks/dev-server-DkytOEG2.js +1 -0
  44. package/dist/_chunks/dev-server-DnODXuNM.js +2056 -0
  45. package/dist/_chunks/dev-server-DnODXuNM.js.map +1 -0
  46. package/dist/_chunks/dist-DtrJyBbw.js +386 -0
  47. package/dist/_chunks/dist-DtrJyBbw.js.map +1 -0
  48. package/dist/_chunks/error-boundary-xxxLtXt6.js +1057 -0
  49. package/dist/_chunks/error-boundary-xxxLtXt6.js.map +1 -0
  50. package/dist/_chunks/fast-hash-C-tVYrLb.js +41 -0
  51. package/dist/_chunks/fast-hash-C-tVYrLb.js.map +1 -0
  52. package/dist/_chunks/flight-source-node-0dE-t3kq.js +519 -0
  53. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +1 -0
  54. package/dist/_chunks/format-BKclgVbk.js +14 -0
  55. package/dist/_chunks/format-BKclgVbk.js.map +1 -0
  56. package/dist/_chunks/fs-identity-BRKuL215.js +207 -0
  57. package/dist/_chunks/fs-identity-BRKuL215.js.map +1 -0
  58. package/dist/_chunks/graph-cache-CYiUS2aS.js +303 -0
  59. package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -0
  60. package/dist/_chunks/href-validation-BIrxavIy.js +213 -0
  61. package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
  62. package/dist/_chunks/json-lossy-check-C8zBY2uZ.js +66 -0
  63. package/dist/_chunks/json-lossy-check-C8zBY2uZ.js.map +1 -0
  64. package/dist/_chunks/live-graph-tSWrv8eH.js +151 -0
  65. package/dist/_chunks/live-graph-tSWrv8eH.js.map +1 -0
  66. package/dist/_chunks/logger-CbLdcy-W.js +662 -0
  67. package/dist/_chunks/logger-CbLdcy-W.js.map +1 -0
  68. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → metadata-routes-B3XJNyIH.js} +70 -27
  69. package/dist/_chunks/metadata-routes-B3XJNyIH.js.map +1 -0
  70. package/dist/_chunks/navigation-root-BQfo1-kG.js +126 -0
  71. package/dist/_chunks/navigation-root-BQfo1-kG.js.map +1 -0
  72. package/dist/_chunks/node-response-Dibufw_b.js +187 -0
  73. package/dist/_chunks/node-response-Dibufw_b.js.map +1 -0
  74. package/dist/_chunks/param-value-C8TNYchQ.js +66 -0
  75. package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
  76. package/dist/_chunks/plugin-context-DxMMvjUt.js +329 -0
  77. package/dist/_chunks/plugin-context-DxMMvjUt.js.map +1 -0
  78. package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
  79. package/dist/_chunks/poison-rules-DoEhbqaY.js +110 -0
  80. package/dist/_chunks/poison-rules-DoEhbqaY.js.map +1 -0
  81. package/dist/_chunks/poison-scan-C4FgMxFl.js +99 -0
  82. package/dist/_chunks/poison-scan-C4FgMxFl.js.map +1 -0
  83. package/dist/_chunks/purge-store-Byr8XOjU.js +14 -0
  84. package/dist/_chunks/purge-store-Byr8XOjU.js.map +1 -0
  85. package/dist/_chunks/render-timeout-DOf_BBcO.js +46 -0
  86. package/dist/_chunks/render-timeout-DOf_BBcO.js.map +1 -0
  87. package/dist/_chunks/resolve-schema-CBR6Lm4i.js +50 -0
  88. package/dist/_chunks/resolve-schema-CBR6Lm4i.js.map +1 -0
  89. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js +243 -0
  90. package/dist/_chunks/rsc-cache-key-ClUiXQnK.js.map +1 -0
  91. package/dist/_chunks/rsc-media-type-DDc7duTD.js +61 -0
  92. package/dist/_chunks/rsc-media-type-DDc7duTD.js.map +1 -0
  93. package/dist/_chunks/rsc-payload-path-dffcs4jp.js +54 -0
  94. package/dist/_chunks/rsc-payload-path-dffcs4jp.js.map +1 -0
  95. package/dist/_chunks/scan-BoP17W3w.js +140 -0
  96. package/dist/_chunks/scan-BoP17W3w.js.map +1 -0
  97. package/dist/_chunks/scanner-Cb3fSjAC.js +2056 -0
  98. package/dist/_chunks/scanner-Cb3fSjAC.js.map +1 -0
  99. package/dist/_chunks/schema-bridge-C83xa9lT.js +199 -0
  100. package/dist/_chunks/schema-bridge-C83xa9lT.js.map +1 -0
  101. package/dist/_chunks/segment-classify-C539Pa2O.js +197 -0
  102. package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -0
  103. package/dist/_chunks/segment-context-xtPUGfdq.js +137 -0
  104. package/dist/_chunks/segment-context-xtPUGfdq.js.map +1 -0
  105. package/dist/_chunks/segment-keys-D5hu1hz4.js +62 -0
  106. package/dist/_chunks/segment-keys-D5hu1hz4.js.map +1 -0
  107. package/dist/_chunks/singleflight-BeVMMKi0.js +55 -0
  108. package/dist/_chunks/singleflight-BeVMMKi0.js.map +1 -0
  109. package/dist/_chunks/sizeof-QPE5nd3u.js +36 -0
  110. package/dist/_chunks/sizeof-QPE5nd3u.js.map +1 -0
  111. package/dist/_chunks/ssr-data-nA3I70_n.js +49 -0
  112. package/dist/_chunks/ssr-data-nA3I70_n.js.map +1 -0
  113. package/dist/_chunks/state-BhNGPsdi.js +50 -0
  114. package/dist/_chunks/state-BhNGPsdi.js.map +1 -0
  115. package/dist/_chunks/status-page-marker-BRX9Ib-d.js +564 -0
  116. package/dist/_chunks/status-page-marker-BRX9Ib-d.js.map +1 -0
  117. package/dist/_chunks/tree-match-6yihorhk.js +169 -0
  118. package/dist/_chunks/tree-match-6yihorhk.js.map +1 -0
  119. package/dist/_chunks/use-query-states-I3JMng6J.js +226 -0
  120. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -0
  121. package/dist/_chunks/walkers-qu8TpiLh.js +144 -0
  122. package/dist/_chunks/walkers-qu8TpiLh.js.map +1 -0
  123. package/dist/_chunks/write-file-atomic-D1qWqHb4.js +32 -0
  124. package/dist/_chunks/write-file-atomic-D1qWqHb4.js.map +1 -0
  125. package/dist/adapters/build-output-helper.d.ts +72 -0
  126. package/dist/adapters/build-output-helper.d.ts.map +1 -0
  127. package/dist/adapters/canonicalize-module.d.ts +8 -0
  128. package/dist/adapters/canonicalize-module.d.ts.map +1 -0
  129. package/dist/adapters/cloudflare-dev.d.ts +109 -0
  130. package/dist/adapters/cloudflare-dev.d.ts.map +1 -0
  131. package/dist/adapters/cloudflare-dev.js +74 -0
  132. package/dist/adapters/cloudflare-dev.js.map +1 -0
  133. package/dist/adapters/cloudflare-kv-cache.d.ts +65 -0
  134. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -0
  135. package/dist/adapters/cloudflare-kv-cache.js +123 -0
  136. package/dist/adapters/cloudflare-kv-cache.js.map +1 -0
  137. package/dist/adapters/cloudflare.d.ts +224 -24
  138. package/dist/adapters/cloudflare.d.ts.map +1 -1
  139. package/dist/adapters/cloudflare.js +1 -188
  140. package/dist/adapters/compress-module.d.ts +25 -4
  141. package/dist/adapters/compress-module.d.ts.map +1 -1
  142. package/dist/adapters/fs-identity.d.ts +63 -0
  143. package/dist/adapters/fs-identity.d.ts.map +1 -0
  144. package/dist/adapters/nitro-immutable-assets.d.ts +47 -0
  145. package/dist/adapters/nitro-immutable-assets.d.ts.map +1 -0
  146. package/dist/adapters/nitro-presets.d.ts +31 -0
  147. package/dist/adapters/nitro-presets.d.ts.map +1 -0
  148. package/dist/adapters/nitro-preview.d.ts +65 -0
  149. package/dist/adapters/nitro-preview.d.ts.map +1 -0
  150. package/dist/adapters/nitro.d.ts +69 -38
  151. package/dist/adapters/nitro.d.ts.map +1 -1
  152. package/dist/adapters/nitro.js +793 -341
  153. package/dist/adapters/nitro.js.map +1 -1
  154. package/dist/adapters/shared.d.ts +67 -0
  155. package/dist/adapters/shared.d.ts.map +1 -0
  156. package/dist/adapters/types.d.ts +124 -16
  157. package/dist/adapters/types.d.ts.map +1 -1
  158. package/dist/adapters/types.js +0 -0
  159. package/dist/analyze/chains.d.ts +124 -0
  160. package/dist/analyze/chains.d.ts.map +1 -0
  161. package/dist/analyze/classify.d.ts +153 -0
  162. package/dist/analyze/classify.d.ts.map +1 -0
  163. package/dist/analyze/crawl-entry.d.ts +17 -0
  164. package/dist/analyze/crawl-entry.d.ts.map +1 -0
  165. package/dist/analyze/crawl-entry.js +314 -0
  166. package/dist/analyze/crawl-entry.js.map +1 -0
  167. package/dist/analyze/crawl.d.ts +134 -0
  168. package/dist/analyze/crawl.d.ts.map +1 -0
  169. package/dist/analyze/graph-cache.d.ts +104 -0
  170. package/dist/analyze/graph-cache.d.ts.map +1 -0
  171. package/dist/analyze/graph-command.d.ts +43 -0
  172. package/dist/analyze/graph-command.d.ts.map +1 -0
  173. package/dist/analyze/graph-command.js +472 -0
  174. package/dist/analyze/graph-command.js.map +1 -0
  175. package/dist/analyze/live-graph.d.ts +81 -0
  176. package/dist/analyze/live-graph.d.ts.map +1 -0
  177. package/dist/analyze/poison-rules.d.ts +72 -0
  178. package/dist/analyze/poison-rules.d.ts.map +1 -0
  179. package/dist/analyze/poison-scan.d.ts +48 -0
  180. package/dist/analyze/poison-scan.d.ts.map +1 -0
  181. package/dist/analyze/scan.d.ts +73 -0
  182. package/dist/analyze/scan.d.ts.map +1 -0
  183. package/dist/cache/cache-api.d.ts +48 -0
  184. package/dist/cache/cache-api.d.ts.map +1 -0
  185. package/dist/cache/fast-hash.d.ts +5 -0
  186. package/dist/cache/fast-hash.d.ts.map +1 -1
  187. package/dist/cache/handler-store.d.ts +33 -0
  188. package/dist/cache/handler-store.d.ts.map +1 -0
  189. package/dist/cache/index.d.ts +32 -9
  190. package/dist/cache/index.d.ts.map +1 -1
  191. package/dist/cache/index.js +3 -326
  192. package/dist/cache/invalidation-epoch.d.ts +43 -0
  193. package/dist/cache/invalidation-epoch.d.ts.map +1 -0
  194. package/dist/cache/json-lossy-check.d.ts +11 -0
  195. package/dist/cache/json-lossy-check.d.ts.map +1 -0
  196. package/dist/cache/redis-handler.d.ts +141 -9
  197. package/dist/cache/redis-handler.d.ts.map +1 -1
  198. package/dist/cache/singleflight.d.ts +21 -2
  199. package/dist/cache/singleflight.d.ts.map +1 -1
  200. package/dist/cache/sizeof.d.ts +22 -0
  201. package/dist/cache/sizeof.d.ts.map +1 -0
  202. package/dist/cache/stable-stringify.d.ts +9 -0
  203. package/dist/cache/stable-stringify.d.ts.map +1 -1
  204. package/dist/cache/store.d.ts +53 -0
  205. package/dist/cache/store.d.ts.map +1 -0
  206. package/dist/cache/stores/cloudflare-kv.d.ts +38 -0
  207. package/dist/cache/stores/cloudflare-kv.d.ts.map +1 -0
  208. package/dist/cache/stores/cloudflare-kv.js +29 -0
  209. package/dist/cache/stores/cloudflare-kv.js.map +1 -0
  210. package/dist/cache/stores/memory.d.ts +42 -0
  211. package/dist/cache/stores/memory.d.ts.map +1 -0
  212. package/dist/cache/stores/memory.js +90 -0
  213. package/dist/cache/stores/memory.js.map +1 -0
  214. package/dist/cache/stores/redis.d.ts +69 -0
  215. package/dist/cache/stores/redis.d.ts.map +1 -0
  216. package/dist/cache/stores/redis.js +35 -0
  217. package/dist/cache/stores/redis.js.map +1 -0
  218. package/dist/cache/stores/vercel.d.ts +36 -0
  219. package/dist/cache/stores/vercel.d.ts.map +1 -0
  220. package/dist/cache/stores/vercel.js +33 -0
  221. package/dist/cache/stores/vercel.js.map +1 -0
  222. package/dist/cache/tag-aware-handler.d.ts +52 -0
  223. package/dist/cache/tag-aware-handler.d.ts.map +1 -0
  224. package/dist/cache/timber-cache.d.ts +21 -11
  225. package/dist/cache/timber-cache.d.ts.map +1 -1
  226. package/dist/cdn/cloudflare-purge.d.ts +23 -0
  227. package/dist/cdn/cloudflare-purge.d.ts.map +1 -0
  228. package/dist/cdn/cloudflare-purge.js +30 -0
  229. package/dist/cdn/cloudflare-purge.js.map +1 -0
  230. package/dist/cdn/fastly-purge.d.ts +25 -0
  231. package/dist/cdn/fastly-purge.d.ts.map +1 -0
  232. package/dist/cdn/fastly-purge.js +33 -0
  233. package/dist/cdn/fastly-purge.js.map +1 -0
  234. package/dist/cdn/headers.d.ts +97 -0
  235. package/dist/cdn/headers.d.ts.map +1 -0
  236. package/dist/cdn/index.d.ts +5 -0
  237. package/dist/cdn/index.d.ts.map +1 -0
  238. package/dist/cdn/index.js +94 -0
  239. package/dist/cdn/index.js.map +1 -0
  240. package/dist/cdn/purge-store.d.ts +23 -0
  241. package/dist/cdn/purge-store.d.ts.map +1 -0
  242. package/dist/cdn/workers-cache-purge.d.ts +20 -0
  243. package/dist/cdn/workers-cache-purge.d.ts.map +1 -0
  244. package/dist/cdn/workers-cache-purge.js +35 -0
  245. package/dist/cdn/workers-cache-purge.js.map +1 -0
  246. package/dist/cli-check.d.ts +133 -0
  247. package/dist/cli-check.d.ts.map +1 -0
  248. package/dist/cli-context.d.ts +54 -0
  249. package/dist/cli-context.d.ts.map +1 -0
  250. package/dist/cli-schema-sync.d.ts +59 -0
  251. package/dist/cli-schema-sync.d.ts.map +1 -0
  252. package/dist/cli.d.ts +88 -16
  253. package/dist/cli.d.ts.map +1 -1
  254. package/dist/cli.js +225 -63
  255. package/dist/cli.js.map +1 -1
  256. package/dist/client/browser-dev.d.ts +42 -2
  257. package/dist/client/browser-dev.d.ts.map +1 -1
  258. package/dist/client/browser-entry/action-dispatch.d.ts +19 -0
  259. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  260. package/dist/client/browser-entry/action-queue.d.ts +64 -0
  261. package/dist/client/browser-entry/action-queue.d.ts.map +1 -0
  262. package/dist/client/browser-entry/form-state.d.ts +22 -0
  263. package/dist/client/browser-entry/form-state.d.ts.map +1 -0
  264. package/dist/client/browser-entry/hmr.d.ts +21 -0
  265. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  266. package/dist/client/browser-entry/hydrate.d.ts +61 -0
  267. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  268. package/dist/client/browser-entry/index.d.ts +32 -0
  269. package/dist/client/browser-entry/index.d.ts.map +1 -0
  270. package/dist/client/browser-entry/post-hydration.d.ts +26 -0
  271. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  272. package/dist/client/browser-entry/router-init.d.ts +41 -0
  273. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  274. package/dist/client/browser-entry/rsc-stream.d.ts +35 -0
  275. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  276. package/dist/client/browser-entry/scroll.d.ts +28 -0
  277. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  278. package/dist/client/deny-last-resort.d.ts +29 -0
  279. package/dist/client/deny-last-resort.d.ts.map +1 -0
  280. package/dist/client/error-boundary.d.ts +58 -9
  281. package/dist/client/error-boundary.d.ts.map +1 -1
  282. package/dist/client/error-boundary.js +1 -126
  283. package/dist/client/error-reconstituter.d.ts +55 -0
  284. package/dist/client/error-reconstituter.d.ts.map +1 -0
  285. package/dist/client/form.d.ts +38 -99
  286. package/dist/client/form.d.ts.map +1 -1
  287. package/dist/client/global-context.d.ts +15 -0
  288. package/dist/client/global-context.d.ts.map +1 -0
  289. package/dist/client/history.d.ts +50 -9
  290. package/dist/client/history.d.ts.map +1 -1
  291. package/dist/client/index.d.ts +21 -33
  292. package/dist/client/index.d.ts.map +1 -1
  293. package/dist/client/index.js +432 -1227
  294. package/dist/client/index.js.map +1 -1
  295. package/dist/client/internal.d.ts +20 -0
  296. package/dist/client/internal.d.ts.map +1 -0
  297. package/dist/client/internal.js +808 -0
  298. package/dist/client/internal.js.map +1 -0
  299. package/dist/client/link.d.ts +85 -60
  300. package/dist/client/link.d.ts.map +1 -1
  301. package/dist/client/location-search.d.ts +12 -0
  302. package/dist/client/location-search.d.ts.map +1 -0
  303. package/dist/client/navigation-api.d.ts +95 -0
  304. package/dist/client/navigation-api.d.ts.map +1 -0
  305. package/dist/client/navigation-commit.d.ts +111 -0
  306. package/dist/client/navigation-commit.d.ts.map +1 -0
  307. package/dist/client/navigation-context.d.ts +54 -36
  308. package/dist/client/navigation-context.d.ts.map +1 -1
  309. package/dist/client/navigation-root.d.ts +106 -0
  310. package/dist/client/navigation-root.d.ts.map +1 -0
  311. package/dist/client/navigation-transition.d.ts +201 -0
  312. package/dist/client/navigation-transition.d.ts.map +1 -0
  313. package/dist/client/nuqs-adapter.d.ts +1 -1
  314. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  315. package/dist/client/params-context.d.ts +81 -0
  316. package/dist/client/params-context.d.ts.map +1 -0
  317. package/dist/client/react-root.d.ts +51 -0
  318. package/dist/client/react-root.d.ts.map +1 -0
  319. package/dist/client/router-effects.d.ts +199 -0
  320. package/dist/client/router-effects.d.ts.map +1 -0
  321. package/dist/client/router-lifecycle.d.ts +104 -0
  322. package/dist/client/router-lifecycle.d.ts.map +1 -0
  323. package/dist/client/router-pipeline.d.ts +85 -0
  324. package/dist/client/router-pipeline.d.ts.map +1 -0
  325. package/dist/client/router-ref.d.ts +2 -2
  326. package/dist/client/router-ref.d.ts.map +1 -1
  327. package/dist/client/router-skew.d.ts +21 -0
  328. package/dist/client/router-skew.d.ts.map +1 -0
  329. package/dist/client/router-types.d.ts +314 -0
  330. package/dist/client/router-types.d.ts.map +1 -0
  331. package/dist/client/router-url.d.ts +24 -0
  332. package/dist/client/router-url.d.ts.map +1 -0
  333. package/dist/client/router.d.ts +1 -97
  334. package/dist/client/router.d.ts.map +1 -1
  335. package/dist/client/rsc-fetch.d.ts +110 -28
  336. package/dist/client/rsc-fetch.d.ts.map +1 -1
  337. package/dist/client/segment-cache.d.ts +186 -25
  338. package/dist/client/segment-cache.d.ts.map +1 -1
  339. package/dist/client/segment-context.d.ts.map +1 -1
  340. package/dist/client/segment-outlet.d.ts +68 -0
  341. package/dist/client/segment-outlet.d.ts.map +1 -0
  342. package/dist/client/segment-update-context.d.ts +15 -0
  343. package/dist/client/segment-update-context.d.ts.map +1 -0
  344. package/dist/client/shallow-url.d.ts +10 -0
  345. package/dist/client/shallow-url.d.ts.map +1 -0
  346. package/dist/client/slot-content-cache-context.d.ts +35 -0
  347. package/dist/client/slot-content-cache-context.d.ts.map +1 -0
  348. package/dist/client/slot-context.d.ts +31 -0
  349. package/dist/client/slot-context.d.ts.map +1 -0
  350. package/dist/client/slot-outlet.d.ts +16 -0
  351. package/dist/client/slot-outlet.d.ts.map +1 -0
  352. package/dist/client/slot-provider.d.ts +25 -0
  353. package/dist/client/slot-provider.d.ts.map +1 -0
  354. package/dist/client/ssr-data.d.ts +26 -50
  355. package/dist/client/ssr-data.d.ts.map +1 -1
  356. package/dist/client/stale-client.d.ts +69 -0
  357. package/dist/client/stale-client.d.ts.map +1 -0
  358. package/dist/client/state.d.ts +21 -13
  359. package/dist/client/state.d.ts.map +1 -1
  360. package/dist/client/status-page-marker.d.ts +25 -0
  361. package/dist/client/status-page-marker.d.ts.map +1 -0
  362. package/dist/client/top-loader.d.ts +7 -6
  363. package/dist/client/top-loader.d.ts.map +1 -1
  364. package/dist/client/unload-guard.d.ts +5 -0
  365. package/dist/client/unload-guard.d.ts.map +1 -1
  366. package/dist/client/use-cookie.d.ts +12 -0
  367. package/dist/client/use-cookie.d.ts.map +1 -1
  368. package/dist/client/use-field-state.d.ts +42 -0
  369. package/dist/client/use-field-state.d.ts.map +1 -0
  370. package/dist/client/use-link-status.d.ts +5 -5
  371. package/dist/client/use-link-status.d.ts.map +1 -1
  372. package/dist/client/use-pathname.d.ts +13 -11
  373. package/dist/client/use-pathname.d.ts.map +1 -1
  374. package/dist/client/use-pending-navigation.d.ts +23 -0
  375. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  376. package/dist/client/use-query-states.d.ts +10 -4
  377. package/dist/client/use-query-states.d.ts.map +1 -1
  378. package/dist/client/use-router.d.ts +15 -8
  379. package/dist/client/use-router.d.ts.map +1 -1
  380. package/dist/client/use-search-params.d.ts +15 -8
  381. package/dist/client/use-search-params.d.ts.map +1 -1
  382. package/dist/client/use-segment-params.d.ts +55 -0
  383. package/dist/client/use-segment-params.d.ts.map +1 -0
  384. package/dist/codec.d.ts +69 -0
  385. package/dist/codec.d.ts.map +1 -0
  386. package/dist/codec.js +76 -0
  387. package/dist/codec.js.map +1 -0
  388. package/dist/config-types.d.ts +321 -0
  389. package/dist/config-types.d.ts.map +1 -0
  390. package/dist/config-validation.d.ts +68 -0
  391. package/dist/config-validation.d.ts.map +1 -0
  392. package/dist/cookies/define-cookie.d.ts +58 -25
  393. package/dist/cookies/define-cookie.d.ts.map +1 -1
  394. package/dist/cookies/index.d.ts +3 -2
  395. package/dist/cookies/index.d.ts.map +1 -1
  396. package/dist/cookies/index.js +256 -36
  397. package/dist/cookies/index.js.map +1 -1
  398. package/dist/cookies/json-cookie.d.ts +64 -0
  399. package/dist/cookies/json-cookie.d.ts.map +1 -0
  400. package/dist/cookies/validation.d.ts +34 -0
  401. package/dist/cookies/validation.d.ts.map +1 -0
  402. package/dist/dev-tools/404-page.d.ts +50 -0
  403. package/dist/dev-tools/404-page.d.ts.map +1 -0
  404. package/dist/dev-tools/browser-logs.d.ts +40 -0
  405. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  406. package/dist/dev-tools/dev-page-shell.d.ts +95 -0
  407. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  408. package/dist/dev-tools/error-page.d.ts +32 -0
  409. package/dist/dev-tools/error-page.d.ts.map +1 -0
  410. package/dist/dev-tools/holding-server.d.ts +46 -0
  411. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  412. package/dist/dev-tools/hydration-overlay.d.ts +11 -0
  413. package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
  414. package/dist/dev-tools/index.d.ts +31 -0
  415. package/dist/dev-tools/index.d.ts.map +1 -0
  416. package/dist/dev-tools/instrumentation.d.ts +74 -0
  417. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  418. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  419. package/dist/dev-tools/logger.d.ts.map +1 -0
  420. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +17 -3
  421. package/dist/dev-tools/logs.d.ts.map +1 -0
  422. package/dist/{plugins/dev-error-overlay.d.ts → dev-tools/overlay.d.ts} +15 -25
  423. package/dist/dev-tools/overlay.d.ts.map +1 -0
  424. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  425. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  426. package/dist/dev-tools/terminal.d.ts +28 -0
  427. package/dist/dev-tools/terminal.d.ts.map +1 -0
  428. package/dist/fonts/ast-walk.d.ts +68 -0
  429. package/dist/fonts/ast-walk.d.ts.map +1 -0
  430. package/dist/fonts/ast.d.ts +112 -8
  431. package/dist/fonts/ast.d.ts.map +1 -1
  432. package/dist/fonts/bundle.d.ts +50 -0
  433. package/dist/fonts/bundle.d.ts.map +1 -0
  434. package/dist/fonts/css.d.ts +1 -1
  435. package/dist/fonts/dev-middleware.d.ts +22 -0
  436. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  437. package/dist/fonts/fallbacks.d.ts +0 -7
  438. package/dist/fonts/fallbacks.d.ts.map +1 -1
  439. package/dist/fonts/google.d.ts +5 -3
  440. package/dist/fonts/google.d.ts.map +1 -1
  441. package/dist/fonts/local.d.ts +5 -5
  442. package/dist/fonts/local.d.ts.map +1 -1
  443. package/dist/fonts/paths.d.ts +43 -0
  444. package/dist/fonts/paths.d.ts.map +1 -0
  445. package/dist/fonts/pipeline.d.ts +177 -0
  446. package/dist/fonts/pipeline.d.ts.map +1 -0
  447. package/dist/fonts/transform.d.ts +82 -0
  448. package/dist/fonts/transform.d.ts.map +1 -0
  449. package/dist/fonts/types.d.ts +47 -1
  450. package/dist/fonts/types.d.ts.map +1 -1
  451. package/dist/fonts/virtual-modules.d.ts +77 -0
  452. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  453. package/dist/index.d.ts +35 -181
  454. package/dist/index.d.ts.map +1 -1
  455. package/dist/index.js +8877 -14232
  456. package/dist/index.js.map +1 -1
  457. package/dist/params/codec-registry.d.ts +26 -0
  458. package/dist/params/codec-registry.d.ts.map +1 -0
  459. package/dist/params/define-schema.d.ts +81 -0
  460. package/dist/params/define-schema.d.ts.map +1 -0
  461. package/dist/params/index.d.ts +5 -0
  462. package/dist/params/index.d.ts.map +1 -0
  463. package/dist/params/index.js +34 -0
  464. package/dist/params/index.js.map +1 -0
  465. package/dist/params/resolve-schema.d.ts +34 -0
  466. package/dist/params/resolve-schema.d.ts.map +1 -0
  467. package/dist/plugin-context.d.ts +262 -0
  468. package/dist/plugin-context.d.ts.map +1 -0
  469. package/dist/plugins/build-manifest.d.ts +7 -3
  470. package/dist/plugins/build-manifest.d.ts.map +1 -1
  471. package/dist/plugins/build-report.d.ts +61 -11
  472. package/dist/plugins/build-report.d.ts.map +1 -1
  473. package/dist/plugins/cache.d.ts +64 -0
  474. package/dist/plugins/cache.d.ts.map +1 -0
  475. package/dist/plugins/callsite-ast.d.ts +117 -0
  476. package/dist/plugins/callsite-ast.d.ts.map +1 -0
  477. package/dist/plugins/callsite-jsx.d.ts +35 -0
  478. package/dist/plugins/callsite-jsx.d.ts.map +1 -0
  479. package/dist/plugins/chunks.d.ts +11 -4
  480. package/dist/plugins/chunks.d.ts.map +1 -1
  481. package/dist/plugins/client-chunks.d.ts +40 -0
  482. package/dist/plugins/client-chunks.d.ts.map +1 -0
  483. package/dist/plugins/client-dep-entries.d.ts +80 -0
  484. package/dist/plugins/client-dep-entries.d.ts.map +1 -0
  485. package/dist/plugins/cloudflare-wasm.d.ts +21 -0
  486. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  487. package/dist/plugins/content.d.ts +1 -1
  488. package/dist/plugins/content.d.ts.map +1 -1
  489. package/dist/plugins/dev-discovery.d.ts +123 -0
  490. package/dist/plugins/dev-discovery.d.ts.map +1 -0
  491. package/dist/plugins/dev-server.d.ts +24 -1
  492. package/dist/plugins/dev-server.d.ts.map +1 -1
  493. package/dist/plugins/encryption-runtime.d.ts +13 -0
  494. package/dist/plugins/encryption-runtime.d.ts.map +1 -0
  495. package/dist/plugins/entries.d.ts +35 -4
  496. package/dist/plugins/entries.d.ts.map +1 -1
  497. package/dist/plugins/fonts.d.ts +35 -74
  498. package/dist/plugins/fonts.d.ts.map +1 -1
  499. package/dist/plugins/graph-endpoint.d.ts +112 -0
  500. package/dist/plugins/graph-endpoint.d.ts.map +1 -0
  501. package/dist/plugins/mdx.d.ts +18 -5
  502. package/dist/plugins/mdx.d.ts.map +1 -1
  503. package/dist/plugins/post-build.d.ts +110 -0
  504. package/dist/plugins/post-build.d.ts.map +1 -0
  505. package/dist/plugins/prebuilt-capture.d.ts +67 -0
  506. package/dist/plugins/prebuilt-capture.d.ts.map +1 -0
  507. package/dist/plugins/prebuilt-options-analysis.d.ts +40 -0
  508. package/dist/plugins/prebuilt-options-analysis.d.ts.map +1 -0
  509. package/dist/plugins/prebuilt.d.ts +98 -0
  510. package/dist/plugins/prebuilt.d.ts.map +1 -0
  511. package/dist/plugins/prerender-sugar.d.ts +39 -0
  512. package/dist/plugins/prerender-sugar.d.ts.map +1 -0
  513. package/dist/plugins/react-resolve.d.ts +49 -0
  514. package/dist/plugins/react-resolve.d.ts.map +1 -0
  515. package/dist/plugins/request-dep/analysis.d.ts +106 -0
  516. package/dist/plugins/request-dep/analysis.d.ts.map +1 -0
  517. package/dist/plugins/request-dep/index.d.ts +75 -0
  518. package/dist/plugins/request-dep/index.d.ts.map +1 -0
  519. package/dist/plugins/request-dep/origin.d.ts +61 -0
  520. package/dist/plugins/request-dep/origin.d.ts.map +1 -0
  521. package/dist/plugins/routing.d.ts +1 -1
  522. package/dist/plugins/routing.d.ts.map +1 -1
  523. package/dist/plugins/rsc-assets-manifest.d.ts +33 -0
  524. package/dist/plugins/rsc-assets-manifest.d.ts.map +1 -0
  525. package/dist/plugins/server-bundle.d.ts +1 -1
  526. package/dist/plugins/server-bundle.d.ts.map +1 -1
  527. package/dist/plugins/shims.d.ts +29 -5
  528. package/dist/plugins/shims.d.ts.map +1 -1
  529. package/dist/plugins/static-build.d.ts +246 -26
  530. package/dist/plugins/static-build.d.ts.map +1 -1
  531. package/dist/routing/codegen-shared.d.ts +26 -0
  532. package/dist/routing/codegen-shared.d.ts.map +1 -0
  533. package/dist/routing/codegen-types.d.ts +61 -0
  534. package/dist/routing/codegen-types.d.ts.map +1 -0
  535. package/dist/routing/codegen-write.d.ts +42 -0
  536. package/dist/routing/codegen-write.d.ts.map +1 -0
  537. package/dist/routing/codegen.d.ts +8 -3
  538. package/dist/routing/codegen.d.ts.map +1 -1
  539. package/dist/routing/collision-probe.d.ts +104 -0
  540. package/dist/routing/collision-probe.d.ts.map +1 -0
  541. package/dist/routing/collision-spaces.d.ts +26 -0
  542. package/dist/routing/collision-spaces.d.ts.map +1 -0
  543. package/dist/routing/convention-lint.d.ts +55 -0
  544. package/dist/routing/convention-lint.d.ts.map +1 -0
  545. package/dist/routing/export-detect.d.ts +91 -0
  546. package/dist/routing/export-detect.d.ts.map +1 -0
  547. package/dist/routing/file-cache.d.ts +8 -0
  548. package/dist/routing/file-cache.d.ts.map +1 -0
  549. package/dist/routing/index.d.ts +13 -7
  550. package/dist/routing/index.d.ts.map +1 -1
  551. package/dist/routing/index.js +5 -2
  552. package/dist/routing/interception-overlap.d.ts +35 -0
  553. package/dist/routing/interception-overlap.d.ts.map +1 -0
  554. package/dist/routing/interception.d.ts +234 -10
  555. package/dist/routing/interception.d.ts.map +1 -1
  556. package/dist/routing/link-codegen.d.ts +105 -0
  557. package/dist/routing/link-codegen.d.ts.map +1 -0
  558. package/dist/routing/manifest-codegen.d.ts +26 -0
  559. package/dist/routing/manifest-codegen.d.ts.map +1 -0
  560. package/dist/routing/scanner.d.ts +14 -10
  561. package/dist/routing/scanner.d.ts.map +1 -1
  562. package/dist/routing/schema-validation.d.ts +35 -0
  563. package/dist/routing/schema-validation.d.ts.map +1 -0
  564. package/dist/routing/segment-classify.d.ts +114 -0
  565. package/dist/routing/segment-classify.d.ts.map +1 -0
  566. package/dist/routing/segment-codegen.d.ts +38 -0
  567. package/dist/routing/segment-codegen.d.ts.map +1 -0
  568. package/dist/routing/segment-keys.d.ts +118 -0
  569. package/dist/routing/segment-keys.d.ts.map +1 -0
  570. package/dist/routing/slot-placement.d.ts +48 -0
  571. package/dist/routing/slot-placement.d.ts.map +1 -0
  572. package/dist/routing/types.d.ts +81 -26
  573. package/dist/routing/types.d.ts.map +1 -1
  574. package/dist/routing/walkers.d.ts +57 -0
  575. package/dist/routing/walkers.d.ts.map +1 -0
  576. package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
  577. package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
  578. package/dist/rsc-runtime/render-flight.d.ts +14 -0
  579. package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
  580. package/dist/rsc-runtime/rsc.d.ts +6 -2
  581. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  582. package/dist/rsc-runtime/ssr.d.ts +8 -0
  583. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  584. package/dist/rsc-runtime/transforms.d.ts +13 -0
  585. package/dist/rsc-runtime/transforms.d.ts.map +1 -0
  586. package/dist/schema-bridge.d.ts +145 -0
  587. package/dist/schema-bridge.d.ts.map +1 -0
  588. package/dist/search-params/define.d.ts +262 -0
  589. package/dist/search-params/define.d.ts.map +1 -0
  590. package/dist/search-params/index.d.ts +3 -7
  591. package/dist/search-params/index.d.ts.map +1 -1
  592. package/dist/search-params/index.js +179 -360
  593. package/dist/search-params/index.js.map +1 -1
  594. package/dist/search-params/parse-total.d.ts +81 -0
  595. package/dist/search-params/parse-total.d.ts.map +1 -0
  596. package/dist/search-params/serialize-equal.d.ts +9 -0
  597. package/dist/search-params/serialize-equal.d.ts.map +1 -0
  598. package/dist/search-params/wrappers.d.ts +76 -0
  599. package/dist/search-params/wrappers.d.ts.map +1 -0
  600. package/dist/server/access-gate.d.ts +98 -10
  601. package/dist/server/access-gate.d.ts.map +1 -1
  602. package/dist/server/action-client.d.ts +20 -133
  603. package/dist/server/action-client.d.ts.map +1 -1
  604. package/dist/server/action-encryption.d.ts +76 -0
  605. package/dist/server/action-encryption.d.ts.map +1 -0
  606. package/dist/server/action-handler.d.ts +58 -11
  607. package/dist/server/action-handler.d.ts.map +1 -1
  608. package/dist/server/action-schema.d.ts +126 -0
  609. package/dist/server/action-schema.d.ts.map +1 -0
  610. package/dist/server/action-types.d.ts +108 -0
  611. package/dist/server/action-types.d.ts.map +1 -0
  612. package/dist/server/actions.d.ts +78 -40
  613. package/dist/server/actions.d.ts.map +1 -1
  614. package/dist/server/als-registry.d.ts +189 -17
  615. package/dist/server/als-registry.d.ts.map +1 -1
  616. package/dist/server/body-limits.d.ts.map +1 -1
  617. package/dist/server/build-manifest.d.ts +25 -30
  618. package/dist/server/build-manifest.d.ts.map +1 -1
  619. package/dist/server/canonicalize.d.ts +32 -0
  620. package/dist/server/canonicalize.d.ts.map +1 -1
  621. package/dist/server/chain-url-parts.d.ts +82 -0
  622. package/dist/server/chain-url-parts.d.ts.map +1 -0
  623. package/dist/server/children-interception.d.ts +49 -0
  624. package/dist/server/children-interception.d.ts.map +1 -0
  625. package/dist/server/client-error-message.d.ts +12 -0
  626. package/dist/server/client-error-message.d.ts.map +1 -0
  627. package/dist/server/coalesce-tick.d.ts +40 -0
  628. package/dist/server/coalesce-tick.d.ts.map +1 -0
  629. package/dist/server/compress.d.ts +2 -0
  630. package/dist/server/compress.d.ts.map +1 -1
  631. package/dist/server/cookie-context.d.ts +149 -0
  632. package/dist/server/cookie-context.d.ts.map +1 -0
  633. package/dist/server/cookie-parsing.d.ts +65 -0
  634. package/dist/server/cookie-parsing.d.ts.map +1 -0
  635. package/dist/server/csp-nonce.d.ts +36 -0
  636. package/dist/server/csp-nonce.d.ts.map +1 -0
  637. package/dist/server/csrf.d.ts +58 -15
  638. package/dist/server/csrf.d.ts.map +1 -1
  639. package/dist/server/debug.d.ts +0 -1
  640. package/dist/server/debug.d.ts.map +1 -1
  641. package/dist/server/default-logger.d.ts +23 -0
  642. package/dist/server/default-logger.d.ts.map +1 -0
  643. package/dist/server/default-status-page.d.ts +45 -0
  644. package/dist/server/default-status-page.d.ts.map +1 -0
  645. package/dist/server/deny-boundary.d.ts +257 -0
  646. package/dist/server/deny-boundary.d.ts.map +1 -0
  647. package/dist/server/deny-renderer.d.ts +22 -15
  648. package/dist/server/deny-renderer.d.ts.map +1 -1
  649. package/dist/server/early-hints-sender.d.ts.map +1 -1
  650. package/dist/server/early-hints.d.ts +14 -12
  651. package/dist/server/early-hints.d.ts.map +1 -1
  652. package/dist/server/error-boundary-wrapper.d.ts +102 -10
  653. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  654. package/dist/server/error-response-headers.d.ts +3 -0
  655. package/dist/server/error-response-headers.d.ts.map +1 -0
  656. package/dist/server/fallback-error.d.ts +19 -7
  657. package/dist/server/fallback-error.d.ts.map +1 -1
  658. package/dist/server/flight-injection-state.d.ts +66 -0
  659. package/dist/server/flight-injection-state.d.ts.map +1 -0
  660. package/dist/server/flight-injector-core.d.ts +125 -0
  661. package/dist/server/flight-injector-core.d.ts.map +1 -0
  662. package/dist/server/flight-scripts.d.ts +63 -0
  663. package/dist/server/flight-scripts.d.ts.map +1 -0
  664. package/dist/server/flight-source-node.d.ts +105 -0
  665. package/dist/server/flight-source-node.d.ts.map +1 -0
  666. package/dist/server/flight-source.d.ts +136 -0
  667. package/dist/server/flight-source.d.ts.map +1 -0
  668. package/dist/server/form-data.d.ts +59 -2
  669. package/dist/server/form-data.d.ts.map +1 -1
  670. package/dist/server/form-state-flight.d.ts +32 -0
  671. package/dist/server/form-state-flight.d.ts.map +1 -0
  672. package/dist/server/head-response.d.ts +35 -0
  673. package/dist/server/head-response.d.ts.map +1 -0
  674. package/dist/server/html-injector-core.d.ts +169 -0
  675. package/dist/server/html-injector-core.d.ts.map +1 -0
  676. package/dist/server/html-injectors.d.ts +77 -47
  677. package/dist/server/html-injectors.d.ts.map +1 -1
  678. package/dist/server/index.d.ts +16 -54
  679. package/dist/server/index.d.ts.map +1 -1
  680. package/dist/server/index.js +638 -3021
  681. package/dist/server/index.js.map +1 -1
  682. package/dist/server/instrumentation.d.ts +11 -4
  683. package/dist/server/instrumentation.d.ts.map +1 -1
  684. package/dist/server/internal.d.ts +47 -0
  685. package/dist/server/internal.d.ts.map +1 -0
  686. package/dist/server/internal.js +4649 -0
  687. package/dist/server/internal.js.map +1 -0
  688. package/dist/server/json-status-response.d.ts +34 -0
  689. package/dist/server/json-status-response.d.ts.map +1 -0
  690. package/dist/server/logger.d.ts +79 -7
  691. package/dist/server/logger.d.ts.map +1 -1
  692. package/dist/server/metadata-collector.d.ts +75 -0
  693. package/dist/server/metadata-collector.d.ts.map +1 -0
  694. package/dist/server/metadata-platform.d.ts +2 -2
  695. package/dist/server/metadata-render.d.ts +2 -2
  696. package/dist/server/metadata-render.d.ts.map +1 -1
  697. package/dist/server/metadata-route-links.d.ts +70 -0
  698. package/dist/server/metadata-route-links.d.ts.map +1 -0
  699. package/dist/server/metadata-routes.d.ts +47 -11
  700. package/dist/server/metadata-routes.d.ts.map +1 -1
  701. package/dist/server/metadata-social.d.ts +2 -2
  702. package/dist/server/metadata.d.ts +10 -2
  703. package/dist/server/metadata.d.ts.map +1 -1
  704. package/dist/server/middleware-runner.d.ts +20 -5
  705. package/dist/server/middleware-runner.d.ts.map +1 -1
  706. package/dist/server/node-body-response.d.ts +55 -0
  707. package/dist/server/node-body-response.d.ts.map +1 -0
  708. package/dist/server/node-response.d.ts +62 -0
  709. package/dist/server/node-response.d.ts.map +1 -0
  710. package/dist/server/node-stream-transforms.d.ts +108 -0
  711. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  712. package/dist/server/node-streams-platform.d.ts +21 -0
  713. package/dist/server/node-streams-platform.d.ts.map +1 -0
  714. package/dist/server/nuqs-ssr-provider.d.ts +7 -3
  715. package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
  716. package/dist/server/param-coercion.d.ts +83 -0
  717. package/dist/server/param-coercion.d.ts.map +1 -0
  718. package/dist/server/pipeline-helpers.d.ts +224 -0
  719. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  720. package/dist/server/pipeline-interception.d.ts +70 -9
  721. package/dist/server/pipeline-interception.d.ts.map +1 -1
  722. package/dist/server/pipeline-metadata.d.ts +16 -1
  723. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  724. package/dist/server/pipeline-outcome.d.ts +59 -0
  725. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  726. package/dist/server/pipeline-phases.d.ts +70 -0
  727. package/dist/server/pipeline-phases.d.ts.map +1 -0
  728. package/dist/server/pipeline.d.ts +161 -23
  729. package/dist/server/pipeline.d.ts.map +1 -1
  730. package/dist/server/port-resolution.d.ts +22 -0
  731. package/dist/server/port-resolution.d.ts.map +1 -0
  732. package/dist/server/prebuilt/cache-key.d.ts +63 -0
  733. package/dist/server/prebuilt/cache-key.d.ts.map +1 -0
  734. package/dist/server/prebuilt/capture-render.d.ts +25 -0
  735. package/dist/server/prebuilt/capture-render.d.ts.map +1 -0
  736. package/dist/server/prebuilt/capture-routes.d.ts +37 -0
  737. package/dist/server/prebuilt/capture-routes.d.ts.map +1 -0
  738. package/dist/server/prebuilt/capture-state.d.ts +101 -0
  739. package/dist/server/prebuilt/capture-state.d.ts.map +1 -0
  740. package/dist/server/prebuilt/key-discipline.d.ts +52 -0
  741. package/dist/server/prebuilt/key-discipline.d.ts.map +1 -0
  742. package/dist/server/prebuilt/lifetime.d.ts +38 -0
  743. package/dist/server/prebuilt/lifetime.d.ts.map +1 -0
  744. package/dist/server/prebuilt/manifest-tag-index.d.ts +27 -0
  745. package/dist/server/prebuilt/manifest-tag-index.d.ts.map +1 -0
  746. package/dist/server/prebuilt/overlay.d.ts +100 -0
  747. package/dist/server/prebuilt/overlay.d.ts.map +1 -0
  748. package/dist/server/prebuilt/payload-source.d.ts +79 -0
  749. package/dist/server/prebuilt/payload-source.d.ts.map +1 -0
  750. package/dist/server/prebuilt/slots.d.ts +106 -0
  751. package/dist/server/prebuilt/slots.d.ts.map +1 -0
  752. package/dist/server/prebuilt/synthetic-store.d.ts +67 -0
  753. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -0
  754. package/dist/server/prebuilt-builder.d.ts +121 -0
  755. package/dist/server/prebuilt-builder.d.ts.map +1 -0
  756. package/dist/server/prebuilt-runtime.d.ts +110 -0
  757. package/dist/server/prebuilt-runtime.d.ts.map +1 -0
  758. package/dist/server/primitives.d.ts +101 -90
  759. package/dist/server/primitives.d.ts.map +1 -1
  760. package/dist/server/publish-params.d.ts +33 -0
  761. package/dist/server/publish-params.d.ts.map +1 -0
  762. package/dist/server/react-cache-bridge.d.ts +59 -0
  763. package/dist/server/react-cache-bridge.d.ts.map +1 -0
  764. package/dist/server/react-cache-scope.d.ts +49 -0
  765. package/dist/server/react-cache-scope.d.ts.map +1 -0
  766. package/dist/server/render-timeout.d.ts +66 -0
  767. package/dist/server/render-timeout.d.ts.map +1 -0
  768. package/dist/server/render-utils.d.ts +35 -0
  769. package/dist/server/render-utils.d.ts.map +1 -0
  770. package/dist/server/request-context.d.ts +153 -103
  771. package/dist/server/request-context.d.ts.map +1 -1
  772. package/dist/server/request-dep.d.ts +15 -0
  773. package/dist/server/request-dep.d.ts.map +1 -0
  774. package/dist/server/response-cache-policy.d.ts +3 -0
  775. package/dist/server/response-cache-policy.d.ts.map +1 -0
  776. package/dist/server/route-element-builder.d.ts +57 -30
  777. package/dist/server/route-element-builder.d.ts.map +1 -1
  778. package/dist/server/route-element-helpers.d.ts +12 -0
  779. package/dist/server/route-element-helpers.d.ts.map +1 -0
  780. package/dist/server/route-handler.d.ts +1 -1
  781. package/dist/server/route-handler.d.ts.map +1 -1
  782. package/dist/server/route-matcher.d.ts +62 -38
  783. package/dist/server/route-matcher.d.ts.map +1 -1
  784. package/dist/server/route-module-loader.d.ts +37 -0
  785. package/dist/server/route-module-loader.d.ts.map +1 -0
  786. package/dist/server/rsc-cache-key-guard.d.ts +78 -0
  787. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -0
  788. package/dist/server/rsc-entry/action-dispatcher.d.ts +65 -0
  789. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -0
  790. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  791. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  792. package/dist/server/rsc-entry/api-handler.d.ts +19 -3
  793. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  794. package/dist/server/rsc-entry/deny-fallback.d.ts +55 -0
  795. package/dist/server/rsc-entry/deny-fallback.d.ts.map +1 -0
  796. package/dist/server/rsc-entry/error-renderer.d.ts +35 -21
  797. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  798. package/dist/server/rsc-entry/helpers.d.ts +14 -59
  799. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  800. package/dist/server/rsc-entry/index.d.ts +30 -6
  801. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  802. package/dist/server/rsc-entry/render-route.d.ts +55 -0
  803. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  804. package/dist/server/rsc-entry/render-signals.d.ts +65 -0
  805. package/dist/server/rsc-entry/render-signals.d.ts.map +1 -0
  806. package/dist/server/rsc-entry/revalidate-renderer.d.ts +98 -0
  807. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  808. package/dist/server/rsc-entry/rsc-payload.d.ts +38 -11
  809. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  810. package/dist/server/rsc-entry/rsc-stream.d.ts +18 -31
  811. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  812. package/dist/server/rsc-entry/ssr-bridge.d.ts +7 -2
  813. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  814. package/dist/server/rsc-entry/ssr-renderer.d.ts +52 -8
  815. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  816. package/dist/server/rsc-error-envelope.d.ts +11 -0
  817. package/dist/server/rsc-error-envelope.d.ts.map +1 -0
  818. package/dist/server/safe-load.d.ts +39 -0
  819. package/dist/server/safe-load.d.ts.map +1 -0
  820. package/dist/server/schema-introspection.d.ts +68 -0
  821. package/dist/server/schema-introspection.d.ts.map +1 -0
  822. package/dist/server/sensitive-fields.d.ts +88 -0
  823. package/dist/server/sensitive-fields.d.ts.map +1 -0
  824. package/dist/server/signal-identity.d.ts +43 -0
  825. package/dist/server/signal-identity.d.ts.map +1 -0
  826. package/dist/server/sitemap-generator.d.ts +130 -0
  827. package/dist/server/sitemap-generator.d.ts.map +1 -0
  828. package/dist/server/sitemap-handler.d.ts +22 -0
  829. package/dist/server/sitemap-handler.d.ts.map +1 -0
  830. package/dist/server/skippable-prefix.d.ts +29 -0
  831. package/dist/server/skippable-prefix.d.ts.map +1 -0
  832. package/dist/server/slot-interception.d.ts +80 -0
  833. package/dist/server/slot-interception.d.ts.map +1 -0
  834. package/dist/server/slot-resolver.d.ts +138 -7
  835. package/dist/server/slot-resolver.d.ts.map +1 -1
  836. package/dist/server/slot-subtree-contain.d.ts +54 -0
  837. package/dist/server/slot-subtree-contain.d.ts.map +1 -0
  838. package/dist/server/ssr-bridge-types.d.ts +213 -0
  839. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  840. package/dist/server/ssr-entry.d.ts +15 -51
  841. package/dist/server/ssr-entry.d.ts.map +1 -1
  842. package/dist/server/ssr-form-state.d.ts +30 -0
  843. package/dist/server/ssr-form-state.d.ts.map +1 -0
  844. package/dist/server/ssr-render.d.ts +59 -32
  845. package/dist/server/ssr-render.d.ts.map +1 -1
  846. package/dist/server/ssr-wrappers.d.ts +93 -0
  847. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  848. package/dist/server/state-tree-diff.d.ts +44 -9
  849. package/dist/server/state-tree-diff.d.ts.map +1 -1
  850. package/dist/server/static-generator.d.ts +112 -0
  851. package/dist/server/static-generator.d.ts.map +1 -0
  852. package/dist/server/static-not-found.d.ts +52 -0
  853. package/dist/server/static-not-found.d.ts.map +1 -0
  854. package/dist/server/status-code-resolver.d.ts +26 -15
  855. package/dist/server/status-code-resolver.d.ts.map +1 -1
  856. package/dist/server/stream-utils.d.ts +93 -0
  857. package/dist/server/stream-utils.d.ts.map +1 -0
  858. package/dist/server/tracing.d.ts +57 -26
  859. package/dist/server/tracing.d.ts.map +1 -1
  860. package/dist/server/tree-match.d.ts +59 -0
  861. package/dist/server/tree-match.d.ts.map +1 -0
  862. package/dist/server/types.d.ts +89 -8
  863. package/dist/server/types.d.ts.map +1 -1
  864. package/dist/server/utils/element-type.d.ts +50 -0
  865. package/dist/server/utils/element-type.d.ts.map +1 -0
  866. package/dist/server/utils/escape-html.d.ts +14 -0
  867. package/dist/server/utils/escape-html.d.ts.map +1 -0
  868. package/dist/server/version-skew.d.ts +61 -0
  869. package/dist/server/version-skew.d.ts.map +1 -0
  870. package/dist/server/workers-cache-bridge.d.ts +26 -0
  871. package/dist/server/workers-cache-bridge.d.ts.map +1 -0
  872. package/dist/shared/als-slots.d.ts +42 -0
  873. package/dist/shared/als-slots.d.ts.map +1 -0
  874. package/dist/shared/base-path.d.ts +56 -0
  875. package/dist/shared/base-path.d.ts.map +1 -0
  876. package/dist/shared/csrf-reject.d.ts +16 -0
  877. package/dist/shared/csrf-reject.d.ts.map +1 -0
  878. package/dist/shared/error-digest.d.ts +28 -0
  879. package/dist/shared/error-digest.d.ts.map +1 -0
  880. package/dist/shared/flight-base64.d.ts +13 -0
  881. package/dist/shared/flight-base64.d.ts.map +1 -0
  882. package/dist/shared/flight-segment.d.ts +18 -0
  883. package/dist/shared/flight-segment.d.ts.map +1 -0
  884. package/dist/shared/form-state-flight.d.ts +32 -0
  885. package/dist/shared/form-state-flight.d.ts.map +1 -0
  886. package/dist/shared/href-validation.d.ts +49 -0
  887. package/dist/shared/href-validation.d.ts.map +1 -0
  888. package/dist/shared/merge-search-params.d.ts +22 -0
  889. package/dist/shared/merge-search-params.d.ts.map +1 -0
  890. package/dist/shared/param-value.d.ts +104 -0
  891. package/dist/shared/param-value.d.ts.map +1 -0
  892. package/dist/shared/payload-root.d.ts +110 -0
  893. package/dist/shared/payload-root.d.ts.map +1 -0
  894. package/dist/shared/redirect-type.d.ts +17 -0
  895. package/dist/shared/redirect-type.d.ts.map +1 -0
  896. package/dist/shared/rsc-cache-key.d.ts +163 -0
  897. package/dist/shared/rsc-cache-key.d.ts.map +1 -0
  898. package/dist/shared/rsc-error-envelope.d.ts +16 -0
  899. package/dist/shared/rsc-error-envelope.d.ts.map +1 -0
  900. package/dist/shared/rsc-manifest.d.ts +28 -0
  901. package/dist/shared/rsc-manifest.d.ts.map +1 -0
  902. package/dist/shared/rsc-media-type.d.ts +52 -0
  903. package/dist/shared/rsc-media-type.d.ts.map +1 -0
  904. package/dist/shared/rsc-payload-path.d.ts +48 -0
  905. package/dist/shared/rsc-payload-path.d.ts.map +1 -0
  906. package/dist/shared/segment-info.d.ts +66 -0
  907. package/dist/shared/segment-info.d.ts.map +1 -0
  908. package/dist/shared/slot-params.d.ts +52 -0
  909. package/dist/shared/slot-params.d.ts.map +1 -0
  910. package/dist/shared/static-platform-files.d.ts +71 -0
  911. package/dist/shared/static-platform-files.d.ts.map +1 -0
  912. package/dist/shared/status-reason-phrase.d.ts +26 -0
  913. package/dist/shared/status-reason-phrase.d.ts.map +1 -0
  914. package/dist/shims/font-google.d.ts +1 -1
  915. package/dist/shims/font-google.d.ts.map +1 -1
  916. package/dist/shims/font-google.js +42 -0
  917. package/dist/shims/font-google.js.map +1 -0
  918. package/dist/shims/font-local.d.ts +26 -0
  919. package/dist/shims/font-local.d.ts.map +1 -0
  920. package/dist/shims/font-local.js +20 -0
  921. package/dist/shims/font-local.js.map +1 -0
  922. package/dist/shims/headers.d.ts +53 -1
  923. package/dist/shims/headers.d.ts.map +1 -1
  924. package/dist/shims/image.d.ts +120 -120
  925. package/dist/shims/image.d.ts.map +1 -1
  926. package/dist/shims/navigation-client.d.ts +25 -12
  927. package/dist/shims/navigation-client.d.ts.map +1 -1
  928. package/dist/shims/navigation-rsc.d.ts +21 -0
  929. package/dist/shims/navigation-rsc.d.ts.map +1 -0
  930. package/dist/shims/navigation.d.ts +10 -5
  931. package/dist/shims/navigation.d.ts.map +1 -1
  932. package/dist/utils/state-machine.d.ts +80 -0
  933. package/dist/utils/state-machine.d.ts.map +1 -0
  934. package/dist/utils/write-file-atomic.d.ts +17 -0
  935. package/dist/utils/write-file-atomic.d.ts.map +1 -0
  936. package/docs/api/30-api-server.mdx +239 -0
  937. package/docs/api/31-api-client.mdx +199 -0
  938. package/docs/api/32-api-cache.mdx +339 -0
  939. package/docs/api/33-api-search-params.mdx +176 -0
  940. package/docs/api/34-api-config.mdx +359 -0
  941. package/docs/api/35-api-typescript.mdx +91 -0
  942. package/docs/api/36-cli.mdx +206 -0
  943. package/docs/learn/00-introduction.mdx +109 -0
  944. package/docs/learn/01-quick-start.mdx +94 -0
  945. package/docs/learn/02-pages-and-layouts.mdx +147 -0
  946. package/docs/learn/03-fetching-data.mdx +227 -0
  947. package/docs/learn/04-access-control.mdx +115 -0
  948. package/docs/learn/05-the-flush-point.mdx +175 -0
  949. package/docs/learn/06-typed-params.mdx +275 -0
  950. package/docs/learn/07-typed-routes.mdx +108 -0
  951. package/docs/learn/08-forms-and-actions.mdx +260 -0
  952. package/docs/learn/09-streaming.mdx +140 -0
  953. package/docs/learn/10-caching.mdx +270 -0
  954. package/docs/learn/11-middleware.mdx +164 -0
  955. package/docs/learn/12-error-handling.mdx +192 -0
  956. package/docs/learn/13-deploying.mdx +289 -0
  957. package/llms.txt +55 -0
  958. package/package.json +120 -29
  959. package/src/adapters/build-output-helper.ts +353 -0
  960. package/src/adapters/canonicalize-module.ts +29 -0
  961. package/src/adapters/cloudflare-dev.ts +183 -0
  962. package/src/adapters/cloudflare-kv-cache.ts +207 -0
  963. package/src/adapters/cloudflare.ts +809 -150
  964. package/src/adapters/compress-module.ts +110 -86
  965. package/src/adapters/fs-identity.ts +155 -0
  966. package/src/adapters/nitro-immutable-assets.ts +142 -0
  967. package/src/adapters/nitro-presets.ts +124 -0
  968. package/src/adapters/nitro-preview.ts +533 -0
  969. package/src/adapters/nitro.ts +331 -445
  970. package/src/adapters/raw-imports.d.ts +5 -0
  971. package/src/adapters/shared.ts +283 -0
  972. package/src/adapters/types.ts +129 -17
  973. package/src/adapters/wrangler.d.ts +7 -0
  974. package/src/analyze/chains.ts +411 -0
  975. package/src/analyze/classify.ts +259 -0
  976. package/src/analyze/crawl-entry.ts +68 -0
  977. package/src/analyze/crawl.ts +500 -0
  978. package/src/analyze/graph-cache.ts +331 -0
  979. package/src/analyze/graph-command.ts +762 -0
  980. package/src/analyze/live-graph.ts +232 -0
  981. package/src/analyze/poison-rules.ts +165 -0
  982. package/src/analyze/poison-scan.ts +159 -0
  983. package/src/analyze/scan.ts +149 -0
  984. package/src/cache/cache-api.ts +107 -0
  985. package/src/cache/fast-hash.ts +5 -0
  986. package/src/cache/handler-store.ts +76 -0
  987. package/src/cache/index.ts +115 -22
  988. package/src/cache/invalidation-epoch.ts +93 -0
  989. package/src/cache/json-lossy-check.ts +69 -0
  990. package/src/cache/redis-handler.ts +198 -20
  991. package/src/cache/singleflight.ts +72 -6
  992. package/src/cache/sizeof.ts +35 -0
  993. package/src/cache/stable-stringify.ts +65 -2
  994. package/src/cache/store.ts +71 -0
  995. package/src/cache/stores/cloudflare-kv.ts +52 -0
  996. package/src/cache/stores/memory.ts +125 -0
  997. package/src/cache/stores/redis.ts +97 -0
  998. package/src/cache/stores/vercel.ts +59 -0
  999. package/src/cache/tag-aware-handler.ts +254 -0
  1000. package/src/cache/timber-cache.ts +165 -40
  1001. package/src/cdn/cloudflare-purge.ts +50 -0
  1002. package/src/cdn/fastly-purge.ts +63 -0
  1003. package/src/cdn/headers.ts +153 -0
  1004. package/src/cdn/index.ts +23 -0
  1005. package/src/cdn/purge-store.ts +34 -0
  1006. package/src/cdn/workers-cache-purge.ts +34 -0
  1007. package/src/cli-check.ts +417 -0
  1008. package/src/cli-context.ts +119 -0
  1009. package/src/cli-schema-sync.ts +401 -0
  1010. package/src/cli.ts +334 -80
  1011. package/src/client/browser-dev.ts +192 -5
  1012. package/src/client/browser-entry/action-dispatch.ts +317 -0
  1013. package/src/client/browser-entry/action-queue.ts +152 -0
  1014. package/src/client/browser-entry/form-state.ts +49 -0
  1015. package/src/client/browser-entry/hmr.ts +70 -0
  1016. package/src/client/browser-entry/hydrate.ts +152 -0
  1017. package/src/client/browser-entry/index.ts +150 -0
  1018. package/src/client/browser-entry/post-hydration.ts +99 -0
  1019. package/src/client/browser-entry/router-init.ts +393 -0
  1020. package/src/client/browser-entry/rsc-stream.ts +145 -0
  1021. package/src/client/browser-entry/scroll.ts +50 -0
  1022. package/src/client/deny-last-resort.tsx +54 -0
  1023. package/src/client/error-boundary.tsx +279 -61
  1024. package/src/client/error-reconstituter.tsx +84 -0
  1025. package/src/client/form.tsx +61 -173
  1026. package/src/client/global-context.ts +31 -0
  1027. package/src/client/history.ts +74 -11
  1028. package/src/client/index.ts +90 -53
  1029. package/src/client/internal.ts +54 -0
  1030. package/src/client/link.tsx +468 -151
  1031. package/src/client/location-search.ts +15 -0
  1032. package/src/client/navigation-api.ts +254 -0
  1033. package/src/client/navigation-commit.ts +318 -0
  1034. package/src/client/navigation-context.ts +67 -134
  1035. package/src/client/navigation-root.tsx +236 -0
  1036. package/src/client/navigation-transition.ts +348 -0
  1037. package/src/client/nuqs-adapter.tsx +21 -9
  1038. package/src/client/params-context.ts +187 -0
  1039. package/src/client/react-root.ts +105 -0
  1040. package/src/client/router-effects.ts +324 -0
  1041. package/src/client/router-lifecycle.ts +374 -0
  1042. package/src/client/router-pipeline.ts +456 -0
  1043. package/src/client/router-ref.ts +3 -3
  1044. package/src/client/router-skew.ts +30 -0
  1045. package/src/client/router-types.ts +346 -0
  1046. package/src/client/router-url.ts +32 -0
  1047. package/src/client/router.ts +500 -424
  1048. package/src/client/rsc-fetch.ts +510 -109
  1049. package/src/client/segment-cache.ts +362 -41
  1050. package/src/client/segment-context.ts +7 -4
  1051. package/src/client/segment-outlet.tsx +96 -0
  1052. package/src/client/segment-update-context.ts +23 -0
  1053. package/src/client/shallow-url.ts +22 -0
  1054. package/src/client/slot-content-cache-context.ts +43 -0
  1055. package/src/client/slot-context.ts +50 -0
  1056. package/src/client/slot-outlet.tsx +22 -0
  1057. package/src/client/slot-provider.tsx +32 -0
  1058. package/src/client/ssr-data.ts +27 -67
  1059. package/src/client/stale-client.ts +191 -0
  1060. package/src/client/state.ts +31 -24
  1061. package/src/client/status-page-marker.tsx +32 -0
  1062. package/src/client/top-loader.tsx +13 -10
  1063. package/src/client/unload-guard.ts +35 -3
  1064. package/src/client/use-cookie.ts +70 -18
  1065. package/src/client/use-field-state.ts +144 -0
  1066. package/src/client/use-link-status.ts +7 -7
  1067. package/src/client/use-pathname.ts +22 -31
  1068. package/src/client/use-pending-navigation.ts +40 -0
  1069. package/src/client/use-query-states.ts +206 -36
  1070. package/src/client/use-router.ts +31 -9
  1071. package/src/client/use-search-params.ts +38 -49
  1072. package/src/client/use-segment-params.ts +69 -0
  1073. package/src/client/use-selected-layout-segment.ts +2 -2
  1074. package/src/codec.ts +149 -0
  1075. package/src/config-types.ts +321 -0
  1076. package/src/config-validation.ts +464 -0
  1077. package/src/cookies/define-cookie.ts +222 -53
  1078. package/src/cookies/index.ts +13 -2
  1079. package/src/cookies/json-cookie.ts +105 -0
  1080. package/src/cookies/validation.ts +192 -0
  1081. package/src/dev-tools/404-page.ts +286 -0
  1082. package/src/dev-tools/browser-logs.ts +55 -0
  1083. package/src/dev-tools/dev-page-shell.ts +278 -0
  1084. package/src/dev-tools/error-page.ts +331 -0
  1085. package/src/dev-tools/holding-server.ts +185 -0
  1086. package/src/dev-tools/hydration-overlay.ts +158 -0
  1087. package/src/dev-tools/index.ts +79 -0
  1088. package/src/dev-tools/instrumentation.ts +261 -0
  1089. package/src/{server/dev-logger.ts → dev-tools/logger.ts} +33 -51
  1090. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +122 -26
  1091. package/src/{plugins/dev-error-overlay.ts → dev-tools/overlay.ts} +25 -80
  1092. package/src/dev-tools/stack-classifier.ts +75 -0
  1093. package/src/dev-tools/terminal.ts +182 -0
  1094. package/src/fonts/ast-walk.ts +235 -0
  1095. package/src/fonts/ast.ts +479 -128
  1096. package/src/fonts/bundle.ts +138 -0
  1097. package/src/fonts/css.ts +1 -1
  1098. package/src/fonts/dev-middleware.ts +85 -0
  1099. package/src/fonts/fallbacks.ts +0 -23
  1100. package/src/fonts/google.ts +101 -19
  1101. package/src/fonts/local.ts +12 -11
  1102. package/src/fonts/paths.ts +58 -0
  1103. package/src/fonts/pipeline.ts +348 -0
  1104. package/src/fonts/transform.ts +311 -0
  1105. package/src/fonts/types.ts +52 -1
  1106. package/src/fonts/virtual-modules.ts +179 -0
  1107. package/src/index.ts +492 -380
  1108. package/src/params/codec-registry.ts +34 -0
  1109. package/src/params/define-schema.ts +115 -0
  1110. package/src/params/index.ts +17 -0
  1111. package/src/params/resolve-schema.ts +84 -0
  1112. package/src/plugin-context.ts +502 -0
  1113. package/src/plugins/build-manifest.ts +189 -36
  1114. package/src/plugins/build-report.ts +299 -87
  1115. package/src/plugins/cache.ts +243 -0
  1116. package/src/plugins/callsite-ast.ts +472 -0
  1117. package/src/plugins/callsite-jsx.ts +243 -0
  1118. package/src/plugins/chunks.ts +74 -5
  1119. package/src/plugins/client-chunks.ts +185 -0
  1120. package/src/plugins/client-dep-entries.ts +124 -0
  1121. package/src/plugins/cloudflare-wasm.ts +141 -0
  1122. package/src/plugins/content.ts +31 -2
  1123. package/src/plugins/dev-discovery.ts +218 -0
  1124. package/src/plugins/dev-server.ts +360 -97
  1125. package/src/plugins/encryption-runtime.ts +31 -0
  1126. package/src/plugins/entries.ts +150 -17
  1127. package/src/plugins/fonts.ts +260 -657
  1128. package/src/plugins/graph-endpoint.ts +532 -0
  1129. package/src/plugins/mdx.ts +108 -35
  1130. package/src/plugins/post-build.ts +327 -0
  1131. package/src/plugins/prebuilt-capture.ts +213 -0
  1132. package/src/plugins/prebuilt-options-analysis.ts +175 -0
  1133. package/src/plugins/prebuilt.ts +670 -0
  1134. package/src/plugins/prerender-sugar.ts +316 -0
  1135. package/src/plugins/react-resolve.ts +149 -0
  1136. package/src/plugins/request-dep/analysis.ts +447 -0
  1137. package/src/plugins/request-dep/index.ts +376 -0
  1138. package/src/plugins/request-dep/origin.ts +310 -0
  1139. package/src/plugins/routing.ts +273 -277
  1140. package/src/plugins/rsc-assets-manifest.ts +251 -0
  1141. package/src/plugins/server-bundle.ts +115 -15
  1142. package/src/plugins/shims.ts +257 -97
  1143. package/src/plugins/static-build.ts +681 -71
  1144. package/src/react-canary.d.ts +2 -0
  1145. package/src/routing/codegen-shared.ts +39 -0
  1146. package/src/routing/codegen-types.ts +62 -0
  1147. package/src/routing/codegen-write.ts +163 -0
  1148. package/src/routing/codegen.ts +349 -232
  1149. package/src/routing/collision-probe.ts +438 -0
  1150. package/src/routing/collision-spaces.ts +281 -0
  1151. package/src/routing/convention-lint.ts +651 -0
  1152. package/src/routing/export-detect.ts +536 -0
  1153. package/src/routing/file-cache.ts +23 -0
  1154. package/src/routing/index.ts +16 -7
  1155. package/src/routing/interception-overlap.ts +141 -0
  1156. package/src/routing/interception.ts +1044 -67
  1157. package/src/routing/link-codegen.ts +280 -0
  1158. package/src/routing/manifest-codegen.ts +232 -0
  1159. package/src/routing/scanner.ts +417 -223
  1160. package/src/routing/schema-validation.ts +155 -0
  1161. package/src/routing/segment-classify.ts +280 -0
  1162. package/src/routing/segment-codegen.ts +99 -0
  1163. package/src/routing/segment-keys.ts +186 -0
  1164. package/src/routing/slot-placement.ts +97 -0
  1165. package/src/routing/types.ts +82 -26
  1166. package/src/routing/walkers.ts +98 -0
  1167. package/src/rsc-runtime/encryption-runtime.ts +78 -0
  1168. package/src/rsc-runtime/render-flight.ts +26 -0
  1169. package/src/rsc-runtime/rsc.ts +17 -2
  1170. package/src/rsc-runtime/ssr.ts +13 -0
  1171. package/src/rsc-runtime/transforms.ts +13 -0
  1172. package/src/rsc-runtime/vendor-types.d.ts +70 -0
  1173. package/src/schema-bridge.ts +382 -0
  1174. package/src/search-params/define.ts +677 -0
  1175. package/src/search-params/index.ts +14 -20
  1176. package/src/search-params/parse-total.ts +91 -0
  1177. package/src/search-params/serialize-equal.ts +14 -0
  1178. package/src/search-params/wrappers.ts +150 -0
  1179. package/src/server/access-gate.tsx +195 -56
  1180. package/src/server/action-client.ts +175 -294
  1181. package/src/server/action-encryption.ts +144 -0
  1182. package/src/server/action-handler.ts +492 -150
  1183. package/src/server/action-schema.ts +203 -0
  1184. package/src/server/action-types.ts +145 -0
  1185. package/src/server/actions.ts +172 -85
  1186. package/src/server/als-registry.ts +245 -30
  1187. package/src/server/body-limits.ts +10 -2
  1188. package/src/server/build-manifest.ts +33 -57
  1189. package/src/server/canonicalize.ts +35 -3
  1190. package/src/server/chain-url-parts.ts +163 -0
  1191. package/src/server/children-interception.ts +116 -0
  1192. package/src/server/client-error-message.ts +18 -0
  1193. package/src/server/coalesce-tick.ts +75 -0
  1194. package/src/server/compress.ts +91 -19
  1195. package/src/server/cookie-context.ts +454 -0
  1196. package/src/server/cookie-parsing.ts +163 -0
  1197. package/src/server/csp-nonce.ts +58 -0
  1198. package/src/server/csrf.ts +228 -35
  1199. package/src/server/debug.ts +0 -1
  1200. package/src/server/default-logger.ts +100 -0
  1201. package/src/server/default-status-page.ts +88 -0
  1202. package/src/server/deny-boundary.ts +527 -0
  1203. package/src/server/deny-renderer.ts +210 -181
  1204. package/src/server/early-hints-sender.ts +4 -3
  1205. package/src/server/early-hints.ts +39 -29
  1206. package/src/server/error-boundary-wrapper.ts +160 -44
  1207. package/src/server/error-response-headers.ts +18 -0
  1208. package/src/server/fallback-error.ts +88 -104
  1209. package/src/server/flight-injection-state.ts +113 -0
  1210. package/src/server/flight-injector-core.ts +328 -0
  1211. package/src/server/flight-scripts.ts +92 -0
  1212. package/src/server/flight-source-node.ts +430 -0
  1213. package/src/server/flight-source.ts +288 -0
  1214. package/src/server/form-data.ts +191 -20
  1215. package/src/server/form-state-flight.ts +67 -0
  1216. package/src/server/head-response.ts +50 -0
  1217. package/src/server/html-injector-core.ts +320 -0
  1218. package/src/server/html-injectors.ts +241 -285
  1219. package/src/server/index.ts +37 -195
  1220. package/src/server/instrumentation.ts +11 -4
  1221. package/src/server/internal.ts +168 -0
  1222. package/src/server/json-status-response.ts +105 -0
  1223. package/src/server/logger.ts +131 -38
  1224. package/src/server/metadata-collector.ts +175 -0
  1225. package/src/server/metadata-platform.ts +2 -2
  1226. package/src/server/metadata-render.ts +30 -8
  1227. package/src/server/metadata-route-links.ts +200 -0
  1228. package/src/server/metadata-routes.ts +114 -24
  1229. package/src/server/metadata-social.ts +2 -2
  1230. package/src/server/metadata.ts +23 -2
  1231. package/src/server/middleware-runner.ts +32 -5
  1232. package/src/server/node-body-response.ts +236 -0
  1233. package/src/server/node-response.ts +93 -0
  1234. package/src/server/node-stream-transforms.ts +340 -0
  1235. package/src/server/node-streams-platform.ts +23 -0
  1236. package/src/server/nuqs-ssr-provider.tsx +8 -7
  1237. package/src/server/param-coercion.ts +201 -0
  1238. package/src/server/pipeline-helpers.ts +548 -0
  1239. package/src/server/pipeline-interception.ts +241 -32
  1240. package/src/server/pipeline-metadata.ts +25 -1
  1241. package/src/server/pipeline-outcome.ts +290 -0
  1242. package/src/server/pipeline-phases.ts +503 -0
  1243. package/src/server/pipeline.ts +423 -426
  1244. package/src/server/port-resolution.ts +43 -0
  1245. package/src/server/prebuilt/cache-key.ts +299 -0
  1246. package/src/server/prebuilt/capture-render.ts +118 -0
  1247. package/src/server/prebuilt/capture-routes.ts +104 -0
  1248. package/src/server/prebuilt/capture-state.ts +196 -0
  1249. package/src/server/prebuilt/key-discipline.ts +122 -0
  1250. package/src/server/prebuilt/lifetime.ts +151 -0
  1251. package/src/server/prebuilt/manifest-tag-index.ts +46 -0
  1252. package/src/server/prebuilt/overlay.ts +256 -0
  1253. package/src/server/prebuilt/payload-source.ts +202 -0
  1254. package/src/server/prebuilt/slots.ts +202 -0
  1255. package/src/server/prebuilt/synthetic-store.ts +125 -0
  1256. package/src/server/prebuilt-builder.ts +514 -0
  1257. package/src/server/prebuilt-runtime.ts +810 -0
  1258. package/src/server/primitives.ts +153 -171
  1259. package/src/server/publish-params.ts +42 -0
  1260. package/src/server/react-cache-bridge.ts +124 -0
  1261. package/src/server/react-cache-scope.ts +104 -0
  1262. package/src/server/render-timeout.ts +128 -0
  1263. package/src/server/render-utils.ts +45 -0
  1264. package/src/server/request-context.ts +298 -324
  1265. package/src/server/request-dep.ts +37 -0
  1266. package/src/server/response-cache-policy.ts +45 -0
  1267. package/src/server/route-element-builder.ts +526 -355
  1268. package/src/server/route-element-helpers.ts +37 -0
  1269. package/src/server/route-handler.ts +67 -27
  1270. package/src/server/route-matcher.ts +238 -267
  1271. package/src/server/route-module-loader.ts +161 -0
  1272. package/src/server/rsc-cache-key-guard.ts +122 -0
  1273. package/src/server/rsc-entry/action-dispatcher.ts +144 -0
  1274. package/src/server/rsc-entry/action-middleware-runner.ts +130 -0
  1275. package/src/server/rsc-entry/api-handler.ts +49 -81
  1276. package/src/server/rsc-entry/deny-fallback.ts +151 -0
  1277. package/src/server/rsc-entry/error-renderer.ts +306 -113
  1278. package/src/server/rsc-entry/helpers.ts +90 -115
  1279. package/src/server/rsc-entry/index.ts +372 -350
  1280. package/src/server/rsc-entry/render-route.ts +248 -0
  1281. package/src/server/rsc-entry/render-signals.ts +108 -0
  1282. package/src/server/rsc-entry/revalidate-renderer.ts +349 -0
  1283. package/src/server/rsc-entry/rsc-payload.ts +212 -113
  1284. package/src/server/rsc-entry/rsc-stream.ts +137 -135
  1285. package/src/server/rsc-entry/ssr-bridge.ts +43 -8
  1286. package/src/server/rsc-entry/ssr-renderer.ts +311 -140
  1287. package/src/server/rsc-error-envelope.ts +18 -0
  1288. package/src/server/rsc-prop-warnings.ts +1 -1
  1289. package/src/server/safe-load.ts +53 -0
  1290. package/src/server/schema-introspection.ts +393 -0
  1291. package/src/server/sensitive-fields.ts +287 -0
  1292. package/src/server/server-only-guard-noop.js +3 -0
  1293. package/src/server/server-timing.ts +1 -1
  1294. package/src/server/signal-identity.ts +112 -0
  1295. package/src/server/sitemap-generator.ts +337 -0
  1296. package/src/server/sitemap-handler.ts +150 -0
  1297. package/src/server/skippable-prefix.ts +172 -0
  1298. package/src/server/slot-interception.ts +168 -0
  1299. package/src/server/slot-resolver.ts +707 -300
  1300. package/src/server/slot-subtree-contain.ts +273 -0
  1301. package/src/server/ssr-bridge-types.ts +217 -0
  1302. package/src/server/ssr-entry.ts +248 -109
  1303. package/src/server/ssr-form-state.ts +58 -0
  1304. package/src/server/ssr-render.ts +334 -101
  1305. package/src/server/ssr-wrappers.tsx +162 -0
  1306. package/src/server/state-tree-diff.ts +85 -30
  1307. package/src/server/static-generator.ts +680 -0
  1308. package/src/server/static-not-found.ts +134 -0
  1309. package/src/server/status-code-resolver.ts +107 -148
  1310. package/src/server/stream-utils.ts +398 -0
  1311. package/src/server/tracing.ts +163 -68
  1312. package/src/server/tree-match.ts +494 -0
  1313. package/src/server/types.ts +96 -11
  1314. package/src/server/utils/element-type.ts +88 -0
  1315. package/src/server/utils/escape-html.ts +20 -0
  1316. package/src/server/version-skew.ts +104 -0
  1317. package/src/server/waituntil-bridge.ts +1 -1
  1318. package/src/server/workers-cache-bridge.ts +33 -0
  1319. package/src/shared/als-slots.ts +74 -0
  1320. package/src/shared/base-path.ts +80 -0
  1321. package/src/shared/csrf-reject.ts +15 -0
  1322. package/src/shared/error-digest.ts +46 -0
  1323. package/src/shared/flight-base64.ts +23 -0
  1324. package/src/shared/flight-segment.ts +35 -0
  1325. package/src/shared/form-state-flight.ts +59 -0
  1326. package/src/shared/href-validation.ts +159 -0
  1327. package/src/shared/merge-search-params.ts +55 -0
  1328. package/src/shared/param-value.ts +281 -0
  1329. package/src/shared/payload-root.ts +153 -0
  1330. package/src/shared/redirect-type.ts +17 -0
  1331. package/src/shared/rsc-cache-key.ts +269 -0
  1332. package/src/shared/rsc-error-envelope.ts +16 -0
  1333. package/src/shared/rsc-manifest.ts +29 -0
  1334. package/src/shared/rsc-media-type.ts +59 -0
  1335. package/src/shared/rsc-payload-path.ts +52 -0
  1336. package/src/shared/segment-info.ts +67 -0
  1337. package/src/shared/slot-params.ts +109 -0
  1338. package/src/shared/static-platform-files.ts +75 -0
  1339. package/src/shared/status-reason-phrase.ts +61 -0
  1340. package/src/shims/font-google.ts +1 -1
  1341. package/src/shims/font-local.ts +34 -0
  1342. package/src/shims/headers.ts +122 -1
  1343. package/src/shims/navigation-client.ts +36 -32
  1344. package/src/shims/navigation-rsc.ts +47 -0
  1345. package/src/shims/navigation.ts +10 -7
  1346. package/src/utils/state-machine.ts +111 -0
  1347. package/src/utils/write-file-atomic.ts +32 -0
  1348. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  1349. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  1350. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  1351. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  1352. package/dist/_chunks/format-RyoGQL74.js +0 -164
  1353. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  1354. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  1355. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  1356. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  1357. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  1358. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  1359. package/dist/_chunks/ssr-data-MjmprTmO.js +0 -88
  1360. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  1361. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  1362. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  1363. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  1364. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  1365. package/dist/_chunks/use-query-states-D5KaffOK.js +0 -109
  1366. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  1367. package/dist/adapters/cloudflare.js.map +0 -1
  1368. package/dist/cache/index.js.map +0 -1
  1369. package/dist/cache/register-cached-function.d.ts +0 -17
  1370. package/dist/cache/register-cached-function.d.ts.map +0 -1
  1371. package/dist/client/browser-entry.d.ts +0 -21
  1372. package/dist/client/browser-entry.d.ts.map +0 -1
  1373. package/dist/client/error-boundary.js.map +0 -1
  1374. package/dist/client/head.d.ts +0 -16
  1375. package/dist/client/head.d.ts.map +0 -1
  1376. package/dist/client/link-status-provider.d.ts +0 -11
  1377. package/dist/client/link-status-provider.d.ts.map +0 -1
  1378. package/dist/client/segment-merger.d.ts +0 -119
  1379. package/dist/client/segment-merger.d.ts.map +0 -1
  1380. package/dist/client/stale-reload.d.ts +0 -44
  1381. package/dist/client/stale-reload.d.ts.map +0 -1
  1382. package/dist/client/transition-root.d.ts +0 -74
  1383. package/dist/client/transition-root.d.ts.map +0 -1
  1384. package/dist/client/types.d.ts +0 -14
  1385. package/dist/client/types.d.ts.map +0 -1
  1386. package/dist/client/use-navigation-pending.d.ts +0 -26
  1387. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  1388. package/dist/client/use-params.d.ts +0 -92
  1389. package/dist/client/use-params.d.ts.map +0 -1
  1390. package/dist/content/index.d.ts +0 -11
  1391. package/dist/content/index.d.ts.map +0 -1
  1392. package/dist/content/index.js +0 -2
  1393. package/dist/plugins/adapter-build.d.ts +0 -18
  1394. package/dist/plugins/adapter-build.d.ts.map +0 -1
  1395. package/dist/plugins/cache-transform.d.ts +0 -36
  1396. package/dist/plugins/cache-transform.d.ts.map +0 -1
  1397. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  1398. package/dist/plugins/dev-logs.d.ts.map +0 -1
  1399. package/dist/plugins/dynamic-transform.d.ts +0 -72
  1400. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  1401. package/dist/plugins/server-action-exports.d.ts +0 -26
  1402. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  1403. package/dist/routing/status-file-lint.d.ts +0 -33
  1404. package/dist/routing/status-file-lint.d.ts.map +0 -1
  1405. package/dist/search-params/analyze.d.ts +0 -54
  1406. package/dist/search-params/analyze.d.ts.map +0 -1
  1407. package/dist/search-params/builtin-codecs.d.ts +0 -105
  1408. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  1409. package/dist/search-params/codecs.d.ts +0 -53
  1410. package/dist/search-params/codecs.d.ts.map +0 -1
  1411. package/dist/search-params/create.d.ts +0 -106
  1412. package/dist/search-params/create.d.ts.map +0 -1
  1413. package/dist/search-params/registry.d.ts +0 -20
  1414. package/dist/search-params/registry.d.ts.map +0 -1
  1415. package/dist/server/asset-headers.d.ts +0 -42
  1416. package/dist/server/asset-headers.d.ts.map +0 -1
  1417. package/dist/server/client-module-map.d.ts +0 -47
  1418. package/dist/server/client-module-map.d.ts.map +0 -1
  1419. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  1420. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  1421. package/dist/server/dev-logger.d.ts.map +0 -1
  1422. package/dist/server/dev-span-processor.d.ts +0 -29
  1423. package/dist/server/dev-span-processor.d.ts.map +0 -1
  1424. package/dist/server/dev-warnings.d.ts +0 -129
  1425. package/dist/server/dev-warnings.d.ts.map +0 -1
  1426. package/dist/server/flush.d.ts +0 -74
  1427. package/dist/server/flush.d.ts.map +0 -1
  1428. package/dist/server/form-flash.d.ts +0 -78
  1429. package/dist/server/form-flash.d.ts.map +0 -1
  1430. package/dist/server/manifest-status-resolver.d.ts +0 -58
  1431. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  1432. package/dist/server/prerender.d.ts +0 -77
  1433. package/dist/server/prerender.d.ts.map +0 -1
  1434. package/dist/server/tree-builder.d.ts +0 -126
  1435. package/dist/server/tree-builder.d.ts.map +0 -1
  1436. package/dist/utils/directive-parser.d.ts +0 -70
  1437. package/dist/utils/directive-parser.d.ts.map +0 -1
  1438. package/src/cache/register-cached-function.ts +0 -103
  1439. package/src/client/browser-entry.ts +0 -678
  1440. package/src/client/head.ts +0 -61
  1441. package/src/client/link-status-provider.tsx +0 -30
  1442. package/src/client/segment-merger.ts +0 -339
  1443. package/src/client/stale-reload.ts +0 -87
  1444. package/src/client/transition-root.tsx +0 -166
  1445. package/src/client/types.ts +0 -21
  1446. package/src/client/use-navigation-pending.ts +0 -38
  1447. package/src/client/use-params.ts +0 -141
  1448. package/src/content/index.ts +0 -13
  1449. package/src/plugins/adapter-build.ts +0 -118
  1450. package/src/plugins/cache-transform.ts +0 -199
  1451. package/src/plugins/dynamic-transform.ts +0 -161
  1452. package/src/plugins/server-action-exports.ts +0 -220
  1453. package/src/routing/status-file-lint.ts +0 -112
  1454. package/src/search-params/analyze.ts +0 -192
  1455. package/src/search-params/builtin-codecs.ts +0 -228
  1456. package/src/search-params/codecs.ts +0 -153
  1457. package/src/search-params/create.ts +0 -321
  1458. package/src/search-params/registry.ts +0 -31
  1459. package/src/server/asset-headers.ts +0 -81
  1460. package/src/server/client-module-map.ts +0 -58
  1461. package/src/server/dev-fetch-instrumentation.ts +0 -96
  1462. package/src/server/dev-span-processor.ts +0 -78
  1463. package/src/server/dev-warnings.ts +0 -283
  1464. package/src/server/flush.ts +0 -182
  1465. package/src/server/form-flash.ts +0 -89
  1466. package/src/server/manifest-status-resolver.ts +0 -215
  1467. package/src/server/prerender.ts +0 -139
  1468. package/src/server/tree-builder.ts +0 -382
  1469. package/src/shims/server-only-noop.js +0 -6
  1470. package/src/utils/directive-parser.ts +0 -529
@@ -1,2704 +1,600 @@
1
- import { n as isDevMode, t as isDebug } from "../_chunks/debug-B3Gypr3D.js";
2
- import { a as warnDenyAfterFlush, c as warnRedirectInAccess, d as warnSlowSlotWithoutSuspense, f as warnStaticRequestApi, i as warnCacheRequestProps, l as warnRedirectInSlotAccess, n as WarningId, o as warnDenyInSuspense, p as warnSuspenseWrappingChildren, r as setViteServer, s as warnDynamicApiInStaticBuild, t as formatSize, u as warnRedirectInSuspense } from "../_chunks/format-RyoGQL74.js";
3
- import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-Cjmvi3rQ.js";
4
- import { a as timingAls, i as revalidationAls, n as formFlashAls, s as waitUntilAls, t as earlyHintsSenderAls } from "../_chunks/als-registry-B7DbZ2hS.js";
5
- import { a as markResponseFlushed, c as setCookieSecrets, i as headers, l as setMutableCookieContext, n as cookies, o as runWithRequestContext, r as getSetCookieHeaders, s as searchParams, t as applyRequestHeaderOverlay, u as setParsedSearchParams } from "../_chunks/request-context-BQUC8PHn.js";
6
- import { a as getTraceStore, c as setSpanAttribute, d as withSpan, i as getOtelTraceId, l as spanId, o as replaceTraceId, r as generateTraceId, s as runWithTraceId, t as addSpanEvent, u as traceId } from "../_chunks/tracing-CemImE6h.js";
7
- import { readFile } from "node:fs/promises";
8
- //#region src/server/waituntil-bridge.ts
1
+ import { A as getSpanId, C as isRedirectSignal, E as addSpanEvent, F as withSpan, S as isDenySignal, T as isDevMode, j as getTraceId, w as isDebug } from "../_chunks/logger-CbLdcy-W.js";
2
+ import { t as formatSize } from "../_chunks/format-BKclgVbk.js";
3
+ import { _ as getHeaders, a as parseFormData, c as deny, d as waitUntil, i as coerce, l as redirect, n as revalidatePath, p as getCookieJar, r as revalidateTag, u as redirectExternal, y as getSegmentParams } from "../_chunks/actions-BwkmAYXq.js";
4
+ //#region src/shared/redirect-type.ts
9
5
  /**
10
- * Per-request waitUntil bridge — ALS bridge for platform adapters.
11
- *
12
- * The generated entry point (Nitro, Cloudflare) wraps the handler with
13
- * `runWithWaitUntil`, binding the platform's lifecycle extension function
14
- * (e.g., h3's `event.waitUntil()` or CF's `ctx.waitUntil()`) for the
15
- * request duration. The `waitUntil()` primitive reads from this ALS to
16
- * dispatch background work to the correct platform API.
17
- *
18
- * Design doc: design/11-platform.md §"waitUntil()"
19
- */
20
- /**
21
- * Get the current request's waitUntil function, if available.
22
- *
23
- * Returns undefined when no platform adapter has installed a waitUntil
24
- * handler for the current request (e.g., on platforms that don't support
25
- * lifecycle extension, or outside a request context).
26
- */
27
- function getWaitUntil() {
28
- return waitUntilAls.getStore();
29
- }
30
- //#endregion
31
- //#region src/server/primitives.ts
32
- /**
33
- * Check if a value is JSON-serializable without data loss.
34
- * Returns a description of the first non-serializable value found, or null if OK.
35
- *
36
- * @internal Exported for testing only.
37
- */
38
- function findNonSerializable(value, path = "data") {
39
- if (value === null || value === void 0) return null;
40
- switch (typeof value) {
41
- case "string":
42
- case "number":
43
- case "boolean": return null;
44
- case "bigint": return `${path} contains a BigInt — BigInt throws in JSON.stringify`;
45
- case "function": return `${path} is a function — functions are not JSON-serializable`;
46
- case "symbol": return `${path} is a symbol — symbols are not JSON-serializable`;
47
- case "object": break;
48
- default: return `${path} has unsupported type "${typeof value}"`;
49
- }
50
- if (value instanceof Date) return `${path} is a Date — Dates silently coerce to strings in JSON.stringify`;
51
- if (value instanceof Map) return `${path} is a Map — Maps serialize as {} in JSON.stringify (data loss)`;
52
- if (value instanceof Set) return `${path} is a Set — Sets serialize as {} in JSON.stringify (data loss)`;
53
- if (value instanceof RegExp) return `${path} is a RegExp — RegExps serialize as {} in JSON.stringify`;
54
- if (value instanceof Error) return `${path} is an Error — Errors serialize as {} in JSON.stringify`;
55
- if (Array.isArray(value)) {
56
- for (let i = 0; i < value.length; i++) {
57
- const result = findNonSerializable(value[i], `${path}[${i}]`);
58
- if (result) return result;
59
- }
60
- return null;
61
- }
62
- const proto = Object.getPrototypeOf(value);
63
- if (proto === null) return `${path} is a null-prototype object — React Flight rejects null prototypes`;
64
- if (proto !== Object.prototype) return `${path} is a ${value.constructor?.name ?? "unknown"} instance — class instances may lose data in JSON.stringify`;
65
- for (const key of Object.keys(value)) {
66
- const result = findNonSerializable(value[key], `${path}.${key}`);
67
- if (result) return result;
68
- }
69
- return null;
70
- }
71
- /**
72
- * Emit a dev-mode warning if data is not JSON-serializable.
73
- * No-op in production.
74
- */
75
- function warnIfNotSerializable(data, callerName) {
76
- if (!isDebug()) return;
77
- if (data === void 0) return;
78
- const issue = findNonSerializable(data);
79
- if (issue) console.warn(`[timber] ${callerName}: ${issue}. Data passed to deny() or RenderError must be JSON-serializable because the post-flush path uses JSON.stringify, not React Flight.`);
80
- }
81
- /**
82
- * Render-phase signal thrown by `deny()`. Caught by the framework to produce
83
- * the correct HTTP status code (segment context) or graceful degradation (slot context).
84
- */
85
- var DenySignal = class extends Error {
86
- status;
87
- data;
88
- constructor(status, data) {
89
- super(`Access denied with status ${status}`);
90
- this.name = "DenySignal";
91
- this.status = status;
92
- this.data = data;
93
- }
94
- /**
95
- * Extract the file that called deny() from the stack trace.
96
- * Returns a short path (e.g. "app/auth/access.ts") or undefined if
97
- * the stack can't be parsed. Dev-only — used for dev log output.
98
- */
99
- get sourceFile() {
100
- if (!this.stack) return void 0;
101
- const frames = this.stack.split("\n");
102
- for (let i = 2; i < frames.length; i++) {
103
- const frame = frames[i];
104
- if (!frame) continue;
105
- if (frame.includes("primitives.ts") || frame.includes("node_modules")) continue;
106
- const match = frame.match(/\(([^)]+?)(?::\d+:\d+)\)/) ?? frame.match(/at\s+([^\s]+?)(?::\d+:\d+)/);
107
- if (match?.[1]) {
108
- const full = match[1];
109
- const appIdx = full.indexOf("/app/");
110
- return appIdx >= 0 ? full.slice(appIdx + 1) : full;
111
- }
112
- }
113
- }
114
- };
115
- /**
116
- * Universal denial primitive. Throws a `DenySignal` that the framework catches.
117
- *
118
- * - In segment context (outside Suspense): produces HTTP status code
119
- * - In slot context: graceful degradation → denied.tsx → default.tsx → null
120
- * - Inside Suspense (hold window): promoted to pre-flush behavior
121
- * - Inside Suspense (after flush): error boundary + noindex meta
122
- *
123
- * @param status - Any 4xx HTTP status code. Defaults to 403.
124
- * @param data - Optional JSON-serializable data passed as `dangerouslyPassData` prop to status-code files.
125
- */
126
- function deny(status = 403, data) {
127
- if (status < 400 || status > 499) throw new Error(`deny() requires a 4xx status code, got ${status}. For 5xx errors, throw a RenderError instead.`);
128
- warnIfNotSerializable(data, "deny()");
129
- throw new DenySignal(status, data);
130
- }
131
- /**
132
- * Convenience alias for `deny(404)`.
133
- *
134
- * Provided for Next.js API compatibility — libraries and user code that
135
- * call `notFound()` from `next/navigation` get the same behavior as
136
- * `deny(404)` in timber.
137
- */
138
- function notFound() {
139
- throw new DenySignal(404);
140
- }
141
- /**
142
- * Next.js redirect type discriminator.
143
- *
144
- * Provided for API compatibility with libraries that import `RedirectType`
145
- * from `next/navigation`. In timber, `redirect()` always uses `replace`
146
- * semantics (no history entry for the redirect itself).
147
- */
148
- var RedirectType = {
149
- push: "push",
150
- replace: "replace"
151
- };
152
- /**
153
- * Render-phase signal thrown by `redirect()` and `redirectExternal()`.
154
- * Caught by the framework to produce a 3xx response or client-side navigation.
155
- */
156
- var RedirectSignal = class extends Error {
157
- location;
158
- status;
159
- constructor(location, status) {
160
- super(`Redirect to ${location}`);
161
- this.name = "RedirectSignal";
162
- this.location = location;
163
- this.status = status;
164
- }
165
- };
166
- /** Pattern matching absolute URLs: http(s):// or protocol-relative // */
167
- var ABSOLUTE_URL_RE = /^(?:[a-zA-Z][a-zA-Z\d+\-.]*:|\/\/)/;
168
- /**
169
- * Redirect to a relative path. Rejects absolute and protocol-relative URLs.
170
- * Use `redirectExternal()` for external redirects with an allow-list.
171
- *
172
- * @param path - Relative path (e.g. '/login', 'settings', '/login?returnTo=/dash')
173
- * @param status - HTTP redirect status code (3xx). Defaults to 302.
174
- */
175
- function redirect(path, status = 302) {
176
- if (status < 300 || status > 399) throw new Error(`redirect() requires a 3xx status code, got ${status}.`);
177
- if (ABSOLUTE_URL_RE.test(path)) throw new Error(`redirect() only accepts relative URLs. Got absolute URL: "${path}". Use redirectExternal(url, allowList) for external redirects.`);
178
- throw new RedirectSignal(path, status);
179
- }
180
- /**
181
- * Permanent redirect to a relative path. Shorthand for `redirect(path, 308)`.
182
- *
183
- * Uses 308 (Permanent Redirect) which preserves the HTTP method — the browser
184
- * will replay POST requests to the new location. This matches Next.js behavior.
185
- *
186
- * @param path - Relative path (e.g. '/new-page', '/dashboard')
187
- */
188
- function permanentRedirect(path) {
189
- redirect(path, 308);
190
- }
191
- /**
192
- * Redirect to an external URL. The hostname must be in the provided allow-list.
193
- *
194
- * @param url - Absolute URL to redirect to.
195
- * @param allowList - Array of allowed hostnames (e.g. ['example.com', 'auth.example.com']).
196
- * @param status - HTTP redirect status code (3xx). Defaults to 302.
197
- */
198
- function redirectExternal(url, allowList, status = 302) {
199
- if (status < 300 || status > 399) throw new Error(`redirectExternal() requires a 3xx status code, got ${status}.`);
200
- let hostname;
201
- try {
202
- hostname = new URL(url).hostname;
203
- } catch {
204
- throw new Error(`redirectExternal() received an invalid URL: "${url}"`);
205
- }
206
- if (!allowList.includes(hostname)) throw new Error(`redirectExternal() target "${hostname}" is not in the allow-list. Allowed: [${allowList.join(", ")}]`);
207
- throw new RedirectSignal(url, status);
208
- }
209
- /**
210
- * Typed throw for render-phase errors that carry structured context to error boundaries.
211
- *
212
- * The `digest` (code + data) is serialized into the RSC stream separately from the
213
- * Error instance — only the digest crosses the RSC → client boundary.
214
- *
215
- * @example
216
- * ```ts
217
- * throw new RenderError('PRODUCT_NOT_FOUND', {
218
- * title: 'Product not found',
219
- * resourceId: params.id,
220
- * })
221
- * ```
222
- */
223
- var RenderError = class extends Error {
224
- code;
225
- digest;
226
- status;
227
- constructor(code, data, options) {
228
- super(`RenderError: ${code}`);
229
- this.name = "RenderError";
230
- this.code = code;
231
- this.digest = {
232
- code,
233
- data
234
- };
235
- warnIfNotSerializable(data, "RenderError");
236
- const status = options?.status ?? 500;
237
- if (status < 400 || status > 599) throw new Error(`RenderError status must be 4xx or 5xx, got ${status}.`);
238
- this.status = status;
239
- }
240
- };
241
- var _waitUntilWarned = false;
242
- /**
243
- * Register a promise to be kept alive after the response is sent.
244
- * Maps to `ctx.waitUntil()` on Cloudflare Workers and similar platforms.
245
- *
246
- * In production, the platform adapter installs a per-request waitUntil
247
- * function via ALS (see waituntil-bridge.ts). This function checks the
248
- * ALS bridge first, then falls back to the legacy adapter argument.
249
- *
250
- * If neither is available, a warning is logged once and the promise is
251
- * left to resolve (or reject) without being tracked.
252
- *
253
- * @param promise - The background work to keep alive.
254
- * @param adapter - Optional legacy adapter (prefer ALS bridge in production).
255
- */
256
- function waitUntil(promise, adapter) {
257
- const alsFn = getWaitUntil();
258
- if (alsFn) {
259
- alsFn(promise);
260
- return;
261
- }
262
- if (adapter && typeof adapter.waitUntil === "function") {
263
- adapter.waitUntil(promise);
264
- return;
265
- }
266
- if (!_waitUntilWarned) {
267
- _waitUntilWarned = true;
268
- console.warn("[timber] waitUntil() is not supported by the current adapter. Background work will not be tracked. This warning is shown once.");
269
- }
270
- }
271
- //#endregion
272
- //#region src/server/canonicalize.ts
273
- /**
274
- * Encoded separators that produce a 400 rejection.
275
- * %2f (/) and %5c (\) cause path-confusion attacks.
276
- */
277
- var ENCODED_SEPARATOR_RE = /%2f|%5c/i;
278
- /** Null byte — rejected. */
279
- var NULL_BYTE_RE = /%00/i;
280
- /**
281
- * Canonicalize a URL pathname.
282
- *
283
- * 1. Reject encoded separators (%2f, %5c) and null bytes (%00)
284
- * 2. Single percent-decode
285
- * 3. Collapse // → /
286
- * 4. Resolve .. segments (reject if escaping root)
287
- * 5. Strip trailing slash (except root "/")
288
- *
289
- * @param rawPathname - The raw pathname from the request URL (percent-encoded)
290
- * @param stripTrailingSlash - Whether to strip trailing slashes. Default: true.
291
- */
292
- function canonicalize(rawPathname, stripTrailingSlash = true) {
293
- if (ENCODED_SEPARATOR_RE.test(rawPathname)) return {
294
- ok: false,
295
- status: 400
296
- };
297
- if (NULL_BYTE_RE.test(rawPathname)) return {
298
- ok: false,
299
- status: 400
300
- };
301
- let decoded;
302
- try {
303
- decoded = decodeURIComponent(rawPathname);
304
- } catch {
305
- return {
306
- ok: false,
307
- status: 400
308
- };
309
- }
310
- if (decoded.includes("\0")) return {
311
- ok: false,
312
- status: 400
313
- };
314
- let pathname = decoded.replace(/\/\/+/g, "/");
315
- const segments = pathname.split("/");
316
- const resolved = [];
317
- for (const seg of segments) if (seg === "..") {
318
- if (resolved.length <= 1) return {
319
- ok: false,
320
- status: 400
321
- };
322
- resolved.pop();
323
- } else if (seg !== ".") resolved.push(seg);
324
- pathname = resolved.join("/") || "/";
325
- if (stripTrailingSlash && pathname.length > 1 && pathname.endsWith("/")) pathname = pathname.slice(0, -1);
326
- return {
327
- ok: true,
328
- pathname
329
- };
330
- }
331
- //#endregion
332
- //#region src/server/proxy.ts
333
- /**
334
- * Run the proxy pipeline.
335
- *
336
- * @param proxyExport - The default export from proxy.ts (function or array)
337
- * @param req - The incoming request
338
- * @param next - The continuation that proceeds to route matching and rendering
339
- * @returns The final response
340
- */
341
- async function runProxy(proxyExport, req, next) {
342
- const fns = Array.isArray(proxyExport) ? proxyExport : [proxyExport];
343
- let i = fns.length;
344
- let composed = next;
345
- while (i--) {
346
- const fn = fns[i];
347
- const downstream = composed;
348
- composed = () => Promise.resolve(fn(req, downstream));
349
- }
350
- return composed();
351
- }
352
- //#endregion
353
- //#region src/server/middleware-runner.ts
354
- /**
355
- * Run a route's middleware function.
356
- *
357
- * @param middlewareFn - The default export from the route's middleware.ts
358
- * @param ctx - The middleware context (req, params, headers, requestHeaders, searchParams)
359
- * @returns A Response if middleware short-circuited, or undefined to continue
360
- */
361
- async function runMiddleware(middlewareFn, ctx) {
362
- const result = await middlewareFn(ctx);
363
- if (result instanceof Response) return result;
364
- }
365
- //#endregion
366
- //#region src/server/server-timing.ts
367
- /**
368
- * Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
369
- *
370
- * Collects timing entries per request using ALS. Each pipeline phase
371
- * (proxy, middleware, render, SSR, access, fetch) records an entry.
372
- * Before response flush, entries are formatted into a Server-Timing header.
373
- *
374
- * Only active in dev mode — zero overhead in production.
375
- *
376
- * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
377
- * Task: LOCAL-290
378
- */
379
- /**
380
- * Run a callback with a per-request timing collector.
381
- * Must be called at the top of the request pipeline (wraps the full request).
382
- */
383
- function runWithTimingCollector(fn) {
384
- return timingAls.run({ entries: [] }, fn);
385
- }
386
- /**
387
- * Run a function and automatically record its duration as a timing entry.
388
- * Returns the function's result. No-ops the recording if outside a collector.
389
- */
390
- async function withTiming(name, desc, fn) {
391
- const store = timingAls.getStore();
392
- if (!store) return fn();
393
- const start = performance.now();
394
- try {
395
- return await fn();
396
- } finally {
397
- const dur = Math.round(performance.now() - start);
398
- store.entries.push({
399
- name,
400
- dur,
401
- desc
402
- });
403
- }
404
- }
405
- /**
406
- * Get the Server-Timing header value for the current request.
407
- * Returns null if no entries exist or outside a collector.
408
- *
409
- * Format: `name;dur=123;desc="description", name2;dur=456`
410
- * See RFC 6797 / Server-Timing spec for format details.
411
- */
412
- function getServerTimingHeader() {
413
- const store = timingAls.getStore();
414
- if (!store || store.entries.length === 0) return null;
415
- const nameCounts = /* @__PURE__ */ new Map();
416
- const parts = store.entries.map((entry) => {
417
- const count = nameCounts.get(entry.name) ?? 0;
418
- nameCounts.set(entry.name, count + 1);
419
- const uniqueName = count > 0 ? `${entry.name}-${count}` : entry.name;
420
- return {
421
- ...entry,
422
- name: uniqueName
423
- };
424
- }).map((entry) => {
425
- let part = `${entry.name};dur=${entry.dur}`;
426
- if (entry.desc) {
427
- const safeDesc = entry.desc.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
428
- part += `;desc="${safeDesc}"`;
429
- }
430
- return part;
431
- });
432
- const MAX_HEADER_SIZE = 4096;
433
- let result = "";
434
- for (let i = 0; i < parts.length; i++) {
435
- const candidate = result ? `${result}, ${parts[i]}` : parts[i];
436
- if (candidate.length > MAX_HEADER_SIZE) break;
437
- result = candidate;
438
- }
439
- return result || null;
440
- }
441
- //#endregion
442
- //#region src/server/error-formatter.ts
443
- /**
444
- * Error Formatter — rewrites SSR/RSC error messages to surface user code.
445
- *
446
- * When React or Vite throw errors during SSR, stack traces reference
447
- * vendored dependency paths (e.g. `.vite/deps_ssr/@vitejs_plugin-rsc_vendor_...`)
448
- * and mangled export names (`__vite_ssr_export_default__`). This module
449
- * rewrites error messages and stack traces to point at user code instead.
450
- *
451
- * Dev-only — in production, errors go through the structured logger
452
- * without formatting.
453
- */
454
- /**
455
- * Patterns that identify internal Vite/RSC vendor paths in stack traces.
456
- * These are replaced with human-readable labels.
457
- */
458
- var VENDOR_PATH_PATTERNS = [
459
- {
460
- pattern: /node_modules\/\.vite\/deps_ssr\/@vitejs_plugin-rsc_vendor_react-server-dom[^\s)]+/g,
461
- replacement: "<react-server-dom>"
462
- },
463
- {
464
- pattern: /node_modules\/\.vite\/deps_ssr\/@vitejs_plugin-rsc_vendor[^\s)]+/g,
465
- replacement: "<rsc-vendor>"
466
- },
467
- {
468
- pattern: /node_modules\/\.vite\/deps_ssr\/[^\s)]+/g,
469
- replacement: "<vite-dep>"
470
- },
471
- {
472
- pattern: /node_modules\/\.vite\/deps\/[^\s)]+/g,
473
- replacement: "<vite-dep>"
474
- }
475
- ];
476
- /**
477
- * Patterns that identify Vite-mangled export names in error messages.
478
- */
479
- var MANGLED_NAME_PATTERNS = [{
480
- pattern: /__vite_ssr_export_default__/g,
481
- replacement: "<default export>"
482
- }, {
483
- pattern: /__vite_ssr_export_(\w+)__/g,
484
- replacement: "<export $1>"
485
- }];
486
- /**
487
- * Rewrite an error's message and stack to replace internal Vite paths
488
- * and mangled names with human-readable labels.
489
- */
490
- function formatSsrError(error) {
491
- if (!(error instanceof Error)) return String(error);
492
- let message = error.message;
493
- let stack = error.stack ?? "";
494
- for (const { pattern, replacement } of MANGLED_NAME_PATTERNS) message = message.replace(pattern, replacement);
495
- for (const { pattern, replacement } of VENDOR_PATH_PATTERNS) stack = stack.replace(pattern, replacement);
496
- for (const { pattern, replacement } of MANGLED_NAME_PATTERNS) stack = stack.replace(pattern, replacement);
497
- const hint = extractErrorHint(error.message);
498
- const parts = [];
499
- parts.push(message);
500
- if (hint) parts.push(` → ${hint}`);
501
- const userFrames = extractUserFrames(stack);
502
- if (userFrames.length > 0) {
503
- parts.push("");
504
- parts.push(" User code in stack:");
505
- for (const frame of userFrames) parts.push(` ${frame}`);
506
- }
507
- return parts.join("\n");
508
- }
509
- /**
510
- * Extract a human-readable hint from common React/RSC error messages.
511
- *
512
- * React error messages contain useful information but the surrounding
513
- * context (vendor paths, mangled names) obscures it. This extracts the
514
- * actionable part as a one-line hint.
515
- */
516
- function extractErrorHint(message) {
517
- if (message.match(/Functions cannot be passed directly to Client Components/)) {
518
- const propMatch = message.match(/<[^>]*?\s(\w+)=\{function/);
519
- if (propMatch) return `Prop "${propMatch[1]}" is a function — mark it "use server" or call it before passing`;
520
- return "A function prop was passed to a Client Component — mark it \"use server\" or call it before passing";
521
- }
522
- if (message.includes("Objects are not valid as a React child")) return "An object was rendered as JSX children — convert to string or extract the value";
523
- const nullRefMatch = message.match(/Cannot read propert(?:y|ies) of (undefined|null) \(reading '(\w+)'\)/);
524
- if (nullRefMatch) return `Accessed .${nullRefMatch[2]} on ${nullRefMatch[1]} — check that the value exists`;
525
- const notFnMatch = message.match(/(\w+) is not a function/);
526
- if (notFnMatch) return `"${notFnMatch[1]}" is not a function — check imports and exports`;
527
- if (message.includes("Element type is invalid")) return "A component resolved to undefined/null — check default exports and import paths";
528
- if (message.includes("Invalid hook call")) return "A hook was called outside of a React component render. If this is a 'use client' component, ensure the directive is at the very top of the file (before any imports) and that @vitejs/plugin-rsc is loaded correctly. Barrel re-exports from non-'use client' files do not propagate the directive.";
529
- return null;
530
- }
531
- /**
532
- * Extract stack frames that reference user code (not node_modules,
533
- * not framework internals).
534
- *
535
- * Returns at most 5 frames to keep output concise.
536
- */
537
- function extractUserFrames(stack) {
538
- const lines = stack.split("\n");
539
- const userFrames = [];
540
- for (const line of lines) {
541
- const trimmed = line.trim();
542
- if (!trimmed.startsWith("at ")) continue;
543
- if (trimmed.includes("node_modules") || trimmed.includes("<react-server-dom>") || trimmed.includes("<rsc-vendor>") || trimmed.includes("<vite-dep>") || trimmed.includes("node:internal")) continue;
544
- userFrames.push(trimmed);
545
- if (userFrames.length >= 5) break;
546
- }
547
- return userFrames;
548
- }
549
- //#endregion
550
- //#region src/server/logger.ts
551
- /**
552
- * Logger — structured logging with environment-aware formatting.
553
- *
554
- * timber.js does not ship a logger. Users export any object with
555
- * info/warn/error/debug methods from instrumentation.ts and the framework
556
- * picks it up. Silent if no logger export is present.
557
- *
558
- * See design/17-logging.md §"Production Logging"
559
- */
560
- var _logger = null;
561
- /**
562
- * Set the user-provided logger. Called by the instrumentation loader
563
- * when it finds a `logger` export in instrumentation.ts.
564
- */
565
- function setLogger(logger) {
566
- _logger = logger;
567
- }
568
- /**
569
- * Get the current logger, or null if none configured.
570
- * Framework-internal — used at framework event points to emit structured logs.
571
- */
572
- function getLogger() {
573
- return _logger;
574
- }
575
- /**
576
- * Inject trace_id and span_id into log data for log–trace correlation.
577
- * Always injects trace_id (never undefined). Injects span_id only when OTEL is active.
578
- */
579
- function withTraceContext(data) {
580
- const store = getTraceStore();
581
- const enriched = { ...data };
582
- if (store) {
583
- enriched.trace_id = store.traceId;
584
- if (store.spanId) enriched.span_id = store.spanId;
585
- }
586
- return enriched;
587
- }
588
- /** Log a completed request. Level: info. */
589
- function logRequestCompleted(data) {
590
- _logger?.info("request completed", withTraceContext(data));
591
- }
592
- /** Log request received. Level: debug. */
593
- function logRequestReceived(data) {
594
- _logger?.debug("request received", withTraceContext(data));
595
- }
596
- /** Log a slow request warning. Level: warn. */
597
- function logSlowRequest(data) {
598
- _logger?.warn("slow request exceeded threshold", withTraceContext(data));
599
- }
600
- /** Log middleware short-circuit. Level: debug. */
601
- function logMiddlewareShortCircuit(data) {
602
- _logger?.debug("middleware short-circuited", withTraceContext(data));
603
- }
604
- /** Log unhandled error in middleware phase. Level: error. */
605
- function logMiddlewareError(data) {
606
- if (_logger) _logger.error("unhandled error in middleware phase", withTraceContext(data));
607
- else if (isDebug()) console.error("[timber] middleware error", data.error);
608
- }
609
- /** Log unhandled render-phase error. Level: error. */
610
- function logRenderError(data) {
611
- if (_logger) _logger.error("unhandled render-phase error", withTraceContext(data));
612
- else if (isDebug()) console.error("[timber] render error:", formatSsrError(data.error));
613
- }
614
- /** Log proxy.ts uncaught error. Level: error. */
615
- function logProxyError(data) {
616
- if (_logger) _logger.error("proxy.ts threw uncaught error", withTraceContext(data));
617
- else if (isDebug()) console.error("[timber] proxy error", data.error);
618
- }
619
- /** Log waitUntil() adapter missing (once at startup). Level: warn. */
620
- function logWaitUntilUnsupported() {
621
- _logger?.warn("adapter does not support waitUntil()");
622
- }
623
- /** Log waitUntil() promise rejection. Level: warn. */
624
- function logWaitUntilRejected(data) {
625
- _logger?.warn("waitUntil() promise rejected", withTraceContext(data));
626
- }
627
- /** Log staleWhileRevalidate refetch failure. Level: warn. */
628
- function logSwrRefetchFailed(data) {
629
- _logger?.warn("staleWhileRevalidate refetch failed", withTraceContext(data));
630
- }
631
- /** Log cache miss. Level: debug. */
632
- function logCacheMiss(data) {
633
- _logger?.debug("timber.cache MISS", withTraceContext(data));
634
- }
635
- //#endregion
636
- //#region src/server/instrumentation.ts
637
- /**
638
- * Instrumentation — loads and runs the user's instrumentation.ts file.
639
- *
640
- * instrumentation.ts is a file convention at the project root that exports:
641
- * - register() — called once at server startup, before the first request
642
- * - onRequestError() — called for every unhandled server error
643
- * - logger — any object with info/warn/error/debug methods
644
- *
645
- * See design/17-logging.md §"instrumentation.ts — The Entry Point"
646
- */
647
- var _initialized = false;
648
- var _onRequestError = null;
649
- /**
650
- * Load and initialize the user's instrumentation.ts module.
651
- *
652
- * - Awaits register() before returning (server blocks on this).
653
- * - Picks up the logger export and wires it into the framework logger.
654
- * - Stores onRequestError for later invocation.
655
- *
656
- * @param loader - Function that dynamically imports the user's instrumentation module.
657
- * Returns null if no instrumentation.ts exists.
658
- */
659
- async function loadInstrumentation(loader) {
660
- if (_initialized) return;
661
- _initialized = true;
662
- let mod;
663
- try {
664
- mod = await loader();
665
- } catch (error) {
666
- console.error("[timber] Failed to load instrumentation.ts:", error);
667
- return;
668
- }
669
- if (!mod) return;
670
- if (mod.logger && typeof mod.logger.info === "function") setLogger(mod.logger);
671
- if (typeof mod.onRequestError === "function") _onRequestError = mod.onRequestError;
672
- if (typeof mod.register === "function") try {
673
- await mod.register();
674
- } catch (error) {
675
- console.error("[timber] instrumentation.ts register() threw:", error);
676
- throw error;
677
- }
678
- }
679
- /**
680
- * Call the user's onRequestError hook. Catches and logs any errors thrown
681
- * by the hook itself — it must not affect the response.
682
- */
683
- async function callOnRequestError(error, request, context) {
684
- if (!_onRequestError) return;
685
- try {
686
- await _onRequestError(error, request, context);
687
- } catch (hookError) {
688
- console.error("[timber] onRequestError hook threw:", hookError);
689
- }
690
- }
691
- /**
692
- * Check if onRequestError is registered.
693
- */
694
- function hasOnRequestError() {
695
- return _onRequestError !== null;
696
- }
697
- //#endregion
698
- //#region src/server/pipeline-metadata.ts
699
- /**
700
- * Metadata route helpers for the request pipeline.
701
- *
702
- * Handles serving static metadata files and serializing sitemap responses.
703
- * Extracted from pipeline.ts to keep files under 500 lines.
704
- *
705
- * See design/16-metadata.md §"Metadata Routes"
706
- */
707
- /**
708
- * Content types that are text-based and should include charset=utf-8.
709
- * Binary formats (images) should not include charset.
710
- */
711
- var TEXT_CONTENT_TYPES = new Set([
712
- "application/xml",
713
- "text/plain",
714
- "application/json",
715
- "application/manifest+json",
716
- "image/svg+xml"
717
- ]);
718
- /**
719
- * Serve a static metadata file by reading it from disk.
720
- *
721
- * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
722
- * are served as-is with the appropriate Content-Type header.
723
- * Text files include charset=utf-8; binary files do not.
724
- *
725
- * See design/16-metadata.md §"Metadata Routes"
726
- */
727
- async function serveStaticMetadataFile(metaMatch) {
728
- const { contentType, file } = metaMatch;
729
- const isText = TEXT_CONTENT_TYPES.has(contentType);
730
- const body = await readFile(file.filePath);
731
- const headers = {
732
- "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
733
- "Content-Length": String(body.byteLength)
734
- };
735
- return new Response(body, {
736
- status: 200,
737
- headers
738
- });
739
- }
740
- /**
741
- * Serialize a sitemap array to XML.
742
- * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
743
- */
744
- function serializeSitemap(entries) {
745
- return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
746
- let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
747
- if (e.lastModified) {
748
- const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
749
- xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
750
- }
751
- if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
752
- if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
753
- xml += "\n </url>";
754
- return xml;
755
- }).join("\n")}\n</urlset>`;
756
- }
757
- /** Escape special XML characters. */
758
- function escapeXml(str) {
759
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
760
- }
761
- //#endregion
762
- //#region src/server/pipeline-interception.ts
763
- /**
764
- * Check if an intercepting route applies for this soft navigation.
765
- *
766
- * Matches the target pathname against interception rewrites, constrained
767
- * by the source URL (X-Timber-URL header — where the user navigates FROM).
768
- *
769
- * Returns the source pathname to re-match if interception applies, or null.
770
- */
771
- function findInterceptionMatch(targetPathname, sourceUrl, rewrites) {
772
- for (const rewrite of rewrites) {
773
- if (!sourceUrl.startsWith(rewrite.interceptingPrefix)) continue;
774
- if (pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern)) return { sourcePathname: rewrite.interceptingPrefix };
775
- }
776
- return null;
777
- }
778
- /**
779
- * Check if a pathname matches a URL pattern with dynamic segments.
780
- *
781
- * Supports [param] (single segment) and [...param] (one or more segments).
782
- * Static segments must match exactly.
783
- */
784
- function pathnameMatchesPattern(pathname, pattern) {
785
- const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
786
- const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
787
- let pi = 0;
788
- for (let i = 0; i < patternParts.length; i++) {
789
- const segment = patternParts[i];
790
- if (segment.startsWith("[...") || segment.startsWith("[[...")) return pi < pathParts.length || segment.startsWith("[[...");
791
- if (segment.startsWith("[") && segment.endsWith("]")) {
792
- if (pi >= pathParts.length) return false;
793
- pi++;
794
- continue;
795
- }
796
- if (pi >= pathParts.length || pathParts[pi] !== segment) return false;
797
- pi++;
798
- }
799
- return pi === pathParts.length;
800
- }
801
- //#endregion
802
- //#region src/server/pipeline.ts
803
- /**
804
- * Request pipeline — the central dispatch for all timber.js requests.
805
- *
806
- * Pipeline stages (in order):
807
- * proxy.ts → canonicalize → route match → 103 Early Hints → middleware.ts → render
808
- *
809
- * Each stage is a pure function or returns a Response to short-circuit.
810
- * Each request gets a trace ID, structured logging, and OTEL spans.
811
- *
812
- * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow",
813
- * and design/17-logging.md §"Production Logging"
814
- */
815
- /**
816
- * Create the request handler from a pipeline configuration.
817
- *
818
- * Returns a function that processes an incoming Request through all pipeline stages
819
- * and produces a Response. This is the top-level entry point for the server.
820
- */
821
- function createPipeline(config) {
822
- const { proxy, matchRoute, render, earlyHints, stripTrailingSlash = true, slowRequestMs = 3e3, serverTiming = "total", onPipelineError } = config;
823
- let activeRequests = 0;
824
- return async (req) => {
825
- const url = new URL(req.url);
826
- const method = req.method;
827
- const path = url.pathname;
828
- const startTime = performance.now();
829
- activeRequests++;
830
- return runWithTraceId(generateTraceId(), async () => {
831
- return runWithRequestContext(req, async () => {
832
- const runRequest = async () => {
833
- logRequestReceived({
834
- method,
835
- path
836
- });
837
- const response = await withSpan("http.server.request", {
838
- "http.request.method": method,
839
- "url.path": path
840
- }, async () => {
841
- const otelIds = await getOtelTraceId();
842
- if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
843
- let result;
844
- if (proxy || config.proxyLoader) result = await runProxyPhase(req, method, path);
845
- else result = await handleRequest(req, method, path);
846
- await setSpanAttribute("http.response.status_code", result.status);
847
- if (serverTiming === "detailed") {
848
- const timingHeader = getServerTimingHeader();
849
- if (timingHeader) {
850
- result = ensureMutableResponse(result);
851
- result.headers.set("Server-Timing", timingHeader);
852
- }
853
- } else if (serverTiming === "total") {
854
- const totalMs = Math.round(performance.now() - startTime);
855
- result = ensureMutableResponse(result);
856
- result.headers.set("Server-Timing", `total;dur=${totalMs}`);
857
- }
858
- return result;
859
- });
860
- const durationMs = Math.round(performance.now() - startTime);
861
- const status = response.status;
862
- const concurrency = activeRequests;
863
- activeRequests--;
864
- logRequestCompleted({
865
- method,
866
- path,
867
- status,
868
- durationMs,
869
- concurrency
870
- });
871
- if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
872
- method,
873
- path,
874
- durationMs,
875
- threshold: slowRequestMs,
876
- concurrency
877
- });
878
- return response;
879
- };
880
- return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
881
- });
882
- });
883
- };
884
- async function runProxyPhase(req, method, path) {
885
- try {
886
- let proxyExport;
887
- if (config.proxyLoader) proxyExport = (await config.proxyLoader()).default;
888
- else proxyExport = config.proxy;
889
- const proxyFn = () => runProxy(proxyExport, req, () => handleRequest(req, method, path));
890
- return await withSpan("timber.proxy", {}, () => serverTiming === "detailed" ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn());
891
- } catch (error) {
892
- logProxyError({ error });
893
- await fireOnRequestError(error, req, "proxy");
894
- if (onPipelineError && error instanceof Error) onPipelineError(error, "proxy");
895
- return new Response(null, { status: 500 });
896
- }
897
- }
898
- async function handleRequest(req, method, path) {
899
- const result = canonicalize(new URL(req.url).pathname, stripTrailingSlash);
900
- if (!result.ok) return new Response(null, { status: result.status });
901
- const canonicalPathname = result.pathname;
902
- if (config.matchMetadataRoute) {
903
- const metaMatch = config.matchMetadataRoute(canonicalPathname);
904
- if (metaMatch) try {
905
- if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
906
- const mod = await metaMatch.file.load();
907
- if (typeof mod.default !== "function") return new Response("Metadata route must export a default function", { status: 500 });
908
- const handlerResult = await mod.default();
909
- if (handlerResult instanceof Response) return handlerResult;
910
- const contentType = metaMatch.contentType;
911
- let body;
912
- if (typeof handlerResult === "string") body = handlerResult;
913
- else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
914
- else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
915
- else body = typeof handlerResult === "string" ? handlerResult : String(handlerResult);
916
- return new Response(body, {
917
- status: 200,
918
- headers: { "Content-Type": `${contentType}; charset=utf-8` }
919
- });
920
- } catch (error) {
921
- logRenderError({
922
- method,
923
- path,
924
- error
925
- });
926
- if (onPipelineError && error instanceof Error) onPipelineError(error, "metadata-route");
927
- return new Response(null, { status: 500 });
928
- }
929
- }
930
- let match = matchRoute(canonicalPathname);
931
- let interception;
932
- const sourceUrl = req.headers.get("X-Timber-URL");
933
- if (sourceUrl && config.interceptionRewrites?.length) {
934
- const intercepted = findInterceptionMatch(canonicalPathname, sourceUrl, config.interceptionRewrites);
935
- if (intercepted) {
936
- const sourceMatch = matchRoute(intercepted.sourcePathname);
937
- if (sourceMatch) {
938
- match = sourceMatch;
939
- interception = { targetPathname: canonicalPathname };
940
- }
941
- }
942
- }
943
- if (!match) {
944
- if (config.renderNoMatch) {
945
- const responseHeaders = new Headers();
946
- return config.renderNoMatch(req, responseHeaders);
947
- }
948
- return new Response(null, { status: 404 });
949
- }
950
- const responseHeaders = new Headers();
951
- const requestHeaderOverlay = new Headers();
952
- responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
953
- if (earlyHints) try {
954
- await earlyHints(match, req, responseHeaders);
955
- } catch {}
956
- if (match.middleware) {
957
- const ctx = {
958
- req,
959
- requestHeaders: requestHeaderOverlay,
960
- headers: responseHeaders,
961
- params: match.params,
962
- searchParams: new URL(req.url).searchParams,
963
- earlyHints: (hints) => {
964
- for (const hint of hints) {
965
- let value = `<${hint.href}>; rel=${hint.rel}`;
966
- if (hint.as !== void 0) value += `; as=${hint.as}`;
967
- if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
968
- if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
969
- responseHeaders.append("Link", value);
970
- }
971
- }
972
- };
973
- try {
974
- setMutableCookieContext(true);
975
- const middlewareFn = () => runMiddleware(match.middleware, ctx);
976
- const middlewareResponse = await withSpan("timber.middleware", {}, () => serverTiming === "detailed" ? withTiming("mw", "middleware.ts", middlewareFn) : middlewareFn());
977
- setMutableCookieContext(false);
978
- if (middlewareResponse) {
979
- const finalResponse = ensureMutableResponse(middlewareResponse);
980
- applyCookieJar(finalResponse.headers);
981
- logMiddlewareShortCircuit({
982
- method,
983
- path,
984
- status: finalResponse.status
985
- });
986
- return finalResponse;
987
- }
988
- applyRequestHeaderOverlay(requestHeaderOverlay);
989
- } catch (error) {
990
- setMutableCookieContext(false);
991
- if (error instanceof RedirectSignal) {
992
- applyCookieJar(responseHeaders);
993
- if ((req.headers.get("Accept") ?? "").includes("text/x-component")) {
994
- responseHeaders.set("X-Timber-Redirect", error.location);
995
- return new Response(null, {
996
- status: 204,
997
- headers: responseHeaders
998
- });
999
- }
1000
- responseHeaders.set("Location", error.location);
1001
- return new Response(null, {
1002
- status: error.status,
1003
- headers: responseHeaders
1004
- });
1005
- }
1006
- if (error instanceof DenySignal) return new Response(null, { status: error.status });
1007
- logMiddlewareError({
1008
- method,
1009
- path,
1010
- error
1011
- });
1012
- await fireOnRequestError(error, req, "handler");
1013
- if (onPipelineError && error instanceof Error) onPipelineError(error, "middleware");
1014
- return new Response(null, { status: 500 });
1015
- }
1016
- }
1017
- applyCookieJar(responseHeaders);
1018
- try {
1019
- const renderFn = () => render(req, match, responseHeaders, requestHeaderOverlay, interception);
1020
- const response = await withSpan("timber.render", { "http.route": canonicalPathname }, () => serverTiming === "detailed" ? withTiming("render", "RSC + SSR render", renderFn) : renderFn());
1021
- markResponseFlushed();
1022
- return response;
1023
- } catch (error) {
1024
- if (error instanceof DenySignal) return new Response(null, { status: error.status });
1025
- if (error instanceof RedirectSignal) {
1026
- if ((req.headers.get("Accept") ?? "").includes("text/x-component")) {
1027
- responseHeaders.set("X-Timber-Redirect", error.location);
1028
- return new Response(null, {
1029
- status: 204,
1030
- headers: responseHeaders
1031
- });
1032
- }
1033
- responseHeaders.set("Location", error.location);
1034
- return new Response(null, {
1035
- status: error.status,
1036
- headers: responseHeaders
1037
- });
1038
- }
1039
- logRenderError({
1040
- method,
1041
- path,
1042
- error
1043
- });
1044
- await fireOnRequestError(error, req, "render");
1045
- if (onPipelineError && error instanceof Error) onPipelineError(error, "render");
1046
- if (config.renderFallbackError) try {
1047
- return await config.renderFallbackError(error, req, responseHeaders);
1048
- } catch {}
1049
- return new Response(null, { status: 500 });
1050
- }
1051
- }
1052
- }
1053
- /**
1054
- * Fire the user's onRequestError hook with request context.
1055
- * Extracts request info from the Request object and calls the instrumentation hook.
1056
- */
1057
- async function fireOnRequestError(error, req, phase) {
1058
- const url = new URL(req.url);
1059
- const headersObj = {};
1060
- req.headers.forEach((v, k) => {
1061
- headersObj[k] = v;
1062
- });
1063
- await callOnRequestError(error, {
1064
- method: req.method,
1065
- path: url.pathname,
1066
- headers: headersObj
1067
- }, {
1068
- phase,
1069
- routePath: url.pathname,
1070
- routeType: "page",
1071
- traceId: traceId()
1072
- });
1073
- }
1074
- /**
1075
- * Apply all Set-Cookie headers from the cookie jar to a Headers object.
1076
- * Each cookie gets its own Set-Cookie header per RFC 6265 §4.1.
1077
- */
1078
- function applyCookieJar(headers) {
1079
- for (const value of getSetCookieHeaders()) headers.append("Set-Cookie", value);
1080
- }
1081
- /**
1082
- * Ensure a Response has mutable headers so the pipeline can safely append
1083
- * Set-Cookie and Server-Timing entries.
1084
- *
1085
- * `Response.redirect()` and some platform-level responses return objects
1086
- * with immutable headers. Calling `.set()` or `.append()` on them throws
1087
- * `TypeError: immutable`. This helper detects the immutable case by
1088
- * attempting a no-op write and, on failure, clones into a fresh Response
1089
- * with mutable headers.
1090
- */
1091
- function ensureMutableResponse(response) {
1092
- try {
1093
- response.headers.set("X-Timber-Probe", "1");
1094
- response.headers.delete("X-Timber-Probe");
1095
- return response;
1096
- } catch {
1097
- return new Response(response.body, {
1098
- status: response.status,
1099
- statusText: response.statusText,
1100
- headers: new Headers(response.headers)
1101
- });
1102
- }
1103
- }
1104
- //#endregion
1105
- //#region src/server/build-manifest.ts
1106
- /**
1107
- * Collect all CSS files needed for a matched route's segment chain.
1108
- *
1109
- * Walks segments root → leaf, collecting CSS for each layout and page.
1110
- * Deduplicates while preserving order (root layout CSS first).
1111
- */
1112
- function collectRouteCss(segments, manifest) {
1113
- const seen = /* @__PURE__ */ new Set();
1114
- const result = [];
1115
- for (const segment of segments) for (const file of [segment.layout, segment.page]) {
1116
- if (!file) continue;
1117
- const cssFiles = manifest.css[file.filePath];
1118
- if (!cssFiles) continue;
1119
- for (const url of cssFiles) if (!seen.has(url)) {
1120
- seen.add(url);
1121
- result.push(url);
1122
- }
1123
- }
1124
- return result;
1125
- }
1126
- /**
1127
- * Collect all font entries needed for a matched route's segment chain.
1128
- *
1129
- * Walks segments root → leaf, collecting fonts for each layout and page.
1130
- * Deduplicates by href while preserving order.
1131
- */
1132
- function collectRouteFonts(segments, manifest) {
1133
- const seen = /* @__PURE__ */ new Set();
1134
- const result = [];
1135
- for (const segment of segments) for (const file of [segment.layout, segment.page]) {
1136
- if (!file) continue;
1137
- const fonts = manifest.fonts[file.filePath];
1138
- if (!fonts) continue;
1139
- for (const entry of fonts) if (!seen.has(entry.href)) {
1140
- seen.add(entry.href);
1141
- result.push(entry);
1142
- }
1143
- }
1144
- return result;
1145
- }
1146
- /**
1147
- * Collect modulepreload URLs for a matched route's segment chain.
1148
- *
1149
- * Walks segments root → leaf, collecting transitive JS dependencies
1150
- * for each layout and page. Deduplicates across segments.
1151
- */
1152
- function collectRouteModulepreloads(segments, manifest) {
1153
- const seen = /* @__PURE__ */ new Set();
1154
- const result = [];
1155
- for (const segment of segments) for (const file of [segment.layout, segment.page]) {
1156
- if (!file) continue;
1157
- const preloads = manifest.modulepreload[file.filePath];
1158
- if (!preloads) continue;
1159
- for (const url of preloads) if (!seen.has(url)) {
1160
- seen.add(url);
1161
- result.push(url);
1162
- }
1163
- }
1164
- return result;
1165
- }
1166
- //#endregion
1167
- //#region src/server/early-hints.ts
1168
- /**
1169
- * 103 Early Hints utilities.
1170
- *
1171
- * Early Hints are sent before the final response to let the browser
1172
- * start fetching critical resources (CSS, fonts, JS) while the server
1173
- * is still rendering.
1174
- *
1175
- * The framework collects hints from two sources:
1176
- * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
1177
- * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
1178
- *
1179
- * Both are emitted as Link headers. Cloudflare CDN automatically converts
1180
- * Link headers into 103 Early Hints responses.
1181
- *
1182
- * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
1183
- */
1184
- /**
1185
- * Format a single EarlyHint as a Link header value.
1186
- *
1187
- * Examples:
1188
- * `</styles/root.css>; rel=preload; as=style`
1189
- * `</fonts/inter.woff2>; rel=preload; as=font; crossorigin=anonymous`
1190
- * `</_timber/client.js>; rel=modulepreload`
1191
- * `<https://fonts.googleapis.com>; rel=preconnect`
1192
- */
1193
- function formatLinkHeader(hint) {
1194
- let value = `<${hint.href}>; rel=${hint.rel}`;
1195
- if (hint.as !== void 0) value += `; as=${hint.as}`;
1196
- if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
1197
- if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
1198
- return value;
1199
- }
1200
- /**
1201
- * Collect all Link header strings for a matched route's segment chain.
1202
- *
1203
- * Walks the build manifest to emit hints for:
1204
- * - CSS stylesheets (rel=preload; as=style)
1205
- * - Font assets (rel=preload; as=font; crossorigin)
1206
- * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
1207
- *
1208
- * Also emits global CSS from the `_global` manifest key. Route files
1209
- * are server components that don't appear in the client bundle, so
1210
- * per-route CSS keying doesn't work with the RSC plugin. The `_global`
1211
- * key contains all CSS assets from the client build — fine for early
1212
- * hints since they're just prefetch signals.
1213
- *
1214
- * Returns formatted Link header strings, deduplicated, root → leaf order.
1215
- * Returns an empty array in dev mode (manifest is empty).
1216
- */
1217
- function collectEarlyHintHeaders(segments, manifest, options) {
1218
- const result = [];
1219
- const seen = /* @__PURE__ */ new Set();
1220
- const add = (header) => {
1221
- if (!seen.has(header)) {
1222
- seen.add(header);
1223
- result.push(header);
1224
- }
1225
- };
1226
- for (const url of collectRouteCss(segments, manifest)) add(formatLinkHeader({
1227
- href: url,
1228
- rel: "preload",
1229
- as: "style"
1230
- }));
1231
- for (const url of manifest.css["_global"] ?? []) add(formatLinkHeader({
1232
- href: url,
1233
- rel: "preload",
1234
- as: "style"
1235
- }));
1236
- for (const font of collectRouteFonts(segments, manifest)) add(formatLinkHeader({
1237
- href: font.href,
1238
- rel: "preload",
1239
- as: "font",
1240
- crossOrigin: "anonymous"
1241
- }));
1242
- if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(formatLinkHeader({
1243
- href: url,
1244
- rel: "modulepreload"
1245
- }));
1246
- return result;
1247
- }
1248
- //#endregion
1249
- //#region src/server/early-hints-sender.ts
1250
- /**
1251
- * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
1252
- *
1253
- * The pipeline collects Link headers for CSS, fonts, and JS chunks at
1254
- * route-match time. On platforms that support it (Node.js v18.11+, Bun),
1255
- * the adapter can send these as a 103 Early Hints interim response before
1256
- * the final response is ready.
1257
- *
1258
- * This module provides an ALS-based bridge: the generated entry point
1259
- * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
1260
- * binding a per-request sender function. The pipeline calls
1261
- * `sendEarlyHints103()` to fire the 103 if a sender is available.
1262
- *
1263
- * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
1264
- * converts Link headers into 103 automatically), no sender is installed
1265
- * and `sendEarlyHints103()` is a no-op.
1266
- *
1267
- * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
1268
- */
1269
- /**
1270
- * Run a function with a per-request early hints sender installed.
1271
- *
1272
- * Called by generated entry points (e.g., Nitro node-server/bun) to
1273
- * bind the platform's writeEarlyHints capability for the request duration.
1274
- */
1275
- function runWithEarlyHintsSender(sender, fn) {
1276
- return earlyHintsSenderAls.run(sender, fn);
1277
- }
1278
- /**
1279
- * Send collected Link headers as a 103 Early Hints response.
1280
- *
1281
- * No-op if no sender is installed for the current request (e.g., on
1282
- * Cloudflare where the CDN handles 103 automatically, or in dev mode).
1283
- *
1284
- * Non-fatal: errors from the sender are caught and silently ignored.
1285
- */
1286
- function sendEarlyHints103(links) {
1287
- if (!links.length) return;
1288
- const sender = earlyHintsSenderAls.getStore();
1289
- if (!sender) return;
1290
- try {
1291
- sender(links);
1292
- } catch {}
1293
- }
1294
- //#endregion
1295
- //#region src/server/tree-builder.ts
1296
- /**
1297
- * Build the unified element tree from a matched segment chain.
1298
- *
1299
- * Construction is bottom-up:
1300
- * 1. Start with the page component (leaf segment)
1301
- * 2. Wrap in status-code error boundaries (fallback chain)
1302
- * 3. Wrap in AccessGate (if segment has access.ts)
1303
- * 4. Pass as children to the segment's layout
1304
- * 5. Repeat up the segment chain to root
1305
- *
1306
- * Parallel slots are resolved at each layout level and composed as named props.
1307
- */
1308
- async function buildElementTree(config) {
1309
- const { segments, params, searchParams, loadModule, createElement, errorBoundaryComponent } = config;
1310
- if (segments.length === 0) throw new Error("[timber] buildElementTree: empty segment chain");
1311
- const leaf = segments[segments.length - 1];
1312
- if (leaf.route && !leaf.page) return {
1313
- tree: null,
1314
- isApiRoute: true
1315
- };
1316
- const PageComponent = (leaf.page ? await loadModule(leaf.page) : null)?.default;
1317
- 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.`);
1318
- let element = createElement(PageComponent, {
1319
- params,
1320
- searchParams
1321
- });
1322
- for (let i = segments.length - 1; i >= 0; i--) {
1323
- const segment = segments[i];
1324
- element = await wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent);
1325
- if (segment.access) {
1326
- const accessFn = (await loadModule(segment.access)).default;
1327
- element = createElement("timber:access-gate", {
1328
- accessFn,
1329
- params,
1330
- searchParams,
1331
- segmentName: segment.segmentName,
1332
- children: element
1333
- });
1334
- }
1335
- if (segment.layout) {
1336
- const LayoutComponent = (await loadModule(segment.layout)).default;
1337
- if (LayoutComponent) {
1338
- const slotProps = {};
1339
- if (segment.slots.size > 0) for (const [slotName, slotNode] of segment.slots) slotProps[slotName] = await buildSlotElement(slotNode, params, searchParams, loadModule, createElement, errorBoundaryComponent);
1340
- element = createElement(LayoutComponent, {
1341
- ...slotProps,
1342
- params,
1343
- searchParams,
1344
- children: element
1345
- });
1346
- }
1347
- }
1348
- }
1349
- return {
1350
- tree: element,
1351
- isApiRoute: false
1352
- };
1353
- }
1354
- /**
1355
- * Build the element tree for a parallel slot.
1356
- *
1357
- * Slots have their own access.ts (SlotAccessGate) and error boundaries.
1358
- * On access denial: denied.tsx → default.tsx → null (graceful degradation).
1359
- */
1360
- async function buildSlotElement(slotNode, params, searchParams, loadModule, createElement, errorBoundaryComponent) {
1361
- const PageComponent = (slotNode.page ? await loadModule(slotNode.page) : null)?.default;
1362
- const DefaultComponent = (slotNode.default ? await loadModule(slotNode.default) : null)?.default;
1363
- if (!PageComponent) return DefaultComponent ? createElement(DefaultComponent, {
1364
- params,
1365
- searchParams
1366
- }) : null;
1367
- let element = createElement(PageComponent, {
1368
- params,
1369
- searchParams
1370
- });
1371
- element = await wrapWithErrorBoundaries(slotNode, element, loadModule, createElement, errorBoundaryComponent);
1372
- if (slotNode.access) {
1373
- const accessFn = (await loadModule(slotNode.access)).default;
1374
- const DeniedComponent = (slotNode.denied ? await loadModule(slotNode.denied) : null)?.default;
1375
- element = createElement("timber:slot-access-gate", {
1376
- accessFn,
1377
- params,
1378
- searchParams,
1379
- deniedFallback: DeniedComponent ? createElement(DeniedComponent, {
1380
- slot: slotNode.segmentName.replace(/^@/, ""),
1381
- dangerouslyPassData: void 0
1382
- }) : null,
1383
- defaultFallback: DefaultComponent ? createElement(DefaultComponent, {
1384
- params,
1385
- searchParams
1386
- }) : null,
1387
- children: element
1388
- });
1389
- }
1390
- return element;
1391
- }
1392
- /**
1393
- * Wrap an element with error boundaries from a segment's status-code files.
1394
- *
1395
- * Wrapping order (innermost to outermost):
1396
- * 1. Specific status files (503.tsx, 429.tsx, etc.)
1397
- * 2. Category catch-alls (4xx.tsx, 5xx.tsx)
1398
- * 3. error.tsx (general error boundary)
1399
- *
1400
- * This creates the fallback chain described in design/10-error-handling.md.
1401
- */
1402
- async function wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent) {
1403
- if (segment.statusFiles) {
1404
- for (const [key, file] of segment.statusFiles) if (key !== "4xx" && key !== "5xx") {
1405
- const status = parseInt(key, 10);
1406
- if (!isNaN(status)) {
1407
- const Component = (await loadModule(file)).default;
1408
- if (Component) element = createElement(errorBoundaryComponent, {
1409
- fallbackComponent: Component,
1410
- status,
1411
- children: element
1412
- });
1413
- }
1414
- }
1415
- for (const [key, file] of segment.statusFiles) if (key === "4xx" || key === "5xx") {
1416
- const Component = (await loadModule(file)).default;
1417
- if (Component) element = createElement(errorBoundaryComponent, {
1418
- fallbackComponent: Component,
1419
- status: key === "4xx" ? 400 : 500,
1420
- children: element
1421
- });
1422
- }
1423
- }
1424
- if (segment.error) {
1425
- const ErrorComponent = (await loadModule(segment.error)).default;
1426
- if (ErrorComponent) element = createElement(errorBoundaryComponent, {
1427
- fallbackComponent: ErrorComponent,
1428
- children: element
1429
- });
1430
- }
1431
- return element;
1432
- }
1433
- //#endregion
1434
- //#region src/server/access-gate.tsx
1435
- /**
1436
- * AccessGate and SlotAccessGate — framework-injected async server components.
1437
- *
1438
- * AccessGate wraps each segment's layout in the element tree. It calls the
1439
- * segment's access.ts before the layout renders. If access.ts calls deny()
1440
- * or redirect(), the signal propagates as a render-phase throw — caught by
1441
- * the flush controller to produce the correct HTTP status code.
1442
- *
1443
- * SlotAccessGate wraps parallel slot content. On denial, it renders the
1444
- * graceful degradation chain: denied.tsx → default.tsx → null. Slot denial
1445
- * does not affect the HTTP status code.
1446
- *
1447
- * See design/04-authorization.md and design/02-rendering-pipeline.md §"AccessGate"
1448
- */
1449
- /**
1450
- * Framework-injected access gate for segments.
1451
- *
1452
- * When a pre-computed `verdict` prop is provided (from the pre-render pass
1453
- * in route-element-builder.ts), AccessGate replays it synchronously — no
1454
- * async, no re-execution of access.ts, immune to Suspense timing. The OTEL
1455
- * span was already emitted during the pre-render pass.
1456
- *
1457
- * When no verdict is provided (backward compat with tree-builder.ts),
1458
- * AccessGate calls accessFn directly with OTEL instrumentation.
1459
- *
1460
- * access.ts is a pure gate — return values are discarded. The layout below
1461
- * gets the same data by calling the same cached functions (React.cache dedup).
1462
- */
1463
- function AccessGate(props) {
1464
- const { accessFn, params, searchParams, segmentName, verdict, children } = props;
1465
- if (verdict !== void 0) {
1466
- if (verdict === "pass") return children;
1467
- throw verdict;
1468
- }
1469
- return accessGateFallback(accessFn, params, searchParams, segmentName, children);
1470
- }
1471
- /**
1472
- * Async fallback for AccessGate when no pre-computed verdict is available.
1473
- * Calls accessFn with OTEL instrumentation.
1474
- */
1475
- async function accessGateFallback(accessFn, params, searchParams, segmentName, children) {
1476
- await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
1477
- try {
1478
- await accessFn({
1479
- params,
1480
- searchParams
1481
- });
1482
- await setSpanAttribute("timber.result", "pass");
1483
- } catch (error) {
1484
- if (error instanceof DenySignal) {
1485
- await setSpanAttribute("timber.result", "deny");
1486
- await setSpanAttribute("timber.deny_status", error.status);
1487
- if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
1488
- } else if (error instanceof RedirectSignal) await setSpanAttribute("timber.result", "redirect");
1489
- throw error;
1490
- }
1491
- });
1492
- return children;
1493
- }
1494
- /**
1495
- * Framework-injected access gate for parallel slots.
1496
- *
1497
- * On denial, graceful degradation: denied.tsx → default.tsx → null.
1498
- * The HTTP status code is unaffected — slot denial is a UI concern, not
1499
- * a protocol concern. The parent layout and sibling slots still render.
1500
- *
1501
- * redirect() in slot access.ts is a dev-mode error — redirecting from a
1502
- * slot doesn't make architectural sense.
1503
- */
1504
- async function SlotAccessGate(props) {
1505
- const { accessFn, params, searchParams, deniedFallback, defaultFallback, children } = props;
1506
- try {
1507
- await accessFn({
1508
- params,
1509
- searchParams
1510
- });
1511
- } catch (error) {
1512
- if (error instanceof DenySignal) return deniedFallback ?? defaultFallback ?? null;
1513
- if (error instanceof RedirectSignal) {
1514
- 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.");
1515
- return deniedFallback ?? defaultFallback ?? null;
1516
- }
1517
- if (isDebug()) console.warn("[timber] Unhandled error in slot access.ts. Use deny() for access control, not unhandled throws.", error);
1518
- throw error;
1519
- }
1520
- return children;
1521
- }
1522
- //#endregion
1523
- //#region src/server/status-code-resolver.ts
1524
- /**
1525
- * Maps legacy file convention names to their corresponding HTTP status codes.
1526
- * Only used in the 4xx component fallback chain.
1527
- */
1528
- var LEGACY_FILE_TO_STATUS = {
1529
- "not-found": 404,
1530
- "forbidden": 403,
1531
- "unauthorized": 401
1532
- };
1533
- /**
1534
- * Resolve the status-code file to render for a given HTTP status code.
1535
- *
1536
- * Walks the segment chain from leaf to root following the fallback chain
1537
- * defined in design/10-error-handling.md. Returns null if no file is found
1538
- * (caller should render the framework default).
1539
- *
1540
- * @param status - The HTTP status code (4xx or 5xx).
1541
- * @param segments - The matched segment chain from root (index 0) to leaf (last).
1542
- * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
1543
- */
1544
- function resolveStatusFile(status, segments, format = "component") {
1545
- if (status >= 400 && status <= 499) return format === "json" ? resolve4xxJson(status, segments) : resolve4xx(status, segments);
1546
- if (status >= 500 && status <= 599) return format === "json" ? resolve5xxJson(status, segments) : resolve5xx(status, segments);
1547
- return null;
1548
- }
1549
- /**
1550
- * 4xx component fallback chain (three separate passes):
1551
- * Pass 1 — status files (leaf → root): {status}.tsx → 4xx.tsx
1552
- * Pass 2 — legacy compat (leaf → root): not-found.tsx / forbidden.tsx / unauthorized.tsx
1553
- * Pass 3 — error.tsx (leaf → root)
1554
- */
1555
- function resolve4xx(status, segments) {
1556
- const statusStr = String(status);
1557
- for (let i = segments.length - 1; i >= 0; i--) {
1558
- const segment = segments[i];
1559
- if (!segment.statusFiles) continue;
1560
- const exact = segment.statusFiles.get(statusStr);
1561
- if (exact) return {
1562
- file: exact,
1563
- status,
1564
- kind: "exact",
1565
- segmentIndex: i
1566
- };
1567
- const category = segment.statusFiles.get("4xx");
1568
- if (category) return {
1569
- file: category,
1570
- status,
1571
- kind: "category",
1572
- segmentIndex: i
1573
- };
1574
- }
1575
- for (let i = segments.length - 1; i >= 0; i--) {
1576
- const segment = segments[i];
1577
- if (!segment.legacyStatusFiles) continue;
1578
- for (const [name, legacyStatus] of Object.entries(LEGACY_FILE_TO_STATUS)) if (legacyStatus === status) {
1579
- const file = segment.legacyStatusFiles.get(name);
1580
- if (file) return {
1581
- file,
1582
- status,
1583
- kind: "legacy",
1584
- segmentIndex: i
1585
- };
1586
- }
1587
- }
1588
- for (let i = segments.length - 1; i >= 0; i--) if (segments[i].error) return {
1589
- file: segments[i].error,
1590
- status,
1591
- kind: "error",
1592
- segmentIndex: i
1593
- };
1594
- return null;
1595
- }
1596
- /**
1597
- * 4xx JSON fallback chain (single pass):
1598
- * Pass 1 — json status files (leaf → root): {status}.json → 4xx.json
1599
- * No legacy compat, no error.tsx — JSON chain terminates at category catch-all.
1600
- */
1601
- function resolve4xxJson(status, segments) {
1602
- const statusStr = String(status);
1603
- for (let i = segments.length - 1; i >= 0; i--) {
1604
- const segment = segments[i];
1605
- if (!segment.jsonStatusFiles) continue;
1606
- const exact = segment.jsonStatusFiles.get(statusStr);
1607
- if (exact) return {
1608
- file: exact,
1609
- status,
1610
- kind: "exact",
1611
- segmentIndex: i
1612
- };
1613
- const category = segment.jsonStatusFiles.get("4xx");
1614
- if (category) return {
1615
- file: category,
1616
- status,
1617
- kind: "category",
1618
- segmentIndex: i
1619
- };
1620
- }
1621
- return null;
1622
- }
1623
- /**
1624
- * 5xx component fallback chain (single pass, per-segment):
1625
- * At each segment (leaf → root): {status}.tsx → 5xx.tsx → error.tsx
1626
- */
1627
- function resolve5xx(status, segments) {
1628
- const statusStr = String(status);
1629
- for (let i = segments.length - 1; i >= 0; i--) {
1630
- const segment = segments[i];
1631
- if (segment.statusFiles) {
1632
- const exact = segment.statusFiles.get(statusStr);
1633
- if (exact) return {
1634
- file: exact,
1635
- status,
1636
- kind: "exact",
1637
- segmentIndex: i
1638
- };
1639
- const category = segment.statusFiles.get("5xx");
1640
- if (category) return {
1641
- file: category,
1642
- status,
1643
- kind: "category",
1644
- segmentIndex: i
1645
- };
1646
- }
1647
- if (segment.error) return {
1648
- file: segment.error,
1649
- status,
1650
- kind: "error",
1651
- segmentIndex: i
1652
- };
1653
- }
1654
- return null;
1655
- }
1656
- /**
1657
- * 5xx JSON fallback chain (single pass):
1658
- * At each segment (leaf → root): {status}.json → 5xx.json
1659
- * No error.tsx equivalent — JSON chain terminates at category catch-all.
1660
- */
1661
- function resolve5xxJson(status, segments) {
1662
- const statusStr = String(status);
1663
- for (let i = segments.length - 1; i >= 0; i--) {
1664
- const segment = segments[i];
1665
- if (!segment.jsonStatusFiles) continue;
1666
- const exact = segment.jsonStatusFiles.get(statusStr);
1667
- if (exact) return {
1668
- file: exact,
1669
- status,
1670
- kind: "exact",
1671
- segmentIndex: i
1672
- };
1673
- const category = segment.jsonStatusFiles.get("5xx");
1674
- if (category) return {
1675
- file: category,
1676
- status,
1677
- kind: "category",
1678
- segmentIndex: i
1679
- };
1680
- }
1681
- return null;
1682
- }
1683
- /**
1684
- * Resolve the denial file for a parallel route slot.
1685
- *
1686
- * Slot denial is graceful degradation — no HTTP status on the wire.
1687
- * Fallback chain: denied.tsx → default.tsx → null.
1688
- *
1689
- * @param slotNode - The segment node for the slot (segmentType === 'slot').
1690
- */
1691
- function resolveSlotDenied(slotNode) {
1692
- const slotName = slotNode.segmentName.replace(/^@/, "");
1693
- if (slotNode.denied) return {
1694
- file: slotNode.denied,
1695
- slotName,
1696
- kind: "denied"
1697
- };
1698
- if (slotNode.default) return {
1699
- file: slotNode.default,
1700
- slotName,
1701
- kind: "default"
1702
- };
1703
- return null;
1704
- }
1705
- //#endregion
1706
- //#region src/server/flush.ts
1707
- /**
1708
- * Flush controller for timber.js rendering.
1709
- *
1710
- * Holds the response until `onShellReady` fires, then commits the HTTP status
1711
- * code and flushes the shell. Render-phase signals (deny, redirect, unhandled
1712
- * throws) caught before flush produce correct HTTP status codes.
1713
- *
1714
- * See design/02-rendering-pipeline.md §"The Flush Point" and §"The Hold Window"
1715
- */
1716
- /**
1717
- * Execute a render and hold the response until the shell is ready.
1718
- *
1719
- * The flush controller:
1720
- * 1. Calls the render function to start renderToReadableStream
1721
- * 2. Waits for shellReady (onShellReady)
1722
- * 3. If a render-phase signal was thrown (deny, redirect, error), produces
1723
- * the correct HTTP status code
1724
- * 4. If the shell rendered successfully, commits the status and streams
1725
- *
1726
- * Render-phase signals caught before flush:
1727
- * - `DenySignal` → HTTP 4xx with appropriate status code
1728
- * - `RedirectSignal` → HTTP 3xx with Location header
1729
- * - `RenderError` → HTTP status from error (default 500)
1730
- * - Unhandled error → HTTP 500
1731
- *
1732
- * @param renderFn - Function that starts the React render.
1733
- * @param options - Flush configuration.
1734
- * @returns The committed HTTP Response.
1735
- */
1736
- async function flushResponse(renderFn, options = {}) {
1737
- const { responseHeaders = new Headers(), defaultStatus = 200 } = options;
1738
- let renderResult;
1739
- try {
1740
- renderResult = await renderFn();
1741
- } catch (error) {
1742
- return handleSignal(error, responseHeaders);
1743
- }
1744
- try {
1745
- await renderResult.shellReady;
1746
- } catch (error) {
1747
- return handleSignal(error, responseHeaders);
1748
- }
1749
- responseHeaders.set("Content-Type", "text/html; charset=utf-8");
1750
- return {
1751
- response: new Response(renderResult.stream, {
1752
- status: defaultStatus,
1753
- headers: responseHeaders
1754
- }),
1755
- status: defaultStatus,
1756
- isRedirect: false,
1757
- isDenial: false
1758
- };
1759
- }
1760
- /**
1761
- * Handle a render-phase signal and produce the correct HTTP response.
1762
- */
1763
- function handleSignal(error, responseHeaders) {
1764
- if (error instanceof RedirectSignal) {
1765
- responseHeaders.set("Location", error.location);
1766
- return {
1767
- response: new Response(null, {
1768
- status: error.status,
1769
- headers: responseHeaders
1770
- }),
1771
- status: error.status,
1772
- isRedirect: true,
1773
- isDenial: false
1774
- };
1775
- }
1776
- if (error instanceof DenySignal) return {
1777
- response: new Response(null, {
1778
- status: error.status,
1779
- headers: responseHeaders
1780
- }),
1781
- status: error.status,
1782
- isRedirect: false,
1783
- isDenial: true
1784
- };
1785
- if (error instanceof RenderError) return {
1786
- response: new Response(null, {
1787
- status: error.status,
1788
- headers: responseHeaders
1789
- }),
1790
- status: error.status,
1791
- isRedirect: false,
1792
- isDenial: false
1793
- };
1794
- console.error("[timber] Unhandled render-phase error:", error);
1795
- return {
1796
- response: new Response(null, {
1797
- status: 500,
1798
- headers: responseHeaders
1799
- }),
1800
- status: 500,
1801
- isRedirect: false,
1802
- isDenial: false
1803
- };
1804
- }
1805
- //#endregion
1806
- //#region src/server/csrf.ts
1807
- /** HTTP methods that are considered safe (no mutation). */
1808
- var SAFE_METHODS = new Set([
1809
- "GET",
1810
- "HEAD",
1811
- "OPTIONS"
1812
- ]);
1813
- /**
1814
- * Validate the Origin header against the request's Host.
1815
- *
1816
- * For mutation methods (POST, PUT, PATCH, DELETE):
1817
- * - If `csrf: false`, skip validation.
1818
- * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
1819
- * - Otherwise, Origin's host must match the request's Host header.
1820
- *
1821
- * Safe methods (GET, HEAD, OPTIONS) always pass.
1822
- */
1823
- function validateCsrf(req, config) {
1824
- if (SAFE_METHODS.has(req.method)) return { ok: true };
1825
- if (config.csrf === false) return { ok: true };
1826
- const origin = req.headers.get("Origin");
1827
- if (!origin) return {
1828
- ok: false,
1829
- status: 403
1830
- };
1831
- if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
1832
- ok: false,
1833
- status: 403
1834
- };
1835
- const host = req.headers.get("Host");
1836
- if (!host) return {
1837
- ok: false,
1838
- status: 403
1839
- };
1840
- let originHost;
1841
- try {
1842
- originHost = new URL(origin).host;
1843
- } catch {
1844
- return {
1845
- ok: false,
1846
- status: 403
1847
- };
1848
- }
1849
- return originHost === host ? { ok: true } : {
1850
- ok: false,
1851
- status: 403
1852
- };
1853
- }
1854
- //#endregion
1855
- //#region src/server/body-limits.ts
1856
- var KB = 1024;
1857
- var MB = 1024 * KB;
1858
- var GB = 1024 * MB;
1859
- var DEFAULT_LIMITS = {
1860
- actionBodySize: 1 * MB,
1861
- uploadBodySize: 10 * MB,
1862
- maxFields: 100
1863
- };
1864
- var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
1865
- /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
1866
- function parseBodySize(size) {
1867
- const match = SIZE_PATTERN.exec(size.trim());
1868
- if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
1869
- const value = Number.parseFloat(match[1]);
1870
- const unit = (match[2] ?? "").toLowerCase();
1871
- switch (unit) {
1872
- case "kb": return Math.floor(value * KB);
1873
- case "mb": return Math.floor(value * MB);
1874
- case "gb": return Math.floor(value * GB);
1875
- case "": return Math.floor(value);
1876
- default: throw new Error(`Unknown size unit: "${unit}"`);
1877
- }
1878
- }
1879
- /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
1880
- function enforceBodyLimits(req, kind, config) {
1881
- const contentLength = req.headers.get("Content-Length");
1882
- if (!contentLength) return {
1883
- ok: false,
1884
- status: 411
1885
- };
1886
- const bodySize = Number.parseInt(contentLength, 10);
1887
- if (Number.isNaN(bodySize)) return {
1888
- ok: false,
1889
- status: 411
1890
- };
1891
- return bodySize <= resolveLimit(kind, config) ? { ok: true } : {
1892
- ok: false,
1893
- status: 413
1894
- };
1895
- }
1896
- /**
1897
- * Resolve the byte limit for a given body kind, using config overrides or defaults.
1898
- */
1899
- function resolveLimit(kind, config) {
1900
- const userLimits = config.limits;
1901
- if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
1902
- return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
1903
- }
1904
- //#endregion
1905
- //#region src/server/metadata-social.ts
1906
- /**
1907
- * Render Open Graph metadata into head element descriptors.
1908
- *
1909
- * Handles og:title, og:description, og:image (with dimensions/alt),
1910
- * og:video, og:audio, og:article:author, and other OG properties.
1911
- */
1912
- function renderOpenGraph(og, elements) {
1913
- const simpleProps = [
1914
- ["og:title", og.title],
1915
- ["og:description", og.description],
1916
- ["og:url", og.url],
1917
- ["og:site_name", og.siteName],
1918
- ["og:locale", og.locale],
1919
- ["og:type", og.type],
1920
- ["og:article:published_time", og.publishedTime],
1921
- ["og:article:modified_time", og.modifiedTime]
1922
- ];
1923
- for (const [property, content] of simpleProps) if (content) elements.push({
1924
- tag: "meta",
1925
- attrs: {
1926
- property,
1927
- content
1928
- }
1929
- });
1930
- if (og.images) if (typeof og.images === "string") elements.push({
1931
- tag: "meta",
1932
- attrs: {
1933
- property: "og:image",
1934
- content: og.images
1935
- }
1936
- });
1937
- else {
1938
- const imgList = Array.isArray(og.images) ? og.images : [og.images];
1939
- for (const img of imgList) {
1940
- elements.push({
1941
- tag: "meta",
1942
- attrs: {
1943
- property: "og:image",
1944
- content: img.url
1945
- }
1946
- });
1947
- if (img.width) elements.push({
1948
- tag: "meta",
1949
- attrs: {
1950
- property: "og:image:width",
1951
- content: String(img.width)
1952
- }
1953
- });
1954
- if (img.height) elements.push({
1955
- tag: "meta",
1956
- attrs: {
1957
- property: "og:image:height",
1958
- content: String(img.height)
1959
- }
1960
- });
1961
- if (img.alt) elements.push({
1962
- tag: "meta",
1963
- attrs: {
1964
- property: "og:image:alt",
1965
- content: img.alt
1966
- }
1967
- });
1968
- }
1969
- }
1970
- if (og.videos) for (const video of og.videos) elements.push({
1971
- tag: "meta",
1972
- attrs: {
1973
- property: "og:video",
1974
- content: video.url
1975
- }
1976
- });
1977
- if (og.audio) for (const audio of og.audio) elements.push({
1978
- tag: "meta",
1979
- attrs: {
1980
- property: "og:audio",
1981
- content: audio.url
1982
- }
1983
- });
1984
- if (og.authors) for (const author of og.authors) elements.push({
1985
- tag: "meta",
1986
- attrs: {
1987
- property: "og:article:author",
1988
- content: author
1989
- }
1990
- });
1991
- }
1992
- /**
1993
- * Render Twitter Card metadata into head element descriptors.
1994
- *
1995
- * Handles twitter:card, twitter:site, twitter:title, twitter:image,
1996
- * twitter:player, and twitter:app (per-platform name/id/url).
1997
- */
1998
- function renderTwitter(tw, elements) {
1999
- const simpleProps = [
2000
- ["twitter:card", tw.card],
2001
- ["twitter:site", tw.site],
2002
- ["twitter:site:id", tw.siteId],
2003
- ["twitter:title", tw.title],
2004
- ["twitter:description", tw.description],
2005
- ["twitter:creator", tw.creator],
2006
- ["twitter:creator:id", tw.creatorId]
2007
- ];
2008
- for (const [name, content] of simpleProps) if (content) elements.push({
2009
- tag: "meta",
2010
- attrs: {
2011
- name,
2012
- content
2013
- }
2014
- });
2015
- if (tw.images) if (typeof tw.images === "string") elements.push({
2016
- tag: "meta",
2017
- attrs: {
2018
- name: "twitter:image",
2019
- content: tw.images
2020
- }
2021
- });
2022
- else {
2023
- const imgList = Array.isArray(tw.images) ? tw.images : [tw.images];
2024
- for (const img of imgList) {
2025
- const url = typeof img === "string" ? img : img.url;
2026
- elements.push({
2027
- tag: "meta",
2028
- attrs: {
2029
- name: "twitter:image",
2030
- content: url
2031
- }
2032
- });
2033
- }
2034
- }
2035
- if (tw.players) for (const player of tw.players) {
2036
- elements.push({
2037
- tag: "meta",
2038
- attrs: {
2039
- name: "twitter:player",
2040
- content: player.playerUrl
2041
- }
2042
- });
2043
- if (player.width) elements.push({
2044
- tag: "meta",
2045
- attrs: {
2046
- name: "twitter:player:width",
2047
- content: String(player.width)
2048
- }
2049
- });
2050
- if (player.height) elements.push({
2051
- tag: "meta",
2052
- attrs: {
2053
- name: "twitter:player:height",
2054
- content: String(player.height)
2055
- }
2056
- });
2057
- if (player.streamUrl) elements.push({
2058
- tag: "meta",
2059
- attrs: {
2060
- name: "twitter:player:stream",
2061
- content: player.streamUrl
2062
- }
2063
- });
2064
- }
2065
- if (tw.app) {
2066
- const platforms = [
2067
- ["iPhone", "iphone"],
2068
- ["iPad", "ipad"],
2069
- ["googlePlay", "googleplay"]
2070
- ];
2071
- if (tw.app.name) {
2072
- for (const [key, tag] of platforms) if (tw.app.id?.[key]) elements.push({
2073
- tag: "meta",
2074
- attrs: {
2075
- name: `twitter:app:name:${tag}`,
2076
- content: tw.app.name
2077
- }
2078
- });
2079
- }
2080
- for (const [key, tag] of platforms) {
2081
- const id = tw.app.id?.[key];
2082
- if (id) elements.push({
2083
- tag: "meta",
2084
- attrs: {
2085
- name: `twitter:app:id:${tag}`,
2086
- content: id
2087
- }
2088
- });
2089
- }
2090
- for (const [key, tag] of platforms) {
2091
- const url = tw.app.url?.[key];
2092
- if (url) elements.push({
2093
- tag: "meta",
2094
- attrs: {
2095
- name: `twitter:app:url:${tag}`,
2096
- content: url
2097
- }
2098
- });
2099
- }
2100
- }
2101
- }
2102
- //#endregion
2103
- //#region src/server/metadata-platform.ts
2104
- /**
2105
- * Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
2106
- */
2107
- function renderIcons(icons, elements) {
2108
- if (icons.icon) {
2109
- if (typeof icons.icon === "string") elements.push({
2110
- tag: "link",
2111
- attrs: {
2112
- rel: "icon",
2113
- href: icons.icon
2114
- }
2115
- });
2116
- else if (Array.isArray(icons.icon)) for (const icon of icons.icon) {
2117
- const attrs = {
2118
- rel: "icon",
2119
- href: icon.url
2120
- };
2121
- if (icon.sizes) attrs.sizes = icon.sizes;
2122
- if (icon.type) attrs.type = icon.type;
2123
- elements.push({
2124
- tag: "link",
2125
- attrs
2126
- });
2127
- }
2128
- }
2129
- if (icons.shortcut) {
2130
- const urls = Array.isArray(icons.shortcut) ? icons.shortcut : [icons.shortcut];
2131
- for (const url of urls) elements.push({
2132
- tag: "link",
2133
- attrs: {
2134
- rel: "shortcut icon",
2135
- href: url
2136
- }
2137
- });
2138
- }
2139
- if (icons.apple) {
2140
- if (typeof icons.apple === "string") elements.push({
2141
- tag: "link",
2142
- attrs: {
2143
- rel: "apple-touch-icon",
2144
- href: icons.apple
2145
- }
2146
- });
2147
- else if (Array.isArray(icons.apple)) for (const icon of icons.apple) {
2148
- const attrs = {
2149
- rel: "apple-touch-icon",
2150
- href: icon.url
2151
- };
2152
- if (icon.sizes) attrs.sizes = icon.sizes;
2153
- elements.push({
2154
- tag: "link",
2155
- attrs
2156
- });
2157
- }
2158
- }
2159
- if (icons.other) for (const icon of icons.other) {
2160
- const attrs = {
2161
- rel: icon.rel,
2162
- href: icon.url
2163
- };
2164
- if (icon.sizes) attrs.sizes = icon.sizes;
2165
- if (icon.type) attrs.type = icon.type;
2166
- elements.push({
2167
- tag: "link",
2168
- attrs
2169
- });
2170
- }
2171
- }
2172
- /**
2173
- * Render alternate link elements (canonical, hreflang, media, types).
2174
- */
2175
- function renderAlternates(alternates, elements) {
2176
- if (alternates.canonical) elements.push({
2177
- tag: "link",
2178
- attrs: {
2179
- rel: "canonical",
2180
- href: alternates.canonical
2181
- }
2182
- });
2183
- if (alternates.languages) for (const [lang, href] of Object.entries(alternates.languages)) elements.push({
2184
- tag: "link",
2185
- attrs: {
2186
- rel: "alternate",
2187
- hreflang: lang,
2188
- href
2189
- }
2190
- });
2191
- if (alternates.media) for (const [media, href] of Object.entries(alternates.media)) elements.push({
2192
- tag: "link",
2193
- attrs: {
2194
- rel: "alternate",
2195
- media,
2196
- href
2197
- }
2198
- });
2199
- if (alternates.types) for (const [type, href] of Object.entries(alternates.types)) elements.push({
2200
- tag: "link",
2201
- attrs: {
2202
- rel: "alternate",
2203
- type,
2204
- href
2205
- }
2206
- });
2207
- }
2208
- /**
2209
- * Render site verification meta tags (Google, Yahoo, Yandex, custom).
2210
- */
2211
- function renderVerification(verification, elements) {
2212
- const verificationProps = [
2213
- ["google-site-verification", verification.google],
2214
- ["y_key", verification.yahoo],
2215
- ["yandex-verification", verification.yandex]
2216
- ];
2217
- for (const [name, content] of verificationProps) if (content) elements.push({
2218
- tag: "meta",
2219
- attrs: {
2220
- name,
2221
- content
2222
- }
2223
- });
2224
- if (verification.other) for (const [name, value] of Object.entries(verification.other)) {
2225
- const content = Array.isArray(value) ? value.join(", ") : value;
2226
- elements.push({
2227
- tag: "meta",
2228
- attrs: {
2229
- name,
2230
- content
2231
- }
2232
- });
2233
- }
2234
- }
2235
- /**
2236
- * Render Apple Web App meta tags and startup image links.
2237
- */
2238
- function renderAppleWebApp(appleWebApp, elements) {
2239
- if (appleWebApp.capable) elements.push({
2240
- tag: "meta",
2241
- attrs: {
2242
- name: "apple-mobile-web-app-capable",
2243
- content: "yes"
2244
- }
2245
- });
2246
- if (appleWebApp.title) elements.push({
2247
- tag: "meta",
2248
- attrs: {
2249
- name: "apple-mobile-web-app-title",
2250
- content: appleWebApp.title
2251
- }
2252
- });
2253
- if (appleWebApp.statusBarStyle) elements.push({
2254
- tag: "meta",
2255
- attrs: {
2256
- name: "apple-mobile-web-app-status-bar-style",
2257
- content: appleWebApp.statusBarStyle
2258
- }
2259
- });
2260
- if (appleWebApp.startupImage) {
2261
- const images = Array.isArray(appleWebApp.startupImage) ? appleWebApp.startupImage : [{ url: appleWebApp.startupImage }];
2262
- for (const img of images) {
2263
- const attrs = {
2264
- rel: "apple-touch-startup-image",
2265
- href: typeof img === "string" ? img : img.url
2266
- };
2267
- if (typeof img === "object" && img.media) attrs.media = img.media;
2268
- elements.push({
2269
- tag: "link",
2270
- attrs
2271
- });
2272
- }
2273
- }
2274
- }
2275
- /**
2276
- * Render App Links (al:*) meta tags for deep linking across platforms.
2277
- */
2278
- function renderAppLinks(appLinks, elements) {
2279
- const platformEntries = [
2280
- ["ios", appLinks.ios],
2281
- ["android", appLinks.android],
2282
- ["windows", appLinks.windows],
2283
- ["windows_phone", appLinks.windowsPhone],
2284
- ["windows_universal", appLinks.windowsUniversal]
2285
- ];
2286
- for (const [platform, entries] of platformEntries) {
2287
- if (!entries) continue;
2288
- for (const entry of entries) for (const [key, value] of Object.entries(entry)) if (value !== void 0 && value !== null) elements.push({
2289
- tag: "meta",
2290
- attrs: {
2291
- property: `al:${platform}:${key}`,
2292
- content: String(value)
2293
- }
2294
- });
2295
- }
2296
- if (appLinks.web) {
2297
- if (appLinks.web.url) elements.push({
2298
- tag: "meta",
2299
- attrs: {
2300
- property: "al:web:url",
2301
- content: appLinks.web.url
2302
- }
2303
- });
2304
- if (appLinks.web.shouldFallback !== void 0) elements.push({
2305
- tag: "meta",
2306
- attrs: {
2307
- property: "al:web:should_fallback",
2308
- content: appLinks.web.shouldFallback ? "true" : "false"
2309
- }
2310
- });
2311
- }
2312
- }
2313
- /**
2314
- * Render Apple iTunes smart banner meta tag.
2315
- */
2316
- function renderItunes(itunes, elements) {
2317
- const parts = [`app-id=${itunes.appId}`];
2318
- if (itunes.affiliateData) parts.push(`affiliate-data=${itunes.affiliateData}`);
2319
- if (itunes.appArgument) parts.push(`app-argument=${itunes.appArgument}`);
2320
- elements.push({
2321
- tag: "meta",
2322
- attrs: {
2323
- name: "apple-itunes-app",
2324
- content: parts.join(", ")
2325
- }
2326
- });
2327
- }
2328
- //#endregion
2329
- //#region src/server/metadata-render.ts
2330
- /**
2331
- * Convert resolved metadata into an array of head element descriptors.
2332
- *
2333
- * Each descriptor has a `tag` ('title', 'meta', 'link') and either
2334
- * `content` (for <title>) or `attrs` (for <meta>/<link>).
2335
- *
2336
- * The framework's MetadataResolver component consumes these descriptors
2337
- * and renders them into the <head>.
2338
- */
2339
- function renderMetadataToElements(metadata) {
2340
- const elements = [];
2341
- if (typeof metadata.title === "string") elements.push({
2342
- tag: "title",
2343
- content: metadata.title
2344
- });
2345
- const simpleMetaProps = [
2346
- ["description", metadata.description],
2347
- ["generator", metadata.generator],
2348
- ["application-name", metadata.applicationName],
2349
- ["referrer", metadata.referrer],
2350
- ["category", metadata.category],
2351
- ["creator", metadata.creator],
2352
- ["publisher", metadata.publisher]
2353
- ];
2354
- for (const [name, content] of simpleMetaProps) if (content) elements.push({
2355
- tag: "meta",
2356
- attrs: {
2357
- name,
2358
- content
2359
- }
2360
- });
2361
- if (metadata.keywords) {
2362
- const content = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
2363
- elements.push({
2364
- tag: "meta",
2365
- attrs: {
2366
- name: "keywords",
2367
- content
2368
- }
2369
- });
2370
- }
2371
- if (metadata.robots) {
2372
- const content = typeof metadata.robots === "string" ? metadata.robots : renderRobotsObject(metadata.robots);
2373
- elements.push({
2374
- tag: "meta",
2375
- attrs: {
2376
- name: "robots",
2377
- content
2378
- }
2379
- });
2380
- if (typeof metadata.robots === "object" && metadata.robots.googleBot) {
2381
- const gbContent = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : renderRobotsObject(metadata.robots.googleBot);
2382
- elements.push({
2383
- tag: "meta",
2384
- attrs: {
2385
- name: "googlebot",
2386
- content: gbContent
2387
- }
2388
- });
2389
- }
2390
- }
2391
- if (metadata.openGraph) renderOpenGraph(metadata.openGraph, elements);
2392
- if (metadata.twitter) renderTwitter(metadata.twitter, elements);
2393
- if (metadata.icons) renderIcons(metadata.icons, elements);
2394
- if (metadata.manifest) elements.push({
2395
- tag: "link",
2396
- attrs: {
2397
- rel: "manifest",
2398
- href: metadata.manifest
2399
- }
2400
- });
2401
- if (metadata.alternates) renderAlternates(metadata.alternates, elements);
2402
- if (metadata.verification) renderVerification(metadata.verification, elements);
2403
- if (metadata.formatDetection) {
2404
- const parts = [];
2405
- if (metadata.formatDetection.telephone === false) parts.push("telephone=no");
2406
- if (metadata.formatDetection.email === false) parts.push("email=no");
2407
- if (metadata.formatDetection.address === false) parts.push("address=no");
2408
- if (parts.length > 0) elements.push({
2409
- tag: "meta",
2410
- attrs: {
2411
- name: "format-detection",
2412
- content: parts.join(", ")
2413
- }
2414
- });
2415
- }
2416
- if (metadata.authors) {
2417
- const authorList = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
2418
- for (const author of authorList) {
2419
- if (author.name) elements.push({
2420
- tag: "meta",
2421
- attrs: {
2422
- name: "author",
2423
- content: author.name
2424
- }
2425
- });
2426
- if (author.url) elements.push({
2427
- tag: "link",
2428
- attrs: {
2429
- rel: "author",
2430
- href: author.url
2431
- }
2432
- });
2433
- }
2434
- }
2435
- if (metadata.appleWebApp) renderAppleWebApp(metadata.appleWebApp, elements);
2436
- if (metadata.appLinks) renderAppLinks(metadata.appLinks, elements);
2437
- if (metadata.itunes) renderItunes(metadata.itunes, elements);
2438
- if (metadata.other) for (const [name, value] of Object.entries(metadata.other)) {
2439
- const content = Array.isArray(value) ? value.join(", ") : value;
2440
- elements.push({
2441
- tag: "meta",
2442
- attrs: {
2443
- name,
2444
- content
2445
- }
2446
- });
2447
- }
2448
- return elements;
2449
- }
2450
- function renderRobotsObject(robots) {
2451
- const parts = [];
2452
- if (robots.index === true) parts.push("index");
2453
- if (robots.index === false) parts.push("noindex");
2454
- if (robots.follow === true) parts.push("follow");
2455
- if (robots.follow === false) parts.push("nofollow");
2456
- return parts.join(", ");
2457
- }
6
+ * Next.js redirect type discriminator.
7
+ *
8
+ * Provided for API compatibility with libraries that import `RedirectType`
9
+ * from `next/navigation`. In timber, `redirect()` always uses `replace`
10
+ * semantics (no history entry for the redirect itself).
11
+ *
12
+ * Lives in shared/ (isomorphic) so both the server primitives and the
13
+ * client-only next/navigation shim export the same definition without the
14
+ * client shim pulling in server code.
15
+ */
16
+ var RedirectType = {
17
+ push: "push",
18
+ replace: "replace"
19
+ };
2458
20
  //#endregion
2459
- //#region src/server/metadata.ts
21
+ //#region src/server/sensitive-fields.ts
22
+ /**
23
+ * Sensitive field stripping — removes password/token/CVV-style fields from
24
+ * the `submittedValues` a `createActionClient` action echoes back to the
25
+ * client for form repopulation.
26
+ *
27
+ * **This is hygiene, not a security boundary.** `submittedValues` only ever
28
+ * returns to the user who typed it, in the response to their own POST:
29
+ *
30
+ * - With JavaScript, it travels in the action's response, a non-cacheable
31
+ * POST fetch. What remains is exposure to devtools, HAR exports and
32
+ * TLS-inspecting proxies.
33
+ * - Without JavaScript, it is rendered into the page's HTML as a field's
34
+ * `defaultValue`: one uncached response, but one that view-source, the
35
+ * back-forward cache and a shared machine can surface. OWASP advises not
36
+ * pre-filling password fields for this reason.
37
+ *
38
+ * The main reason to strip is UX: a password or card field comes back empty
39
+ * after a failed submit, as users expect.
40
+ *
41
+ * What is stripped: a field whose name matches the built-in deny-list (or the
42
+ * configured option), and a field the action's schema marks sensitive with
43
+ * `.meta({ sensitive: true })` (Valibot: `v.metadata({ sensitive: true })`),
44
+ * at its exact path. The schema mark covers names the list misses
45
+ * (`recoveryPhrase`) and always applies, even with the name list turned off.
46
+ *
47
+ * Only `createActionClient` strips, because only it builds `submittedValues`.
48
+ * A raw `'use server'` action owns its return value: whatever it returns is
49
+ * what the client gets, on both paths.
50
+ *
51
+ * See design/08-forms-and-actions.md §"Sensitive field stripping"
52
+ * See design/13-security.md §"Sensitive field stripping"
53
+ */
54
+ /**
55
+ * Substring patterns matched against the normalized field name.
56
+ * Normalization = lowercase + strip `_` and `-`.
57
+ *
58
+ * Any field whose normalized name *contains* one of these strings is
59
+ * considered sensitive. Entries like `currentPassword`, `passwordConfirmation`,
60
+ * and `user.password` all match via the `password` substring. Every pattern
61
+ * here is long enough not to occur inside an ordinary word.
62
+ */
63
+ var BUILTIN_SUBSTRING_PATTERNS = [
64
+ "password",
65
+ "passwd",
66
+ "secret",
67
+ "apikey",
68
+ "accesstoken",
69
+ "refreshtoken",
70
+ "cardnumber",
71
+ "cardcvc",
72
+ "socialsecuritynumber",
73
+ "mfacode",
74
+ "twofactorcode",
75
+ "privatekey"
76
+ ];
2460
77
  /**
2461
- * Resolve a title value with an optional template.
2462
- *
2463
- * - string → apply template if present
2464
- * - { absolute: '...' } → use as-is, skip template
2465
- * - { default: '...' } → use as fallback (no template applied)
2466
- * - undefined → undefined
78
+ * Patterns matched at the start or end of a word of the field name. These are
79
+ * short enough to occur inside ordinary words (`otp` in `footPath` and
80
+ * `notpublic`, `ssn` in `class_number` and `classnumber`), so they must
81
+ * begin or end a word: `otp`, `otpCode`, `otpcode`, `userotp`, `user_ssn`,
82
+ * `SSNLast4`, `newpwd`, `cardcvv`.
83
+ */
84
+ var BUILTIN_WORD_PATTERNS = [
85
+ "pwd",
86
+ "cvv",
87
+ "cvc",
88
+ "ssn",
89
+ "otp",
90
+ "totp"
91
+ ];
92
+ /**
93
+ * Exact matches against the normalized field name. These are field names that
94
+ * are too short or too common to substring-match safely. e.g. `token` alone
95
+ * would match `csrfToken`, which is not sensitive — so `token` is exact-only,
96
+ * while legitimate token fields are covered by `accesstoken` / `refreshtoken`.
2467
97
  */
2468
- function resolveTitle(title, template) {
2469
- if (title === void 0 || title === null) return;
2470
- if (typeof title === "string") return template ? template.replace("%s", title) : title;
2471
- if (title.absolute !== void 0) return title.absolute;
2472
- if (title.default !== void 0) return title.default;
2473
- }
98
+ var BUILTIN_EXACT_PATTERNS = ["token"];
2474
99
  /**
2475
- * Resolve metadata from a segment chain.
2476
- *
2477
- * Processes entries from root layout to page (in segment order).
2478
- * The merge algorithm:
2479
- * 1. Shallow-merge all keys except title (later wins)
2480
- * 2. Track the most recent title template
2481
- * 3. Resolve the final title using the template
2482
- *
2483
- * In error state, the page entry is dropped and noindex is injected.
2484
- *
2485
- * See design/16-metadata.md §"Merge Algorithm"
100
+ * Normalize a field name for deny-list comparison.
101
+ * Lowercases the string and strips `_` and `-` so camelCase, snake_case, and
102
+ * kebab-case variants all compare equal (`api_key` / `apiKey` / `api-key` →
103
+ * `apikey`).
2486
104
  */
2487
- function resolveMetadata(entries, options = {}) {
2488
- const { errorState = false } = options;
2489
- const merged = {};
2490
- let titleTemplate;
2491
- let lastDefault;
2492
- let rawTitle;
2493
- for (const { metadata, isPage } of entries) {
2494
- if (errorState && isPage) continue;
2495
- if (metadata.title !== void 0 && typeof metadata.title === "object") {
2496
- if (metadata.title.template !== void 0) titleTemplate = metadata.title.template;
2497
- if (metadata.title.default !== void 0) lastDefault = metadata.title.default;
2498
- }
2499
- for (const key of Object.keys(metadata)) {
2500
- if (key === "title") continue;
2501
- merged[key] = metadata[key];
2502
- }
2503
- if (metadata.title !== void 0) rawTitle = metadata.title;
2504
- }
2505
- if (errorState) {
2506
- rawTitle = lastDefault !== void 0 ? { default: lastDefault } : rawTitle;
2507
- titleTemplate = void 0;
2508
- }
2509
- const resolvedTitle = resolveTitle(rawTitle, titleTemplate);
2510
- if (resolvedTitle !== void 0) merged.title = resolvedTitle;
2511
- if (errorState) merged.robots = "noindex";
2512
- return merged;
105
+ function normalize$1(name) {
106
+ return name.replace(/[_-]/g, "").toLowerCase();
2513
107
  }
2514
108
  /**
2515
- * Check if a string is an absolute URL.
109
+ * Split a field name into lowercase words at anything that is not a letter
110
+ * and at a lowercase-to-uppercase hump: `user_ssnLast4` → `user`, `ssn`,
111
+ * `last`. An acronym stays joined to what follows it (`OTPcode` →
112
+ * `otpcode`, `SSNLast` → `ssnlast`), which a start-of-word match still finds.
2516
113
  */
2517
- function isAbsoluteUrl(url) {
2518
- return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
114
+ function words(name) {
115
+ return name.split(/[^A-Za-z]+|(?<=[a-z])(?=[A-Z])/).filter(Boolean).map((w) => w.toLowerCase());
116
+ }
117
+ /** Whether a short pattern begins or ends one of the name's words. */
118
+ function hasWordPattern(name) {
119
+ return words(name).some((word) => BUILTIN_WORD_PATTERNS.some((p) => word.startsWith(p) || word.endsWith(p)));
2519
120
  }
2520
121
  /**
2521
- * Resolve a relative URL against a base URL.
122
+ * Check whether a name matches the built-in deny-list (with optional extras).
123
+ * Extras are merged into the substring pattern list after normalization.
2522
124
  */
2523
- function resolveUrl(url, base) {
2524
- if (isAbsoluteUrl(url)) return url;
2525
- return new URL(url, base).toString();
125
+ function isBuiltinSensitive(name, extras) {
126
+ const normalized = normalize$1(name);
127
+ if (BUILTIN_EXACT_PATTERNS.includes(normalized)) return true;
128
+ for (const pattern of BUILTIN_SUBSTRING_PATTERNS) if (normalized.includes(pattern)) return true;
129
+ if (hasWordPattern(name)) return true;
130
+ if (extras && extras.length > 0) for (const extra of extras) {
131
+ const normExtra = normalize$1(extra);
132
+ if (normExtra.length === 0) continue;
133
+ if (normalized.includes(normExtra)) return true;
134
+ }
135
+ return false;
2526
136
  }
2527
137
  /**
2528
- * Resolve relative URLs in metadata fields against metadataBase.
138
+ * Resolve a `SensitiveFieldsOption` into a concrete predicate.
139
+ * Precedence: per-action > global > built-in default.
2529
140
  *
2530
- * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
2531
- * If metadataBase is not set, returns the metadata unchanged.
141
+ * - Per-action `undefined` → fall back to global.
142
+ * - Global `undefined` → use built-in list.
143
+ * - Either level set to `false` → no name matching (returns `null`).
144
+ * - `true` → built-in list.
145
+ * - `string[]` → built-in ∪ extras.
146
+ * - function → custom, replaces the built-in list entirely.
2532
147
  */
2533
- function resolveMetadataUrls(metadata) {
2534
- const base = metadata.metadataBase;
2535
- if (!base) return metadata;
2536
- const result = { ...metadata };
2537
- if (result.openGraph) {
2538
- result.openGraph = { ...result.openGraph };
2539
- if (typeof result.openGraph.images === "string") result.openGraph.images = resolveUrl(result.openGraph.images, base);
2540
- else if (Array.isArray(result.openGraph.images)) result.openGraph.images = result.openGraph.images.map((img) => ({
2541
- ...img,
2542
- url: resolveUrl(img.url, base)
2543
- }));
2544
- else if (result.openGraph.images) result.openGraph.images = {
2545
- ...result.openGraph.images,
2546
- url: resolveUrl(result.openGraph.images.url, base)
2547
- };
2548
- if (result.openGraph.url && !isAbsoluteUrl(result.openGraph.url)) result.openGraph.url = resolveUrl(result.openGraph.url, base);
2549
- }
2550
- if (result.twitter) {
2551
- result.twitter = { ...result.twitter };
2552
- if (typeof result.twitter.images === "string") result.twitter.images = resolveUrl(result.twitter.images, base);
2553
- else if (Array.isArray(result.twitter.images)) {
2554
- const resolved = result.twitter.images.map((img) => typeof img === "string" ? resolveUrl(img, base) : {
2555
- ...img,
2556
- url: resolveUrl(img.url, base)
2557
- });
2558
- const allStrings = resolved.every((r) => typeof r === "string");
2559
- result.twitter.images = allStrings ? resolved : resolved;
2560
- } else if (result.twitter.images) result.twitter.images = {
2561
- ...result.twitter.images,
2562
- url: resolveUrl(result.twitter.images.url, base)
2563
- };
2564
- }
2565
- if (result.alternates) {
2566
- result.alternates = { ...result.alternates };
2567
- if (result.alternates.canonical && !isAbsoluteUrl(result.alternates.canonical)) result.alternates.canonical = resolveUrl(result.alternates.canonical, base);
2568
- if (result.alternates.languages) {
2569
- const langs = {};
2570
- for (const [lang, url] of Object.entries(result.alternates.languages)) langs[lang] = isAbsoluteUrl(url) ? url : resolveUrl(url, base);
2571
- result.alternates.languages = langs;
148
+ function resolveSensitivePredicate(perAction, global) {
149
+ const chosen = perAction !== void 0 ? perAction : global;
150
+ if (chosen === false) return null;
151
+ if (chosen === void 0 || chosen === true) return (name) => isBuiltinSensitive(name);
152
+ if (typeof chosen === "function") return chosen;
153
+ const extras = chosen;
154
+ return (name) => isBuiltinSensitive(name, extras);
155
+ }
156
+ var warnedFields = /* @__PURE__ */ new Set();
157
+ function warnStripped(name, markedInSchema) {
158
+ if (!isDebug()) return;
159
+ if (warnedFields.has(name)) return;
160
+ warnedFields.add(name);
161
+ console.warn(`[timber] stripped sensitive field "${name}" from submittedValues. ` + (markedInSchema ? `The action's schema marks it sensitive; remove the mark to echo it.` : `Override via forms.stripSensitiveFields in timber.config.ts.`));
162
+ }
163
+ /**
164
+ * Walk an object (recursively) and return a copy without its sensitive
165
+ * fields: every key `predicate` matches, and every field `shape` (the
166
+ * schema's declared shape) marks sensitive. Nested objects like
167
+ * `{ user: { password: '...' } }` are handled — `user.password` is stripped
168
+ * while other `user.*` fields remain.
169
+ *
170
+ * - Arrays are walked element-wise (object entries inside arrays are cleaned).
171
+ * - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.
172
+ * - When a stripped key is encountered, it is omitted from the result entirely
173
+ * — we do NOT set it to an empty string, because that would overwrite a
174
+ * valid `defaultValue` the form author might have set.
175
+ */
176
+ function stripSensitiveFields(value, predicate, shape) {
177
+ if (predicate === null && !hasSensitive(shape)) return value;
178
+ return stripFrom(value, predicate, shape);
179
+ }
180
+ function stripFrom(value, predicate, shape) {
181
+ if (value === null || typeof value !== "object") return value;
182
+ if (value instanceof Blob || value instanceof Date) return value;
183
+ if (Array.isArray(value)) return value.map((item) => stripFrom(item, predicate, shape?.item));
184
+ const indexed = shape?.item !== void 0 && shape.properties === void 0;
185
+ const result = {};
186
+ for (const [key, nested] of Object.entries(value)) {
187
+ const child = indexed ? shape.item : shape?.properties?.[key];
188
+ if (child?.sensitive || predicate?.(key)) {
189
+ warnStripped(key, child?.sensitive === true);
190
+ continue;
2572
191
  }
2573
- }
2574
- if (result.icons) {
2575
- result.icons = { ...result.icons };
2576
- if (typeof result.icons.icon === "string") result.icons.icon = resolveUrl(result.icons.icon, base);
2577
- else if (Array.isArray(result.icons.icon)) result.icons.icon = result.icons.icon.map((i) => ({
2578
- ...i,
2579
- url: resolveUrl(i.url, base)
2580
- }));
2581
- if (typeof result.icons.apple === "string") result.icons.apple = resolveUrl(result.icons.apple, base);
2582
- else if (Array.isArray(result.icons.apple)) result.icons.apple = result.icons.apple.map((i) => ({
2583
- ...i,
2584
- url: resolveUrl(i.url, base)
2585
- }));
192
+ result[key] = stripFrom(nested, predicate, child);
2586
193
  }
2587
194
  return result;
2588
195
  }
196
+ /** Whether `shape` marks any field at or below it sensitive. */
197
+ function hasSensitive(shape) {
198
+ if (!shape) return false;
199
+ if (shape.sensitive) return true;
200
+ if (hasSensitive(shape.item)) return true;
201
+ return Object.values(shape.properties ?? {}).some(hasSensitive);
202
+ }
203
+ [
204
+ ...BUILTIN_SUBSTRING_PATTERNS,
205
+ ...BUILTIN_WORD_PATTERNS,
206
+ ...BUILTIN_EXACT_PATTERNS
207
+ ];
2589
208
  //#endregion
2590
- //#region src/server/form-data.ts
2591
- /**
2592
- * FormData preprocessing — schema-agnostic conversion of FormData to typed objects.
2593
- *
2594
- * FormData is all strings. Schema validation expects typed values. This module
2595
- * bridges the gap with intelligent coercion that runs *before* schema validation.
2596
- *
2597
- * Inspired by zod-form-data, but schema-agnostic — works with any Standard Schema
2598
- * library (Zod, Valibot, ArkType).
2599
- *
2600
- * See design/08-forms-and-actions.md §"parseFormData() and coerce helpers"
2601
- */
209
+ //#region src/server/action-schema.ts
210
+ /** Check if a schema implements the Standard Schema protocol. */
211
+ function isStandardSchema(schema) {
212
+ return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"].validate === "function";
213
+ }
2602
214
  /**
2603
- * Convert FormData into a plain object with intelligent coercion.
2604
- *
2605
- * Handles:
2606
- * - **Duplicate keys → arrays**: `tags=js&tags=ts` → `{ tags: ["js", "ts"] }`
2607
- * - **Nested dot-paths**: `user.name=Alice` → `{ user: { name: "Alice" } }`
2608
- * - **Empty strings → undefined**: Enables `.optional()` semantics in schemas
2609
- * - **Empty Files → undefined**: File inputs with no selection become `undefined`
2610
- * - **Strips `$ACTION_*` fields**: React's internal hidden fields are excluded
215
+ * Validate `input` with `schema`, through Standard Schema when the schema
216
+ * implements it, and through `.safeParse()` / `.parse()` otherwise. Only
217
+ * synchronous Standard Schema validation is supported.
2611
218
  */
2612
- function parseFormData(formData) {
2613
- const flat = {};
2614
- for (const key of new Set(formData.keys())) {
2615
- if (key.startsWith("$ACTION_")) continue;
2616
- const processed = formData.getAll(key).map(normalizeValue);
2617
- if (processed.length === 1) flat[key] = processed[0];
2618
- else flat[key] = processed.filter((v) => v !== void 0);
219
+ function validateWithSchema(schema, input) {
220
+ if (isStandardSchema(schema)) {
221
+ const result = schema["~standard"].validate(input);
222
+ if (result instanceof Promise) throw new Error("[timber] createActionClient: schema returned a Promise — only sync schemas are supported.");
223
+ if (result.issues) return {
224
+ ok: false,
225
+ validationErrors: extractStandardSchemaErrors(result.issues)
226
+ };
227
+ return {
228
+ ok: true,
229
+ value: result.value
230
+ };
231
+ }
232
+ if (typeof schema.safeParse === "function") {
233
+ const result = schema.safeParse(input);
234
+ if (!result.success) return {
235
+ ok: false,
236
+ validationErrors: extractValidationErrors(result.error)
237
+ };
238
+ return {
239
+ ok: true,
240
+ value: result.data
241
+ };
242
+ }
243
+ try {
244
+ return {
245
+ ok: true,
246
+ value: schema.parse(input)
247
+ };
248
+ } catch (parseError) {
249
+ return {
250
+ ok: false,
251
+ validationErrors: extractValidationErrors(parseError)
252
+ };
2619
253
  }
2620
- return expandDotPaths(flat);
2621
254
  }
2622
255
  /**
2623
- * Normalize a single FormData entry value.
2624
- * - Empty strings → undefined (enables .optional() semantics)
2625
- * - Empty File objects (no selection) → undefined
2626
- * - Everything else passes through as-is
256
+ * Extract validation errors from a schema error.
257
+ * Supports Zod's flatten() and generic issues array.
2627
258
  */
2628
- function normalizeValue(value) {
2629
- if (typeof value === "string") return value === "" ? void 0 : value;
2630
- if (value instanceof File && value.size === 0 && value.name === "") return;
2631
- return value;
259
+ function extractValidationErrors(error) {
260
+ if (typeof error.flatten === "function") return error.flatten().fieldErrors;
261
+ if (error.issues) {
262
+ const errors = {};
263
+ for (const issue of error.issues) {
264
+ const path = issue.path?.join(".") ?? "_root";
265
+ (errors[path] ??= []).push(issue.message);
266
+ }
267
+ return errors;
268
+ }
269
+ return { _root: ["Validation failed"] };
2632
270
  }
2633
271
  /**
2634
- * Expand dot-notation keys into nested objects.
2635
- * `{ "user.name": "Alice", "user.age": "30" }` → `{ user: { name: "Alice", age: "30" } }`
2636
- *
2637
- * Keys without dots are left as-is. Bracket notation (e.g. `items[0]`) is NOT
2638
- * supported — use dot notation (`items.0`) instead.
272
+ * Extract validation errors from Standard Schema issues.
2639
273
  */
2640
- function expandDotPaths(flat) {
2641
- const result = {};
2642
- let hasDotPaths = false;
2643
- for (const key of Object.keys(flat)) if (key.includes(".")) {
2644
- hasDotPaths = true;
2645
- break;
274
+ function extractStandardSchemaErrors(issues) {
275
+ const errors = {};
276
+ for (const issue of issues) {
277
+ const path = issue.path?.map((p) => {
278
+ if (typeof p === "object" && p !== null && "key" in p) return String(p.key);
279
+ return String(p);
280
+ }).join(".") ?? "_root";
281
+ (errors[path] ??= []).push(issue.message);
2646
282
  }
2647
- if (!hasDotPaths) return flat;
2648
- for (const [key, value] of Object.entries(flat)) {
2649
- if (!key.includes(".")) {
2650
- result[key] = value;
2651
- continue;
2652
- }
2653
- const parts = key.split(".");
2654
- let current = result;
2655
- for (let i = 0; i < parts.length - 1; i++) {
2656
- const part = parts[i];
2657
- if (current[part] === void 0 || current[part] === null) current[part] = {};
2658
- if (typeof current[part] !== "object" || current[part] instanceof File) current[part] = {};
2659
- current = current[part];
283
+ return Object.keys(errors).length > 0 ? errors : { _root: ["Validation failed"] };
284
+ }
285
+ //#endregion
286
+ //#region src/server/schema-introspection.ts
287
+ /**
288
+ * Schema introspection — the shape of an action's input as its schema
289
+ * declares it: which fields are lists, which may be absent, and which the
290
+ * schema marks sensitive.
291
+ *
292
+ * Standard Schema v1 has no introspection API, so this feature-detects what
293
+ * the libraries expose:
294
+ *
295
+ * - **Zod 4**: its schema tree (`_zod.def`, documented for library authors),
296
+ * with `.meta()` for marks and `_zod.optin` for fields that may be absent.
297
+ * Not Zod's JSON Schema: that describes a `z.preprocess(fn, z.array(…))`
298
+ * field as the inner array, and wrapping a scalar before `fn` runs would
299
+ * hand a comma-splitting preprocessor `['a,b']`. A preprocessed field is
300
+ * its author's to read, so it has no shape here.
301
+ * - **Valibot**: its schema objects (`entries`, `item`, `wrapped`, `options`),
302
+ * with `v.metadata({ sensitive: true })` read from the pipe.
303
+ * - **Standard JSON Schema** (`~standard.jsonSchema.input()`) for any other
304
+ * library that implements it, such as ArkType, whose
305
+ * `.configure({ sensitive: true })` lands in the JSON Schema node.
306
+ *
307
+ * Any other schema (a legacy `.parse()` schema, Zod 3, a hand-written
308
+ * Standard Schema) has no shape: its form input is not normalized and only
309
+ * the name deny-list strips its echo.
310
+ *
311
+ * A union merges its branches: a field is sensitive if any branch marks it,
312
+ * and a list only if every branch declares it one. An intersection merges
313
+ * its parts, which all apply: a list or sensitive if any part says so.
314
+ *
315
+ * `createActionClient` computes the shape once per action and keeps it on the
316
+ * action's closure. It is used twice, by `normalizeListFields` (before
317
+ * validation, and for `submittedValues`) and by `stripSensitiveFields`.
318
+ *
319
+ * See design/08-forms-and-actions.md §"The Form Model" and
320
+ * §"Sensitive field stripping".
321
+ */
322
+ /**
323
+ * The shape of `schema`'s input, or `undefined` when the schema library
324
+ * exposes nothing to read it from.
325
+ */
326
+ function introspectSchema(schema) {
327
+ if (!isStandardSchema(schema)) return void 0;
328
+ const standard = schema["~standard"];
329
+ if (standard.vendor === "zod" && isRecord(schema) && isRecord(schema._zod)) return fromZod(schema, /* @__PURE__ */ new Set());
330
+ if (standard.vendor === "valibot") return fromValibot(schema, /* @__PURE__ */ new Set());
331
+ const jsonSchema = standard.jsonSchema;
332
+ if (!isRecord(jsonSchema) || typeof jsonSchema.input !== "function") return void 0;
333
+ let root;
334
+ try {
335
+ root = jsonSchema.input({ target: "draft-2020-12" });
336
+ } catch {
337
+ return;
338
+ }
339
+ return isRecord(root) ? fromJsonSchema(root, root, /* @__PURE__ */ new Set()) : void 0;
340
+ }
341
+ /** Zod wrappers whose `innerType` is the field's real type. */
342
+ var ZOD_WRAPPERS = /* @__PURE__ */ new Set([
343
+ "optional",
344
+ "nullable",
345
+ "default",
346
+ "prefault",
347
+ "nonoptional",
348
+ "readonly",
349
+ "catch"
350
+ ]);
351
+ function fromZod(schema, seen) {
352
+ if (!isRecord(schema) || seen.has(schema) || !isRecord(schema._zod)) return void 0;
353
+ const inner = new Set(seen).add(schema);
354
+ const def = schema._zod.def;
355
+ if (!isRecord(def)) return void 0;
356
+ const marks = withMarks(schema._zod.optin === "optional", zodSensitive(schema));
357
+ switch (def.type) {
358
+ case "object": {
359
+ if (!isRecord(def.shape)) return marks(void 0);
360
+ const properties = {};
361
+ for (const [key, child] of Object.entries(def.shape)) {
362
+ const shape = fromZod(child, inner);
363
+ if (shape) properties[key] = shape;
364
+ }
365
+ return marks({ properties });
2660
366
  }
2661
- current[parts[parts.length - 1]] = value;
367
+ case "array": return marks({
368
+ item: fromZod(def.element, inner) ?? {},
369
+ list: true
370
+ });
371
+ case "union": return marks(mergeAll(asList(def.options).map((option) => fromZod(option, inner))));
372
+ case "intersection": return marks(intersectAll([fromZod(def.left, inner), fromZod(def.right, inner)]));
373
+ case "pipe":
374
+ if (isRecord(def.in) && isRecord(def.in._zod) && isRecord(def.in._zod.def)) {
375
+ if (def.in._zod.def.type === "transform") return marks(void 0);
376
+ }
377
+ return marks(fromZod(def.in, inner));
378
+ default:
379
+ if (typeof def.type === "string" && ZOD_WRAPPERS.has(def.type)) return marks(fromZod(def.innerType, inner));
380
+ return marks(void 0);
2662
381
  }
2663
- return result;
2664
382
  }
2665
- /**
2666
- * Schema-agnostic coercion primitives for common FormData patterns.
2667
- *
2668
- * These are plain transform functions — they compose with any schema library's
2669
- * `transform`/`preprocess` pipeline:
2670
- *
2671
- * ```ts
2672
- * // Zod
2673
- * z.preprocess(coerce.number, z.number())
2674
- * // Valibot
2675
- * v.pipe(v.unknown(), v.transform(coerce.number), v.number())
2676
- * ```
2677
- */
2678
- var coerce = {
2679
- number(value) {
2680
- if (value === void 0 || value === null || value === "") return void 0;
2681
- if (typeof value === "number") return value;
2682
- if (typeof value !== "string") return void 0;
2683
- const num = Number(value);
2684
- if (Number.isNaN(num)) return void 0;
2685
- return num;
2686
- },
2687
- checkbox(value) {
2688
- if (value === void 0 || value === null || value === "") return false;
2689
- if (typeof value === "boolean") return value;
2690
- return typeof value === "string" && value.length > 0;
2691
- },
2692
- json(value) {
2693
- if (value === void 0 || value === null || value === "") return void 0;
2694
- if (typeof value !== "string") return value;
2695
- try {
2696
- return JSON.parse(value);
2697
- } catch {
2698
- return;
383
+ /** `.meta()` read back: Zod returns the schema's registered metadata. */
384
+ function zodSensitive(schema) {
385
+ if (typeof schema.meta !== "function") return false;
386
+ try {
387
+ const meta = schema.meta();
388
+ return isRecord(meta) && meta.sensitive === true;
389
+ } catch {
390
+ return false;
391
+ }
392
+ }
393
+ /** Valibot wrappers whose `wrapped` schema is the field's real type. */
394
+ var VALIBOT_WRAPPERS = /* @__PURE__ */ new Set([
395
+ "optional",
396
+ "exact_optional",
397
+ "nullable",
398
+ "nullish",
399
+ "undefinedable",
400
+ "non_optional",
401
+ "non_nullable",
402
+ "non_nullish"
403
+ ]);
404
+ /** Valibot wrappers that let the field be absent. */
405
+ var VALIBOT_OPTIONAL = /* @__PURE__ */ new Set([
406
+ "optional",
407
+ "exact_optional",
408
+ "nullish",
409
+ "undefinedable"
410
+ ]);
411
+ var VALIBOT_OBJECTS = /* @__PURE__ */ new Set([
412
+ "object",
413
+ "loose_object",
414
+ "strict_object",
415
+ "object_with_rest"
416
+ ]);
417
+ function fromValibot(schema, seen) {
418
+ if (!isRecord(schema) || seen.has(schema)) return void 0;
419
+ const inner = new Set(seen).add(schema);
420
+ const sensitive = Array.isArray(schema.pipe) && schema.pipe.some((action) => isRecord(action) && action.kind === "metadata" && isRecord(action.metadata) && action.metadata.sensitive === true);
421
+ const type = schema.type;
422
+ const marks = withMarks(typeof type === "string" && VALIBOT_OPTIONAL.has(type), sensitive);
423
+ if (typeof type !== "string") return marks(void 0);
424
+ if (VALIBOT_WRAPPERS.has(type)) return marks(fromValibot(schema.wrapped, inner));
425
+ if (type === "array") return marks({
426
+ item: fromValibot(schema.item, inner) ?? {},
427
+ list: true
428
+ });
429
+ if (type === "union" || type === "variant") return marks(mergeAll(asList(schema.options).map((option) => fromValibot(option, inner))));
430
+ if (type === "intersect") return marks(intersectAll(asList(schema.options).map((option) => fromValibot(option, inner))));
431
+ if (VALIBOT_OBJECTS.has(type) && isRecord(schema.entries)) {
432
+ const properties = {};
433
+ for (const [key, child] of Object.entries(schema.entries)) {
434
+ const shape = fromValibot(child, inner);
435
+ if (shape) properties[key] = shape;
436
+ }
437
+ return marks({ properties });
438
+ }
439
+ return marks(void 0);
440
+ }
441
+ function fromJsonSchema(node, root, refs) {
442
+ const marks = withMarks(false, node.sensitive === true);
443
+ const ref = node.$ref;
444
+ if (typeof ref === "string") {
445
+ if (refs.has(ref)) return marks(void 0);
446
+ const target = resolveRef(root, ref);
447
+ if (!target) return marks(void 0);
448
+ return marks(fromJsonSchema(target, root, new Set(refs).add(ref)));
449
+ }
450
+ const branches = node.anyOf ?? node.oneOf;
451
+ if (Array.isArray(branches)) return marks(mergeAll(branches.filter((b) => isRecord(b) && b.type !== "null").map((b) => fromJsonSchema(b, root, refs))));
452
+ if (Array.isArray(node.allOf)) return marks(intersectAll(node.allOf.filter(isRecord).map((part) => fromJsonSchema(part, root, refs))));
453
+ if ((Array.isArray(node.type) ? node.type : [node.type]).includes("array") && isRecord(node.items)) return marks({
454
+ item: fromJsonSchema(node.items, root, refs) ?? {},
455
+ list: true
456
+ });
457
+ if (isRecord(node.properties)) {
458
+ const required = new Set(asList(node.required));
459
+ const properties = {};
460
+ for (const [key, child] of Object.entries(node.properties)) {
461
+ const shape = isRecord(child) ? fromJsonSchema(child, root, refs) : void 0;
462
+ if (shape) properties[key] = required.has(key) ? shape : {
463
+ ...shape,
464
+ optional: true
465
+ };
466
+ }
467
+ return marks({ properties });
468
+ }
469
+ return marks(void 0);
470
+ }
471
+ /** Resolve a local `#/$defs/...` or `#/definitions/...` reference. */
472
+ function resolveRef(root, ref) {
473
+ if (!ref.startsWith("#/")) return void 0;
474
+ let node = root;
475
+ for (const segment of ref.slice(2).split("/")) {
476
+ if (!isRecord(node)) return void 0;
477
+ node = node[segment.replaceAll("~1", "/").replaceAll("~0", "~")];
478
+ }
479
+ return isRecord(node) ? node : void 0;
480
+ }
481
+ /**
482
+ * One shape for the branches of a union. A field is sensitive if any branch
483
+ * marks it, a list only if every branch declares it one, and optional if any
484
+ * branch lacks it. A branch with no shape makes nothing a list, but its
485
+ * siblings' marks still apply.
486
+ */
487
+ function mergeAll(shapes) {
488
+ if (shapes.length === 0) return void 0;
489
+ return shapes.reduce((merged, shape, i) => i === 0 ? shape ?? {} : merge(merged ?? {}, shape ?? {}), void 0);
490
+ }
491
+ function merge(a, b) {
492
+ const out = {};
493
+ if (a.sensitive || b.sensitive) out.sensitive = true;
494
+ if (a.optional || b.optional) out.optional = true;
495
+ if (a.list && b.list) out.list = true;
496
+ if (a.item || b.item) out.item = merge(a.item ?? {}, b.item ?? {});
497
+ if (a.properties || b.properties) {
498
+ const properties = {};
499
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
500
+ for (const key of keys) {
501
+ const left = a.properties?.[key];
502
+ const right = b.properties?.[key];
503
+ properties[key] = left && right ? merge(left, right) : {
504
+ ...left ?? right,
505
+ optional: true
506
+ };
2699
507
  }
508
+ out.properties = properties;
509
+ }
510
+ return out;
511
+ }
512
+ /**
513
+ * One shape for the parts of an intersection, which all apply: a field is a
514
+ * list or sensitive if any part says so, and optional only if every part
515
+ * that declares it lets it be absent.
516
+ */
517
+ function intersectAll(shapes) {
518
+ const present = shapes.filter((shape) => shape !== void 0);
519
+ if (present.length === 0) return void 0;
520
+ return present.reduce(intersect);
521
+ }
522
+ function intersect(a, b) {
523
+ const out = {};
524
+ if (a.sensitive || b.sensitive) out.sensitive = true;
525
+ if (a.optional && b.optional) out.optional = true;
526
+ if (a.list || b.list) out.list = true;
527
+ if (a.item || b.item) out.item = intersect(a.item ?? {}, b.item ?? {});
528
+ if (a.properties || b.properties) {
529
+ const properties = {};
530
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
531
+ for (const key of keys) {
532
+ const left = a.properties?.[key];
533
+ const right = b.properties?.[key];
534
+ properties[key] = left && right ? intersect(left, right) : left ?? right ?? {};
535
+ }
536
+ out.properties = properties;
537
+ }
538
+ return out;
539
+ }
540
+ /**
541
+ * Give every field the schema declares as a list the same shape whatever its
542
+ * count. `parseFormData` reads a repeated name as an array, a single value as
543
+ * a scalar, and an absent name not at all; here a scalar becomes `[value]`,
544
+ * and an absent or blank required list becomes `[]` (blanks are dropped from
545
+ * a list, as `parseFormData` drops them from a repeated name). An optional
546
+ * list that was not submitted (or was one blank) is absent, so `.optional()` still means
547
+ * "not sent". Lists inside lists and objects are normalized too. An object
548
+ * where a list is declared (an indexed list with a gap) is left for the
549
+ * schema to reject.
550
+ *
551
+ * Returns a copy; the input is not written to.
552
+ */
553
+ function normalizeListFields(values, shape) {
554
+ if (!shape) return values;
555
+ return normalize(values, shape);
556
+ }
557
+ function normalize(value, shape) {
558
+ if (shape.list && shape.item) {
559
+ if (value === void 0 || value === "") return shape.optional ? void 0 : [];
560
+ if (isPlainObject(value)) return value;
561
+ const list = Array.isArray(value) ? value : [value];
562
+ const item = shape.item;
563
+ return list.map((v) => normalize(v, item));
564
+ }
565
+ if (shape.properties && isPlainObject(value)) {
566
+ const out = { ...value };
567
+ for (const [key, child] of Object.entries(shape.properties)) {
568
+ const current = Object.hasOwn(out, key) ? out[key] : void 0;
569
+ if (key === "__proto__") continue;
570
+ const normalized = normalize(current, child);
571
+ if (normalized === void 0) delete out[key];
572
+ else out[key] = normalized;
573
+ }
574
+ return out;
2700
575
  }
2701
- };
576
+ return value;
577
+ }
578
+ /** Apply a node's own marks to the shape read from what it wraps. */
579
+ function withMarks(optional, sensitive) {
580
+ return (shape) => {
581
+ if (!optional && !sensitive) return shape;
582
+ return {
583
+ ...shape,
584
+ ...optional ? { optional: true } : {},
585
+ ...sensitive ? { sensitive: true } : {}
586
+ };
587
+ };
588
+ }
589
+ function asList(value) {
590
+ return Array.isArray(value) ? value : [];
591
+ }
592
+ function isRecord(value) {
593
+ return typeof value === "object" && value !== null;
594
+ }
595
+ function isPlainObject(value) {
596
+ return isRecord(value) && !Array.isArray(value) && !(value instanceof Blob);
597
+ }
2702
598
  //#endregion
2703
599
  //#region src/server/action-client.ts
2704
600
  /**
@@ -2711,7 +607,11 @@ var coerce = {
2711
607
  * 1. Direct call: action(input) → Promise<ActionResult>
2712
608
  * 2. React useActionState: (prevState, formData) => Promise<ActionResult>
2713
609
  *
2714
- * See design/08-forms-and-actions.md §"Middleware for Server Actions"
610
+ * Types live in `action-types.ts`, schema handling in `action-schema.ts`, and
611
+ * the schema's declared shape (list fields, sensitive fields) in
612
+ * `schema-introspection.ts`.
613
+ *
614
+ * See design/08-forms-and-actions.md §"Middleware and Server Actions"
2715
615
  */
2716
616
  /**
2717
617
  * Typed error class for server actions. Carries a string code and optional data.
@@ -2731,10 +631,6 @@ var ActionError = class extends Error {
2731
631
  this.data = data;
2732
632
  }
2733
633
  };
2734
- /** Check if a schema implements the Standard Schema protocol. */
2735
- function isStandardSchema(schema) {
2736
- return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"].validate === "function";
2737
- }
2738
634
  /**
2739
635
  * Run middleware array or single function. Returns merged context.
2740
636
  */
@@ -2754,43 +650,11 @@ async function runActionMiddleware(middleware) {
2754
650
  return await middleware();
2755
651
  }
2756
652
  /**
2757
- * Extract validation errors from a schema error.
2758
- * Supports Zod's flatten() and generic issues array.
2759
- */
2760
- function extractValidationErrors(error) {
2761
- if (typeof error.flatten === "function") return error.flatten().fieldErrors;
2762
- if (error.issues) {
2763
- const errors = {};
2764
- for (const issue of error.issues) {
2765
- const path = issue.path?.join(".") ?? "_root";
2766
- if (!errors[path]) errors[path] = [];
2767
- errors[path].push(issue.message);
2768
- }
2769
- return errors;
2770
- }
2771
- return { _root: ["Validation failed"] };
2772
- }
2773
- /**
2774
- * Extract validation errors from Standard Schema issues.
2775
- */
2776
- function extractStandardSchemaErrors(issues) {
2777
- const errors = {};
2778
- for (const issue of issues) {
2779
- const path = issue.path?.map((p) => {
2780
- if (typeof p === "object" && p !== null && "key" in p) return String(p.key);
2781
- return String(p);
2782
- }).join(".") ?? "_root";
2783
- if (!errors[path]) errors[path] = [];
2784
- errors[path].push(issue.message);
2785
- }
2786
- return Object.keys(errors).length > 0 ? errors : { _root: ["Validation failed"] };
2787
- }
2788
- /**
2789
653
  * Wrap unexpected errors into a safe server error result.
2790
654
  * ActionError → typed result. Other errors → INTERNAL_ERROR (no leak).
2791
655
  *
2792
- * Exported for use by action-handler.ts to catch errors from raw 'use server'
2793
- * functions that don't use createActionClient.
656
+ * `createActionClient` actions only. A raw `'use server'` function that
657
+ * throws is rejected on the client instead (action-handler.ts).
2794
658
  */
2795
659
  function handleActionError(error) {
2796
660
  if (error instanceof ActionError) return { serverError: {
@@ -2824,62 +688,59 @@ function handleActionError(error) {
2824
688
  */
2825
689
  function createActionClient(config = {}) {
2826
690
  function buildAction(schema, fn) {
691
+ let shape;
692
+ let introspected = false;
693
+ const getShape = () => {
694
+ if (!introspected) {
695
+ shape = introspectSchema(schema);
696
+ introspected = true;
697
+ }
698
+ return shape;
699
+ };
2827
700
  async function actionHandler(...args) {
701
+ const last = args.at(-1);
702
+ const form = last instanceof FormData ? normalizeListFields(parseFormData(last), getShape()) : void 0;
703
+ const sensitivePredicate = resolveSensitivePredicate(config.stripSensitiveFields, void 0);
704
+ const echo = (value) => {
705
+ const withoutFiles = stripFiles(value);
706
+ if (withoutFiles === void 0) return void 0;
707
+ return stripSensitiveFields(withoutFiles, sensitivePredicate, getShape());
708
+ };
2828
709
  try {
2829
710
  const ctx = await runActionMiddleware(config.middleware);
2830
- let rawInput;
2831
- if (args.length === 2 && args[1] instanceof FormData) rawInput = schema ? parseFormData(args[1]) : args[1];
2832
- else if (args.length === 1 && args[0] instanceof FormData) rawInput = schema ? parseFormData(args[0]) : args[0];
2833
- else rawInput = args[0];
2834
- if (config.fileSizeLimit !== void 0 && rawInput && typeof rawInput === "object") {
2835
- const fileSizeErrors = validateFileSizes(rawInput, config.fileSizeLimit);
711
+ const rawInput = schema && form ? form : last;
712
+ const submitted = form ?? rawInput;
713
+ if (config.fileSizeLimit !== void 0 && submitted && typeof submitted === "object") {
714
+ const fileSizeErrors = validateFileSizes(submitted, config.fileSizeLimit);
2836
715
  if (fileSizeErrors) return {
2837
716
  validationErrors: fileSizeErrors,
2838
- submittedValues: stripFiles(rawInput)
717
+ submittedValues: echo(submitted)
2839
718
  };
2840
719
  }
2841
- const submittedValues = schema ? stripFiles(rawInput) : void 0;
2842
- let input;
2843
- if (schema) if (isStandardSchema(schema)) {
2844
- const result = schema["~standard"].validate(rawInput);
2845
- if (result instanceof Promise) throw new Error("[timber] createActionClient: schema returned a Promise — only sync schemas are supported.");
2846
- if (result.issues) {
2847
- const validationErrors = extractStandardSchemaErrors(result.issues);
2848
- logValidationFailure(validationErrors);
2849
- return {
2850
- validationErrors,
2851
- submittedValues
2852
- };
2853
- }
2854
- input = result.value;
2855
- } else if (typeof schema.safeParse === "function") {
2856
- const result = schema.safeParse(rawInput);
2857
- if (!result.success) {
2858
- const validationErrors = extractValidationErrors(result.error);
2859
- logValidationFailure(validationErrors);
720
+ let input = rawInput;
721
+ if (schema) {
722
+ const validation = validateWithSchema(schema, rawInput);
723
+ if (!validation.ok) {
724
+ logValidationFailure(validation.validationErrors);
2860
725
  return {
2861
- validationErrors,
2862
- submittedValues
726
+ validationErrors: validation.validationErrors,
727
+ submittedValues: echo(submitted)
2863
728
  };
2864
729
  }
2865
- input = result.data;
2866
- } else try {
2867
- input = schema.parse(rawInput);
2868
- } catch (parseError) {
2869
- const validationErrors = extractValidationErrors(parseError);
2870
- logValidationFailure(validationErrors);
2871
- return {
2872
- validationErrors,
2873
- submittedValues
2874
- };
730
+ input = validation.value;
2875
731
  }
2876
- else input = rawInput;
2877
732
  return { data: await fn({
2878
733
  ctx,
2879
734
  input
2880
735
  }) };
2881
736
  } catch (error) {
2882
- return handleActionError(error);
737
+ if (isRedirectSignal(error) || isDenySignal(error)) throw error;
738
+ const result = handleActionError(error);
739
+ const submittedValues = form && echo(form);
740
+ return submittedValues ? {
741
+ ...result,
742
+ submittedValues
743
+ } : result;
2883
744
  }
2884
745
  }
2885
746
  return actionHandler;
@@ -2896,305 +757,61 @@ function createActionClient(config = {}) {
2896
757
  };
2897
758
  }
2898
759
  /**
2899
- * Convenience wrapper for the common case: validate input, run handler.
2900
- * No middleware needed.
2901
- *
2902
- * @example
2903
- * ```ts
2904
- * 'use server'
2905
- * import { validated } from '@timber-js/app/server'
2906
- * import { z } from 'zod'
2907
- *
2908
- * export const createTodo = validated(
2909
- * z.object({ title: z.string().min(1) }),
2910
- * async (input) => {
2911
- * await db.todos.create(input)
2912
- * }
2913
- * )
2914
- * ```
2915
- */
2916
- function validated(schema, handler) {
2917
- return createActionClient().schema(schema).action(async ({ input }) => handler(input));
2918
- }
2919
- /**
2920
760
  * Log validation failures in dev mode so developers can see what went wrong.
2921
761
  * In production, validation errors are only returned to the client.
2922
762
  */
2923
763
  function logValidationFailure(errors) {
2924
764
  if (!isDebug()) return;
2925
- const fields = Object.entries(errors).map(([field, messages]) => ` ${field}: ${messages.join(", ")}`).join("\n");
765
+ const fields = Object.entries(errors).map(([field, messages]) => ` ${field}: ${(messages ?? []).join(", ")}`).join("\n");
2926
766
  console.warn(`[timber] action schema validation failed:\n${fields}`);
2927
767
  }
2928
768
  /**
2929
769
  * Validate that all File objects in the input are within the size limit.
2930
770
  * Returns validation errors keyed by field name, or null if all files are ok.
771
+ * Keys are dot paths (`rows.0.file`), the form a field name and a Standard
772
+ * Schema error use, so `errors.field()` finds a file in a list.
2931
773
  */
2932
774
  function validateFileSizes(input, limit) {
2933
- const errors = {};
2934
775
  const limitKb = Math.round(limit / 1024);
2935
- const limitLabel = limit >= 1024 * 1024 ? `${Math.round(limit / (1024 * 1024))}MB` : `${limitKb}KB`;
2936
- for (const [key, value] of Object.entries(input)) if (value instanceof File && value.size > limit) errors[key] = [`File "${value.name}" (${formatSize(value.size)}) exceeds the ${limitLabel} limit`];
2937
- else if (Array.isArray(value)) {
2938
- const oversized = value.filter((item) => item instanceof File && item.size > limit);
2939
- if (oversized.length > 0) errors[key] = oversized.map((f) => `File "${f.name}" (${formatSize(f.size)}) exceeds the ${limitLabel} limit`);
776
+ const limitLabel = limit >= 1048576 ? `${Math.round(limit / 1048576)}MB` : `${limitKb}KB`;
777
+ const errors = {};
778
+ function walk(obj, prefix) {
779
+ for (const [key, value] of Object.entries(obj)) {
780
+ const path = prefix ? `${prefix}.${key}` : key;
781
+ if (value instanceof File && value.size > limit) errors[path] = [`File "${value.name}" (${formatSize(value.size)}) exceeds the ${limitLabel} limit`];
782
+ else if (Array.isArray(value)) for (let i = 0; i < value.length; i++) {
783
+ const item = value[i];
784
+ const itemPath = `${path}.${i}`;
785
+ if (item instanceof File && item.size > limit) (errors[itemPath] ??= []).push(`File "${item.name}" (${formatSize(item.size)}) exceeds the ${limitLabel} limit`);
786
+ else if (typeof item === "object" && item !== null && !(item instanceof File)) walk(item, itemPath);
787
+ }
788
+ else if (typeof value === "object" && value !== null && !(value instanceof File)) walk(value, path);
789
+ }
2940
790
  }
791
+ walk(input, "");
2941
792
  return Object.keys(errors).length > 0 ? errors : null;
2942
793
  }
2943
794
  /**
2944
- * Strip File objects from a value, returning a plain object safe for
2945
- * serialization. File objects can't be serialized and shouldn't be echoed back.
795
+ * Strip File objects from a value, returning a copy safe for serialization.
796
+ * File objects can't be serialized and shouldn't be echoed back.
797
+ *
798
+ * Mirrors `parseFormData`'s output: objects and arrays at any depth, arrays
799
+ * of arrays included. A File in an array becomes `undefined` rather than
800
+ * being removed, so `rows.2` still names the third element (TIM-1573).
2946
801
  */
2947
802
  function stripFiles(value) {
2948
- if (value === null || value === void 0) return void 0;
2949
- if (typeof value !== "object") return void 0;
803
+ if (value === null || typeof value !== "object" || value instanceof File) return void 0;
804
+ return stripFilesFrom(value);
805
+ }
806
+ function stripFilesFrom(value) {
807
+ if (value instanceof File) return void 0;
808
+ if (Array.isArray(value)) return value.map(stripFilesFrom);
809
+ if (typeof value !== "object" || value === null) return value;
2950
810
  const result = {};
2951
- for (const [k, v] of Object.entries(value)) {
2952
- if (v instanceof File) continue;
2953
- if (Array.isArray(v)) result[k] = v.filter((item) => !(item instanceof File));
2954
- else if (typeof v === "object" && v !== null && !(v instanceof File)) result[k] = stripFiles(v) ?? {};
2955
- else result[k] = v;
2956
- }
811
+ for (const [k, v] of Object.entries(value)) if (!(v instanceof File)) result[k] = stripFilesFrom(v);
2957
812
  return result;
2958
813
  }
2959
814
  //#endregion
2960
- //#region src/server/form-flash.ts
2961
- /**
2962
- * Read the form flash data for the current request.
2963
- *
2964
- * Returns `null` if no flash data is present (i.e., this is a normal page
2965
- * render, not a re-render after a no-JS form submission).
2966
- *
2967
- * Pass the flash as the initial state to `useActionState` so the form
2968
- * component has a single source of truth for both with-JS and no-JS paths:
2969
- *
2970
- * ```tsx
2971
- * // app/contact/page.tsx (server component)
2972
- * import { getFormFlash } from '@timber-js/app/server'
2973
- *
2974
- * export default function ContactPage() {
2975
- * const flash = getFormFlash()
2976
- * return <ContactForm flash={flash} />
2977
- * }
2978
- *
2979
- * // app/contact/form.tsx (client component)
2980
- * export function ContactForm({ flash }) {
2981
- * const [result, action, isPending] = useActionState(submitContact, flash)
2982
- * // result is the single source of truth — flash seeds it on no-JS
2983
- * }
2984
- * ```
2985
- */
2986
- function getFormFlash() {
2987
- return formFlashAls.getStore() ?? null;
2988
- }
2989
- //#endregion
2990
- //#region src/server/actions.ts
2991
- /**
2992
- * Get the current revalidation state. Throws if called outside an action context.
2993
- * @internal
2994
- */
2995
- function getRevalidationState() {
2996
- const state = revalidationAls.getStore();
2997
- if (!state) throw new Error("revalidatePath/revalidateTag called outside of a server action context. These functions can only be called during action execution.");
2998
- return state;
2999
- }
3000
- /**
3001
- * Re-render the route at `path` and include the RSC flight payload in the
3002
- * action response. The client reconciles inline — no separate fetch needed.
3003
- *
3004
- * Can be called from server actions, API routes, or any server-side context.
3005
- *
3006
- * @param path - The path to re-render (e.g. '/dashboard', '/todos').
3007
- */
3008
- function revalidatePath(path) {
3009
- const state = getRevalidationState();
3010
- if (!state.paths.includes(path)) state.paths.push(path);
3011
- }
3012
- /**
3013
- * Invalidate all pre-rendered shells and 'use cache' entries tagged with `tag`.
3014
- * Does not return a payload — the next request for an invalidated route re-renders fresh.
3015
- *
3016
- * @param tag - The cache tag to invalidate (e.g. 'products', 'user:123').
3017
- */
3018
- function revalidateTag(tag) {
3019
- const state = getRevalidationState();
3020
- if (!state.tags.includes(tag)) state.tags.push(tag);
3021
- }
3022
- /**
3023
- * Execute a server action and process revalidation.
3024
- *
3025
- * 1. Sets up revalidation state
3026
- * 2. Calls the action function
3027
- * 3. Processes revalidateTag calls (invalidates cache entries)
3028
- * 4. Processes revalidatePath calls (re-renders and captures RSC payload)
3029
- * 5. Returns the action result + optional RSC payload
3030
- *
3031
- * @param actionFn - The server action function to execute.
3032
- * @param args - Arguments to pass to the action.
3033
- * @param config - Handler configuration (cache handler, renderer).
3034
- */
3035
- async function executeAction(actionFn, args, config = {}, spanMeta) {
3036
- const state = {
3037
- paths: [],
3038
- tags: []
3039
- };
3040
- let actionResult;
3041
- let redirectTo;
3042
- let redirectStatus;
3043
- await revalidationAls.run(state, async () => {
3044
- try {
3045
- actionResult = await withSpan("timber.action", {
3046
- ...spanMeta?.actionFile ? { "timber.action_file": spanMeta.actionFile } : {},
3047
- ...spanMeta?.actionName ? { "timber.action_name": spanMeta.actionName } : {}
3048
- }, () => actionFn(...args));
3049
- } catch (error) {
3050
- if (error instanceof RedirectSignal) {
3051
- redirectTo = error.location;
3052
- redirectStatus = error.status;
3053
- } else throw error;
3054
- }
3055
- });
3056
- if (state.tags.length > 0 && config.cacheHandler) await Promise.all(state.tags.map((tag) => config.cacheHandler.invalidate({ tag })));
3057
- let revalidation;
3058
- if (state.paths.length > 0 && config.renderer) {
3059
- const path = state.paths[0];
3060
- try {
3061
- revalidation = await config.renderer(path);
3062
- } catch (renderError) {
3063
- if (renderError instanceof RedirectSignal) {
3064
- redirectTo = renderError.location;
3065
- redirectStatus = renderError.status;
3066
- } else console.error("[timber] revalidatePath render failed:", renderError);
3067
- }
3068
- }
3069
- return {
3070
- actionResult,
3071
- revalidation,
3072
- ...redirectTo ? {
3073
- redirectTo,
3074
- redirectStatus
3075
- } : {}
3076
- };
3077
- }
3078
- /**
3079
- * Build an HTTP Response for a no-JS form submission.
3080
- * Standard POST → 302 redirect pattern.
3081
- *
3082
- * @param redirectPath - Where to redirect after the action executes.
3083
- */
3084
- function buildNoJsResponse(redirectPath, status = 302) {
3085
- return new Response(null, {
3086
- status,
3087
- headers: { Location: redirectPath }
3088
- });
3089
- }
3090
- /**
3091
- * Detect whether the incoming request is an RSC action request (with JS)
3092
- * or a plain HTML form POST (no JS).
3093
- *
3094
- * RSC action requests use Accept: text/x-component or Content-Type: text/x-component.
3095
- */
3096
- function isRscActionRequest(req) {
3097
- const accept = req.headers.get("Accept") ?? "";
3098
- const contentType = req.headers.get("Content-Type") ?? "";
3099
- return accept.includes("text/x-component") || contentType.includes("text/x-component");
3100
- }
3101
- //#endregion
3102
- //#region src/server/route-handler.ts
3103
- /** All recognized HTTP method export names. */
3104
- var HTTP_METHODS = [
3105
- "GET",
3106
- "POST",
3107
- "PUT",
3108
- "PATCH",
3109
- "DELETE",
3110
- "HEAD",
3111
- "OPTIONS"
3112
- ];
3113
- /**
3114
- * Resolve the full list of allowed methods for a route module.
3115
- *
3116
- * Includes:
3117
- * - All explicitly exported methods
3118
- * - HEAD (implicit when GET is exported)
3119
- * - OPTIONS (always implicit)
3120
- */
3121
- function resolveAllowedMethods(mod) {
3122
- const methods = [];
3123
- for (const method of HTTP_METHODS) {
3124
- if (method === "HEAD" || method === "OPTIONS") continue;
3125
- if (mod[method]) methods.push(method);
3126
- }
3127
- if (mod.GET && !mod.HEAD) methods.push("HEAD");
3128
- else if (mod.HEAD) methods.push("HEAD");
3129
- if (!mod.OPTIONS) methods.push("OPTIONS");
3130
- else methods.push("OPTIONS");
3131
- return methods;
3132
- }
3133
- /**
3134
- * Handle an incoming request against a route.ts module.
3135
- *
3136
- * Dispatches to the named method handler, auto-generates 405/OPTIONS,
3137
- * and merges response headers from ctx.headers.
3138
- */
3139
- async function handleRouteRequest(mod, ctx) {
3140
- const method = ctx.req.method.toUpperCase();
3141
- const allowHeader = resolveAllowedMethods(mod).join(", ");
3142
- if (method === "OPTIONS") {
3143
- if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
3144
- return new Response(null, {
3145
- status: 204,
3146
- headers: { Allow: allowHeader }
3147
- });
3148
- }
3149
- if (method === "HEAD") {
3150
- if (mod.HEAD) return runHandler(mod.HEAD, ctx);
3151
- if (mod.GET) {
3152
- const res = await runHandler(mod.GET, ctx);
3153
- return new Response(null, {
3154
- status: res.status,
3155
- headers: res.headers
3156
- });
3157
- }
3158
- }
3159
- const handler = mod[method];
3160
- if (!handler) return new Response(null, {
3161
- status: 405,
3162
- headers: { Allow: allowHeader }
3163
- });
3164
- return runHandler(handler, ctx);
3165
- }
3166
- /**
3167
- * Run a handler, merge ctx.headers into the response, and catch errors.
3168
- */
3169
- async function runHandler(handler, ctx) {
3170
- try {
3171
- return mergeResponseHeaders(await handler(ctx), ctx.headers);
3172
- } catch (error) {
3173
- console.error("[timber] Uncaught error in route.ts handler:", error);
3174
- return new Response(null, { status: 500 });
3175
- }
3176
- }
3177
- /**
3178
- * Merge response headers from ctx.headers into the handler's response.
3179
- * ctx.headers (set by middleware or the handler) are applied to the final response.
3180
- * Handler-set headers take precedence over ctx.headers.
3181
- */
3182
- function mergeResponseHeaders(res, ctxHeaders) {
3183
- let hasCtxHeaders = false;
3184
- ctxHeaders.forEach(() => {
3185
- hasCtxHeaders = true;
3186
- });
3187
- if (!hasCtxHeaders) return res;
3188
- const merged = new Headers();
3189
- ctxHeaders.forEach((value, key) => merged.set(key, value));
3190
- res.headers.forEach((value, key) => merged.set(key, value));
3191
- return new Response(res.body, {
3192
- status: res.status,
3193
- statusText: res.statusText,
3194
- headers: merged
3195
- });
3196
- }
3197
- //#endregion
3198
- export { AccessGate, ActionError, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RedirectType, RenderError, SlotAccessGate, WarningId, addSpanEvent, buildElementTree, buildNoJsResponse, callOnRequestError, canonicalize, classifyMetadataRoute, coerce, collectEarlyHintHeaders, cookies, createActionClient, createPipeline, deny, enforceBodyLimits, executeAction, flushResponse, formatLinkHeader, generateTraceId, getFormFlash, getLogger, getMetadataRouteAutoLink, getMetadataRouteServePath, getSetCookieHeaders, handleRouteRequest, hasOnRequestError, headers, isRscActionRequest, loadInstrumentation, logCacheMiss, logMiddlewareError, logMiddlewareShortCircuit, logProxyError, logRenderError, logRequestCompleted, logRequestReceived, logSlowRequest, logSwrRefetchFailed, logWaitUntilRejected, logWaitUntilUnsupported, markResponseFlushed, notFound, parseBodySize, parseFormData, permanentRedirect, redirect, redirectExternal, renderMetadataToElements, replaceTraceId, resolveAllowedMethods, resolveMetadata, resolveMetadataUrls, resolveSlotDenied, resolveStatusFile, resolveTitle, revalidatePath, revalidateTag, runMiddleware, runProxy, runWithEarlyHintsSender, runWithRequestContext, runWithTraceId, searchParams, sendEarlyHints103, setCookieSecrets, setLogger, setMutableCookieContext, setParsedSearchParams, setViteServer, spanId, traceId, validateCsrf, validated, waitUntil, warnCacheRequestProps, warnDenyAfterFlush, warnDenyInSuspense, warnDynamicApiInStaticBuild, warnRedirectInAccess, warnRedirectInSlotAccess, warnRedirectInSuspense, warnSlowSlotWithoutSuspense, warnStaticRequestApi, warnSuspenseWrappingChildren, withSpan };
815
+ export { ActionError, RedirectType, addSpanEvent, coerce, createActionClient, deny, getCookieJar, getHeaders, getSegmentParams, getSpanId, getTraceId, parseFormData, redirect, redirectExternal, revalidatePath, revalidateTag, waitUntil, withSpan };
3199
816
 
3200
817
  //# sourceMappingURL=index.js.map