@builtbyfriends/bwf 0.0.0-stage → 1.9.2

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 (448) hide show
  1. package/AGENTS_TEMPLATE.md +4 -0
  2. package/LICENSE +22 -0
  3. package/README.md +48 -2
  4. package/dist/account-cmd-Ddt8lGeL.mjs +45 -0
  5. package/dist/agents-BLiMq9E1.mjs +113 -0
  6. package/dist/application-analysis-C9Ck2Yeg.mjs +1498 -0
  7. package/dist/application-routing-DbR-W5lG.mjs +25 -0
  8. package/dist/atomic-write-DA6eD1Kp.mjs +17 -0
  9. package/dist/auth-BKsUmWbT.d.mts +77 -0
  10. package/dist/auth-DkvoW5hB.mjs +33 -0
  11. package/dist/auth-aKyIWkdS.mjs +1 -0
  12. package/dist/auth-client-6-Ft9i9T.d.mts +5 -0
  13. package/dist/auth-client-DwCdwKbw.mjs +5 -0
  14. package/dist/auth-client-react-CJdeErvM.mjs +5 -0
  15. package/dist/auth-client-react-DvQLe5Zb.d.mts +5 -0
  16. package/dist/auth-link-CCl-hJol.mjs +26 -0
  17. package/dist/auth-migrations-DDeifS3v.mjs +206 -0
  18. package/dist/auth-router-BG74WFUf.mjs +66 -0
  19. package/dist/auth-xnkmpZUl.mjs +311 -0
  20. package/dist/base64-ikl9yBy3.mjs +15 -0
  21. package/dist/better-auth-shared-Br6TNaYJ.mjs +473 -0
  22. package/dist/better-auth-shared-CsBNvPOU.d.mts +56 -0
  23. package/dist/build-cmd-BnZezraT.mjs +153 -0
  24. package/dist/build-output-dir-Clj_unKN.mjs +402 -0
  25. package/dist/cancel-deploy-DKAj5U1Z.mjs +57 -0
  26. package/dist/cf-access-Bhz9wX6p.mjs +131 -0
  27. package/dist/cf-access-CUP5L08W.mjs +67 -0
  28. package/dist/cf-build-output-DA6uJomQ.mjs +1 -0
  29. package/dist/cf-build-output-DNQTwMNU.mjs +438 -0
  30. package/dist/cf-command-values-2kOtxMo1.mjs +26 -0
  31. package/dist/cf-config-migrate-COOCi4Ge.mjs +330 -0
  32. package/dist/cf-worker-settings-CIh4t_yG.mjs +41 -0
  33. package/dist/cli/cli.d.mts +1 -0
  34. package/dist/cli/cli.mjs +88 -0
  35. package/dist/cli/cloudflare-operation-process.d.mts +1 -0
  36. package/dist/cli/cloudflare-operation-process.mjs +1284 -0
  37. package/dist/cli/env-schema-probe.d.mts +43 -0
  38. package/dist/cli/env-schema-probe.mjs +165 -0
  39. package/dist/cli-main-BfYf6fnB.mjs +1846 -0
  40. package/dist/client-D3D5RM5h.mjs +940 -0
  41. package/dist/client-VF2Nzc7Z.mjs +1 -0
  42. package/dist/cloudflare-auth-DzkU9H6r.mjs +152 -0
  43. package/dist/cloudflare-cmd-Bm6UhzAQ.mjs +59 -0
  44. package/dist/cloudflare-config-i8yanry0.mjs +186 -0
  45. package/dist/cloudflare-connect-B4ItSbJi.mjs +55 -0
  46. package/dist/cloudflare-operations-BcK849ue.mjs +1 -0
  47. package/dist/cloudflare-operations-DGF7xH7O.mjs +627 -0
  48. package/dist/cloudflare-process-tThIjEB2.mjs +309 -0
  49. package/dist/cloudflare-user-output-CqONaAbP.mjs +19 -0
  50. package/dist/collect-8i0wU63d.mjs +1 -0
  51. package/dist/collect-C6Blu9yw.mjs +48 -0
  52. package/dist/config-CN_RFRkS.mjs +86 -0
  53. package/dist/config-D5G-Tx6o.mjs +1 -0
  54. package/dist/config-DOaFIK3w.mjs +88 -0
  55. package/dist/config-entry.d.mts +202 -0
  56. package/dist/config-entry.mjs +6 -0
  57. package/dist/config-tNx0HlFv.mjs +516 -0
  58. package/dist/connect-CSNWKLzB.mjs +84 -0
  59. package/dist/create-project-B35ux-LA.mjs +126 -0
  60. package/dist/create-project-tJ1KwNss.mjs +1 -0
  61. package/dist/database-provider-DkZo4VwN.mjs +5 -0
  62. package/dist/database-provider.d.mts +25 -0
  63. package/dist/database-provider.mjs +1 -0
  64. package/dist/db-SOv4E9wr.mjs +1735 -0
  65. package/dist/delete-BSKI7V23.mjs +65 -0
  66. package/dist/deploy-BCSQoKC0.mjs +2 -0
  67. package/dist/deploy-CWJ3JJs_.mjs +6512 -0
  68. package/dist/deploy.d.mts +31 -0
  69. package/dist/deploy.mjs +118 -0
  70. package/dist/dev-inbox-I0nqTCdf.mjs +216 -0
  71. package/dist/discover-DJPmQcL5.mjs +36 -0
  72. package/dist/discover-EVuydEoM.mjs +1 -0
  73. package/dist/dist-B6eN80gc.mjs +1612 -0
  74. package/dist/dist-Cp4b1_T9.mjs +1 -0
  75. package/dist/dist-DMYe8CZJ.mjs +48 -0
  76. package/dist/dist-STQXl8ck.mjs +1878 -0
  77. package/dist/domain-BJaAbxuQ.mjs +149 -0
  78. package/dist/dotenv-4NdUCXbB.mjs +156 -0
  79. package/dist/drizzle-DqVFXtlc.mjs +306 -0
  80. package/dist/drizzle-Ds5P0n-S.mjs +1 -0
  81. package/dist/edge.d.mts +2 -0
  82. package/dist/edge.mjs +1 -0
  83. package/dist/email-C_ATvNIG.mjs +2865 -0
  84. package/dist/email-cloudflare-oXk2G1G3.mjs +854 -0
  85. package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
  86. package/dist/email-rIfZgVAB.mjs +742 -0
  87. package/dist/env-BGTu3KWZ.mjs +73 -0
  88. package/dist/env-DUyTzroe.mjs +88 -0
  89. package/dist/env-Dl4Wggec.mjs +71 -0
  90. package/dist/env-helpers-BX0APszT.mjs +135 -0
  91. package/dist/env-helpers-U56xuFgL.d.mts +20 -0
  92. package/dist/env-mask-BsHxq3R8.mjs +46 -0
  93. package/dist/env-public-Cw_xPi1D.d.mts +119 -0
  94. package/dist/env-raw-Bo6TtrHU.mjs +41 -0
  95. package/dist/env-types-Bg-dTh8u.mjs +56 -0
  96. package/dist/env-validation-BlXzGgLZ.mjs +1 -0
  97. package/dist/env-validation-DeqFUSKg.mjs +488 -0
  98. package/dist/fetch-CBgyyhzm.d.mts +87 -0
  99. package/dist/fetch-error-DmlRM6e4.mjs +264 -0
  100. package/dist/fetch-stream-2GUN3YN1.mjs +102 -0
  101. package/dist/fetch-stream-bUXynOyZ.d.mts +32 -0
  102. package/dist/fetch-tpPiSK10.mjs +25 -0
  103. package/dist/gen-dc13IRXh.mjs +509 -0
  104. package/dist/gen-kQqhFyOP.mjs +1 -0
  105. package/dist/generate-BgtlYpKg.mjs +1 -0
  106. package/dist/generate-Da9mWKzU.mjs +80 -0
  107. package/dist/generated-wrangler-config-CoDaaFsA.mjs +17 -0
  108. package/dist/git-metadata-Cukp5kV5.mjs +82 -0
  109. package/dist/github-cmd-DT5Onu6E.mjs +690 -0
  110. package/dist/handler-B_ocHStk.d.mts +279 -0
  111. package/dist/handler-CNq7aSs1.mjs +161 -0
  112. package/dist/help-BK35YcRa.mjs +1946 -0
  113. package/dist/help-DaRezBj7.mjs +1 -0
  114. package/dist/inbound-CqubE-9T.d.mts +311 -0
  115. package/dist/inbound-lHugZPuK.mjs +509 -0
  116. package/dist/index.d.mts +64 -0
  117. package/dist/index.mjs +4163 -0
  118. package/dist/info-CLQoCenb.mjs +109 -0
  119. package/dist/init-CXanf5ck.mjs +2486 -0
  120. package/dist/limits-CMmYT2l8.d.mts +16 -0
  121. package/dist/limits-D27Lp6FP.mjs +46 -0
  122. package/dist/link-DinwJnon.mjs +52 -0
  123. package/dist/list-B1WAE9Wt.mjs +130 -0
  124. package/dist/live-KkEeda1Z.d.mts +105 -0
  125. package/dist/live-saC8barp.mjs +410 -0
  126. package/dist/load-user-env-g0ahkZcj.mjs +34 -0
  127. package/dist/local-d1-bUoAtFUe.mjs +103 -0
  128. package/dist/log-JDnPc0cF.mjs +23 -0
  129. package/dist/login-BUzyiyHV.mjs +1 -0
  130. package/dist/login-Dbv_T3Ru.mjs +87 -0
  131. package/dist/logs-BjMJooJQ.mjs +129 -0
  132. package/dist/migrate-DjW9_-sS.mjs +1 -0
  133. package/dist/migrate-DtcfKqPW.mjs +125 -0
  134. package/dist/migration-handler-22qiuWPq.mjs +469 -0
  135. package/dist/migration-handler-Bb2BJh6g.d.mts +38 -0
  136. package/dist/mime-BMUN_QKG.mjs +1004 -0
  137. package/dist/mysql-migration-sql-CNuBSqdx.mjs +239 -0
  138. package/dist/neon-CJzQSycr.mjs +52 -0
  139. package/dist/node-tfv-3v0V.mjs +64 -0
  140. package/dist/operator-ai-logging-Ay7M4KWw.mjs +121 -0
  141. package/dist/operator-args-BiGmSlZx.mjs +722 -0
  142. package/dist/operator-auth-DdYZYEkO.mjs +47 -0
  143. package/dist/operator-client-DBujdELO.mjs +82 -0
  144. package/dist/operator-cmd-BsHKYJYt.mjs +1 -0
  145. package/dist/operator-cmd-DTIkOAnP.mjs +443 -0
  146. package/dist/output-Bb34lF0w.mjs +173 -0
  147. package/dist/output-CVolXKC1.mjs +1 -0
  148. package/dist/package-BX_giUBX.mjs +1444 -0
  149. package/dist/package-json-DvS6IFRv.mjs +43 -0
  150. package/dist/pg-DoyPxa_X.mjs +15 -0
  151. package/dist/picocolors-D1NxSLw-.mjs +71 -0
  152. package/dist/plan-BHNt1QhK.mjs +1 -0
  153. package/dist/plan-DX4_-OM5.mjs +58 -0
  154. package/dist/platform-args-C-DyuCNX.mjs +1 -0
  155. package/dist/platform-args-CyeQWaZ7.mjs +538 -0
  156. package/dist/platform-auth-config-BfXqKSyZ.mjs +371 -0
  157. package/dist/platform-auth-protection-5FR6qoP_.mjs +231 -0
  158. package/dist/platform-auth-recovery-B5ZlqA8K.mjs +309 -0
  159. package/dist/platform-cmd-CcFDxtrl.mjs +1 -0
  160. package/dist/platform-cmd-ChXeBrRH.mjs +193 -0
  161. package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
  162. package/dist/platform-domain-CwatS3cz.mjs +256 -0
  163. package/dist/platform-lifecycle-0cXTmMsh.mjs +8928 -0
  164. package/dist/platform-lifecycle-BcoBAMux.mjs +1 -0
  165. package/dist/platform-management-6Wbdbob5.mjs +1607 -0
  166. package/dist/platform-management-hhnczOzr.mjs +1 -0
  167. package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
  168. package/dist/platform-recovery-DgIwlqB-.mjs +96 -0
  169. package/dist/platform-registry-x1m9HBxf.mjs +450 -0
  170. package/dist/platform-runtime-logs-kkoiYFpF.mjs +72 -0
  171. package/dist/platform-setup-DX8y_6Kh.mjs +306 -0
  172. package/dist/prepare-B9mB47T5.mjs +84 -0
  173. package/dist/prepare-DNIq07so.mjs +13 -0
  174. package/dist/prepare-LHkyJqxi.mjs +1 -0
  175. package/dist/project-CC7eN00D.mjs +141 -0
  176. package/dist/project-DcSd4BeI.mjs +1 -0
  177. package/dist/project-cmd-BydRwr-x.mjs +109 -0
  178. package/dist/project-paths-iXHKRTTQ.mjs +159 -0
  179. package/dist/project-slug-BUy0lmyR.mjs +1 -0
  180. package/dist/project-slug-CO6ci9XG.mjs +7 -0
  181. package/dist/project-team-CvdLhDF2.mjs +129 -0
  182. package/dist/project-token-CwZdUEGu.mjs +70 -0
  183. package/dist/project-tsconfig-P9X952KG.mjs +98 -0
  184. package/dist/project-zero-trust-CKDoPdN1.mjs +64 -0
  185. package/dist/providers-Cd3c7wi0.mjs +64 -0
  186. package/dist/providers-Df69hb_X.d.mts +5 -0
  187. package/dist/provision-BA59NCPO.mjs +1 -0
  188. package/dist/provision-C90fULHJ.mjs +1814 -0
  189. package/dist/queues-Bc3FsBQT.d.mts +5 -0
  190. package/dist/r2-conditions-DSLmkiR5.mjs +60 -0
  191. package/dist/requests-DNhfyF3l.mjs +52 -0
  192. package/dist/resolve-project-BCsAMDRA.mjs +47 -0
  193. package/dist/resolve-project-DhU9_lIo.mjs +1 -0
  194. package/dist/resource-name-DlJ9QXzg.mjs +10 -0
  195. package/dist/response-HmNjB30w.mjs +29 -0
  196. package/dist/rollback-wi6WK5T6.mjs +150 -0
  197. package/dist/rolldown-runtime-uD8oG6U2.mjs +24 -0
  198. package/dist/route-types-CRWhr93D.mjs +592 -0
  199. package/dist/route-url-BIDZT78M.mjs +58 -0
  200. package/dist/route-url-Bla3Upsy.d.mts +42 -0
  201. package/dist/routes-stub.d.mts +24 -0
  202. package/dist/routes-stub.mjs +1 -0
  203. package/dist/routing-assets-CSheDWWM.mjs +54 -0
  204. package/dist/rpc-DcByS_q0.d.mts +39 -0
  205. package/dist/rpc-DtxIN9Tv.mjs +19 -0
  206. package/dist/runner-CPerdjIl.mjs +163 -0
  207. package/dist/runner-CUNtS5x7.mjs +1 -0
  208. package/dist/runner-mysql-BjSoQ-mW.mjs +1 -0
  209. package/dist/runner-mysql-BmTI2EiF.mjs +145 -0
  210. package/dist/runner-pg-2pjltt0t.mjs +1 -0
  211. package/dist/runner-pg-mYc75KfH.mjs +61 -0
  212. package/dist/runtime/ai.d.mts +50 -0
  213. package/dist/runtime/ai.mjs +455 -0
  214. package/dist/runtime/auth-client-react.d.mts +2 -0
  215. package/dist/runtime/auth-client-react.mjs +1 -0
  216. package/dist/runtime/auth-client.d.mts +2 -0
  217. package/dist/runtime/auth-client.mjs +1 -0
  218. package/dist/runtime/auth.d.mts +2 -0
  219. package/dist/runtime/auth.mjs +1 -0
  220. package/dist/runtime/better-auth-mysql.d.mts +5 -0
  221. package/dist/runtime/better-auth-mysql.mjs +21 -0
  222. package/dist/runtime/better-auth-pg.d.mts +5 -0
  223. package/dist/runtime/better-auth-pg.mjs +21 -0
  224. package/dist/runtime/better-auth.d.mts +6 -0
  225. package/dist/runtime/better-auth.mjs +22 -0
  226. package/dist/runtime/client-react.d.mts +5 -0
  227. package/dist/runtime/client-react.mjs +5 -0
  228. package/dist/runtime/client.d.mts +5 -0
  229. package/dist/runtime/client.mjs +5 -0
  230. package/dist/runtime/db-mysql.d.mts +2 -0
  231. package/dist/runtime/db-mysql.mjs +1 -0
  232. package/dist/runtime/db-pg.d.mts +2 -0
  233. package/dist/runtime/db-pg.mjs +1 -0
  234. package/dist/runtime/db.d.mts +17 -0
  235. package/dist/runtime/db.mjs +36 -0
  236. package/dist/runtime/drizzle-arktype.d.mts +1 -0
  237. package/dist/runtime/drizzle-arktype.mjs +2 -0
  238. package/dist/runtime/drizzle-valibot.d.mts +1 -0
  239. package/dist/runtime/drizzle-valibot.mjs +2 -0
  240. package/dist/runtime/drizzle-zod.d.mts +1 -0
  241. package/dist/runtime/drizzle-zod.mjs +2 -0
  242. package/dist/runtime/durable.d.mts +64 -0
  243. package/dist/runtime/durable.mjs +165 -0
  244. package/dist/runtime/email/testing.d.mts +108 -0
  245. package/dist/runtime/email/testing.mjs +268 -0
  246. package/dist/runtime/email-protocol.d.mts +25 -0
  247. package/dist/runtime/email-protocol.mjs +1 -0
  248. package/dist/runtime/email.d.mts +26 -0
  249. package/dist/runtime/email.mjs +524 -0
  250. package/dist/runtime/env-public-client.d.mts +19 -0
  251. package/dist/runtime/env-public-client.mjs +55 -0
  252. package/dist/runtime/env-public.d.mts +4 -0
  253. package/dist/runtime/env-public.mjs +277 -0
  254. package/dist/runtime/env.d.mts +12 -0
  255. package/dist/runtime/env.mjs +1 -0
  256. package/dist/runtime/fetch-server.d.mts +6 -0
  257. package/dist/runtime/fetch-server.mjs +29 -0
  258. package/dist/runtime/fetch-stream.d.mts +3 -0
  259. package/dist/runtime/fetch-stream.mjs +3 -0
  260. package/dist/runtime/fetch.d.mts +2 -0
  261. package/dist/runtime/fetch.mjs +3 -0
  262. package/dist/runtime/handler.d.mts +3 -0
  263. package/dist/runtime/handler.mjs +1 -0
  264. package/dist/runtime/kv.d.mts +45 -0
  265. package/dist/runtime/kv.mjs +103 -0
  266. package/dist/runtime/limits.d.mts +2 -0
  267. package/dist/runtime/limits.mjs +1 -0
  268. package/dist/runtime/live-client.d.mts +40 -0
  269. package/dist/runtime/live-client.mjs +282 -0
  270. package/dist/runtime/live-server.d.mts +11 -0
  271. package/dist/runtime/live-server.mjs +419 -0
  272. package/dist/runtime/live.d.mts +3 -0
  273. package/dist/runtime/live.mjs +1 -0
  274. package/dist/runtime/log.d.mts +24 -0
  275. package/dist/runtime/log.mjs +57 -0
  276. package/dist/runtime/migration-handler-mysql.d.mts +2 -0
  277. package/dist/runtime/migration-handler-mysql.mjs +111 -0
  278. package/dist/runtime/migration-handler-pg.d.mts +2 -0
  279. package/dist/runtime/migration-handler-pg.mjs +94 -0
  280. package/dist/runtime/migration-handler.d.mts +2 -0
  281. package/dist/runtime/migration-handler.mjs +1 -0
  282. package/dist/runtime/procedure.d.mts +27 -0
  283. package/dist/runtime/procedure.mjs +36 -0
  284. package/dist/runtime/procedures.d.mts +24 -0
  285. package/dist/runtime/procedures.mjs +56 -0
  286. package/dist/runtime/queues.d.mts +2 -0
  287. package/dist/runtime/queues.mjs +8 -0
  288. package/dist/runtime/remote/binding-handler.d.mts +11 -0
  289. package/dist/runtime/remote/binding-handler.mjs +227 -0
  290. package/dist/runtime/remote/index.d.mts +12 -0
  291. package/dist/runtime/remote/index.mjs +467 -0
  292. package/dist/runtime/response.d.mts +11 -0
  293. package/dist/runtime/response.mjs +1 -0
  294. package/dist/runtime/route-url.d.mts +2 -0
  295. package/dist/runtime/route-url.mjs +1 -0
  296. package/dist/runtime/routing.d.mts +53 -0
  297. package/dist/runtime/routing.mjs +425 -0
  298. package/dist/runtime/rpc-react.d.mts +16 -0
  299. package/dist/runtime/rpc-react.mjs +50 -0
  300. package/dist/runtime/rpc.d.mts +2 -0
  301. package/dist/runtime/rpc.mjs +1 -0
  302. package/dist/runtime/sandbox-container.d.mts +3 -0
  303. package/dist/runtime/sandbox-container.mjs +1 -0
  304. package/dist/runtime/sandbox.d.mts +5 -0
  305. package/dist/runtime/sandbox.mjs +196 -0
  306. package/dist/runtime/schema-d1.d.mts +1 -0
  307. package/dist/runtime/schema-d1.mjs +2 -0
  308. package/dist/runtime/schema-mysql.d.mts +1 -0
  309. package/dist/runtime/schema-mysql.mjs +2 -0
  310. package/dist/runtime/schema-pg.d.mts +1 -0
  311. package/dist/runtime/schema-pg.mjs +2 -0
  312. package/dist/runtime/seed.d.mts +34 -0
  313. package/dist/runtime/seed.mjs +5 -0
  314. package/dist/runtime/sse-client.d.mts +31 -0
  315. package/dist/runtime/sse-client.mjs +42 -0
  316. package/dist/runtime/sse.d.mts +32 -0
  317. package/dist/runtime/sse.mjs +1 -0
  318. package/dist/runtime/storage.d.mts +4 -0
  319. package/dist/runtime/storage.mjs +13 -0
  320. package/dist/runtime/validator.d.mts +2 -0
  321. package/dist/runtime/validator.mjs +1 -0
  322. package/dist/runtime/ws-server.d.mts +26 -0
  323. package/dist/runtime/ws-server.mjs +297 -0
  324. package/dist/runtime/ws.d.mts +2 -0
  325. package/dist/runtime/ws.mjs +108 -0
  326. package/dist/sandbox-CWDjoEG2.d.mts +50 -0
  327. package/dist/sandbox-container-BqamdFCx.d.mts +73 -0
  328. package/dist/sandbox-container-d1AHLpgn.mjs +291 -0
  329. package/dist/secret-D5XrWshs.mjs +146 -0
  330. package/dist/skills-Dr3AjuBF.mjs +63 -0
  331. package/dist/sqlite-validation-CLJXXN93.mjs +24 -0
  332. package/dist/sse-CxR30yMF.mjs +174 -0
  333. package/dist/standard-schema-CuDawHOC.d.mts +40 -0
  334. package/dist/static-asset-marker-mWMX2dLa.mjs +38 -0
  335. package/dist/subcommand-prompt-B9yUo--u.mjs +370 -0
  336. package/dist/terminal-log-text-DNsWJREL.mjs +31 -0
  337. package/dist/types-D7-4tBu7.d.mts +1 -0
  338. package/dist/untrusted-env-lL7RkYiC.mjs +50 -0
  339. package/dist/validate-B-zsjhiz.mjs +162 -0
  340. package/dist/validate-DbqGdPPY.mjs +1 -0
  341. package/dist/validator-8-NZs2Xr.mjs +168 -0
  342. package/dist/version-metadata-DPhqnpaa.mjs +23 -0
  343. package/dist/wrangler-C3uyPadQ.mjs +1 -0
  344. package/dist/wrangler-TqTvJFWS.mjs +1452 -0
  345. package/dist/ws-DZRiIpYw.d.mts +137 -0
  346. package/dist/yarn-pnp-DgWbE7z5.mjs +91 -0
  347. package/docs/guide/ai.md +273 -0
  348. package/docs/guide/app-types.md +101 -0
  349. package/docs/guide/auth.md +255 -0
  350. package/docs/guide/database/d1.md +86 -0
  351. package/docs/guide/database/mysql.md +72 -0
  352. package/docs/guide/database/postgresql.md +94 -0
  353. package/docs/guide/database.md +454 -0
  354. package/docs/guide/deployment.md +124 -0
  355. package/docs/guide/durable-state.md +192 -0
  356. package/docs/guide/edge/headers.md +47 -0
  357. package/docs/guide/edge/redirects.md +85 -0
  358. package/docs/guide/edge/rewrites.md +119 -0
  359. package/docs/guide/edge/static-assets.md +94 -0
  360. package/docs/guide/email/domains.md +119 -0
  361. package/docs/guide/email/receiving.md +142 -0
  362. package/docs/guide/email/sending.md +262 -0
  363. package/docs/guide/email.md +23 -0
  364. package/docs/guide/env-vars.md +115 -0
  365. package/docs/guide/index.md +37 -0
  366. package/docs/guide/jobs.md +80 -0
  367. package/docs/guide/kv.md +100 -0
  368. package/docs/guide/live.md +181 -0
  369. package/docs/guide/platform/administration/access.md +165 -0
  370. package/docs/guide/platform/administration/connected-apps.md +84 -0
  371. package/docs/guide/platform/administration/email.md +169 -0
  372. package/docs/guide/platform/administration/operations.md +100 -0
  373. package/docs/guide/platform/administration/plans.md +156 -0
  374. package/docs/guide/platform/administration/projects.md +74 -0
  375. package/docs/guide/platform/administration/zero-trust.md +205 -0
  376. package/docs/guide/platform/development/local.md +122 -0
  377. package/docs/guide/platform/development/runtime.md +115 -0
  378. package/docs/guide/platform/development/schema-ci.md +44 -0
  379. package/docs/guide/platform/installation/ci.md +62 -0
  380. package/docs/guide/platform/installation/credentials.md +140 -0
  381. package/docs/guide/platform/installation/domains.md +120 -0
  382. package/docs/guide/platform/installation/first-deployment.md +95 -0
  383. package/docs/guide/platform/installation/maintenance.md +250 -0
  384. package/docs/guide/platform/installation/prerequisites.md +176 -0
  385. package/docs/guide/platform/installation/setup.md +300 -0
  386. package/docs/guide/platform/installation/uninstall.md +110 -0
  387. package/docs/guide/platform-administration.md +19 -0
  388. package/docs/guide/platform-development.md +16 -0
  389. package/docs/guide/procedures.md +48 -0
  390. package/docs/guide/project-collaboration.md +99 -0
  391. package/docs/guide/queues.md +149 -0
  392. package/docs/guide/quickstart.md +129 -0
  393. package/docs/guide/remote-dev.md +67 -0
  394. package/docs/guide/sandboxes.md +134 -0
  395. package/docs/guide/self-hosted-platform.md +45 -0
  396. package/docs/guide/server-routing.md +283 -0
  397. package/docs/guide/sse.md +174 -0
  398. package/docs/guide/storage.md +82 -0
  399. package/docs/guide/testing.md +64 -0
  400. package/docs/guide/type-safety.md +270 -0
  401. package/docs/guide/typed-fetch.md +98 -0
  402. package/docs/guide/websockets.md +230 -0
  403. package/docs/index.md +102 -0
  404. package/docs/integrations/agents.md +38 -0
  405. package/docs/integrations/cloudflare.md +241 -0
  406. package/docs/integrations/hono.md +127 -0
  407. package/docs/reference/api/auth.md +195 -0
  408. package/docs/reference/api/client.md +90 -0
  409. package/docs/reference/api/database.md +118 -0
  410. package/docs/reference/api/deploy.md +63 -0
  411. package/docs/reference/api/durable.md +47 -0
  412. package/docs/reference/api/env.md +51 -0
  413. package/docs/reference/api/handlers.md +189 -0
  414. package/docs/reference/api/plugin.md +40 -0
  415. package/docs/reference/api/resources.md +116 -0
  416. package/docs/reference/api/rewrites.md +111 -0
  417. package/docs/reference/api/types.md +126 -0
  418. package/docs/reference/api.md +71 -0
  419. package/docs/reference/cli/auth.md +87 -0
  420. package/docs/reference/cli/database.md +159 -0
  421. package/docs/reference/cli/deploy.md +117 -0
  422. package/docs/reference/cli/domains.md +42 -0
  423. package/docs/reference/cli/email.md +145 -0
  424. package/docs/reference/cli/generate.md +113 -0
  425. package/docs/reference/cli/github.md +181 -0
  426. package/docs/reference/cli/platform-config.md +93 -0
  427. package/docs/reference/cli/platform-email.md +81 -0
  428. package/docs/reference/cli/platform-installation.md +166 -0
  429. package/docs/reference/cli/platform-operations.md +90 -0
  430. package/docs/reference/cli/platform-users.md +159 -0
  431. package/docs/reference/cli/platform-zero-trust.md +60 -0
  432. package/docs/reference/cli/platform.md +78 -0
  433. package/docs/reference/cli/project.md +208 -0
  434. package/docs/reference/cli/secrets.md +79 -0
  435. package/docs/reference/cli/setup.md +88 -0
  436. package/docs/reference/cli.md +115 -0
  437. package/docs/reference/config.md +478 -0
  438. package/docs/reference/resource-inference.md +72 -0
  439. package/docs/reference/structure.md +138 -0
  440. package/package.json +389 -3
  441. package/sandbox.Dockerfile +4 -0
  442. package/schema.json +353 -0
  443. package/skills/bwf/SKILL.md +100 -0
  444. package/skills/migrate-vite-cloudflare-to-bwf/SKILL.md +53 -0
  445. package/templates/assets/bwf.svg +5 -0
  446. package/templates/assets/icons.svg +49 -0
  447. package/templates/assets/react.svg +1 -0
  448. package/templates/assets/stack.svg +35 -0
