@timber-js/app 0.2.0-alpha.186 → 0.2.0-alpha.188

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 (331) hide show
  1. package/dist/_chunks/{actions-C-Rw9vPc.js → actions-35jnMdeJ.js} +4 -3
  2. package/dist/_chunks/{actions-C-Rw9vPc.js.map → actions-35jnMdeJ.js.map} +1 -1
  3. package/dist/_chunks/als-registry-C6kcfprT.js +41 -0
  4. package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -0
  5. package/dist/_chunks/{als-slots-mFweg276.js → als-slots-BEEIPKYm.js} +3 -4
  6. package/dist/_chunks/{als-slots-mFweg276.js.map → als-slots-BEEIPKYm.js.map} +1 -1
  7. package/dist/_chunks/{cache-api-Cd0VZ_Pd.js → cache-api-DjNrIWRR.js} +7 -13
  8. package/dist/_chunks/cache-api-DjNrIWRR.js.map +1 -0
  9. package/dist/_chunks/cli-check-CpmN7Nh-.js +256 -0
  10. package/dist/_chunks/cli-check-CpmN7Nh-.js.map +1 -0
  11. package/dist/_chunks/cli-schema-sync-CGMp_Psg.js +298 -0
  12. package/dist/_chunks/cli-schema-sync-CGMp_Psg.js.map +1 -0
  13. package/dist/_chunks/{cloudflare-Cs0uZXea.js → cloudflare-CGP6BZKO.js} +4 -3
  14. package/dist/_chunks/{cloudflare-Cs0uZXea.js.map → cloudflare-CGP6BZKO.js.map} +1 -1
  15. package/dist/_chunks/convention-lint-kXsgc_-7.js +784 -0
  16. package/dist/_chunks/convention-lint-kXsgc_-7.js.map +1 -0
  17. package/dist/_chunks/{error-boundary-DpYRI_I1.js → error-boundary-D-ODYX41.js} +25 -2
  18. package/dist/_chunks/error-boundary-D-ODYX41.js.map +1 -0
  19. package/dist/_chunks/file-cache-DmX7OqZP.js +454 -0
  20. package/dist/_chunks/file-cache-DmX7OqZP.js.map +1 -0
  21. package/dist/_chunks/{logger-N7e5auP0.js → logger-D8xJZXIN.js} +27 -40
  22. package/dist/_chunks/logger-D8xJZXIN.js.map +1 -0
  23. package/dist/_chunks/mdx-file-C005ay-P.js +25 -0
  24. package/dist/_chunks/mdx-file-C005ay-P.js.map +1 -0
  25. package/dist/_chunks/{plugin-context-DEGLSJs3.js → plugin-context-rCinWLiE.js} +7 -2
  26. package/dist/_chunks/{plugin-context-DEGLSJs3.js.map → plugin-context-rCinWLiE.js.map} +1 -1
  27. package/dist/_chunks/purge-store-Byr8XOjU.js +14 -0
  28. package/dist/_chunks/purge-store-Byr8XOjU.js.map +1 -0
  29. package/dist/_chunks/{resolve-schema-Dz3fcFUo.js → resolve-schema-5ma5pp1b.js} +2 -2
  30. package/dist/_chunks/{resolve-schema-Dz3fcFUo.js.map → resolve-schema-5ma5pp1b.js.map} +1 -1
  31. package/dist/_chunks/rsc-media-type-DRqE_lD_.js +46 -0
  32. package/dist/_chunks/rsc-media-type-DRqE_lD_.js.map +1 -0
  33. package/dist/_chunks/{cli-schema-sync-CKgHC2MB.js → scanner-C8b0Gcw3.js} +5 -298
  34. package/dist/_chunks/scanner-C8b0Gcw3.js.map +1 -0
  35. package/dist/_chunks/schema-bridge-Cc2Gngu1.js +199 -0
  36. package/dist/_chunks/schema-bridge-Cc2Gngu1.js.map +1 -0
  37. package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -1
  38. package/dist/_chunks/{param-value-C8TNYchQ.js → segment-context-CjOlyB8Y.js} +33 -2
  39. package/dist/_chunks/segment-context-CjOlyB8Y.js.map +1 -0
  40. package/dist/_chunks/segment-keys-BawYuNFO.js.map +1 -1
  41. package/dist/_chunks/{use-query-states-DFvWd-EA.js → use-query-states-BbU5Ge1V.js} +74 -26
  42. package/dist/_chunks/use-query-states-BbU5Ge1V.js.map +1 -0
  43. package/dist/_chunks/{navigation-root-B29qg0_T.js → use-segment-params-C4r4BD9T.js} +129 -5
  44. package/dist/_chunks/use-segment-params-C4r4BD9T.js.map +1 -0
  45. package/dist/_chunks/walkers-RzN6AFjr.js +141 -0
  46. package/dist/_chunks/walkers-RzN6AFjr.js.map +1 -0
  47. package/dist/adapters/cloudflare-dev.js +1 -1
  48. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  49. package/dist/adapters/cloudflare.d.ts.map +1 -1
  50. package/dist/adapters/cloudflare.js +1 -1
  51. package/dist/adapters/compress-module.d.ts +12 -0
  52. package/dist/adapters/compress-module.d.ts.map +1 -1
  53. package/dist/adapters/nitro.js +54 -2
  54. package/dist/adapters/nitro.js.map +1 -1
  55. package/dist/cache/index.js +1 -1
  56. package/dist/cdn/cloudflare-purge.js +30 -0
  57. package/dist/cdn/cloudflare-purge.js.map +1 -0
  58. package/dist/cdn/fastly-purge.js +33 -0
  59. package/dist/cdn/fastly-purge.js.map +1 -0
  60. package/dist/cdn/index.js +94 -0
  61. package/dist/cdn/index.js.map +1 -0
  62. package/dist/cdn/workers-cache-purge.js +35 -0
  63. package/dist/cdn/workers-cache-purge.js.map +1 -0
  64. package/dist/cli-check.d.ts +153 -0
  65. package/dist/cli-check.d.ts.map +1 -0
  66. package/dist/cli.d.ts +34 -8
  67. package/dist/cli.d.ts.map +1 -1
  68. package/dist/cli.js +46 -21
  69. package/dist/cli.js.map +1 -1
  70. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
  71. package/dist/client/browser-entry/index.d.ts +1 -1
  72. package/dist/client/browser-entry/index.d.ts.map +1 -1
  73. package/dist/client/error-boundary.d.ts +6 -0
  74. package/dist/client/error-boundary.d.ts.map +1 -1
  75. package/dist/client/error-boundary.js +1 -1
  76. package/dist/client/index.d.ts +1 -0
  77. package/dist/client/index.d.ts.map +1 -1
  78. package/dist/client/index.js +27 -33
  79. package/dist/client/index.js.map +1 -1
  80. package/dist/client/internal.js +33 -17
  81. package/dist/client/internal.js.map +1 -1
  82. package/dist/client/link.d.ts +1 -7
  83. package/dist/client/link.d.ts.map +1 -1
  84. package/dist/client/navigation-commit.d.ts +16 -0
  85. package/dist/client/navigation-commit.d.ts.map +1 -1
  86. package/dist/client/router-pipeline.d.ts.map +1 -1
  87. package/dist/client/router.d.ts.map +1 -1
  88. package/dist/client/rsc-fetch.d.ts +9 -1
  89. package/dist/client/rsc-fetch.d.ts.map +1 -1
  90. package/dist/client/segment-cache.d.ts +14 -0
  91. package/dist/client/segment-cache.d.ts.map +1 -1
  92. package/dist/client/use-query-states.d.ts +9 -3
  93. package/dist/client/use-query-states.d.ts.map +1 -1
  94. package/dist/codec.js +1 -1
  95. package/dist/cookies/define-cookie.d.ts.map +1 -1
  96. package/dist/cookies/index.js +2 -2
  97. package/dist/cookies/index.js.map +1 -1
  98. package/dist/index.d.ts +4 -1
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +142 -477
  101. package/dist/index.js.map +1 -1
  102. package/dist/params/index.js +1 -1
  103. package/dist/plugin-context.d.ts +15 -0
  104. package/dist/plugin-context.d.ts.map +1 -1
  105. package/dist/plugins/routing.d.ts +0 -9
  106. package/dist/plugins/routing.d.ts.map +1 -1
  107. package/dist/plugins/shims.d.ts.map +1 -1
  108. package/dist/plugins/static-build.d.ts +24 -0
  109. package/dist/plugins/static-build.d.ts.map +1 -1
  110. package/dist/routing/codegen-shared.d.ts +3 -44
  111. package/dist/routing/codegen-shared.d.ts.map +1 -1
  112. package/dist/routing/codegen-types.d.ts +10 -31
  113. package/dist/routing/codegen-types.d.ts.map +1 -1
  114. package/dist/routing/codegen-write.d.ts +51 -0
  115. package/dist/routing/codegen-write.d.ts.map +1 -0
  116. package/dist/routing/codegen.d.ts.map +1 -1
  117. package/dist/routing/convention-lint.d.ts +18 -4
  118. package/dist/routing/convention-lint.d.ts.map +1 -1
  119. package/dist/routing/export-detect.d.ts +16 -0
  120. package/dist/routing/export-detect.d.ts.map +1 -1
  121. package/dist/routing/index.js +3 -2
  122. package/dist/routing/link-codegen.d.ts +19 -4
  123. package/dist/routing/link-codegen.d.ts.map +1 -1
  124. package/dist/routing/manifest-codegen.d.ts +1 -7
  125. package/dist/routing/manifest-codegen.d.ts.map +1 -1
  126. package/dist/routing/segment-keys.d.ts +22 -0
  127. package/dist/routing/segment-keys.d.ts.map +1 -1
  128. package/dist/routing/types.d.ts +0 -6
  129. package/dist/routing/types.d.ts.map +1 -1
  130. package/dist/schema-bridge.d.ts +60 -9
  131. package/dist/schema-bridge.d.ts.map +1 -1
  132. package/dist/search-params/define.d.ts +62 -8
  133. package/dist/search-params/define.d.ts.map +1 -1
  134. package/dist/search-params/index.d.ts +0 -1
  135. package/dist/search-params/index.d.ts.map +1 -1
  136. package/dist/search-params/index.js +66 -29
  137. package/dist/search-params/index.js.map +1 -1
  138. package/dist/search-params/parse-total.d.ts +70 -0
  139. package/dist/search-params/parse-total.d.ts.map +1 -0
  140. package/dist/search-params/wrappers.d.ts +26 -3
  141. package/dist/search-params/wrappers.d.ts.map +1 -1
  142. package/dist/server/access-gate.d.ts +19 -8
  143. package/dist/server/access-gate.d.ts.map +1 -1
  144. package/dist/server/action-handler.d.ts.map +1 -1
  145. package/dist/server/als-registry.d.ts +16 -0
  146. package/dist/server/als-registry.d.ts.map +1 -1
  147. package/dist/server/chain-url-parts.d.ts +2 -3
  148. package/dist/server/chain-url-parts.d.ts.map +1 -1
  149. package/dist/server/compress.d.ts.map +1 -1
  150. package/dist/server/deny-boundary.d.ts +148 -15
  151. package/dist/server/deny-boundary.d.ts.map +1 -1
  152. package/dist/server/deny-renderer.d.ts +2 -2
  153. package/dist/server/deny-renderer.d.ts.map +1 -1
  154. package/dist/server/error-boundary-wrapper.d.ts +85 -15
  155. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  156. package/dist/server/index.d.ts +0 -1
  157. package/dist/server/index.d.ts.map +1 -1
  158. package/dist/server/index.js +3 -2
  159. package/dist/server/index.js.map +1 -1
  160. package/dist/server/internal.d.ts +3 -1
  161. package/dist/server/internal.d.ts.map +1 -1
  162. package/dist/server/internal.js +344 -237
  163. package/dist/server/internal.js.map +1 -1
  164. package/dist/server/metadata-collector.d.ts +52 -0
  165. package/dist/server/metadata-collector.d.ts.map +1 -0
  166. package/dist/server/param-coercion.d.ts +12 -5
  167. package/dist/server/param-coercion.d.ts.map +1 -1
  168. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  169. package/dist/server/pipeline-outcome.d.ts.map +1 -1
  170. package/dist/server/pipeline-phases.d.ts.map +1 -1
  171. package/dist/server/primitives.d.ts +23 -0
  172. package/dist/server/primitives.d.ts.map +1 -1
  173. package/dist/server/route-element-builder.d.ts +1 -12
  174. package/dist/server/route-element-builder.d.ts.map +1 -1
  175. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -1
  176. package/dist/server/rsc-entry/deny-fallback.d.ts.map +1 -1
  177. package/dist/server/rsc-entry/error-renderer.d.ts +1 -1
  178. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  179. package/dist/server/rsc-entry/helpers.d.ts +0 -7
  180. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  181. package/dist/server/rsc-entry/index.d.ts +0 -1
  182. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  183. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  184. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -1
  185. package/dist/server/rsc-entry/rsc-payload.d.ts +1 -3
  186. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  187. package/dist/server/rsc-entry/rsc-stream.d.ts +12 -0
  188. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  189. package/dist/server/rsc-entry/ssr-renderer.d.ts +0 -2
  190. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  191. package/dist/server/skippable-prefix.d.ts +3 -0
  192. package/dist/server/skippable-prefix.d.ts.map +1 -1
  193. package/dist/server/slot-resolver.d.ts +18 -19
  194. package/dist/server/slot-resolver.d.ts.map +1 -1
  195. package/dist/server/ssr-bridge-types.d.ts +11 -0
  196. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  197. package/dist/server/ssr-entry.d.ts +0 -1
  198. package/dist/server/ssr-entry.d.ts.map +1 -1
  199. package/dist/server/state-tree-diff.d.ts +9 -16
  200. package/dist/server/state-tree-diff.d.ts.map +1 -1
  201. package/dist/server/static-generator.d.ts.map +1 -1
  202. package/dist/server/status-code-resolver.d.ts +8 -1
  203. package/dist/server/status-code-resolver.d.ts.map +1 -1
  204. package/dist/server/tree-builder.d.ts +28 -43
  205. package/dist/server/tree-builder.d.ts.map +1 -1
  206. package/dist/server/types.d.ts +12 -7
  207. package/dist/server/types.d.ts.map +1 -1
  208. package/dist/server/utils/element-type.d.ts +40 -0
  209. package/dist/server/utils/element-type.d.ts.map +1 -0
  210. package/dist/shared/rsc-media-type.d.ts +40 -0
  211. package/dist/shared/rsc-media-type.d.ts.map +1 -0
  212. package/dist/shared/segment-info.d.ts +7 -0
  213. package/dist/shared/segment-info.d.ts.map +1 -1
  214. package/docs/api/30-api-server.mdx +1 -1
  215. package/docs/api/33-api-search-params.mdx +38 -16
  216. package/docs/api/35-api-typescript.mdx +3 -3
  217. package/docs/api/36-cli.mdx +34 -7
  218. package/docs/learn/00-introduction.mdx +1 -1
  219. package/docs/learn/02-pages-and-layouts.mdx +1 -1
  220. package/docs/learn/05-typed-params.mdx +8 -8
  221. package/docs/learn/07-typed-routes.mdx +12 -7
  222. package/docs/learn/11-error-handling.mdx +16 -0
  223. package/docs/more/01-advanced-routing.mdx +1 -1
  224. package/docs/more/03-coming-from-nextjs.mdx +2 -2
  225. package/docs/more/50-ai-agent-instructions.mdx +6 -4
  226. package/package.json +8 -5
  227. package/src/adapters/cloudflare.ts +4 -1
  228. package/src/adapters/compress-module.ts +79 -1
  229. package/src/cli-check.ts +458 -0
  230. package/src/cli.ts +59 -24
  231. package/src/client/browser-entry/action-dispatch.ts +2 -1
  232. package/src/client/browser-entry/index.ts +0 -5
  233. package/src/client/error-boundary.tsx +65 -1
  234. package/src/client/index.ts +14 -3
  235. package/src/client/link.tsx +65 -64
  236. package/src/client/navigation-commit.ts +27 -4
  237. package/src/client/params-context.ts +4 -4
  238. package/src/client/router-pipeline.ts +4 -0
  239. package/src/client/router.ts +1 -0
  240. package/src/client/rsc-fetch.ts +14 -4
  241. package/src/client/segment-cache.ts +26 -5
  242. package/src/client/use-query-states.ts +102 -39
  243. package/src/cookies/define-cookie.ts +6 -1
  244. package/src/index.ts +20 -3
  245. package/src/plugin-context.ts +26 -0
  246. package/src/plugins/routing.ts +84 -146
  247. package/src/plugins/shims.ts +0 -1
  248. package/src/plugins/static-build.ts +78 -24
  249. package/src/routing/codegen-shared.ts +3 -79
  250. package/src/routing/codegen-types.ts +10 -31
  251. package/src/routing/codegen-write.ts +139 -0
  252. package/src/routing/codegen.ts +56 -182
  253. package/src/routing/convention-lint.ts +139 -40
  254. package/src/routing/export-detect.ts +151 -7
  255. package/src/routing/link-codegen.ts +32 -65
  256. package/src/routing/manifest-codegen.ts +1 -59
  257. package/src/routing/scanner.ts +3 -3
  258. package/src/routing/segment-keys.ts +37 -0
  259. package/src/routing/types.ts +0 -6
  260. package/src/schema-bridge.ts +180 -58
  261. package/src/search-params/define.ts +102 -37
  262. package/src/search-params/index.ts +0 -1
  263. package/src/search-params/parse-total.ts +78 -0
  264. package/src/search-params/wrappers.ts +60 -11
  265. package/src/server/access-gate.tsx +61 -68
  266. package/src/server/action-handler.ts +1 -4
  267. package/src/server/als-registry.ts +16 -0
  268. package/src/server/chain-url-parts.ts +2 -3
  269. package/src/server/compress.ts +9 -1
  270. package/src/server/deny-boundary.ts +269 -41
  271. package/src/server/deny-renderer.ts +32 -21
  272. package/src/server/error-boundary-wrapper.ts +166 -79
  273. package/src/server/index.ts +1 -3
  274. package/src/server/internal.ts +2 -2
  275. package/src/server/metadata-collector.ts +115 -0
  276. package/src/server/param-coercion.ts +13 -61
  277. package/src/server/pipeline-helpers.ts +2 -2
  278. package/src/server/pipeline-outcome.ts +2 -1
  279. package/src/server/pipeline-phases.ts +9 -9
  280. package/src/server/primitives.ts +25 -0
  281. package/src/server/route-element-builder.ts +169 -194
  282. package/src/server/rsc-cache-key-guard.ts +2 -8
  283. package/src/server/rsc-entry/deny-fallback.ts +3 -2
  284. package/src/server/rsc-entry/error-renderer.ts +31 -11
  285. package/src/server/rsc-entry/helpers.ts +3 -12
  286. package/src/server/rsc-entry/index.ts +0 -5
  287. package/src/server/rsc-entry/render-route.ts +14 -11
  288. package/src/server/rsc-entry/revalidate-renderer.ts +2 -1
  289. package/src/server/rsc-entry/rsc-payload.ts +104 -20
  290. package/src/server/rsc-entry/rsc-stream.ts +25 -2
  291. package/src/server/rsc-entry/ssr-renderer.ts +28 -16
  292. package/src/server/skippable-prefix.ts +21 -39
  293. package/src/server/slot-resolver.ts +69 -189
  294. package/src/server/ssr-bridge-types.ts +12 -0
  295. package/src/server/ssr-entry.ts +8 -6
  296. package/src/server/state-tree-diff.ts +11 -62
  297. package/src/server/static-generator.ts +3 -2
  298. package/src/server/status-code-resolver.ts +28 -11
  299. package/src/server/tree-builder.ts +35 -228
  300. package/src/server/types.ts +12 -7
  301. package/src/server/utils/element-type.ts +72 -0
  302. package/src/shared/rsc-media-type.ts +43 -0
  303. package/src/shared/segment-info.ts +7 -0
  304. package/dist/_chunks/cache-api-Cd0VZ_Pd.js.map +0 -1
  305. package/dist/_chunks/cli-schema-sync-CKgHC2MB.js.map +0 -1
  306. package/dist/_chunks/error-boundary-DpYRI_I1.js.map +0 -1
  307. package/dist/_chunks/logger-N7e5auP0.js.map +0 -1
  308. package/dist/_chunks/navigation-root-B29qg0_T.js.map +0 -1
  309. package/dist/_chunks/param-value-C8TNYchQ.js.map +0 -1
  310. package/dist/_chunks/registry-DbJPKoBp.js +0 -20
  311. package/dist/_chunks/registry-DbJPKoBp.js.map +0 -1
  312. package/dist/_chunks/schema-bridge-DT_Tn0Xf.js +0 -119
  313. package/dist/_chunks/schema-bridge-DT_Tn0Xf.js.map +0 -1
  314. package/dist/_chunks/segment-context-ZDnXDkbz.js +0 -34
  315. package/dist/_chunks/segment-context-ZDnXDkbz.js.map +0 -1
  316. package/dist/_chunks/use-query-states-DFvWd-EA.js.map +0 -1
  317. package/dist/_chunks/use-segment-params-ClyUNq4d.js +0 -128
  318. package/dist/_chunks/use-segment-params-ClyUNq4d.js.map +0 -1
  319. package/dist/_chunks/walkers-BhhwI9TD.js +0 -936
  320. package/dist/_chunks/walkers-BhhwI9TD.js.map +0 -1
  321. package/dist/search-params/registry.d.ts +0 -20
  322. package/dist/search-params/registry.d.ts.map +0 -1
  323. package/dist/segment-params/define.d.ts +0 -83
  324. package/dist/segment-params/define.d.ts.map +0 -1
  325. package/dist/segment-params/index.d.ts +0 -3
  326. package/dist/segment-params/index.d.ts.map +0 -1
  327. package/dist/segment-params/index.js +0 -70
  328. package/dist/segment-params/index.js.map +0 -1
  329. package/src/search-params/registry.ts +0 -31
  330. package/src/segment-params/define.ts +0 -226
  331. package/src/segment-params/index.ts +0 -9
