@geekmidas/cli 10.0.0-alpha.11 → 10.0.0-alpha.110

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 (501) hide show
  1. package/README.md +315 -414
  2. package/bin/adjacent-tsconfig.mjs +46 -8
  3. package/bin/gkm.mjs +11 -3
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-BwbYTMtB.cjs +1090 -0
  7. package/dist/EndpointGenerator-BwbYTMtB.cjs.map +1 -0
  8. package/dist/EndpointGenerator-CvLX8bpx.mjs +1031 -0
  9. package/dist/EndpointGenerator-CvLX8bpx.mjs.map +1 -0
  10. package/dist/GoDaddyProvider-CjeOduia.mjs +388 -0
  11. package/dist/GoDaddyProvider-CjeOduia.mjs.map +1 -0
  12. package/dist/GoDaddyProvider-qNUzTXI7.cjs +388 -0
  13. package/dist/GoDaddyProvider-qNUzTXI7.cjs.map +1 -0
  14. package/dist/{HostingerProvider-BcyFRbqV.mjs → HostingerProvider-BNpS9aRJ.mjs} +29 -25
  15. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +1 -0
  16. package/dist/{HostingerProvider-BOvsgATO.cjs → HostingerProvider-DR1iws1P.cjs} +29 -25
  17. package/dist/HostingerProvider-DR1iws1P.cjs.map +1 -0
  18. package/dist/LegacyStateStore-MxiSu7KJ.cjs +124 -0
  19. package/dist/LegacyStateStore-MxiSu7KJ.cjs.map +1 -0
  20. package/dist/LegacyStateStore-pgscYsiG.mjs +124 -0
  21. package/dist/LegacyStateStore-pgscYsiG.mjs.map +1 -0
  22. package/dist/LocalStateStore-BcvyKbAw.mjs +167 -0
  23. package/dist/LocalStateStore-BcvyKbAw.mjs.map +1 -0
  24. package/dist/LocalStateStore-Bm8Vmwjb.cjs +178 -0
  25. package/dist/LocalStateStore-Bm8Vmwjb.cjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-BD6ZOQ51.cjs +541 -0
  27. package/dist/OpenApiTsGenerator-BD6ZOQ51.cjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-DXXFXSbO.mjs +536 -0
  29. package/dist/OpenApiTsGenerator-DXXFXSbO.mjs.map +1 -0
  30. package/dist/{Route53Provider-CH9XH7bz.cjs → Route53Provider-Bllus2NR.cjs} +21 -22
  31. package/dist/Route53Provider-Bllus2NR.cjs.map +1 -0
  32. package/dist/{Route53Provider-C0xmer8U.mjs → Route53Provider-QXxjkZO1.mjs} +13 -13
  33. package/dist/Route53Provider-QXxjkZO1.mjs.map +1 -0
  34. package/dist/S3StateStore-DXHSBVsV.cjs +222 -0
  35. package/dist/S3StateStore-DXHSBVsV.cjs.map +1 -0
  36. package/dist/S3StateStore-H2XsAzpJ.mjs +223 -0
  37. package/dist/S3StateStore-H2XsAzpJ.mjs.map +1 -0
  38. package/dist/SSMStateStore-BLPSNl-U.cjs +204 -0
  39. package/dist/SSMStateStore-BLPSNl-U.cjs.map +1 -0
  40. package/dist/SSMStateStore-CENciQEM.mjs +205 -0
  41. package/dist/SSMStateStore-CENciQEM.mjs.map +1 -0
  42. package/dist/SubscriberGenerator-CeH7wbYt.cjs +571 -0
  43. package/dist/SubscriberGenerator-CeH7wbYt.cjs.map +1 -0
  44. package/dist/SubscriberGenerator-DHnIYwUU.mjs +518 -0
  45. package/dist/SubscriberGenerator-DHnIYwUU.mjs.map +1 -0
  46. package/dist/add-Cdg1kEqN.cjs +719 -0
  47. package/dist/add-Cdg1kEqN.cjs.map +1 -0
  48. package/dist/add-snhdVmR-.mjs +717 -0
  49. package/dist/add-snhdVmR-.mjs.map +1 -0
  50. package/dist/appPorts-BoXMwolc.mjs +249 -0
  51. package/dist/appPorts-BoXMwolc.mjs.map +1 -0
  52. package/dist/appPorts-IW-OZmRi.cjs +296 -0
  53. package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
  54. package/dist/aws-8QQ8n-t6.mjs +89 -0
  55. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  56. package/dist/aws-DY9NqQIT.cjs +100 -0
  57. package/dist/aws-DY9NqQIT.cjs.map +1 -0
  58. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  59. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  60. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  61. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  62. package/dist/{backup-provisioner-DXXg6FIL.mjs → backup-provisioner-C8DnCmxK.mjs} +11 -8
  63. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  64. package/dist/{backup-provisioner-cE2PuCTb.cjs → backup-provisioner-oDEsPj02.cjs} +22 -20
  65. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  66. package/dist/backups/runner.cjs +519 -0
  67. package/dist/backups/runner.cjs.map +1 -0
  68. package/dist/backups/runner.d.cts +102 -0
  69. package/dist/backups/runner.d.cts.map +1 -0
  70. package/dist/backups/runner.d.mts +102 -0
  71. package/dist/backups/runner.d.mts.map +1 -0
  72. package/dist/backups/runner.mjs +506 -0
  73. package/dist/backups/runner.mjs.map +1 -0
  74. package/dist/{bundler-CaTGtiaO.cjs → bundler-B4GDxImV.cjs} +38 -35
  75. package/dist/bundler-B4GDxImV.cjs.map +1 -0
  76. package/dist/{bundler-S3ek7ea-.mjs → bundler-Wd9H4QLJ.mjs} +36 -32
  77. package/dist/bundler-Wd9H4QLJ.mjs.map +1 -0
  78. package/dist/cli-BZYz55tO.cjs +71 -0
  79. package/dist/cli-BZYz55tO.cjs.map +1 -0
  80. package/dist/cli-BzrDSNSg.mjs +71 -0
  81. package/dist/cli-BzrDSNSg.mjs.map +1 -0
  82. package/dist/compose-DN9zySvQ.cjs +3330 -0
  83. package/dist/compose-DN9zySvQ.cjs.map +1 -0
  84. package/dist/compose-Gsd1Nq7R.mjs +3187 -0
  85. package/dist/compose-Gsd1Nq7R.mjs.map +1 -0
  86. package/dist/config-D48erO2j.d.mts +269 -0
  87. package/dist/config-D48erO2j.d.mts.map +1 -0
  88. package/dist/config-DHDtsQrB.d.cts +269 -0
  89. package/dist/config-DHDtsQrB.d.cts.map +1 -0
  90. package/dist/config.cjs +421 -11
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -120
  93. package/dist/config.d.mts +4 -120
  94. package/dist/config.mjs +405 -4
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-Cf5Pf8VE.mjs +237 -0
  97. package/dist/credentialSchemas-Cf5Pf8VE.mjs.map +1 -0
  98. package/dist/credentialSchemas-D_VUCDUh.cjs +272 -0
  99. package/dist/credentialSchemas-D_VUCDUh.cjs.map +1 -0
  100. package/dist/credentials-B5N5yKk6.mjs +267 -0
  101. package/dist/credentials-B5N5yKk6.mjs.map +1 -0
  102. package/dist/credentials-Zqr3QQYB.cjs +350 -0
  103. package/dist/credentials-Zqr3QQYB.cjs.map +1 -0
  104. package/dist/databases-BeGP5eDh.mjs +495 -0
  105. package/dist/databases-BeGP5eDh.mjs.map +1 -0
  106. package/dist/databases-DGALFDG3.cjs +598 -0
  107. package/dist/databases-DGALFDG3.cjs.map +1 -0
  108. package/dist/define-6poNqm5O.mjs +106 -0
  109. package/dist/define-6poNqm5O.mjs.map +1 -0
  110. package/dist/define-crmMcXFS.cjs +153 -0
  111. package/dist/define-crmMcXFS.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +212 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +653 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +653 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +145 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envkit-patch.cjs +18 -10
  121. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  122. package/dist/deploy/sniffer-envkit-patch.d.cts +0 -2
  123. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  124. package/dist/deploy/sniffer-envkit-patch.d.mts +0 -2
  125. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  126. package/dist/deploy/sniffer-envkit-patch.mjs +10 -2
  127. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  128. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  129. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  130. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  131. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  132. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  133. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  134. package/dist/deploy/sniffer-hooks.cjs +13 -7
  135. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  136. package/dist/deploy/sniffer-hooks.d.cts +1 -2
  137. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  138. package/dist/deploy/sniffer-hooks.d.mts +1 -2
  139. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  140. package/dist/deploy/sniffer-hooks.mjs +10 -3
  141. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  142. package/dist/deploy/sniffer-loader.cjs +16 -7
  143. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  144. package/dist/deploy/sniffer-loader.d.cts +1 -1
  145. package/dist/deploy/sniffer-loader.d.mts +1 -1
  146. package/dist/deploy/sniffer-loader.mjs +14 -3
  147. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  148. package/dist/deploy/sniffer-routes-worker.cjs +11 -11
  149. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  150. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  151. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  152. package/dist/deploy/sniffer-routes-worker.mjs +4 -4
  153. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  154. package/dist/deploy/sniffer-worker.cjs +15 -6
  155. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  156. package/dist/deploy/sniffer-worker.d.cts +1 -3
  157. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  158. package/dist/deploy/sniffer-worker.d.mts +1 -3
  159. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  160. package/dist/deploy/sniffer-worker.mjs +15 -4
  161. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  162. package/dist/deploy-CFvq8daZ.cjs +2390 -0
  163. package/dist/deploy-CFvq8daZ.cjs.map +1 -0
  164. package/dist/deploy-H2S8_mTx.mjs +2317 -0
  165. package/dist/deploy-H2S8_mTx.mjs.map +1 -0
  166. package/dist/derive-B4vDpzgP.mjs +150 -0
  167. package/dist/derive-B4vDpzgP.mjs.map +1 -0
  168. package/dist/derive-DAbo49sm.cjs +161 -0
  169. package/dist/derive-DAbo49sm.cjs.map +1 -0
  170. package/dist/discover-Bsr7HjqJ.cjs +616 -0
  171. package/dist/discover-Bsr7HjqJ.cjs.map +1 -0
  172. package/dist/discover-Ca8U75dl.mjs +537 -0
  173. package/dist/discover-Ca8U75dl.mjs.map +1 -0
  174. package/dist/discover-CvTtV5ZD.d.cts +108 -0
  175. package/dist/discover-CvTtV5ZD.d.cts.map +1 -0
  176. package/dist/discover-W2kab9Lc.d.mts +108 -0
  177. package/dist/discover-W2kab9Lc.d.mts.map +1 -0
  178. package/dist/dns-BdETzP10.cjs +1057 -0
  179. package/dist/dns-BdETzP10.cjs.map +1 -0
  180. package/dist/dns-pFMShDqW.mjs +926 -0
  181. package/dist/dns-pFMShDqW.mjs.map +1 -0
  182. package/dist/dokploy-HioAjP7K.cjs +38 -0
  183. package/dist/dokploy-HioAjP7K.cjs.map +1 -0
  184. package/dist/dokploy-oDJbnvCb.mjs +38 -0
  185. package/dist/dokploy-oDJbnvCb.mjs.map +1 -0
  186. package/dist/drivers-D11JHxrD.mjs +177 -0
  187. package/dist/drivers-D11JHxrD.mjs.map +1 -0
  188. package/dist/drivers-GKaA6ITM.cjs +200 -0
  189. package/dist/drivers-GKaA6ITM.cjs.map +1 -0
  190. package/dist/{emit-CIlvnDvV.mjs → emit-C1e8qD08.mjs} +13 -26
  191. package/dist/emit-C1e8qD08.mjs.map +1 -0
  192. package/dist/{emit-CUD1BWls.cjs → emit-Dmc1nvdS.cjs} +31 -57
  193. package/dist/emit-Dmc1nvdS.cjs.map +1 -0
  194. package/dist/encryption-D5pDJyp2.mjs +89 -0
  195. package/dist/encryption-D5pDJyp2.mjs.map +1 -0
  196. package/dist/encryption-DVCxD-gV.cjs +90 -0
  197. package/dist/encryption-DVCxD-gV.cjs.map +1 -0
  198. package/dist/engine-BaJGPzte.cjs +3196 -0
  199. package/dist/engine-BaJGPzte.cjs.map +1 -0
  200. package/dist/engine-CfAKgr2_.mjs +3083 -0
  201. package/dist/engine-CfAKgr2_.mjs.map +1 -0
  202. package/dist/errors-D8Gwp5kU.mjs +23 -0
  203. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  204. package/dist/errors-DMC4Umsb.cjs +34 -0
  205. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  206. package/dist/github-D902Vwr9.cjs +829 -0
  207. package/dist/github-D902Vwr9.cjs.map +1 -0
  208. package/dist/github-E-ZxqFPq.mjs +829 -0
  209. package/dist/github-E-ZxqFPq.mjs.map +1 -0
  210. package/dist/identity-CBXr4wNi.mjs +129 -0
  211. package/dist/identity-CBXr4wNi.mjs.map +1 -0
  212. package/dist/identity-CbLfgQNT.cjs +182 -0
  213. package/dist/identity-CbLfgQNT.cjs.map +1 -0
  214. package/dist/{index-Ayxg_DQY.d.mts → index-8OfpOtSI.d.cts} +39 -24
  215. package/dist/index-8OfpOtSI.d.cts.map +1 -0
  216. package/dist/{index-CR5urhWX.d.cts → index-Dpji6Bxq.d.mts} +39 -24
  217. package/dist/index-Dpji6Bxq.d.mts.map +1 -0
  218. package/dist/index.cjs +13764 -12651
  219. package/dist/index.cjs.map +1 -1
  220. package/dist/index.d.cts +1 -1
  221. package/dist/index.d.mts +1 -1
  222. package/dist/index.mjs +13654 -12553
  223. package/dist/index.mjs.map +1 -1
  224. package/dist/local-BwC2v2Y8.mjs +224 -0
  225. package/dist/local-BwC2v2Y8.mjs.map +1 -0
  226. package/dist/local-DNhnkugT.cjs +241 -0
  227. package/dist/local-DNhnkugT.cjs.map +1 -0
  228. package/dist/migrate-BZ0GnSZQ.mjs +181 -0
  229. package/dist/migrate-BZ0GnSZQ.mjs.map +1 -0
  230. package/dist/migrate-CTqhWtev.cjs +271 -0
  231. package/dist/migrate-CTqhWtev.cjs.map +1 -0
  232. package/dist/migrate-DCXwHcWX.mjs +266 -0
  233. package/dist/migrate-DCXwHcWX.mjs.map +1 -0
  234. package/dist/migrate-Df81ew0k.cjs +181 -0
  235. package/dist/migrate-Df81ew0k.cjs.map +1 -0
  236. package/dist/openapi.cjs +214 -10
  237. package/dist/openapi.cjs.map +1 -0
  238. package/dist/openapi.d.cts +38 -17
  239. package/dist/openapi.d.cts.map +1 -1
  240. package/dist/openapi.d.mts +38 -17
  241. package/dist/openapi.d.mts.map +1 -1
  242. package/dist/openapi.mjs +208 -5
  243. package/dist/openapi.mjs.map +1 -0
  244. package/dist/projectBucket-BBbQ1lHF.cjs +263 -0
  245. package/dist/projectBucket-BBbQ1lHF.cjs.map +1 -0
  246. package/dist/projectBucket-C_DN4WzF.mjs +222 -0
  247. package/dist/projectBucket-C_DN4WzF.mjs.map +1 -0
  248. package/dist/provider-BqpjG9QM.cjs +57 -0
  249. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  250. package/dist/provider-CEOKk8NS.mjs +46 -0
  251. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  252. package/dist/ready-BMFjxBYA.cjs +404 -0
  253. package/dist/ready-BMFjxBYA.cjs.map +1 -0
  254. package/dist/ready-CIt5SOtg.mjs +375 -0
  255. package/dist/ready-CIt5SOtg.mjs.map +1 -0
  256. package/dist/reconcile/public.cjs +3 -5
  257. package/dist/reconcile/public.d.cts +11 -87
  258. package/dist/reconcile/public.d.cts.map +1 -1
  259. package/dist/reconcile/public.d.mts +11 -87
  260. package/dist/reconcile/public.d.mts.map +1 -1
  261. package/dist/reconcile/public.mjs +3 -4
  262. package/dist/{reconcile-C13ERt1U.mjs → reconcile--I7V4Klj.mjs} +4 -7
  263. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  264. package/dist/{reconcile-CYMhFSYy.cjs → reconcile-CuCQBa5-.cjs} +5 -8
  265. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  266. package/dist/resolve-BMpPd8x3.mjs +263 -0
  267. package/dist/resolve-BMpPd8x3.mjs.map +1 -0
  268. package/dist/resolve-D043YmW9.cjs +316 -0
  269. package/dist/resolve-D043YmW9.cjs.map +1 -0
  270. package/dist/rollback-CBiYsQ3T.cjs +165 -0
  271. package/dist/rollback-CBiYsQ3T.cjs.map +1 -0
  272. package/dist/rollback-CDs_XNb0.mjs +136 -0
  273. package/dist/rollback-CDs_XNb0.mjs.map +1 -0
  274. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  275. package/dist/{chunk-CUT6urMc.cjs → rolldown-runtime-C0BPl7ul.cjs} +23 -10
  276. package/dist/run-BJLIerMM.mjs +133 -0
  277. package/dist/run-BJLIerMM.mjs.map +1 -0
  278. package/dist/run-fVZ-rLnc.cjs +174 -0
  279. package/dist/run-fVZ-rLnc.cjs.map +1 -0
  280. package/dist/runtime-ACdfK59n.d.cts +82 -0
  281. package/dist/runtime-ACdfK59n.d.cts.map +1 -0
  282. package/dist/runtime-YyQuekxi.d.mts +82 -0
  283. package/dist/runtime-YyQuekxi.d.mts.map +1 -0
  284. package/dist/s3-CrPoA89T.cjs +215 -0
  285. package/dist/s3-CrPoA89T.cjs.map +1 -0
  286. package/dist/s3-DQXZdmCM.mjs +215 -0
  287. package/dist/s3-DQXZdmCM.mjs.map +1 -0
  288. package/dist/sandbox/config-worker.cjs +43 -0
  289. package/dist/sandbox/config-worker.cjs.map +1 -0
  290. package/dist/sandbox/config-worker.d.cts +1 -0
  291. package/dist/sandbox/config-worker.d.mts +1 -0
  292. package/dist/sandbox/config-worker.mjs +44 -0
  293. package/dist/sandbox/config-worker.mjs.map +1 -0
  294. package/dist/sandbox/credentials-worker.cjs +54 -0
  295. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  296. package/dist/sandbox/credentials-worker.d.cts +1 -0
  297. package/dist/sandbox/credentials-worker.d.mts +1 -0
  298. package/dist/sandbox/credentials-worker.mjs +55 -0
  299. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  300. package/dist/sandbox/discover-worker.cjs +47 -0
  301. package/dist/sandbox/discover-worker.cjs.map +1 -0
  302. package/dist/sandbox/discover-worker.d.cts +1 -0
  303. package/dist/sandbox/discover-worker.d.mts +1 -0
  304. package/dist/sandbox/discover-worker.mjs +48 -0
  305. package/dist/sandbox/discover-worker.mjs.map +1 -0
  306. package/dist/sandbox/migrate-worker.cjs +75 -0
  307. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  308. package/dist/sandbox/migrate-worker.d.cts +1 -0
  309. package/dist/sandbox/migrate-worker.d.mts +1 -0
  310. package/dist/sandbox/migrate-worker.mjs +76 -0
  311. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  312. package/dist/sandbox-C4g1eG31.d.mts +104 -0
  313. package/dist/sandbox-C4g1eG31.d.mts.map +1 -0
  314. package/dist/sandbox-CHv3OYXg.cjs +165 -0
  315. package/dist/sandbox-CHv3OYXg.cjs.map +1 -0
  316. package/dist/sandbox-CbVB7uOD.mjs +118 -0
  317. package/dist/sandbox-CbVB7uOD.mjs.map +1 -0
  318. package/dist/sandbox-CdKgQ3XU.d.cts +104 -0
  319. package/dist/sandbox-CdKgQ3XU.d.cts.map +1 -0
  320. package/dist/{workspace-C-a3G_U0.cjs → schemas-BCwKKA42.mjs} +958 -1868
  321. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  322. package/dist/{workspace-DaEX7FEg.mjs → schemas-BQ_v0lEX.cjs} +1048 -1678
  323. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  324. package/dist/secretsManager-CQORubp9.mjs +97 -0
  325. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  326. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  327. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  328. package/dist/seeds-BjcO4DDa.mjs +8194 -0
  329. package/dist/seeds-BjcO4DDa.mjs.map +1 -0
  330. package/dist/seeds-DNqRA1aQ.cjs +9173 -0
  331. package/dist/seeds-DNqRA1aQ.cjs.map +1 -0
  332. package/dist/sniffer-DipSS8r8.cjs +1998 -0
  333. package/dist/sniffer-DipSS8r8.cjs.map +1 -0
  334. package/dist/sniffer-b0XPmSyT.mjs +1825 -0
  335. package/dist/sniffer-b0XPmSyT.mjs.map +1 -0
  336. package/dist/sst-B-Uz4cvm.cjs +464 -0
  337. package/dist/sst-B-Uz4cvm.cjs.map +1 -0
  338. package/dist/sst-C1pxbFEd.mjs +441 -0
  339. package/dist/sst-C1pxbFEd.mjs.map +1 -0
  340. package/dist/stage-C_y2UovO.cjs +266 -0
  341. package/dist/stage-C_y2UovO.cjs.map +1 -0
  342. package/dist/stage-DrDmZusd.mjs +266 -0
  343. package/dist/stage-DrDmZusd.mjs.map +1 -0
  344. package/dist/stages-DJrOYLZ-.mjs +176 -0
  345. package/dist/stages-DJrOYLZ-.mjs.map +1 -0
  346. package/dist/stages-_3RVNG83.cjs +176 -0
  347. package/dist/stages-_3RVNG83.cjs.map +1 -0
  348. package/dist/target/public.cjs +15 -0
  349. package/dist/target/public.d.cts +28 -0
  350. package/dist/target/public.d.cts.map +1 -0
  351. package/dist/target/public.d.mts +28 -0
  352. package/dist/target/public.d.mts.map +1 -0
  353. package/dist/target/public.mjs +4 -0
  354. package/dist/terminal-CvRLxz6g.mjs +85 -0
  355. package/dist/terminal-CvRLxz6g.mjs.map +1 -0
  356. package/dist/terminal-D_NRPW4W.cjs +85 -0
  357. package/dist/terminal-D_NRPW4W.cjs.map +1 -0
  358. package/dist/types-B6UXlEkf.d.cts +7650 -0
  359. package/dist/types-B6UXlEkf.d.cts.map +1 -0
  360. package/dist/types-HqVPddRK.d.mts +7649 -0
  361. package/dist/types-HqVPddRK.d.mts.map +1 -0
  362. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  363. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  364. package/dist/utils-D_fxUqvU.mjs +156 -0
  365. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  366. package/dist/vitest.cjs +65 -0
  367. package/dist/vitest.cjs.map +1 -0
  368. package/dist/vitest.d.cts +29 -0
  369. package/dist/vitest.d.cts.map +1 -0
  370. package/dist/vitest.d.mts +29 -0
  371. package/dist/vitest.d.mts.map +1 -0
  372. package/dist/vitest.mjs +65 -0
  373. package/dist/vitest.mjs.map +1 -0
  374. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  375. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  376. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  377. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  378. package/dist/workspace/index.cjs +8 -4
  379. package/dist/workspace/index.d.cts +3 -3
  380. package/dist/workspace/index.d.mts +3 -3
  381. package/dist/workspace/index.mjs +2 -3
  382. package/dist/workspace-BwqQnool.cjs +2806 -0
  383. package/dist/workspace-BwqQnool.cjs.map +1 -0
  384. package/dist/workspace-D1QbNd55.mjs +2394 -0
  385. package/dist/workspace-D1QbNd55.mjs.map +1 -0
  386. package/package.json +54 -22
  387. package/dist/CachedStateProvider-BEBl2wQT.cjs +0 -60
  388. package/dist/CachedStateProvider-BEBl2wQT.cjs.map +0 -1
  389. package/dist/CachedStateProvider-C-8wtlto.mjs +0 -3
  390. package/dist/CachedStateProvider-Co4n5Wvs.mjs +0 -54
  391. package/dist/CachedStateProvider-Co4n5Wvs.mjs.map +0 -1
  392. package/dist/CachedStateProvider-DqhGpzsm.cjs +0 -3
  393. package/dist/HostingerProvider-BOvsgATO.cjs.map +0 -1
  394. package/dist/HostingerProvider-BcyFRbqV.mjs.map +0 -1
  395. package/dist/LocalStateProvider-Bq-0C0sg.mjs +0 -42
  396. package/dist/LocalStateProvider-Bq-0C0sg.mjs.map +0 -1
  397. package/dist/LocalStateProvider-yjXZXZDM.cjs +0 -43
  398. package/dist/LocalStateProvider-yjXZXZDM.cjs.map +0 -1
  399. package/dist/Route53Provider-C0xmer8U.mjs.map +0 -1
  400. package/dist/Route53Provider-CH9XH7bz.cjs.map +0 -1
  401. package/dist/SSMStateProvider-CXtNgPfy.cjs +0 -66
  402. package/dist/SSMStateProvider-CXtNgPfy.cjs.map +0 -1
  403. package/dist/SSMStateProvider-DOZifZfE.mjs +0 -66
  404. package/dist/SSMStateProvider-DOZifZfE.mjs.map +0 -1
  405. package/dist/backup-provisioner-DXXg6FIL.mjs.map +0 -1
  406. package/dist/backup-provisioner-cE2PuCTb.cjs.map +0 -1
  407. package/dist/bundler-CaTGtiaO.cjs.map +0 -1
  408. package/dist/bundler-S3ek7ea-.mjs.map +0 -1
  409. package/dist/chunk-Duj1WY3L.mjs +0 -7
  410. package/dist/config-B0L2tvvC.mjs +0 -402
  411. package/dist/config-B0L2tvvC.mjs.map +0 -1
  412. package/dist/config-HhDpJmLO.cjs +0 -462
  413. package/dist/config-HhDpJmLO.cjs.map +0 -1
  414. package/dist/config.d.cts.map +0 -1
  415. package/dist/config.d.mts.map +0 -1
  416. package/dist/credentials-B2Pyh3bJ.cjs +0 -2681
  417. package/dist/credentials-B2Pyh3bJ.cjs.map +0 -1
  418. package/dist/credentials-B5zRHdAl.mjs +0 -141
  419. package/dist/credentials-B5zRHdAl.mjs.map +0 -1
  420. package/dist/credentials-BapzjyV5.cjs +0 -195
  421. package/dist/credentials-BapzjyV5.cjs.map +0 -1
  422. package/dist/credentials-CZrys9C5.mjs +0 -2549
  423. package/dist/credentials-CZrys9C5.mjs.map +0 -1
  424. package/dist/discover-CAlFgYec.mjs +0 -229
  425. package/dist/discover-CAlFgYec.mjs.map +0 -1
  426. package/dist/discover-DTmFeloL.cjs +0 -271
  427. package/dist/discover-DTmFeloL.cjs.map +0 -1
  428. package/dist/dokploy-api-5cK2InBm.cjs +0 -3
  429. package/dist/dokploy-api-D2Ny4Jrc.mjs +0 -3
  430. package/dist/dokploy-api-pdaBryoY.mjs +0 -706
  431. package/dist/dokploy-api-pdaBryoY.mjs.map +0 -1
  432. package/dist/dokploy-api-zqKe9lHH.cjs +0 -718
  433. package/dist/dokploy-api-zqKe9lHH.cjs.map +0 -1
  434. package/dist/emit-CIlvnDvV.mjs.map +0 -1
  435. package/dist/emit-CUD1BWls.cjs.map +0 -1
  436. package/dist/encryption-D2pL3tHH.cjs +0 -54
  437. package/dist/encryption-D2pL3tHH.cjs.map +0 -1
  438. package/dist/encryption-YDsXXi6w.mjs +0 -3
  439. package/dist/encryption-_4zwjOAR.mjs +0 -42
  440. package/dist/encryption-_4zwjOAR.mjs.map +0 -1
  441. package/dist/encryption-sQ2Oxx0d.cjs +0 -4
  442. package/dist/fullstack-secrets-D6MyHhQP.cjs +0 -111
  443. package/dist/fullstack-secrets-D6MyHhQP.cjs.map +0 -1
  444. package/dist/fullstack-secrets-METaRLS1.mjs +0 -87
  445. package/dist/fullstack-secrets-METaRLS1.mjs.map +0 -1
  446. package/dist/generator-CNzBw7g5.cjs +0 -289
  447. package/dist/generator-CNzBw7g5.cjs.map +0 -1
  448. package/dist/generator-VE2JrFlY.mjs +0 -253
  449. package/dist/generator-VE2JrFlY.mjs.map +0 -1
  450. package/dist/github-BrvaPkFf.cjs +0 -197
  451. package/dist/github-BrvaPkFf.cjs.map +0 -1
  452. package/dist/github-CrpsXSfV.mjs +0 -196
  453. package/dist/github-CrpsXSfV.mjs.map +0 -1
  454. package/dist/index-Ayxg_DQY.d.mts.map +0 -1
  455. package/dist/index-CR5urhWX.d.cts.map +0 -1
  456. package/dist/keystore-C9rint2E.cjs +0 -101
  457. package/dist/keystore-C9rint2E.cjs.map +0 -1
  458. package/dist/keystore-TxeYM7an.mjs +0 -83
  459. package/dist/keystore-TxeYM7an.mjs.map +0 -1
  460. package/dist/openapi-DaKlTKxz.cjs +0 -2075
  461. package/dist/openapi-DaKlTKxz.cjs.map +0 -1
  462. package/dist/openapi-react-query-BKH334Ug.cjs +0 -173
  463. package/dist/openapi-react-query-BKH334Ug.cjs.map +0 -1
  464. package/dist/openapi-react-query-DoR5CmzQ.mjs +0 -167
  465. package/dist/openapi-react-query-DoR5CmzQ.mjs.map +0 -1
  466. package/dist/openapi-react-query.cjs +0 -4
  467. package/dist/openapi-react-query.d.cts +0 -11
  468. package/dist/openapi-react-query.d.cts.map +0 -1
  469. package/dist/openapi-react-query.d.mts +0 -11
  470. package/dist/openapi-react-query.d.mts.map +0 -1
  471. package/dist/openapi-react-query.mjs +0 -4
  472. package/dist/openapi-y1d7Kalt.mjs +0 -2021
  473. package/dist/openapi-y1d7Kalt.mjs.map +0 -1
  474. package/dist/reconcile-C13ERt1U.mjs.map +0 -1
  475. package/dist/reconcile-CYMhFSYy.cjs.map +0 -1
  476. package/dist/setup-BWgMs4gg.mjs +0 -12
  477. package/dist/setup-DOv92pIu.cjs +0 -473
  478. package/dist/setup-DOv92pIu.cjs.map +0 -1
  479. package/dist/setup-DQo_h_yK.mjs +0 -443
  480. package/dist/setup-DQo_h_yK.mjs.map +0 -1
  481. package/dist/setup-lCx_DcUo.cjs +0 -12
  482. package/dist/storage-B020InPW.mjs +0 -222
  483. package/dist/storage-B020InPW.mjs.map +0 -1
  484. package/dist/storage-CSNplaJn.cjs +0 -282
  485. package/dist/storage-CSNplaJn.cjs.map +0 -1
  486. package/dist/storage-DGBzMLZa.mjs +0 -4
  487. package/dist/storage-DlVol_oj.cjs +0 -8
  488. package/dist/sync-0ILCb-1S.cjs +0 -93
  489. package/dist/sync-0ILCb-1S.cjs.map +0 -1
  490. package/dist/sync-CzHXiR9c.mjs +0 -76
  491. package/dist/sync-CzHXiR9c.mjs.map +0 -1
  492. package/dist/sync-DYENfOt4.cjs +0 -4
  493. package/dist/sync-HAau6h_R.mjs +0 -3
  494. package/dist/types-CL7jPFM2.d.mts +0 -2220
  495. package/dist/types-CL7jPFM2.d.mts.map +0 -1
  496. package/dist/types-Y3fKQSAK.d.cts +0 -2220
  497. package/dist/types-Y3fKQSAK.d.cts.map +0 -1
  498. package/dist/workspace-C-a3G_U0.cjs.map +0 -1
  499. package/dist/workspace-DQxxs7Jk.cjs +0 -10
  500. package/dist/workspace-DaEX7FEg.mjs.map +0 -1
  501. package/dist/workspace-DbI580qS.mjs +0 -9