@@ -0,0 +1,1814 @@
1
+ import { a as join, c as resolve$2, n as dirname, o as normalize, t as basename } from "./dist-DMYe8CZJ.mjs";
2
+ import { n as bwfLog, r as bwfWarn } from "./log-JDnPc0cF.mjs";
3
+ import { n as scanWranglerDotenvKeys } from "./dotenv-4NdUCXbB.mjs";
4
+ import { c as resolveCloudflareOperationArgv, n as decodeCloudflareOperationResult, r as encodeCloudflareOperation } from "./cloudflare-process-tThIjEB2.mjs";
5
+ import { A as writeProvisionedWranglerConfig, _ as readProvisionedBindingEntry, h as persistMaterializedWranglerConfig, s as assertNoDuplicateMembers } from "./wrangler-TqTvJFWS.mjs";
6
+ import { createRequire } from "node:module";
7
+ import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, unlinkSync, writeSync } from "node:fs";
8
+ import { isRecord } from "@builtbyfriends/deploy-core";
9
+ import { randomUUID } from "node:crypto";
10
+ import { parse } from "jsonc-parser";
11
+ import { spawn } from "node:child_process";
12
+ import { resolve } from "node:path/posix";
13
+ import { resolve as resolve$1 } from "node:path/win32";
14
+ import lockfile from "proper-lockfile";
15
+ // src/cli/provision.ts
16
+ /**
17
+ * Desired id-bearing resources whose binding has no real id in the root config, using the
18
+ * same rule as read-first. Reads only the local config; queues have no id and are skipped.
19
+ */
20
+ function checkCloudflareProvisionDrift(configPath, desired) {
21
+ const config = readRootConfig(configPath);
22
+ const missing = [];
23
+ const isProvisioned = (field, binding, hasRealId) => {
24
+ const entry = readProvisionedBindingEntry(config, field, binding, configPath);
25
+ return entry !== void 0 && hasRealId(entry);
26
+ };
27
+ if (desired.d1) {
28
+ if (!isProvisioned("d1_databases", desired.d1.binding, (e) => isRealD1Id(e.database_id))) missing.push({
29
+ binding: desired.d1.binding,
30
+ kind: "d1",
31
+ name: desired.d1.name
32
+ });
33
+ }
34
+ for (const kv of desired.kvNamespaces) if (!isProvisioned("kv_namespaces", kv.binding, (e) => isRealKvId(e.id))) missing.push({
35
+ binding: kv.binding,
36
+ kind: "kv",
37
+ name: kv.title
38
+ });
39
+ if (desired.r2) {
40
+ if (!isProvisioned("r2_buckets", desired.r2.binding, (e) => isRealStoredR2BucketName(e.bucket_name, desired.r2?.bucketName))) missing.push({
41
+ binding: desired.r2.binding,
42
+ kind: "r2",
43
+ name: desired.r2.bucketName
44
+ });
45
+ }
46
+ if (desired.hyperdrive) {
47
+ if (!isProvisioned("hyperdrive", desired.hyperdrive.binding, (e) => isRealHyperdriveId(e.id))) missing.push({
48
+ binding: desired.hyperdrive.binding,
49
+ kind: "hyperdrive",
50
+ name: desired.hyperdrive.name
51
+ });
52
+ }
53
+ return { missing };
54
+ }
55
+ /** Where bwf keeps D1 migrations — written as `migrations_dir` on the D1 entry. */
56
+ const D1_MIGRATIONS_DIR = "./db/migrations";
57
+ /** UTF-8 byte-order mark. Node's utf-8 read preserves a leading one. */
58
+ const UTF8_BOM = "";
59
+ const D1_ID_PLACEHOLDER = "local";
60
+ const KV_ID_PLACEHOLDER = "local";
61
+ const R2_BUCKET_NAME_PLACEHOLDER = "default";
62
+ const D1_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
63
+ const HEX32_ID_RE = /^[0-9a-f]{32}$/i;
64
+ /** R2 bucket-name grammar (wrangler's `isValidR2BucketName`). */
65
+ const R2_BUCKET_NAME_RE = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;
66
+ /** A real (non-placeholder) D1 `database_id`. */
67
+ function isRealD1Id(value) {
68
+ return typeof value === "string" && value !== D1_ID_PLACEHOLDER && D1_ID_RE.test(value);
69
+ }
70
+ /** A real (non-placeholder) KV namespace `id`. */
71
+ function isRealKvId(value) {
72
+ return typeof value === "string" && value !== KV_ID_PLACEHOLDER && HEX32_ID_RE.test(value);
73
+ }
74
+ /** A Hyperdrive config `id` that is a real 32-hex string (no placeholder exists). */
75
+ function isRealHyperdriveId(value) {
76
+ return typeof value === "string" && HEX32_ID_RE.test(value);
77
+ }
78
+ /** An R2 `bucket_name` satisfying wrangler's bucket-name GRAMMAR (format only). */
79
+ function isValidR2BucketNameFormat(value) {
80
+ return typeof value === "string" && R2_BUCKET_NAME_RE.test(value);
81
+ }
82
+ /**
83
+ * A stored R2 `bucket_name` naming a real bucket: any non-empty string except the `default`
84
+ * placeholder (unless desired). Grammar is not checked, so a contradicting name still fails.
85
+ */
86
+ function isRealStoredR2BucketName(value, desiredName) {
87
+ return typeof value === "string" && value.length > 0 && (value !== R2_BUCKET_NAME_PLACEHOLDER || value === desiredName);
88
+ }
89
+ const defaultLogger = {
90
+ info: (msg) => bwfLog(msg),
91
+ warn: (msg) => bwfWarn(msg)
92
+ };
93
+ /**
94
+ * Env vars that move the Cloudflare CLI's API transport to another endpoint or select another
95
+ * config env. Provisioning pins one base ({@link provisionEnv}) and rejects them in project
96
+ * dotenv.
97
+ */
98
+ const TRANSPORT_REDIRECT_ENV_VARS = [
99
+ "CLOUDFLARE_API_BASE_URL",
100
+ "CF_API_BASE_URL",
101
+ "WRANGLER_API_ENVIRONMENT",
102
+ "CLOUDFLARE_COMPLIANCE_REGION",
103
+ "CLOUDFLARE_ENV"
104
+ ];
105
+ /**
106
+ * Session-output file variables. Provisioning keeps operation output off disk, so they are
107
+ * scrubbed from the child env and rejected in project dotenv. Secrets travel over stdin.
108
+ */
109
+ const OUTPUT_FILE_ENV_VARS = ["WRANGLER_OUTPUT_FILE_PATH", "WRANGLER_OUTPUT_FILE_DIRECTORY"];
110
+ /**
111
+ * The one API base URL this provision uses, resolved like wrangler's `getCloudflareApiBaseUrl`
112
+ * so the Hyperdrive REST lister and the Cloudflare CLI agree:
113
+ * 1. a present `CLOUDFLARE_API_BASE_URL` (then `CF_API_BASE_URL`) is used as-is, even empty;
114
+ * 2. otherwise the staging and compliance selectors derive it, and invalid values fail;
115
+ * 3. the config's `compliance_region` is always validated.
116
+ */
117
+ function resolvePinnedApiBaseUrl(env = process.env, configComplianceRegion) {
118
+ const configRegion = configComplianceRegion !== void 0 ? assertComplianceChoice(configComplianceRegion, "the Cloudflare config \"compliance_region\"") : void 0;
119
+ const direct = env.CLOUDFLARE_API_BASE_URL !== void 0 ? env.CLOUDFLARE_API_BASE_URL : env.CF_API_BASE_URL;
120
+ if (direct !== void 0) return direct;
121
+ return `https://api${resolveComplianceRegion(env, configRegion) === "fedramp_high" ? ".fed" : ""}${resolveApiEnvironment(env) === "staging" ? ".staging" : ""}.cloudflare.com/client/v4`;
122
+ }
123
+ /**
124
+ * The compliance region that names the workers.dev host, resolved like wrangler's
125
+ * `getComplianceRegionSubdomain`. It reads the same inputs as {@link resolvePinnedApiBaseUrl},
126
+ * but a direct API base does not skip the region checks, because the base does not name the
127
+ * workers.dev host. Returns undefined for an invalid or conflicting region, so that a caller
128
+ * does not guess a host. Without a direct base, the API base resolution fails first.
129
+ */
130
+ function resolveWorkersDevComplianceRegion(env = process.env, configComplianceRegion) {
131
+ try {
132
+ return resolveComplianceRegion(env, configComplianceRegion !== void 0 ? assertComplianceChoice(configComplianceRegion, "the Cloudflare config \"compliance_region\"") : void 0);
133
+ } catch {
134
+ return;
135
+ }
136
+ }
137
+ /** `WRANGLER_API_ENVIRONMENT` like wrangler: absent means production; other values fail. */
138
+ function resolveApiEnvironment(env) {
139
+ const raw = env.WRANGLER_API_ENVIRONMENT;
140
+ if (raw === void 0) return "production";
141
+ if (raw !== "production" && raw !== "staging") throw new Error(`provision: the WRANGLER_API_ENVIRONMENT environment variable must be one of "production" or "staging", got ${JSON.stringify(raw)}. The Cloudflare tooling rejects this value, so provisioning refuses to guess an endpoint; fix or unset it and retry.`);
142
+ return raw;
143
+ }
144
+ /** Compliance-region values wrangler accepts. */
145
+ const COMPLIANCE_REGIONS = ["public", "fedramp_high"];
146
+ function assertComplianceChoice(value, source) {
147
+ if (value !== "public" && value !== "fedramp_high") throw new Error(`provision: ${source} must be one of ${COMPLIANCE_REGIONS.map((c) => JSON.stringify(c)).join(" or ")}, got ${JSON.stringify(value)}.`);
148
+ return value;
149
+ }
150
+ /** Effective compliance region like wrangler: values are validated and a conflict fails. */
151
+ function resolveComplianceRegion(env, configRegion) {
152
+ const rawEnv = env.CLOUDFLARE_COMPLIANCE_REGION;
153
+ const envRegion = rawEnv !== void 0 ? assertComplianceChoice(rawEnv, "the CLOUDFLARE_COMPLIANCE_REGION environment variable") : void 0;
154
+ if (envRegion !== void 0 && configRegion !== void 0 && envRegion !== configRegion) throw new Error(`provision: the Cloudflare compliance region is set to conflicting values — the CLOUDFLARE_COMPLIANCE_REGION environment variable is ${JSON.stringify(envRegion)} but the Cloudflare config "compliance_region" is ${JSON.stringify(configRegion)}. The Cloudflare tooling refuses to run with a mismatched compliance region; reconcile them (remove one, or set them equal) and retry.`);
155
+ return envRegion ?? configRegion ?? "public";
156
+ }
157
+ /** Project dotenv files the fence scans for `env`; provisioning selects no named env (`''`). */
158
+ function defaultWranglerEnvFiles(env) {
159
+ return [
160
+ ".env",
161
+ ".env.local",
162
+ `.env.${env}`,
163
+ `.env.${env}.local`
164
+ ];
165
+ }
166
+ /**
167
+ * Fail when a project dotenv file sets a transport-redirect or session-output variable.
168
+ * Cloudflare tooling reads these files from the project, which would move its authenticated
169
+ * transport away from the pinned base. Values exported in the shell are honored instead.
170
+ */
171
+ function assertNoTransportRedirectInProjectDotenv(root, platform = process.platform) {
172
+ const dotenvCaseInsensitive = platform === "win32";
173
+ const devVarsFile = existsSync(join(root, ".dev.vars.")) ? ".dev.vars." : ".dev.vars";
174
+ const files = [...defaultWranglerEnvFiles("").map((file) => ({
175
+ file,
176
+ caseInsensitive: dotenvCaseInsensitive
177
+ })), {
178
+ file: devVarsFile,
179
+ caseInsensitive: false
180
+ }];
181
+ for (const { file, caseInsensitive } of files) {
182
+ const keys = scanWranglerDotenvKeys(join(root, file));
183
+ const lowerKeys = caseInsensitive ? new Set([...keys].map((key) => key.toLowerCase())) : void 0;
184
+ const declares = (name) => lowerKeys !== void 0 ? lowerKeys.has(name.toLowerCase()) : keys.has(name);
185
+ const offenders = TRANSPORT_REDIRECT_ENV_VARS.filter(declares);
186
+ if (offenders.length > 0) throw new Error(`provision: refusing to provision — the project file "${file}" sets ${offenders.join(", ")}, which Cloudflare tooling reads from project files and would redirect its authenticated Cloudflare API transport (and credentials) to a different endpoint/account than this provision is pinned to (the Hyperdrive existence check would then run against a DIFFERENT endpoint, risking cross-environment writes or duplicate resources). Remove ${offenders.join(", ")} from "${file}" and, if you truly need a non-default endpoint, export it in your shell/CI environment instead — that pin IS honored for both the Cloudflare operations and the existence check.`);
187
+ const outputOffenders = OUTPUT_FILE_ENV_VARS.filter(declares);
188
+ if (outputOffenders.length > 0) throw new Error(`provision: refusing to provision — the project file "${file}" sets ${outputOffenders.join(", ")}. bwf does not allow Cloudflare session output files during provisioning. Remove ${outputOffenders.join(", ")} from "${file}".`);
189
+ }
190
+ }
191
+ /**
192
+ * Delete `name` from `env` in place. Windows env keys are case-insensitive, so every spelling
193
+ * is removed there; elsewhere only the exact key.
194
+ */
195
+ function deleteEnvVarCaseAware(env, name, platform = process.platform) {
196
+ if (platform !== "win32") {
197
+ delete env[name];
198
+ return;
199
+ }
200
+ const lower = name.toLowerCase();
201
+ for (const key of Object.keys(env)) if (key.toLowerCase() === lower) delete env[key];
202
+ }
203
+ /**
204
+ * Child env for a Cloudflare operation. CF Access credentials, transport selectors and output
205
+ * sinks are scrubbed; the account, API base and sanitized logging are pinned.
206
+ */
207
+ function provisionEnv(ctx) {
208
+ const env = { ...process.env };
209
+ const platform = ctx?.platform ?? process.platform;
210
+ const scrub = (name) => deleteEnvVarCaseAware(env, name, platform);
211
+ scrub("CF_ACCESS_CLIENT_ID");
212
+ scrub("CF_ACCESS_CLIENT_SECRET");
213
+ scrub("CF_ACCESS_TOKEN");
214
+ scrub("NOSAM_ACCESS_CREDENTIALS");
215
+ scrub("NOSAM_ACCESS_ORIGIN");
216
+ scrub("CF_ACCESS_READINESS_ORIGIN");
217
+ for (const name of TRANSPORT_REDIRECT_ENV_VARS) scrub(name);
218
+ for (const name of OUTPUT_FILE_ENV_VARS) scrub(name);
219
+ scrub("WRANGLER_LOG_SANITIZE");
220
+ env.WRANGLER_LOG_SANITIZE = "true";
221
+ if (ctx?.apiBaseUrl !== void 0) env.CLOUDFLARE_API_BASE_URL = ctx.apiBaseUrl;
222
+ if (ctx?.accountId) {
223
+ scrub("CLOUDFLARE_ACCOUNT_ID");
224
+ env.CLOUDFLARE_ACCOUNT_ID = ctx.accountId;
225
+ }
226
+ if (ctx?.apiToken) {
227
+ for (const name of [
228
+ "CLOUDFLARE_API_TOKEN",
229
+ "CF_API_TOKEN",
230
+ "CLOUDFLARE_API_KEY",
231
+ "CF_API_KEY",
232
+ "CLOUDFLARE_EMAIL",
233
+ "CF_EMAIL"
234
+ ]) scrub(name);
235
+ env.CLOUDFLARE_API_TOKEN = ctx.apiToken;
236
+ }
237
+ return env;
238
+ }
239
+ /** Per-command timeout; the default runner SIGKILLs a child that runs longer. */
240
+ const COMMAND_TIMEOUT_MS = 12e4;
241
+ /**
242
+ * After a SIGKILL, how long to wait for both `close` and the whole process group to be gone.
243
+ * If that cannot be confirmed, the runner rejects with {@link WranglerQuarantineError}.
244
+ */
245
+ const CONFIRM_KILL_GRACE_MS = 5e3;
246
+ /** The pid-poll interval while confirming post-SIGKILL termination. */
247
+ const CONFIRM_KILL_POLL_MS = 20;
248
+ /** Extra time a signal teardown allows beyond a runner's confirmation window. */
249
+ const SIGNAL_TEARDOWN_DEADLINE_MARGIN_MS = 5e3;
250
+ /** ESRCH means the group already exited; any other kill error is a real failure. */
251
+ function isAlreadyGoneKillError(error) {
252
+ return error?.code === "ESRCH";
253
+ }
254
+ /**
255
+ * The runner could not confirm that a spawned child and its process group are dead. The child
256
+ * may still be creating resources, so the provision lock is kept instead of released.
257
+ */
258
+ var WranglerQuarantineError = class extends Error {
259
+ quarantine = true;
260
+ pid;
261
+ constructor(pid, detail) {
262
+ const pidLabel = pid !== void 0 ? ` (pid ${pid})` : "";
263
+ super(`provision: the spawned Cloudflare operation process could not be confirmed terminated${pidLabel} — ${detail}. It may still be running and creating resources, so the cross-process provision lock is intentionally RETAINED (not released) and its owner is recorded in a quarantine sidecar ("<Cloudflare config>.bwf-provision.lock.quarantine.json") that blocks concurrent provisions. Recovery: verify the process${pidLabel} is dead (e.g. \`kill -0 <pid>\`; terminate it if not) — the NEXT provision then confirms the recorded group is gone and clears the quarantine automatically. To clear it manually instead, remove the sidecar and the "<Cloudflare config>.bwf-provision.lock.lock" directory, then re-run.`);
264
+ this.name = "WranglerQuarantineError";
265
+ this.pid = pid;
266
+ }
267
+ };
268
+ let activeProvisionSlot;
269
+ function acquireProcessProvisionSlot() {
270
+ if (activeProvisionSlot !== void 0) throw new Error("provision: a provision is already active in this process — run provisions sequentially. provisionCloudflareResources supports at most one concurrent provision per process; concurrent provisions across PROCESSES are serialized by the on-disk provision lock instead.");
271
+ if (retentionWatchdog !== void 0) throw new Error(`provision: a previous provision in this process is still retaining its lock — an unconfirmed Cloudflare operation process${retentionWatchdog.info.pid !== void 0 ? ` (pid ${retentionWatchdog.info.pid})` : ""} could not be quarantined durably yet. No new provision may start until that retention resolves (the child is confirmed dead, or the quarantine metadata persists durably).`);
272
+ const token = Symbol("nosam-provision-slot");
273
+ activeProvisionSlot = token;
274
+ return () => {
275
+ if (activeProvisionSlot === token) activeProvisionSlot = void 0;
276
+ };
277
+ }
278
+ /**
279
+ * The active provision's lock-quarantine hook. A child captures it at registration, so a
280
+ * failed teardown quarantines only its own provision lock with its own pid.
281
+ */
282
+ let activeProvisionQuarantineHook;
283
+ /** True when `error` is a quarantine failure whose provision lock must stay retained. */
284
+ function isQuarantineError(error) {
285
+ return error instanceof WranglerQuarantineError || error?.quarantine === true;
286
+ }
287
+ /** Concurrent registrations are allowed only for two immutable Worker uploads. */
288
+ const activeRegistrations = /* @__PURE__ */ new Map();
289
+ let coordinatorListenersInstalled = false;
290
+ let activeTeardown;
291
+ let reRaisedOnce = false;
292
+ const onCoordinatorSigint = () => coordinatorHandleSignal("SIGINT");
293
+ const onCoordinatorSigterm = () => coordinatorHandleSignal("SIGTERM");
294
+ function installCoordinatorListeners() {
295
+ if (coordinatorListenersInstalled) return;
296
+ coordinatorListenersInstalled = true;
297
+ process.on("SIGINT", onCoordinatorSigint);
298
+ process.on("SIGTERM", onCoordinatorSigterm);
299
+ }
300
+ function removeCoordinatorListeners() {
301
+ if (!coordinatorListenersInstalled) return;
302
+ coordinatorListenersInstalled = false;
303
+ process.removeListener("SIGINT", onCoordinatorSigint);
304
+ process.removeListener("SIGTERM", onCoordinatorSigterm);
305
+ }
306
+ function canRegisterRunner(parallelWorkerUpload) {
307
+ return activeRegistrations.size === 0 || parallelWorkerUpload && activeProvisionQuarantineHook === void 0 && activeRegistrations.size < 2 && [...activeRegistrations.values()].every((entry) => entry.parallelWorkerUpload);
308
+ }
309
+ function registerRunner(registrant, parallelWorkerUpload) {
310
+ if (!canRegisterRunner(parallelWorkerUpload)) throw new Error("provision: internal invariant violated — a Cloudflare child tried to register outside its concurrency limit");
311
+ activeRegistrations.set(registrant, {
312
+ registrant,
313
+ lockQuarantine: activeProvisionQuarantineHook,
314
+ parallelWorkerUpload
315
+ });
316
+ installCoordinatorListeners();
317
+ }
318
+ function deregisterRunner(registrant) {
319
+ activeRegistrations.delete(registrant);
320
+ if (activeRegistrations.size === 0 && activeTeardown === void 0 && retentionWatchdog === void 0) removeCoordinatorListeners();
321
+ }
322
+ function coordinatorHandleSignal(signal) {
323
+ if (activeTeardown !== void 0) return;
324
+ if (retentionWatchdog !== void 0 && activeRegistrations.size === 0) {
325
+ process.stderr.write(`provision: ignoring ${signal} — a provision lock is retained while an unconfirmed Cloudflare operation process may live and its quarantine metadata is not yet durable. The process exits once the child is confirmed dead or the metadata persists.\n`);
326
+ return;
327
+ }
328
+ const teardown = {
329
+ signal,
330
+ pending: 0,
331
+ dispatching: true,
332
+ persistFailed: false,
333
+ finished: false,
334
+ deadlineTimer: void 0,
335
+ expirePendingPairs: []
336
+ };
337
+ activeTeardown = teardown;
338
+ const snapshot = [...activeRegistrations.values()];
339
+ teardown.pending = snapshot.length;
340
+ if (snapshot.length > 0) {
341
+ const deadlineMs = Math.max(...snapshot.map((r) => r.registrant.teardownDeadlineMs));
342
+ teardown.deadlineTimer = setTimeout(() => {
343
+ for (const expire of teardown.expirePendingPairs) expire(`the coordinator-wide ${deadlineMs}ms teardown deadline expired before the process group's termination was confirmed`);
344
+ }, deadlineMs);
345
+ }
346
+ for (const registration of snapshot) coordinatorTearDownRegistrant(teardown, registration);
347
+ teardown.dispatching = false;
348
+ maybeFinishCoordinatorTeardown(teardown);
349
+ }
350
+ /** Finish after dispatch completes and every registrant is resolved. */
351
+ function maybeFinishCoordinatorTeardown(teardown) {
352
+ if (!teardown.dispatching && teardown.pending === 0) finishCoordinatorTeardown(teardown);
353
+ }
354
+ function coordinatorTearDownRegistrant(teardown, registration) {
355
+ const { registrant, lockQuarantine } = registration;
356
+ let done = false;
357
+ const complete = () => {
358
+ if (done) return;
359
+ done = true;
360
+ teardown.pending -= 1;
361
+ maybeFinishCoordinatorTeardown(teardown);
362
+ };
363
+ const quarantinePair = (detail) => {
364
+ if (done) return;
365
+ if (lockQuarantine !== void 0) try {
366
+ lockQuarantine({
367
+ pid: registrant.pid(),
368
+ reason: `the spawned Cloudflare operation process could not be confirmed terminated after a forwarded ${teardown.signal} — ${detail}`
369
+ });
370
+ } catch (failure) {
371
+ teardown.persistFailed = true;
372
+ process.stderr.write(`provision: ${failure.message}\n`);
373
+ }
374
+ const pid = registrant.pid();
375
+ process.stderr.write(`provision: warning — the Cloudflare operation process group${typeof pid === "number" ? ` (pid ${pid})` : ""} could not be confirmed terminated after ${teardown.signal} (${detail}). It may still be running; the provision lock is retained (quarantined) — verify the process is dead before re-running provision.\n`);
376
+ registrant.quarantine(detail);
377
+ complete();
378
+ };
379
+ teardown.expirePendingPairs.push(quarantinePair);
380
+ const outcome = registrant.signalGroup(teardown.signal);
381
+ if (typeof outcome === "object") {
382
+ quarantinePair(`the process group could not be signalled: ${outcome.error.message}`);
383
+ return;
384
+ }
385
+ if (outcome === "gone") registrant.markGroupGone();
386
+ registrant.awaitConfirmedDead((result) => {
387
+ if (result.confirmed) complete();
388
+ else quarantinePair(result.detail);
389
+ });
390
+ }
391
+ function finishCoordinatorTeardown(teardown) {
392
+ if (teardown.finished) return;
393
+ teardown.finished = true;
394
+ if (teardown.deadlineTimer !== void 0) clearTimeout(teardown.deadlineTimer);
395
+ removeCoordinatorListeners();
396
+ if (teardown.persistFailed || retentionWatchdog !== void 0) {
397
+ activeTeardown = void 0;
398
+ installCoordinatorListeners();
399
+ process.stderr.write(`provision: NOT re-raising ${teardown.signal} — a provision lock's quarantine metadata could not be persisted, so the lock is intentionally still held by this process to keep it from being stolen while the unconfirmed Cloudflare operation process may live.\n`);
400
+ return;
401
+ }
402
+ if (reRaisedOnce) return;
403
+ reRaisedOnce = true;
404
+ process.kill(process.pid, teardown.signal);
405
+ setTimeout(() => {}, 2e3);
406
+ }
407
+ const RETENTION_RETRY_MIN_MS = 250;
408
+ const RETENTION_RETRY_MAX_MS = 5e3;
409
+ let retentionWatchdog;
410
+ /** Quarantine `lock`; if persisting fails, arm the retention watchdog before rethrowing. */
411
+ function retainQuarantinedLock(lock, info) {
412
+ try {
413
+ lock.quarantine(info);
414
+ } catch (error) {
415
+ armRetentionWatchdog(lock, info);
416
+ throw error;
417
+ }
418
+ }
419
+ function armRetentionWatchdog(lock, info) {
420
+ if (retentionWatchdog !== void 0) return;
421
+ process.stderr.write(`provision: warning — quarantine metadata for the unconfirmed Cloudflare operation process${info.pid !== void 0 ? ` (pid ${info.pid})` : ""} could not be persisted, so the provision lock "${lock.lockTargetPath}.lock" is RETAINED by this process, which stays alive until the child is confirmed dead or the metadata persists durably.\n`);
422
+ installCoordinatorListeners();
423
+ let attempt = 0;
424
+ const resolveWatchdog = () => {
425
+ if (retentionWatchdog !== void 0) clearTimeout(retentionWatchdog.timer);
426
+ retentionWatchdog = void 0;
427
+ if (activeRegistrations.size === 0 && activeTeardown === void 0) removeCoordinatorListeners();
428
+ };
429
+ const tick = () => {
430
+ if (info.pid !== void 0) {
431
+ let dead = false;
432
+ try {
433
+ process.kill(process.platform === "win32" ? info.pid : -info.pid, 0);
434
+ } catch (error) {
435
+ dead = isAlreadyGoneKillError(error);
436
+ }
437
+ if (dead) {
438
+ lock.release().then(() => resolveWatchdog(), (error) => {
439
+ process.stderr.write(`provision: the retained provision lock could not be released after the child's death was confirmed (${error.message}); the mutex self-heals once stale.\n`);
440
+ resolveWatchdog();
441
+ });
442
+ return;
443
+ }
444
+ }
445
+ try {
446
+ lock.quarantine(info);
447
+ resolveWatchdog();
448
+ return;
449
+ } catch {}
450
+ attempt += 1;
451
+ const delay = Math.min(RETENTION_RETRY_MIN_MS * 2 ** attempt, RETENTION_RETRY_MAX_MS);
452
+ if (retentionWatchdog !== void 0) retentionWatchdog.timer = setTimeout(tick, delay);
453
+ };
454
+ retentionWatchdog = {
455
+ lock,
456
+ info,
457
+ timer: setTimeout(tick, RETENTION_RETRY_MIN_MS)
458
+ };
459
+ }
460
+ /**
461
+ * Default runner: spawns the typed operation entry ({@link resolveCloudflareOperationArgv})
462
+ * without a shell; secrets go through stdin. It is async so the lock heartbeat keeps running.
463
+ */
464
+ function createDefaultRunWrangler(root, options) {
465
+ const launcher = options?.launcher ?? resolveCloudflareOperationArgv();
466
+ const timeoutMs = options?.timeoutMs ?? COMMAND_TIMEOUT_MS;
467
+ const confirmGraceMs = options?.confirmKillGraceMs ?? CONFIRM_KILL_GRACE_MS;
468
+ const killProcessGroup = options?.killProcessGroup ?? ((target, signal) => process.kill(target, signal));
469
+ const [command, ...prefix] = launcher;
470
+ const isWindows = process.platform === "win32";
471
+ const teardownDeadlineMs = options?.signalTeardownDeadlineMs ?? confirmGraceMs + SIGNAL_TEARDOWN_DEADLINE_MARGIN_MS;
472
+ return (args, opts) => new Promise((resolvePromise, rejectPromise) => {
473
+ const parallelWorkerUpload = options?.parallelWorkerUpload === true && args.type === "versions.upload";
474
+ const interactive = (args.type === "versions.upload" || args.type === "worker.deploy") && args.interactive === true;
475
+ if (activeTeardown !== void 0) {
476
+ rejectPromise(/* @__PURE__ */ new Error(`provision: refusing to spawn a Cloudflare operation process — a fatal ${activeTeardown.signal} is being handled and this process is terminating; no new Cloudflare operation may start.`));
477
+ return;
478
+ }
479
+ if (!canRegisterRunner(parallelWorkerUpload)) {
480
+ rejectPromise(/* @__PURE__ */ new Error("provision: refusing to spawn a Cloudflare operation process — another one is already active in this process (only two immutable Worker uploads may overlap; all other Cloudflare commands and provisions remain sequential)."));
481
+ return;
482
+ }
483
+ const child = spawn(command, [...prefix, ...encodeCloudflareOperation(args)], {
484
+ cwd: opts.cwd ?? root,
485
+ shell: false,
486
+ env: {
487
+ ...provisionEnv({
488
+ accountId: opts.accountId,
489
+ apiBaseUrl: opts.apiBaseUrl,
490
+ apiToken: opts.apiToken
491
+ }),
492
+ ...opts.suppressLogs ? { WRANGLER_WRITE_LOGS: "false" } : {}
493
+ },
494
+ stdio: interactive ? "inherit" : [
495
+ opts.input === void 0 ? "ignore" : "pipe",
496
+ "pipe",
497
+ "pipe"
498
+ ],
499
+ windowsHide: true,
500
+ detached: !isWindows
501
+ });
502
+ let stdout = "";
503
+ let stderr = "";
504
+ let timedOut = false;
505
+ let settled = false;
506
+ let spawned = false;
507
+ let postSpawnError;
508
+ let closed = false;
509
+ let groupGone = false;
510
+ child.once("spawn", () => {
511
+ spawned = true;
512
+ });
513
+ child.stdout?.setEncoding("utf-8");
514
+ child.stderr?.setEncoding("utf-8");
515
+ child.stdout?.on("data", (chunk) => {
516
+ stdout += chunk;
517
+ });
518
+ child.stderr?.on("data", (chunk) => {
519
+ stderr += chunk;
520
+ });
521
+ const signalGroup = (signal) => {
522
+ try {
523
+ if (!isWindows && typeof child.pid === "number") {
524
+ killProcessGroup(-child.pid, signal);
525
+ return "signaled";
526
+ }
527
+ if (isWindows && typeof child.pid === "number") {
528
+ if (child.exitCode !== null || child.signalCode !== null) return "gone";
529
+ killProcessGroup(child.pid, signal);
530
+ return "signaled";
531
+ }
532
+ if (child.kill(signal)) return "signaled";
533
+ if (child.exitCode !== null || child.signalCode !== null) return "gone";
534
+ return { error: /* @__PURE__ */ new Error(`child.kill(${signal}) returned false (signal not delivered)`) };
535
+ } catch (error) {
536
+ return isAlreadyGoneKillError(error) ? "gone" : { error };
537
+ }
538
+ };
539
+ /** True when the whole process group no longer exists (`kill(-pid, 0)` → ESRCH). */
540
+ const probeGroupGone = () => {
541
+ if (groupGone) return true;
542
+ if (typeof child.pid !== "number") {
543
+ groupGone = true;
544
+ return true;
545
+ }
546
+ if (isWindows) {
547
+ if (child.exitCode !== null || child.signalCode !== null) {
548
+ groupGone = true;
549
+ return true;
550
+ }
551
+ try {
552
+ process.kill(child.pid, 0);
553
+ } catch (error) {
554
+ groupGone = isAlreadyGoneKillError(error);
555
+ }
556
+ return groupGone;
557
+ }
558
+ try {
559
+ process.kill(-child.pid, 0);
560
+ } catch (error) {
561
+ groupGone = isAlreadyGoneKillError(error);
562
+ }
563
+ return groupGone;
564
+ };
565
+ const timeoutStderr = (extra) => [
566
+ stderr,
567
+ `provision: the Cloudflare operation process exceeded the ${timeoutMs}ms command timeout`,
568
+ extra
569
+ ].filter(Boolean).join("\n");
570
+ const deregisterSelf = () => deregisterRunner(registrant);
571
+ const finish = (result) => {
572
+ if (settled) return;
573
+ settled = true;
574
+ clearTimeout(commandTimer);
575
+ deregisterSelf();
576
+ resolvePromise(interactive ? result : decodeCloudflareOperationResult(result));
577
+ };
578
+ const quarantine = (detail) => {
579
+ if (settled) return;
580
+ settled = true;
581
+ clearTimeout(commandTimer);
582
+ deregisterSelf();
583
+ rejectPromise(new WranglerQuarantineError(child.pid, detail));
584
+ };
585
+ const confirmPollNudges = [];
586
+ const nudgeConfirmPolls = () => {
587
+ for (const poll of confirmPollNudges) poll();
588
+ };
589
+ const awaitConfirmedDead = (handlers) => {
590
+ const deadline = Date.now() + confirmGraceMs;
591
+ let pollTimer;
592
+ const poll = () => {
593
+ clearTimeout(pollTimer);
594
+ if (handlers.stopWhenSettled && settled) return;
595
+ if (closed && probeGroupGone()) {
596
+ handlers.onConfirmed();
597
+ return;
598
+ }
599
+ if (Date.now() >= deadline) {
600
+ handlers.onExpiry();
601
+ return;
602
+ }
603
+ pollTimer = setTimeout(poll, CONFIRM_KILL_POLL_MS);
604
+ };
605
+ confirmPollNudges.push(poll);
606
+ poll();
607
+ };
608
+ const confirmThenSettle = (makeResult, what) => {
609
+ awaitConfirmedDead({
610
+ stopWhenSettled: true,
611
+ onConfirmed: () => finish(makeResult()),
612
+ onExpiry: () => quarantine(`the process group could not be confirmed terminated within ${confirmGraceMs}ms of ${what}`)
613
+ });
614
+ };
615
+ const registrant = {
616
+ pid: () => child.pid,
617
+ signalGroup,
618
+ teardownDeadlineMs,
619
+ markGroupGone: () => {
620
+ groupGone = true;
621
+ },
622
+ awaitConfirmedDead: (onDone) => {
623
+ awaitConfirmedDead({
624
+ stopWhenSettled: false,
625
+ onConfirmed: () => onDone({ confirmed: true }),
626
+ onExpiry: () => onDone({
627
+ confirmed: false,
628
+ detail: `the process group did not terminate within ${confirmGraceMs}ms of the forwarded signal`
629
+ })
630
+ });
631
+ },
632
+ quarantine
633
+ };
634
+ const commandTimer = setTimeout(() => {
635
+ timedOut = true;
636
+ const outcome = signalGroup("SIGKILL");
637
+ if (typeof outcome === "object") {
638
+ quarantine(`the process group could not be killed: ${outcome.error.message}`);
639
+ return;
640
+ }
641
+ if (outcome === "gone") groupGone = true;
642
+ confirmThenSettle(() => normalizeRunWranglerResult({
643
+ stdout,
644
+ stderr: timeoutStderr(),
645
+ status: null,
646
+ signal: "SIGKILL"
647
+ }), `the timeout SIGKILL (${timeoutStderr()})`);
648
+ }, timeoutMs);
649
+ const handleProcessError = (error) => {
650
+ if (!spawned && typeof child.pid !== "number") {
651
+ finish(normalizeRunWranglerResult({
652
+ stdout,
653
+ stderr,
654
+ status: null,
655
+ signal: null,
656
+ error
657
+ }));
658
+ return;
659
+ }
660
+ if (settled || timedOut || postSpawnError !== void 0) return;
661
+ postSpawnError = error;
662
+ clearTimeout(commandTimer);
663
+ const outcome = signalGroup("SIGKILL");
664
+ if (typeof outcome === "object") {
665
+ quarantine(`a post-spawn child error (${error.message}) was followed by a failed process-group kill: ${outcome.error.message}`);
666
+ return;
667
+ }
668
+ if (outcome === "gone") groupGone = true;
669
+ confirmThenSettle(() => normalizeRunWranglerResult({
670
+ stdout,
671
+ stderr: [stderr, `provision: the spawned Cloudflare operation process emitted an error after spawn: ${error.message}`].filter(Boolean).join("\n"),
672
+ status: null,
673
+ signal: "SIGKILL"
674
+ }), `a post-spawn child error (${error.message}; the group was SIGKILLed)`);
675
+ };
676
+ child.on("error", handleProcessError);
677
+ child.stdin?.on("error", handleProcessError);
678
+ child.on("close", (code, signal) => {
679
+ closed = true;
680
+ if (code === 0 && child.stdin && !child.stdin.writableFinished) handleProcessError(/* @__PURE__ */ new Error("the Cloudflare operation process closed stdin before all input was written"));
681
+ if (timedOut || postSpawnError !== void 0) {
682
+ nudgeConfirmPolls();
683
+ return;
684
+ }
685
+ clearTimeout(commandTimer);
686
+ const makeResult = () => normalizeRunWranglerResult({
687
+ stdout,
688
+ stderr,
689
+ status: code,
690
+ signal
691
+ });
692
+ if (probeGroupGone()) {
693
+ finish(makeResult());
694
+ return;
695
+ }
696
+ const outcome = signalGroup("SIGKILL");
697
+ if (typeof outcome === "object") {
698
+ quarantine(`the child exited (status ${String(code)}) but its process group is still alive and could not be killed: ${outcome.error.message}`);
699
+ return;
700
+ }
701
+ if (outcome === "gone") groupGone = true;
702
+ confirmThenSettle(makeResult, `the child's exit (status ${String(code)}; surviving process-group members were SIGKILLed)`);
703
+ nudgeConfirmPolls();
704
+ });
705
+ registerRunner(registrant, parallelWorkerUpload);
706
+ options?.onSpawnedChild?.(child);
707
+ if (opts.input !== void 0) child.stdin?.end(opts.input);
708
+ });
709
+ }
710
+ /**
711
+ * Normalize a finished child into a {@link RunWranglerResult}. A signal, a spawn error or a
712
+ * non-numeric status is a non-zero failure, never success.
713
+ */
714
+ function normalizeRunWranglerResult(result) {
715
+ const stdout = result.stdout ?? "";
716
+ const notes = [];
717
+ if (result.signal != null) notes.push(`provision: the Cloudflare operation process was terminated by signal ${result.signal}`);
718
+ if (result.error != null) notes.push(`provision: the Cloudflare operation process could not be spawned: ${result.error.message}`);
719
+ const status = typeof result.status !== "number" || result.signal != null || result.error != null ? typeof result.status === "number" && result.status !== 0 ? result.status : 1 : result.status;
720
+ const baseStderr = result.stderr ?? "";
721
+ return {
722
+ stdout,
723
+ stderr: notes.length > 0 ? [baseStderr, ...notes].filter(Boolean).join("\n") : baseStderr,
724
+ status,
725
+ signal: result.signal ?? null,
726
+ error: result.error != null ? result.error.message : null
727
+ };
728
+ }
729
+ /** A signal-killed or unspawned child: its output is never read as success or absence. */
730
+ function isHardFailure(result) {
731
+ return result.signal != null || result.error != null;
732
+ }
733
+ /** The child ran to completion and reported SUCCESS (a clean numeric exit 0). */
734
+ function isCleanSuccess(result) {
735
+ return !isHardFailure(result) && result.status === 0;
736
+ }
737
+ /** A completed child with a non-zero exit: the only result that may mean "not found". */
738
+ function isCleanFailure(result) {
739
+ return !isHardFailure(result) && Number.isSafeInteger(result.status) && result.status > 0;
740
+ }
741
+ /** Overall deadline for the Hyperdrive lister, so a stalled list cannot hold the lock forever. */
742
+ const HYPERDRIVE_LIST_TIMEOUT_MS = 6e4;
743
+ /** Run `start` under an overall deadline: abort and reject at `ms`, even if it ignores the signal. */
744
+ function withListerDeadline(start, ms) {
745
+ return new Promise((resolve, reject) => {
746
+ const controller = new AbortController();
747
+ const timer = setTimeout(() => {
748
+ controller.abort();
749
+ reject(/* @__PURE__ */ new Error(`the existence check exceeded the ${ms}ms deadline`));
750
+ }, ms);
751
+ Promise.resolve().then(() => start(controller.signal)).then((value) => {
752
+ clearTimeout(timer);
753
+ resolve(value);
754
+ }, (error) => {
755
+ clearTimeout(timer);
756
+ reject(error);
757
+ });
758
+ });
759
+ }
760
+ /**
761
+ * API token for the Hyperdrive REST check: the caller's, else `CLOUDFLARE_API_TOKEN`. Shared by
762
+ * the up-front fence and the default lister so they always agree.
763
+ */
764
+ function resolveHyperdriveApiToken(apiToken) {
765
+ const token = apiToken ?? process.env.CLOUDFLARE_API_TOKEN;
766
+ return typeof token === "string" && token.length > 0 ? token : void 0;
767
+ }
768
+ /**
769
+ * Default Hyperdrive lister over the REST API. Returns `undefined` without a token, so the
770
+ * caller fails closed before a blind create.
771
+ */
772
+ function createDefaultListHyperdriveConfigs(apiToken) {
773
+ const token = resolveHyperdriveApiToken(apiToken);
774
+ if (!token) return;
775
+ return async ({ accountId, apiBaseUrl, signal }) => {
776
+ const perPage = 100;
777
+ const listUrl = (page) => `${apiBaseUrl}/accounts/${accountId}/hyperdrive/configs?page=${page}&per_page=${perPage}`;
778
+ const byId = /* @__PURE__ */ new Map();
779
+ let expectedTotal;
780
+ for (let page = 1;; page++) {
781
+ const res = await fetch(listUrl(page), {
782
+ headers: { Authorization: `Bearer ${token}` },
783
+ signal
784
+ });
785
+ if (!res.ok) throw new Error(`Cloudflare API returned HTTP ${res.status} listing Hyperdrive configs`);
786
+ const body = await res.json();
787
+ if (!isRecord(body) || body.success !== true || !Array.isArray(body.result)) throw new Error("Cloudflare API returned an unsuccessful or malformed Hyperdrive configs payload");
788
+ const info = body.result_info;
789
+ const totalCount = isRecord(info) && typeof info.total_count === "number" && Number.isInteger(info.total_count) ? info.total_count : void 0;
790
+ if (totalCount === void 0 || totalCount < 0) throw new Error("Cloudflare API returned Hyperdrive configs without valid pagination metadata (result_info.total_count); cannot prove the list is complete");
791
+ if (expectedTotal === void 0) expectedTotal = totalCount;
792
+ else if (totalCount !== expectedTotal) throw new Error("Cloudflare API returned inconsistent Hyperdrive pagination totals across pages; cannot prove the list is complete");
793
+ if (body.result.length === 0 && byId.size < expectedTotal) throw new Error("Cloudflare API returned an empty Hyperdrive page before all configs were listed; cannot prove the list is complete");
794
+ for (const entry of body.result) {
795
+ if (!isRecord(entry) || typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.name !== "string" || entry.name.length === 0) throw new Error("Cloudflare API returned a malformed Hyperdrive config entry (missing id/name)");
796
+ if (byId.has(entry.id)) throw new Error("Cloudflare API returned a duplicate Hyperdrive config id across pages; cannot prove the list is complete");
797
+ byId.set(entry.id, {
798
+ id: entry.id,
799
+ name: entry.name
800
+ });
801
+ }
802
+ if (byId.size > expectedTotal) throw new Error("Cloudflare API returned more Hyperdrive configs than result_info.total_count; cannot prove the list is complete");
803
+ if (byId.size === expectedTotal) break;
804
+ }
805
+ return [...byId.values()];
806
+ };
807
+ }
808
+ /**
809
+ * Validate a Hyperdrive list from any lister and return the config named `name`, if any. A
810
+ * malformed member, a bad or duplicate id, or more than one match fails closed.
811
+ */
812
+ function selectHyperdriveMatch(configs, name, configPath) {
813
+ const seenIds = /* @__PURE__ */ new Set();
814
+ const validated = [];
815
+ for (const config of configs) {
816
+ if (!isRecord(config) || typeof config.id !== "string" || config.id.length === 0 || typeof config.name !== "string" || config.name.length === 0) throw new Error(`provision: the Hyperdrive existence check returned a malformed config entry (each must be an object with a non-empty string id and name). Cannot verify whether ${JSON.stringify(name)} already exists; refusing to create a possible duplicate.`);
817
+ if (!isRealHyperdriveId(config.id)) throw new Error(`provision: the Hyperdrive existence check returned a config ${JSON.stringify(config.name)} with a malformed id ${JSON.stringify(config.id)} (expected a 32-character hex Hyperdrive id). Cannot verify whether ${JSON.stringify(name)} already exists; refusing to create a possible duplicate.`);
818
+ if (seenIds.has(config.id)) throw new Error(`provision: the Hyperdrive existence check returned a duplicate config id ${JSON.stringify(config.id)}. Cannot verify existing configs; refusing to create a possible duplicate.`);
819
+ seenIds.add(config.id);
820
+ validated.push({
821
+ id: config.id,
822
+ name: config.name
823
+ });
824
+ }
825
+ const named = validated.filter((c) => c.name === name);
826
+ if (named.length > 1) throw new Error(`provision: cannot adopt Hyperdrive config ${JSON.stringify(name)} — ${named.length} configs in this account share that name (ids: ${named.map((c) => c.id).join(", ")}). Hyperdrive names are not account-unique; remove the duplicates or pin the id in "${configPath}", then retry.`);
827
+ return named[0];
828
+ }
829
+ /** The quarantine sidecar path for a lock target. */
830
+ function quarantineSidecarPath(lockTarget) {
831
+ return `${lockTarget}.quarantine.json`;
832
+ }
833
+ /**
834
+ * Persist quarantine metadata durably (temp file, fsync, rename, directory fsync), then read it
835
+ * back. Throws on any failure.
836
+ */
837
+ function writeQuarantineSidecar(sidecarPath, info, dirDurability) {
838
+ const payload = JSON.stringify({
839
+ pid: info.pid ?? null,
840
+ pgid: process.platform === "win32" ? null : info.pid ?? null,
841
+ reason: info.reason,
842
+ quarantinedAt: (/* @__PURE__ */ new Date()).toISOString(),
843
+ quarantinedBy: process.pid,
844
+ generation: `${randomUUID()}.${process.hrtime.bigint().toString()}`
845
+ }, null, 2);
846
+ const tmpPath = `${sidecarPath}.tmp-${process.pid}`;
847
+ try {
848
+ const fd = openSync(tmpPath, "w");
849
+ try {
850
+ writeSync(fd, payload);
851
+ fsyncSync(fd);
852
+ } finally {
853
+ closeSync(fd);
854
+ }
855
+ renameSync(tmpPath, sidecarPath);
856
+ } catch (error) {
857
+ try {
858
+ unlinkSync(tmpPath);
859
+ } catch {}
860
+ throw error;
861
+ }
862
+ const dirOpen = dirDurability?.openSync ?? openSync;
863
+ const dirFsync = dirDurability?.fsyncSync ?? fsyncSync;
864
+ const dirClose = dirDurability?.closeSync ?? closeSync;
865
+ try {
866
+ const dirFd = dirOpen(dirname(sidecarPath), "r");
867
+ try {
868
+ dirFsync(dirFd);
869
+ } finally {
870
+ dirClose(dirFd);
871
+ }
872
+ } catch (error) {
873
+ const code = error.code ?? "";
874
+ if (![
875
+ "EISDIR",
876
+ "EPERM",
877
+ "EINVAL",
878
+ "ENOTSUP",
879
+ "ENOSYS"
880
+ ].includes(code)) {
881
+ try {
882
+ unlinkSync(sidecarPath);
883
+ } catch {}
884
+ throw error;
885
+ }
886
+ }
887
+ const readBack = JSON.parse(readFileSync(sidecarPath, "utf-8"));
888
+ if (!isRecord(readBack) || readBack.pid !== (info.pid ?? null) || readBack.reason !== info.reason) throw new Error(`the quarantine sidecar "${sidecarPath}" did not verify after writing`);
889
+ }
890
+ function readPositiveInt(value) {
891
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
892
+ }
893
+ /**
894
+ * Quarantine gate, run under the recovery mutex before each lock attempt. With a sidecar
895
+ * present, the recorded group is probed: confirmed dead clears the sidecar, alive or unknown
896
+ * fails closed. Only the sidecar generation that was inspected is cleared; the mutex directory
897
+ * is left for proper-lockfile's stale handling, since removing it by hand could race another
898
+ * acquirer.
899
+ */
900
+ function assertQuarantineClearedOrClear(lockTarget, onBeforeClear) {
901
+ const sidecarPath = quarantineSidecarPath(lockTarget);
902
+ if (!existsSync(sidecarPath)) return;
903
+ let recorded;
904
+ try {
905
+ const parsed = JSON.parse(readFileSync(sidecarPath, "utf-8"));
906
+ recorded = isRecord(parsed) ? parsed : void 0;
907
+ } catch {
908
+ recorded = void 0;
909
+ }
910
+ const pid = readPositiveInt(recorded?.pid);
911
+ const pgid = readPositiveInt(recorded?.pgid);
912
+ const reason = typeof recorded?.reason === "string" ? recorded.reason : void 0;
913
+ const quarantinedAt = typeof recorded?.quarantinedAt === "string" ? recorded.quarantinedAt : void 0;
914
+ const probeTarget = pgid !== void 0 && process.platform !== "win32" ? -pgid : pid ?? pgid;
915
+ let confirmedDead = false;
916
+ if (probeTarget !== void 0) try {
917
+ process.kill(probeTarget, 0);
918
+ } catch (error) {
919
+ confirmedDead = isAlreadyGoneKillError(error);
920
+ }
921
+ if (!confirmedDead) {
922
+ const who = pid !== void 0 || pgid !== void 0 ? `process group ${String(pgid ?? pid)}` : "an unrecorded process";
923
+ throw new Error(`provision: refusing to provision — a previous provision QUARANTINED this config's lock because a spawned Cloudflare operation process could not be confirmed terminated (${who}${quarantinedAt ? `, quarantined at ${quarantinedAt}` : ""}${reason ? `; reason: ${reason}` : ""}). It may still be creating resources. Verify the process is dead (e.g. \`kill -0 ${String(pid ?? "<pid>")}\`; terminate it if not) and re-run — the quarantine then clears automatically. If you are CERTAIN the recorded process is unrelated (pid reuse) or gone, remove "${sidecarPath}" and the "${lockTarget}.lock" directory manually, then retry.`);
924
+ }
925
+ const inspectedGeneration = typeof recorded?.generation === "string" ? recorded.generation : void 0;
926
+ onBeforeClear?.();
927
+ let current;
928
+ try {
929
+ const reread = JSON.parse(readFileSync(sidecarPath, "utf-8"));
930
+ current = isRecord(reread) ? reread : void 0;
931
+ } catch (error) {
932
+ if (error.code === "ENOENT") return;
933
+ current = void 0;
934
+ }
935
+ const currentGeneration = typeof current?.generation === "string" ? current.generation : void 0;
936
+ if (current === void 0 || currentGeneration !== inspectedGeneration) throw new Error(`provision: refusing to clear the quarantine sidecar "${sidecarPath}" — it changed while this recovery decision was being made (a newer quarantine generation was persisted). Re-run to re-evaluate the current quarantine.`);
937
+ try {
938
+ unlinkSync(sidecarPath);
939
+ } catch (error) {
940
+ if (error.code !== "ENOENT") throw error;
941
+ }
942
+ }
943
+ function loadProperLockfileInternals() {
944
+ try {
945
+ return createRequire(import.meta.url)("proper-lockfile/lib/lockfile.js");
946
+ } catch {
947
+ return;
948
+ }
949
+ }
950
+ /** `realpathSync` returns backslashes on Windows; normalize so one file has one spelling. */
951
+ function toPosixConfigPath(nativePath) {
952
+ return process.platform === "win32" ? normalize(nativePath) : nativePath;
953
+ }
954
+ /**
955
+ * Canonical config path, so symlink aliases share one lock identity. A dangling symlink is
956
+ * followed; a missing file canonicalizes its parent directory instead.
957
+ */
958
+ function canonicalizeConfigPath(absoluteConfigPath, depth = 0) {
959
+ try {
960
+ return toPosixConfigPath(realpathSync(absoluteConfigPath));
961
+ } catch (error) {
962
+ if (error.code !== "ENOENT") throw error;
963
+ }
964
+ let linkStat;
965
+ try {
966
+ linkStat = lstatSync(absoluteConfigPath);
967
+ } catch {
968
+ linkStat = void 0;
969
+ }
970
+ if (linkStat?.isSymbolicLink()) {
971
+ if (depth >= 40) throw Object.assign(/* @__PURE__ */ new Error(`ELOOP: too many symbolic links while resolving "${absoluteConfigPath}"`), { code: "ELOOP" });
972
+ const target = readlinkSync(absoluteConfigPath);
973
+ return canonicalizeConfigPath(resolve$2(dirname(absoluteConfigPath), target), depth + 1);
974
+ }
975
+ const dir = dirname(absoluteConfigPath);
976
+ try {
977
+ return join(realpathSync(dir), basename(absoluteConfigPath));
978
+ } catch (error) {
979
+ if (error.code !== "ENOENT") throw error;
980
+ return absoluteConfigPath;
981
+ }
982
+ }
983
+ /**
984
+ * A lock not refreshed for this long counts as abandoned. A live owner refreshes it every
985
+ * {@link LOCK_UPDATE_MS}; this needs a free event loop, which is why the runner is async.
986
+ */
987
+ const LOCK_STALE_MS = 12e4;
988
+ /** Refresh interval keeping a live owner's lock fresh (must be < {@link LOCK_STALE_MS}). */
989
+ const LOCK_UPDATE_MS = 2e4;
990
+ /** Backoff while waiting for a held lock (about a minute). */
991
+ const LOCK_RETRIES = {
992
+ retries: 100,
993
+ factor: 1.5,
994
+ minTimeout: 200,
995
+ maxTimeout: 2e3
996
+ };
997
+ /** Stale window of the short-lived recovery mutex. */
998
+ const RECOVERY_LOCK_STALE_MS = 6e3;
999
+ /** Backoff schedule for our own retry loop (proper-lockfile runs with `retries: 0`). */
1000
+ function normalizeLockRetries(retries) {
1001
+ if (typeof retries === "number") return {
1002
+ ...LOCK_RETRIES,
1003
+ retries
1004
+ };
1005
+ return {
1006
+ retries: retries?.retries ?? LOCK_RETRIES.retries,
1007
+ factor: retries?.factor ?? LOCK_RETRIES.factor,
1008
+ minTimeout: retries?.minTimeout ?? LOCK_RETRIES.minTimeout,
1009
+ maxTimeout: retries?.maxTimeout ?? LOCK_RETRIES.maxTimeout
1010
+ };
1011
+ }
1012
+ /** The registry key proper-lockfile uses with `realpath: false` (native separators). */
1013
+ function resolveProperLockfileKey(file, platform = process.platform) {
1014
+ return platform === "win32" ? resolve$1(file) : resolve(file);
1015
+ }
1016
+ /**
1017
+ * Acquire the provision lock (`<configPath>.bwf-provision.lock.lock`). The lock targets are
1018
+ * synthetic paths, so `realpath: false` avoids creating marker files; the config path is
1019
+ * already canonical. A compromised lock throws.
1020
+ *
1021
+ * Each attempt runs under a short recovery mutex: quarantine gate, one non-retrying
1022
+ * acquisition, then the gate again under ownership. This loop owns retries, so the gate runs
1023
+ * on every attempt and a quarantined lock is never taken over by age.
1024
+ */
1025
+ async function acquireProvisionLock(configPath, lockOptions) {
1026
+ const lockTarget = `${configPath}.bwf-provision.lock`;
1027
+ const recoveryTarget = `${lockTarget}.recovery`;
1028
+ const staleMs = lockOptions?.stale ?? LOCK_STALE_MS;
1029
+ const retryCfg = normalizeLockRetries(lockOptions?.retries);
1030
+ const isElocked = (error) => error?.code === "ELOCKED";
1031
+ const backoffDelay = (attempt) => new Promise((resolveSleep) => setTimeout(resolveSleep, Math.min(retryCfg.minTimeout * retryCfg.factor ** attempt, retryCfg.maxTimeout)));
1032
+ const acquireOnce = () => lockfile.lock(lockTarget, {
1033
+ stale: staleMs,
1034
+ update: lockOptions?.update ?? LOCK_UPDATE_MS,
1035
+ retries: 0,
1036
+ realpath: false,
1037
+ ...lockOptions?.fs !== void 0 ? { fs: lockOptions.fs } : {},
1038
+ onCompromised: (error) => {
1039
+ throw error;
1040
+ }
1041
+ });
1042
+ const acquireRecoveryOnce = () => lockfile.lock(recoveryTarget, {
1043
+ stale: RECOVERY_LOCK_STALE_MS,
1044
+ retries: 0,
1045
+ realpath: false,
1046
+ onCompromised: (error) => {
1047
+ throw error;
1048
+ }
1049
+ });
1050
+ let release;
1051
+ for (let attempt = 0;; attempt++) {
1052
+ let releaseRecovery;
1053
+ try {
1054
+ releaseRecovery = await acquireRecoveryOnce();
1055
+ } catch (error) {
1056
+ if (isElocked(error) && attempt < retryCfg.retries) {
1057
+ await backoffDelay(attempt);
1058
+ continue;
1059
+ }
1060
+ throw error;
1061
+ }
1062
+ let mainHeldByOther = false;
1063
+ try {
1064
+ assertQuarantineClearedOrClear(lockTarget, lockOptions?.onBeforeQuarantineClear);
1065
+ try {
1066
+ release = await acquireOnce();
1067
+ } catch (error) {
1068
+ if (isElocked(error) && attempt < retryCfg.retries) mainHeldByOther = true;
1069
+ else throw error;
1070
+ }
1071
+ if (!mainHeldByOther) try {
1072
+ assertQuarantineClearedOrClear(lockTarget, lockOptions?.onBeforeQuarantineClear);
1073
+ } catch (gateError) {
1074
+ let revalidateReleaseError;
1075
+ try {
1076
+ await release();
1077
+ } catch (error) {
1078
+ revalidateReleaseError = error;
1079
+ }
1080
+ release = void 0;
1081
+ if (revalidateReleaseError !== void 0) throw new AggregateError([gateError, revalidateReleaseError], `provision: a quarantine was found right after acquiring the provision lock AND the fresh lock could not be released afterward. Quarantine: ${gateError.message}; release error: ${revalidateReleaseError.message}`, { cause: gateError });
1082
+ throw gateError;
1083
+ }
1084
+ } finally {
1085
+ try {
1086
+ await releaseRecovery();
1087
+ } catch {}
1088
+ }
1089
+ if (!mainHeldByOther) break;
1090
+ await backoffDelay(attempt);
1091
+ }
1092
+ const acquiredRelease = release;
1093
+ let releasePromise;
1094
+ const doRelease = async () => {
1095
+ try {
1096
+ await acquiredRelease();
1097
+ } catch (error) {
1098
+ if (error?.code === "ERELEASED") return;
1099
+ throw new Error(`provision: failed to release the cross-process provision lock "${lockTarget}.lock" (${error.message}). The mutex directory may still exist and will block future provisions until it goes stale (~${Math.round(staleMs / 1e3)}s). Remove it manually if it persists, then retry.`);
1100
+ }
1101
+ };
1102
+ return {
1103
+ lockTargetPath: lockTarget,
1104
+ release: () => releasePromise ??= doRelease(),
1105
+ quarantine: (info) => {
1106
+ if (releasePromise !== void 0) return;
1107
+ try {
1108
+ writeQuarantineSidecar(quarantineSidecarPath(lockTarget), info, lockOptions?.dirDurability);
1109
+ } catch (error) {
1110
+ throw new Error(`provision: could not persist quarantine metadata to "${quarantineSidecarPath(lockTarget)}" (${error.message}). The cross-process provision lock "${lockTarget}.lock" is intentionally STILL HELD by this process (tracked, heartbeat running) so it cannot go stale and be stolen while the unconfirmed Cloudflare operation process${info.pid !== void 0 ? ` (pid ${info.pid})` : ""} may still be running. Manual recovery: verify the process is dead${info.pid !== void 0 ? ` (e.g. \`kill -0 ${info.pid}\`)` : ""} and terminate it if not; the lock is freed when this process exits — remove the "${lockTarget}.lock" directory if it persists, then re-run.`);
1111
+ }
1112
+ releasePromise = Promise.resolve();
1113
+ const locks = loadProperLockfileInternals()?.getLocks?.();
1114
+ if (!locks) return;
1115
+ const key = resolveProperLockfileKey(lockTarget);
1116
+ const tracked = locks[key];
1117
+ if (tracked) {
1118
+ tracked.released = true;
1119
+ if (tracked.updateTimeout !== void 0) clearTimeout(tracked.updateTimeout);
1120
+ delete locks[key];
1121
+ }
1122
+ }
1123
+ };
1124
+ }
1125
+ /** One binding entry, via the strict reader that fails on duplicate or colliding bindings. */
1126
+ function readBindingEntry(configPath, field, binding) {
1127
+ return readProvisionedBindingEntry(readRootConfig(configPath), field, binding, configPath);
1128
+ }
1129
+ /**
1130
+ * Read the root config fresh (wrangler edits it), without a BOM. A parse error or a non-object
1131
+ * fails; a missing file reads as `{}`.
1132
+ */
1133
+ function readRootConfig(configPath) {
1134
+ if (!existsSync(configPath)) return {};
1135
+ const raw = readFileSync(configPath, "utf-8");
1136
+ const content = raw.startsWith(UTF8_BOM) ? raw.slice(1) : raw;
1137
+ const errors = [];
1138
+ const parsed = parse(content, errors, { allowTrailingComma: true });
1139
+ if (errors.length > 0) throw new Error(`provision: cannot read "${configPath}" — it is not valid JSON/JSONC. Fix the file and retry.`);
1140
+ if (!isRecord(parsed)) throw new Error(`provision: "${configPath}" must be a JSON object.`);
1141
+ return parsed;
1142
+ }
1143
+ /** Throw unless a discovery call exited cleanly, so a failed list never means "absent". */
1144
+ function assertDiscoverySucceeded(result, label) {
1145
+ if (!isCleanSuccess(result)) throw new Error(`provision: ${label} failed (exit ${String(result.status)}): ${result.stderr || result.stdout || "no output"}. Cannot verify existing resources; refusing to create a possible duplicate.`);
1146
+ }
1147
+ /**
1148
+ * Reject the whole list if any member lacks a non-empty name or a valid id. A malformed member
1149
+ * could be the target, so it is never filtered out as "absent".
1150
+ */
1151
+ function validateResourceList(list, spec) {
1152
+ const validated = [];
1153
+ for (const member of list) {
1154
+ if (!isRecord(member)) throw new Error(`provision: ${spec.command} returned a malformed ${spec.resource} entry (not an object). Cannot verify existing resources; refusing to create a possible duplicate.`);
1155
+ const rawName = member[spec.nameField];
1156
+ const nameValid = typeof rawName === "string" && rawName.length > 0;
1157
+ const idValid = spec.hasValidId(member);
1158
+ if (nameValid && !idValid) throw new Error(`provision: ${spec.command} returned a ${spec.resource} ${spec.nameLabel} ${JSON.stringify(rawName)} with no valid id (${spec.idRule}). Cannot verify existing resources; refusing to create a possible duplicate.`);
1159
+ if (!nameValid) throw new Error(`provision: ${spec.command} returned a malformed ${spec.resource} entry with no valid ${spec.nameField}. Cannot verify existing resources; refusing to create a possible duplicate.`);
1160
+ validated.push(member);
1161
+ }
1162
+ return validated;
1163
+ }
1164
+ function reconcileD1IdAliases(entry) {
1165
+ const present = [entry.database_id, entry.uuid].filter((value) => value !== void 0 && value !== "");
1166
+ if (present.length === 0) return { kind: "absent" };
1167
+ const ids = /* @__PURE__ */ new Set();
1168
+ for (const value of present) {
1169
+ if (!isRealD1Id(value)) return { kind: "invalid" };
1170
+ ids.add(value);
1171
+ }
1172
+ if (ids.size !== 1) return { kind: "invalid" };
1173
+ return {
1174
+ kind: "id",
1175
+ id: [...ids][0]
1176
+ };
1177
+ }
1178
+ /**
1179
+ * Strict D1 identity check shared by `d1 list` and `d1 info`. `other` when no name alias
1180
+ * (`name`, `database_name`) equals `requestedName`; `claimed-but-invalid` when one does but the
1181
+ * name or id aliases conflict; otherwise `match`.
1182
+ */
1183
+ function normalizeD1(entry, requestedName) {
1184
+ if (entry === void 0) return { kind: "other" };
1185
+ const names = [entry.name, entry.database_name].filter((value) => typeof value === "string" && value.length > 0);
1186
+ if (!names.includes(requestedName)) return { kind: "other" };
1187
+ if (new Set(names).size > 1) return { kind: "claimed-but-invalid" };
1188
+ const reconciled = reconcileD1IdAliases(entry);
1189
+ if (reconciled.kind !== "id") return { kind: "claimed-but-invalid" };
1190
+ return {
1191
+ kind: "match",
1192
+ id: reconciled.id
1193
+ };
1194
+ }
1195
+ /** True when a `d1 create` failure means the name is already taken (code 7502). */
1196
+ function isAlreadyExistsError(result) {
1197
+ return result.errorCode === 7502;
1198
+ }
1199
+ /**
1200
+ * True only for a completed non-zero probe with the provider's typed not-found result (R2
1201
+ * code 10006, or the queue operation's `not-found`). Nothing else counts as absence.
1202
+ */
1203
+ function isConfirmedAbsent(result, kind) {
1204
+ return isCleanFailure(result) && (kind === "r2" ? result.errorCode === 10006 : result.failure === "not-found");
1205
+ }
1206
+ /** Only a completed, typed not-found response confirms queue absence. */
1207
+ function isQueueConfirmedAbsent(result) {
1208
+ return isConfirmedAbsent(result, "queue");
1209
+ }
1210
+ /** Reuse and post-create verification require clean success and the exact returned name. */
1211
+ function queueInfoConfirmsExists(result, name) {
1212
+ return isCleanSuccess(result) && isRecord(result.data) && result.data.name === name;
1213
+ }
1214
+ /** Throw when the writer found no D1 entry to attach `migrations_dir` to. */
1215
+ function assertD1MigrationsDirApplied(result, binding, configPath) {
1216
+ if (result.d1MigrationsDirSkipped) throw new Error(`provision: could not set migrations_dir for D1 binding ${JSON.stringify(binding)} — no matching d1_databases entry exists in "${configPath}" after provisioning it. The D1 resource was not written to the config as expected; inspect the file and retry.`);
1217
+ }
1218
+ /**
1219
+ * After a create reports success, re-read the config and require a real id, plus the exact
1220
+ * name where the name is the identity. A success status alone is not trusted.
1221
+ */
1222
+ function assertCreateWroteRealId(configPath, spec, binding, name) {
1223
+ const entry = readBindingEntry(configPath, spec.field, binding);
1224
+ const idOk = !!entry && spec.idValidator(entry[spec.idField]);
1225
+ const nameOk = spec.nameField === void 0 || !!entry && entry[spec.nameField] === name;
1226
+ if (!idOk || !nameOk) throw new Error(`provision: ${spec.command} ${name} reported success but "${configPath}" does not hold the expected ${spec.resource} for binding ${JSON.stringify(binding)} afterward (need a real ${spec.idField}${spec.nameField ? ` and ${spec.nameField} === ${JSON.stringify(name)}` : ""}). The create may have been interrupted or written a different resource. Refusing to record a wrong/unprovisioned resource; inspect the account/config and retry.`);
1227
+ }
1228
+ /** True when `value` contains an ASCII control character (0x00–0x1F or 0x7F). */
1229
+ function hasControlChar(value) {
1230
+ for (let i = 0; i < value.length; i++) {
1231
+ const code = value.charCodeAt(i);
1232
+ if (code < 32 || code === 127) return true;
1233
+ }
1234
+ return false;
1235
+ }
1236
+ /** The universal option-injection guard for ANY Cloudflare operation ARGV positional. */
1237
+ function assertNoOptionInjection(kind, name) {
1238
+ if (typeof name !== "string" || name.length === 0 || name.startsWith("-") || hasControlChar(name)) throw new Error(`provision: refusing to pass an unsafe ${kind} name ${JSON.stringify(name)} to a Cloudflare operation. A name may not be empty, begin with "-" (it would be parsed as a CLI flag), or contain control characters. Rename the resource and retry.`);
1239
+ }
1240
+ /** Per-resource Cloudflare naming grammar. KV titles may contain spaces and mixed case. */
1241
+ const RESOURCE_NAME_GRAMMARS = {
1242
+ r2: {
1243
+ re: R2_BUCKET_NAME_RE,
1244
+ label: "R2 bucket",
1245
+ rule: "be 3–63 characters, contain only lowercase letters, digits and \"-\", and begin and end with a letter or digit"
1246
+ },
1247
+ kvTitle: {
1248
+ re: /^[\s\S]{1,512}$/,
1249
+ label: "KV namespace",
1250
+ rule: "be 1–512 characters and contain no control characters (spaces are allowed)"
1251
+ },
1252
+ d1: {
1253
+ re: /^[A-Za-z0-9][A-Za-z0-9_-]{0,62}$/,
1254
+ label: "D1 database",
1255
+ rule: "be 1–63 characters, start with a letter or digit, and contain only letters, digits, \"-\" or \"_\""
1256
+ },
1257
+ hyperdrive: {
1258
+ re: /^[A-Za-z0-9][A-Za-z0-9_-]{0,62}$/,
1259
+ label: "Hyperdrive config",
1260
+ rule: "be 1–63 characters, start with a letter or digit, and contain only letters, digits, \"-\" or \"_\""
1261
+ },
1262
+ queue: {
1263
+ re: /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/,
1264
+ label: "queue",
1265
+ rule: "be 1–63 characters, contain only letters, digits and \"-\", and begin and end with a letter or digit"
1266
+ }
1267
+ };
1268
+ /** Validate an argv positional: the option-injection guard, then the resource grammar. */
1269
+ function assertValidResourceName(kind, name) {
1270
+ assertNoOptionInjection(RESOURCE_NAME_GRAMMARS[kind].label, name);
1271
+ const grammar = RESOURCE_NAME_GRAMMARS[kind];
1272
+ if (!grammar.re.test(name)) throw new Error(`provision: refusing to pass an invalid ${grammar.label} name ${JSON.stringify(name)} to a Cloudflare operation. A ${grammar.label} name must ${grammar.rule}. Rename the resource and retry.`);
1273
+ }
1274
+ /** Redactor that replaces the exact connection string and masks any URL userinfo password. */
1275
+ function createSecretRedactor(connectionString) {
1276
+ return (text) => {
1277
+ let out = text;
1278
+ if (typeof connectionString === "string" && connectionString.length > 0) out = out.split(connectionString).join("[REDACTED]");
1279
+ out = out.replace(/(\w[\w+.-]*:\/\/[^\s/@:]+:)[^\s@/]+(@)/g, "$1[REDACTED]$2");
1280
+ return out;
1281
+ };
1282
+ }
1283
+ /** Redact a runner rejection, keeping the same Error object so quarantine fields survive. */
1284
+ function redactRejection(error, redactText) {
1285
+ if (!(error instanceof Error)) return new Error(redactText(String(error)));
1286
+ error.message = redactText(error.message);
1287
+ if (typeof error.stack === "string") error.stack = redactText(error.stack);
1288
+ return error;
1289
+ }
1290
+ /**
1291
+ * Ensure every desired resource exists in the user's Cloudflare account and record its id in
1292
+ * the root config, creating or adopting as needed. A binding with a real id is left as is.
1293
+ */
1294
+ async function provisionCloudflareResources(root, rootWranglerPath, desired, opts) {
1295
+ const releaseProvisionSlot = acquireProcessProvisionSlot();
1296
+ try {
1297
+ return await provisionWithProcessSlot(root, rootWranglerPath, desired, opts);
1298
+ } finally {
1299
+ releaseProvisionSlot();
1300
+ }
1301
+ }
1302
+ /** The provision body, run while holding this process's single provision slot. */
1303
+ async function provisionWithProcessSlot(root, rootWranglerPath, desired, opts) {
1304
+ const configPath = canonicalizeConfigPath(resolve$2(root, rootWranglerPath));
1305
+ const lock = await acquireProvisionLock(configPath, opts?.lockOptions);
1306
+ const quarantineHook = (info) => retainQuarantinedLock(lock, info);
1307
+ activeProvisionQuarantineHook = quarantineHook;
1308
+ let result;
1309
+ let threw = false;
1310
+ let bodyError;
1311
+ try {
1312
+ result = await provisionCloudflareResourcesLocked(root, configPath, desired, opts);
1313
+ } catch (error) {
1314
+ threw = true;
1315
+ bodyError = error;
1316
+ }
1317
+ if (activeProvisionQuarantineHook === quarantineHook) activeProvisionQuarantineHook = void 0;
1318
+ if (threw) {
1319
+ if (isQuarantineError(bodyError)) {
1320
+ try {
1321
+ retainQuarantinedLock(lock, {
1322
+ pid: typeof bodyError.pid === "number" ? bodyError.pid : void 0,
1323
+ reason: typeof bodyError.message === "string" ? bodyError.message : String(bodyError)
1324
+ });
1325
+ } catch (quarantineError) {
1326
+ throw new AggregateError([bodyError, quarantineError], `provision failed with an unconfirmed Cloudflare operation process AND its quarantine metadata could not be persisted — the cross-process provision lock is intentionally still held by this process (not released, not stealable) while the child may live. Primary error: ${bodyError instanceof Error ? bodyError.message : String(bodyError)}; quarantine error: ${quarantineError instanceof Error ? quarantineError.message : String(quarantineError)}.`, { cause: bodyError });
1327
+ }
1328
+ throw bodyError;
1329
+ }
1330
+ let releaseError;
1331
+ try {
1332
+ await lock.release();
1333
+ } catch (error) {
1334
+ releaseError = error;
1335
+ }
1336
+ if (releaseError !== void 0) throw new AggregateError([bodyError, releaseError], `provision failed AND the cross-process provision lock could not be released afterward — a leaked mutex may block future provisions. Primary error: ${bodyError instanceof Error ? bodyError.message : String(bodyError)}; release error: ${releaseError instanceof Error ? releaseError.message : String(releaseError)}.`, { cause: bodyError });
1337
+ throw bodyError;
1338
+ }
1339
+ await lock.release();
1340
+ return result;
1341
+ }
1342
+ async function enableD1ReadReplicationViaApi(context, token, fetchImpl = fetch) {
1343
+ const response = await fetchImpl(`${context.apiBaseUrl}/accounts/${context.accountId}/d1/database/${context.databaseId}`, {
1344
+ method: "PUT",
1345
+ headers: {
1346
+ Authorization: `Bearer ${token}`,
1347
+ "Content-Type": "application/json"
1348
+ },
1349
+ body: JSON.stringify({ read_replication: { mode: "auto" } }),
1350
+ signal: AbortSignal.timeout(15e3)
1351
+ });
1352
+ const envelope = await response.json().catch(() => null);
1353
+ if (!response.ok || envelope?.success !== true) throw new Error(`provision: could not enable D1 read replication for database ${context.databaseId} (Cloudflare API status ${response.status}). The credential needs D1 Edit permission.`);
1354
+ }
1355
+ async function reconcileD1(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log, transportAccountId, transportApiBaseUrl, opts) {
1356
+ if (desired.d1) {
1357
+ const { binding, name } = desired.d1;
1358
+ const migrationsDir = desired.d1.migrationsDir ?? D1_MIGRATIONS_DIR;
1359
+ const entry = readBindingEntry(configPath, "d1_databases", binding);
1360
+ if (entry && isRealD1Id(entry.database_id)) {
1361
+ const storedName = entry.database_name;
1362
+ if (storedName !== void 0 && storedName !== name) throw new Error(`provision: D1 binding ${JSON.stringify(binding)} in "${configPath}" stores database_name ${JSON.stringify(storedName)} (with a real database_id), but this deploy wants database ${JSON.stringify(name)}. Refusing to reuse a database that contradicts the desired name. Fix "${configPath}" — correct the entry's database_name/database_id (or remove the entry to re-provision) — or rename the desired database, then retry.`);
1363
+ assertD1MigrationsDirApplied(write({ d1MigrationsDir: {
1364
+ binding,
1365
+ dir: migrationsDir
1366
+ } }), binding, configPath);
1367
+ resources.push({
1368
+ kind: "d1",
1369
+ binding,
1370
+ name,
1371
+ action: "reused",
1372
+ id: entry.database_id
1373
+ });
1374
+ } else {
1375
+ const listResult = await runWrangler({
1376
+ type: "d1.list",
1377
+ configPath
1378
+ }, {});
1379
+ assertDiscoverySucceeded(listResult, "Cloudflare d1 list");
1380
+ const rawList = listResult.data;
1381
+ if (!Array.isArray(rawList)) throw new Error(`provision: Cloudflare d1 list did not return a JSON array; cannot verify whether D1 database ${JSON.stringify(name)} exists. Refusing to create a possible duplicate.`);
1382
+ const claimants = validateResourceList(rawList, {
1383
+ resource: "D1 database",
1384
+ command: "Cloudflare d1 list",
1385
+ hasValidId: (member) => reconcileD1IdAliases(member).kind === "id",
1386
+ idRule: "its uuid/database_id aliases must be present, well-formed D1 UUIDs agreeing on one id",
1387
+ nameField: "name",
1388
+ nameLabel: "named"
1389
+ }).map((db) => normalizeD1(db, name)).filter((m) => m.kind !== "other");
1390
+ if (claimants.length > 1) throw new Error(`provision: Cloudflare d1 list returned ${claimants.length} D1 databases named ${JSON.stringify(name)}. D1 database names are account-unique, so this is ambiguous; cannot pick one to adopt and refusing to create a possible duplicate. Inspect the account and retry.`);
1391
+ if (claimants.length === 1 && claimants[0].kind === "claimed-but-invalid") throw new Error(`provision: Cloudflare d1 list returned a D1 database named ${JSON.stringify(name)} with an ambiguous or empty id (conflicting/blank uuid/database_id, or conflicting name aliases). Cannot adopt it, and refusing to create a possible duplicate; inspect the account and retry.`);
1392
+ const existing = claimants.length === 1 && claimants[0].kind === "match" ? claimants[0] : void 0;
1393
+ if (existing) {
1394
+ log.info(`adopted existing D1 database ${name} (${existing.id})`);
1395
+ assertD1MigrationsDirApplied(write({
1396
+ d1: {
1397
+ binding,
1398
+ databaseName: name,
1399
+ databaseId: existing.id
1400
+ },
1401
+ d1MigrationsDir: {
1402
+ binding,
1403
+ dir: migrationsDir
1404
+ }
1405
+ }), binding, configPath);
1406
+ resources.push({
1407
+ kind: "d1",
1408
+ binding,
1409
+ name,
1410
+ action: "adopted",
1411
+ id: existing.id
1412
+ });
1413
+ } else {
1414
+ const created = await runWrangler({
1415
+ type: "d1.create",
1416
+ name,
1417
+ binding,
1418
+ configPath
1419
+ });
1420
+ if (isCleanSuccess(created)) {
1421
+ assertCreateWroteRealId(configPath, {
1422
+ field: "d1_databases",
1423
+ idField: "database_id",
1424
+ idValidator: isRealD1Id,
1425
+ nameField: "database_name",
1426
+ resource: "D1 database",
1427
+ command: "Cloudflare d1 create"
1428
+ }, binding, name);
1429
+ persistCreatedConfig();
1430
+ assertD1MigrationsDirApplied(write({ d1MigrationsDir: {
1431
+ binding,
1432
+ dir: migrationsDir
1433
+ } }), binding, configPath);
1434
+ resources.push({
1435
+ kind: "d1",
1436
+ binding,
1437
+ name,
1438
+ action: "created"
1439
+ });
1440
+ } else if (isCleanFailure(created) && isAlreadyExistsError(created)) {
1441
+ const infoResult = await runWrangler({
1442
+ type: "d1.info",
1443
+ name,
1444
+ configPath
1445
+ }, {});
1446
+ assertDiscoverySucceeded(infoResult, `Cloudflare d1 info ${name}`);
1447
+ const info = normalizeD1(isRecord(infoResult.data) ? infoResult.data : void 0, name);
1448
+ if (info.kind !== "match") throw new Error(`provision: Cloudflare d1 create ${name} reported the database already exists, but Cloudflare d1 info ${name} did not return a database with a matching name and an unambiguous id. Refusing to adopt an unverified database.`);
1449
+ log.info(`adopted existing D1 database ${name} (${info.id})`);
1450
+ assertD1MigrationsDirApplied(write({
1451
+ d1: {
1452
+ binding,
1453
+ databaseName: name,
1454
+ databaseId: info.id
1455
+ },
1456
+ d1MigrationsDir: {
1457
+ binding,
1458
+ dir: migrationsDir
1459
+ }
1460
+ }), binding, configPath);
1461
+ resources.push({
1462
+ kind: "d1",
1463
+ binding,
1464
+ name,
1465
+ action: "adopted",
1466
+ id: info.id
1467
+ });
1468
+ } else throw new Error(`provision: Cloudflare d1 create ${name} failed: ${created.stderr || created.stdout}`);
1469
+ }
1470
+ }
1471
+ const databaseId = readBindingEntry(configPath, "d1_databases", binding)?.database_id;
1472
+ if (!isRealD1Id(databaseId)) throw new Error(`provision: D1 binding ${binding} has no real database id after setup.`);
1473
+ const context = {
1474
+ databaseId,
1475
+ accountId: transportAccountId,
1476
+ apiBaseUrl: transportApiBaseUrl
1477
+ };
1478
+ if (opts?.enableD1ReadReplication) await opts.enableD1ReadReplication(context);
1479
+ else {
1480
+ let token = opts?.apiToken ?? process.env.CLOUDFLARE_API_TOKEN;
1481
+ if (!token) {
1482
+ const auth = await runWrangler({
1483
+ type: "auth.token",
1484
+ configPath
1485
+ }, { suppressLogs: true });
1486
+ const parsed = isCleanSuccess(auth) && isRecord(auth.data) ? auth.data : void 0;
1487
+ if ((parsed?.type === "oauth" || parsed?.type === "api_token") && typeof parsed.token === "string") token = parsed.token;
1488
+ }
1489
+ if (!token) throw new Error("provision: D1 read replication requires a Cloudflare API bearer with D1 Edit permission. Run `bwf cloudflare login`, or set CLOUDFLARE_API_TOKEN, then retry.");
1490
+ await enableD1ReadReplicationViaApi(context, token);
1491
+ }
1492
+ }
1493
+ }
1494
+ async function reconcileKv(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log) {
1495
+ for (const { binding, title } of desired.kvNamespaces) {
1496
+ const entry = readBindingEntry(configPath, "kv_namespaces", binding);
1497
+ if (entry && isRealKvId(entry.id)) {
1498
+ resources.push({
1499
+ kind: "kv",
1500
+ binding,
1501
+ name: title,
1502
+ action: "reused",
1503
+ id: entry.id
1504
+ });
1505
+ continue;
1506
+ }
1507
+ const listResult = await runWrangler({
1508
+ type: "kv.namespace.list",
1509
+ configPath
1510
+ }, {});
1511
+ assertDiscoverySucceeded(listResult, "Cloudflare kv namespace list");
1512
+ const rawList = listResult.data;
1513
+ if (!Array.isArray(rawList)) throw new Error(`provision: Cloudflare kv namespace list did not return a JSON array; cannot verify whether KV namespace ${JSON.stringify(title)} exists. Refusing to create a possible duplicate.`);
1514
+ const matches = validateResourceList(rawList, {
1515
+ resource: "KV namespace",
1516
+ command: "Cloudflare kv namespace list",
1517
+ hasValidId: (member) => isRealKvId(member.id),
1518
+ idRule: "its id is missing or not a well-formed 32-hex namespace id",
1519
+ nameField: "title",
1520
+ nameLabel: "titled"
1521
+ }).filter((ns) => ns.title === title).map((ns) => ({ id: ns.id }));
1522
+ if (matches.length > 0) {
1523
+ const chosen = matches.reduce((min, ns) => ns.id < min.id ? ns : min);
1524
+ if (matches.length > 1) log.warn(`multiple KV namespaces titled "${title}" (${matches.map((m) => m.id).join(", ")}); adopting the lexicographically-smallest id ${chosen.id}`);
1525
+ log.info(`adopted existing KV namespace ${title} (${chosen.id})`);
1526
+ write({ kv: {
1527
+ binding,
1528
+ id: chosen.id
1529
+ } });
1530
+ resources.push({
1531
+ kind: "kv",
1532
+ binding,
1533
+ name: title,
1534
+ action: "adopted",
1535
+ id: chosen.id
1536
+ });
1537
+ } else {
1538
+ const created = await runWrangler({
1539
+ type: "kv.namespace.create",
1540
+ name: title,
1541
+ binding,
1542
+ configPath
1543
+ });
1544
+ if (!isCleanSuccess(created)) throw new Error(`provision: Cloudflare kv namespace create ${title} failed: ${created.stderr || created.stdout}`);
1545
+ assertCreateWroteRealId(configPath, {
1546
+ field: "kv_namespaces",
1547
+ idField: "id",
1548
+ idValidator: isRealKvId,
1549
+ resource: "KV namespace",
1550
+ command: "Cloudflare kv namespace create"
1551
+ }, binding, title);
1552
+ persistCreatedConfig();
1553
+ resources.push({
1554
+ kind: "kv",
1555
+ binding,
1556
+ name: title,
1557
+ action: "created"
1558
+ });
1559
+ }
1560
+ }
1561
+ }
1562
+ async function reconcileR2(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log) {
1563
+ if (desired.r2) {
1564
+ const { binding, bucketName } = desired.r2;
1565
+ const entry = readBindingEntry(configPath, "r2_buckets", binding);
1566
+ const storedBucketName = entry?.bucket_name;
1567
+ if (entry && isRealStoredR2BucketName(storedBucketName, bucketName)) {
1568
+ if (storedBucketName !== bucketName) throw new Error(`provision: R2 binding ${JSON.stringify(binding)} in "${configPath}" stores bucket_name ${JSON.stringify(storedBucketName)}, but this deploy wants bucket ${JSON.stringify(bucketName)}. bucket_name IS the R2 identity, so this entry contradicts the desired bucket. Fix "${configPath}" — correct the entry's bucket_name (or remove the entry to re-provision) — or rename the desired bucket, then retry.`);
1569
+ resources.push({
1570
+ kind: "r2",
1571
+ binding,
1572
+ name: bucketName,
1573
+ action: "reused"
1574
+ });
1575
+ } else {
1576
+ const info = await runWrangler({
1577
+ type: "r2.bucket.info",
1578
+ name: bucketName,
1579
+ configPath
1580
+ }, {});
1581
+ if (isCleanSuccess(info)) {
1582
+ const payload = info.data;
1583
+ if (!isRecord(payload) || payload.name !== bucketName) throw new Error(`provision: Cloudflare r2 bucket info ${bucketName} exited 0 but did not identify the requested bucket (expected name ${JSON.stringify(bucketName)}). Refusing to adopt an unverified bucket. Output: ${info.stdout || info.stderr}`);
1584
+ log.info(`adopted existing R2 bucket ${bucketName}`);
1585
+ write({ r2: {
1586
+ binding,
1587
+ bucketName
1588
+ } });
1589
+ resources.push({
1590
+ kind: "r2",
1591
+ binding,
1592
+ name: bucketName,
1593
+ action: "adopted"
1594
+ });
1595
+ } else if (isConfirmedAbsent(info, "r2")) {
1596
+ const created = await runWrangler({
1597
+ type: "r2.bucket.create",
1598
+ ...desired.r2.locationHint ? { locationHint: desired.r2.locationHint } : {},
1599
+ name: bucketName,
1600
+ binding,
1601
+ configPath
1602
+ });
1603
+ if (!isCleanSuccess(created)) throw new Error(`provision: Cloudflare r2 bucket create ${bucketName} failed: ${created.stderr || created.stdout}`);
1604
+ assertCreateWroteRealId(configPath, {
1605
+ field: "r2_buckets",
1606
+ idField: "bucket_name",
1607
+ idValidator: isValidR2BucketNameFormat,
1608
+ nameField: "bucket_name",
1609
+ resource: "R2 bucket",
1610
+ command: "Cloudflare r2 bucket create"
1611
+ }, binding, bucketName);
1612
+ if (bucketName === R2_BUCKET_NAME_PLACEHOLDER) {
1613
+ const verify = await runWrangler({
1614
+ type: "r2.bucket.info",
1615
+ name: bucketName,
1616
+ configPath
1617
+ }, {});
1618
+ if (!isCleanSuccess(verify) || !isRecord(verify.data) || verify.data.name !== bucketName) throw new Error(`provision: Cloudflare r2 bucket create ${bucketName} reported success but a follow-up Cloudflare r2 bucket info ${bucketName} did not confirm the bucket exists. The create may have been interrupted, and the config entry is indistinguishable from the local-dev placeholder for this name. Refusing to record an unprovisioned bucket; inspect the account and retry.`);
1619
+ }
1620
+ persistCreatedConfig();
1621
+ resources.push({
1622
+ kind: "r2",
1623
+ binding,
1624
+ name: bucketName,
1625
+ action: "created"
1626
+ });
1627
+ } else throw new Error(`provision: Cloudflare r2 bucket info ${bucketName} failed: ${info.stderr || info.stdout}. Cannot determine whether the bucket exists; refusing to create a possible duplicate.`);
1628
+ }
1629
+ }
1630
+ }
1631
+ async function reconcileHyperdrive(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log, transportAccountId, transportApiBaseUrl, redactSecrets, opts) {
1632
+ if (desired.hyperdrive) {
1633
+ const { binding, name, connectionString } = desired.hyperdrive;
1634
+ const entry = readBindingEntry(configPath, "hyperdrive", binding);
1635
+ if (entry && isRealHyperdriveId(entry.id)) resources.push({
1636
+ kind: "hyperdrive",
1637
+ binding,
1638
+ name,
1639
+ action: "reused",
1640
+ id: entry.id
1641
+ });
1642
+ else {
1643
+ const lister = opts?.listHyperdriveConfigs ?? createDefaultListHyperdriveConfigs(opts?.apiToken);
1644
+ let validatedConfigs;
1645
+ let existenceUnknown = true;
1646
+ if (lister) try {
1647
+ const result = await withListerDeadline((signal) => lister({
1648
+ accountId: transportAccountId,
1649
+ apiBaseUrl: transportApiBaseUrl,
1650
+ signal
1651
+ }), opts?.listTimeoutMs ?? HYPERDRIVE_LIST_TIMEOUT_MS);
1652
+ if (!Array.isArray(result)) throw new Error(`the existence check returned a ${result === null ? "null" : typeof result} result instead of an array`);
1653
+ validatedConfigs = result;
1654
+ existenceUnknown = false;
1655
+ } catch (error) {
1656
+ log.warn(`Hyperdrive existence check for ${name} failed: ` + redactSecrets(error instanceof Error ? error.message : String(error)));
1657
+ existenceUnknown = true;
1658
+ validatedConfigs = void 0;
1659
+ }
1660
+ const existing = validatedConfigs !== void 0 ? selectHyperdriveMatch(validatedConfigs, name, configPath) : void 0;
1661
+ if (existing) {
1662
+ log.info(`adopted existing Hyperdrive config ${name} (${existing.id})`);
1663
+ write({ hyperdrive: {
1664
+ binding,
1665
+ id: existing.id
1666
+ } });
1667
+ resources.push({
1668
+ kind: "hyperdrive",
1669
+ binding,
1670
+ name,
1671
+ action: "adopted",
1672
+ id: existing.id
1673
+ });
1674
+ } else if (!connectionString) {
1675
+ const reason = "no connection string provided";
1676
+ log.warn(`skipping Hyperdrive config ${name}: ${reason}`);
1677
+ resources.push({
1678
+ kind: "hyperdrive",
1679
+ binding,
1680
+ name,
1681
+ action: "skipped",
1682
+ reason
1683
+ });
1684
+ } else if (existenceUnknown) throw new Error(`provision: could not check whether Hyperdrive config ${JSON.stringify(name)} already exists (see the warning above). A create would duplicate a config with the same name, so bwf did not create it. Check that CLOUDFLARE_API_TOKEN can read Hyperdrive configs, then retry.`);
1685
+ else {
1686
+ const created = await runWrangler({
1687
+ type: "hyperdrive.create",
1688
+ name,
1689
+ binding,
1690
+ configPath
1691
+ }, { input: connectionString });
1692
+ if (!isCleanSuccess(created)) throw new Error(`provision: Cloudflare hyperdrive create ${name} failed: ${created.stderr || created.stdout}`);
1693
+ assertCreateWroteRealId(configPath, {
1694
+ field: "hyperdrive",
1695
+ idField: "id",
1696
+ idValidator: isRealHyperdriveId,
1697
+ resource: "Hyperdrive config",
1698
+ command: "Cloudflare hyperdrive create"
1699
+ }, binding, name);
1700
+ persistCreatedConfig();
1701
+ resources.push({
1702
+ kind: "hyperdrive",
1703
+ binding,
1704
+ name,
1705
+ action: "created"
1706
+ });
1707
+ }
1708
+ }
1709
+ }
1710
+ }
1711
+ async function reconcileQueues(desired, configPath, runWrangler, resources) {
1712
+ for (const name of desired.queues) {
1713
+ const info = await runWrangler({
1714
+ type: "queues.info",
1715
+ name,
1716
+ configPath
1717
+ });
1718
+ if (queueInfoConfirmsExists(info, name)) {
1719
+ resources.push({
1720
+ kind: "queue",
1721
+ name,
1722
+ action: "reused"
1723
+ });
1724
+ continue;
1725
+ }
1726
+ if (!isConfirmedAbsent(info, "queue")) throw new Error(`provision: Cloudflare queues info ${name} failed or did not confirm the queue exists: ${info.stderr || info.stdout || "no output"}`);
1727
+ const created = await runWrangler({
1728
+ type: "queues.create",
1729
+ name,
1730
+ configPath
1731
+ });
1732
+ if (!isCleanSuccess(created)) throw new Error(`provision: Cloudflare queues create ${name} failed: ${created.stderr || created.stdout}`);
1733
+ if (!queueInfoConfirmsExists(await runWrangler({
1734
+ type: "queues.info",
1735
+ name,
1736
+ configPath
1737
+ }), name)) throw new Error(`provision: Cloudflare queues create ${name} reported success but Cloudflare queues info ${name} did not confirm the queue exists afterward. The create may have been interrupted. Refusing to record an unprovisioned queue; inspect the account and retry.`);
1738
+ resources.push({
1739
+ kind: "queue",
1740
+ name,
1741
+ action: "created"
1742
+ });
1743
+ }
1744
+ }
1745
+ /** The provision body, run under the lock with the canonical config path. */
1746
+ async function provisionCloudflareResourcesLocked(root, configPath, desired, opts) {
1747
+ if (existsSync(configPath)) {
1748
+ const raw = readFileSync(configPath, "utf-8");
1749
+ const content = raw.startsWith(UTF8_BOM) ? raw.slice(1) : raw;
1750
+ assertNoDuplicateMembers(content, configPath);
1751
+ }
1752
+ if (desired.d1) assertValidResourceName("d1", desired.d1.name);
1753
+ for (const { title } of desired.kvNamespaces) assertValidResourceName("kvTitle", title);
1754
+ if (desired.r2) assertValidResourceName("r2", desired.r2.bucketName);
1755
+ if (desired.hyperdrive) assertValidResourceName("hyperdrive", desired.hyperdrive.name);
1756
+ for (const queueName of desired.queues) assertValidResourceName("queue", queueName);
1757
+ const rootConfig = readRootConfig(configPath);
1758
+ const rawConfigAccountId = rootConfig.account_id;
1759
+ const configAccountId = typeof rawConfigAccountId === "string" && rawConfigAccountId.length > 0 ? rawConfigAccountId : void 0;
1760
+ const rawComplianceRegion = rootConfig.compliance_region;
1761
+ if (rawComplianceRegion !== void 0 && typeof rawComplianceRegion !== "string") throw new Error(`provision: "${configPath}" has a non-string "compliance_region"; it must be "public" or "fedramp_high". Fix the config and retry.`);
1762
+ const configComplianceRegion = typeof rawComplianceRegion === "string" ? rawComplianceRegion : void 0;
1763
+ if (configAccountId && opts?.accountId && configAccountId !== opts.accountId) throw new Error(`provision: Cloudflare account mismatch — "${configPath}" pins account_id ${JSON.stringify(configAccountId)} but deploy requested ${JSON.stringify(opts.accountId)}. Reconcile them (correct or remove the config's account_id, or deploy to the pinned account) and retry.`);
1764
+ const ambientAccountId = typeof process.env.CLOUDFLARE_ACCOUNT_ID === "string" && process.env.CLOUDFLARE_ACCOUNT_ID.length > 0 ? process.env.CLOUDFLARE_ACCOUNT_ID : void 0;
1765
+ const effectiveAccountId = configAccountId ?? opts?.accountId ?? ambientAccountId;
1766
+ const log = opts?.log ?? defaultLogger;
1767
+ const resources = [];
1768
+ const write = (patch) => writeProvisionedWranglerConfig(root, patch, { configPath });
1769
+ const persistCreatedConfig = () => persistMaterializedWranglerConfig(configPath);
1770
+ const hasRemoteWork = !!desired.d1 || desired.kvNamespaces.length > 0 || !!desired.r2 || !!desired.hyperdrive || desired.queues.length > 0;
1771
+ if (hasRemoteWork && !effectiveAccountId) throw new Error("provision: no Cloudflare account is resolvable. Set `cloudflare.account_id` in bwf.config.ts or export CLOUDFLARE_ACCOUNT_ID, then rerun `bwf deploy`. bwf does not provision resources without a pinned account.");
1772
+ if (hasRemoteWork) assertNoTransportRedirectInProjectDotenv(root);
1773
+ if (desired.hyperdrive && !opts?.listHyperdriveConfigs) {
1774
+ const { binding, name, connectionString } = desired.hyperdrive;
1775
+ const entry = readBindingEntry(configPath, "hyperdrive", binding);
1776
+ if (!(entry !== void 0 && isRealHyperdriveId(entry.id)) && !resolveHyperdriveApiToken(opts?.apiToken)) {
1777
+ if (connectionString) throw new Error(`provision: Hyperdrive config ${JSON.stringify(name)} has no ID yet. Before bwf creates one, it checks for an existing config with the Cloudflare API. That check needs an API token; a browser login cannot call it. Without the check, a create could duplicate an existing config with the same name, so nothing was provisioned. Either (a) export CLOUDFLARE_API_TOKEN with Hyperdrive edit permission and rerun, or (b) create the Hyperdrive config in the Cloudflare dashboard and add its ID to the ${JSON.stringify(binding)} entry in \`cloudflare.hyperdrive\` in bwf.config.ts. Deploying an already-provisioned Hyperdrive needs no token.`);
1778
+ throw new Error(`provision: Hyperdrive config ${JSON.stringify(name)} has no ID yet, and there is no DATABASE_URL to create it from. Nothing was provisioned. Either (a) export DATABASE_URL with your PostgreSQL connection string and rerun (bwf reads it from the shell — a value in .env/.env.local is NOT used here, so it never ships as a plaintext worker var), or (b) create the Hyperdrive config in the Cloudflare dashboard and add its ID to the ${JSON.stringify(binding)} entry in \`cloudflare.hyperdrive\` in bwf.config.ts. Deploying an already-provisioned Hyperdrive needs neither DATABASE_URL nor an API token.`);
1779
+ }
1780
+ }
1781
+ let accountIdWritten = false;
1782
+ if (effectiveAccountId && configAccountId !== effectiveAccountId) {
1783
+ write({ accountId: effectiveAccountId });
1784
+ accountIdWritten = true;
1785
+ }
1786
+ const transportAccountId = effectiveAccountId;
1787
+ const transportApiBaseUrl = resolvePinnedApiBaseUrl(process.env, configComplianceRegion);
1788
+ const selectedRunWrangler = opts?.runWrangler ?? createDefaultRunWrangler(root);
1789
+ const redactSecrets = createSecretRedactor(desired.hyperdrive?.connectionString);
1790
+ const redactResult = (result) => ({
1791
+ ...result,
1792
+ stdout: redactSecrets(result.stdout),
1793
+ stderr: redactSecrets(result.stderr),
1794
+ error: result.error != null ? redactSecrets(result.error) : result.error
1795
+ });
1796
+ const runWrangler = (args, callOpts) => Promise.resolve(selectedRunWrangler(args, {
1797
+ ...callOpts,
1798
+ accountId: transportAccountId,
1799
+ apiBaseUrl: transportApiBaseUrl
1800
+ })).then(redactResult, (error) => {
1801
+ throw redactRejection(error, redactSecrets);
1802
+ });
1803
+ await reconcileD1(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log, transportAccountId, transportApiBaseUrl, opts);
1804
+ await reconcileKv(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log);
1805
+ await reconcileR2(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log);
1806
+ await reconcileHyperdrive(desired, configPath, runWrangler, write, persistCreatedConfig, resources, log, transportAccountId, transportApiBaseUrl, redactSecrets, opts);
1807
+ await reconcileQueues(desired, configPath, runWrangler, resources);
1808
+ return {
1809
+ resources,
1810
+ configPath,
1811
+ accountIdWritten
1812
+ };
1813
+ }
1814
+ export { provisionEnv as _, checkCloudflareProvisionDrift as a, resolveWorkersDevComplianceRegion as b, enableD1ReadReplicationViaApi as c, isQueueConfirmedAbsent as d, isRealD1Id as f, provisionCloudflareResources as g, normalizeRunWranglerResult as h, assertValidResourceName as i, isAlreadyGoneKillError as l, isRealKvId as m, acquireProvisionLock as n, createDefaultRunWrangler as o, isRealHyperdriveId as p, assertNoTransportRedirectInProjectDotenv as r, deleteEnvVarCaseAware as s, WranglerQuarantineError as t, isQuarantineError as u, resolvePinnedApiBaseUrl as v, resolveProperLockfileKey as y };