@@ -1,13 +1,65 @@
1
+ import { t as RSC_CONTENT_TYPE } from "../_chunks/rsc-media-type-DRqE_lD_.js";
1
2
  import { a as IMMUTABLE_CACHE, i as writeHeadersFile, n as findUnhashedStaticFiles, r as runSharedBuildSteps, t as buildStaticDirectoryOutput } from "../_chunks/build-output-helper-C3DrfzZR.js";
2
3
  import { transformWithOxc } from "vite";
3
4
  import { basename, dirname, join, relative } from "node:path";
4
5
  import { cp, glob, readFile, writeFile } from "node:fs/promises";
5
6
  import { execFile } from "node:child_process";
6
7
  //#region src/server/compress.ts?raw
7
- var compress_default = "// Response compression for self-hosted deployments (dev server, Nitro preview).\n//\n// Uses CompressionStream (Web Platform API) for gzip. Brotli is intentionally\n// left to CDNs and reverse proxies — at streaming-friendly quality levels its\n// ratio advantage is marginal, and node:zlib's brotli transform buffers output\n// internally, breaking streaming. Cloudflare Workers auto-compress at the edge —\n// this module is only used on Node.js/Bun.\n//\n// See design/25-production-deployments.md.\n\n// ─── Constants ────────────────────────────────────────────────────────────\n\n/**\n * MIME types that benefit from compression.\n * text/* is handled via prefix matching; these are the specific\n * application/* and image/* types that are compressible.\n */\nexport const COMPRESSIBLE_TYPES = new Set([\n 'text/html',\n 'text/css',\n 'text/plain',\n 'text/xml',\n 'text/javascript',\n 'text/x-component',\n 'application/json',\n 'application/javascript',\n 'application/xml',\n 'application/xhtml+xml',\n 'application/rss+xml',\n 'application/atom+xml',\n 'image/svg+xml',\n]);\n\n/**\n * Status codes that should never be compressed (no body or special semantics).\n */\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\n// ─── Encoding Negotiation ─────────────────────────────────────────────────\n\n/**\n * Parse Accept-Encoding and return the best supported encoding.\n * Returns 'gzip' if the client accepts it, null otherwise.\n *\n * Brotli (br) is intentionally not handled at the application level.\n * At the streaming-friendly quality levels (0–4), brotli's compression\n * ratio advantage over gzip is marginal, and node:zlib's brotli transform\n * buffers output internally — turning smooth streaming responses into\n * large infrequent bursts. Brotli's real wins come from offline/static\n * compression at higher quality levels (5–11), which CDNs and reverse\n * proxies (Cloudflare, nginx, Caddy) apply on cached responses.\n *\n * See design/25-production-deployments.md.\n */\nexport function negotiateEncoding(acceptEncoding: string): 'gzip' | null {\n if (!acceptEncoding) return null;\n\n // Parse tokens with quality values from the Accept-Encoding header.\n // Per RFC 9110 §12.5.3, q=0 means \"not acceptable\" — the client explicitly\n // rejects that encoding. Tokens without a q-value default to q=1.\n // e.g. \"gzip;q=1.0, br;q=0\" → gzip is acceptable, br is rejected.\n const parts = acceptEncoding.split(',');\n for (const part of parts) {\n const [token, ...params] = part.split(';');\n const name = token.trim().toLowerCase();\n if (name !== 'gzip') continue;\n\n // Check for q=0 (explicitly disabled)\n let qValue = 1; // default quality is 1\n for (const param of params) {\n const trimmed = param.trim().toLowerCase();\n if (trimmed.startsWith('q=')) {\n qValue = parseFloat(trimmed.slice(2));\n if (Number.isNaN(qValue)) qValue = 1;\n break;\n }\n }\n\n if (qValue > 0) return 'gzip';\n }\n\n return null;\n}\n\n// ─── Compressibility Check ────────────────────────────────────────────────\n\n/**\n * Determine if a response should be compressed.\n *\n * Returns false for:\n * - Responses without a body (204, 304, null body)\n * - Already-encoded responses (Content-Encoding set)\n * - Non-compressible content types (images, binary)\n * - SSE streams (text/event-stream — must not be buffered)\n */\nexport function shouldCompress(response: Response): boolean {\n // No body to compress\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n\n // Already compressed\n if (response.headers.has('Content-Encoding')) return false;\n\n // Check content type\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n\n // Extract the MIME type (strip charset and other parameters)\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n\n // SSE must not be compressed — it relies on chunk-by-chunk delivery\n if (mimeType === 'text/event-stream') return false;\n\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\n// ─── Compression ──────────────────────────────────────────────────────────\n\n/**\n * Compress a Web Response if the client supports it and the content is compressible.\n *\n * Returns the original response unchanged if compression is not applicable.\n * Returns a new Response with the compressed body, Content-Encoding, and Vary headers.\n *\n * The body is piped through a compression stream — no buffering of the full response.\n * This preserves streaming behavior for HTML shell + deferred Suspense chunks.\n */\nexport function compressResponse(request: Request, response: Response): Response {\n // Check if response is compressible\n if (!shouldCompress(response)) return response;\n\n // Negotiate encoding with the client\n const acceptEncoding = request.headers.get('Accept-Encoding') ?? '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n\n // Compress the body stream with gzip via the Web Platform CompressionStream API.\n const compressedBody = compressWithGzip(response.body!);\n\n // Build new headers: copy originals, add compression headers, remove Content-Length\n // (compressed size is unknown until streaming completes).\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n\n // Append to Vary header (preserve existing Vary values)\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', `${existingVary}, Accept-Encoding`);\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n// ─── Gzip (node:zlib with Z_SYNC_FLUSH) ──────────────────────────────────\n//\n// Uses node:zlib's createGzip with Z_SYNC_FLUSH so each chunk is flushed\n// to the output immediately. The Web Platform CompressionStream API buffers\n// internally and does NOT flush per-chunk — this kills streaming because\n// the browser doesn't receive the HTML shell until the gzip stream closes\n// (i.e. after all Suspense boundaries resolve).\n//\n// Z_SYNC_FLUSH adds ~2–5% size overhead vs Z_NO_FLUSH but preserves\n// correct streaming behavior: the shell renders instantly, Suspense\n// fallbacks are visible immediately, and streamed content appears\n// progressively.\n\nimport { createGzip, constants } from 'node:zlib';\nimport { Readable, pipeline } from 'node:stream';\n\n/**\n * Compress a ReadableStream with gzip, flushing each chunk immediately.\n *\n * Uses node:zlib's createGzip with Z_SYNC_FLUSH to ensure each HTML chunk\n * (shell, Suspense resolution, RSC payload) is delivered to the browser\n * as soon as it's available — preserving streaming semantics.\n */\nfunction compressWithGzip(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n const nodeInput = Readable.fromWeb(body as import('stream/web').ReadableStream);\n\n // pipeline() instead of bare pipe(): pipe() does not forward source errors,\n // so an erroring body (streaming route handler, dropped upstream fetch)\n // would emit an unhandled 'error' event and crash the process. pipeline()\n // destroys gzip on source error — the returned web stream rejects — and\n // tears down nodeInput when the consumer cancels the web stream, which\n // cancels the source body via fromWeb. The error reaches the consumer\n // through the web stream; the callback only marks it handled at the Node\n // layer.\n pipeline(nodeInput, gzip, () => {});\n\n return Readable.toWeb(gzip) as ReadableStream<Uint8Array>;\n}\n";
8
+ var compress_default = "// Response compression for self-hosted deployments (dev server, Nitro preview).\n//\n// Uses CompressionStream (Web Platform API) for gzip. Brotli is intentionally\n// left to CDNs and reverse proxies — at streaming-friendly quality levels its\n// ratio advantage is marginal, and node:zlib's brotli transform buffers output\n// internally, breaking streaming. Cloudflare Workers auto-compress at the edge —\n// this module is only used on Node.js/Bun.\n//\n// See design/25-production-deployments.md.\n//\n// This module is also emitted standalone as `_compress.mjs` by\n// `adapters/compress-module.ts`, which strips types but does not bundle. Its\n// imports must therefore be interpolated there — a new import that is not\n// fails the build with an explanatory error rather than resolving to nothing\n// on the deployed server.\n\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.js';\n\n// ─── Constants ────────────────────────────────────────────────────────────\n\n/**\n * MIME types that benefit from compression.\n * text/* is handled via prefix matching; these are the specific\n * application/* and image/* types that are compressible.\n */\nexport const COMPRESSIBLE_TYPES = new Set([\n 'text/html',\n 'text/css',\n 'text/plain',\n 'text/xml',\n 'text/javascript',\n RSC_CONTENT_TYPE,\n 'application/json',\n 'application/javascript',\n 'application/xml',\n 'application/xhtml+xml',\n 'application/rss+xml',\n 'application/atom+xml',\n 'image/svg+xml',\n]);\n\n/**\n * Status codes that should never be compressed (no body or special semantics).\n */\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\n// ─── Encoding Negotiation ─────────────────────────────────────────────────\n\n/**\n * Parse Accept-Encoding and return the best supported encoding.\n * Returns 'gzip' if the client accepts it, null otherwise.\n *\n * Brotli (br) is intentionally not handled at the application level.\n * At the streaming-friendly quality levels (0–4), brotli's compression\n * ratio advantage over gzip is marginal, and node:zlib's brotli transform\n * buffers output internally — turning smooth streaming responses into\n * large infrequent bursts. Brotli's real wins come from offline/static\n * compression at higher quality levels (5–11), which CDNs and reverse\n * proxies (Cloudflare, nginx, Caddy) apply on cached responses.\n *\n * See design/25-production-deployments.md.\n */\nexport function negotiateEncoding(acceptEncoding: string): 'gzip' | null {\n if (!acceptEncoding) return null;\n\n // Parse tokens with quality values from the Accept-Encoding header.\n // Per RFC 9110 §12.5.3, q=0 means \"not acceptable\" — the client explicitly\n // rejects that encoding. Tokens without a q-value default to q=1.\n // e.g. \"gzip;q=1.0, br;q=0\" → gzip is acceptable, br is rejected.\n const parts = acceptEncoding.split(',');\n for (const part of parts) {\n const [token, ...params] = part.split(';');\n const name = token.trim().toLowerCase();\n if (name !== 'gzip') continue;\n\n // Check for q=0 (explicitly disabled)\n let qValue = 1; // default quality is 1\n for (const param of params) {\n const trimmed = param.trim().toLowerCase();\n if (trimmed.startsWith('q=')) {\n qValue = parseFloat(trimmed.slice(2));\n if (Number.isNaN(qValue)) qValue = 1;\n break;\n }\n }\n\n if (qValue > 0) return 'gzip';\n }\n\n return null;\n}\n\n// ─── Compressibility Check ────────────────────────────────────────────────\n\n/**\n * Determine if a response should be compressed.\n *\n * Returns false for:\n * - Responses without a body (204, 304, null body)\n * - Already-encoded responses (Content-Encoding set)\n * - Non-compressible content types (images, binary)\n * - SSE streams (text/event-stream — must not be buffered)\n */\nexport function shouldCompress(response: Response): boolean {\n // No body to compress\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n\n // Already compressed\n if (response.headers.has('Content-Encoding')) return false;\n\n // Check content type\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n\n // Extract the MIME type (strip charset and other parameters)\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n\n // SSE must not be compressed — it relies on chunk-by-chunk delivery\n if (mimeType === 'text/event-stream') return false;\n\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\n// ─── Compression ──────────────────────────────────────────────────────────\n\n/**\n * Compress a Web Response if the client supports it and the content is compressible.\n *\n * Returns the original response unchanged if compression is not applicable.\n * Returns a new Response with the compressed body, Content-Encoding, and Vary headers.\n *\n * The body is piped through a compression stream — no buffering of the full response.\n * This preserves streaming behavior for HTML shell + deferred Suspense chunks.\n */\nexport function compressResponse(request: Request, response: Response): Response {\n // Check if response is compressible\n if (!shouldCompress(response)) return response;\n\n // Negotiate encoding with the client\n const acceptEncoding = request.headers.get('Accept-Encoding') ?? '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n\n // Compress the body stream with gzip via the Web Platform CompressionStream API.\n const compressedBody = compressWithGzip(response.body!);\n\n // Build new headers: copy originals, add compression headers, remove Content-Length\n // (compressed size is unknown until streaming completes).\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n\n // Append to Vary header (preserve existing Vary values)\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', `${existingVary}, Accept-Encoding`);\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n// ─── Gzip (node:zlib with Z_SYNC_FLUSH) ──────────────────────────────────\n//\n// Uses node:zlib's createGzip with Z_SYNC_FLUSH so each chunk is flushed\n// to the output immediately. The Web Platform CompressionStream API buffers\n// internally and does NOT flush per-chunk — this kills streaming because\n// the browser doesn't receive the HTML shell until the gzip stream closes\n// (i.e. after all Suspense boundaries resolve).\n//\n// Z_SYNC_FLUSH adds ~2–5% size overhead vs Z_NO_FLUSH but preserves\n// correct streaming behavior: the shell renders instantly, Suspense\n// fallbacks are visible immediately, and streamed content appears\n// progressively.\n\nimport { createGzip, constants } from 'node:zlib';\nimport { Readable, pipeline } from 'node:stream';\n\n/**\n * Compress a ReadableStream with gzip, flushing each chunk immediately.\n *\n * Uses node:zlib's createGzip with Z_SYNC_FLUSH to ensure each HTML chunk\n * (shell, Suspense resolution, RSC payload) is delivered to the browser\n * as soon as it's available — preserving streaming semantics.\n */\nfunction compressWithGzip(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n const nodeInput = Readable.fromWeb(body as import('stream/web').ReadableStream);\n\n // pipeline() instead of bare pipe(): pipe() does not forward source errors,\n // so an erroring body (streaming route handler, dropped upstream fetch)\n // would emit an unhandled 'error' event and crash the process. pipeline()\n // destroys gzip on source error — the returned web stream rejects — and\n // tears down nodeInput when the consumer cancels the web stream, which\n // cancels the source body via fromWeb. The error reaches the consumer\n // through the web stream; the callback only marks it handled at the Node\n // layer.\n pipeline(nodeInput, gzip, () => {});\n\n return Readable.toWeb(gzip) as ReadableStream<Uint8Array>;\n}\n";
8
9
  //#endregion
