@builtbyfriends/bwf 0.0.0-stage → 1.9.1

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-Cj0I2_bJ.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-D-DddkCQ.mjs +26 -0
  17. package/dist/auth-migrations-DDeifS3v.mjs +206 -0
  18. package/dist/auth-router-tWzIwf8f.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-HeXRQml6.mjs +1846 -0
  40. package/dist/client-D3D5RM5h.mjs +940 -0
  41. package/dist/client-VF2Nzc7Z.mjs +1 -0
  42. package/dist/cloudflare-auth-jb-1e43r.mjs +152 -0
  43. package/dist/cloudflare-cmd-B62t8Fm-.mjs +59 -0
  44. package/dist/cloudflare-config-i8yanry0.mjs +186 -0
  45. package/dist/cloudflare-connect-x7IsYghw.mjs +55 -0
  46. package/dist/cloudflare-operations-BeK7bhnP.mjs +627 -0
  47. package/dist/cloudflare-operations-C3Uu0Emj.mjs +1 -0
  48. package/dist/cloudflare-process-Cc6oiJqk.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-hLPNppu3.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-BH_md90k.mjs +1735 -0
  65. package/dist/delete-BSKI7V23.mjs +65 -0
  66. package/dist/deploy-C8KHBNsh.mjs +6512 -0
  67. package/dist/deploy-DCZBr7Ey.mjs +2 -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-C4ZhEiFG.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-B3TWga7x.mjs +742 -0
  84. package/dist/email-C_ATvNIG.mjs +2865 -0
  85. package/dist/email-cloudflare-DuAc9zny.mjs +854 -0
  86. package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
  87. package/dist/env-CTAo8ifZ.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-BufZConV.mjs +488 -0
  97. package/dist/env-validation-DPqDo4DU.mjs +1 -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-CJ7DiiRF.mjs +161 -0
  111. package/dist/handler-CVsIfRv7.d.mts +279 -0
  112. package/dist/help-Bpv6Qeqn.mjs +1946 -0
  113. package/dist/help-CfZ4Bsw5.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-DRUR0j8C.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-B84t4BhW.mjs +130 -0
  124. package/dist/live-Dui0-aj_.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-C3EeOV7-.mjs +103 -0
  128. package/dist/log-JDnPc0cF.mjs +23 -0
  129. package/dist/login-Bl5lH8nH.mjs +87 -0
  130. package/dist/login-DoI7AsbY.mjs +1 -0
  131. package/dist/logs-CaT2N2f7.mjs +129 -0
  132. package/dist/migrate-CbGscX-V.mjs +125 -0
  133. package/dist/migrate-Ce3JKLVs.mjs +1 -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-BFg32YyY.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-C73WWJBl.mjs +443 -0
  145. package/dist/operator-cmd-CdZytuAF.mjs +1 -0
  146. package/dist/output-Bb34lF0w.mjs +173 -0
  147. package/dist/output-CVolXKC1.mjs +1 -0
  148. package/dist/package-DO4d3Qz5.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-NI_vfWvD.mjs +538 -0
  155. package/dist/platform-args-ZC1-A1N9.mjs +1 -0
  156. package/dist/platform-auth-config-d-lY5-aY.mjs +371 -0
  157. package/dist/platform-auth-protection-Dhw7lUCk.mjs +231 -0
  158. package/dist/platform-auth-recovery-DaCc0tlx.mjs +309 -0
  159. package/dist/platform-cmd-5Ry-C9im.mjs +193 -0
  160. package/dist/platform-cmd-5oZq91lI.mjs +1 -0
  161. package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
  162. package/dist/platform-domain-DLVdGvGG.mjs +256 -0
  163. package/dist/platform-lifecycle-CUgjipXO.mjs +1 -0
  164. package/dist/platform-lifecycle-fRt5VMls.mjs +8928 -0
  165. package/dist/platform-management-5hEsRfR2.mjs +1 -0
  166. package/dist/platform-management-Djh1hzLP.mjs +1607 -0
  167. package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
  168. package/dist/platform-recovery-Cghx7FCR.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-SfwCwnZg.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-DTF19-fC.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-DGlFJ3T9.mjs +1 -0
  188. package/dist/provision-mYVLuQiy.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-BvCHol52.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-7aA5hGoM.mjs +145 -0
  209. package/dist/runner-mysql-DrMKw203.mjs +1 -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-DCF9RXTc.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-DsSoNsKJ.mjs +23 -0
  343. package/dist/wrangler-DU784Dkf.mjs +1452 -0
  344. package/dist/wrangler-Rr9_76DQ.mjs +1 -0
  345. package/dist/ws-Q_osq9VK.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,1284 @@