@@ -0,0 +1,2317 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { s as gkmHome } from "./run-BJLIerMM.mjs";
3
+ import { r as storedCredentials } from "./credentials-B5N5yKk6.mjs";
4
+ import { $ as IamUserNotOwned, G as checkS3Config, J as BucketNameUnavailable, K as AccessKeyLimit, L as resolveStageTelemetry, N as assertDeployedStage, Q as BucketRegionUnknown, U as stageProvider, W as S3_PROVISIONING, X as BucketProbeFailed, Y as BucketOwnedByAnotherProject, Z as BucketRegionMismatch, et as ProvisionedBucketUnreachable, ht as isReservedStageKey, nt as RotationInProgress, q as BucketKeySetElsewhere, rt as S3RegionRequired, tt as RecordedBucketUnreachable, u as getAppBuildOrder } from "./workspace-D1QbNd55.mjs";
5
+ import { S as deploysWithCompose, _ as backupExpiries, c as stageDnsDomains, d as BACKUPS_URL_KEY, n as dnsCredentials, u as BACKUPS_SERVICE, x as stageBackups, y as backupsPrefix } from "./dns-pFMShDqW.mjs";
6
+ import { o as builtinTarget } from "./define-6poNqm5O.mjs";
7
+ import { $ as devServicesUsed, $n as resolveHost, A as assertStageProvidersEnabled, Fn as usesTelemetry, It as secretsStoreFor, M as stageProviderNotes, N as PROVIDER_KINDS, Qn as isMainFrontendApp, X as ExternalServicesNotConfigured, Y as DevServicesNeedServerTarget, Zn as NoDomainForStage, _ as createComposeState, at as appEnvKeys, dt as constructGlobs, et as externalServices, rt as stageServiceDeclarations, tt as reportDevServices, u as DeployJournal, v as createEmptyState, zt as initStageSecrets } from "./seeds-BjcO4DDa.mjs";
8
+ import { n as derivedApps, t as appKey } from "./derive-B4vDpzgP.mjs";
9
+ import { n as deployIdentity, t as applicationName } from "./identity-CBXr4wNi.mjs";
10
+ import { i as discover, p as withOutput } from "./discover-Ca8U75dl.mjs";
11
+ import { c as withSandbox } from "./sandbox-CbVB7uOD.mjs";
12
+ import { findWorkspaceRoot, loadWorkspaceConfig } from "./config.mjs";
13
+ import { a as parseTargetOptions, o as resolveTarget } from "./resolve-BMpPd8x3.mjs";
14
+ import { t as LocalSandbox } from "./local-BwC2v2Y8.mjs";
15
+ import { E as eventError, S as createStateStore, v as assertStateOutlivesRun, y as assertStateRoom } from "./sniffer-b0XPmSyT.mjs";
16
+ import { a as findProjectBucket, i as ensureProjectBucket, o as projectBucketName, r as callerAccountId, s as reconcileProjectBucketLifecycle } from "./projectBucket-C_DN4WzF.mjs";
17
+ import { n as assertStageCredentials } from "./credentialSchemas-Cf5Pf8VE.mjs";
18
+ import { resolve } from "node:path";
19
+ import { randomInt } from "node:crypto";
20
+ import { dependentsOf, kebabCase, provideKey, providedKeyFor } from "@geekmidas/manifest";
21
+ import * as s3Url from "@geekmidas/storage/s3-url";
22
+ //#region src/providers/aws.ts
23
+ /**
24
+ * The AWS account a provider provisions in — the stage's, found the way the
25
+ * SSM and Secrets Manager stores find it.
26
+ *
27
+ * 1. `--profile`, resolved on its own: exported keys left over from another
28
+ * account never win over a profile someone named.
29
+ * 2. `AWS_PROFILE`, else `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` — the
30
+ * deploy's own `aws` credential kind (`storedCredentials`).
31
+ * 3. The SDK's default chain: `~/.aws` default profile, SSO, a role. In CI,
32
+ * whatever `aws-actions/configure-aws-credentials` exported.
33
+ *
34
+ * None of them: the provider has no provisioning credentials, and the stage
35
+ * is treated as `external`.
36
+ */
37
+ async function awsProvisioningCredentials(lookup) {
38
+ const region = lookup.env.AWS_REGION ?? lookup.env.AWS_DEFAULT_REGION;
39
+ const where = region ? { region } : {};
40
+ if (lookup.profile) return {
41
+ profile: lookup.profile,
42
+ ...where
43
+ };
44
+ const stored = await storedCredentials({
45
+ env: lookup.env,
46
+ ...lookup.home ? { home: lookup.home } : {}
47
+ }).get({
48
+ kind: "aws",
49
+ stage: lookup.stage
50
+ });
51
+ if (stored) return stored;
52
+ try {
53
+ const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
54
+ await fromNodeProviderChain({
55
+ timeout: 1e3,
56
+ maxRetries: 0
57
+ })();
58
+ return {
59
+ chain: true,
60
+ ...where
61
+ };
62
+ } catch {
63
+ return;
64
+ }
65
+ }
66
+ /**
67
+ * An S3-compatible endpoint the environment points the SDK at — the AWS
68
+ * emulator in tests. The SDK reads it itself; it is read here too, because
69
+ * an emulator takes path-style requests, and a key written for one has to
70
+ * say where it is.
71
+ */
72
+ function awsEndpoint(env, service) {
73
+ return env[`AWS_ENDPOINT_URL_${service}`] ?? env.AWS_ENDPOINT_URL;
74
+ }
75
+ /** An SDK client's config for a provisioning credential. */
76
+ async function awsClientConfig(credential, region) {
77
+ if ("profile" in credential) {
78
+ const { fromIni } = await import("@aws-sdk/credential-providers");
79
+ return {
80
+ region,
81
+ credentials: fromIni({ profile: credential.profile })
82
+ };
83
+ }
84
+ if ("accessKeyId" in credential) return {
85
+ region,
86
+ credentials: {
87
+ accessKeyId: credential.accessKeyId,
88
+ secretAccessKey: credential.secretAccessKey,
89
+ ...credential.sessionToken ? { sessionToken: credential.sessionToken } : {}
90
+ }
91
+ };
92
+ return { region };
93
+ }
94
+ //#endregion
95
+ //#region src/target/secrets.ts
96
+ /**
97
+ * A stage's secrets as a target sees them: read and written through the
98
+ * stage's own store, and masked in everything the run prints once read.
99
+ */
100
+ /**
101
+ * Shorter values are left alone: what a progress line legitimately prints —
102
+ * a port, a stage, an app name — would otherwise come out as `***` wherever
103
+ * a secret happened to share it.
104
+ */
105
+ const SHORTEST_MASKED = 6;
106
+ /** The values a run must never print, and the rewrite that keeps it so. */
107
+ var Redactor = class {
108
+ values = /* @__PURE__ */ new Set();
109
+ add(value) {
110
+ if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
111
+ }
112
+ /** `text` with every masked value replaced by `***`, longest first. */
113
+ redact(text) {
114
+ if (this.values.size === 0) return text;
115
+ let out = text;
116
+ const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
117
+ for (const value of longestFirst) out = out.replaceAll(value, "***");
118
+ return out;
119
+ }
120
+ };
121
+ /** Every value in `secrets` that is a secret rather than a label. */
122
+ function secretValues(secrets) {
123
+ return [
124
+ secrets.seed,
125
+ ...Object.entries(secrets.custom ?? {}).filter(([key]) => !isReservedStageKey(key)).map(([, value]) => value),
126
+ ...Object.values(secrets.urls ?? {}),
127
+ ...Object.values(secrets.services ?? {}).map((service) => service?.password)
128
+ ].filter((value) => typeof value === "string");
129
+ }
130
+ /**
131
+ * The stage's secrets through the store `secrets.store` names for it. Opening
132
+ * one builds a client and makes no request, so a target that never reads them
133
+ * costs nothing.
134
+ */
135
+ async function deploySecrets(workspace, stage, redactor, options = {}) {
136
+ const store = await secretsStoreFor(workspace, stage, options);
137
+ const mask = (secrets) => {
138
+ for (const value of secretValues(secrets)) redactor.add(value);
139
+ };
140
+ return {
141
+ store: store.name,
142
+ async read() {
143
+ const secrets = await store.read(stage);
144
+ if (secrets) mask(secrets);
145
+ return secrets;
146
+ },
147
+ async write(secrets) {
148
+ mask(secrets);
149
+ await store.write(stage, secrets);
150
+ },
151
+ mask: (value) => redactor.add(value)
152
+ };
153
+ }
154
+ const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
155
+ /** A name that S3 would refuse — what the name builder never returns. */
156
+ var InvalidBucketName = class extends GkmError {
157
+ bucket;
158
+ reason;
159
+ constructor(bucket, reason) {
160
+ super(`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the construct or set deploy.namespace in gkm.config.ts to something that leaves room for it.`);
161
+ this.bucket = bucket;
162
+ this.reason = reason;
163
+ this.name = "InvalidBucketName";
164
+ }
165
+ };
166
+ /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
167
+ function part(value) {
168
+ return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
169
+ }
170
+ /**
171
+ * `parts` joined by `-`, shortened to `max` characters by trimming the longest
172
+ * part one character at a time — so a long construct id gives way before a
173
+ * short stage name does, and every part keeps its start.
174
+ */
175
+ function fitParts(parts, max) {
176
+ const kept = parts.map(part).filter(Boolean);
177
+ const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
178
+ while (length() > max) {
179
+ let longest = 0;
180
+ for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
181
+ if (kept[longest].length <= 1) break;
182
+ kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
183
+ }
184
+ return kept.join("-");
185
+ }
186
+ /** Why `name` is not a valid bucket name, or undefined when it is. */
187
+ function bucketNameProblem(name) {
188
+ if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
189
+ if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
190
+ if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
191
+ if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
192
+ if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
193
+ }
194
+ /**
195
+ * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
196
+ * dots, shortened to leave room for a clash's suffix.
197
+ *
198
+ * @throws {InvalidBucketName} when nothing usable is left
199
+ */
200
+ function bucketName(input) {
201
+ const name = fitParts([
202
+ input.scope,
203
+ input.stage,
204
+ input.id
205
+ ], 56);
206
+ const problem = bucketNameProblem(name);
207
+ if (problem) throw new InvalidBucketName(name, problem);
208
+ return name;
209
+ }
210
+ /** Six random `[a-z0-9]` characters. */
211
+ function randomSuffix(random = randomInt) {
212
+ let suffix = "";
213
+ for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
214
+ return suffix;
215
+ }
216
+ /** The good name with a clash's suffix. */
217
+ function suffixedBucketName(good, suffix) {
218
+ return `${good}-${suffix}`;
219
+ }
220
+ /**
221
+ * The IAM user a bucket is reached with on a stage:
222
+ * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
223
+ */
224
+ function iamUserName(input) {
225
+ return fitParts([
226
+ "gkm",
227
+ input.scope,
228
+ input.stage,
229
+ input.id
230
+ ], 64);
231
+ }
232
+ /** The path every user gkm creates is under, so it finds its own. */
233
+ const IAM_USER_PATH = "/gkm/";
234
+ /** The inline policy each user is given. */
235
+ const IAM_POLICY_NAME = "gkm-bucket";
236
+ //#endregion
237
+ //#region src/providers/s3/policy.ts
238
+ const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
239
+ /**
240
+ * What the app's key may do: objects in this bucket, and listing it — and
241
+ * nothing else in the account.
242
+ *
243
+ * Multipart uploads are in it because a presigned upload of a large file is
244
+ * one, and an abandoned one is cleaned up by the app. Reading old versions is
245
+ * added only when the bucket keeps them.
246
+ */
247
+ function userPolicy(bucket, options = {}) {
248
+ return {
249
+ Version: "2012-10-17",
250
+ Statement: [{
251
+ Sid: "GkmObjects",
252
+ Effect: "Allow",
253
+ Action: [
254
+ "s3:GetObject",
255
+ "s3:PutObject",
256
+ "s3:DeleteObject",
257
+ "s3:AbortMultipartUpload",
258
+ "s3:ListMultipartUploadParts",
259
+ ...options.versioning ? ["s3:GetObjectVersion"] : []
260
+ ],
261
+ Resource: `${bucketArn(bucket)}/*`
262
+ }, {
263
+ Sid: "GkmBucket",
264
+ Effect: "Allow",
265
+ Action: [
266
+ "s3:ListBucket",
267
+ "s3:GetBucketLocation",
268
+ "s3:ListBucketMultipartUploads"
269
+ ],
270
+ Resource: bucketArn(bucket)
271
+ }]
272
+ };
273
+ }
274
+ /**
275
+ * One open pattern as the resource it is public on. A `**` is S3's `*`; a
276
+ * single `*` is too, which crosses `/` where the construct's own check does
277
+ * not — the construct is the stricter of the two (see `bucketPolicy` in
278
+ * reconcile, which the local MinIO is given the same way).
279
+ */
280
+ function openResource(bucket, pattern) {
281
+ const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
282
+ return `${bucketArn(bucket)}/${path}`;
283
+ }
284
+ /**
285
+ * The bucket's own policy: every request refused unless it came over TLS,
286
+ * and — only when a file server opens paths on it — anonymous `s3:GetObject`
287
+ * on exactly those prefixes.
288
+ */
289
+ function bucketPolicy(bucket, open = []) {
290
+ const statements = [{
291
+ Sid: "GkmDenyInsecureTransport",
292
+ Effect: "Deny",
293
+ Principal: "*",
294
+ Action: "s3:*",
295
+ Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
296
+ Condition: { Bool: { "aws:SecureTransport": "false" } }
297
+ }];
298
+ if (open.length > 0) statements.push({
299
+ Sid: "GkmOpenPaths",
300
+ Effect: "Allow",
301
+ Principal: "*",
302
+ Action: "s3:GetObject",
303
+ Resource: [...new Set(open.map((p) => openResource(bucket, p)))].sort()
304
+ });
305
+ return {
306
+ Version: "2012-10-17",
307
+ Statement: statements
308
+ };
309
+ }
310
+ /**
311
+ * Block Public Access. All four flags on, unless the bucket has open paths:
312
+ * then a *policy* may make it public (`BlockPublicPolicy`,
313
+ * `RestrictPublicBuckets` off), and ACLs still may not.
314
+ */
315
+ function publicAccessBlock(open) {
316
+ return {
317
+ BlockPublicAcls: true,
318
+ IgnorePublicAcls: true,
319
+ BlockPublicPolicy: !open,
320
+ RestrictPublicBuckets: !open
321
+ };
322
+ }
323
+ function corsRule(origins) {
324
+ return {
325
+ AllowedMethods: [
326
+ "GET",
327
+ "HEAD",
328
+ "POST",
329
+ "PUT"
330
+ ],
331
+ AllowedOrigins: [...new Set(origins)].sort(),
332
+ AllowedHeaders: ["*"],
333
+ ExposeHeaders: ["ETag"],
334
+ MaxAgeSeconds: 3e3
335
+ };
336
+ }
337
+ /**
338
+ * A policy document in one canonical form — keys sorted, a lone string a
339
+ * one-element list, lists sorted — so one AWS reformatted reads as the same
340
+ * document rather than as drift.
341
+ */
342
+ function canonicalPolicy(value) {
343
+ return JSON.stringify(canonical(value));
344
+ }
345
+ function canonical(value, key) {
346
+ if (Array.isArray(value)) {
347
+ const items = value.map((v) => canonical(v));
348
+ return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
349
+ }
350
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
351
+ const v = value[k];
352
+ return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" ? Array.isArray(v) ? v : [v] : v, k)];
353
+ }));
354
+ return value;
355
+ }
356
+ //#endregion
357
+ //#region src/providers/iam.ts
358
+ /**
359
+ * An IAM user gkm creates for one thing on a stage, its inline policy, and
360
+ * the access key written into the stage's secrets as an `s3://` URL — what
361
+ * the `s3` provider gives each bucket, and the deploy gives a stage's
362
+ * backups.
363
+ *
364
+ * - **The user** is under `/gkm/`, tagged with the deploy identity, the stage
365
+ * and what it is for. One that exists without those tags is someone
366
+ * else's, and is refused rather than taken over.
367
+ * - **Its policy** is read on every run and put back when it drifted.
368
+ * - **Its key**: one, written into the stage's secrets the moment IAM shows
369
+ * its secret. `--rotate-keys` issues a successor and keeps the old one
370
+ * active until the stage has deployed with the new one; the next run after
371
+ * that — or `--retire-old-keys` — deletes it.
372
+ * - **A new key** takes IAM seconds to become usable: the state records when
373
+ * it was issued, and a check made with it waits that out
374
+ * ({@link whileKeyIsNew}).
375
+ */
376
+ /** The tags gkm finds its own buckets and users by. */
377
+ const TAG_PROJECT = "gkm:project";
378
+ const TAG_STAGE = "gkm:stage";
379
+ const TAG_CONSTRUCT = "gkm:construct";
380
+ /** The keys gkm tags a bucket and a user with. */
381
+ function identityTags(ctx, id) {
382
+ return [
383
+ {
384
+ Key: TAG_PROJECT,
385
+ Value: ctx.identity.key
386
+ },
387
+ {
388
+ Key: TAG_STAGE,
389
+ Value: ctx.stage
390
+ },
391
+ {
392
+ Key: TAG_CONSTRUCT,
393
+ Value: id
394
+ }
395
+ ];
396
+ }
397
+ /** A read whose "there is none" answer is one of `missing`. */
398
+ async function readOr$1(read, missing) {
399
+ try {
400
+ return await read();
401
+ } catch (error) {
402
+ const e = error;
403
+ if (missing.includes(e?.Code ?? e?.name ?? "")) return void 0;
404
+ throw error;
405
+ }
406
+ }
407
+ /** IAM returns a policy document URL-encoded; an emulator may not. */
408
+ function decodePolicy(document) {
409
+ try {
410
+ return decodeURIComponent(document);
411
+ } catch {
412
+ return document;
413
+ }
414
+ }
415
+ /**
416
+ * The user and its inline policy: found — and refused when it is not this
417
+ * stage's — or created, and the policy put back when it drifted.
418
+ *
419
+ * @throws {IamUserNotOwned}
420
+ */
421
+ async function ensureIamUser(ctx, clients, input) {
422
+ const { IAM, iam } = clients;
423
+ const { id, user, policy } = input;
424
+ const entry = {
425
+ key: `iam-user:${id}`,
426
+ type: "iam-user"
427
+ };
428
+ const found = await readOr$1(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
429
+ if (found?.User) {
430
+ const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
431
+ const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
432
+ if (found.User.Path !== "/gkm/" || tag("gkm:project") !== ctx.identity.key || tag("gkm:stage") !== ctx.stage) throw new IamUserNotOwned(user, ctx.identity.key, ctx.stage);
433
+ await ctx.state.ready(entry, user);
434
+ } else await ctx.change({
435
+ construct: id,
436
+ resource: `IAM user ${user}`,
437
+ change: `create under ${IAM_USER_PATH}`
438
+ }, async () => {
439
+ await ctx.state.pending(entry);
440
+ await iam.send(new IAM.CreateUserCommand({
441
+ UserName: user,
442
+ Path: IAM_USER_PATH,
443
+ Tags: identityTags(ctx, id)
444
+ }));
445
+ await ctx.state.ready(entry, user);
446
+ });
447
+ const exists = Boolean(found?.User) || !ctx.dryRun;
448
+ const current = exists ? await readOr$1(() => iam.send(new IAM.GetUserPolicyCommand({
449
+ UserName: user,
450
+ PolicyName: input.policyName
451
+ })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
452
+ const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
453
+ if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
454
+ construct: id,
455
+ resource: `IAM user ${user}`,
456
+ change: `policy ${input.policyName}: ${input.describe}`
457
+ }, async () => {
458
+ await iam.send(new IAM.PutUserPolicyCommand({
459
+ UserName: user,
460
+ PolicyName: input.policyName,
461
+ PolicyDocument: JSON.stringify(policy)
462
+ }));
463
+ });
464
+ return {
465
+ user,
466
+ exists
467
+ };
468
+ }
469
+ /**
470
+ * The user's access key, in the stage's secrets as the bucket's URL.
471
+ *
472
+ * - First run: one key, written into the stage's secrets.
473
+ * - `--rotate-keys`: a second key, written in place of the first; the first
474
+ * stays active until the stage has deployed with the second, and the next
475
+ * run after that deploy — or `--retire-old-keys` — deletes it.
476
+ * - A key the secrets no longer hold (a store emptied by hand): replaced the
477
+ * same way, since its secret cannot be read back.
478
+ *
479
+ * @throws {BucketKeySetElsewhere} when the secret names another bucket
480
+ * @throws {RotationInProgress} on `--rotate-keys` with the last rotation's old key still active
481
+ * @throws {AccessKeyLimit} when the user has two keys gkm did not record
482
+ */
483
+ async function ensureAccessKey(ctx, clients, input) {
484
+ const { IAM, iam } = clients;
485
+ const { id, bucket, user, urlKey } = input;
486
+ const entryKey = `iam-access-key:${id}`;
487
+ const record = ctx.state.record(entryKey);
488
+ const given = ctx.secrets[urlKey];
489
+ let inUrl;
490
+ let parsed;
491
+ if (given !== void 0) {
492
+ try {
493
+ parsed = s3Url.parse(given);
494
+ } catch {
495
+ parsed = void 0;
496
+ }
497
+ if (parsed?.bucket !== bucket) throw new BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
498
+ inUrl = parsed.accessKeyId;
499
+ }
500
+ const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
501
+ let current = record?.status === "ready" ? record.id : void 0;
502
+ let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
503
+ const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
504
+ const entry = (data = {}) => ({
505
+ key: entryKey,
506
+ type: "iam-access-key",
507
+ data: {
508
+ user,
509
+ ...data
510
+ }
511
+ });
512
+ if (previous && current) {
513
+ const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
514
+ if (ctx.retireOldKeys || deployed) {
515
+ const old = previous;
516
+ const keep = current;
517
+ await ctx.change({
518
+ construct: id,
519
+ resource: `IAM user ${user}`,
520
+ change: `delete the rotated-out access key ${old}`
521
+ }, async () => {
522
+ if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
523
+ UserName: user,
524
+ AccessKeyId: old
525
+ }));
526
+ await ctx.state.ready(entry(), keep);
527
+ });
528
+ previous = void 0;
529
+ } else ctx.log(` ${id}: the old access key ${previous} stays active until '${ctx.stage}' is deployed with the new one; the next deploy after that deletes it (or pass --retire-old-keys)`);
530
+ }
531
+ if (!current && inUrl && listed.includes(inUrl)) {
532
+ await ctx.state.ready(entry(), inUrl);
533
+ current = inUrl;
534
+ }
535
+ if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) {
536
+ if (parsed && parsed.region !== clients.region) {
537
+ const address = parsed;
538
+ await ctx.change({
539
+ construct: id,
540
+ resource: urlKey,
541
+ change: `name ${clients.region}, the bucket's region (it said ${address.region ?? "none"})`
542
+ }, () => ctx.writeSecrets({ [urlKey]: s3Url.build({
543
+ ...address,
544
+ region: clients.region
545
+ }) }));
546
+ }
547
+ return;
548
+ }
549
+ if (ctx.rotateKeys && previous) throw new RotationInProgress(id, previous, ctx.stage);
550
+ const outgoing = current && listed.includes(current) ? current : void 0;
551
+ if (listed.length >= 2) throw new AccessKeyLimit(user, listed);
552
+ const why = !current ? "create an access key" : ctx.rotateKeys ? "rotate: issue a new access key" : "issue a new access key (the secrets no longer hold the recorded one)";
553
+ await ctx.change({
554
+ construct: id,
555
+ resource: `IAM user ${user}`,
556
+ change: why
557
+ }, async () => {
558
+ await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
559
+ const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
560
+ await ctx.writeSecrets({ [urlKey]: s3Url.build({
561
+ bucket,
562
+ region: clients.region,
563
+ ...clients.endpoint ? {
564
+ endpoint: clients.endpoint,
565
+ forcePathStyle: true
566
+ } : {},
567
+ accessKeyId: key.AccessKeyId,
568
+ secretAccessKey: key.SecretAccessKey
569
+ }) });
570
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
571
+ await ctx.state.ready(entry(outgoing ? {
572
+ previous: outgoing,
573
+ rotatedAt: issuedAt,
574
+ issuedAt
575
+ } : { issuedAt }), key.AccessKeyId);
576
+ });
577
+ if (outgoing) ctx.log(` ${urlKey} holds the new key. This deploy moves '${ctx.stage}' onto it; the next deploy after it deletes the old key ${outgoing}`);
578
+ }
579
+ /** How long a key issued this recently counts as new to IAM. */
580
+ const NEW_KEY_WINDOW_MS = 6e5;
581
+ /** The waits between asks while a new key becomes usable: about a minute. */
582
+ let newKeyWaits = [
583
+ 2e3,
584
+ 4e3,
585
+ 8e3,
586
+ 15e3,
587
+ 15e3,
588
+ 15e3
589
+ ];
590
+ /**
591
+ * When the key in a URL was issued, if the stage's state says it was just
592
+ * now — the record of `id`'s key naming that very key.
593
+ */
594
+ function issuedJustNow(resources, id, accessKeyId) {
595
+ const record = resources?.[`iam-access-key:${id}`];
596
+ const issuedAt = record?.data?.issuedAt;
597
+ if (record?.id !== accessKeyId || typeof issuedAt !== "string") return;
598
+ const age = Date.now() - Date.parse(issuedAt);
599
+ return age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : void 0;
600
+ }
601
+ /**
602
+ * `ask` again, for about a minute, while it is `refused` and the key was
603
+ * issued just now — IAM refuses a key for seconds after making it. Returns
604
+ * the last answer and how long was waited.
605
+ */
606
+ async function whileKeyIsNew(first, options) {
607
+ let answer = first;
608
+ let waited = 0;
609
+ if (!options.issuedAt || !options.refused(answer)) return {
610
+ answer,
611
+ waited
612
+ };
613
+ options.onWait?.();
614
+ for (const wait of newKeyWaits) {
615
+ await new Promise((resolve) => setTimeout(resolve, wait));
616
+ waited += wait;
617
+ answer = await options.ask();
618
+ if (!options.refused(answer)) break;
619
+ }
620
+ return {
621
+ answer,
622
+ waited
623
+ };
624
+ }
625
+ //#endregion
626
+ //#region src/backups/provision.ts
627
+ /** What the backups user and its key are recorded and tagged as. */
628
+ const BACKUPS_ID = "backups";
629
+ /** The backups user's inline policy's name. */
630
+ const BACKUPS_POLICY_NAME = "gkm-backups";
631
+ /** Where a deploy's check puts its marker, under the backups prefix. */
632
+ const VERIFY_MARKER = ".gkm-verify";
633
+ /** The backups user's name: `gkm-<project>-<stage>-backups`. */
634
+ function backupsUserName(scope, stage) {
635
+ return iamUserName({
636
+ scope,
637
+ stage,
638
+ id: BACKUPS_ID
639
+ });
640
+ }
641
+ /**
642
+ * The backups key's policy: put objects under the stage's backups prefix.
643
+ * Uploading in parts is `s3:PutObject` too; aborting one is not, and the
644
+ * bucket's lifecycle does it instead.
645
+ */
646
+ function backupsPolicy(bucket, prefix) {
647
+ return {
648
+ Version: "2012-10-17",
649
+ Statement: [{
650
+ Sid: "GkmBackupsPut",
651
+ Effect: "Allow",
652
+ Action: ["s3:PutObject"],
653
+ Resource: `arn:aws:s3:::${bucket}/${prefix}/*`
654
+ }]
655
+ };
656
+ }
657
+ /** A stage that backs up, and no AWS credentials to create its key with. */
658
+ var BackupsCredentialsMissing = class extends GkmError {
659
+ stage;
660
+ constructor(stage) {
661
+ super(`'${stage}' runs Postgres, so the deploy backs it up — and creates the IAM user and key it backs up with in the stage's AWS account — and it found no AWS credentials to do it with. On this machine, supply ${S3_PROVISIONING.describe}. In CI, the step that runs the deploy needs the stage's role (AWS_ROLE_ARN, from gkm deploy:github). To take no backups, set deploy.backups.${stage}: false.`);
662
+ this.stage = stage;
663
+ this.name = "BackupsCredentialsMissing";
664
+ }
665
+ };
666
+ /** No region to create the project bucket in. */
667
+ var BackupsRegionRequired = class extends GkmError {
668
+ stage;
669
+ constructor(stage) {
670
+ super(`'${stage}' is backed up to the project bucket, and there is no region to find it in: set state: { provider: 's3', region } in gkm.config.ts, or AWS_REGION.`);
671
+ this.stage = stage;
672
+ this.name = "BackupsRegionRequired";
673
+ }
674
+ };
675
+ /** A bucket construct whose IAM user would be the backups user. */
676
+ var BackupsUserNameTaken = class extends GkmError {
677
+ stage;
678
+ construct;
679
+ constructor(stage, construct) {
680
+ super(`The bucket '${construct}' is reached on '${stage}' with the IAM user the stage's backups are put with — both are named after 'backups'. Rename the construct, or set deploy.backups.${stage}: false.`);
681
+ this.stage = stage;
682
+ this.construct = construct;
683
+ this.name = "BackupsUserNameTaken";
684
+ }
685
+ };
686
+ /** The backups key could not put its marker: backups would fail too. */
687
+ var BackupsKeyRefused = class extends GkmError {
688
+ stage;
689
+ bucket;
690
+ key;
691
+ said;
692
+ constructor(stage, bucket, key, said) {
693
+ super(`The ${BACKUPS_URL_KEY} key of '${stage}' could not put s3://${bucket}/${key} (${said}), so its backups would fail the same way. Run the deploy with the stage's AWS credentials to put its user and policy back, or --rotate-keys to issue it a new key.`);
694
+ this.stage = stage;
695
+ this.bucket = bucket;
696
+ this.key = key;
697
+ this.said = said;
698
+ this.name = "BackupsKeyRefused";
699
+ }
700
+ };
701
+ /**
702
+ * The region the project bucket is in: the state's, when it is kept in S3,
703
+ * the secrets store's when that is in AWS, the credential's, `AWS_REGION`.
704
+ */
705
+ function backupsRegion(workspace, stage, credential, env = process.env) {
706
+ const state = workspace.state;
707
+ const store = workspace.secrets?.store;
708
+ const region = (state && "region" in state ? state.region : void 0) ?? (store && typeof store === "object" && "region" in store ? store.region : void 0) ?? credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
709
+ if (!region) throw new BackupsRegionRequired(stage);
710
+ return region;
711
+ }
712
+ /**
713
+ * The stage's backups bucket, lifecycle, user and key — or, for a stage set
714
+ * to `false`, a notice and nothing else. Returns what the stage's backups
715
+ * came to.
716
+ *
717
+ * @throws {BackupsCredentialsMissing} when there are no AWS credentials
718
+ */
719
+ async function ensureStageBackups(input) {
720
+ const { workspace, manifest, stage, ctx } = input;
721
+ const env = input.env ?? process.env;
722
+ const choice = stageBackups(workspace, manifest, stage);
723
+ if (choice.mode === "disabled") {
724
+ ctx.log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
725
+ return choice;
726
+ }
727
+ if (choice.mode !== "on") return choice;
728
+ if (stageProvider(workspace, "objects", stage).mode === "provider") {
729
+ const clash = Object.entries(manifest).find(([id, d]) => d.kind === "objects" && appKey(id) === "backups");
730
+ if (clash) throw new BackupsUserNameTaken(stage, clash[0]);
731
+ }
732
+ const credential = await awsProvisioningCredentials({
733
+ stage,
734
+ env,
735
+ ...input.profile ? { profile: input.profile } : {},
736
+ ...input.home ? { home: input.home } : {}
737
+ });
738
+ if (!credential) throw new BackupsCredentialsMissing(stage);
739
+ const region = backupsRegion(workspace, stage, credential, env);
740
+ const clients = await backupsClients(credential, region, env);
741
+ const bucket = projectBucketName(ctx.identity.scope, await callerAccountId(clients.sts));
742
+ const prefix = backupsPrefix(workspace, stage);
743
+ const expiries = backupExpiries(workspace, manifest);
744
+ ctx.log(`💾 backups: ${choice.backups.describe}, to s3://${bucket}/${prefix}/${ctx.dryRun ? " (dry run)" : ""}`);
745
+ if (await findProjectBucket(clients.s3, bucket) === "none") await ctx.change({
746
+ construct: BACKUPS_SERVICE,
747
+ resource: `bucket ${bucket}`,
748
+ change: `create in ${region}, expiring each stage's backups`
749
+ }, async () => {
750
+ await ensureProjectBucket(clients.s3, {
751
+ bucket,
752
+ region,
753
+ identity: ctx.identity,
754
+ expiries
755
+ });
756
+ });
757
+ else if (await reconcileProjectBucketLifecycle(clients.s3, bucket, expiries, { dryRun: true })) await ctx.change({
758
+ construct: BACKUPS_SERVICE,
759
+ resource: `bucket ${bucket}`,
760
+ change: `lifecycle: ${expiries.map((e) => `${e.prefix} after ${e.days} days`).join(", ")}`
761
+ }, async () => {
762
+ await reconcileProjectBucketLifecycle(clients.s3, bucket, expiries);
763
+ });
764
+ const user = await ensureIamUser(ctx, clients, {
765
+ id: BACKUPS_ID,
766
+ user: backupsUserName(ctx.identity.scope, stage),
767
+ policyName: BACKUPS_POLICY_NAME,
768
+ policy: backupsPolicy(bucket, prefix),
769
+ describe: `put objects under ${prefix}/ only`
770
+ });
771
+ await ensureAccessKey(ctx, clients, {
772
+ id: BACKUPS_ID,
773
+ bucket,
774
+ urlKey: BACKUPS_URL_KEY,
775
+ ...user
776
+ });
777
+ return choice;
778
+ }
779
+ /** The clients a backups run creates through. */
780
+ async function backupsClients(credential, region, env) {
781
+ const S3 = await import("@aws-sdk/client-s3");
782
+ const IAM = await import("@aws-sdk/client-iam");
783
+ const { STSClient } = await import("@aws-sdk/client-sts");
784
+ const config = await awsClientConfig(credential, region);
785
+ const endpoint = awsEndpoint(env, "S3");
786
+ return {
787
+ IAM,
788
+ iam: new IAM.IAMClient(config),
789
+ s3: new S3.S3Client({
790
+ ...config,
791
+ ...endpoint ? {
792
+ endpoint,
793
+ forcePathStyle: true
794
+ } : {}
795
+ }),
796
+ sts: new STSClient(config),
797
+ region,
798
+ ...endpoint ? { endpoint } : {}
799
+ };
800
+ }
801
+ /**
802
+ * The stage's backups key puts its marker under the prefix — the one thing
803
+ * it may do. A key issued by this deploy is waited for, as a bucket's is.
804
+ * Returns whether there was a key to check.
805
+ *
806
+ * @throws {BackupsKeyRefused}
807
+ */
808
+ async function verifyStageBackups(input) {
809
+ const { stage } = input;
810
+ if (stageBackups(input.workspace, input.manifest, stage).mode !== "on") return false;
811
+ const url = input.secrets[BACKUPS_URL_KEY];
812
+ if (!url) return false;
813
+ const address = (await import("@geekmidas/storage/s3-url")).parse(url);
814
+ if (!address.accessKeyId || !address.secretAccessKey) return false;
815
+ const S3 = await import("@aws-sdk/client-s3");
816
+ const client = new S3.S3Client({
817
+ region: address.region ?? "us-east-1",
818
+ credentials: {
819
+ accessKeyId: address.accessKeyId,
820
+ secretAccessKey: address.secretAccessKey
821
+ },
822
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
823
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
824
+ });
825
+ const Key = `${backupsPrefix(input.workspace, stage)}/${VERIFY_MARKER}`;
826
+ const put = async () => {
827
+ try {
828
+ await client.send(new S3.PutObjectCommand({
829
+ Bucket: address.bucket,
830
+ Key,
831
+ Body: (/* @__PURE__ */ new Date()).toISOString(),
832
+ ContentType: "text/plain"
833
+ }));
834
+ return {
835
+ ok: true,
836
+ said: ""
837
+ };
838
+ } catch (error) {
839
+ const e = error;
840
+ const status = e.$metadata?.httpStatusCode;
841
+ return {
842
+ ok: false,
843
+ ...status !== void 0 ? { status } : {},
844
+ said: `HTTP ${status ?? "no response"} ${e.name ?? "Error"}: ${e.message ?? ""}`
845
+ };
846
+ }
847
+ };
848
+ try {
849
+ const { answer } = await whileKeyIsNew(await put(), {
850
+ issuedAt: issuedJustNow(input.resources, BACKUPS_ID, address.accessKeyId),
851
+ refused: (answer) => !answer.ok && answer.status === 403,
852
+ ask: put,
853
+ onWait: () => input.log?.(` backups: waiting for the new key ${address.accessKeyId} to become active…`)
854
+ });
855
+ if (!answer.ok) throw new BackupsKeyRefused(stage, address.bucket, Key, answer.said);
856
+ return true;
857
+ } finally {
858
+ client.destroy();
859
+ }
860
+ }
861
+ //#endregion
862
+ //#region src/providers/s3/origins.ts
863
+ /**
864
+ * Which browser origins may call a bucket: the stage's sites that depend on
865
+ * an API using it.
866
+ *
867
+ * The same reading of the graph an API's own CORS origins are — its callers —
868
+ * taken one step further: a site that calls an API which hands it a presigned
869
+ * upload URL is a site whose browser PUTs to the bucket. A site that reads the
870
+ * bucket (or a file server over it) itself is one too. Nothing is written
871
+ * down: add a site that calls the API and the next provision run allows it.
872
+ */
873
+ /** The keys a reader of this bucket holds: its URL, and each server's over it. */
874
+ function bucketKeys(manifest, bucket) {
875
+ return [provideKey(bucket, "url"), ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => provideKey(id, "url"))];
876
+ }
877
+ function bucketOrigins(input) {
878
+ const { manifest, workspace, stage } = input;
879
+ const keys = bucketKeys(manifest, input.bucket);
880
+ const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "site").filter(([id]) => {
881
+ const env = appEnvKeys(manifest, appKey(id), input.runnables);
882
+ return env !== void 0 && keys.some((key) => env.has(key));
883
+ });
884
+ const sites = /* @__PURE__ */ new Set();
885
+ for (const [id, declaration] of readers) {
886
+ if (declaration.kind === "site") {
887
+ sites.add(id);
888
+ continue;
889
+ }
890
+ for (const caller of dependentsOf(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
891
+ }
892
+ const origins = /* @__PURE__ */ new Set();
893
+ const unresolved = [];
894
+ for (const id of [...sites].sort()) {
895
+ const name = appKey(id);
896
+ const app = workspace.apps[name];
897
+ if (!app) {
898
+ unresolved.push(name);
899
+ continue;
900
+ }
901
+ try {
902
+ const host = resolveHost(name, app, stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
903
+ origins.add(`https://${host}`);
904
+ } catch (error) {
905
+ if (!(error instanceof NoDomainForStage)) throw error;
906
+ unresolved.push(name);
907
+ }
908
+ }
909
+ return {
910
+ origins: [...origins].sort(),
911
+ unresolved
912
+ };
913
+ }
914
+ //#endregion
915
+ //#region src/providers/s3/index.ts
916
+ function bucketConstructs(manifest) {
917
+ return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
918
+ id,
919
+ versioned: d.versioned === true,
920
+ servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
921
+ id: sid,
922
+ open: s.open ?? []
923
+ })).sort((a, b) => a.id.localeCompare(b.id))
924
+ })).sort((a, b) => a.id.localeCompare(b.id));
925
+ }
926
+ /**
927
+ * The region the stage's buckets are created in: the entry's, the secrets
928
+ * store's when it is in AWS, the credential's, `AWS_REGION`.
929
+ */
930
+ function s3Region(ctx, env = process.env) {
931
+ const store = ctx.workspace.secrets?.store;
932
+ const storeRegion = store && typeof store === "object" && "region" in store ? store.region : void 0;
933
+ const region = ctx.config.region ?? storeRegion ?? ctx.credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
934
+ if (!region) throw new S3RegionRequired(ctx.stage);
935
+ return region;
936
+ }
937
+ /**
938
+ * The address a file server over `bucket` serves on: the bucket's regional
939
+ * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
940
+ * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
941
+ * its path-style address.
942
+ */
943
+ function bucketPublicUrl(bucket, region, endpoint) {
944
+ if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
945
+ return `https://${bucket}.s3.${region}.amazonaws.com`;
946
+ }
947
+ /** What an AWS SDK error is called, whichever field carries it. */
948
+ function errorName(error) {
949
+ const e = error;
950
+ return e?.Code ?? e?.name ?? "";
951
+ }
952
+ /** The answer an SDK call failed with. */
953
+ function s3Answer(error) {
954
+ const e = error;
955
+ const headers = Object.fromEntries(Object.entries(e?.$response?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
956
+ const status = e?.$metadata?.httpStatusCode ?? e?.$response?.statusCode;
957
+ const region = headers["x-amz-bucket-region"];
958
+ const requestId = e?.$metadata?.requestId ?? headers["x-amz-request-id"];
959
+ const id2 = e?.$metadata?.extendedRequestId ?? headers["x-amz-id-2"];
960
+ return {
961
+ ...status !== void 0 ? { status } : {},
962
+ name: errorName(error) || "Error",
963
+ message: e?.message ?? String(error),
964
+ ...region ? { region } : {},
965
+ ...requestId ? { requestId } : {},
966
+ ...id2 ? { id2 } : {}
967
+ };
968
+ }
969
+ /**
970
+ * `HTTP 403 Unknown: UnknownError [x-amz-bucket-region: eu-west-1,
971
+ * x-amz-request-id: …, x-amz-id-2: …]` — everything S3 said, for a message.
972
+ */
973
+ function describeAnswer(answer) {
974
+ const said = answer.message && answer.message !== answer.name ? `${answer.name}: ${answer.message}` : answer.name;
975
+ const headers = [
976
+ answer.region && `x-amz-bucket-region: ${answer.region}`,
977
+ answer.requestId && `x-amz-request-id: ${answer.requestId}`,
978
+ answer.id2 && `x-amz-id-2: ${answer.id2}`
979
+ ].filter(Boolean);
980
+ return `${answer.status === void 0 ? "no response" : `HTTP ${answer.status}`} ${said}` + (headers.length > 0 ? ` [${headers.join(", ")}]` : "");
981
+ }
982
+ /** `HeadBucket`: the bucket's region when it answers, else what S3 said. */
983
+ async function headBucket(S3, client, bucket) {
984
+ try {
985
+ const out = await client.send(new S3.HeadBucketCommand({ Bucket: bucket }));
986
+ return {
987
+ ok: true,
988
+ ...out.BucketRegion ? { region: out.BucketRegion } : {}
989
+ };
990
+ } catch (error) {
991
+ return {
992
+ ok: false,
993
+ ...s3Answer(error)
994
+ };
995
+ }
996
+ }
997
+ /** `GetBucketLocation`'s answer as a region: none is us-east-1, `EU` eu-west-1. */
998
+ async function bucketLocation(S3, client, bucket) {
999
+ try {
1000
+ const location = (await client.send(new S3.GetBucketLocationCommand({ Bucket: bucket }))).LocationConstraint;
1001
+ return { region: !location ? "us-east-1" : location === "EU" ? "eu-west-1" : location };
1002
+ } catch (error) {
1003
+ return { failed: s3Answer(error) };
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Where `bucket` is: `HeadBucket`'s `x-amz-bucket-region` — on a 200, a 301
1008
+ * or a 400 alike — else `GetBucketLocation`.
1009
+ *
1010
+ * @throws {BucketRegionUnknown}
1011
+ */
1012
+ async function bucketRegion(clients, bucket) {
1013
+ const { S3, s3 } = clients;
1014
+ const head = await headBucket(S3, s3, bucket);
1015
+ if (head.region) return head.region;
1016
+ const location = await bucketLocation(S3, s3, bucket);
1017
+ if ("region" in location) return location.region;
1018
+ throw new BucketRegionUnknown(bucket, head.ok ? "HTTP 200 without x-amz-bucket-region" : describeAnswer(head), describeAnswer(location.failed));
1019
+ }
1020
+ /** A read whose "there is none" answer is one of `missing`. */
1021
+ async function readOr(read, missing) {
1022
+ try {
1023
+ return await read();
1024
+ } catch (error) {
1025
+ if (missing.includes(errorName(error))) return void 0;
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ const defaultClients = async (credential, region) => {
1030
+ const S3 = await import("@aws-sdk/client-s3");
1031
+ const IAM = await import("@aws-sdk/client-iam");
1032
+ const config = await awsClientConfig(credential, region);
1033
+ const endpoint = awsEndpoint(process.env, "S3");
1034
+ return {
1035
+ S3,
1036
+ IAM,
1037
+ s3: new S3.S3Client({
1038
+ ...config,
1039
+ ...endpoint ? {
1040
+ endpoint,
1041
+ forcePathStyle: true
1042
+ } : {}
1043
+ }),
1044
+ iam: new IAM.IAMClient(config),
1045
+ region,
1046
+ ...endpoint ? { endpoint } : {}
1047
+ };
1048
+ };
1049
+ /** For tests: what makes the clients. */
1050
+ let makeClients = defaultClients;
1051
+ async function ensureS3(ctx) {
1052
+ const region = s3Region(ctx);
1053
+ const clients = await makeClients(ctx.credential, region);
1054
+ for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct);
1055
+ }
1056
+ async function ensureBucket(ctx, stageClients, construct) {
1057
+ const { id } = construct;
1058
+ const nameInput = {
1059
+ scope: ctx.identity.scope,
1060
+ stage: ctx.stage,
1061
+ id: appKey(id)
1062
+ };
1063
+ const versioning = ctx.config.versioning ?? construct.versioned;
1064
+ const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
1065
+ const located = await ensureBucketName(ctx, stageClients, id, bucketName(nameInput));
1066
+ const { bucket, exists } = located;
1067
+ let clients = stageClients;
1068
+ if (located.region !== stageClients.region) {
1069
+ clients = await makeClients(ctx.credential, located.region);
1070
+ ctx.log(` '${bucket}' is in ${located.region}, not ${stageClients.region}: '${id}' is reached and addressed there`);
1071
+ }
1072
+ await ensureBucketSettings(ctx, clients, {
1073
+ id,
1074
+ bucket,
1075
+ exists,
1076
+ versioning,
1077
+ open
1078
+ });
1079
+ const user = await ensureIamUser(ctx, clients, {
1080
+ id,
1081
+ user: iamUserName(nameInput),
1082
+ policyName: IAM_POLICY_NAME,
1083
+ policy: userPolicy(bucket, { versioning }),
1084
+ describe: "this bucket only"
1085
+ });
1086
+ await ensureAccessKey(ctx, clients, {
1087
+ id,
1088
+ bucket,
1089
+ urlKey: provideKey(id, "url"),
1090
+ ...user
1091
+ });
1092
+ const publicUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
1093
+ for (const server of construct.servers) {
1094
+ const key = provideKey(server.id, "url");
1095
+ const entry = {
1096
+ key: `file-server:${server.id}`,
1097
+ type: "url"
1098
+ };
1099
+ const recorded = ctx.state.record(entry.key)?.id;
1100
+ const current = ctx.secrets[key];
1101
+ if (current === publicUrl) {
1102
+ await ctx.state.ready(entry, publicUrl);
1103
+ continue;
1104
+ }
1105
+ if (current !== void 0 && current !== recorded) {
1106
+ ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
1107
+ continue;
1108
+ }
1109
+ await ctx.change({
1110
+ construct: server.id,
1111
+ resource: key,
1112
+ change: `set to ${publicUrl}`
1113
+ }, async () => {
1114
+ await ctx.writeSecrets({ [key]: publicUrl });
1115
+ await ctx.state.ready(entry, publicUrl);
1116
+ });
1117
+ }
1118
+ }
1119
+ /**
1120
+ * The bucket's name: the recorded one, else the good name, else the good
1121
+ * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
1122
+ */
1123
+ async function ensureBucketName(ctx, clients, id, good) {
1124
+ const { S3, s3, region } = clients;
1125
+ const key = `s3-bucket:${id}`;
1126
+ const record = ctx.state.record(key);
1127
+ const entry = (name, where) => ({
1128
+ key,
1129
+ type: "s3-bucket",
1130
+ data: {
1131
+ name,
1132
+ region: where
1133
+ }
1134
+ });
1135
+ /**
1136
+ * Whether this account holds `name`: yes, no, or someone else does. Read
1137
+ * by status — a `HEAD` has no body, so its error is named `Unknown` — and,
1138
+ * when S3 says the bucket is in another region, asked again there.
1139
+ */
1140
+ const probe = async (name) => {
1141
+ let head = await headBucket(S3, s3, name);
1142
+ if (!head.ok && head.region && head.region !== region && (head.status === 301 || head.status === 400)) {
1143
+ const there = await makeClients(ctx.credential, head.region);
1144
+ head = await headBucket(there.S3, there.s3, name);
1145
+ }
1146
+ if (head.ok) return "ours";
1147
+ if (head.status === 404) return "none";
1148
+ if (head.status === 403) return "taken";
1149
+ throw new BucketProbeFailed(name, describeAnswer(head));
1150
+ };
1151
+ /** Where the bucket is now — read, not assumed: it may be adopted. */
1152
+ const located = async (name, made) => ctx.dryRun && made === "created" ? region : bucketRegion(clients, name);
1153
+ const create = async (name) => {
1154
+ if (ctx.dryRun) {
1155
+ const found = await probe(name);
1156
+ if (found === "none") {
1157
+ await ctx.change({
1158
+ construct: id,
1159
+ resource: `bucket ${name}`,
1160
+ change: `create in ${region}`
1161
+ }, async () => {});
1162
+ return "created";
1163
+ }
1164
+ return found;
1165
+ }
1166
+ await ctx.state.pending(entry(name, region));
1167
+ try {
1168
+ await s3.send(new S3.CreateBucketCommand({
1169
+ Bucket: name,
1170
+ ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
1171
+ }));
1172
+ } catch (error) {
1173
+ const code = errorName(error);
1174
+ if (code === "BucketAlreadyOwnedByYou") return "ours";
1175
+ if (code === "BucketAlreadyExists") return "taken";
1176
+ throw error;
1177
+ }
1178
+ await ctx.change({
1179
+ construct: id,
1180
+ resource: `bucket ${name}`,
1181
+ change: `create in ${region}`
1182
+ }, async () => {});
1183
+ return "created";
1184
+ };
1185
+ const adopt = async (name, where) => {
1186
+ const there = where === region ? clients : await makeClients(ctx.credential, where);
1187
+ const owner = (await readOr(() => there.s3.send(new there.S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === TAG_PROJECT)?.Value;
1188
+ if (owner && owner !== ctx.identity.key) throw new BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
1189
+ };
1190
+ if (record?.status === "ready" && record.id) {
1191
+ const found = await probe(record.id);
1192
+ if (found === "taken") throw new RecordedBucketUnreachable(id, record.id);
1193
+ const made = found === "ours" ? "ours" : await create(record.id);
1194
+ if (made === "taken") throw new RecordedBucketUnreachable(id, record.id);
1195
+ const where = await located(record.id, made);
1196
+ if (!ctx.dryRun) await ctx.state.ready(entry(record.id, where), record.id);
1197
+ return {
1198
+ bucket: record.id,
1199
+ exists: made === "ours",
1200
+ region: where
1201
+ };
1202
+ }
1203
+ const pending = record?.data?.name;
1204
+ const names = [
1205
+ ...typeof pending === "string" && pending !== good ? [pending] : [],
1206
+ good,
1207
+ ...Array.from({ length: 5 }, () => suffixedBucketName(good, randomSuffix()))
1208
+ ];
1209
+ const tried = [];
1210
+ for (const name of names) {
1211
+ tried.push(name);
1212
+ const made = await create(name);
1213
+ if (made === "taken") continue;
1214
+ const where = await located(name, made);
1215
+ if (made === "ours") await adopt(name, where);
1216
+ if (!ctx.dryRun) await ctx.state.ready(entry(name, where), name);
1217
+ if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
1218
+ return {
1219
+ bucket: name,
1220
+ exists: made === "ours",
1221
+ region: where
1222
+ };
1223
+ }
1224
+ throw new BucketNameUnavailable(id, tried.filter((n) => n !== pending));
1225
+ }
1226
+ /** Tags, Block Public Access, encryption, policy, versioning and CORS. */
1227
+ async function ensureBucketSettings(ctx, clients, input) {
1228
+ const { S3, s3 } = clients;
1229
+ const { id, bucket } = input;
1230
+ const Bucket = bucket;
1231
+ const fresh = ctx.dryRun && !input.exists;
1232
+ const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
1233
+ const set = (change, apply) => ctx.change({
1234
+ construct: id,
1235
+ resource: `bucket ${bucket}`,
1236
+ change
1237
+ }, () => apply().then(() => void 0));
1238
+ const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
1239
+ const ours = identityTags(ctx, id);
1240
+ const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
1241
+ if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
1242
+ Bucket,
1243
+ Tagging: { TagSet: [...others, ...ours].map((t) => ({
1244
+ Key: t.Key,
1245
+ Value: t.Value
1246
+ })) }
1247
+ })));
1248
+ const isOpen = input.open.length > 0;
1249
+ const block = publicAccessBlock(isOpen);
1250
+ const ensureBlock = async () => {
1251
+ const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
1252
+ if (!(now && Object.keys(block).every((k) => (now[k] ?? false) === block[k]))) await set(isOpen ? "block public access (ACLs; the policy opens the open paths)" : "block all public access", () => s3.send(new S3.PutPublicAccessBlockCommand({
1253
+ Bucket,
1254
+ PublicAccessBlockConfiguration: block
1255
+ })));
1256
+ };
1257
+ const policy = bucketPolicy(bucket, input.open);
1258
+ const ensurePolicy = async () => {
1259
+ const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
1260
+ if (!(current?.Policy !== void 0 && canonicalPolicy(JSON.parse(current.Policy)) === canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
1261
+ Bucket,
1262
+ Policy: JSON.stringify(policy)
1263
+ })));
1264
+ };
1265
+ if (isOpen) {
1266
+ await ensureBlock();
1267
+ await ensurePolicy();
1268
+ } else {
1269
+ await ensurePolicy();
1270
+ await ensureBlock();
1271
+ }
1272
+ if ((await read(() => s3.send(new S3.GetBucketEncryptionCommand({ Bucket })), ["ServerSideEncryptionConfigurationNotFoundError"]))?.ServerSideEncryptionConfiguration?.Rules?.[0]?.ApplyServerSideEncryptionByDefault?.SSEAlgorithm !== "AES256" && !fresh) await set("encrypt by default (SSE-S3)", () => s3.send(new S3.PutBucketEncryptionCommand({
1273
+ Bucket,
1274
+ ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
1275
+ })));
1276
+ const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
1277
+ if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
1278
+ Bucket,
1279
+ VersioningConfiguration: { Status: "Enabled" }
1280
+ })));
1281
+ else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
1282
+ Bucket,
1283
+ VersioningConfiguration: { Status: "Suspended" }
1284
+ })));
1285
+ const { origins, unresolved } = bucketOrigins({
1286
+ workspace: ctx.workspace,
1287
+ manifest: ctx.manifest,
1288
+ runnables: ctx.runnables,
1289
+ stage: ctx.stage,
1290
+ bucket: id
1291
+ });
1292
+ if (unresolved.length > 0) ctx.log(` ${unresolved.join(", ")} ${unresolved.length === 1 ? "has" : "have"} no address on '${ctx.stage}' (domains.${ctx.stage}), so ${unresolved.length === 1 ? "is" : "are"} not in '${bucket}''s CORS`);
1293
+ if (origins.length === 0) return;
1294
+ const rule = corsRule(origins);
1295
+ const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
1296
+ if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
1297
+ Bucket,
1298
+ CORSConfiguration: { CORSRules: [rule] }
1299
+ })));
1300
+ }
1301
+ function canonicalCors(rule) {
1302
+ const sorted = (list) => [...list ?? []].sort();
1303
+ return JSON.stringify({
1304
+ AllowedMethods: sorted(rule.AllowedMethods),
1305
+ AllowedOrigins: sorted(rule.AllowedOrigins),
1306
+ AllowedHeaders: sorted(rule.AllowedHeaders),
1307
+ ExposeHeaders: sorted(rule.ExposeHeaders),
1308
+ MaxAgeSeconds: rule.MaxAgeSeconds ?? null
1309
+ });
1310
+ }
1311
+ /**
1312
+ * Each provisioned bucket answers `HeadBucket` to the key in the stage's
1313
+ * secrets — the one the apps will use. A bucket whose URL carries no key is
1314
+ * not one this provider wrote, and the deploy's own check covers a URL that
1315
+ * is missing.
1316
+ *
1317
+ * A failure is read by its status, never its name — a `HEAD` has no body,
1318
+ * so SDK v3 calls a 301, 400 or 403 `Unknown` — and the message carries
1319
+ * everything S3 said: status, error, region, request ids.
1320
+ *
1321
+ * @throws {BucketRegionMismatch} the bucket is in another region than its URL says
1322
+ * @throws {ProvisionedBucketUnreachable}
1323
+ */
1324
+ async function verifyS3(ctx) {
1325
+ const S3 = await import("@aws-sdk/client-s3");
1326
+ for (const { id } of bucketConstructs(ctx.manifest)) {
1327
+ const urlKey = provideKey(id, "url");
1328
+ const url = ctx.secrets[urlKey];
1329
+ if (url === void 0) continue;
1330
+ const address = s3Url.parse(url);
1331
+ if (!address.accessKeyId || !address.secretAccessKey) continue;
1332
+ const asked = address.region ?? ctx.config.region ?? "us-east-1";
1333
+ const client = new S3.S3Client({
1334
+ region: asked,
1335
+ credentials: {
1336
+ accessKeyId: address.accessKeyId,
1337
+ secretAccessKey: address.secretAccessKey
1338
+ },
1339
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
1340
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
1341
+ });
1342
+ try {
1343
+ const issuedAt = issuedJustNow(ctx.resources, id, address.accessKeyId);
1344
+ const { answer: head, waited } = await whileKeyIsNew(await headBucket(S3, client, address.bucket), {
1345
+ issuedAt,
1346
+ refused: (answer) => !answer.ok && answer.status === 403,
1347
+ ask: () => headBucket(S3, client, address.bucket),
1348
+ onWait: () => ctx.log?.(` ${id}: waiting for the new key ${address.accessKeyId} to become active…`)
1349
+ });
1350
+ if (head.ok) continue;
1351
+ const fail = (reason) => new ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, reason);
1352
+ const said = describeAnswer(head);
1353
+ if (head.status === 301 || head.status === 400 && head.region && head.region !== asked) {
1354
+ let where = head.region;
1355
+ let located = "";
1356
+ if (!where) {
1357
+ const location = await bucketLocation(S3, client, address.bucket);
1358
+ if ("region" in location) where = location.region;
1359
+ else located = `; GetBucketLocation answered ${describeAnswer(location.failed)}`;
1360
+ }
1361
+ if (where && where !== asked) throw new BucketRegionMismatch(id, address.bucket, ctx.stage, urlKey, where, address.region, asked, said);
1362
+ throw fail(`S3 redirected the request (${said}${located})`);
1363
+ }
1364
+ if (head.status === 404) throw fail(`it does not exist (${said})`);
1365
+ if (head.status === 403) throw fail(`the key is refused — AccessDenied, or an invalid or not-yet-active key (${said})` + (issuedAt ? `. The key was issued at ${issuedAt} by this deploy, and IAM keys take seconds to become usable: it was still refused after waiting ${Math.round(waited / 1e3)}s` : ""));
1366
+ throw fail(said);
1367
+ } finally {
1368
+ client.destroy();
1369
+ }
1370
+ }
1371
+ }
1372
+ //#endregion
1373
+ //#region src/providers/registry.ts
1374
+ /**
1375
+ * The providers gkm ships, by kind and name — registered the way a deploy
1376
+ * target's built-ins are (`target/builtins.ts`). A provider from a package is
1377
+ * one more entry here once there is a loading story for it.
1378
+ */
1379
+ const BUILTIN_PROVIDERS = { objects: { s3: {
1380
+ kind: "objects",
1381
+ name: "s3",
1382
+ check: checkS3Config,
1383
+ provisioning: S3_PROVISIONING,
1384
+ credentials: awsProvisioningCredentials,
1385
+ runtimeKeys(manifest) {
1386
+ return bucketConstructs(manifest).flatMap((b) => [provideKey(b.id, "url"), ...b.servers.map((s) => provideKey(s.id, "url"))]);
1387
+ },
1388
+ ensure: ensureS3,
1389
+ verify: verifyS3
1390
+ } } };
1391
+ /** The provider `kind` names `name`, if gkm has one. */
1392
+ function builtinProvider(kind, name) {
1393
+ return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
1394
+ }
1395
+ //#endregion
1396
+ //#region src/providers/index.ts
1397
+ /** The constructs of a kind: `objects` is every bucket. */
1398
+ function constructsOf(manifest, kind) {
1399
+ return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
1400
+ }
1401
+ /**
1402
+ * What every deploy runs: each provider's `verify()` — the cheap check that
1403
+ * what it created is still there and the stage's key reaches it. Nothing on
1404
+ * the local stage, and nothing for a kind on `external` or `false` — a kind
1405
+ * the stage has none of is the deploy's readiness check's to refuse.
1406
+ */
1407
+ async function verifyStageProviders(input) {
1408
+ const verified = [];
1409
+ for (const kind of PROVIDER_KINDS) {
1410
+ if (constructsOf(input.manifest, kind).length === 0) continue;
1411
+ const choice = stageProvider(input.workspace, kind, input.stage);
1412
+ if (choice.mode !== "provider") continue;
1413
+ const provider = builtinProvider(kind, choice.name);
1414
+ await provider.verify({
1415
+ workspace: input.workspace,
1416
+ manifest: input.manifest,
1417
+ stage: input.stage,
1418
+ config: choice.config,
1419
+ secrets: input.secrets,
1420
+ ...input.resources ? { resources: input.resources } : {},
1421
+ ...input.log ? { log: input.log } : {}
1422
+ });
1423
+ verified.push(`${kind}: ${provider.name}`);
1424
+ }
1425
+ if (await verifyStageBackups(input)) verified.push("backups: s3");
1426
+ return verified;
1427
+ }
1428
+ /**
1429
+ * A stage whose provider creates its resources, and no credentials to create
1430
+ * them with. Raised before anything is created, built or started.
1431
+ */
1432
+ var ProviderCredentialsMissing = class extends GkmError {
1433
+ stage;
1434
+ kind;
1435
+ provider;
1436
+ ids;
1437
+ env;
1438
+ describe;
1439
+ login;
1440
+ constructor(stage, kind, provider, ids, env, describe, login) {
1441
+ super(`deploy.${kind}.${stage} is ${provider}, so the deploy creates what ${ids.join(", ")} ${ids.length === 1 ? "is" : "are"} backed by on '${stage}' and writes ${ids.length === 1 ? "its key" : "their keys"} into the stage's secrets — and it found no ${provider} credentials to do it with. On this machine, supply ${describe}` + (login ? `, or run gkm login --provider ${login}` : "") + `. In CI, the step that runs the deploy needs them: the '${stage}' environment's role (AWS_ROLE_ARN, from gkm deploy:github), assumed before that step. With the keys set by hand instead, set deploy.${kind}.${stage} to 'external'.`);
1442
+ this.stage = stage;
1443
+ this.kind = kind;
1444
+ this.provider = provider;
1445
+ this.ids = ids;
1446
+ this.env = env;
1447
+ this.describe = describe;
1448
+ this.login = login;
1449
+ this.name = "ProviderCredentialsMissing";
1450
+ }
1451
+ };
1452
+ /**
1453
+ * `ensure()` for every provider the stage configures — find or create, fix
1454
+ * drift, record in the stage's state, write the runtime keys into its
1455
+ * secrets. Run by the deploy, which holds the stage's lock. A provider with
1456
+ * no provisioning credentials stops the run with
1457
+ * {@link ProviderCredentialsMissing} before anything is created.
1458
+ */
1459
+ async function provisionStage(options) {
1460
+ const { workspace, stage, manifest } = options;
1461
+ const dryRun = options.dryRun === true;
1462
+ const env = options.env ?? process.env;
1463
+ const log = options.log ?? ((line) => console.log(line));
1464
+ const runnables = options.runnables ?? {};
1465
+ const reports = [];
1466
+ const configured = [];
1467
+ for (const kind of PROVIDER_KINDS) {
1468
+ const choice = stageProvider(workspace, kind, stage);
1469
+ if (choice.mode !== "provider") {
1470
+ reports.push({
1471
+ kind,
1472
+ mode: choice.mode,
1473
+ actions: [],
1474
+ planned: []
1475
+ });
1476
+ continue;
1477
+ }
1478
+ const provider = builtinProvider(kind, choice.name);
1479
+ const report = {
1480
+ kind,
1481
+ mode: "provider",
1482
+ provider: provider.name,
1483
+ actions: [],
1484
+ planned: []
1485
+ };
1486
+ reports.push(report);
1487
+ const ids = constructsOf(manifest, kind);
1488
+ if (ids.length === 0) continue;
1489
+ const credential = await provider.credentials({
1490
+ stage,
1491
+ env,
1492
+ ...options.profile ? { profile: options.profile } : {},
1493
+ ...options.home ? { home: options.home } : {}
1494
+ });
1495
+ if (credential === void 0) throw new ProviderCredentialsMissing(stage, kind, provider.name, ids, provider.provisioning.env, provider.provisioning.describe, provider.provisioning.login);
1496
+ configured.push({
1497
+ kind,
1498
+ provider,
1499
+ config: choice.config,
1500
+ credential,
1501
+ report
1502
+ });
1503
+ }
1504
+ const backups = stageBackups(workspace, manifest, stage);
1505
+ if (configured.length === 0 && backups.mode !== "on") {
1506
+ if (backups.mode === "disabled") log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
1507
+ return reports;
1508
+ }
1509
+ const identity = deployIdentity(workspace, stage);
1510
+ let secrets = (await options.secrets.read())?.custom ?? {};
1511
+ for (const entry of configured) entry.report.planned = entry.provider.runtimeKeys(manifest).filter((key) => secrets[key] === void 0);
1512
+ const state = dryRun ? await readOnlyState(options.state, stage) : journalState(await DeployJournal.open(options.state, stage, () => deploysWithCompose(workspace) ? createComposeState(stage) : createEmptyState(stage, "", "")));
1513
+ const writeSecrets = async (values) => {
1514
+ if (dryRun) return;
1515
+ const stored = await options.secrets.read() ?? initStageSecrets(stage);
1516
+ const next = {
1517
+ ...stored,
1518
+ custom: {
1519
+ ...stored.custom,
1520
+ ...values
1521
+ },
1522
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1523
+ };
1524
+ await options.secrets.write(next);
1525
+ secrets = next.custom;
1526
+ };
1527
+ for (const entry of configured) {
1528
+ log(`☁️ ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
1529
+ await entry.provider.ensure({
1530
+ workspace,
1531
+ manifest,
1532
+ runnables,
1533
+ stage,
1534
+ identity,
1535
+ config: entry.config,
1536
+ credential: entry.credential,
1537
+ get secrets() {
1538
+ return secrets;
1539
+ },
1540
+ state,
1541
+ dryRun,
1542
+ rotateKeys: options.rotateKeys === true,
1543
+ retireOldKeys: options.retireOldKeys === true,
1544
+ async change(action, apply) {
1545
+ if (!dryRun) await apply();
1546
+ entry.report.actions.push(action);
1547
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
1548
+ },
1549
+ writeSecrets,
1550
+ log
1551
+ });
1552
+ if (entry.report.actions.length === 0) log(" up to date");
1553
+ }
1554
+ if (backups.mode === "on" || backups.mode === "disabled") {
1555
+ const report = {
1556
+ kind: "backups",
1557
+ mode: backups.mode === "on" ? "provider" : "none",
1558
+ actions: [],
1559
+ planned: backups.mode === "on" && secrets["BACKUPS_URL"] === void 0 ? [BACKUPS_URL_KEY] : []
1560
+ };
1561
+ reports.push(report);
1562
+ await ensureStageBackups({
1563
+ workspace,
1564
+ manifest,
1565
+ stage,
1566
+ ...options.profile ? { profile: options.profile } : {},
1567
+ ...options.home ? { home: options.home } : {},
1568
+ env,
1569
+ ctx: {
1570
+ identity,
1571
+ stage,
1572
+ state,
1573
+ dryRun,
1574
+ get secrets() {
1575
+ return secrets;
1576
+ },
1577
+ rotateKeys: options.rotateKeys === true,
1578
+ retireOldKeys: options.retireOldKeys === true,
1579
+ async change(action, apply) {
1580
+ if (!dryRun) await apply();
1581
+ report.actions.push(action);
1582
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
1583
+ },
1584
+ writeSecrets,
1585
+ log
1586
+ }
1587
+ });
1588
+ if (backups.mode === "on" && report.actions.length === 0) log(" up to date");
1589
+ }
1590
+ return reports;
1591
+ }
1592
+ /** The journal as `ensure()` sees it. */
1593
+ function journalState(journal) {
1594
+ return {
1595
+ record: (key) => journal.record(key),
1596
+ pending: (entry) => journal.pending(entry),
1597
+ ready: (entry, id) => journal.ready(entry, id),
1598
+ lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
1599
+ };
1600
+ }
1601
+ /** What a dry run reads, and the writes it does not make. */
1602
+ async function readOnlyState(store, stage) {
1603
+ const stored = await store.read(stage);
1604
+ return {
1605
+ record: (key) => stored?.resources[key],
1606
+ pending: async () => {},
1607
+ ready: async () => {},
1608
+ ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
1609
+ };
1610
+ }
1611
+ //#endregion
1612
+ //#region src/secrets/stale.ts
1613
+ /**
1614
+ * Stored secrets an older gkm generated that now shadow a derived value.
1615
+ *
1616
+ * Before constructs, initialising a stage wrote an address for each app into
1617
+ * its custom secrets: `<APP>_DATABASE_URL` as a `postgresql://…@localhost`
1618
+ * URL with a password of its own, and `http://localhost:<port>` for a site or
1619
+ * an auth server. Those keys are now a construct's — `database.schema('AuthDatabase')`
1620
+ * provides `AUTH_DATABASE_URL`, `new BetterAuth('Auth')` provides `AUTH_URL`
1621
+ * — and a deploy derives them. A value the stage holds is a value set by hand,
1622
+ * and set by hand wins: the container is handed `localhost`, where nothing
1623
+ * answers, with a password no role has.
1624
+ *
1625
+ * So a deploy refuses such a stage rather than run it, naming each key and
1626
+ * the command that removes it. Nothing is deleted for the user: the value is
1627
+ * theirs, and only they can say it is stale. A URL that names a real host — a
1628
+ * managed database — is a deliberate choice and still wins.
1629
+ */
1630
+ /** The kinds whose URL an older gkm wrote into a stage's secrets. */
1631
+ const ADDRESSED = /* @__PURE__ */ new Set([
1632
+ "database",
1633
+ "database-reader",
1634
+ "database-schema",
1635
+ "rest-api",
1636
+ "site"
1637
+ ]);
1638
+ /** Hosts that are this machine — never anything, inside a container. */
1639
+ const LOOPBACK = /* @__PURE__ */ new Set([
1640
+ "localhost",
1641
+ "127.0.0.1",
1642
+ "[::1]",
1643
+ "::1"
1644
+ ]);
1645
+ /**
1646
+ * A stage holds a construct's address as a custom secret, pointing at
1647
+ * `localhost` — what an older `gkm secrets:init`, `gkm setup` or `gkm init`
1648
+ * generated. Set by hand wins over derived, so the app would be handed it.
1649
+ */
1650
+ var StaleStageSecrets = class extends GkmError {
1651
+ stage;
1652
+ stale;
1653
+ constructor(stage, stale) {
1654
+ const one = stale.length === 1;
1655
+ super(`The stage '${stage}' holds ${one ? "a value" : "values"} an older gkm generated for ${one ? "an address a construct" : "addresses constructs"} now ${one ? "provides" : "provide"}:\n` + stale.map((s) => ` ${s.key}: ${s.construct}'s, stored pointing at ${s.host}`).join("\n") + `
1656
+ A stored value wins over the derived one, so the app would be handed an address where nothing answers inside its container. Remove ${one ? "it" : "each"}, and the construct's own value is used:\n` + stale.map((s) => ` gkm secrets:unset ${s.key} --stage ${stage}`).join("\n") + "\nA managed service set with its real host is not affected.");
1657
+ this.stage = stage;
1658
+ this.stale = stale;
1659
+ this.name = "StaleStageSecrets";
1660
+ }
1661
+ };
1662
+ /** The host a stored value names, if it is a URL. */
1663
+ function hostOf(value) {
1664
+ try {
1665
+ return new URL(value).hostname;
1666
+ } catch {
1667
+ return;
1668
+ }
1669
+ }
1670
+ /**
1671
+ * Each stored key that a construct provides an address for, holding an
1672
+ * address on this machine.
1673
+ */
1674
+ function staleStageSecrets(manifest, supplied) {
1675
+ const stale = [];
1676
+ for (const [id, declaration] of Object.entries(manifest)) {
1677
+ if (!ADDRESSED.has(declaration.kind)) continue;
1678
+ const key = providedKeyFor(id, declaration.kind, "url");
1679
+ const value = supplied[key];
1680
+ if (value === void 0) continue;
1681
+ const host = hostOf(value);
1682
+ if (host === void 0 || !LOOPBACK.has(host)) continue;
1683
+ stale.push({
1684
+ key,
1685
+ construct: id,
1686
+ host
1687
+ });
1688
+ }
1689
+ return stale.sort((a, b) => a.key.localeCompare(b.key));
1690
+ }
1691
+ /**
1692
+ * Refuse a stage whose stored secrets would shadow a construct's address with
1693
+ * `localhost`.
1694
+ *
1695
+ * @throws {StaleStageSecrets} naming each key and the command removing it
1696
+ */
1697
+ function assertNoStaleSecrets(options) {
1698
+ const stale = staleStageSecrets(options.manifest, options.supplied);
1699
+ if (stale.length > 0) throw new StaleStageSecrets(options.stage, stale);
1700
+ }
1701
+ //#endregion
1702
+ //#region src/deploy/readiness.ts
1703
+ /**
1704
+ * Whether a stage is ready to be deployed: the one check, run once by every
1705
+ * deploy through a server target — after the stage's providers have created
1706
+ * what they create and written its keys, and before the target touches
1707
+ * anything.
1708
+ *
1709
+ * A build is not a deploy. Images carry no stage's keys, so a build-only run
1710
+ * (`gkm compose --build --push`) never calls this: a key the deploy itself
1711
+ * writes — a provider's bucket URL — is not there yet when CI builds, and
1712
+ * must not stop the build.
1713
+ */
1714
+ /**
1715
+ * The stage has every key it needs, read from its secrets as the providers
1716
+ * left them:
1717
+ *
1718
+ * 1. no kind it declares is one the stage set to `false`;
1719
+ * 2. its mail and storage are its own — or a dev service, where allowed,
1720
+ * reported once, loudly;
1721
+ * 3. what its providers created is still there, and its key reaches it;
1722
+ * 4. no key holds an address an older gkm stored for what a construct now
1723
+ * provides;
1724
+ * 5. each third party's credentials match their construct's schema.
1725
+ *
1726
+ * The local stage derives its mail and storage, so only 4 and 5 apply to it.
1727
+ *
1728
+ * @throws {StageProviderDisabled}
1729
+ * @throws {ExternalServicesNotConfigured} naming every missing key at once
1730
+ * @throws {StaleStageSecrets}
1731
+ * @throws {CredentialsInvalid}
1732
+ */
1733
+ async function assertStageReady(ctx) {
1734
+ const { workspace, manifest, stage } = ctx;
1735
+ const supplied = (await ctx.secrets.read())?.custom ?? {};
1736
+ if (stage !== workspace.stages.local) {
1737
+ assertStageProvidersEnabled(workspace, manifest, stage);
1738
+ const domain = workspace.domains?.[stage];
1739
+ const services = externalServices({
1740
+ stage,
1741
+ declarations: stageServiceDeclarations({
1742
+ manifest,
1743
+ ...ctx.runnables ? { runnables: ctx.runnables } : {}
1744
+ }),
1745
+ supplied,
1746
+ allow: ctx.allowDevServices,
1747
+ ...domain ? { domain } : {},
1748
+ providers: stageProviderNotes(workspace, stage)
1749
+ });
1750
+ if (services.missing.length > 0) throw new ExternalServicesNotConfigured(stage, services.missing);
1751
+ reportDevServices(ctx, devServicesUsed(services));
1752
+ const verified = await verifyStageProviders({
1753
+ workspace,
1754
+ manifest,
1755
+ stage,
1756
+ secrets: supplied,
1757
+ resources: (await ctx.state.read(stage))?.resources ?? {},
1758
+ log: (line) => ctx.logger.info(line)
1759
+ });
1760
+ for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
1761
+ }
1762
+ assertNoStaleSecrets({
1763
+ manifest,
1764
+ stage,
1765
+ supplied
1766
+ });
1767
+ await assertStageCredentials({
1768
+ root: workspace.root,
1769
+ patterns: constructGlobs(workspace),
1770
+ manifest,
1771
+ stage,
1772
+ supplied
1773
+ });
1774
+ }
1775
+ //#endregion
1776
+ //#region src/deploy/orchestrate.ts
1777
+ /**
1778
+ * The run around a target: what every deploy does whatever it deploys
1779
+ * through.
1780
+ *
1781
+ * It loads the workspace, resolves the target, works out the apps and the
1782
+ * identity, takes the stage's lock, and calls the target's phases in order,
1783
+ * reporting each as it starts, finishes or fails. Everything that is about
1784
+ * *where* the stage goes is the target's.
1785
+ */
1786
+ /** Apps were asked for by name that the workspace does not have. */
1787
+ var UnknownDeployApps = class extends GkmError {
1788
+ apps;
1789
+ available;
1790
+ constructor(apps, available) {
1791
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
1792
+ this.apps = apps;
1793
+ this.available = available;
1794
+ this.name = "UnknownDeployApps";
1795
+ }
1796
+ };
1797
+ /** Every app asked for deploys through some other target. */
1798
+ var NoDeployableApps = class extends GkmError {
1799
+ stage;
1800
+ target;
1801
+ constructor(stage, target) {
1802
+ super(`No apps to deploy through "${target}": every selected app deploys somewhere else. Pick the target with --target, or set each app's deploy in gkm.config.ts.`);
1803
+ this.stage = stage;
1804
+ this.target = target;
1805
+ this.name = "NoDeployableApps";
1806
+ }
1807
+ };
1808
+ /** A build-only run through a target with no build phase. */
1809
+ var TargetBuildsNothing = class extends GkmError {
1810
+ target;
1811
+ constructor(target) {
1812
+ super(`"${target}" has no build phase, so a build-only run would do nothing. Deploy it in full, or build through a target that builds images (compose).`);
1813
+ this.target = target;
1814
+ this.name = "TargetBuildsNothing";
1815
+ }
1816
+ };
1817
+ /** A failed rollback, after the failure that called for it. */
1818
+ var RollbackFailed = class extends Error {
1819
+ target;
1820
+ failure;
1821
+ constructor(target, failure, cause) {
1822
+ super(`Deploying through "${target}" failed, and so did rolling it back: ${cause instanceof Error ? cause.message : String(cause)}. The stage may be part-released; deploy again, or roll it back by hand. The first failure: ${failure instanceof Error ? failure.message : String(failure)}`, { cause });
1823
+ this.target = target;
1824
+ this.failure = failure;
1825
+ this.name = "RollbackFailed";
1826
+ }
1827
+ };
1828
+ /**
1829
+ * Generate image tag from stage and timestamp
1830
+ */
1831
+ function generateTag(stage) {
1832
+ return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
1833
+ }
1834
+ /** Why an app that deploys through another target is left out. */
1835
+ function elsewhere(target, stage) {
1836
+ const instead = builtinTarget(target)?.instead?.(stage);
1837
+ if (instead) return `it deploys through "${target}" — ${instead}`;
1838
+ return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
1839
+ }
1840
+ /**
1841
+ * Deploy a workspace's stage through its target.
1842
+ *
1843
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
1844
+ * exits: credentials come from `ctx.credentials`, progress goes to
1845
+ * `ctx.emit` and to `output`, and every failure is thrown.
1846
+ *
1847
+ * @internal
1848
+ */
1849
+ async function runDeploy(source, request, ctx) {
1850
+ const { stage } = request;
1851
+ const redactor = ctx.redactor ?? new Redactor();
1852
+ const emit = (event) => ctx.emit(event.type === "log" ? {
1853
+ ...event,
1854
+ message: redactor.redact(event.message)
1855
+ } : event);
1856
+ /** Run one phase between its events. */
1857
+ const phase = async (name, body) => {
1858
+ ctx.signal?.throwIfAborted();
1859
+ emit({
1860
+ type: "phase.started",
1861
+ phase: name
1862
+ });
1863
+ try {
1864
+ const value = await body();
1865
+ emit({
1866
+ type: "phase.finished",
1867
+ phase: name
1868
+ });
1869
+ return value;
1870
+ } catch (error) {
1871
+ emit({
1872
+ type: "phase.failed",
1873
+ phase: name,
1874
+ error: eventError(error)
1875
+ });
1876
+ throw error;
1877
+ }
1878
+ };
1879
+ ctx.signal?.throwIfAborted();
1880
+ emit({
1881
+ type: "phase.started",
1882
+ phase: "validate"
1883
+ });
1884
+ let prepared;
1885
+ try {
1886
+ prepared = await prepare(source, request, ctx, emit, redactor);
1887
+ } catch (error) {
1888
+ emit({
1889
+ type: "phase.failed",
1890
+ phase: "validate",
1891
+ error: eventError(error)
1892
+ });
1893
+ throw error;
1894
+ }
1895
+ const { resolved, phaseCtx, store } = prepared;
1896
+ const { target } = resolved;
1897
+ const resources = !ctx.buildOnly && phaseCtx.stage !== phaseCtx.workspace.stages.local;
1898
+ const provision = async () => {
1899
+ if (!request.skipDns && resolved.target.runtime === "server") try {
1900
+ await dnsCredentials(phaseCtx.stage, stageDnsDomains(phaseCtx.stage, phaseCtx.workspace.domains, phaseCtx.workspace.dns), ctx.credentials);
1901
+ } catch (error) {
1902
+ emit({
1903
+ type: "phase.failed",
1904
+ phase: "validate",
1905
+ error: eventError(error)
1906
+ });
1907
+ throw error;
1908
+ }
1909
+ await provisionResources(phaseCtx, request, ctx, store, emit);
1910
+ };
1911
+ if (ctx.dryRun) {
1912
+ if (resources) await provision();
1913
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1914
+ await phase("plan", () => target.plan(phaseCtx, run));
1915
+ return target.result(phaseCtx, run);
1916
+ }
1917
+ if (ctx.buildOnly) {
1918
+ if (!target.build) throw new TargetBuildsNothing(resolved.name);
1919
+ const run = await validate(phaseCtx, emit, () => target.validate(phaseCtx));
1920
+ await phase("build", () => target.build(phaseCtx, run));
1921
+ return target.result(phaseCtx, run);
1922
+ }
1923
+ let lock;
1924
+ try {
1925
+ assertStateOutlivesRun(phaseCtx.workspace, stage, "deploy");
1926
+ lock = await store.lock(stage, { operation: "deploy" });
1927
+ } catch (error) {
1928
+ emit({
1929
+ type: "phase.failed",
1930
+ phase: "validate",
1931
+ error: eventError(error)
1932
+ });
1933
+ throw error;
1934
+ }
1935
+ try {
1936
+ try {
1937
+ await assertStateRoom(store, stage);
1938
+ } catch (error) {
1939
+ emit({
1940
+ type: "phase.failed",
1941
+ phase: "validate",
1942
+ error: eventError(error)
1943
+ });
1944
+ throw error;
1945
+ }
1946
+ if (resources) await provision();
1947
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1948
+ if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
1949
+ if (target.build) await phase("build", () => target.build(phaseCtx, run));
1950
+ let releasing = "release";
1951
+ try {
1952
+ await phase("release", () => target.release(phaseCtx, run));
1953
+ releasing = "verify";
1954
+ if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
1955
+ } catch (error) {
1956
+ if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
1957
+ if (!target.rollback) throw error;
1958
+ try {
1959
+ await phase("rollback", () => target.rollback(phaseCtx, run, {
1960
+ phase: releasing,
1961
+ error
1962
+ }));
1963
+ } catch (rollbackError) {
1964
+ throw new RollbackFailed(resolved.name, error, rollbackError);
1965
+ }
1966
+ throw error;
1967
+ }
1968
+ return await target.result(phaseCtx, run);
1969
+ } finally {
1970
+ await lock.release();
1971
+ }
1972
+ }
1973
+ /**
1974
+ * The stage's providers, run inside the validate phase. A dry run plans them
1975
+ * and, so the checks after it see the stage as the run would leave it, reads
1976
+ * the keys they would write as placeholders.
1977
+ */
1978
+ async function provisionResources(phaseCtx, request, ctx, store, emit) {
1979
+ try {
1980
+ const reports = await provisionStage({
1981
+ workspace: phaseCtx.workspace,
1982
+ stage: phaseCtx.stage,
1983
+ manifest: phaseCtx.manifest,
1984
+ runnables: phaseCtx.runnables ?? {},
1985
+ secrets: phaseCtx.secrets,
1986
+ state: store,
1987
+ dryRun: ctx.dryRun,
1988
+ ...request.rotateKeys ? { rotateKeys: true } : {},
1989
+ ...request.retireOldKeys ? { retireOldKeys: true } : {},
1990
+ ...ctx.home ? { home: ctx.home } : {},
1991
+ log: (line) => phaseCtx.logger.info(line)
1992
+ });
1993
+ if (!ctx.dryRun) return;
1994
+ const planned = reports.flatMap((r) => r.planned);
1995
+ if (planned.length === 0) return;
1996
+ const secrets = phaseCtx.secrets;
1997
+ phaseCtx.secrets = {
1998
+ ...secrets,
1999
+ async read() {
2000
+ const stored = await secrets.read() ?? initStageSecrets(phaseCtx.stage);
2001
+ const custom = { ...stored.custom };
2002
+ for (const key of planned) custom[key] ??= PLANNED_BY_THE_DEPLOY;
2003
+ return {
2004
+ ...stored,
2005
+ custom
2006
+ };
2007
+ }
2008
+ };
2009
+ } catch (error) {
2010
+ emit({
2011
+ type: "phase.failed",
2012
+ phase: "validate",
2013
+ error: eventError(error)
2014
+ });
2015
+ throw error;
2016
+ }
2017
+ }
2018
+ /** What a dry run reads for a key its providers would write. */
2019
+ const PLANNED_BY_THE_DEPLOY = "s3://planned-by-this-deploy";
2020
+ /**
2021
+ * What a deploy validates: the stage ready to be deployed — every key it
2022
+ * needs, read as its providers left them — then what the target would run,
2023
+ * then whatever only the target checks. A build-only run validates the
2024
+ * target's run alone: it calls neither readiness check.
2025
+ */
2026
+ async function readyToDeploy(target, phaseCtx) {
2027
+ if (target.runtime === "server") await assertStageReady(phaseCtx);
2028
+ const run = await target.validate(phaseCtx);
2029
+ await target.ready?.(phaseCtx, run);
2030
+ return run;
2031
+ }
2032
+ /** `body`, then the run's `deploy.started`, inside the validate phase. */
2033
+ async function validate(phaseCtx, emit, body) {
2034
+ try {
2035
+ const run = await body();
2036
+ const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
2037
+ emit({
2038
+ type: "deploy.started",
2039
+ stage: phaseCtx.stage,
2040
+ target: phaseCtx.target,
2041
+ identity: phaseCtx.identity.key,
2042
+ tag: phaseCtx.tag,
2043
+ apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
2044
+ dryRun: phaseCtx.dryRun
2045
+ });
2046
+ emit({
2047
+ type: "phase.finished",
2048
+ phase: "validate"
2049
+ });
2050
+ return run;
2051
+ } catch (error) {
2052
+ emit({
2053
+ type: "phase.failed",
2054
+ phase: "validate",
2055
+ error: eventError(error)
2056
+ });
2057
+ throw error;
2058
+ }
2059
+ }
2060
+ /** Everything the phases are handed, worked out before the first of them. */
2061
+ async function prepare(source, request, ctx, emit, redactor) {
2062
+ const { stage } = request;
2063
+ const configured = typeof source === "function" ? await source() : source;
2064
+ const local = stage === configured.stages.local;
2065
+ if (!local) assertDeployedStage(configured.stages, stage);
2066
+ const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
2067
+ const resolved = await resolveTarget(targetName, {
2068
+ workspace: configured,
2069
+ stage,
2070
+ ...ctx.targets ? { host: ctx.targets } : {}
2071
+ });
2072
+ if (local && !resolved.target.capabilities.localStage) assertDeployedStage(configured.stages, stage);
2073
+ const options = await parseTargetOptions(resolved);
2074
+ const allowDevServices = request.allowDevServices === true;
2075
+ if (allowDevServices && resolved.target.runtime === "aws") throw new DevServicesNeedServerTarget(targetName);
2076
+ const runnables = {};
2077
+ const background = {};
2078
+ const manifest = await discover({
2079
+ patterns: constructGlobs(configured),
2080
+ cwd: configured.root,
2081
+ runnables,
2082
+ background
2083
+ });
2084
+ resolveStageTelemetry({
2085
+ ...configured.deploy?.telemetry ? { telemetry: configured.deploy.telemetry } : {},
2086
+ stage,
2087
+ local,
2088
+ target: targetName,
2089
+ runtime: resolved.target.runtime,
2090
+ selfHosted: resolved.target.capabilities.selfHostedTelemetry === true,
2091
+ used: usesTelemetry(manifest)
2092
+ });
2093
+ const units = derivedApps(manifest, configured);
2094
+ const workspace = Object.keys(units).length > 0 ? {
2095
+ ...configured,
2096
+ apps: units
2097
+ } : configured;
2098
+ const identity = deployIdentity(workspace, stage);
2099
+ const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
2100
+ cwd: workspace.root,
2101
+ stage
2102
+ }) : generateTag(stage));
2103
+ const buildOrder = getAppBuildOrder(workspace);
2104
+ let selected = buildOrder;
2105
+ if (request.apps && request.apps.length > 0) {
2106
+ const unknown = request.apps.filter((name) => !workspace.apps[name]);
2107
+ if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
2108
+ selected = buildOrder.filter((name) => request.apps.includes(name));
2109
+ }
2110
+ const skipped = [];
2111
+ const skip = (app, reason) => {
2112
+ skipped.push({
2113
+ app,
2114
+ reason
2115
+ });
2116
+ emit({
2117
+ type: "app.skipped",
2118
+ app,
2119
+ reason
2120
+ });
2121
+ };
2122
+ const byDefault = configured.deploy?.default ?? "dokploy";
2123
+ const apps = selected.filter((name) => {
2124
+ const own = workspace.apps[name].resolvedDeployTarget;
2125
+ const deploysThrough = own === byDefault ? targetName : own;
2126
+ if (deploysThrough === targetName) return true;
2127
+ skip(name, elsewhere(deploysThrough, stage));
2128
+ return false;
2129
+ });
2130
+ if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
2131
+ const store = await createStateStore({
2132
+ config: stage === workspace.stages.local ? void 0 : workspace.state,
2133
+ workspaceRoot: workspace.root,
2134
+ workspaceName: workspace.name,
2135
+ namespace: workspace.deploy?.namespace
2136
+ });
2137
+ const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
2138
+ const line = (level) => (message) => emit({
2139
+ type: "log",
2140
+ level,
2141
+ message
2142
+ });
2143
+ const logger = {
2144
+ info: line("info"),
2145
+ warn: line("warn"),
2146
+ error: line("error")
2147
+ };
2148
+ return {
2149
+ resolved,
2150
+ phaseCtx: {
2151
+ target: targetName,
2152
+ cwd: workspace.root,
2153
+ stage,
2154
+ tag,
2155
+ tagGiven: request.tag !== void 0,
2156
+ apps,
2157
+ skipped,
2158
+ identity,
2159
+ workspace,
2160
+ manifest,
2161
+ runnables,
2162
+ background,
2163
+ options,
2164
+ dryRun: ctx.dryRun,
2165
+ atomic: request.atomic ?? false,
2166
+ allowDevServices,
2167
+ ...request.skipDns ? { skipDns: true } : {},
2168
+ credentials: ctx.credentials,
2169
+ state: store,
2170
+ secrets,
2171
+ logger,
2172
+ signal: ctx.signal ?? new AbortController().signal,
2173
+ childOutput: ctx.childOutput ?? "inherit",
2174
+ emit,
2175
+ skip,
2176
+ name: (resource) => applicationName(identity, resource)
2177
+ },
2178
+ store
2179
+ };
2180
+ }
2181
+ //#endregion
2182
+ //#region src/deploy/deploy.ts
2183
+ /**
2184
+ * `deploy()`: a deploy as a library call.
2185
+ *
2186
+ * `gkm deploy` could only be driven from an interactive terminal: it prompted
2187
+ * for what it lacked and exited the process on failure, worked out of
2188
+ * `process.cwd()`, and reported progress by printing. Here the caller says
2189
+ * where the project is, hands over the credentials and a signal, and gets back
2190
+ * a run — events to iterate while it goes, and a structured result at the end.
2191
+ * Nothing below this asks a person anything or ends the process; `gkm deploy`
2192
+ * is a thin wrapper that does both.
2193
+ */
2194
+ /**
2195
+ * Every event a run emits, kept so that each iteration — however late it
2196
+ * starts — sees the run from its first event to its last.
2197
+ */
2198
+ var EventLog = class {
2199
+ events = [];
2200
+ closed = false;
2201
+ waiting = [];
2202
+ push(event) {
2203
+ this.events.push(event);
2204
+ this.wake();
2205
+ }
2206
+ close() {
2207
+ this.closed = true;
2208
+ this.wake();
2209
+ }
2210
+ wake() {
2211
+ const waiting = this.waiting;
2212
+ this.waiting = [];
2213
+ for (const resume of waiting) resume();
2214
+ }
2215
+ async *iterate() {
2216
+ let next = 0;
2217
+ while (true) if (next < this.events.length) yield this.events[next++];
2218
+ else if (this.closed) return;
2219
+ else await new Promise((resume) => this.waiting.push(resume));
2220
+ }
2221
+ };
2222
+ function forward(logger, level, message) {
2223
+ if (!logger) return;
2224
+ if (level === "info") logger.info(message);
2225
+ else if (level === "error" && logger.error) logger.error(message);
2226
+ else logger.warn(message);
2227
+ }
2228
+ /**
2229
+ * Deploy a project's stage.
2230
+ *
2231
+ * ```ts
2232
+ * import { deploy } from '@geekmidas/cli/deploy';
2233
+ *
2234
+ * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
2235
+ * for await (const event of run) {
2236
+ * if (event.type === 'app.deployed') console.log(event.app, event.url);
2237
+ * }
2238
+ * const result = await run.result;
2239
+ * ```
2240
+ *
2241
+ * The run starts at once; iterating it is optional, and an iteration started
2242
+ * late still sees every event from the first.
2243
+ */
2244
+ function deploy(input) {
2245
+ const log = new EventLog();
2246
+ const redactor = new Redactor();
2247
+ const emit = (event) => {
2248
+ const masked = event.type === "log" ? {
2249
+ ...event,
2250
+ message: redactor.redact(event.message)
2251
+ } : event;
2252
+ log.push(masked);
2253
+ if (masked.type === "log") forward(input.logger, masked.level, masked.message);
2254
+ };
2255
+ const ctx = {
2256
+ emit,
2257
+ credentials: input.credentials ?? storedCredentials({ home: input.home ?? gkmHome() }),
2258
+ dryRun: input.dryRun ?? false,
2259
+ ...input.buildOnly ? { buildOnly: true } : {},
2260
+ home: input.home ?? gkmHome(),
2261
+ redactor,
2262
+ ...input.signal ? { signal: input.signal } : {},
2263
+ ...input.childOutput ? { childOutput: input.childOutput } : {},
2264
+ ...input.targets ? { targets: input.targets } : {}
2265
+ };
2266
+ const result = withOutput((level, message) => emit({
2267
+ type: "log",
2268
+ level,
2269
+ message
2270
+ }), async () => {
2271
+ try {
2272
+ input.signal?.throwIfAborted();
2273
+ const sandbox = input.sandbox ?? new LocalSandbox({ root: findWorkspaceRoot(resolve(input.cwd)) });
2274
+ const deployed = await withSandbox(sandbox, () => runDeploy(() => load(input, sandbox), {
2275
+ stage: input.stage,
2276
+ ...input.target ? { target: input.target } : {},
2277
+ ...input.tag ? { tag: input.tag } : {},
2278
+ ...input.apps ? { apps: input.apps } : {},
2279
+ ...input.atomic ? { atomic: true } : {},
2280
+ ...input.allowDevServices ? { allowDevServices: input.allowDevServices } : {},
2281
+ ...input.skipDns ? { skipDns: true } : {},
2282
+ ...input.rotateKeys ? { rotateKeys: true } : {},
2283
+ ...input.retireOldKeys ? { retireOldKeys: true } : {}
2284
+ }, ctx));
2285
+ emit({
2286
+ type: "deploy.finished",
2287
+ result: deployed
2288
+ });
2289
+ return deployed;
2290
+ } catch (error) {
2291
+ emit({
2292
+ type: "deploy.failed",
2293
+ error: eventError(error)
2294
+ });
2295
+ throw error;
2296
+ } finally {
2297
+ log.close();
2298
+ }
2299
+ });
2300
+ result.catch(() => {});
2301
+ return {
2302
+ result,
2303
+ [Symbol.asyncIterator]: () => log.iterate()
2304
+ };
2305
+ }
2306
+ /**
2307
+ * The workspace at `input.cwd`. The stage is checked by the run, once it
2308
+ * knows the target: one that runs on this machine may take the local stage.
2309
+ */
2310
+ async function load(input, sandbox) {
2311
+ const { workspace } = await loadWorkspaceConfig(resolve(input.cwd), { sandbox });
2312
+ return workspace;
2313
+ }
2314
+ //#endregion
2315
+ export { UnknownDeployApps as a, bucketName as c, awsEndpoint as d, awsProvisioningCredentials as f, TargetBuildsNothing as i, iamUserName as l, NoDeployableApps as n, backupsUserName as o, RollbackFailed as r, IAM_USER_PATH as s, deploy as t, awsClientConfig as u };
2316
+
2317
+ //# sourceMappingURL=deploy-H2S8_mTx.mjs.map