9
10
  //#region src/adapters/compress-module.ts
10
11
  /**
12
+ * The one import `server/compress.ts` is allowed to carry, and its inlined
13
+ * form.
14
+ *
15
+ * The binding list is matched exactly rather than as `{…}`. A second binding
16
+ * added to that import would otherwise be erased along with the statement and
17
+ * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this
18
+ * whole module exists to make impossible. Matching exactly means such an
19
+ * import falls through to the rejection below instead.
20
+ */
21
+ var INLINED_IMPORTS = [{
22
+ pattern: /^import\s*\{\s*RSC_CONTENT_TYPE\s*,?\s*\}\s*from\s*["'][^"']*shared\/rsc-media-type\.js["'];?[ \t]*$/m,
23
+ replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`
24
+ }];
25
+ /**
26
+ * Every way a module specifier can reach the emitted file, minus Node
27
+ * builtins.
28
+ *
29
+ * `node:*` is exempt because it resolves on the deployed server exactly as it
30
+ * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,
31
+ * and self-hosted (Node/Bun) is the only place this file runs. Everything
32
+ * else — relative paths, bare packages — has no resolution target next to a
33
+ * lone `.mjs` in the build output.
34
+ *
35
+ * All three forms are listed rather than the one `server/compress.ts` happens
36
+ * to use, because a re-export or a lazy `await import()` fails in exactly the
37
+ * same place and is exactly as invisible until deploy.
38
+ */
39
+ var MODULE_SPECIFIERS = [
40
+ /^[ \t]*(?:import|export)\b[^\n]*\bfrom\s*["'](?!node:)[^"']+["']/m,
41
+ /^[ \t]*import\s*["'](?!node:)[^"']+["']/m,
42
+ /\bimport\s*\(\s*["'](?!node:)[^"']+["']/
43
+ ];
44
+ /**
45
+ * Replace the shared-module imports with their values and reject anything
46
+ * else that would leave a dangling specifier in `_compress.mjs`.
47
+ *
48
+ * Exported separately from `generateCompressModule` so both branches can be
49
+ * driven with fixtures: the source it normally compiles is fixed, so a test
50
+ * of the generator alone can only ever exercise whichever branch that source
51
+ * happens to take today.
52
+ *
53
+ * @internal Exported for testing.
54
+ */
55
+ function inlineCompressImports(code) {
56
+ let out = code;
57
+ for (const { pattern, replacement } of INLINED_IMPORTS) out = out.replace(pattern, replacement);
58
+ const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(out)).find(Boolean);
59
+ if (surviving) throw new Error(`[timber] server/compress.ts is emitted as a standalone _compress.mjs (type-stripped, not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\n Either inline the value in adapters/compress-module.ts (see INLINED_IMPORTS) or keep the dependency out of server/compress.ts.`);
60
+ return out;
61
+ }
62
+ /**
11
63
  * Compile server/compress.ts into a standalone ESM module.
12
64
  *
13
65
  * Uses Vite's OXC transform to strip TypeScript types from the
@@ -17,7 +69,7 @@ var compress_default = "// Response compression for self-hosted deployments (dev
17
69
  * @internal Exported for testing.
18
70
  */
19
71
  async function generateCompressModule() {
20
- return "// Generated by @timber-js/app — compiled from server/compress.ts.\n// Do not edit — this file is regenerated on each build.\n" + (await transformWithOxc(compress_default, "compress.ts", { lang: "ts" })).code;
72
+ return "// Generated by @timber-js/app — compiled from server/compress.ts.\n// Do not edit — this file is regenerated on each build.\n" + inlineCompressImports((await transformWithOxc(compress_default, "compress.ts", { lang: "ts" })).code);
21
73
  }
22
74
  //#endregion
23
75
  //#region src/adapters/nitro.ts
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile, cp, glob } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative, dirname, basename } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { adapterBase, IMMUTABLE_CACHE, generateHeadersFile } from './shared.js';\nimport {\n runSharedBuildSteps,\n buildStaticDirectoryOutput,\n findUnhashedStaticFiles,\n writeHeadersFile,\n} from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /**\n * Path to the server bundle directory relative to outputDir.\n * Nitro places the bundled server entry + _chunks/ here.\n * Most presets use `server`; Vercel uses `functions/__server.func`.\n */\n serverBundleDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (config.output === 'static' && config.staticPagesDir) {\n await buildStaticDirectoryOutput(config, buildDir, outDir, 'public');\n const publicDir = join(outDir, 'public');\n\n // Write _headers for cache control + extensionless Content-Type.\n // Netlify supports the _headers convention just like Cloudflare.\n await writeHeadersFile(publicDir, config, await findUnhashedStaticFiles(publicDir));\n\n // Platform-specific files for static deploy targets.\n const target = options.staticTarget ?? 'generic';\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(outDir, preset, options.nitroConfig);\n\n // Copy prebuilt flight payloads from the canonical build source\n // (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into\n // the Nitro output. The RSC entry resolves `../prebuilt/` relative to\n // its bundled chunk (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n const prebuiltSrc = join(buildDir, 'prebuilt');\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {\n recursive: true,\n }).catch((e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n return { serverDir };\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Send Response Module ───────────────────────────────────────────────────\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n\n/**\n * Resolve the destination path for prebuilt flight payloads in the Nitro\n * output directory. The RSC entry resolves `../prebuilt/` relative to its\n * bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must\n * live at `<serverBundleDir>/prebuilt/`.\n *\n * The serverBundleDir varies by preset — Nitro's Vercel preset uses\n * `functions/__server.func` while most others use `server`.\n *\n * @internal Exported for testing.\n */\nexport function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {\n const presetConfig = PRESET_CONFIGS[preset];\n return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');\n}\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) =>\n cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).catch(\n (e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n }\n )\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,eAAsB,yBAA0C;CAK9D,OACE,oIAEA,MAPmB,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAKQ;AAEX;;;AC0BA,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,m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QACd,QAAQ;EACf,CAAC;EACD,MAAM,QAAQ,KAAK,QAAQ,MAAM;EACjC,MAAM,QAAQ,KAAK,QAAQ,MAAM;CACnC,CAAC;AACH;;;;;;;;;;;AAcA,SAAgB,6BAAqC;CACnD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDT;;;;;AAQA,SAAgB,gBAAgB,QAAmC;CACjE,OAAO,eAAe;AACxB;;;;;;;;;;;;AAaA,SAAgB,0BAA0B,QAAgB,QAA6B;CACrF,MAAM,eAAe,eAAe;CACpC,OAAO,KAAK,QAAQ,aAAa,WAAW,aAAa,iBAAiB,UAAU;AACtF;;;;;;;;;;;AAYA,eAAsB,+BACpB,cACA,aACA,cACe;CACf,MAAM,WAAqB,CAAC;CAC5B,IAAI;EACF,WAAW,MAAM,SAAS,KAAK,aAAa,EAAE,KAAK,aAAa,CAAC,GAC/D,IAAI,CAAC,MAAM,SAAS,YAAY,GAC9B,SAAS,KAAK,KAAK,cAAc,KAAK,CAAC;CAG7C,QAAQ;EACN;CACF;CACA,MAAM,QAAQ,IACZ,SAAS,KAAK,QACZ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,OACzD,MAA6B;EAC5B,IAAI,EAAE,SAAS,UAAU,MAAM;CACjC,CACF,CACF,CACF;AACF"}
1
+ {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n//\n// The transform strips types; it does NOT bundle. The emitted file sits\n// alone in the build output, so any import specifier that survives into it\n// is a module resolution failure at runtime on the deployed server. Shared\n// constants are therefore interpolated here — the same treatment the\n// Cloudflare worker template gives `RSC_KEY_HEADERS` — and anything else\n// that reaches the output as an import is rejected with a build error\n// rather than shipped.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.js';\n\n/**\n * The one import `server/compress.ts` is allowed to carry, and its inlined\n * form.\n *\n * The binding list is matched exactly rather than as `{…}`. A second binding\n * added to that import would otherwise be erased along with the statement and\n * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this\n * whole module exists to make impossible. Matching exactly means such an\n * import falls through to the rejection below instead.\n */\nconst INLINED_IMPORTS: ReadonlyArray<{ pattern: RegExp; replacement: string }> = [\n {\n pattern:\n /^import\\s*\\{\\s*RSC_CONTENT_TYPE\\s*,?\\s*\\}\\s*from\\s*[\"'][^\"']*shared\\/rsc-media-type\\.js[\"'];?[ \\t]*$/m,\n replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`,\n },\n];\n\n/**\n * Every way a module specifier can reach the emitted file, minus Node\n * builtins.\n *\n * `node:*` is exempt because it resolves on the deployed server exactly as it\n * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,\n * and self-hosted (Node/Bun) is the only place this file runs. Everything\n * else — relative paths, bare packages — has no resolution target next to a\n * lone `.mjs` in the build output.\n *\n * All three forms are listed rather than the one `server/compress.ts` happens\n * to use, because a re-export or a lazy `await import()` fails in exactly the\n * same place and is exactly as invisible until deploy.\n */\nconst MODULE_SPECIFIERS: readonly RegExp[] = [\n // import … from '…' / export … from '…'\n /^[ \\t]*(?:import|export)\\b[^\\n]*\\bfrom\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import '…' (side effect only)\n /^[ \\t]*import\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import('…') (dynamic, literal specifier)\n /\\bimport\\s*\\(\\s*[\"'](?!node:)[^\"']+[\"']/,\n];\n\n/**\n * Replace the shared-module imports with their values and reject anything\n * else that would leave a dangling specifier in `_compress.mjs`.\n *\n * Exported separately from `generateCompressModule` so both branches can be\n * driven with fixtures: the source it normally compiles is fixed, so a test\n * of the generator alone can only ever exercise whichever branch that source\n * happens to take today.\n *\n * @internal Exported for testing.\n */\nexport function inlineCompressImports(code: string): string {\n let out = code;\n for (const { pattern, replacement } of INLINED_IMPORTS) {\n out = out.replace(pattern, replacement);\n }\n const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(out)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] server/compress.ts is emitted as a standalone _compress.mjs (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in adapters/compress-module.ts (see INLINED_IMPORTS) or ` +\n `keep the dependency out of server/compress.ts.`\n );\n }\n return out;\n}\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n inlineCompressImports(result.code)\n );\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile, cp, glob } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative, dirname, basename } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { adapterBase, IMMUTABLE_CACHE, generateHeadersFile } from './shared.js';\nimport {\n runSharedBuildSteps,\n buildStaticDirectoryOutput,\n findUnhashedStaticFiles,\n writeHeadersFile,\n} from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /**\n * Path to the server bundle directory relative to outputDir.\n * Nitro places the bundled server entry + _chunks/ here.\n * Most presets use `server`; Vercel uses `functions/__server.func`.\n */\n serverBundleDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (config.output === 'static' && config.staticPagesDir) {\n await buildStaticDirectoryOutput(config, buildDir, outDir, 'public');\n const publicDir = join(outDir, 'public');\n\n // Write _headers for cache control + extensionless Content-Type.\n // Netlify supports the _headers convention just like Cloudflare.\n await writeHeadersFile(publicDir, config, await findUnhashedStaticFiles(publicDir));\n\n // Platform-specific files for static deploy targets.\n const target = options.staticTarget ?? 'generic';\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(outDir, preset, options.nitroConfig);\n\n // Copy prebuilt flight payloads from the canonical build source\n // (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into\n // the Nitro output. The RSC entry resolves `../prebuilt/` relative to\n // its bundled chunk (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n const prebuiltSrc = join(buildDir, 'prebuilt');\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {\n recursive: true,\n }).catch((e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n return { serverDir };\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Send Response Module ───────────────────────────────────────────────────\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n\n/**\n * Resolve the destination path for prebuilt flight payloads in the Nitro\n * output directory. The RSC entry resolves `../prebuilt/` relative to its\n * bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must\n * live at `<serverBundleDir>/prebuilt/`.\n *\n * The serverBundleDir varies by preset — Nitro's Vercel preset uses\n * `functions/__server.func` while most others use `server`.\n *\n * @internal Exported for testing.\n */\nexport function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {\n const presetConfig = PRESET_CONFIGS[preset];\n return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');\n}\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) =>\n cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).catch(\n (e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n }\n )\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,kBAA2E,CAC/E;CACE,SACE;CACF,aAAa,4BAA4B,KAAK,UAAU,gBAAgB,EAAE;AAC5E,CACF;;;;;;;;;;;;;;;AAgBA,IAAM,oBAAuC;CAE3C;CAEA;CAEA;AACF;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,MAAsB;CAC1D,IAAI,MAAM;CACV,KAAK,MAAM,EAAE,SAAS,iBAAiB,iBACrC,MAAM,IAAI,QAAQ,SAAS,WAAW;CAExC,MAAM,YAAY,kBAAkB,KAAK,YAAY,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO;CACpF,IAAI,WACF,MAAM,IAAI,MACR,sJACmE,UAAU,EAAE,CAAC,KAAK,EAAE,mIAGzF;CAEF,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,yBAA0C;CAK9D,OACE,mIAEA,uBAAsB,MAPH,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAK8B,IAAI;AAErC;;;ACpDA,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,GAAG,EAAE,EAAE;CAC5D;CAC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;AACH;;;;;;;;;;;AAcA,SAAgB,6BAAqC;CACnD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDT;;;;;AAQA,SAAgB,gBAAgB,QAAmC;CACjE,OAAO,eAAe;AACxB;;;;;;;;;;;;AAaA,SAAgB,0BAA0B,QAAgB,QAA6B;CACrF,MAAM,eAAe,eAAe;CACpC,OAAO,KAAK,QAAQ,aAAa,WAAW,aAAa,iBAAiB,UAAU;AACtF;;;;;;;;;;;AAYA,eAAsB,+BACpB,cACA,aACA,cACe;CACf,MAAM,WAAqB,CAAC;CAC5B,IAAI;EACF,WAAW,MAAM,SAAS,KAAK,aAAa,EAAE,KAAK,aAAa,CAAC,GAC/D,IAAI,CAAC,MAAM,SAAS,YAAY,GAC9B,SAAS,KAAK,KAAK,cAAc,KAAK,CAAC;CAG7C,QAAQ;EACN;CACF;CACA,MAAM,QAAQ,IACZ,SAAS,KAAK,QACZ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,OACzD,MAA6B;EAC5B,IAAI,EAAE,SAAS,UAAU,MAAM;CACjC,CACF,CACF,CACF;AACF"}
@@ -1,3 +1,3 @@
1
- import { _ as setDefaultSingleflightTimeout, f as MemoryCacheHandler, g as setCacheHandler, h as getCacheHandler, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-Cd0VZ_Pd.js";
1
+ import { _ as setDefaultSingleflightTimeout, f as MemoryCacheHandler, g as setCacheHandler, h as getCacheHandler, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-DjNrIWRR.js";
2
2
  import { t as estimateByteSize } from "../_chunks/sizeof-lXffQ1Vr.js";
3
3
  export { MemoryCacheHandler, RedisCacheHandler, TagAwareCacheHandler, cache, estimateByteSize, getCacheHandler, setCacheHandler, setDefaultSingleflightTimeout };
@@ -0,0 +1,30 @@
1
+ //#region src/cdn/cloudflare-purge.ts
2
+ var CloudflarePurge = class {
3
+ zoneId;
4
+ apiToken;
5
+ _fetch;
6
+ constructor(opts) {
7
+ this.zoneId = opts.zoneId;
8
+ this.apiToken = opts.apiToken;
9
+ this._fetch = opts.fetch ?? globalThis.fetch;
10
+ }
11
+ async purgeTags(tags) {
12
+ if (tags.length === 0) return;
13
+ const res = await this._fetch(`https://api.cloudflare.com/client/v4/zones/${this.zoneId}/purge_cache`, {
14
+ method: "POST",
15
+ headers: {
16
+ "Authorization": `Bearer ${this.apiToken}`,
17
+ "Content-Type": "application/json"
18
+ },
19
+ body: JSON.stringify({ tags })
20
+ });
21
+ if (!res.ok) {
22
+ const body = await res.text();
23
+ throw new Error(`Cloudflare purge failed (${res.status}): ${body}`);
24
+ }
25
+ }
26
+ };
27
+ //#endregion
28
+ export { CloudflarePurge };
29
+
30
+ //# sourceMappingURL=cloudflare-purge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-purge.js","names":[],"sources":["../../src/cdn/cloudflare-purge.ts"],"sourcesContent":["/**\n * Cloudflare CDN purge handler — purges by cache tag via the Cloudflare API.\n *\n * Requires Cloudflare Enterprise for tag-based purging.\n * See https://developers.cloudflare.com/cache/how-to/purge-cache/purge-by-tags/\n */\n\nimport type { CdnPurgeHandler } from './purge-store';\n\nexport interface CloudflarePurgeOptions {\n /** Cloudflare zone ID. */\n zoneId: string;\n /** API token with Cache Purge permission. */\n apiToken: string;\n /** Override fetch for testing. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport class CloudflarePurge implements CdnPurgeHandler {\n private readonly zoneId: string;\n private readonly apiToken: string;\n private readonly _fetch: typeof globalThis.fetch;\n\n constructor(opts: CloudflarePurgeOptions) {\n this.zoneId = opts.zoneId;\n this.apiToken = opts.apiToken;\n this._fetch = opts.fetch ?? globalThis.fetch;\n }\n\n async purgeTags(tags: string[]): Promise<void> {\n if (tags.length === 0) return;\n\n const res = await this._fetch(\n `https://api.cloudflare.com/client/v4/zones/${this.zoneId}/purge_cache`,\n {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ tags }),\n }\n );\n\n if (!res.ok) {\n const body = await res.text();\n throw new Error(`Cloudflare purge failed (${res.status}): ${body}`);\n }\n }\n}\n"],"mappings":";AAkBA,IAAa,kBAAb,MAAwD;CACtD;CACA;CACA;CAEA,YAAY,MAA8B;EACxC,KAAK,SAAS,KAAK;EACnB,KAAK,WAAW,KAAK;EACrB,KAAK,SAAS,KAAK,SAAS,WAAW;CACzC;CAEA,MAAM,UAAU,MAA+B;EAC7C,IAAI,KAAK,WAAW,GAAG;EAEvB,MAAM,MAAM,MAAM,KAAK,OACrB,8CAA8C,KAAK,OAAO,eAC1D;GACE,QAAQ;GACR,SAAS;IACP,iBAAiB,UAAU,KAAK;IAChC,gBAAgB;GAClB;GACA,MAAM,KAAK,UAAU,EAAE,KAAK,CAAC;EAC/B,CACF;EAEA,IAAI,CAAC,IAAI,IAAI;GACX,MAAM,OAAO,MAAM,IAAI,KAAK;GAC5B,MAAM,IAAI,MAAM,4BAA4B,IAAI,OAAO,KAAK,MAAM;EACpE;CACF;AACF"}
@@ -0,0 +1,33 @@
1
+ //#region src/cdn/fastly-purge.ts
2
+ var FastlyPurge = class {
3
+ serviceId;
4
+ apiToken;
5
+ softPurge;
6
+ _fetch;
7
+ constructor(opts) {
8
+ this.serviceId = opts.serviceId;
9
+ this.apiToken = opts.apiToken;
10
+ this.softPurge = opts.softPurge ?? false;
11
+ this._fetch = opts.fetch ?? globalThis.fetch;
12
+ }
13
+ async purgeTags(tags) {
14
+ if (tags.length === 0) return;
15
+ const failures = (await Promise.allSettled(tags.map((tag) => this._fetch(`https://api.fastly.com/service/${this.serviceId}/purge/${encodeURIComponent(tag)}`, {
16
+ method: "POST",
17
+ headers: {
18
+ "Fastly-Key": this.apiToken,
19
+ ...this.softPurge ? { "Fastly-Soft-Purge": "1" } : {}
20
+ }
21
+ }).then(async (res) => {
22
+ if (!res.ok) {
23
+ const body = await res.text();
24
+ throw new Error(`Fastly purge failed for tag "${tag}" (${res.status}): ${body}`);
25
+ }
26
+ })))).filter((r) => r.status === "rejected");
27
+ if (failures.length > 0) throw new Error(`Fastly purge failed for ${failures.length}/${tags.length} tags: ${failures.map((f) => f.reason?.message).join("; ")}`);
28
+ }
29
+ };
30
+ //#endregion
31
+ export { FastlyPurge };
32
+
33
+ //# sourceMappingURL=fastly-purge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fastly-purge.js","names":[],"sources":["../../src/cdn/fastly-purge.ts"],"sourcesContent":["/**\n * Fastly CDN purge handler — purges by surrogate key via the Fastly API.\n *\n * See https://www.fastly.com/documentation/reference/api/purging/\n */\n\nimport type { CdnPurgeHandler } from './purge-store';\n\nexport interface FastlyPurgeOptions {\n /** Fastly service ID. */\n serviceId: string;\n /** Fastly API token with purge permission. */\n apiToken: string;\n /** Use soft purge (marks as stale instead of immediate delete). Default: false. */\n softPurge?: boolean;\n /** Override fetch for testing. */\n fetch?: typeof globalThis.fetch;\n}\n\nexport class FastlyPurge implements CdnPurgeHandler {\n private readonly serviceId: string;\n private readonly apiToken: string;\n private readonly softPurge: boolean;\n private readonly _fetch: typeof globalThis.fetch;\n\n constructor(opts: FastlyPurgeOptions) {\n this.serviceId = opts.serviceId;\n this.apiToken = opts.apiToken;\n this.softPurge = opts.softPurge ?? false;\n this._fetch = opts.fetch ?? globalThis.fetch;\n }\n\n async purgeTags(tags: string[]): Promise<void> {\n if (tags.length === 0) return;\n\n const results = await Promise.allSettled(\n tags.map((tag) =>\n this._fetch(\n `https://api.fastly.com/service/${this.serviceId}/purge/${encodeURIComponent(tag)}`,\n {\n method: 'POST',\n headers: {\n 'Fastly-Key': this.apiToken,\n ...(this.softPurge ? { 'Fastly-Soft-Purge': '1' } : {}),\n },\n }\n ).then(async (res) => {\n if (!res.ok) {\n const body = await res.text();\n throw new Error(`Fastly purge failed for tag \"${tag}\" (${res.status}): ${body}`);\n }\n })\n )\n );\n\n const failures = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');\n if (failures.length > 0) {\n throw new Error(\n `Fastly purge failed for ${failures.length}/${tags.length} tags: ${failures.map((f) => f.reason?.message).join('; ')}`\n );\n }\n }\n}\n"],"mappings":";AAmBA,IAAa,cAAb,MAAoD;CAClD;CACA;CACA;CACA;CAEA,YAAY,MAA0B;EACpC,KAAK,YAAY,KAAK;EACtB,KAAK,WAAW,KAAK;EACrB,KAAK,YAAY,KAAK,aAAa;EACnC,KAAK,SAAS,KAAK,SAAS,WAAW;CACzC;CAEA,MAAM,UAAU,MAA+B;EAC7C,IAAI,KAAK,WAAW,GAAG;EAsBvB,MAAM,YAAW,MApBK,QAAQ,WAC5B,KAAK,KAAK,QACR,KAAK,OACH,kCAAkC,KAAK,UAAU,SAAS,mBAAmB,GAAG,KAChF;GACE,QAAQ;GACR,SAAS;IACP,cAAc,KAAK;IACnB,GAAI,KAAK,YAAY,EAAE,qBAAqB,IAAI,IAAI,CAAC;GACvD;EACF,CACF,CAAC,CAAC,KAAK,OAAO,QAAQ;GACpB,IAAI,CAAC,IAAI,IAAI;IACX,MAAM,OAAO,MAAM,IAAI,KAAK;IAC5B,MAAM,IAAI,MAAM,gCAAgC,IAAI,KAAK,IAAI,OAAO,KAAK,MAAM;GACjF;EACF,CAAC,CACH,CACF,EAAA,CAEyB,QAAQ,MAAkC,EAAE,WAAW,UAAU;EAC1F,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,MACR,2BAA2B,SAAS,OAAO,GAAG,KAAK,OAAO,SAAS,SAAS,KAAK,MAAM,EAAE,QAAQ,OAAO,CAAC,CAAC,KAAK,IAAI,GACrH;CAEJ;AACF"}
@@ -0,0 +1,94 @@
1
+ import { n as setCdnPurgeHandler, t as getCdnPurgeHandler } from "../_chunks/purge-store-Byr8XOjU.js";
2
+ //#region src/cdn/headers.ts
3
+ /**
4
+ * Build a `Cache-Control` header value.
5
+ *
6
+ * ```ts
7
+ * ctx.headers.set('Cache-Control', cacheControl({
8
+ * public: true,
9
+ * maxAge: 300,
10
+ * staleWhileRevalidate: 60,
11
+ * }));
12
+ * ```
13
+ */
14
+ function cacheControl(opts) {
15
+ if (opts.public && opts.private) throw new Error("cacheControl: public and private are mutually exclusive");
16
+ if (opts.noStore && opts.maxAge !== void 0) throw new Error("cacheControl: noStore makes maxAge meaningless — remove one");
17
+ const parts = [];
18
+ parts.push(opts.public ? "public" : "private");
19
+ if (opts.noStore) parts.push("no-store");
20
+ if (opts.noCache) parts.push("no-cache");
21
+ if (opts.maxAge !== void 0) parts.push(`max-age=${opts.maxAge}`);
22
+ if (opts.sMaxAge !== void 0) parts.push(`s-maxage=${opts.sMaxAge}`);
23
+ if (opts.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${opts.staleWhileRevalidate}`);
24
+ if (opts.staleIfError !== void 0) parts.push(`stale-if-error=${opts.staleIfError}`);
25
+ if (opts.mustRevalidate) parts.push("must-revalidate");
26
+ if (opts.immutable) parts.push("immutable");
27
+ return parts.join(", ");
28
+ }
29
+ /**
30
+ * Build a `Surrogate-Control` header value (Fastly, Akamai, Varnish).
31
+ *
32
+ * ```ts
33
+ * ctx.headers.set('Surrogate-Control', surrogateControl({ maxAge: 3600 }));
34
+ * ```
35
+ */
36
+ function surrogateControl(opts) {
37
+ const parts = [];
38
+ if (opts.noStore) parts.push("no-store");
39
+ if (opts.maxAge !== void 0) parts.push(`max-age=${opts.maxAge}`);
40
+ if (opts.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${opts.staleWhileRevalidate}`);
41
+ if (opts.staleIfError !== void 0) parts.push(`stale-if-error=${opts.staleIfError}`);
42
+ return parts.join(", ");
43
+ }
44
+ /**
45
+ * Build a `CDN-Cache-Control` header value (Cloudflare).
46
+ * Same directive syntax as Surrogate-Control but recognized by Cloudflare.
47
+ *
48
+ * ```ts
49
+ * ctx.headers.set('CDN-Cache-Control', cdnCacheControl({ maxAge: 3600 }));
50
+ * ```
51
+ */
52
+ function cdnCacheControl(opts) {
53
+ return surrogateControl(opts);
54
+ }
55
+ /**
56
+ * Build a `Surrogate-Key` header value — space-separated tags for CDN
57
+ * tag-based purging (Fastly, Cloudflare Enterprise, Akamai).
58
+ *
59
+ * Tags are deduplicated. Tags must not contain spaces or double quotes
60
+ * (these are separators/delimiters in the header format).
61
+ *
62
+ * ```ts
63
+ * ctx.headers.set('Surrogate-Key', surrogateKey(['products', `product:${id}`]));
64
+ * ```
65
+ */
66
+ function surrogateKey(tags) {
67
+ for (const tag of tags) if (tag.includes(" ") || tag.includes("\"")) throw new Error(`surrogateKey: tag "${tag}" must not contain spaces or double quotes`);
68
+ return [...new Set(tags)].join(" ");
69
+ }
70
+ /**
71
+ * Build a `Cache-Tag` header value — comma-separated tags for Cloudflare
72
+ * Workers Cache tag-based purging. Available on ALL Cloudflare plans.
73
+ *
74
+ * Tags are deduplicated. Tags must not contain commas (the delimiter).
75
+ * Maximum tag length is 1024 characters per Cloudflare's limits.
76
+ *
77
+ * Use this instead of `surrogateKey()` when using Cloudflare Workers Cache
78
+ * (ctx.cache.purge). Workers Cache reads `Cache-Tag`, not `Surrogate-Key`.
79
+ *
80
+ * ```ts
81
+ * ctx.headers.set('Cache-Tag', cacheTag(['products', `product:${id}`]));
82
+ * ```
83
+ */
84
+ function cacheTag(tags) {
85
+ for (const tag of tags) {
86
+ if (tag.includes(",")) throw new Error(`cacheTag: tag "${tag}" must not contain commas`);
87
+ if (tag.length > 1024) throw new Error(`cacheTag: tag "${tag}" exceeds 1024-character limit`);
88
+ }
89
+ return [...new Set(tags)].join(",");
90
+ }
91
+ //#endregion
92
+ export { cacheControl, cacheTag, cdnCacheControl, getCdnPurgeHandler, setCdnPurgeHandler, surrogateControl, surrogateKey };
93
+
94
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cdn/headers.ts"],"sourcesContent":["/**\n * CDN header helpers — pure functions that build Cache-Control,\n * CDN-Cache-Control, Surrogate-Control, and Surrogate-Key header values.\n *\n * These are developer-elected utilities for wiring CDN caching in\n * proxy.ts / middleware.ts. The framework never sets these automatically.\n * See design/25-production-deployments.md §Layer 2.\n */\n\nexport interface CacheControlOptions {\n /** Mark the response as publicly cacheable (CDN, shared caches). */\n public?: boolean;\n /** Mark the response as private (browser cache only, not CDN). */\n private?: boolean;\n /** Max freshness in seconds for the browser/client. */\n maxAge?: number;\n /** Max freshness in seconds for shared caches (CDN, proxy). Overrides maxAge for CDNs. */\n sMaxAge?: number;\n /** Serve stale while revalidating in the background (seconds). */\n staleWhileRevalidate?: number;\n /** Serve stale on upstream error (seconds). */\n staleIfError?: number;\n /** Response must not be stored by any cache. */\n noStore?: boolean;\n /** Caches must revalidate before using a stored response. */\n noCache?: boolean;\n /** Caches must revalidate once stale — no serving stale without checking origin. */\n mustRevalidate?: boolean;\n /** Response will not change — allows aggressive caching. Pair with hashed URLs. */\n immutable?: boolean;\n}\n\n/**\n * Build a `Cache-Control` header value.\n *\n * ```ts\n * ctx.headers.set('Cache-Control', cacheControl({\n * public: true,\n * maxAge: 300,\n * staleWhileRevalidate: 60,\n * }));\n * ```\n */\nexport function cacheControl(opts: CacheControlOptions): string {\n if (opts.public && opts.private) {\n throw new Error('cacheControl: public and private are mutually exclusive');\n }\n if (opts.noStore && opts.maxAge !== undefined) {\n throw new Error('cacheControl: noStore makes maxAge meaningless — remove one');\n }\n\n const parts: string[] = [];\n\n parts.push(opts.public ? 'public' : 'private');\n\n if (opts.noStore) parts.push('no-store');\n if (opts.noCache) parts.push('no-cache');\n if (opts.maxAge !== undefined) parts.push(`max-age=${opts.maxAge}`);\n if (opts.sMaxAge !== undefined) parts.push(`s-maxage=${opts.sMaxAge}`);\n if (opts.staleWhileRevalidate !== undefined)\n parts.push(`stale-while-revalidate=${opts.staleWhileRevalidate}`);\n if (opts.staleIfError !== undefined) parts.push(`stale-if-error=${opts.staleIfError}`);\n if (opts.mustRevalidate) parts.push('must-revalidate');\n if (opts.immutable) parts.push('immutable');\n\n return parts.join(', ');\n}\n\nexport interface SurrogateControlOptions {\n /** Max freshness in seconds for the surrogate (CDN). */\n maxAge?: number;\n /** Do not store in surrogate cache. */\n noStore?: boolean;\n /** Serve stale while revalidating (seconds). */\n staleWhileRevalidate?: number;\n /** Serve stale on error (seconds). */\n staleIfError?: number;\n}\n\n/**\n * Build a `Surrogate-Control` header value (Fastly, Akamai, Varnish).\n *\n * ```ts\n * ctx.headers.set('Surrogate-Control', surrogateControl({ maxAge: 3600 }));\n * ```\n */\nexport function surrogateControl(opts: SurrogateControlOptions): string {\n const parts: string[] = [];\n if (opts.noStore) parts.push('no-store');\n if (opts.maxAge !== undefined) parts.push(`max-age=${opts.maxAge}`);\n if (opts.staleWhileRevalidate !== undefined)\n parts.push(`stale-while-revalidate=${opts.staleWhileRevalidate}`);\n if (opts.staleIfError !== undefined) parts.push(`stale-if-error=${opts.staleIfError}`);\n return parts.join(', ');\n}\n\n/**\n * Build a `CDN-Cache-Control` header value (Cloudflare).\n * Same directive syntax as Surrogate-Control but recognized by Cloudflare.\n *\n * ```ts\n * ctx.headers.set('CDN-Cache-Control', cdnCacheControl({ maxAge: 3600 }));\n * ```\n */\nexport function cdnCacheControl(opts: SurrogateControlOptions): string {\n return surrogateControl(opts);\n}\n\n/**\n * Build a `Surrogate-Key` header value — space-separated tags for CDN\n * tag-based purging (Fastly, Cloudflare Enterprise, Akamai).\n *\n * Tags are deduplicated. Tags must not contain spaces or double quotes\n * (these are separators/delimiters in the header format).\n *\n * ```ts\n * ctx.headers.set('Surrogate-Key', surrogateKey(['products', `product:${id}`]));\n * ```\n */\nexport function surrogateKey(tags: string[]): string {\n for (const tag of tags) {\n if (tag.includes(' ') || tag.includes('\"')) {\n throw new Error(`surrogateKey: tag \"${tag}\" must not contain spaces or double quotes`);\n }\n }\n return [...new Set(tags)].join(' ');\n}\n\n/**\n * Build a `Cache-Tag` header value — comma-separated tags for Cloudflare\n * Workers Cache tag-based purging. Available on ALL Cloudflare plans.\n *\n * Tags are deduplicated. Tags must not contain commas (the delimiter).\n * Maximum tag length is 1024 characters per Cloudflare's limits.\n *\n * Use this instead of `surrogateKey()` when using Cloudflare Workers Cache\n * (ctx.cache.purge). Workers Cache reads `Cache-Tag`, not `Surrogate-Key`.\n *\n * ```ts\n * ctx.headers.set('Cache-Tag', cacheTag(['products', `product:${id}`]));\n * ```\n */\nexport function cacheTag(tags: string[]): string {\n for (const tag of tags) {\n if (tag.includes(',')) {\n throw new Error(`cacheTag: tag \"${tag}\" must not contain commas`);\n }\n if (tag.length > 1024) {\n throw new Error(`cacheTag: tag \"${tag}\" exceeds 1024-character limit`);\n }\n }\n return [...new Set(tags)].join(',');\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAmC;CAC9D,IAAI,KAAK,UAAU,KAAK,SACtB,MAAM,IAAI,MAAM,yDAAyD;CAE3E,IAAI,KAAK,WAAW,KAAK,WAAW,KAAA,GAClC,MAAM,IAAI,MAAM,6DAA6D;CAG/E,MAAM,QAAkB,CAAC;CAEzB,MAAM,KAAK,KAAK,SAAS,WAAW,SAAS;CAE7C,IAAI,KAAK,SAAS,MAAM,KAAK,UAAU;CACvC,IAAI,KAAK,SAAS,MAAM,KAAK,UAAU;CACvC,IAAI,KAAK,WAAW,KAAA,GAAW,MAAM,KAAK,WAAW,KAAK,QAAQ;CAClE,IAAI,KAAK,YAAY,KAAA,GAAW,MAAM,KAAK,YAAY,KAAK,SAAS;CACrE,IAAI,KAAK,yBAAyB,KAAA,GAChC,MAAM,KAAK,0BAA0B,KAAK,sBAAsB;CAClE,IAAI,KAAK,iBAAiB,KAAA,GAAW,MAAM,KAAK,kBAAkB,KAAK,cAAc;CACrF,IAAI,KAAK,gBAAgB,MAAM,KAAK,iBAAiB;CACrD,IAAI,KAAK,WAAW,MAAM,KAAK,WAAW;CAE1C,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;;AAoBA,SAAgB,iBAAiB,MAAuC;CACtE,MAAM,QAAkB,CAAC;CACzB,IAAI,KAAK,SAAS,MAAM,KAAK,UAAU;CACvC,IAAI,KAAK,WAAW,KAAA,GAAW,MAAM,KAAK,WAAW,KAAK,QAAQ;CAClE,IAAI,KAAK,yBAAyB,KAAA,GAChC,MAAM,KAAK,0BAA0B,KAAK,sBAAsB;CAClE,IAAI,KAAK,iBAAiB,KAAA,GAAW,MAAM,KAAK,kBAAkB,KAAK,cAAc;CACrF,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;;;AAUA,SAAgB,gBAAgB,MAAuC;CACrE,OAAO,iBAAiB,IAAI;AAC9B;;;;;;;;;;;;AAaA,SAAgB,aAAa,MAAwB;CACnD,KAAK,MAAM,OAAO,MAChB,IAAI,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,IAAG,GACvC,MAAM,IAAI,MAAM,sBAAsB,IAAI,2CAA2C;CAGzF,OAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AACpC;;;;;;;;;;;;;;;AAgBA,SAAgB,SAAS,MAAwB;CAC/C,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,IAAI,SAAS,GAAG,GAClB,MAAM,IAAI,MAAM,kBAAkB,IAAI,0BAA0B;EAElE,IAAI,IAAI,SAAS,MACf,MAAM,IAAI,MAAM,kBAAkB,IAAI,+BAA+B;CAEzE;CACA,OAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AACpC"}
@@ -0,0 +1,35 @@
1
+ import { c as workersCachePurgeAls } from "../_chunks/als-registry-C6kcfprT.js";
2
+ //#region src/server/workers-cache-bridge.ts
3
+ /**
4
+ * Per-request Workers Cache purge bridge — ALS bridge for Cloudflare adapter.
5
+ *
6
+ * The generated _worker.js wraps each request with `runWithWorkersCachePurge`,
7
+ * binding `ctx.cache` from the Cloudflare ExecutionContext. The
8
+ * `WorkersCachePurge` CDN purge handler reads from this ALS to call
9
+ * `ctx.cache.purge({ tags })` without needing an API token.
10
+ *
11
+ * Design doc: design/06-caching.md, design/25-production-deployments.md
12
+ */
13
+ /**
14
+ * Get the current request's Workers Cache context, if available.
15
+ *
16
+ * Returns undefined outside a Cloudflare Workers request context
17
+ * or on platforms without Workers Cache support.
18
+ */
19
+ function getWorkersCachePurgeCtx() {
20
+ return workersCachePurgeAls.getStore();
21
+ }
22
+ //#endregion
23
+ //#region src/cdn/workers-cache-purge.ts
24
+ var WorkersCachePurge = class {
25
+ async purgeTags(tags) {
26
+ if (tags.length === 0) return;
27
+ const ctx = getWorkersCachePurgeCtx();
28
+ if (!ctx) throw new Error("WorkersCachePurge: no Workers Cache context available. This handler can only be used within a Cloudflare Workers request context.");
29
+ await ctx.purge({ tags });
30
+ }
31
+ };
32
+ //#endregion
33
+ export { WorkersCachePurge };
34
+
35
+ //# sourceMappingURL=workers-cache-purge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workers-cache-purge.js","names":[],"sources":["../../src/server/workers-cache-bridge.ts","../../src/cdn/workers-cache-purge.ts"],"sourcesContent":["/**\n * Per-request Workers Cache purge bridge — ALS bridge for Cloudflare adapter.\n *\n * The generated _worker.js wraps each request with `runWithWorkersCachePurge`,\n * binding `ctx.cache` from the Cloudflare ExecutionContext. The\n * `WorkersCachePurge` CDN purge handler reads from this ALS to call\n * `ctx.cache.purge({ tags })` without needing an API token.\n *\n * Design doc: design/06-caching.md, design/25-production-deployments.md\n */\n\nimport { workersCachePurgeAls } from './als-registry.js';\nimport type { WorkersCachePurgeCtx } from './als-registry.js';\n\n/**\n * Run a function with Workers Cache purge context available.\n *\n * Called by the generated Cloudflare _worker.js entry to bind\n * `ctx.cache` for the request duration.\n */\nexport function runWithWorkersCachePurge<T>(ctx: WorkersCachePurgeCtx, fn: () => T): T {\n return workersCachePurgeAls.run(ctx, fn);\n}\n\n/**\n * Get the current request's Workers Cache context, if available.\n *\n * Returns undefined outside a Cloudflare Workers request context\n * or on platforms without Workers Cache support.\n */\nexport function getWorkersCachePurgeCtx(): WorkersCachePurgeCtx | undefined {\n return workersCachePurgeAls.getStore();\n}\n","/**\n * Cloudflare Workers Cache purge handler — purges by cache tag via\n * ctx.cache.purge() on the ExecutionContext.\n *\n * Available on ALL Cloudflare plans (no Enterprise requirement).\n * No API token needed — uses the Workers runtime's built-in cache API.\n *\n * Auto-wired by the Cloudflare adapter when no user-configured CDN\n * purge handler is set. Uses the Workers Cache ALS bridge to access\n * ctx.cache from within the request context.\n */\n\nimport type { CdnPurgeHandler } from './purge-store';\nimport { getWorkersCachePurgeCtx } from '../server/workers-cache-bridge.js';\n\nexport class WorkersCachePurge implements CdnPurgeHandler {\n async purgeTags(tags: string[]): Promise<void> {\n if (tags.length === 0) return;\n\n const ctx = getWorkersCachePurgeCtx();\n if (!ctx) {\n throw new Error(\n 'WorkersCachePurge: no Workers Cache context available. ' +\n 'This handler can only be used within a Cloudflare Workers request context.'\n );\n }\n\n await ctx.purge({ tags });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,SAAgB,0BAA4D;CAC1E,OAAO,qBAAqB,SAAS;AACvC;;;ACjBA,IAAa,oBAAb,MAA0D;CACxD,MAAM,UAAU,MAA+B;EAC7C,IAAI,KAAK,WAAW,GAAG;EAEvB,MAAM,MAAM,wBAAwB;EACpC,IAAI,CAAC,KACH,MAAM,IAAI,MACR,mIAEF;EAGF,MAAM,IAAI,MAAM,EAAE,KAAK,CAAC;CAC1B;AACF"}