1
+ #!/usr/bin/env node
2
+ import { n as __toESM } from "../rolldown-runtime-uD8oG6U2.mjs";
3
+ import { a as join, c as resolve, n as dirname } from "../dist-DMYe8CZJ.mjs";
4
+ import { i as safePositional, n as isD1Bookmark, r as readCfUploadOutput, t as CF_VERSION_SOURCE_MAX_OUTPUT_BYTES } from "../cf-command-values-2kOtxMo1.mjs";
5
+ import { n as getBwfUserAgent, r as getCfCliVersion, t as publishCloudflareWorkerSettings } from "../cf-worker-settings-CIh4t_yG.mjs";
6
+ import { t as require_picocolors } from "../picocolors-D1NxSLw-.mjs";
7
+ import { l as formatUrl } from "../output-Bb34lF0w.mjs";
8
+ import { t as sanitizeTerminalLogText } from "../terminal-log-text-DNsWJREL.mjs";
9
+ import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { fileURLToPath } from "node:url";
11
+ import { parsePlatformResourceOwnershipMarker } from "@builtbyfriends/platform";
12
+ import { tmpdir } from "node:os";
13
+ import { stripVTControlCharacters } from "node:util";
14
+ import { parse } from "jsonc-parser";
15
+ import { spawn, spawnSync } from "node:child_process";
16
+ import { setGlobalProxyFromEnv } from "node:http";
17
+ import { getCloudflareAuthUseKeyringFromEnv } from "@cloudflare/workers-auth";
18
+ import { createCfAuth, createCfProfileStore, readUserPreferences, setKeyringPreference } from "@cloudflare/workers-auth/cf";
19
+ // src/cli/cf-session.ts
20
+ const logger = {
21
+ debug() {},
22
+ info() {},
23
+ log() {},
24
+ warn() {},
25
+ error() {}
26
+ };
27
+ function session(root) {
28
+ const auth = createCfAuth({
29
+ logger,
30
+ userAgent: "nosam",
31
+ prompt: async () => {
32
+ throw new Error("Cloudflare session reads cannot prompt.");
33
+ },
34
+ select: async () => {
35
+ throw new Error("Cloudflare session reads cannot prompt.");
36
+ },
37
+ isNoDefaultValueProvidedError: () => false
38
+ });
39
+ auth.setProfile(createCfProfileStore({ logger }).resolve({ cwd: root }));
40
+ return auth;
41
+ }
42
+ /** Borrow only the profile just verified by cf, including its encrypted store. */
43
+ function readCfSessionCredential(root, identity) {
44
+ if (identity.authenticated !== true || identity.tokenValid !== true) return null;
45
+ const auth = session(root);
46
+ if (identity.authSource !== `OAuth token from ${auth.getCredentialStore().path()}`) return null;
47
+ const token = auth.readAuthCredentials()?.oauth_token;
48
+ if (typeof token !== "string" || token.length === 0) return null;
49
+ persistCfKeyringPreference(root);
50
+ return token;
51
+ }
52
+ /** Keep subsequent cf logins on the encrypted profile adopted by bwf. */
53
+ function persistCfKeyringPreference(root) {
54
+ if (getCloudflareAuthUseKeyringFromEnv() === false || readUserPreferences().keyring_enabled === true) return;
55
+ const auth = session(root);
56
+ if (!setKeyringPreference(true, {
57
+ logger,
58
+ getCredentialStore: auth.getCredentialStore
59
+ }).enabled) throw new Error("Cloudflare encrypted credential storage is unavailable.");
60
+ }
61
+ // src/cli/cloudflare-login-output.ts
62
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
63
+ /** The bundled cf login prints the device code before opening the browser. */
64
+ function cloudflareDeviceCode(output) {
65
+ const plain = stripVTControlCharacters(output);
66
+ return /and enter the code:\s*([A-Za-z0-9-]+)\s/i.exec(plain)?.[1] ?? /[?&]user_code=([A-Za-z0-9-]+)\s/i.exec(plain)?.[1] ?? null;
67
+ }
68
+ function cloudflareVerificationUrl(output) {
69
+ const plain = stripVTControlCharacters(output);
70
+ return /(?:Opening a link in your default browser:|Visit this link to authenticate:)\s*(https?:\/\/\S+)\s/i.exec(plain)?.[1] ?? /please visit:\s*(https?:\/\/\S+)\s/i.exec(plain)?.[1] ?? null;
71
+ }
72
+ function printCloudflareLoginLink(url) {
73
+ console.log(`Open this link if your browser did not open: ${formatUrl(url)}`);
74
+ }
75
+ function printCloudflareLoginPrompt(code) {
76
+ console.log(code ? `Opening Cloudflare login in your browser. Confirm the code ${import_picocolors.default.blue(code)} in your browser. Press Ctrl+C to cancel.` : "Opening Cloudflare login in your browser. Confirm the code shown in your browser. Press Ctrl+C to cancel.");
77
+ }
78
+ // src/cli/platform-worker-user-agent.ts
79
+ /** Attribute infrastructure uploads using the installer's existing ownership proof. */
80
+ function platformWorkerUploadAttribution(config) {
81
+ const vars = config.vars;
82
+ if (typeof vars?.PLATFORM_OWNERSHIP_MARKER !== "string") return;
83
+ try {
84
+ const marker = parsePlatformResourceOwnershipMarker(JSON.parse(vars.PLATFORM_OWNERSHIP_MARKER));
85
+ if (marker.resourceKind !== "worker" || marker.accountId !== config.account_id || marker.resourceName !== config.name || ![
86
+ "api-worker",
87
+ "proxy-worker",
88
+ "dispatch-worker",
89
+ "tail-worker",
90
+ "email-gateway-worker"
91
+ ].includes(marker.resourceKey)) return;
92
+ const version = typeof vars.PLATFORM_VERSION === "string" ? vars.PLATFORM_VERSION : "unknown";
93
+ return `nosam-platform-install/${encodeURIComponent(version)} nosam-role/${marker.resourceKey} nosam-installation/${encodeURIComponent(marker.installationId)}`;
94
+ } catch {
95
+ return;
96
+ }
97
+ }
98
+ // src/cli/cloudflare-operation-process.ts
99
+ const cf = join(dirname(fileURLToPath(import.meta.resolve("cf/package.json"))), "bin", "cf");
100
+ const operation = (() => {
101
+ try {
102
+ return JSON.parse(process.argv[2] ?? "null");
103
+ } catch {
104
+ return null;
105
+ }
106
+ })();
107
+ process.env.CLOUDFLARE_AUTH_USE_KEYRING ??= "true";
108
+ if (hasProxyEnvironment(process.env)) setGlobalProxyFromEnv();
109
+ function hasProxyEnvironment(env) {
110
+ return Boolean(env.HTTP_PROXY || env.HTTPS_PROXY || env.http_proxy || env.https_proxy);
111
+ }
112
+ function apiBaseUrl() {
113
+ return (process.env.CLOUDFLARE_API_BASE_URL ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, "");
114
+ }
115
+ function cfEnvironment() {
116
+ const env = {
117
+ ...process.env,
118
+ CF_DELEGATION: "1",
119
+ CLI_VERSION: getCfCliVersion(operation.type === "versions.upload" || operation.type === "worker.deploy" ? platformWorkerUploadAttribution(config()) : void 0),
120
+ CF_SEND_TELEMETRY: "false",
121
+ CF_NO_OSC_PROGRESS: "1",
122
+ CLOUDFLARE_AUTH_USE_KEYRING: process.env.CLOUDFLARE_AUTH_USE_KEYRING
123
+ };
124
+ if (hasProxyEnvironment(env)) env.NODE_USE_ENV_PROXY = "1";
125
+ for (const [canonical, alias] of [
126
+ ["CLOUDFLARE_API_TOKEN", "CF_API_TOKEN"],
127
+ ["CLOUDFLARE_API_KEY", "CF_API_KEY"],
128
+ ["CLOUDFLARE_EMAIL", "CF_EMAIL"],
129
+ ["CLOUDFLARE_ACCOUNT_ID", "CF_ACCOUNT_ID"]
130
+ ]) if (!env[canonical] && env[alias]) env[canonical] = env[alias];
131
+ return env;
132
+ }
133
+ function result(status, stdout = "", stderr = "", data) {
134
+ const code = /\[(?:code:\s*)?(\d{4,})\]/.exec(stderr);
135
+ const errorCode = code ? Number(code[1]) : void 0;
136
+ return {
137
+ status,
138
+ stdout,
139
+ stderr,
140
+ ...data !== void 0 ? { data } : {},
141
+ ...errorCode ? { errorCode } : {},
142
+ ...[
143
+ 10006,
144
+ 10007,
145
+ 10090
146
+ ].includes(errorCode ?? 0) ? { failure: "not-found" } : {}
147
+ };
148
+ }
149
+ function runCf(command, cwd = process.cwd(), bounds, interactive = false) {
150
+ const env = cfEnvironment();
151
+ env.CF_QUIET = "1";
152
+ const child = spawnSync(process.execPath, [cf, ...command], {
153
+ cwd,
154
+ env,
155
+ encoding: "utf8",
156
+ shell: false,
157
+ windowsHide: true,
158
+ maxBuffer: bounds?.maxOutputBytes ?? 33554432,
159
+ ...bounds ? { timeout: bounds.timeoutMs } : {},
160
+ stdio: interactive ? "inherit" : [
161
+ "ignore",
162
+ "pipe",
163
+ "pipe"
164
+ ]
165
+ });
166
+ const stderr = [
167
+ child.stderr || "",
168
+ child.error?.message || "",
169
+ child.signal ? `Cloudflare CLI terminated by ${child.signal}.` : ""
170
+ ].filter(Boolean).join("\n").replace(/\[(\d{4,})\]/g, "[code: $1]");
171
+ if (child.signal || child.error || child.status === null) return {
172
+ status: 1,
173
+ stdout: "",
174
+ stderr,
175
+ signal: child.signal,
176
+ error: child.error?.message ?? (child.signal ? void 0 : "Cloudflare CLI did not report an exit status.")
177
+ };
178
+ return result(child.status, child.stdout ?? "", stderr);
179
+ }
180
+ function runInteractiveCf(command) {
181
+ return new Promise((resolve) => {
182
+ const child = spawn(process.execPath, [
183
+ cf,
184
+ ...command,
185
+ "--quiet"
186
+ ], {
187
+ cwd: process.cwd(),
188
+ env: {
189
+ ...cfEnvironment(),
190
+ CF_QUIET: "1"
191
+ },
192
+ shell: false,
193
+ stdio: [
194
+ "inherit",
195
+ "pipe",
196
+ "pipe"
197
+ ],
198
+ windowsHide: true
199
+ });
200
+ let output = "";
201
+ let announced = false;
202
+ let announcedLink = false;
203
+ let settled = false;
204
+ const finish = (value) => {
205
+ if (!settled) {
206
+ settled = true;
207
+ resolve(value);
208
+ }
209
+ };
210
+ const collect = (chunk) => {
211
+ output = (output + chunk.toString()).slice(-32768);
212
+ if (!announced) {
213
+ const code = cloudflareDeviceCode(output);
214
+ if (code) {
215
+ announced = true;
216
+ printCloudflareLoginPrompt(code);
217
+ }
218
+ }
219
+ if (!announcedLink) {
220
+ const url = cloudflareVerificationUrl(output);
221
+ if (url) {
222
+ announcedLink = true;
223
+ printCloudflareLoginLink(url);
224
+ }
225
+ }
226
+ };
227
+ child.stdout.on("data", collect);
228
+ child.stderr.on("data", collect);
229
+ child.once("error", (error) => finish(result(1, "", error.message)));
230
+ child.once("close", (status, signal) => {
231
+ if (status === 0) {
232
+ if (!announced) printCloudflareLoginPrompt(null);
233
+ finish(result(0));
234
+ } else finish(result(status ?? 1, "", output.trim() || `Cloudflare login ended${signal ? ` (${signal})` : ""}.`));
235
+ });
236
+ });
237
+ }
238
+ async function withBuildOutput(raw, sourceMain, action) {
239
+ const scratch = mkdtempSync(join(tmpdir(), "nosam-cf-command-"));
240
+ try {
241
+ const main = "index.js";
242
+ if (sourceMain) copyFileSync(sourceMain, join(scratch, main));
243
+ else {
244
+ const { NOSAM_SECRET_DRAFT_SOURCE } = await import("@builtbyfriends/deploy-cloudflare");
245
+ writeFileSync(join(scratch, main), NOSAM_SECRET_DRAFT_SOURCE);
246
+ }
247
+ writeFileSync(join(scratch, "wrangler.json"), JSON.stringify({
248
+ ...raw,
249
+ main,
250
+ compatibility_date: raw.compatibility_date ?? "2025-01-01"
251
+ }), { mode: 384 });
252
+ const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? raw.account_id;
253
+ if (typeof accountId !== "string" || !accountId) throw new Error("Cloudflare account is not pinned for Worker deployment.");
254
+ const { prepareCfBuildOutput } = await import("../cf-build-output-DA6uJomQ.mjs");
255
+ const output = await prepareCfBuildOutput(scratch, accountId);
256
+ if (!output) throw new Error("Could not prepare the Cloudflare Worker build output.");
257
+ try {
258
+ await assertExistingProvisionableResources(output.directory, accountId);
259
+ return action(output.directory);
260
+ } finally {
261
+ await output.dispose();
262
+ }
263
+ } finally {
264
+ rmSync(scratch, {
265
+ recursive: true,
266
+ force: true
267
+ });
268
+ }
269
+ }
270
+ function parsedJson(value) {
271
+ return JSON.parse(value);
272
+ }
273
+ function object(value) {
274
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Cloudflare returned an unexpected response.");
275
+ return value;
276
+ }
277
+ function configPath() {
278
+ return "configPath" in operation ? operation.configPath : void 0;
279
+ }
280
+ function config() {
281
+ const path = configPath();
282
+ if (!path) throw new Error("Cloudflare config path is required for this operation.");
283
+ return object(parse(readFileSync(path, "utf8")));
284
+ }
285
+ function workerName() {
286
+ const name = ("workerName" in operation ? operation.workerName : void 0) ?? config().name;
287
+ if (typeof name !== "string" || !name) throw new Error("Cloudflare Worker name is missing from the generated config.");
288
+ return name;
289
+ }
290
+ function updateBinding(section, binding, values) {
291
+ const path = configPath();
292
+ if (!path || !binding) throw new Error("Cloudflare resource binding and config are required.");
293
+ const current = config();
294
+ const previous = Array.isArray(current[section]) ? current[section] : [];
295
+ const existing = previous.map(object).find((entry) => entry.binding === binding);
296
+ current[section] = [...previous.filter((entry) => object(entry).binding !== binding), {
297
+ ...existing,
298
+ binding,
299
+ ...values
300
+ }];
301
+ writeFileSync(path, `${JSON.stringify(current, null, 2)}\n`);
302
+ }
303
+ function d1Database(token) {
304
+ const entries = config().d1_databases;
305
+ if (!Array.isArray(entries)) throw new Error("D1 database binding is unavailable.");
306
+ const selected = entries.map(object).find((entry) => entry.database_id === token || entry.database_name === token || entry.binding === token);
307
+ if (!selected || typeof selected.database_id !== "string") throw new Error("D1 database binding is unavailable.");
308
+ return {
309
+ id: selected.database_id,
310
+ dir: typeof selected.migrations_dir === "string" ? selected.migrations_dir : "./migrations",
311
+ ...typeof selected.migrations_pattern === "string" ? { pattern: selected.migrations_pattern } : {},
312
+ table: typeof selected.migrations_table === "string" ? selected.migrations_table : "d1_migrations"
313
+ };
314
+ }
315
+ function previousD1Bookmark(stdout) {
316
+ try {
317
+ const previous = object(parsedJson(stdout)).previous_bookmark;
318
+ return isD1Bookmark(previous) ? previous : void 0;
319
+ } catch {
320
+ return;
321
+ }
322
+ }
323
+ function cleanJson(command, transform) {
324
+ const called = runCf(command);
325
+ if (called.status !== 0 || !transform) return called;
326
+ return result(0, `${JSON.stringify(transform(parsedJson(called.stdout)))}\n`, called.stderr);
327
+ }
328
+ function accountId() {
329
+ const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? config().account_id;
330
+ if (typeof accountId !== "string" || !accountId) throw new Error("Cloudflare account is not pinned for API inspection.");
331
+ return accountId;
332
+ }
333
+ async function cloudflareApiGet(path, failure, extraHeaders = {}) {
334
+ const url = `${apiBaseUrl()}${path}`;
335
+ const response = await fetch(url, {
336
+ headers: {
337
+ ...await apiHeaders(),
338
+ ...extraHeaders
339
+ },
340
+ redirect: "error",
341
+ signal: AbortSignal.timeout(3e4)
342
+ });
343
+ const body = object(await response.json());
344
+ if (!response.ok || body.success !== true) throw new Error(`${failure} (HTTP ${response.status})`);
345
+ return body;
346
+ }
347
+ async function clearWorkerCronSchedules(worker) {
348
+ const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/schedules`;
349
+ const response = await fetch(endpoint, {
350
+ method: "PUT",
351
+ headers: {
352
+ ...await apiHeaders(),
353
+ "Content-Type": "application/json"
354
+ },
355
+ body: "[]",
356
+ redirect: "error",
357
+ signal: AbortSignal.timeout(3e4)
358
+ });
359
+ const body = object(await response.json());
360
+ const schedules = object(body.result).schedules;
361
+ if (!response.ok || body.success !== true || !Array.isArray(schedules) || schedules.length !== 0) throw new Error(`Cloudflare did not clear the Worker Cron Triggers (HTTP ${response.status}).`);
362
+ return result(0);
363
+ }
364
+ async function clearWorkerCustomDomains(worker) {
365
+ const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/domains/records`;
366
+ const response = await fetch(endpoint, {
367
+ method: "PUT",
368
+ headers: {
369
+ ...await apiHeaders(),
370
+ "Content-Type": "application/json"
371
+ },
372
+ body: JSON.stringify({
373
+ override_scope: true,
374
+ override_existing_origin: false,
375
+ override_existing_dns_record: false,
376
+ origins: []
377
+ }),
378
+ redirect: "error",
379
+ signal: AbortSignal.timeout(3e4)
380
+ });
381
+ if (!response.ok) throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`);
382
+ let body;
383
+ try {
384
+ body = await response.json();
385
+ } catch {
386
+ throw new Error(`Cloudflare returned HTTP ${response.status} with a non-JSON custom-domain response.`);
387
+ }
388
+ if (object(body).success !== true) throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`);
389
+ return result(0);
390
+ }
391
+ async function assertExistingProvisionableResources(directory, account) {
392
+ const { readBuildOutput } = await import("@cloudflare/build-output-utils");
393
+ const bindings = (await readBuildOutput(directory)).workers.default.config.env ?? {};
394
+ const queueNames = /* @__PURE__ */ new Set();
395
+ const accountPath = `/accounts/${encodeURIComponent(account)}`;
396
+ for (const [bindingName, value] of Object.entries(bindings)) {
397
+ const binding = object(value);
398
+ const identifier = (key) => {
399
+ const id = binding[key];
400
+ if (typeof id !== "string" || !id) throw new Error(`Cloudflare binding ${bindingName} has no ${key}; refusing automatic provisioning.`);
401
+ return id;
402
+ };
403
+ if (binding.type === "kv" || binding.type === "d1") identifier("id");
404
+ else if (binding.type === "r2") {
405
+ const name = identifier("name");
406
+ const jurisdiction = binding.jurisdiction;
407
+ if (jurisdiction !== void 0 && typeof jurisdiction !== "string") throw new Error(`Cloudflare R2 binding ${bindingName} has an invalid jurisdiction.`);
408
+ await cloudflareApiGet(`${accountPath}/r2/buckets/${encodeURIComponent(name)}`, `Cloudflare R2 bucket ${name} is unavailable; refusing automatic provisioning.`, jurisdiction ? { "cf-r2-jurisdiction": jurisdiction } : {});
409
+ } else if (binding.type === "queue") queueNames.add(identifier("name"));
410
+ else if (binding.type === "dispatch-namespace") {
411
+ const name = identifier("namespace");
412
+ await cloudflareApiGet(`${accountPath}/workers/dispatch/namespaces/${encodeURIComponent(name)}`, `Cloudflare dispatch namespace ${name} is unavailable; refusing automatic provisioning.`);
413
+ } else if (binding.type === "ai-search-namespace") {
414
+ const name = identifier("namespace");
415
+ await cloudflareApiGet(`${accountPath}/ai-search/namespaces/${encodeURIComponent(name)}`, `Cloudflare AI Search namespace ${name} is unavailable; refusing automatic provisioning.`);
416
+ } else if (binding.type === "agent-memory") {
417
+ const name = identifier("namespace");
418
+ await cloudflareApiGet(`${accountPath}/agent-memory/namespaces/${encodeURIComponent(name)}`, `Cloudflare Agent Memory namespace ${name} is unavailable; refusing automatic provisioning.`);
419
+ } else if (binding.type === "flagship") identifier("id");
420
+ }
421
+ if (queueNames.size > 0) {
422
+ const existing = new Set((await readAllQueues()).map((queue) => queue.queue_name));
423
+ for (const name of queueNames) if (!existing.has(name)) throw new Error(`Cloudflare Queue ${name} is unavailable; refusing automatic provisioning.`);
424
+ }
425
+ }
426
+ async function readVersionResources(worker, versionId) {
427
+ const resources = object(object((await cloudflareApiGet(`/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/versions/${encodeURIComponent(versionId)}`, "Cloudflare did not return Worker version resources.")).result).resources);
428
+ if (!Array.isArray(resources.bindings) || !resources.script || !resources.script_runtime) throw new Error("Cloudflare Worker version resources were incomplete.");
429
+ return resources;
430
+ }
431
+ let cachedApiHeaders;
432
+ /** This process runs one operation, so the credential is read once. */
433
+ function apiHeaders() {
434
+ cachedApiHeaders ??= readApiHeaders();
435
+ return cachedApiHeaders;
436
+ }
437
+ async function readApiHeaders() {
438
+ const key = process.env.CLOUDFLARE_API_KEY ?? process.env.CF_API_KEY;
439
+ const email = process.env.CLOUDFLARE_EMAIL ?? process.env.CF_EMAIL;
440
+ const token = process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN;
441
+ if (key && email && !token) return {
442
+ "User-Agent": getBwfUserAgent(),
443
+ "X-Auth-Key": key,
444
+ "X-Auth-Email": email
445
+ };
446
+ const credential = await sessionCredential();
447
+ if (!("token" in credential)) throw new Error("Cloudflare session bearer is unavailable.");
448
+ return {
449
+ "User-Agent": getBwfUserAgent(),
450
+ Authorization: `Bearer ${credential.token}`
451
+ };
452
+ }
453
+ async function withSecretFile(content, action) {
454
+ const directory = mkdtempSync(join(tmpdir(), "nosam-cf-secret-"));
455
+ try {
456
+ const path = join(directory, "body.json");
457
+ writeFileSync(path, content, { mode: 384 });
458
+ return await action(path);
459
+ } finally {
460
+ rmSync(directory, {
461
+ recursive: true,
462
+ force: true
463
+ });
464
+ }
465
+ }
466
+ const NO_OAUTH_BEARER = "Cloudflare session has no OAuth bearer.";
467
+ async function sessionCredential() {
468
+ const token = process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN;
469
+ if (token) return {
470
+ type: "api_token",
471
+ token
472
+ };
473
+ const identity = runCf(["auth", "whoami"]);
474
+ if (identity.status !== 0) return { failure: [`cf auth whoami exited with code ${String(identity.status)}.`, identity.stderr.trim()].filter(Boolean).join("\n") };
475
+ const state = object(parsedJson(identity.stdout));
476
+ if (state.authenticated !== true || state.tokenValid !== true) return { failure: NO_OAUTH_BEARER };
477
+ const credential = readCfSessionCredential(process.cwd(), state);
478
+ return credential ? {
479
+ type: "oauth",
480
+ token: credential
481
+ } : { failure: NO_OAUTH_BEARER };
482
+ }
483
+ async function auth() {
484
+ if (operation.type === "auth.login") {
485
+ const loggedIn = await runInteractiveCf([
486
+ "auth",
487
+ "login",
488
+ "--force"
489
+ ]);
490
+ if (loggedIn.status === 0) persistCfKeyringPreference(process.cwd());
491
+ return loggedIn;
492
+ }
493
+ if (operation.type === "auth.logout") return runCf(["auth", "logout"]);
494
+ if (operation.type === "auth.whoami") {
495
+ const called = runCf(["auth", "whoami"]);
496
+ if (called.status !== 0) return called;
497
+ const identity = object(parsedJson(called.stdout));
498
+ if (identity.authenticated !== true || identity.tokenValid !== true) return result(1, "", "Cloudflare authentication is required.", { loggedIn: false });
499
+ if (String(identity.authSource).startsWith("OAuth token from ")) persistCfKeyringPreference(process.cwd());
500
+ return result(0, "", called.stderr, {
501
+ loggedIn: true,
502
+ accounts: identity.accounts,
503
+ email: identity.email,
504
+ tokenPermissions: identity.scopes,
505
+ authType: process.env.CLOUDFLARE_API_KEY || process.env.CF_API_KEY ? "Global API Key" : String(identity.authSource).startsWith("OAuth token") ? "OAuth Token" : "API Token"
506
+ });
507
+ }
508
+ if (operation.type !== "auth.token") throw new Error("Unsupported Cloudflare authentication operation.");
509
+ const credential = await sessionCredential();
510
+ if ("token" in credential) return result(0, "", "", credential);
511
+ return result(1, "", credential.failure, process.env.CLOUDFLARE_API_KEY || process.env.CF_API_KEY ? { type: "api_key" } : void 0);
512
+ }
513
+ function listAllResourcePages(command, extraFlags = []) {
514
+ const pageSize = 100;
515
+ const entries = [];
516
+ for (let page = 1; page <= 100; page++) {
517
+ const listed = runCf([
518
+ ...command,
519
+ "--page",
520
+ String(page),
521
+ "--per-page",
522
+ String(pageSize),
523
+ ...extraFlags
524
+ ]);
525
+ if (listed.status !== 0) return listed;
526
+ const items = parsedJson(listed.stdout);
527
+ if (!Array.isArray(items) || items.length > pageSize) throw new Error(`Cloudflare returned an invalid ${command.join(" ")} page.`);
528
+ entries.push(...items);
529
+ if (items.length < pageSize) return result(0, `${JSON.stringify(entries)}\n`);
530
+ }
531
+ throw new Error(`Cloudflare ${command.join(" ")} exceeded the supported page limit.`);
532
+ }
533
+ /**
534
+ * Each consumer's Worker script name, or null for one that is not a Worker (HTTP pull).
535
+ * Undefined when the list is incomplete or unreadable; only queue naming needs it.
536
+ */
537
+ function queueConsumerWorkers(queue) {
538
+ const consumers = queue.consumers;
539
+ if (!Array.isArray(consumers) || queue.consumers_total_count !== void 0 && queue.consumers_total_count !== consumers.length) return;
540
+ const workers = [];
541
+ for (const entry of consumers) {
542
+ const consumer = object(entry);
543
+ const { script_name: scriptName, script } = consumer;
544
+ if (scriptName !== void 0 && (typeof scriptName !== "string" || !scriptName) || script !== void 0 && (typeof script !== "string" || !script) || scriptName !== void 0 && script !== void 0 && scriptName !== script) return;
545
+ const name = scriptName ?? script;
546
+ if (typeof name === "string" && (consumer.type === void 0 || consumer.type === "worker")) workers.push(name);
547
+ else if (name === void 0 && consumer.type === "http_pull") workers.push(null);
548
+ else return;
549
+ }
550
+ return workers;
551
+ }
552
+ async function readAllQueues() {
553
+ const queues = [];
554
+ const seen = /* @__PURE__ */ new Set();
555
+ for (let page = 1; page <= 1e3; page++) {
556
+ const body = await cloudflareApiGet(`/accounts/${encodeURIComponent(accountId())}/queues?page=${page}`, "Cloudflare did not return the Queue list.");
557
+ const entries = body.result;
558
+ const info = object(body.result_info);
559
+ if (!Array.isArray(entries) || !Number.isSafeInteger(info.page) || info.page !== page || !Number.isSafeInteger(info.total_pages) || info.total_pages < 0 || info.total_pages > 1e3) throw new Error("Cloudflare returned incomplete Queue pagination.");
560
+ for (const entry of entries) {
561
+ const queue = object(entry);
562
+ if (typeof queue.queue_id !== "string" || typeof queue.queue_name !== "string" || seen.has(queue.queue_id)) throw new Error("Cloudflare returned an invalid Queue list.");
563
+ seen.add(queue.queue_id);
564
+ queues.push(queue);
565
+ }
566
+ if (page >= info.total_pages) return queues;
567
+ }
568
+ throw new Error("Cloudflare Queue list exceeded the supported page limit.");
569
+ }
570
+ async function resources() {
571
+ switch (operation.type) {
572
+ case "workers.subdomain.get": {
573
+ const { subdomain } = object((await cloudflareApiGet(`/accounts/${encodeURIComponent(accountId())}/workers/subdomain`, "Cloudflare did not return the account workers.dev subdomain.")).result);
574
+ if (typeof subdomain !== "string" || !subdomain.trim()) throw new Error("Cloudflare returned an invalid account workers.dev subdomain.");
575
+ return result(0, "", "", { subdomain });
576
+ }
577
+ case "d1.execute": return runCf([
578
+ "d1",
579
+ "query",
580
+ d1Database(operation.database).id,
581
+ `--sql=${operation.sql}`
582
+ ]);
583
+ case "d1.migrations.list":
584
+ case "d1.migrations.apply": {
585
+ const database = d1Database(operation.database);
586
+ const verb = operation.type === "d1.migrations.list" ? "list" : "apply";
587
+ const called = runCf([
588
+ "d1",
589
+ "migrations",
590
+ verb,
591
+ database.id,
592
+ "--dir",
593
+ database.dir,
594
+ ...database.pattern ? ["--pattern", database.pattern] : [],
595
+ "--table",
596
+ database.table
597
+ ]);
598
+ if (called.status !== 0 || verb !== "list") return called;
599
+ const pending = parsedJson(called.stdout);
600
+ if (!Array.isArray(pending) || pending.some((item) => typeof object(item).Name !== "string")) throw new Error("D1 migration list was malformed.");
601
+ return result(0, "", called.stderr, { pending: pending.map((item) => object(item).Name) });
602
+ }
603
+ case "d1.time-travel.bookmark": {
604
+ const called = runCf([
605
+ "d1",
606
+ "time-travel",
607
+ "get-bookmark",
608
+ d1Database(operation.database).id
609
+ ]);
610
+ if (called.status !== 0) return called;
611
+ const bookmark = object(parsedJson(called.stdout)).bookmark;
612
+ if (!isD1Bookmark(bookmark)) throw new Error("D1 Time Travel bookmark was malformed.");
613
+ return result(0, "", called.stderr, { bookmark });
614
+ }
615
+ case "d1.time-travel.restore": {
616
+ const database = d1Database(operation.database);
617
+ if ("bookmark" in operation.target && !isD1Bookmark(operation.target.bookmark)) throw new Error("D1 Time Travel bookmark was malformed.");
618
+ const target = "bookmark" in operation.target ? `--bookmark=${operation.target.bookmark}` : `--timestamp=${operation.target.timestamp}`;
619
+ const called = runCf([
620
+ "d1",
621
+ "time-travel",
622
+ "restore",
623
+ database.id,
624
+ target,
625
+ "--force"
626
+ ]);
627
+ if (called.status !== 0) return called;
628
+ return result(0, "", called.stderr, { previousBookmark: previousD1Bookmark(called.stdout) });
629
+ }
630
+ case "containers.list": return runCf([
631
+ "containers",
632
+ "applications",
633
+ "list"
634
+ ]);
635
+ case "d1.list": return listAllResourcePages(["d1", "list"]);
636
+ case "d1.info": {
637
+ const listed = listAllResourcePages(["d1", "list"]);
638
+ if (listed.status !== 0) return listed;
639
+ const list = parsedJson(listed.stdout);
640
+ if (!Array.isArray(list)) throw new Error("D1 list was malformed.");
641
+ const value = list.find((item) => object(item).name === operation.name);
642
+ return value === void 0 ? {
643
+ ...result(1, "", "D1 database does not exist."),
644
+ failure: "not-found"
645
+ } : result(0, "", "", value);
646
+ }
647
+ case "d1.create": {
648
+ const created = runCf([
649
+ "d1",
650
+ "create",
651
+ "--name",
652
+ operation.name
653
+ ]);
654
+ if (created.status !== 0) return created;
655
+ const database = object(parsedJson(created.stdout));
656
+ if (typeof database.uuid !== "string") throw new Error("D1 creation returned no database ID.");
657
+ updateBinding("d1_databases", operation.binding, {
658
+ database_name: operation.name,
659
+ database_id: database.uuid
660
+ });
661
+ return created;
662
+ }
663
+ case "kv.namespace.list": return listAllResourcePages([
664
+ "kv",
665
+ "namespaces",
666
+ "list"
667
+ ], [
668
+ "--order",
669
+ "id",
670
+ "--direction",
671
+ "asc"
672
+ ]);
673
+ case "kv.namespace.create": {
674
+ const created = runCf([
675
+ "kv",
676
+ "namespaces",
677
+ "create",
678
+ "--title",
679
+ operation.name
680
+ ]);
681
+ if (created.status !== 0) return created;
682
+ const namespace = object(parsedJson(created.stdout));
683
+ if (typeof namespace.id !== "string") throw new Error("KV creation returned no namespace ID.");
684
+ updateBinding("kv_namespaces", operation.binding, { id: namespace.id });
685
+ return created;
686
+ }
687
+ case "r2.bucket.info": return runCf([
688
+ "r2",
689
+ "buckets",
690
+ "get",
691
+ operation.name
692
+ ]);
693
+ case "r2.bucket.create": {
694
+ const created = runCf([
695
+ "r2",
696
+ "buckets",
697
+ "create",
698
+ "--name",
699
+ operation.name,
700
+ ...operation.locationHint ? ["--location-hint", operation.locationHint] : []
701
+ ]);
702
+ if (created.status === 0) updateBinding("r2_buckets", operation.binding, { bucket_name: operation.name });
703
+ return created;
704
+ }
705
+ case "hyperdrive.create": {
706
+ const url = new URL(readFileSync(0, "utf8"));
707
+ const name = operation.name;
708
+ const created = await withSecretFile(JSON.stringify({
709
+ name,
710
+ origin: {
711
+ host: url.hostname,
712
+ port: Number(url.port || (url.protocol.startsWith("mysql") ? 3306 : 5432)),
713
+ database: decodeURIComponent(url.pathname.replace(/^\//, "")),
714
+ scheme: url.protocol.replace(":", ""),
715
+ user: decodeURIComponent(url.username),
716
+ password: decodeURIComponent(url.password)
717
+ }
718
+ }), (path) => runCf([
719
+ "hyperdrive",
720
+ "create",
721
+ "--body",
722
+ "@" + path
723
+ ]));
724
+ if (created.status !== 0) return {
725
+ ...created,
726
+ stdout: "",
727
+ stderr: "Hyperdrive creation failed."
728
+ };
729
+ const hyperdrive = object(parsedJson(created.stdout));
730
+ if (typeof hyperdrive.id !== "string") throw new Error("Hyperdrive creation returned no ID.");
731
+ updateBinding("hyperdrive", operation.binding, { id: hyperdrive.id });
732
+ return result(0, "", "", {
733
+ id: hyperdrive.id,
734
+ name
735
+ });
736
+ }
737
+ case "queues.create": return runCf([
738
+ "queues",
739
+ "create",
740
+ "--queue-name",
741
+ operation.name
742
+ ]);
743
+ case "queues.info": {
744
+ const queue = (await readAllQueues()).find((item) => item.queue_name === operation.name);
745
+ const consumers = queue && queueConsumerWorkers(queue);
746
+ return queue ? result(0, "", "", {
747
+ id: queue.queue_id,
748
+ name: queue.queue_name,
749
+ ...consumers ? { consumers } : {}
750
+ }) : {
751
+ ...result(1, "", "Cloudflare Queue does not exist."),
752
+ failure: "not-found"
753
+ };
754
+ }
755
+ default: throw new Error("Unsupported Cloudflare resource operation.");
756
+ }
757
+ }
758
+ function emailZone(domain) {
759
+ const labels = domain.split(".");
760
+ for (let offset = 0; offset <= labels.length - 2; offset++) {
761
+ const candidate = labels.slice(offset).join(".");
762
+ const read = runCf([
763
+ "email-routing",
764
+ "settings",
765
+ "get",
766
+ "--zone",
767
+ candidate
768
+ ]);
769
+ if (read.status === 0) return candidate;
770
+ if (read.signal || read.error || !/Zone not found:/.test(read.stderr)) throw new Error("Cloudflare could not resolve the Email zone.");
771
+ }
772
+ throw new Error(`Cloudflare Email zone for ${domain} was not found.`);
773
+ }
774
+ function email() {
775
+ if (!("domain" in operation)) throw new Error("Cloudflare Email domain is missing.");
776
+ const domain = operation.domain;
777
+ switch (operation.type) {
778
+ case "email.routing.settings": {
779
+ const read = runCf([
780
+ "email-routing",
781
+ "settings",
782
+ "get",
783
+ "--zone",
784
+ domain
785
+ ]);
786
+ return read.status !== 0 && !read.signal && !read.error && /Zone not found:/.test(read.stderr) ? result(0, "", "", null) : read;
787
+ }
788
+ case "email.routing.enable": return runCf([
789
+ "email-routing",
790
+ "enable",
791
+ "--zone",
792
+ domain,
793
+ "--name",
794
+ domain
795
+ ]);
796
+ case "email.routing.rules.list": return listAllResourcePages([
797
+ "email-routing",
798
+ "rules",
799
+ "list-account"
800
+ ], ["--zone", domain]);
801
+ case "email.sending.settings": {
802
+ const listed = runCf([
803
+ "email-sending",
804
+ "subdomains",
805
+ "list",
806
+ "--zone",
807
+ emailZone(domain)
808
+ ]);
809
+ if (listed.status !== 0) return listed;
810
+ const values = parsedJson(listed.stdout);
811
+ if (!Array.isArray(values)) throw new Error("Email Sending subdomains were malformed.");
812
+ return result(0, "", "", values.map(object).find((item) => item.name === domain) ?? null);
813
+ }
814
+ case "email.sending.enable": return runCf([
815
+ "email-sending",
816
+ "subdomains",
817
+ "create",
818
+ "--zone",
819
+ emailZone(domain),
820
+ "--name",
821
+ domain
822
+ ]);
823
+ default: throw new Error("Unsupported Cloudflare Email operation.");
824
+ }
825
+ }
826
+ async function postWorkersApi(path, body) {
827
+ const response = await fetch(`${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workers/workers${path}`, {
828
+ method: "POST",
829
+ headers: {
830
+ ...await apiHeaders(),
831
+ "Content-Type": "application/json"
832
+ },
833
+ body: JSON.stringify(body),
834
+ redirect: "error",
835
+ signal: AbortSignal.timeout(3e4)
836
+ });
837
+ const parsed = await response.json().catch(() => null);
838
+ return {
839
+ status: response.status,
840
+ body: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null
841
+ };
842
+ }
843
+ /** An error that keeps the first few reasons Cloudflare gave, so the user can act on them. */
844
+ function workersApiFailure(action, response) {
845
+ const reasons = (Array.isArray(response.body?.errors) ? response.body.errors : []).slice(0, 3).flatMap((error) => {
846
+ if (!error || typeof error !== "object") return [];
847
+ const { code, message } = error;
848
+ if (typeof message !== "string" || !message) return [];
849
+ return [`${typeof code === "number" ? `code ${code}: ` : ""}${message.slice(0, 300)}`];
850
+ });
851
+ return new Error([`Cloudflare did not ${action} (HTTP ${response.status}).`, ...reasons].join("\n"));
852
+ }
853
+ function workerWithoutDeploymentMessage(worker) {
854
+ return [
855
+ `Cloudflare Worker "${worker}" exists but has no deployment, so bwf cannot set its secrets.`,
856
+ "If a deploy or secret command is running for this Worker, wait for it to finish and run this command again.",
857
+ `Otherwise, run \`bwf deploy\` first. If the deploy stops because a required secret is missing, delete the Worker "${worker}" in the Cloudflare dashboard (Workers & Pages) and run this command again.`
858
+ ].join("\n");
859
+ }
860
+ /**
861
+ * Set secrets on a Worker that has no deployed code yet.
862
+ *
863
+ * Cloudflare keeps secrets on deployed Worker versions, so the secrets go live inside an empty
864
+ * placeholder that the first `bwf deploy` replaces. Deploy that placeholder only to a Worker this
865
+ * command created: when a first `bwf deploy` or another secret command creates the Worker after
866
+ * the 10007, a placeholder would replace that app or its secrets. The Worker create fails (409)
867
+ * when the name is taken, and the placeholder and its secrets go live in one request.
868
+ *
869
+ * A Worker that exists without a deployment (another command is setting it up, or an earlier one
870
+ * failed after the create) cannot tell those cases apart, so this fails with the recovery steps.
871
+ */
872
+ async function setSecretsOnWorkerWithoutCode(worker, values, retry) {
873
+ const created = await postWorkersApi("", {
874
+ name: worker,
875
+ subdomain: {
876
+ enabled: false,
877
+ previews_enabled: false
878
+ }
879
+ });
880
+ if (created.status === 409) {
881
+ const retried = retry();
882
+ if (retried.status === 0 || retried.errorCode !== 10007 && retried.errorCode !== 10013) return retried;
883
+ return result(1, "", workerWithoutDeploymentMessage(worker));
884
+ }
885
+ if (created.status !== 200 || created.body?.success !== true) throw workersApiFailure("create the Worker", created);
886
+ const { NOSAM_SECRET_DRAFT_MESSAGE, NOSAM_SECRET_DRAFT_SOURCE } = await import("@builtbyfriends/deploy-cloudflare");
887
+ const uploaded = await postWorkersApi(`/${encodeURIComponent(worker)}/versions?deploy=true`, {
888
+ main_module: "index.js",
889
+ modules: [{
890
+ name: "index.js",
891
+ content_type: "application/javascript+module",
892
+ content_base64: Buffer.from(NOSAM_SECRET_DRAFT_SOURCE).toString("base64")
893
+ }],
894
+ compatibility_date: config().compatibility_date ?? "2025-01-01",
895
+ bindings: Object.entries(values).map(([name, text]) => ({
896
+ type: "secret_text",
897
+ name,
898
+ text
899
+ })),
900
+ annotations: { "workers/message": NOSAM_SECRET_DRAFT_MESSAGE }
901
+ });
902
+ if (uploaded.status !== 200 || uploaded.body?.success !== true) throw workersApiFailure("deploy the secret placeholder", uploaded);
903
+ return result(0);
904
+ }
905
+ async function secrets() {
906
+ const worker = workerName();
907
+ const apply = async (values, action) => {
908
+ const first = action();
909
+ if (first.status === 0 || first.errorCode !== 10007) return first;
910
+ return setSecretsOnWorkerWithoutCode(worker, values, action);
911
+ };
912
+ switch (operation.type) {
913
+ case "secret.list": return runCf([
914
+ "workers",
915
+ "secrets",
916
+ "list",
917
+ "--worker",
918
+ worker
919
+ ]);
920
+ case "secret.put": {
921
+ const value = readFileSync(0, "utf8").replace(/\n$/, "");
922
+ const name = operation.name;
923
+ return withSecretFile(JSON.stringify({
924
+ name,
925
+ text: value,
926
+ type: "secret_text"
927
+ }), (path) => apply({ [name]: value }, () => runCf([
928
+ "workers",
929
+ "secrets",
930
+ "update",
931
+ name,
932
+ "--worker",
933
+ worker,
934
+ "--body",
935
+ "@" + path
936
+ ])));
937
+ }
938
+ case "secret.bulk": {
939
+ const values = object(parsedJson(readFileSync(0, "utf8")));
940
+ const texts = {};
941
+ for (const [name, text] of Object.entries(values)) {
942
+ if (typeof text !== "string") throw new Error("Secret values must be strings.");
943
+ texts[name] = text;
944
+ }
945
+ const patch = Object.fromEntries(Object.entries(texts).map(([name, text]) => [name, {
946
+ type: "secret_text",
947
+ text
948
+ }]));
949
+ return withSecretFile(JSON.stringify({ secrets: patch }), (path) => apply(texts, () => runCf([
950
+ "workers",
951
+ "secrets",
952
+ "bulk",
953
+ "--worker",
954
+ worker,
955
+ "--file",
956
+ path
957
+ ])));
958
+ }
959
+ case "secret.delete": return runCf([
960
+ "workers",
961
+ "secrets",
962
+ "delete",
963
+ operation.name,
964
+ "--worker",
965
+ worker,
966
+ "--force"
967
+ ]);
968
+ default: throw new Error("Unsupported Cloudflare secret operation.");
969
+ }
970
+ }
971
+ async function workerHistory() {
972
+ const worker = workerName();
973
+ switch (operation.type) {
974
+ case "deployments.status":
975
+ case "deployments.list": {
976
+ const called = runCf([
977
+ "workers",
978
+ "deployments",
979
+ "list",
980
+ "--worker",
981
+ worker
982
+ ]);
983
+ if (called.status !== 0) return called;
984
+ const deployments = object(parsedJson(called.stdout)).deployments;
985
+ if (!Array.isArray(deployments)) throw new Error("Worker deployments were malformed.");
986
+ return operation.type === "deployments.list" ? result(0, "", called.stderr, deployments) : deployments[0] ? result(0, "", called.stderr, deployments[0]) : result(1, "", "Worker has no active deployment.");
987
+ }
988
+ case "versions.list": return cleanJson([
989
+ "workers",
990
+ "versions",
991
+ "list",
992
+ "--worker-id",
993
+ worker
994
+ ], (value) => {
995
+ if (!Array.isArray(value)) throw new Error("Worker versions were malformed.");
996
+ return value.map((entry) => {
997
+ const version = object(entry);
998
+ return {
999
+ ...version,
1000
+ metadata: { created_on: version.created_on }
1001
+ };
1002
+ });
1003
+ });
1004
+ case "versions.view": {
1005
+ const versionId = operation.versionId;
1006
+ const called = runCf([
1007
+ "workers",
1008
+ "versions",
1009
+ "get",
1010
+ versionId,
1011
+ "--worker-id",
1012
+ worker,
1013
+ ...operation.includeSource ? ["--include", "modules"] : []
1014
+ ], process.cwd(), operation.includeSource ? {
1015
+ timeoutMs: 3e4,
1016
+ maxOutputBytes: CF_VERSION_SOURCE_MAX_OUTPUT_BYTES
1017
+ } : void 0);
1018
+ if (called.status !== 0) return called;
1019
+ const version = object(parsedJson(called.stdout));
1020
+ if (version.id !== versionId || !Array.isArray(version.bindings)) throw new Error("Worker version bindings were malformed.");
1021
+ if (operation.includeSource) return result(0, "", called.stderr, version);
1022
+ const resources = await readVersionResources(worker, versionId);
1023
+ return result(0, "", called.stderr, {
1024
+ ...version,
1025
+ resources
1026
+ });
1027
+ }
1028
+ case "versions.deploy": {
1029
+ const versions = operation.versions.map((value) => ({
1030
+ version_id: value.versionId,
1031
+ percentage: value.percentage
1032
+ }));
1033
+ if (!versions.length || versions.some((value) => !/^[-a-f\d]{36}$/i.test(value.version_id) || !Number.isFinite(value.percentage) || value.percentage < 0 || value.percentage > 100) || Math.abs(versions.reduce((sum, value) => sum + value.percentage, 0) - 100) > .001) throw new Error("Cloudflare deployment percentages must total 100.");
1034
+ return runCf([
1035
+ "workers",
1036
+ "deployments",
1037
+ "create",
1038
+ "--worker",
1039
+ worker,
1040
+ "--body",
1041
+ JSON.stringify({
1042
+ strategy: "percentage",
1043
+ versions,
1044
+ ...operation.message ? { annotations: { "workers/message": operation.message } } : {}
1045
+ }),
1046
+ ...operation.bypassDeploymentChecks ? ["--bypass-deployment-checks"] : []
1047
+ ]);
1048
+ }
1049
+ default: throw new Error("Unsupported Cloudflare Worker history operation.");
1050
+ }
1051
+ }
1052
+ async function workerChanges() {
1053
+ if (operation.type === "queues.consumer.remove") {
1054
+ const queue = (await readAllQueues()).find((item) => item.queue_name === operation.queueName);
1055
+ if (!queue || typeof queue.queue_id !== "string") return {
1056
+ ...result(1, "", "Cloudflare Queue does not exist."),
1057
+ failure: "not-found"
1058
+ };
1059
+ const consumers = runCf([
1060
+ "queues",
1061
+ "consumers",
1062
+ "list",
1063
+ "--queue-id",
1064
+ queue.queue_id
1065
+ ]);
1066
+ if (consumers.status !== 0) return consumers;
1067
+ const members = parsedJson(consumers.stdout);
1068
+ if (!Array.isArray(members)) throw new Error("Queue consumer list was malformed.");
1069
+ const matching = members.map(object).filter((entry) => {
1070
+ const name = entry.script_name ?? entry.script;
1071
+ if (entry.script_name !== void 0 && (typeof entry.script_name !== "string" || !entry.script_name) || entry.script !== void 0 && (typeof entry.script !== "string" || !entry.script) || entry.script_name !== void 0 && entry.script !== void 0 && entry.script_name !== entry.script || entry.type === "worker" && name === void 0) throw new Error("Queue consumer Worker identity is ambiguous.");
1072
+ return name === operation.workerName;
1073
+ });
1074
+ if (matching.length > 1) throw new Error("Queue consumer Worker identity is ambiguous.");
1075
+ for (const item of matching) {
1076
+ if (!safePositional(item.consumer_id) || /\s/.test(item.consumer_id) || item.type !== void 0 && item.type !== "worker") throw new Error("Queue consumer ID or type is invalid.");
1077
+ const deleted = runCf([
1078
+ "queues",
1079
+ "consumers",
1080
+ "delete",
1081
+ item.consumer_id,
1082
+ "--queue-id",
1083
+ queue.queue_id,
1084
+ "--force"
1085
+ ]);
1086
+ if (deleted.status !== 0) return deleted;
1087
+ }
1088
+ return result(0);
1089
+ }
1090
+ const raw = config();
1091
+ const name = workerName();
1092
+ if (raw.name !== name) throw new Error("Cloudflare Worker target changed.");
1093
+ if (operation.type === "triggers.clear-crons" || operation.type === "triggers.clear-domains") {
1094
+ if (raw.account_id !== void 0 && raw.account_id !== accountId()) throw new Error("Cloudflare trigger target changed.");
1095
+ return operation.type === "triggers.clear-crons" ? clearWorkerCronSchedules(name) : clearWorkerCustomDomains(name);
1096
+ }
1097
+ if (operation.type === "triggers.deploy") {
1098
+ const deployed = await withBuildOutput(raw, null, (directory) => runCf([
1099
+ "workers",
1100
+ "triggers",
1101
+ "deploy",
1102
+ "--prebuilt"
1103
+ ], directory));
1104
+ if (deployed.status === 0 && (raw.observability !== void 0 || raw.logpush !== void 0)) await publishCloudflareWorkerSettings({
1105
+ apiBaseUrl: apiBaseUrl(),
1106
+ accountId: accountId(),
1107
+ workerName: name,
1108
+ observability: raw.observability,
1109
+ logpush: raw.logpush,
1110
+ headers: await apiHeaders()
1111
+ });
1112
+ return deployed;
1113
+ }
1114
+ if (operation.type === "versions.upload" || operation.type === "worker.deploy") {
1115
+ const path = configPath();
1116
+ if (typeof raw.main !== "string" || !raw.main || raw.no_bundle !== true) throw new Error("Cloudflare Worker upload requires a prebuilt platform Worker.");
1117
+ const source = resolve(dirname(path), raw.main);
1118
+ const request = operation;
1119
+ const called = await withBuildOutput(raw, source, (directory) => runCf([
1120
+ ...request.type === "worker.deploy" ? ["deploy"] : [
1121
+ "workers",
1122
+ "versions",
1123
+ "create"
1124
+ ],
1125
+ "--prebuilt",
1126
+ ...request.message ? [`--message=${request.message}`] : [],
1127
+ ...request.secretsFilePath ? ["--secrets-file", request.secretsFilePath] : []
1128
+ ], directory, void 0, request.interactive === true));
1129
+ if (called.status !== 0 || request.interactive === true) return called;
1130
+ let uploaded = {};
1131
+ try {
1132
+ uploaded = object(parsedJson(called.stdout));
1133
+ } catch {}
1134
+ const printed = readCfUploadOutput(called);
1135
+ const versionId = uploaded.version_id ?? uploaded.id ?? uploaded.versionId ?? printed.versionId;
1136
+ if (typeof versionId !== "string" || !/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(versionId)) throw new Error("Cloudflare did not return the uploaded Worker version ID.");
1137
+ const previewUrl = typeof uploaded.preview_url === "string" ? uploaded.preview_url : printed.previewUrl;
1138
+ const workersDevUrl = typeof uploaded.workers_dev_url === "string" ? uploaded.workers_dev_url : printed.workersDevUrl;
1139
+ return result(0, "", called.stderr, {
1140
+ versionId,
1141
+ ...previewUrl ? { previewUrl } : {},
1142
+ ...workersDevUrl ? { workersDevUrl } : {}
1143
+ });
1144
+ }
1145
+ throw new Error("Unsupported Cloudflare Worker operation.");
1146
+ }
1147
+ async function tail() {
1148
+ if (operation.type !== "tail") throw new Error("Cloudflare tail operation is required.");
1149
+ const worker = workerName();
1150
+ const raw = config();
1151
+ const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? raw.account_id;
1152
+ if (!worker || typeof accountId !== "string" || !accountId || worker !== raw.name) throw new Error("Cloudflare tail target is not pinned.");
1153
+ const filters = [];
1154
+ if (operation.search) filters.push({ query: operation.search });
1155
+ if (operation.versionId) filters.push({ scriptVersion: operation.versionId });
1156
+ if (operation.status === "error") filters.push({ outcome: [
1157
+ "exception",
1158
+ "exceededCpu",
1159
+ "exceededMemory",
1160
+ "unknown"
1161
+ ] });
1162
+ const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(worker)}/tails`;
1163
+ const headers = {
1164
+ ...await apiHeaders(),
1165
+ "Content-Type": "application/json"
1166
+ };
1167
+ const stopped = new AbortController();
1168
+ let socket;
1169
+ let finish;
1170
+ const stop = () => {
1171
+ stopped.abort();
1172
+ socket?.close();
1173
+ finish?.();
1174
+ };
1175
+ process.once("SIGINT", stop);
1176
+ process.once("SIGTERM", stop);
1177
+ let record;
1178
+ try {
1179
+ const created = await fetch(endpoint, {
1180
+ method: "POST",
1181
+ headers,
1182
+ body: JSON.stringify({ filters }),
1183
+ signal: AbortSignal.any([stopped.signal, AbortSignal.timeout(3e4)])
1184
+ });
1185
+ const body = object(await created.json());
1186
+ if (!created.ok || body.success !== true) return result(1, "", "Could not start the Cloudflare Worker tail.");
1187
+ record = object(body.result);
1188
+ if (typeof record.id !== "string" || typeof record.url !== "string") throw new Error("Cloudflare Worker tail response was incomplete.");
1189
+ const tailUrl = record.url;
1190
+ if (stopped.signal.aborted) return result(0);
1191
+ await new Promise((resolve, reject) => {
1192
+ finish = resolve;
1193
+ let pendingMessages = Promise.resolve();
1194
+ socket = new WebSocket(tailUrl, "trace-v1");
1195
+ socket.addEventListener("open", () => {
1196
+ socket.send(JSON.stringify({ debug: false }));
1197
+ });
1198
+ socket.addEventListener("message", (event) => {
1199
+ pendingMessages = pendingMessages.then(async () => {
1200
+ const data = event.data;
1201
+ const text = typeof data === "string" ? data : data instanceof Blob ? await data.text() : data instanceof ArrayBuffer ? new TextDecoder().decode(data) : null;
1202
+ if (text === null) throw new Error("Unsupported Cloudflare tail frame.");
1203
+ const log = object(parsedJson(text));
1204
+ const detail = object(log.event ?? {});
1205
+ const request = object(detail.request ?? {});
1206
+ const prefix = typeof request.url === "string" ? `${request.method ?? "GET"} ${request.url}` : typeof detail.queue === "string" ? `Queue ${detail.queue}` : typeof detail.mailFrom === "string" ? `Email from ${detail.mailFrom}` : "Worker event";
1207
+ process.stdout.write(`${sanitizeTerminalLogText(prefix)} - ${log.outcome ?? "unknown"} @ ${new Date(Number(log.eventTimestamp)).toLocaleString()}\n`);
1208
+ if (Array.isArray(log.logs)) for (const line of log.logs.map(object)) {
1209
+ const message = Array.isArray(line.message) ? line.message.join(" ") : "";
1210
+ process.stdout.write(` (${line.level ?? "log"}) ${sanitizeTerminalLogText(message)}\n`);
1211
+ }
1212
+ if (Array.isArray(log.exceptions)) for (const exception of log.exceptions.map(object)) process.stderr.write(` ${sanitizeTerminalLogText(`${exception.name ?? "Error"}: ${exception.message ?? ""}`)}\n`);
1213
+ }).catch(() => {
1214
+ process.stderr.write("Cloudflare returned a malformed tail event.\n");
1215
+ });
1216
+ });
1217
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error("Cloudflare Worker tail connection failed.")));
1218
+ socket.addEventListener("close", () => void pendingMessages.then(resolve));
1219
+ if (stopped.signal.aborted) resolve();
1220
+ });
1221
+ } catch (error) {
1222
+ if (stopped.signal.aborted) return result(0);
1223
+ throw error;
1224
+ } finally {
1225
+ process.off("SIGINT", stop);
1226
+ process.off("SIGTERM", stop);
1227
+ socket?.close();
1228
+ if (record && typeof record.id === "string") await fetch(`${endpoint}/${encodeURIComponent(record.id)}`, {
1229
+ method: "DELETE",
1230
+ headers,
1231
+ signal: AbortSignal.timeout(5e3)
1232
+ }).catch(() => {});
1233
+ if (stopped.signal.aborted) process.exit(0);
1234
+ }
1235
+ return result(0);
1236
+ }
1237
+ async function main() {
1238
+ if (process.argv.length !== 3) throw new Error("Exactly one typed Cloudflare operation is required.");
1239
+ if (!operation || typeof operation !== "object" || typeof operation.type !== "string") throw new Error("Cloudflare operation is required.");
1240
+ if (operation.type.startsWith("auth.")) return auth();
1241
+ if (operation.type.startsWith("secret.")) return secrets();
1242
+ if (operation.type === "tail") return tail();
1243
+ if (operation.type.startsWith("email.")) return email();
1244
+ if (operation.type.startsWith("deployments.") || operation.type.startsWith("versions.") && operation.type !== "versions.upload") return workerHistory();
1245
+ if (operation.type.startsWith("triggers.") || operation.type === "worker.deploy" || operation.type === "versions.upload" || operation.type === "queues.consumer.remove") return workerChanges();
1246
+ return resources();
1247
+ }
1248
+ const terminalOperation = operation?.type === "auth.login" || operation?.type === "tail" || (operation?.type === "versions.upload" || operation?.type === "worker.deploy") && operation.interactive === true;
1249
+ try {
1250
+ const output = await main();
1251
+ if (!terminalOperation) {
1252
+ let data = output.data;
1253
+ let humanOutput = "";
1254
+ if (data === void 0 && output.stdout.trim()) try {
1255
+ data = parsedJson(output.stdout);
1256
+ } catch {
1257
+ humanOutput = output.stdout;
1258
+ }
1259
+ process.stdout.write(JSON.stringify({
1260
+ operationResult: 1,
1261
+ ...output.signal ? { signal: output.signal } : {},
1262
+ ...output.error ? { error: output.error } : {},
1263
+ ...data !== void 0 ? { data } : {},
1264
+ ...output.errorCode !== void 0 ? { errorCode: output.errorCode } : {},
1265
+ ...output.failure ? { failure: output.failure } : {},
1266
+ ...output.stderr ? { errors: [{
1267
+ code: output.errorCode,
1268
+ message: output.stderr
1269
+ }] } : {},
1270
+ ...humanOutput ? { output: humanOutput } : {}
1271
+ }) + "\n");
1272
+ }
1273
+ if (output.stderr) process.stderr.write(output.stderr);
1274
+ process.exitCode = output.status;
1275
+ } catch (error) {
1276
+ const message = error instanceof Error ? error.message : "Cloudflare operation failed.";
1277
+ if (!terminalOperation) process.stdout.write(JSON.stringify({
1278
+ operationResult: 1,
1279
+ errors: [{ message }]
1280
+ }) + "\n");
1281
+ process.stderr.write(message);
1282
+ process.exitCode = 1;
1283
+ }
1284
+ export {};