@geekmidas/cli 10.0.0-alpha.16 → 10.0.0-alpha.160

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 (438) hide show
  1. package/README.md +323 -380
  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-B5BKAoLz.mjs +1039 -0
  7. package/dist/EndpointGenerator-B5BKAoLz.mjs.map +1 -0
  8. package/dist/EndpointGenerator-DxrRqfJ3.cjs +1098 -0
  9. package/dist/EndpointGenerator-DxrRqfJ3.cjs.map +1 -0
  10. package/dist/GoDaddyProvider-C9dDlH9I.mjs +412 -0
  11. package/dist/GoDaddyProvider-C9dDlH9I.mjs.map +1 -0
  12. package/dist/GoDaddyProvider-DkUMcMYy.cjs +412 -0
  13. package/dist/GoDaddyProvider-DkUMcMYy.cjs.map +1 -0
  14. package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-9faYOQnQ.cjs} +23 -9
  15. package/dist/HostingerProvider-9faYOQnQ.cjs.map +1 -0
  16. package/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-BEuKG2gz.mjs} +23 -9
  17. package/dist/HostingerProvider-BEuKG2gz.mjs.map +1 -0
  18. package/dist/LegacyStateStore-C44jUnMH.cjs +124 -0
  19. package/dist/LegacyStateStore-C44jUnMH.cjs.map +1 -0
  20. package/dist/LegacyStateStore-DPKhjUR6.mjs +124 -0
  21. package/dist/LegacyStateStore-DPKhjUR6.mjs.map +1 -0
  22. package/dist/LocalStateStore-B95WE99i.cjs +178 -0
  23. package/dist/LocalStateStore-B95WE99i.cjs.map +1 -0
  24. package/dist/LocalStateStore-BU3fWkcT.mjs +167 -0
  25. package/dist/LocalStateStore-BU3fWkcT.mjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-DOTLKBFf.cjs +539 -0
  27. package/dist/OpenApiTsGenerator-DOTLKBFf.cjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-Vaf0pI8u.mjs +534 -0
  29. package/dist/OpenApiTsGenerator-Vaf0pI8u.mjs.map +1 -0
  30. package/dist/{Route53Provider-Cvj40A8I.mjs → Route53Provider-Di_SD9CF.mjs} +3 -3
  31. package/dist/Route53Provider-Di_SD9CF.mjs.map +1 -0
  32. package/dist/{Route53Provider-DVILBsvV.cjs → Route53Provider-emLuQHVw.cjs} +3 -3
  33. package/dist/Route53Provider-emLuQHVw.cjs.map +1 -0
  34. package/dist/S3StateStore-Cpbeijr5.mjs +223 -0
  35. package/dist/S3StateStore-Cpbeijr5.mjs.map +1 -0
  36. package/dist/S3StateStore-zU5kClhd.cjs +222 -0
  37. package/dist/S3StateStore-zU5kClhd.cjs.map +1 -0
  38. package/dist/SSMStateStore-BxkKMBi_.mjs +205 -0
  39. package/dist/SSMStateStore-BxkKMBi_.mjs.map +1 -0
  40. package/dist/SSMStateStore-D9uviQ3T.cjs +204 -0
  41. package/dist/SSMStateStore-D9uviQ3T.cjs.map +1 -0
  42. package/dist/SubscriberGenerator-BybB6uez.mjs +783 -0
  43. package/dist/SubscriberGenerator-BybB6uez.mjs.map +1 -0
  44. package/dist/SubscriberGenerator-mZpSuSU7.cjs +848 -0
  45. package/dist/SubscriberGenerator-mZpSuSU7.cjs.map +1 -0
  46. package/dist/add-Bb2IL3Yq.cjs +713 -0
  47. package/dist/add-Bb2IL3Yq.cjs.map +1 -0
  48. package/dist/add-Dj-gtqTO.mjs +711 -0
  49. package/dist/add-Dj-gtqTO.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/apps-0vc4Oz9_.cjs +6247 -0
  55. package/dist/apps-0vc4Oz9_.cjs.map +1 -0
  56. package/dist/apps-FRNlECwi.mjs +5621 -0
  57. package/dist/apps-FRNlECwi.mjs.map +1 -0
  58. package/dist/aws-8QQ8n-t6.mjs +89 -0
  59. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  60. package/dist/aws-DY9NqQIT.cjs +100 -0
  61. package/dist/aws-DY9NqQIT.cjs.map +1 -0
  62. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  63. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  64. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  65. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  66. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  67. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  68. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  69. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  70. package/dist/backups/runner.cjs +519 -0
  71. package/dist/backups/runner.cjs.map +1 -0
  72. package/dist/backups/runner.d.cts +102 -0
  73. package/dist/backups/runner.d.cts.map +1 -0
  74. package/dist/backups/runner.d.mts +102 -0
  75. package/dist/backups/runner.d.mts.map +1 -0
  76. package/dist/backups/runner.mjs +506 -0
  77. package/dist/backups/runner.mjs.map +1 -0
  78. package/dist/{bundler-BodTL4kf.mjs → bundler-9EM4ZHcu.mjs} +59 -14
  79. package/dist/bundler-9EM4ZHcu.mjs.map +1 -0
  80. package/dist/{bundler-BeNDZdHQ.cjs → bundler-Bg2eEFEh.cjs} +59 -14
  81. package/dist/bundler-Bg2eEFEh.cjs.map +1 -0
  82. package/dist/cli-CmoSOzNq.mjs +80 -0
  83. package/dist/cli-CmoSOzNq.mjs.map +1 -0
  84. package/dist/cli-YtLjcAZT.cjs +80 -0
  85. package/dist/cli-YtLjcAZT.cjs.map +1 -0
  86. package/dist/compose-3AtZF7ul.mjs +1560 -0
  87. package/dist/compose-3AtZF7ul.mjs.map +1 -0
  88. package/dist/compose-CW1DGfYc.cjs +1919 -0
  89. package/dist/compose-CW1DGfYc.cjs.map +1 -0
  90. package/dist/compose-CnXZAYNM.mjs +3068 -0
  91. package/dist/compose-CnXZAYNM.mjs.map +1 -0
  92. package/dist/compose-D7gOSspy.cjs +3157 -0
  93. package/dist/compose-D7gOSspy.cjs.map +1 -0
  94. package/dist/config-B5Hi3mLK.cjs +821 -0
  95. package/dist/config-B5Hi3mLK.cjs.map +1 -0
  96. package/dist/config-BNmLn0dw.d.mts +291 -0
  97. package/dist/config-BNmLn0dw.d.mts.map +1 -0
  98. package/dist/config-CkuiD9Jv.d.cts +291 -0
  99. package/dist/config-CkuiD9Jv.d.cts.map +1 -0
  100. package/dist/config-DWTUVGRE.mjs +696 -0
  101. package/dist/config-DWTUVGRE.mjs.map +1 -0
  102. package/dist/config.cjs +13 -3
  103. package/dist/config.d.cts +4 -117
  104. package/dist/config.d.mts +4 -117
  105. package/dist/config.mjs +3 -3
  106. package/dist/credentialSchemas-BAklWDna.cjs +271 -0
  107. package/dist/credentialSchemas-BAklWDna.cjs.map +1 -0
  108. package/dist/credentialSchemas-mz9QZTYh.mjs +236 -0
  109. package/dist/credentialSchemas-mz9QZTYh.mjs.map +1 -0
  110. package/dist/credentials-CjFtNBVH.mjs +1834 -0
  111. package/dist/credentials-CjFtNBVH.mjs.map +1 -0
  112. package/dist/credentials-DwIRfeBL.cjs +2289 -0
  113. package/dist/credentials-DwIRfeBL.cjs.map +1 -0
  114. package/dist/databases-C1qqNxTu.mjs +588 -0
  115. package/dist/databases-C1qqNxTu.mjs.map +1 -0
  116. package/dist/databases-CrKh5jw6.cjs +703 -0
  117. package/dist/databases-CrKh5jw6.cjs.map +1 -0
  118. package/dist/define-6poNqm5O.mjs +106 -0
  119. package/dist/define-6poNqm5O.mjs.map +1 -0
  120. package/dist/define-crmMcXFS.cjs +153 -0
  121. package/dist/define-crmMcXFS.cjs.map +1 -0
  122. package/dist/deploy/public.cjs +211 -0
  123. package/dist/deploy/public.cjs.map +1 -0
  124. package/dist/deploy/public.d.cts +658 -0
  125. package/dist/deploy/public.d.cts.map +1 -0
  126. package/dist/deploy/public.d.mts +658 -0
  127. package/dist/deploy/public.d.mts.map +1 -0
  128. package/dist/deploy/public.mjs +144 -0
  129. package/dist/deploy/public.mjs.map +1 -0
  130. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  131. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  132. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  133. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  134. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  135. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  136. package/dist/deploy/sniffer-hooks.cjs +1 -1
  137. package/dist/deploy/sniffer-hooks.mjs +1 -1
  138. package/dist/deploy/sniffer-loader.cjs +2 -2
  139. package/dist/deploy/sniffer-loader.mjs +1 -1
  140. package/dist/deploy/sniffer-routes-worker.cjs +2 -2
  141. package/dist/deploy/sniffer-routes-worker.mjs +1 -1
  142. package/dist/deploy-3bsiWJxj.cjs +3925 -0
  143. package/dist/deploy-3bsiWJxj.cjs.map +1 -0
  144. package/dist/deploy-BI3fHnyb.mjs +3869 -0
  145. package/dist/deploy-BI3fHnyb.mjs.map +1 -0
  146. package/dist/discover-CRywE7yc.cjs +1085 -0
  147. package/dist/discover-CRywE7yc.cjs.map +1 -0
  148. package/dist/discover-DbDrCQ8h.mjs +940 -0
  149. package/dist/discover-DbDrCQ8h.mjs.map +1 -0
  150. package/dist/docker-CwayjAF2.cjs +1515 -0
  151. package/dist/docker-CwayjAF2.cjs.map +1 -0
  152. package/dist/docker-DPdn7tYJ.mjs +1408 -0
  153. package/dist/docker-DPdn7tYJ.mjs.map +1 -0
  154. package/dist/dokploy-BMBL-_Xu.cjs +38 -0
  155. package/dist/dokploy-BMBL-_Xu.cjs.map +1 -0
  156. package/dist/dokploy-tmnH0Du_.mjs +38 -0
  157. package/dist/dokploy-tmnH0Du_.mjs.map +1 -0
  158. package/dist/drivers-BhdC9Efj.cjs +248 -0
  159. package/dist/drivers-BhdC9Efj.cjs.map +1 -0
  160. package/dist/drivers-wcDnzf7l.mjs +213 -0
  161. package/dist/drivers-wcDnzf7l.mjs.map +1 -0
  162. package/dist/eas-BVGQAUDc.mjs +334 -0
  163. package/dist/eas-BVGQAUDc.mjs.map +1 -0
  164. package/dist/eas-meN1xady.cjs +337 -0
  165. package/dist/eas-meN1xady.cjs.map +1 -0
  166. package/dist/emit-C4KSXOeS.mjs +153 -0
  167. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  168. package/dist/emit-DiW0kbue.cjs +164 -0
  169. package/dist/emit-DiW0kbue.cjs.map +1 -0
  170. package/dist/encryption-C8AMbomA.mjs +89 -0
  171. package/dist/encryption-C8AMbomA.mjs.map +1 -0
  172. package/dist/encryption-DvFVZdGz.cjs +90 -0
  173. package/dist/encryption-DvFVZdGz.cjs.map +1 -0
  174. package/dist/engine-BbWj0w3F.mjs +3217 -0
  175. package/dist/engine-BbWj0w3F.mjs.map +1 -0
  176. package/dist/engine-BmiIUVWa.cjs +3330 -0
  177. package/dist/engine-BmiIUVWa.cjs.map +1 -0
  178. package/dist/errors-D8Gwp5kU.mjs +23 -0
  179. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  180. package/dist/errors-DMC4Umsb.cjs +34 -0
  181. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  182. package/dist/github-BWqQr8q6.cjs +901 -0
  183. package/dist/github-BWqQr8q6.cjs.map +1 -0
  184. package/dist/github-Dc1daUbH.mjs +900 -0
  185. package/dist/github-Dc1daUbH.mjs.map +1 -0
  186. package/dist/googlePlay-ByaFUly7.mjs +931 -0
  187. package/dist/googlePlay-ByaFUly7.mjs.map +1 -0
  188. package/dist/googlePlay-CdVCdfU8.cjs +931 -0
  189. package/dist/googlePlay-CdVCdfU8.cjs.map +1 -0
  190. package/dist/{index-C-VLwB_Y.d.mts → index-B35vTdAW.d.cts} +38 -14
  191. package/dist/index-B35vTdAW.d.cts.map +1 -0
  192. package/dist/{index-C-HkOEBt.d.cts → index-Dv1Zj86i.d.mts} +38 -14
  193. package/dist/index-Dv1Zj86i.d.mts.map +1 -0
  194. package/dist/index.cjs +13730 -12325
  195. package/dist/index.cjs.map +1 -1
  196. package/dist/index.mjs +13771 -12364
  197. package/dist/index.mjs.map +1 -1
  198. package/dist/local-CnVFHJjS.mjs +224 -0
  199. package/dist/local-CnVFHJjS.mjs.map +1 -0
  200. package/dist/local-qevrV6dZ.cjs +241 -0
  201. package/dist/local-qevrV6dZ.cjs.map +1 -0
  202. package/dist/migrate-BEuCcCwN.mjs +267 -0
  203. package/dist/migrate-BEuCcCwN.mjs.map +1 -0
  204. package/dist/migrate-CRRps1i6.cjs +272 -0
  205. package/dist/migrate-CRRps1i6.cjs.map +1 -0
  206. package/dist/migrate-CU8_ZWP1.cjs +181 -0
  207. package/dist/migrate-CU8_ZWP1.cjs.map +1 -0
  208. package/dist/migrate-DgfKZB41.mjs +181 -0
  209. package/dist/migrate-DgfKZB41.mjs.map +1 -0
  210. package/dist/notes-BrBnyZz5.cjs +500 -0
  211. package/dist/notes-BrBnyZz5.cjs.map +1 -0
  212. package/dist/notes-CIzrdBKE.mjs +399 -0
  213. package/dist/notes-CIzrdBKE.mjs.map +1 -0
  214. package/dist/openapi.cjs +213 -7
  215. package/dist/openapi.cjs.map +1 -0
  216. package/dist/openapi.d.cts +32 -8
  217. package/dist/openapi.d.cts.map +1 -1
  218. package/dist/openapi.d.mts +32 -8
  219. package/dist/openapi.d.mts.map +1 -1
  220. package/dist/openapi.mjs +208 -2
  221. package/dist/openapi.mjs.map +1 -0
  222. package/dist/projectBucket-CDJd3prK.mjs +222 -0
  223. package/dist/projectBucket-CDJd3prK.mjs.map +1 -0
  224. package/dist/projectBucket-CKr_zObJ.cjs +263 -0
  225. package/dist/projectBucket-CKr_zObJ.cjs.map +1 -0
  226. package/dist/provider-BqpjG9QM.cjs +57 -0
  227. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  228. package/dist/provider-CEOKk8NS.mjs +46 -0
  229. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  230. package/dist/publish-Bq96_QnK.mjs +123 -0
  231. package/dist/publish-Bq96_QnK.mjs.map +1 -0
  232. package/dist/publish-DMKXh1Tb.cjs +124 -0
  233. package/dist/publish-DMKXh1Tb.cjs.map +1 -0
  234. package/dist/ready-BjFMu_1J.mjs +375 -0
  235. package/dist/ready-BjFMu_1J.mjs.map +1 -0
  236. package/dist/ready-eVMJIcWn.cjs +404 -0
  237. package/dist/ready-eVMJIcWn.cjs.map +1 -0
  238. package/dist/reconcile/public.cjs +3 -5
  239. package/dist/reconcile/public.d.cts +33 -89
  240. package/dist/reconcile/public.d.cts.map +1 -1
  241. package/dist/reconcile/public.d.mts +33 -89
  242. package/dist/reconcile/public.d.mts.map +1 -1
  243. package/dist/reconcile/public.mjs +3 -3
  244. package/dist/{reconcile-DhQ00DpU.mjs → reconcile--I7V4Klj.mjs} +2 -2
  245. package/dist/{reconcile-DhQ00DpU.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  246. package/dist/{reconcile-Dd2iyILf.cjs → reconcile-CuCQBa5-.cjs} +3 -3
  247. package/dist/{reconcile-Dd2iyILf.cjs.map → reconcile-CuCQBa5-.cjs.map} +1 -1
  248. package/dist/resolve-CSsE7frp.mjs +263 -0
  249. package/dist/resolve-CSsE7frp.mjs.map +1 -0
  250. package/dist/resolve-DF9GrosZ.cjs +316 -0
  251. package/dist/resolve-DF9GrosZ.cjs.map +1 -0
  252. package/dist/rollback-BBFGGmMa.cjs +165 -0
  253. package/dist/rollback-BBFGGmMa.cjs.map +1 -0
  254. package/dist/rollback-CZthwqus.mjs +136 -0
  255. package/dist/rollback-CZthwqus.mjs.map +1 -0
  256. package/dist/runtime-CFvcLEJW.d.cts +82 -0
  257. package/dist/runtime-CFvcLEJW.d.cts.map +1 -0
  258. package/dist/runtime-dwsH6ddo.d.mts +82 -0
  259. package/dist/runtime-dwsH6ddo.d.mts.map +1 -0
  260. package/dist/s3-BBRkezf7.mjs +215 -0
  261. package/dist/s3-BBRkezf7.mjs.map +1 -0
  262. package/dist/s3-CI2QYgXH.cjs +215 -0
  263. package/dist/s3-CI2QYgXH.cjs.map +1 -0
  264. package/dist/sandbox/config-worker.cjs +43 -0
  265. package/dist/sandbox/config-worker.cjs.map +1 -0
  266. package/dist/sandbox/config-worker.d.cts +1 -0
  267. package/dist/sandbox/config-worker.d.mts +1 -0
  268. package/dist/sandbox/config-worker.mjs +44 -0
  269. package/dist/sandbox/config-worker.mjs.map +1 -0
  270. package/dist/sandbox/credentials-worker.cjs +53 -0
  271. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  272. package/dist/sandbox/credentials-worker.d.cts +1 -0
  273. package/dist/sandbox/credentials-worker.d.mts +1 -0
  274. package/dist/sandbox/credentials-worker.mjs +54 -0
  275. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  276. package/dist/sandbox/discover-worker.cjs +47 -0
  277. package/dist/sandbox/discover-worker.cjs.map +1 -0
  278. package/dist/sandbox/discover-worker.d.cts +1 -0
  279. package/dist/sandbox/discover-worker.d.mts +1 -0
  280. package/dist/sandbox/discover-worker.mjs +48 -0
  281. package/dist/sandbox/discover-worker.mjs.map +1 -0
  282. package/dist/sandbox/migrate-worker.cjs +75 -0
  283. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  284. package/dist/sandbox/migrate-worker.d.cts +1 -0
  285. package/dist/sandbox/migrate-worker.d.mts +1 -0
  286. package/dist/sandbox/migrate-worker.mjs +76 -0
  287. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  288. package/dist/{workspace-mFpI_ky_.cjs → schemas-BCwKKA42.mjs} +399 -1162
  289. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  290. package/dist/{workspace-CgwmXEtc.mjs → schemas-BQ_v0lEX.cjs} +487 -971
  291. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  292. package/dist/secretsManager-CQORubp9.mjs +97 -0
  293. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  294. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  295. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  296. package/dist/seeds-B3xvUAQf.cjs +363 -0
  297. package/dist/seeds-B3xvUAQf.cjs.map +1 -0
  298. package/dist/seeds-BCC8vAXR.mjs +298 -0
  299. package/dist/seeds-BCC8vAXR.mjs.map +1 -0
  300. package/dist/serverSetup-C4iAABtI.mjs +685 -0
  301. package/dist/serverSetup-C4iAABtI.mjs.map +1 -0
  302. package/dist/serverSetup-Dt2DTlwa.cjs +685 -0
  303. package/dist/serverSetup-Dt2DTlwa.cjs.map +1 -0
  304. package/dist/sniffer-C2Ot1IbK.mjs +1824 -0
  305. package/dist/sniffer-C2Ot1IbK.mjs.map +1 -0
  306. package/dist/sniffer-bTrGuu9z.cjs +1997 -0
  307. package/dist/sniffer-bTrGuu9z.cjs.map +1 -0
  308. package/dist/snsSubscriptions-CFKb7fv0.cjs +1173 -0
  309. package/dist/snsSubscriptions-CFKb7fv0.cjs.map +1 -0
  310. package/dist/snsSubscriptions-QDDDn9Qi.mjs +1048 -0
  311. package/dist/snsSubscriptions-QDDDn9Qi.mjs.map +1 -0
  312. package/dist/sst-DDRWlXdv.mjs +478 -0
  313. package/dist/sst-DDRWlXdv.mjs.map +1 -0
  314. package/dist/sst-iRdMlGKd.cjs +501 -0
  315. package/dist/sst-iRdMlGKd.cjs.map +1 -0
  316. package/dist/stack-B9iDYMrq.cjs +2431 -0
  317. package/dist/stack-B9iDYMrq.cjs.map +1 -0
  318. package/dist/stack-CIOY44aC.mjs +2256 -0
  319. package/dist/stack-CIOY44aC.mjs.map +1 -0
  320. package/dist/stage-DA74aD_V.mjs +302 -0
  321. package/dist/stage-DA74aD_V.mjs.map +1 -0
  322. package/dist/stage-ycFS9mVn.cjs +313 -0
  323. package/dist/stage-ycFS9mVn.cjs.map +1 -0
  324. package/dist/stages-B0yOikgt.cjs +190 -0
  325. package/dist/stages-B0yOikgt.cjs.map +1 -0
  326. package/dist/stages-yA9bhStl.mjs +190 -0
  327. package/dist/stages-yA9bhStl.mjs.map +1 -0
  328. package/dist/target/public.cjs +15 -0
  329. package/dist/target/public.d.cts +28 -0
  330. package/dist/target/public.d.cts.map +1 -0
  331. package/dist/target/public.d.mts +28 -0
  332. package/dist/target/public.d.mts.map +1 -0
  333. package/dist/target/public.mjs +4 -0
  334. package/dist/terminal-DX22WLvT.mjs +85 -0
  335. package/dist/terminal-DX22WLvT.mjs.map +1 -0
  336. package/dist/terminal-RxfbNUwl.cjs +85 -0
  337. package/dist/terminal-RxfbNUwl.cjs.map +1 -0
  338. package/dist/types-Bl_CwZC9.cjs +90 -0
  339. package/dist/types-Bl_CwZC9.cjs.map +1 -0
  340. package/dist/{types-kvBQjpPo.d.mts → types-Dk--xVOT.d.cts} +2159 -364
  341. package/dist/types-Dk--xVOT.d.cts.map +1 -0
  342. package/dist/{types-RhXmHR-e.d.cts → types-DwQYpd_0.d.mts} +2157 -364
  343. package/dist/types-DwQYpd_0.d.mts.map +1 -0
  344. package/dist/types-Y1NfWlyG.mjs +61 -0
  345. package/dist/types-Y1NfWlyG.mjs.map +1 -0
  346. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  347. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  348. package/dist/utils-D_fxUqvU.mjs +156 -0
  349. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  350. package/dist/vitest.cjs +65 -0
  351. package/dist/vitest.cjs.map +1 -0
  352. package/dist/vitest.d.cts +29 -0
  353. package/dist/vitest.d.cts.map +1 -0
  354. package/dist/vitest.d.mts +29 -0
  355. package/dist/vitest.d.mts.map +1 -0
  356. package/dist/vitest.mjs +65 -0
  357. package/dist/vitest.mjs.map +1 -0
  358. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  359. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  360. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  361. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  362. package/dist/workspace/index.cjs +6 -2
  363. package/dist/workspace/index.d.cts +3 -3
  364. package/dist/workspace/index.d.mts +3 -3
  365. package/dist/workspace/index.mjs +2 -2
  366. package/dist/workspace-1szcahj9.cjs +2916 -0
  367. package/dist/workspace-1szcahj9.cjs.map +1 -0
  368. package/dist/workspace-DFGsrjGD.mjs +2480 -0
  369. package/dist/workspace-DFGsrjGD.mjs.map +1 -0
  370. package/package.json +65 -13
  371. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  372. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  373. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  374. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  375. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  376. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  377. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  378. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  379. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  380. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  381. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  382. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  383. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  384. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  385. package/dist/bundler-BeNDZdHQ.cjs.map +0 -1
  386. package/dist/bundler-BodTL4kf.mjs.map +0 -1
  387. package/dist/config-Q1rvKHvw.cjs +0 -467
  388. package/dist/config-Q1rvKHvw.cjs.map +0 -1
  389. package/dist/config-pqGD3hF9.mjs +0 -414
  390. package/dist/config-pqGD3hF9.mjs.map +0 -1
  391. package/dist/config.d.cts.map +0 -1
  392. package/dist/config.d.mts.map +0 -1
  393. package/dist/credentials-BekkKtY_.mjs +0 -2780
  394. package/dist/credentials-BekkKtY_.mjs.map +0 -1
  395. package/dist/credentials-Q6F0uqJq.cjs +0 -2917
  396. package/dist/credentials-Q6F0uqJq.cjs.map +0 -1
  397. package/dist/discover-BERGFg8v.cjs +0 -288
  398. package/dist/discover-BERGFg8v.cjs.map +0 -1
  399. package/dist/discover-CK-n3w6b.mjs +0 -244
  400. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  401. package/dist/emit-BdoPFjZf.cjs +0 -253
  402. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  403. package/dist/emit-Bzq7JsMP.mjs +0 -224
  404. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  405. package/dist/fullstack-secrets-BET8gqwK.mjs +0 -81
  406. package/dist/fullstack-secrets-BET8gqwK.mjs.map +0 -1
  407. package/dist/fullstack-secrets-DXsWO-5m.cjs +0 -92
  408. package/dist/fullstack-secrets-DXsWO-5m.cjs.map +0 -1
  409. package/dist/generator-LfZU7NlU.mjs +0 -247
  410. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  411. package/dist/generator-Wdfp0jCS.cjs +0 -282
  412. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  413. package/dist/github-BfflNPVe.cjs +0 -203
  414. package/dist/github-BfflNPVe.cjs.map +0 -1
  415. package/dist/github-CRwnxKmD.mjs +0 -203
  416. package/dist/github-CRwnxKmD.mjs.map +0 -1
  417. package/dist/index-C-HkOEBt.d.cts.map +0 -1
  418. package/dist/index-C-VLwB_Y.d.mts.map +0 -1
  419. package/dist/keystore-B4PRlbgE.mjs +0 -81
  420. package/dist/keystore-B4PRlbgE.mjs.map +0 -1
  421. package/dist/keystore-DgGRj2Yy.cjs +0 -98
  422. package/dist/keystore-DgGRj2Yy.cjs.map +0 -1
  423. package/dist/openapi-Dcbme-Us.cjs +0 -2038
  424. package/dist/openapi-Dcbme-Us.cjs.map +0 -1
  425. package/dist/openapi-vy4JzhUv.mjs +0 -1991
  426. package/dist/openapi-vy4JzhUv.mjs.map +0 -1
  427. package/dist/storage-C-30BD1e.cjs +0 -272
  428. package/dist/storage-C-30BD1e.cjs.map +0 -1
  429. package/dist/storage-P_b3w7uj.mjs +0 -231
  430. package/dist/storage-P_b3w7uj.mjs.map +0 -1
  431. package/dist/sync-B3xxXtJT.mjs +0 -88
  432. package/dist/sync-B3xxXtJT.mjs.map +0 -1
  433. package/dist/sync-D7uTIIEi.cjs +0 -111
  434. package/dist/sync-D7uTIIEi.cjs.map +0 -1
  435. package/dist/types-RhXmHR-e.d.cts.map +0 -1
  436. package/dist/types-kvBQjpPo.d.mts.map +0 -1
  437. package/dist/workspace-CgwmXEtc.mjs.map +0 -1
  438. package/dist/workspace-mFpI_ky_.cjs.map +0 -1
@@ -0,0 +1,3869 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { M as initStageSecrets, X as deployIdentity, Y as applicationName, a as findRootDomain, bt as gkmHome, d as mxValue, h as createEmptyState, i as extractSubdomain, k as secretsStoreFor, m as createComposeState, o as normalizeDnsConfig, r as storedCredentials } from "./credentials-CjFtNBVH.mjs";
3
+ import { $ as BucketOwnedByAnotherProject, G as checkSesConfig, J as S3_PROVISIONING, K as InboxNotProvisioned, L as resolveStageTelemetry, N as assertDeployedStage, Q as BucketNameUnavailable, U as stageProvider, W as SES_PROVISIONING, X as AccessKeyLimit, Y as checkS3Config, Z as BucketKeySetElsewhere, at as RecordedBucketUnreachable, et as BucketProbeFailed, it as ProvisionedBucketUnreachable, nt as BucketRegionUnknown, ot as RotationInProgress, q as SesReceivingUnsupported, rt as IamUserNotOwned, st as S3RegionRequired, tt as BucketRegionMismatch, u as getAppBuildOrder, yt as isReservedStageKey } from "./workspace-DFGsrjGD.mjs";
4
+ import { A as originSecretKey, D as ORIGIN_VERIFY_HEADER, Et as mergeLifecycle, Gt as backupExpiries, Xt as deploysWithCompose, Yt as stageBackups, dt as BACKUPS_URL_KEY, f as constructGlobs, j as processorOriginHost, k as newOriginSecret, qt as backupsPrefix, t as appEnvKeys, ut as BACKUPS_SERVICE, zt as usesTelemetry } from "./apps-FRNlECwi.mjs";
5
+ import { o as builtinTarget } from "./define-6poNqm5O.mjs";
6
+ import { at as resolveHost, it as isMainFrontendApp, nt as NoDomainForStage } from "./compose-3AtZF7ul.mjs";
7
+ import { s as subscriberRoute } from "./SubscriberGenerator-BybB6uez.mjs";
8
+ import { _ as withLoadedConfig, l as findWorkspaceRoot, m as loadWorkspaceConfig, v as appKey, y as derivedApps } from "./config-DWTUVGRE.mjs";
9
+ import { _ as withSandbox, b as withOutput, i as discover } from "./discover-DbDrCQ8h.mjs";
10
+ import { a as parseTargetOptions, o as resolveTarget } from "./resolve-CSsE7frp.mjs";
11
+ import { a as PROVIDER_KINDS, c as DevServicesNeedServerTarget, f as devServicesUsed, g as stageServiceDeclarations, i as stageProviderNotes, l as ExternalServicesNotConfigured, m as reportDevServices, n as assertStageProvidersEnabled, p as externalServices } from "./notes-CIzrdBKE.mjs";
12
+ import { w as assertSitePasswords } from "./stack-CIOY44aC.mjs";
13
+ import { _ as stageDnsDomains, a as subscriptionKey, b as awsEndpoint, d as recordTtl, l as dnsCredentials, m as settleStackDns, o as subscriptionResource, x as awsProvisioningCredentials, y as awsClientConfig } from "./snsSubscriptions-QDDDn9Qi.mjs";
14
+ import { t as LocalSandbox } from "./local-CnVFHJjS.mjs";
15
+ import { E as eventError, S as createStateStore, v as assertStateOutlivesRun, y as assertStateRoom } from "./sniffer-C2Ot1IbK.mjs";
16
+ import { a as findProjectBucket, i as ensureProjectBucket, o as projectBucketName, r as callerAccountId, s as reconcileProjectBucketLifecycle } from "./projectBucket-CDJd3prK.mjs";
17
+ import { d as DeployJournal } from "./seeds-BCC8vAXR.mjs";
18
+ import { n as assertStageCredentials } from "./credentialSchemas-mz9QZTYh.mjs";
19
+ import { resolve } from "node:path";
20
+ import { randomInt } from "node:crypto";
21
+ import { INBOX_MESSAGES_PREFIX, bucketExpiry, dependentsOf, kebabCase, provideKey, providedKeyFor, receiptRecipients } from "@geekmidas/manifest";
22
+ import * as s3Url from "@geekmidas/storage/s3-url";
23
+ //#region src/target/secrets.ts
24
+ /**
25
+ * A stage's secrets as a target sees them: read and written through the
26
+ * stage's own store, and masked in everything the run prints once read.
27
+ */
28
+ /**
29
+ * Shorter values are left alone: what a progress line legitimately prints —
30
+ * a port, a stage, an app name — would otherwise come out as `***` wherever
31
+ * a secret happened to share it.
32
+ */
33
+ const SHORTEST_MASKED = 6;
34
+ /** The values a run must never print, and the rewrite that keeps it so. */
35
+ var Redactor = class {
36
+ values = /* @__PURE__ */ new Set();
37
+ add(value) {
38
+ if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
39
+ }
40
+ /** `text` with every masked value replaced by `***`, longest first. */
41
+ redact(text) {
42
+ if (this.values.size === 0) return text;
43
+ let out = text;
44
+ const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
45
+ for (const value of longestFirst) out = out.replaceAll(value, "***");
46
+ return out;
47
+ }
48
+ };
49
+ /** Every value in `secrets` that is a secret rather than a label. */
50
+ function secretValues(secrets) {
51
+ return [
52
+ secrets.seed,
53
+ ...Object.entries(secrets.custom ?? {}).filter(([key]) => !isReservedStageKey(key)).map(([, value]) => value),
54
+ ...Object.values(secrets.urls ?? {}),
55
+ ...Object.values(secrets.services ?? {}).map((service) => service?.password)
56
+ ].filter((value) => typeof value === "string");
57
+ }
58
+ /**
59
+ * The stage's secrets through the store `secrets.store` names for it. Opening
60
+ * one builds a client and makes no request, so a target that never reads them
61
+ * costs nothing.
62
+ */
63
+ async function deploySecrets(workspace, stage, redactor, options = {}) {
64
+ const store = await secretsStoreFor(workspace, stage, options);
65
+ const mask = (secrets) => {
66
+ for (const value of secretValues(secrets)) redactor.add(value);
67
+ };
68
+ return {
69
+ store: store.name,
70
+ async read() {
71
+ const secrets = await store.read(stage);
72
+ if (secrets) mask(secrets);
73
+ return secrets;
74
+ },
75
+ async write(secrets) {
76
+ mask(secrets);
77
+ await store.write(stage, secrets);
78
+ },
79
+ mask: (value) => redactor.add(value)
80
+ };
81
+ }
82
+ const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
83
+ /** A name that S3 would refuse — what the name builder never returns. */
84
+ var InvalidBucketName = class extends GkmError {
85
+ bucket;
86
+ reason;
87
+ constructor(bucket, reason) {
88
+ 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.`);
89
+ this.bucket = bucket;
90
+ this.reason = reason;
91
+ this.name = "InvalidBucketName";
92
+ }
93
+ };
94
+ /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
95
+ function part(value) {
96
+ return kebabCase(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
97
+ }
98
+ /**
99
+ * `parts` joined by `-`, shortened to `max` characters by trimming the longest
100
+ * part one character at a time — so a long construct id gives way before a
101
+ * short stage name does, and every part keeps its start.
102
+ */
103
+ function fitParts(parts, max) {
104
+ const kept = parts.map(part).filter(Boolean);
105
+ const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
106
+ while (length() > max) {
107
+ let longest = 0;
108
+ for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
109
+ if (kept[longest].length <= 1) break;
110
+ kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
111
+ }
112
+ return kept.join("-");
113
+ }
114
+ /** Why `name` is not a valid bucket name, or undefined when it is. */
115
+ function bucketNameProblem(name) {
116
+ if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
117
+ if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
118
+ if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
119
+ if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
120
+ if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
121
+ }
122
+ /**
123
+ * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
124
+ * dots, shortened to leave room for a clash's suffix.
125
+ *
126
+ * @throws {InvalidBucketName} when nothing usable is left
127
+ */
128
+ function bucketName(input) {
129
+ const name = fitParts([
130
+ input.scope,
131
+ input.stage,
132
+ input.id
133
+ ], 56);
134
+ const problem = bucketNameProblem(name);
135
+ if (problem) throw new InvalidBucketName(name, problem);
136
+ return name;
137
+ }
138
+ /** Six random `[a-z0-9]` characters. */
139
+ function randomSuffix(random = randomInt) {
140
+ let suffix = "";
141
+ for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
142
+ return suffix;
143
+ }
144
+ /** The good name with a clash's suffix. */
145
+ function suffixedBucketName(good, suffix) {
146
+ return `${good}-${suffix}`;
147
+ }
148
+ /**
149
+ * The IAM user a bucket is reached with on a stage:
150
+ * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
151
+ */
152
+ function iamUserName(input) {
153
+ return fitParts([
154
+ "gkm",
155
+ input.scope,
156
+ input.stage,
157
+ input.id
158
+ ], 64);
159
+ }
160
+ /** The path every user gkm creates is under, so it finds its own. */
161
+ const IAM_USER_PATH = "/gkm/";
162
+ /** The inline policy each user is given. */
163
+ const IAM_POLICY_NAME = "gkm-bucket";
164
+ //#endregion
165
+ //#region src/providers/s3/policy.ts
166
+ const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
167
+ /**
168
+ * What the app's key may do: objects in this bucket, and listing it — and
169
+ * nothing else in the account.
170
+ *
171
+ * Multipart uploads are in it because a presigned upload of a large file is
172
+ * one, and an abandoned one is cleaned up by the app. Reading old versions is
173
+ * added only when the bucket keeps them.
174
+ */
175
+ function userPolicy(bucket, options = {}) {
176
+ return {
177
+ Version: "2012-10-17",
178
+ Statement: [
179
+ {
180
+ Sid: "GkmObjects",
181
+ Effect: "Allow",
182
+ Action: [
183
+ "s3:GetObject",
184
+ "s3:PutObject",
185
+ "s3:DeleteObject",
186
+ "s3:AbortMultipartUpload",
187
+ "s3:ListMultipartUploadParts",
188
+ ...options.versioning ? ["s3:GetObjectVersion"] : []
189
+ ],
190
+ Resource: `${bucketArn(bucket)}/*`
191
+ },
192
+ {
193
+ Sid: "GkmBucket",
194
+ Effect: "Allow",
195
+ Action: [
196
+ "s3:ListBucket",
197
+ "s3:GetBucketLocation",
198
+ "s3:ListBucketMultipartUploads"
199
+ ],
200
+ Resource: bucketArn(bucket)
201
+ },
202
+ ...options.eventsTopicArn ? [{
203
+ Sid: "GkmEvents",
204
+ Effect: "Allow",
205
+ Action: "sns:ConfirmSubscription",
206
+ Resource: options.eventsTopicArn
207
+ }] : []
208
+ ]
209
+ };
210
+ }
211
+ /**
212
+ * One open pattern as the resource it is public on. A `**` is S3's `*`; a
213
+ * single `*` is too, which crosses `/` where the construct's own check does
214
+ * not — the construct is the stricter of the two (see `bucketPolicy` in
215
+ * reconcile, which the local MinIO is given the same way).
216
+ */
217
+ function openResource(bucket, pattern) {
218
+ const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
219
+ return `${bucketArn(bucket)}/${path}`;
220
+ }
221
+ /**
222
+ * The bucket's own policy: every request refused unless it came over TLS,
223
+ * and — only when a file server opens paths on it — `s3:GetObject` on
224
+ * exactly those prefixes: to anyone, or, when a CDN serves them, to
225
+ * CloudFront alone, for exactly the stage's distributions. Behind a CDN the
226
+ * bucket is never public: a key outside the open prefixes is refused to
227
+ * CloudFront too, so the edge answers it 403.
228
+ */
229
+ function bucketPolicy(bucket, open = [], options = {}) {
230
+ const statements = [{
231
+ Sid: "GkmDenyInsecureTransport",
232
+ Effect: "Deny",
233
+ Principal: "*",
234
+ Action: "s3:*",
235
+ Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
236
+ Condition: { Bool: { "aws:SecureTransport": "false" } }
237
+ }];
238
+ const resources = [...new Set(open.map((p) => openResource(bucket, p)))].sort();
239
+ if (open.length > 0 && options.cdn) statements.push({
240
+ Sid: "GkmCdnRead",
241
+ Effect: "Allow",
242
+ Principal: { Service: "cloudfront.amazonaws.com" },
243
+ Action: "s3:GetObject",
244
+ Resource: resources,
245
+ Condition: { StringEquals: { "AWS:SourceArn": [...new Set(options.cdn.distributionArns)].sort() } }
246
+ });
247
+ else if (open.length > 0) statements.push({
248
+ Sid: "GkmOpenPaths",
249
+ Effect: "Allow",
250
+ Principal: "*",
251
+ Action: "s3:GetObject",
252
+ Resource: resources
253
+ });
254
+ if (options.sesWrite) statements.push({
255
+ Sid: "GkmSesWritesMail",
256
+ Effect: "Allow",
257
+ Principal: { Service: "ses.amazonaws.com" },
258
+ Action: "s3:PutObject",
259
+ Resource: `${bucketArn(bucket)}/${options.sesWrite.prefix}*`,
260
+ Condition: { StringEquals: { "aws:SourceAccount": options.sesWrite.account } }
261
+ });
262
+ return {
263
+ Version: "2012-10-17",
264
+ Statement: statements
265
+ };
266
+ }
267
+ /**
268
+ * Block Public Access. All four flags on, unless the bucket has open paths:
269
+ * then a *policy* may make it public (`BlockPublicPolicy`,
270
+ * `RestrictPublicBuckets` off), and ACLs still may not.
271
+ */
272
+ function publicAccessBlock(open) {
273
+ return {
274
+ BlockPublicAcls: true,
275
+ IgnorePublicAcls: true,
276
+ BlockPublicPolicy: !open,
277
+ RestrictPublicBuckets: !open
278
+ };
279
+ }
280
+ function corsRule(origins) {
281
+ return {
282
+ AllowedMethods: [
283
+ "GET",
284
+ "HEAD",
285
+ "POST",
286
+ "PUT"
287
+ ],
288
+ AllowedOrigins: [...new Set(origins)].sort(),
289
+ AllowedHeaders: ["*"],
290
+ ExposeHeaders: ["ETag"],
291
+ MaxAgeSeconds: 3e3
292
+ };
293
+ }
294
+ /**
295
+ * A policy document in one canonical form — keys sorted, a lone string a
296
+ * one-element list, lists sorted — so one AWS reformatted reads as the same
297
+ * document rather than as drift.
298
+ */
299
+ function canonicalPolicy(value) {
300
+ return JSON.stringify(canonical(value));
301
+ }
302
+ function canonical(value, key) {
303
+ if (Array.isArray(value)) {
304
+ const items = value.map((v) => canonical(v));
305
+ return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
306
+ }
307
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
308
+ const v = value[k];
309
+ return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" || k === "AWS:SourceArn" ? Array.isArray(v) ? v : [v] : v, k)];
310
+ }));
311
+ return value;
312
+ }
313
+ //#endregion
314
+ //#region src/providers/iam.ts
315
+ /**
316
+ * An IAM user gkm creates for one thing on a stage, its inline policy, and
317
+ * the access key written into the stage's secrets as an `s3://` URL — what
318
+ * the `s3` provider gives each bucket, and the deploy gives a stage's
319
+ * backups.
320
+ *
321
+ * - **The user** is under `/gkm/`, tagged with the deploy identity, the stage
322
+ * and what it is for. One that exists without those tags is someone
323
+ * else's, and is refused rather than taken over.
324
+ * - **Its policy** is read on every run and put back when it drifted.
325
+ * - **Its key**: one, written into the stage's secrets the moment IAM shows
326
+ * its secret. `--rotate-keys` issues a successor and keeps the old one
327
+ * active until the stage has deployed with the new one; the next run after
328
+ * that — or `--retire-old-keys` — deletes it.
329
+ * - **A new key** takes IAM seconds to become usable: the state records when
330
+ * it was issued, and a check made with it waits that out
331
+ * ({@link whileKeyIsNew}).
332
+ */
333
+ /** The tags gkm finds its own buckets and users by. */
334
+ const TAG_PROJECT = "gkm:project";
335
+ const TAG_STAGE = "gkm:stage";
336
+ const TAG_CONSTRUCT = "gkm:construct";
337
+ /** The keys gkm tags a bucket and a user with. */
338
+ function identityTags(ctx, id) {
339
+ return [
340
+ {
341
+ Key: TAG_PROJECT,
342
+ Value: ctx.identity.key
343
+ },
344
+ {
345
+ Key: TAG_STAGE,
346
+ Value: ctx.stage
347
+ },
348
+ {
349
+ Key: TAG_CONSTRUCT,
350
+ Value: id
351
+ }
352
+ ];
353
+ }
354
+ /** A read whose "there is none" answer is one of `missing`. */
355
+ async function readOr$3(read, missing) {
356
+ try {
357
+ return await read();
358
+ } catch (error) {
359
+ const e = error;
360
+ if (missing.includes(e?.Code ?? e?.name ?? "")) return void 0;
361
+ throw error;
362
+ }
363
+ }
364
+ /** IAM returns a policy document URL-encoded; an emulator may not. */
365
+ function decodePolicy(document) {
366
+ try {
367
+ return decodeURIComponent(document);
368
+ } catch {
369
+ return document;
370
+ }
371
+ }
372
+ /**
373
+ * The user and its inline policy: found — and refused when it is not this
374
+ * stage's — or created, and the policy put back when it drifted.
375
+ *
376
+ * @throws {IamUserNotOwned}
377
+ */
378
+ async function ensureIamUser(ctx, clients, input) {
379
+ const { IAM, iam } = clients;
380
+ const { id, user, policy } = input;
381
+ const entry = {
382
+ key: `iam-user:${id}`,
383
+ type: "iam-user"
384
+ };
385
+ const found = await readOr$3(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
386
+ if (found?.User) {
387
+ const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
388
+ const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
389
+ 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);
390
+ await ctx.state.ready(entry, user);
391
+ } else await ctx.change({
392
+ construct: id,
393
+ resource: `IAM user ${user}`,
394
+ change: `create under ${IAM_USER_PATH}`
395
+ }, async () => {
396
+ await ctx.state.pending(entry);
397
+ await iam.send(new IAM.CreateUserCommand({
398
+ UserName: user,
399
+ Path: IAM_USER_PATH,
400
+ Tags: identityTags(ctx, id)
401
+ }));
402
+ await ctx.state.ready(entry, user);
403
+ });
404
+ const exists = Boolean(found?.User) || !ctx.dryRun;
405
+ const current = exists ? await readOr$3(() => iam.send(new IAM.GetUserPolicyCommand({
406
+ UserName: user,
407
+ PolicyName: input.policyName
408
+ })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
409
+ const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
410
+ if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
411
+ construct: id,
412
+ resource: `IAM user ${user}`,
413
+ change: `policy ${input.policyName}: ${input.describe}`
414
+ }, async () => {
415
+ await iam.send(new IAM.PutUserPolicyCommand({
416
+ UserName: user,
417
+ PolicyName: input.policyName,
418
+ PolicyDocument: JSON.stringify(policy)
419
+ }));
420
+ });
421
+ return {
422
+ user,
423
+ exists
424
+ };
425
+ }
426
+ /**
427
+ * The user's access key, in the stage's secrets as the bucket's URL.
428
+ *
429
+ * - First run: one key, written into the stage's secrets.
430
+ * - `--rotate-keys`: a second key, written in place of the first; the first
431
+ * stays active until the stage has deployed with the second, and the next
432
+ * run after that deploy — or `--retire-old-keys` — deletes it.
433
+ * - A key the secrets no longer hold (a store emptied by hand): replaced the
434
+ * same way, since its secret cannot be read back.
435
+ *
436
+ * @throws {BucketKeySetElsewhere} when the secret names another bucket
437
+ * @throws {RotationInProgress} on `--rotate-keys` with the last rotation's old key still active
438
+ * @throws {AccessKeyLimit} when the user has two keys gkm did not record
439
+ */
440
+ async function ensureAccessKey(ctx, clients, input) {
441
+ const { IAM, iam } = clients;
442
+ const { id, bucket, user, urlKey } = input;
443
+ const entryKey = `iam-access-key:${id}`;
444
+ const record = ctx.state.record(entryKey);
445
+ const given = ctx.secrets[urlKey];
446
+ let inUrl;
447
+ let parsed;
448
+ if (given !== void 0) {
449
+ try {
450
+ parsed = s3Url.parse(given);
451
+ } catch {
452
+ parsed = void 0;
453
+ }
454
+ if (parsed?.bucket !== bucket) throw new BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
455
+ inUrl = parsed.accessKeyId;
456
+ }
457
+ const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
458
+ let current = record?.status === "ready" ? record.id : void 0;
459
+ let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
460
+ const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
461
+ const entry = (data = {}) => ({
462
+ key: entryKey,
463
+ type: "iam-access-key",
464
+ data: {
465
+ user,
466
+ ...data
467
+ }
468
+ });
469
+ if (previous && current) {
470
+ const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
471
+ if (ctx.retireOldKeys || deployed) {
472
+ const old = previous;
473
+ const keep = current;
474
+ await ctx.change({
475
+ construct: id,
476
+ resource: `IAM user ${user}`,
477
+ change: `delete the rotated-out access key ${old}`
478
+ }, async () => {
479
+ if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
480
+ UserName: user,
481
+ AccessKeyId: old
482
+ }));
483
+ await ctx.state.ready(entry(), keep);
484
+ });
485
+ previous = void 0;
486
+ } 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)`);
487
+ }
488
+ if (!current && inUrl && listed.includes(inUrl)) {
489
+ await ctx.state.ready(entry(), inUrl);
490
+ current = inUrl;
491
+ }
492
+ if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) {
493
+ if (parsed && parsed.region !== clients.region) {
494
+ const address = parsed;
495
+ await ctx.change({
496
+ construct: id,
497
+ resource: urlKey,
498
+ change: `name ${clients.region}, the bucket's region (it said ${address.region ?? "none"})`
499
+ }, () => ctx.writeSecrets({ [urlKey]: s3Url.build({
500
+ ...address,
501
+ region: clients.region
502
+ }) }));
503
+ }
504
+ return;
505
+ }
506
+ if (ctx.rotateKeys && previous) throw new RotationInProgress(id, previous, ctx.stage);
507
+ const outgoing = current && listed.includes(current) ? current : void 0;
508
+ if (listed.length >= 2) throw new AccessKeyLimit(user, listed);
509
+ 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)";
510
+ await ctx.change({
511
+ construct: id,
512
+ resource: `IAM user ${user}`,
513
+ change: why
514
+ }, async () => {
515
+ await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
516
+ const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
517
+ await ctx.writeSecrets({ [urlKey]: s3Url.build({
518
+ bucket,
519
+ region: clients.region,
520
+ ...clients.endpoint ? {
521
+ endpoint: clients.endpoint,
522
+ forcePathStyle: true
523
+ } : {},
524
+ accessKeyId: key.AccessKeyId,
525
+ secretAccessKey: key.SecretAccessKey
526
+ }) });
527
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
528
+ await ctx.state.ready(entry(outgoing ? {
529
+ previous: outgoing,
530
+ rotatedAt: issuedAt,
531
+ issuedAt
532
+ } : { issuedAt }), key.AccessKeyId);
533
+ });
534
+ 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}`);
535
+ }
536
+ /** How long a key issued this recently counts as new to IAM. */
537
+ const NEW_KEY_WINDOW_MS = 6e5;
538
+ /** The waits between asks while a new key becomes usable: about a minute. */
539
+ let newKeyWaits = [
540
+ 2e3,
541
+ 4e3,
542
+ 8e3,
543
+ 15e3,
544
+ 15e3,
545
+ 15e3
546
+ ];
547
+ /**
548
+ * When the key in a URL was issued, if the stage's state says it was just
549
+ * now — the record of `id`'s key naming that very key.
550
+ */
551
+ function issuedJustNow(resources, id, accessKeyId) {
552
+ const record = resources?.[`iam-access-key:${id}`];
553
+ const issuedAt = record?.data?.issuedAt;
554
+ if (record?.id !== accessKeyId || typeof issuedAt !== "string") return;
555
+ const age = Date.now() - Date.parse(issuedAt);
556
+ return age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : void 0;
557
+ }
558
+ /**
559
+ * `ask` again, for about a minute, while it is `refused` and the key was
560
+ * issued just now — IAM refuses a key for seconds after making it. Returns
561
+ * the last answer and how long was waited.
562
+ */
563
+ async function whileKeyIsNew(first, options) {
564
+ let answer = first;
565
+ let waited = 0;
566
+ if (!options.issuedAt || !options.refused(answer)) return {
567
+ answer,
568
+ waited
569
+ };
570
+ options.onWait?.();
571
+ for (const wait of newKeyWaits) {
572
+ await new Promise((resolve) => setTimeout(resolve, wait));
573
+ waited += wait;
574
+ answer = await options.ask();
575
+ if (!options.refused(answer)) break;
576
+ }
577
+ return {
578
+ answer,
579
+ waited
580
+ };
581
+ }
582
+ //#endregion
583
+ //#region src/backups/provision.ts
584
+ /** What the backups user and its key are recorded and tagged as. */
585
+ const BACKUPS_ID = "backups";
586
+ /** The backups user's inline policy's name. */
587
+ const BACKUPS_POLICY_NAME = "gkm-backups";
588
+ /** Where a deploy's check puts its marker, under the backups prefix. */
589
+ const VERIFY_MARKER = ".gkm-verify";
590
+ /** The backups user's name: `gkm-<project>-<stage>-backups`. */
591
+ function backupsUserName(scope, stage) {
592
+ return iamUserName({
593
+ scope,
594
+ stage,
595
+ id: BACKUPS_ID
596
+ });
597
+ }
598
+ /**
599
+ * The backups key's policy: put objects under the stage's backups prefix.
600
+ * Uploading in parts is `s3:PutObject` too; aborting one is not, and the
601
+ * bucket's lifecycle does it instead.
602
+ */
603
+ function backupsPolicy(bucket, prefix) {
604
+ return {
605
+ Version: "2012-10-17",
606
+ Statement: [{
607
+ Sid: "GkmBackupsPut",
608
+ Effect: "Allow",
609
+ Action: ["s3:PutObject"],
610
+ Resource: `arn:aws:s3:::${bucket}/${prefix}/*`
611
+ }]
612
+ };
613
+ }
614
+ /** A stage that backs up, and no AWS credentials to create its key with. */
615
+ var BackupsCredentialsMissing = class extends GkmError {
616
+ stage;
617
+ constructor(stage) {
618
+ 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.`);
619
+ this.stage = stage;
620
+ this.name = "BackupsCredentialsMissing";
621
+ }
622
+ };
623
+ /** No region to create the project bucket in. */
624
+ var BackupsRegionRequired = class extends GkmError {
625
+ stage;
626
+ constructor(stage) {
627
+ 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.`);
628
+ this.stage = stage;
629
+ this.name = "BackupsRegionRequired";
630
+ }
631
+ };
632
+ /** A bucket construct whose IAM user would be the backups user. */
633
+ var BackupsUserNameTaken = class extends GkmError {
634
+ stage;
635
+ construct;
636
+ constructor(stage, construct) {
637
+ 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.`);
638
+ this.stage = stage;
639
+ this.construct = construct;
640
+ this.name = "BackupsUserNameTaken";
641
+ }
642
+ };
643
+ /** The backups key could not put its marker: backups would fail too. */
644
+ var BackupsKeyRefused = class extends GkmError {
645
+ stage;
646
+ bucket;
647
+ key;
648
+ said;
649
+ constructor(stage, bucket, key, said) {
650
+ 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.`);
651
+ this.stage = stage;
652
+ this.bucket = bucket;
653
+ this.key = key;
654
+ this.said = said;
655
+ this.name = "BackupsKeyRefused";
656
+ }
657
+ };
658
+ /**
659
+ * The region the project bucket is in: the state's, when it is kept in S3,
660
+ * the secrets store's when that is in AWS, the credential's, `AWS_REGION`.
661
+ */
662
+ function backupsRegion(workspace, stage, credential, env = process.env) {
663
+ const state = workspace.state;
664
+ const store = workspace.secrets?.store;
665
+ 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;
666
+ if (!region) throw new BackupsRegionRequired(stage);
667
+ return region;
668
+ }
669
+ /**
670
+ * The stage's backups bucket, lifecycle, user and key — or, for a stage set
671
+ * to `false`, a notice and nothing else. Returns what the stage's backups
672
+ * came to.
673
+ *
674
+ * @throws {BackupsCredentialsMissing} when there are no AWS credentials
675
+ */
676
+ async function ensureStageBackups(input) {
677
+ const { workspace, manifest, stage, ctx } = input;
678
+ const env = input.env ?? process.env;
679
+ const choice = stageBackups(workspace, manifest, stage);
680
+ if (choice.mode === "disabled") {
681
+ ctx.log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
682
+ return choice;
683
+ }
684
+ if (choice.mode !== "on") return choice;
685
+ if (stageProvider(workspace, "objects", stage).mode === "provider") {
686
+ const clash = Object.entries(manifest).find(([id, d]) => d.kind === "objects" && appKey(id) === "backups");
687
+ if (clash) throw new BackupsUserNameTaken(stage, clash[0]);
688
+ }
689
+ const credential = await awsProvisioningCredentials({
690
+ stage,
691
+ env,
692
+ ...input.profile ? { profile: input.profile } : {},
693
+ ...input.home ? { home: input.home } : {}
694
+ });
695
+ if (!credential) throw new BackupsCredentialsMissing(stage);
696
+ const region = backupsRegion(workspace, stage, credential, env);
697
+ const clients = await backupsClients(credential, region, env);
698
+ const bucket = projectBucketName(ctx.identity.scope, await callerAccountId(clients.sts));
699
+ const prefix = backupsPrefix(workspace, stage);
700
+ const expiries = backupExpiries(workspace, manifest);
701
+ ctx.log(`💾 backups: ${choice.backups.describe}, to s3://${bucket}/${prefix}/${ctx.dryRun ? " (dry run)" : ""}`);
702
+ if (await findProjectBucket(clients.s3, bucket) === "none") await ctx.change({
703
+ construct: BACKUPS_SERVICE,
704
+ resource: `bucket ${bucket}`,
705
+ change: `create in ${region}, expiring each stage's backups`
706
+ }, async () => {
707
+ await ensureProjectBucket(clients.s3, {
708
+ bucket,
709
+ region,
710
+ identity: ctx.identity,
711
+ expiries
712
+ });
713
+ });
714
+ else if (await reconcileProjectBucketLifecycle(clients.s3, bucket, expiries, { dryRun: true })) await ctx.change({
715
+ construct: BACKUPS_SERVICE,
716
+ resource: `bucket ${bucket}`,
717
+ change: `lifecycle: ${expiries.map((e) => `${e.prefix} after ${e.days} days`).join(", ")}`
718
+ }, async () => {
719
+ await reconcileProjectBucketLifecycle(clients.s3, bucket, expiries);
720
+ });
721
+ const user = await ensureIamUser(ctx, clients, {
722
+ id: BACKUPS_ID,
723
+ user: backupsUserName(ctx.identity.scope, stage),
724
+ policyName: BACKUPS_POLICY_NAME,
725
+ policy: backupsPolicy(bucket, prefix),
726
+ describe: `put objects under ${prefix}/ only`
727
+ });
728
+ await ensureAccessKey(ctx, clients, {
729
+ id: BACKUPS_ID,
730
+ bucket,
731
+ urlKey: BACKUPS_URL_KEY,
732
+ ...user
733
+ });
734
+ return choice;
735
+ }
736
+ /** The clients a backups run creates through. */
737
+ async function backupsClients(credential, region, env) {
738
+ const S3 = await import("@aws-sdk/client-s3");
739
+ const IAM = await import("@aws-sdk/client-iam");
740
+ const { STSClient } = await import("@aws-sdk/client-sts");
741
+ const config = await awsClientConfig(credential, region);
742
+ const endpoint = awsEndpoint(env, "S3");
743
+ return {
744
+ IAM,
745
+ iam: new IAM.IAMClient(config),
746
+ s3: new S3.S3Client({
747
+ ...config,
748
+ ...endpoint ? {
749
+ endpoint,
750
+ forcePathStyle: true
751
+ } : {}
752
+ }),
753
+ sts: new STSClient(config),
754
+ region,
755
+ ...endpoint ? { endpoint } : {}
756
+ };
757
+ }
758
+ /**
759
+ * The stage's backups key puts its marker under the prefix — the one thing
760
+ * it may do. A key issued by this deploy is waited for, as a bucket's is.
761
+ * Returns whether there was a key to check.
762
+ *
763
+ * @throws {BackupsKeyRefused}
764
+ */
765
+ async function verifyStageBackups(input) {
766
+ const { stage } = input;
767
+ if (stageBackups(input.workspace, input.manifest, stage).mode !== "on") return false;
768
+ const url = input.secrets[BACKUPS_URL_KEY];
769
+ if (!url) return false;
770
+ const address = (await import("@geekmidas/storage/s3-url")).parse(url);
771
+ if (!address.accessKeyId || !address.secretAccessKey) return false;
772
+ const S3 = await import("@aws-sdk/client-s3");
773
+ const client = new S3.S3Client({
774
+ region: address.region ?? "us-east-1",
775
+ credentials: {
776
+ accessKeyId: address.accessKeyId,
777
+ secretAccessKey: address.secretAccessKey
778
+ },
779
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
780
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
781
+ });
782
+ const Key = `${backupsPrefix(input.workspace, stage)}/${VERIFY_MARKER}`;
783
+ const put = async () => {
784
+ try {
785
+ await client.send(new S3.PutObjectCommand({
786
+ Bucket: address.bucket,
787
+ Key,
788
+ Body: (/* @__PURE__ */ new Date()).toISOString(),
789
+ ContentType: "text/plain"
790
+ }));
791
+ return {
792
+ ok: true,
793
+ said: ""
794
+ };
795
+ } catch (error) {
796
+ const e = error;
797
+ const status = e.$metadata?.httpStatusCode;
798
+ return {
799
+ ok: false,
800
+ ...status !== void 0 ? { status } : {},
801
+ said: `HTTP ${status ?? "no response"} ${e.name ?? "Error"}: ${e.message ?? ""}`
802
+ };
803
+ }
804
+ };
805
+ try {
806
+ const { answer } = await whileKeyIsNew(await put(), {
807
+ issuedAt: issuedJustNow(input.resources, BACKUPS_ID, address.accessKeyId),
808
+ refused: (answer) => !answer.ok && answer.status === 403,
809
+ ask: put,
810
+ onWait: () => input.log?.(` backups: waiting for the new key ${address.accessKeyId} to become active…`)
811
+ });
812
+ if (!answer.ok) throw new BackupsKeyRefused(stage, address.bucket, Key, answer.said);
813
+ return true;
814
+ } finally {
815
+ client.destroy();
816
+ }
817
+ }
818
+ //#endregion
819
+ //#region src/providers/dnsWriter.ts
820
+ /**
821
+ * The DNS records a provider asks for — a certificate's validation record, a
822
+ * CDN's name, a domain's MX — written through the stage's own DNS providers.
823
+ *
824
+ * The same machinery the deploy's DNS step uses for the stack's hosts
825
+ * (`settleStackDns`), handed a plan of CNAMEs and MX records instead of the
826
+ * server's addresses — an MX's value in its zone-file form,
827
+ * `<priority> <host>`, which every DNS provider reads and writes: a record holding its value is left alone, one with another value
828
+ * is replaced and printed, and what is written is read back. A host under no
829
+ * domain in `dns`, or under a `manual` one, is printed for the person to
830
+ * create and reported back, so the provider can say what it is waiting on.
831
+ */
832
+ async function writeProviderDns(records, options) {
833
+ const { log } = options;
834
+ const dns = options.workspace.dns ? normalizeDnsConfig(options.workspace.dns) : {};
835
+ const manual = [];
836
+ const domains = /* @__PURE__ */ new Map();
837
+ for (const record of records) {
838
+ const host = record.host.toLowerCase().replace(/\.$/, "");
839
+ const target = record.value.replace(/\.$/, "");
840
+ const value = record.type === "MX" ? mxValue(record.priority, target) : target;
841
+ const domain = findRootDomain(host, dns);
842
+ if (!domain) {
843
+ log(` create at its DNS host: ${host} ${record.type} ${value}`);
844
+ manual.push(host);
845
+ continue;
846
+ }
847
+ const config = dns[domain];
848
+ const plan = domains.get(domain) ?? {
849
+ domain,
850
+ provider: typeof config.provider === "string" ? config.provider : "custom",
851
+ config,
852
+ records: []
853
+ };
854
+ const planned = {
855
+ host,
856
+ domain,
857
+ name: extractSubdomain(host, domain),
858
+ type: record.type,
859
+ value,
860
+ ttl: recordTtl(config)
861
+ };
862
+ plan.records.push(planned);
863
+ domains.set(domain, plan);
864
+ }
865
+ if (domains.size === 0) return { manual };
866
+ const plans = [...domains.values()];
867
+ const tokens = await dnsCredentials(options.stage, plans.map(({ domain, config }) => ({
868
+ domain,
869
+ config
870
+ })), options.credentials);
871
+ const applied = await settleStackDns({
872
+ stage: options.stage,
873
+ server: { ipv4: "" },
874
+ domains: plans,
875
+ uncovered: []
876
+ }, {
877
+ ...options.dryRun ? { dryRun: true } : { confirm: true },
878
+ log,
879
+ credentials: {
880
+ ...tokens.godaddy ? { credential: tokens.godaddy } : {},
881
+ log
882
+ },
883
+ ...tokens.hostinger ? { hostinger: tokens.hostinger } : {},
884
+ ...options.providerFor ? { providerFor: options.providerFor } : {}
885
+ });
886
+ for (const change of applied.changes) {
887
+ if (change.action !== "manual") continue;
888
+ const host = plans.find((p) => p.domain === change.domain)?.records.find((r) => r.name === change.name)?.host;
889
+ if (host) manual.push(host);
890
+ }
891
+ return { manual: [...new Set(manual)].sort() };
892
+ }
893
+ //#endregion
894
+ //#region src/providers/s3/cdn.ts
895
+ /** AWS's managed `CachingOptimized` cache policy: path-keyed, gzip and brotli. */
896
+ const CACHING_OPTIMIZED = "658327ea-f89d-4fab-a63d-7e88639e58f6";
897
+ /** What an immutable path is served with. */
898
+ const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
899
+ /** The only region CloudFront reads a certificate from. */
900
+ const CDN_REGION = "us-east-1";
901
+ /** The distribution's bucket origin. */
902
+ const ORIGIN_ID = "bucket";
903
+ /** Its processors' origin: the stack's processor unit, at a host of its own. */
904
+ const PROCESSORS_ORIGIN_ID = "processors";
905
+ /**
906
+ * AWS's managed `CachingOptimizedForUncompressedObjects`: keyed on the path
907
+ * alone, and nothing re-compressed — a derivative is an image, already
908
+ * compressed, and its width is in the path, so nothing else may fragment it.
909
+ */
910
+ const CACHING_OPTIMIZED_UNCOMPRESSED = "b2884449-e4de-46a7-ac36-70bc7f1ddd6d";
911
+ /** A CDN is a name on the stage's domain, and the stage has none. */
912
+ var FileServerCdnNeedsDomain = class extends GkmError {
913
+ server;
914
+ stage;
915
+ constructor(server, stage) {
916
+ super(`'${server}' is served through a CDN on '${stage}', which answers on <fileserver>.<domain> — and '${stage}' has no domain. Set domains.${stage} in gkm.config.ts, or set deploy.objects.${stage}.cdn to false to serve it from the bucket's own endpoint.`);
917
+ this.server = server;
918
+ this.stage = stage;
919
+ this.name = "FileServerCdnNeedsDomain";
920
+ }
921
+ };
922
+ /**
923
+ * The certificate is waiting on its validation record: one the person has to
924
+ * create, or one that has not propagated yet. Everything up to it is
925
+ * recorded, so the next deploy carries on from here.
926
+ */
927
+ var CdnCertificatePending = class extends GkmError {
928
+ server;
929
+ host;
930
+ record;
931
+ reason;
932
+ constructor(server, host, record, reason) {
933
+ super((reason === "manual" ? `The certificate for ${host} ('${server}') is validated by a DNS record no DNS provider in gkm.config.ts can write. Create it at the domain's DNS host:
934
+ ` : `The certificate for ${host} ('${server}') is not issued yet: ACM has not seen its validation record. It is written; DNS can take a while to answer with it. Check it resolves:
935
+ `) + ` ${record.name} CNAME ${record.value}\nthen deploy again — the certificate and everything before it are recorded, and the deploy carries on from there.`);
936
+ this.server = server;
937
+ this.host = host;
938
+ this.record = record;
939
+ this.reason = reason;
940
+ this.name = "CdnCertificatePending";
941
+ }
942
+ };
943
+ /** ACM gave up on the certificate. */
944
+ var CdnCertificateFailed = class extends GkmError {
945
+ server;
946
+ host;
947
+ status;
948
+ reason;
949
+ constructor(server, host, status, reason) {
950
+ super(`ACM did not issue the certificate for ${host} ('${server}'): ${status}` + (reason ? ` (${reason})` : "") + ". A CAA record on the domain that does not allow amazon.com, or a validation record removed before it was checked, are the usual causes. Fix it and deploy again: a new certificate is requested.");
951
+ this.server = server;
952
+ this.host = host;
953
+ this.status = status;
954
+ this.reason = reason;
955
+ this.name = "CdnCertificateFailed";
956
+ }
957
+ };
958
+ /** Where a file server answers: `<fileserver>.<domain>`. */
959
+ function cdnHost(serverId, domain) {
960
+ return `${appKey(serverId)}.${domain}`.toLowerCase();
961
+ }
962
+ /**
963
+ * The name the stage's CDN resources go by, within CloudFront's limits:
964
+ * letters, digits, `-` and `_`, and at most 64 characters (an origin access
965
+ * control's). Kept whole where it fits; otherwise shortened with a hash of
966
+ * the whole, so two long names never meet.
967
+ */
968
+ function cdnName(scope, stage, serverId) {
969
+ const whole = `gkm-${scope}-${stage}-${appKey(serverId)}`.replace(/[^A-Za-z0-9_-]/g, "-");
970
+ if (whole.length <= 56) return whole;
971
+ return `${whole.slice(0, 47)}-${hash(whole)}`;
972
+ }
973
+ function hash(value) {
974
+ let h = 2166136261;
975
+ for (let i = 0; i < value.length; i++) {
976
+ h ^= value.charCodeAt(i);
977
+ h = Math.imul(h, 16777619);
978
+ }
979
+ return (h >>> 0).toString(36).padStart(8, "0").slice(0, 8);
980
+ }
981
+ /**
982
+ * An open or immutable glob as a CloudFront path pattern. CloudFront's `*`
983
+ * crosses `/`, so a single star is as wide as a double one — the bucket
984
+ * policy reads it the same way, and the construct's own check is the
985
+ * stricter of the three.
986
+ */
987
+ function pathPattern(glob) {
988
+ return glob.replace(/^\/+/, "").replace(/\*\*/g, "*");
989
+ }
990
+ /** A CloudFront list: its `Quantity` and, when it has some, its `Items`. */
991
+ function list(items) {
992
+ return items.length > 0 ? {
993
+ Quantity: items.length,
994
+ Items: [...items]
995
+ } : { Quantity: 0 };
996
+ }
997
+ /** One of the stage's response headers policies. */
998
+ function headersPolicyConfig(input) {
999
+ return {
1000
+ Name: input.name,
1001
+ Comment: input.comment,
1002
+ ...input.origins.length > 0 ? { CorsConfig: {
1003
+ AccessControlAllowOrigins: list([...input.origins].sort()),
1004
+ AccessControlAllowHeaders: {
1005
+ Quantity: 1,
1006
+ Items: ["*"]
1007
+ },
1008
+ AccessControlAllowMethods: {
1009
+ Quantity: 3,
1010
+ Items: [
1011
+ "GET",
1012
+ "HEAD",
1013
+ "OPTIONS"
1014
+ ]
1015
+ },
1016
+ AccessControlAllowCredentials: false,
1017
+ AccessControlMaxAgeSec: 86400,
1018
+ OriginOverride: false
1019
+ } } : {},
1020
+ ...input.immutable ? { CustomHeadersConfig: {
1021
+ Quantity: 1,
1022
+ Items: [{
1023
+ Header: "Cache-Control",
1024
+ Value: IMMUTABLE_CACHE_CONTROL,
1025
+ Override: true
1026
+ }]
1027
+ } } : {}
1028
+ };
1029
+ }
1030
+ /** The parts of a distribution's config this provider owns. */
1031
+ function distributionConfig(input) {
1032
+ const behaviour = (policy) => ({
1033
+ TargetOriginId: ORIGIN_ID,
1034
+ ViewerProtocolPolicy: "redirect-to-https",
1035
+ AllowedMethods: {
1036
+ Quantity: 3,
1037
+ Items: [
1038
+ "GET",
1039
+ "HEAD",
1040
+ "OPTIONS"
1041
+ ],
1042
+ CachedMethods: {
1043
+ Quantity: 2,
1044
+ Items: ["GET", "HEAD"]
1045
+ }
1046
+ },
1047
+ Compress: true,
1048
+ CachePolicyId: CACHING_OPTIMIZED,
1049
+ ...policy ? { ResponseHeadersPolicyId: policy } : {},
1050
+ ...BEHAVIOUR_DEFAULTS
1051
+ });
1052
+ const patterns = [...new Set(input.immutable.map(pathPattern))].sort();
1053
+ const processors = input.processors;
1054
+ const processorPatterns = processors ? [...new Set(processors.prefixes.map((p) => `${pathPattern(p)}*`))].sort() : [];
1055
+ return {
1056
+ CallerReference: input.callerReference,
1057
+ Comment: input.comment,
1058
+ Enabled: true,
1059
+ Aliases: {
1060
+ Quantity: 1,
1061
+ Items: [input.host]
1062
+ },
1063
+ Origins: list([{
1064
+ Id: ORIGIN_ID,
1065
+ DomainName: input.bucketDomain,
1066
+ OriginPath: "",
1067
+ S3OriginConfig: { OriginAccessIdentity: "" },
1068
+ OriginAccessControlId: input.originAccessControlId,
1069
+ CustomHeaders: { Quantity: 0 },
1070
+ ...ORIGIN_DEFAULTS
1071
+ }, ...processors ? [{
1072
+ Id: PROCESSORS_ORIGIN_ID,
1073
+ DomainName: processors.host,
1074
+ OriginPath: "",
1075
+ CustomOriginConfig: {
1076
+ HTTPPort: 80,
1077
+ HTTPSPort: 443,
1078
+ OriginProtocolPolicy: "https-only",
1079
+ OriginSslProtocols: {
1080
+ Quantity: 1,
1081
+ Items: ["TLSv1.2"]
1082
+ },
1083
+ OriginReadTimeout: 30,
1084
+ OriginKeepaliveTimeout: 5
1085
+ },
1086
+ ...ORIGIN_DEFAULTS,
1087
+ CustomHeaders: {
1088
+ Quantity: 1,
1089
+ Items: [{
1090
+ HeaderName: ORIGIN_VERIFY_HEADER,
1091
+ HeaderValue: processors.secret
1092
+ }]
1093
+ }
1094
+ }] : []]),
1095
+ DefaultCacheBehavior: behaviour(input.corsPolicyId),
1096
+ CacheBehaviors: list([...processorPatterns.map((PathPattern) => ({
1097
+ ...behaviour(input.corsPolicyId),
1098
+ TargetOriginId: PROCESSORS_ORIGIN_ID,
1099
+ Compress: false,
1100
+ CachePolicyId: CACHING_OPTIMIZED_UNCOMPRESSED,
1101
+ PathPattern
1102
+ })), ...patterns.map((PathPattern) => ({
1103
+ ...behaviour(input.immutablePolicyId),
1104
+ PathPattern
1105
+ }))]),
1106
+ ViewerCertificate: {
1107
+ ACMCertificateArn: input.certificateArn,
1108
+ SSLSupportMethod: "sni-only",
1109
+ MinimumProtocolVersion: "TLSv1.2_2021",
1110
+ CloudFrontDefaultCertificate: false
1111
+ },
1112
+ HttpVersion: "http2and3",
1113
+ IsIPV6Enabled: true,
1114
+ DefaultRootObject: ""
1115
+ };
1116
+ }
1117
+ /**
1118
+ * What CloudFront fills in a behaviour, at its own defaults. Optional when a
1119
+ * distribution is created, required when it is updated — an update replaces
1120
+ * each behaviour and origin whole, and one without them is refused ("The
1121
+ * parameter SmoothStreaming flag is missing", "The 'OriginCustomHeaders'
1122
+ * field is missing"). At the defaults, `holds` still matches a distribution
1123
+ * CloudFront filled in itself.
1124
+ */
1125
+ const BEHAVIOUR_DEFAULTS = {
1126
+ SmoothStreaming: false,
1127
+ FieldLevelEncryptionId: "",
1128
+ TrustedSigners: {
1129
+ Enabled: false,
1130
+ Quantity: 0
1131
+ },
1132
+ TrustedKeyGroups: {
1133
+ Enabled: false,
1134
+ Quantity: 0
1135
+ },
1136
+ LambdaFunctionAssociations: { Quantity: 0 },
1137
+ FunctionAssociations: { Quantity: 0 }
1138
+ };
1139
+ /** What CloudFront fills in an origin, at its own defaults: see above. */
1140
+ const ORIGIN_DEFAULTS = {
1141
+ ConnectionAttempts: 3,
1142
+ ConnectionTimeout: 10
1143
+ };
1144
+ /**
1145
+ * Whether `current` already holds everything in `wanted`: each key `wanted`
1146
+ * names, recursively, with lists compared as sets. What else `current` holds
1147
+ * — logging, a WAF, geo restrictions set by hand — is left alone, and a
1148
+ * `CallerReference`, fixed at creation, is never compared.
1149
+ */
1150
+ function holds(current, wanted, key) {
1151
+ if (key === "CallerReference") return true;
1152
+ if (Array.isArray(wanted)) return Array.isArray(current) && current.length === wanted.length && wanted.every((w) => current.some((c) => holds(c, w)));
1153
+ if (wanted && typeof wanted === "object") {
1154
+ if (!current || typeof current !== "object") return false;
1155
+ return Object.entries(wanted).every(([k, v]) => holds(current[k], v, k));
1156
+ }
1157
+ return current === wanted;
1158
+ }
1159
+ /** Header configs a policy may hold that this provider never sets. */
1160
+ const FOREIGN_HEADER_CONFIGS = [
1161
+ "CorsConfig",
1162
+ "CustomHeadersConfig",
1163
+ "SecurityHeadersConfig",
1164
+ "RemoveHeadersConfig",
1165
+ "ServerTimingHeadersConfig"
1166
+ ];
1167
+ /** Whether a policy is exactly what is wanted: nothing missing, nothing more. */
1168
+ function sameHeadersPolicy(current, wanted) {
1169
+ if (!current || !holds(current, wanted)) return false;
1170
+ return FOREIGN_HEADER_CONFIGS.every((k) => {
1171
+ if (k in wanted) return true;
1172
+ const extra = current[k];
1173
+ return !extra || extra.Quantity === 0;
1174
+ });
1175
+ }
1176
+ const defaultCdnClients = async (credential) => {
1177
+ const CF = await import("@aws-sdk/client-cloudfront");
1178
+ const ACM = await import("@aws-sdk/client-acm");
1179
+ const config = await awsClientConfig(credential, CDN_REGION);
1180
+ const cloudfront = awsEndpoint(process.env, "CLOUDFRONT");
1181
+ const acm = awsEndpoint(process.env, "ACM");
1182
+ return {
1183
+ CF,
1184
+ ACM,
1185
+ cloudfront: new CF.CloudFrontClient({
1186
+ ...config,
1187
+ ...cloudfront ? { endpoint: cloudfront } : {}
1188
+ }),
1189
+ acm: new ACM.ACMClient({
1190
+ ...config,
1191
+ ...acm ? { endpoint: acm } : {}
1192
+ }),
1193
+ wait: {
1194
+ timeoutMs: 9e5,
1195
+ intervalMs: 1e4
1196
+ }
1197
+ };
1198
+ };
1199
+ let makeCdnClients = defaultCdnClients;
1200
+ /** What an AWS SDK error is called, whichever field carries it. */
1201
+ function errorName$3(error) {
1202
+ const e = error;
1203
+ return e?.Code ?? e?.name ?? "";
1204
+ }
1205
+ async function readOr$2(read, missing) {
1206
+ try {
1207
+ return await read();
1208
+ } catch (error) {
1209
+ if (missing.includes(errorName$3(error))) return void 0;
1210
+ throw error;
1211
+ }
1212
+ }
1213
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1214
+ /** What stands in for an id a dry run would create. */
1215
+ const PLANNED = "(created by this deploy)";
1216
+ /** Each file server over a bucket, behind its own distribution. */
1217
+ async function ensureBucketCdn(ctx, input) {
1218
+ const domain = ctx.workspace.domains?.[ctx.stage];
1219
+ if (!domain) throw new FileServerCdnNeedsDomain(input.servers[0].id, ctx.stage);
1220
+ const clients = await makeCdnClients(ctx.credential);
1221
+ const out = {
1222
+ distributionArns: [],
1223
+ urls: {}
1224
+ };
1225
+ for (const server of input.servers) {
1226
+ const { arn, url } = await ensureServerCdn(ctx, clients, {
1227
+ ...input,
1228
+ server,
1229
+ host: cdnHost(server.id, domain),
1230
+ processorHost: processorOriginHost(server.id, domain)
1231
+ });
1232
+ out.distributionArns.push(arn);
1233
+ out.urls[server.id] = url;
1234
+ }
1235
+ return out;
1236
+ }
1237
+ async function ensureServerCdn(ctx, clients, input) {
1238
+ const { server, host } = input;
1239
+ const name = cdnName(ctx.identity.scope, ctx.stage, server.id);
1240
+ const comment = `gkm ${ctx.identity.key} ${ctx.stage} ${server.id}`.slice(0, 128);
1241
+ const certificateArn = await ensureCertificate(ctx, clients, {
1242
+ id: server.id,
1243
+ host,
1244
+ name
1245
+ });
1246
+ const originAccessControlId = await ensureOriginAccessControl(ctx, clients, {
1247
+ id: server.id,
1248
+ name,
1249
+ bucket: input.bucket
1250
+ });
1251
+ const corsPolicyId = input.origins.length > 0 ? await ensureHeadersPolicy(ctx, clients, {
1252
+ id: server.id,
1253
+ kind: "cors",
1254
+ config: headersPolicyConfig({
1255
+ name: `${name}-cors`,
1256
+ comment: `${comment}: CORS`,
1257
+ origins: input.origins,
1258
+ immutable: false
1259
+ })
1260
+ }) : void 0;
1261
+ const immutablePolicyId = server.immutable.length > 0 ? await ensureHeadersPolicy(ctx, clients, {
1262
+ id: server.id,
1263
+ kind: "immutable",
1264
+ config: headersPolicyConfig({
1265
+ name: `${name}-immutable`,
1266
+ comment: `${comment}: CORS and Cache-Control immutable`,
1267
+ origins: input.origins,
1268
+ immutable: true
1269
+ })
1270
+ }) : void 0;
1271
+ const processors = server.processors?.length ? {
1272
+ prefixes: server.processors,
1273
+ host: input.processorHost,
1274
+ secret: await ensureOriginSecret(ctx, server.id)
1275
+ } : void 0;
1276
+ const distribution = await ensureDistribution(ctx, clients, {
1277
+ id: server.id,
1278
+ comment,
1279
+ config: distributionConfig({
1280
+ comment,
1281
+ callerReference: name,
1282
+ host,
1283
+ certificateArn,
1284
+ bucketDomain: `${input.bucket}.s3.${input.region}.amazonaws.com`,
1285
+ originAccessControlId,
1286
+ ...corsPolicyId ? { corsPolicyId } : {},
1287
+ ...immutablePolicyId ? { immutablePolicyId } : {},
1288
+ immutable: server.immutable,
1289
+ ...processors ? { processors } : {}
1290
+ })
1291
+ });
1292
+ if (distribution.domainName !== PLANNED) {
1293
+ if ((await ctx.writeDns([{
1294
+ host,
1295
+ type: "CNAME",
1296
+ value: distribution.domainName
1297
+ }])).manual.includes(host)) ctx.log(` ${host} answers once that record exists — ${server.id}'s URL is https://${host}`);
1298
+ }
1299
+ return {
1300
+ arn: distribution.arn,
1301
+ url: `https://${host}`
1302
+ };
1303
+ }
1304
+ /**
1305
+ * The secret the CDN sends a file server's processors: the one in the stage's
1306
+ * secrets, or a new one written there — read by the stack, whose edge checks
1307
+ * it, when it composes.
1308
+ */
1309
+ async function ensureOriginSecret(ctx, serverId) {
1310
+ const key = originSecretKey(serverId);
1311
+ const kept = ctx.secrets[key];
1312
+ if (kept) return kept;
1313
+ const secret = newOriginSecret();
1314
+ ctx.log(` ${serverId}: a new processor origin secret, kept as ${key}`);
1315
+ await ctx.writeSecrets({ [key]: secret });
1316
+ return secret;
1317
+ }
1318
+ /** The certificate for `host`: recorded, adopted, or requested — then issued. */
1319
+ async function ensureCertificate(ctx, clients, input) {
1320
+ const { ACM, acm } = clients;
1321
+ const { id, host } = input;
1322
+ const entry = {
1323
+ key: `acm-certificate:${id}`,
1324
+ type: "acm-certificate",
1325
+ data: { host }
1326
+ };
1327
+ const describe = (arn) => readOr$2(() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })), ["ResourceNotFoundException"]).then((out) => out?.Certificate);
1328
+ let arn;
1329
+ const recorded = ctx.state.record(entry.key);
1330
+ if (recorded?.id && recorded.data?.host === host) {
1331
+ const found = await describe(recorded.id);
1332
+ if (found && found.Status !== "FAILED" && found.Status !== "VALIDATION_TIMED_OUT" && found.Status !== "REVOKED" && found.Status !== "EXPIRED") arn = recorded.id;
1333
+ }
1334
+ if (!arn) {
1335
+ arn = await findCertificate(clients, host);
1336
+ if (arn) ctx.log(` adopting the certificate for ${host} — ${arn}`);
1337
+ }
1338
+ if (!arn) {
1339
+ if (ctx.dryRun) {
1340
+ await ctx.change({
1341
+ construct: id,
1342
+ resource: `certificate ${host}`,
1343
+ change: "request (ACM, us-east-1, DNS-validated)"
1344
+ }, async () => {});
1345
+ return PLANNED;
1346
+ }
1347
+ await ctx.state.pending(entry);
1348
+ arn = (await acm.send(new ACM.RequestCertificateCommand({
1349
+ DomainName: host,
1350
+ ValidationMethod: "DNS",
1351
+ IdempotencyToken: input.name.replace(/[^A-Za-z0-9]/g, "").slice(0, 32),
1352
+ Tags: identityTags(ctx, id).map((t) => ({
1353
+ Key: t.Key,
1354
+ Value: t.Value
1355
+ }))
1356
+ }))).CertificateArn;
1357
+ await ctx.change({
1358
+ construct: id,
1359
+ resource: `certificate ${host}`,
1360
+ change: "request (ACM, us-east-1, DNS-validated)"
1361
+ }, async () => {});
1362
+ }
1363
+ if (!ctx.dryRun) await ctx.state.ready(entry, arn);
1364
+ let certificate = await describe(arn);
1365
+ let record = certificate?.DomainValidationOptions?.[0]?.ResourceRecord;
1366
+ for (let i = 0; !record && i < 15; i++) {
1367
+ await sleep(Math.min(clients.wait.intervalMs, 2e3));
1368
+ certificate = await describe(arn);
1369
+ record = certificate?.DomainValidationOptions?.[0]?.ResourceRecord;
1370
+ }
1371
+ const validation = record ? {
1372
+ name: record.Name.replace(/\.$/, ""),
1373
+ value: record.Value.replace(/\.$/, "")
1374
+ } : void 0;
1375
+ const written = validation ? await ctx.writeDns([{
1376
+ host: validation.name,
1377
+ type: "CNAME",
1378
+ value: validation.value
1379
+ }]) : { manual: [] };
1380
+ if (certificate?.Status === "ISSUED" || ctx.dryRun) return arn;
1381
+ if (validation && written.manual.includes(validation.name.toLowerCase())) throw new CdnCertificatePending(id, host, validation, "manual");
1382
+ ctx.log(` waiting for ACM to issue the certificate for ${host}…`);
1383
+ const deadline = Date.now() + clients.wait.timeoutMs;
1384
+ while (certificate?.Status === "PENDING_VALIDATION" && Date.now() < deadline) {
1385
+ await sleep(clients.wait.intervalMs);
1386
+ certificate = await describe(arn);
1387
+ }
1388
+ if (certificate?.Status === "ISSUED") return arn;
1389
+ if (certificate?.Status === "PENDING_VALIDATION" || !certificate) throw new CdnCertificatePending(id, host, validation ?? {
1390
+ name: `(not published yet) ${host}`,
1391
+ value: ""
1392
+ }, "timeout");
1393
+ throw new CdnCertificateFailed(id, host, certificate.Status ?? "unknown", certificate.FailureReason);
1394
+ }
1395
+ /** An issued or pending certificate for exactly `host`, if the account has one. */
1396
+ async function findCertificate(clients, host) {
1397
+ const { ACM, acm } = clients;
1398
+ let NextToken;
1399
+ do {
1400
+ const page = await acm.send(new ACM.ListCertificatesCommand({
1401
+ CertificateStatuses: ["ISSUED", "PENDING_VALIDATION"],
1402
+ ...NextToken ? { NextToken } : {}
1403
+ }));
1404
+ const match = page.CertificateSummaryList?.find((c) => c.DomainName?.toLowerCase() === host);
1405
+ if (match?.CertificateArn) return match.CertificateArn;
1406
+ NextToken = page.NextToken;
1407
+ } while (NextToken);
1408
+ }
1409
+ /** The origin access control CloudFront signs its bucket requests with. */
1410
+ async function ensureOriginAccessControl(ctx, clients, input) {
1411
+ const { CF, cloudfront } = clients;
1412
+ const entry = {
1413
+ key: `cloudfront-oac:${input.id}`,
1414
+ type: "cloudfront-oac",
1415
+ data: { name: input.name }
1416
+ };
1417
+ const recorded = ctx.state.record(entry.key)?.id;
1418
+ if (recorded) {
1419
+ if (await readOr$2(() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: recorded })), ["NoSuchOriginAccessControl"])) return recorded;
1420
+ }
1421
+ let Marker;
1422
+ do {
1423
+ const page = await cloudfront.send(new CF.ListOriginAccessControlsCommand({ ...Marker ? { Marker } : {} }));
1424
+ const match = page.OriginAccessControlList?.Items?.find((o) => o.Name === input.name);
1425
+ if (match?.Id) {
1426
+ if (!ctx.dryRun) await ctx.state.ready(entry, match.Id);
1427
+ return match.Id;
1428
+ }
1429
+ Marker = page.OriginAccessControlList?.NextMarker;
1430
+ } while (Marker);
1431
+ let id = PLANNED;
1432
+ await ctx.change({
1433
+ construct: input.id,
1434
+ resource: `origin access control ${input.name}`,
1435
+ change: `create (CloudFront signs its reads of ${input.bucket})`
1436
+ }, async () => {
1437
+ await ctx.state.pending(entry);
1438
+ id = (await cloudfront.send(new CF.CreateOriginAccessControlCommand({ OriginAccessControlConfig: {
1439
+ Name: input.name,
1440
+ Description: `gkm: CloudFront's reads of ${input.bucket}`,
1441
+ OriginAccessControlOriginType: "s3",
1442
+ SigningBehavior: "always",
1443
+ SigningProtocol: "sigv4"
1444
+ } }))).OriginAccessControl.Id;
1445
+ await ctx.state.ready(entry, id);
1446
+ });
1447
+ return id;
1448
+ }
1449
+ /** One response headers policy, as wanted. */
1450
+ async function ensureHeadersPolicy(ctx, clients, input) {
1451
+ const { CF, cloudfront } = clients;
1452
+ const { config } = input;
1453
+ const entry = {
1454
+ key: `cloudfront-headers:${input.id}:${input.kind}`,
1455
+ type: "cloudfront-headers",
1456
+ data: { name: config.Name }
1457
+ };
1458
+ const read = (Id) => readOr$2(() => cloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id })), ["NoSuchResponseHeadersPolicy"]);
1459
+ let id = ctx.state.record(entry.key)?.id;
1460
+ let current = id ? await read(id) : void 0;
1461
+ if (!current) {
1462
+ id = void 0;
1463
+ let Marker;
1464
+ do {
1465
+ const page = await cloudfront.send(new CF.ListResponseHeadersPoliciesCommand({
1466
+ Type: "custom",
1467
+ ...Marker ? { Marker } : {}
1468
+ }));
1469
+ const match = page.ResponseHeadersPolicyList?.Items?.find((p) => p.ResponseHeadersPolicy?.ResponseHeadersPolicyConfig?.Name === config.Name);
1470
+ if (match?.ResponseHeadersPolicy?.Id) {
1471
+ id = match.ResponseHeadersPolicy.Id;
1472
+ current = await read(id);
1473
+ }
1474
+ Marker = page.ResponseHeadersPolicyList?.NextMarker;
1475
+ } while (!id && Marker);
1476
+ }
1477
+ if (id && current) {
1478
+ if (!ctx.dryRun) await ctx.state.ready(entry, id);
1479
+ if (sameHeadersPolicy(current.ResponseHeadersPolicyConfig, config)) return id;
1480
+ const existing = id;
1481
+ await ctx.change({
1482
+ construct: input.id,
1483
+ resource: `response headers policy ${config.Name}`,
1484
+ change: "put back what drifted"
1485
+ }, async () => {
1486
+ await cloudfront.send(new CF.UpdateResponseHeadersPolicyCommand({
1487
+ Id: existing,
1488
+ IfMatch: current.ETag,
1489
+ ResponseHeadersPolicyConfig: config
1490
+ }));
1491
+ });
1492
+ return existing;
1493
+ }
1494
+ let created = PLANNED;
1495
+ await ctx.change({
1496
+ construct: input.id,
1497
+ resource: `response headers policy ${config.Name}`,
1498
+ change: "create"
1499
+ }, async () => {
1500
+ await ctx.state.pending(entry);
1501
+ created = (await cloudfront.send(new CF.CreateResponseHeadersPolicyCommand({ ResponseHeadersPolicyConfig: config }))).ResponseHeadersPolicy.Id;
1502
+ await ctx.state.ready(entry, created);
1503
+ });
1504
+ return created;
1505
+ }
1506
+ /** The distribution: recorded, found by its comment, or created — as wanted. */
1507
+ async function ensureDistribution(ctx, clients, input) {
1508
+ const { CF, cloudfront } = clients;
1509
+ const entry = {
1510
+ key: `cloudfront-distribution:${input.id}`,
1511
+ type: "cloudfront-distribution"
1512
+ };
1513
+ const get = (Id) => readOr$2(() => cloudfront.send(new CF.GetDistributionCommand({ Id })), ["NoSuchDistribution"]);
1514
+ let found = ctx.state.record(entry.key)?.id ? await get(ctx.state.record(entry.key).id) : void 0;
1515
+ if (!found) {
1516
+ let Marker;
1517
+ do {
1518
+ const page = await cloudfront.send(new CF.ListDistributionsCommand({ ...Marker ? { Marker } : {} }));
1519
+ const match = page.DistributionList?.Items?.find((d) => d.Comment === input.comment);
1520
+ if (match?.Id) found = await get(match.Id);
1521
+ Marker = page.DistributionList?.NextMarker;
1522
+ } while (!found && Marker);
1523
+ }
1524
+ if (found?.Distribution) {
1525
+ const distribution = found.Distribution;
1526
+ const id = distribution.Id;
1527
+ const located = {
1528
+ arn: distribution.ARN,
1529
+ domainName: distribution.DomainName
1530
+ };
1531
+ if (!ctx.dryRun) await ctx.state.ready({
1532
+ ...entry,
1533
+ data: located
1534
+ }, id);
1535
+ const current = await cloudfront.send(new CF.GetDistributionConfigCommand({ Id: id }));
1536
+ if (holds(current.DistributionConfig, input.config)) return located;
1537
+ await ctx.change({
1538
+ construct: input.id,
1539
+ resource: `distribution ${id}`,
1540
+ change: "put back what drifted"
1541
+ }, async () => {
1542
+ await cloudfront.send(new CF.UpdateDistributionCommand({
1543
+ Id: id,
1544
+ IfMatch: current.ETag,
1545
+ DistributionConfig: {
1546
+ ...current.DistributionConfig,
1547
+ ...input.config,
1548
+ CallerReference: current.DistributionConfig.CallerReference
1549
+ }
1550
+ }));
1551
+ });
1552
+ return located;
1553
+ }
1554
+ let created = {
1555
+ arn: `arn:aws:cloudfront::${PLANNED}`,
1556
+ domainName: PLANNED
1557
+ };
1558
+ const host = input.config.Aliases?.Items?.[0] ?? input.id;
1559
+ await ctx.change({
1560
+ construct: input.id,
1561
+ resource: `distribution ${host}`,
1562
+ change: "create (CloudFront, takes minutes to reach every edge)"
1563
+ }, async () => {
1564
+ await ctx.state.pending(entry);
1565
+ const out = await cloudfront.send(new CF.CreateDistributionWithTagsCommand({ DistributionConfigWithTags: {
1566
+ DistributionConfig: input.config,
1567
+ Tags: { Items: identityTags(ctx, input.id).map((t) => ({
1568
+ Key: t.Key,
1569
+ Value: t.Value
1570
+ })) }
1571
+ } }));
1572
+ created = {
1573
+ arn: out.Distribution.ARN,
1574
+ domainName: out.Distribution.DomainName
1575
+ };
1576
+ await ctx.state.ready({
1577
+ ...entry,
1578
+ data: created
1579
+ }, out.Distribution.Id);
1580
+ });
1581
+ return created;
1582
+ }
1583
+ //#endregion
1584
+ //#region src/providers/s3/events.ts
1585
+ /** What S3 tells the topic about: every object written, and every removed. */
1586
+ const BUCKET_EVENTS = ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"];
1587
+ /**
1588
+ * Each bucket a subscriber watches, with the subscribers watching it: the
1589
+ * worker that runs each, and its export — what its route is named after.
1590
+ *
1591
+ * Read off the bucket's own node, where discovery nests every subscriber
1592
+ * bound to it with the worker that owns it.
1593
+ */
1594
+ function bucketWatchers(manifest) {
1595
+ const watched = /* @__PURE__ */ new Map();
1596
+ for (const [id, declaration] of Object.entries(manifest)) {
1597
+ if (declaration.kind !== "objects") continue;
1598
+ const subscribers = declaration.subscribers ?? [];
1599
+ if (subscribers.length === 0) continue;
1600
+ watched.set(id, subscribers.flatMap((s) => s.owner ? [{
1601
+ worker: s.owner,
1602
+ name: s.id
1603
+ }] : []).sort((a, b) => `${a.worker}/${a.name}`.localeCompare(`${b.worker}/${b.name}`)));
1604
+ }
1605
+ return watched;
1606
+ }
1607
+ /** The topic a bucket's changes are published to. */
1608
+ function eventsTopicName(bucket) {
1609
+ return `${bucket.replaceAll(".", "-")}-events`;
1610
+ }
1611
+ /** What SNS gives up delivering, kept. */
1612
+ function eventsDeadLetterName(bucket) {
1613
+ return `${eventsTopicName(bucket)}-dlq`;
1614
+ }
1615
+ /** Only this bucket, in this account, may publish to its topic. */
1616
+ function eventsTopicPolicy(topicArn, bucket, account) {
1617
+ return {
1618
+ Version: "2012-10-17",
1619
+ Statement: [{
1620
+ Sid: "GkmBucketPublishes",
1621
+ Effect: "Allow",
1622
+ Principal: { Service: "s3.amazonaws.com" },
1623
+ Action: "sns:Publish",
1624
+ Resource: topicArn,
1625
+ Condition: {
1626
+ ArnLike: { "aws:SourceArn": `arn:aws:s3:::${bucket}` },
1627
+ StringEquals: { "aws:SourceAccount": account }
1628
+ }
1629
+ }]
1630
+ };
1631
+ }
1632
+ /** Only the bucket's topic may send to its dead-letter queue. */
1633
+ function eventsDeadLetterPolicy(queueArn, topicArn) {
1634
+ return {
1635
+ Version: "2012-10-17",
1636
+ Statement: [{
1637
+ Sid: "GkmTopicDeadLetters",
1638
+ Effect: "Allow",
1639
+ Principal: { Service: "sns.amazonaws.com" },
1640
+ Action: "sqs:SendMessage",
1641
+ Resource: queueArn,
1642
+ Condition: { ArnEquals: { "aws:SourceArn": topicArn } }
1643
+ }]
1644
+ };
1645
+ }
1646
+ /** The id this provider's notification entry goes under. */
1647
+ const notificationId = (id) => `gkm-${id}`;
1648
+ /**
1649
+ * The bucket's notifications with this provider's entry put back, and whether
1650
+ * that changed anything. Every other entry — a queue, a function, a topic
1651
+ * somebody added by hand — is kept exactly as it was.
1652
+ */
1653
+ function mergedNotifications(current, id, topicArn) {
1654
+ const own = notificationId(id);
1655
+ const wanted = {
1656
+ Id: own,
1657
+ TopicArn: topicArn,
1658
+ Events: [...BUCKET_EVENTS]
1659
+ };
1660
+ const topics = current.TopicConfigurations ?? [];
1661
+ const existing = topics.find((t) => t.Id === own);
1662
+ const same = existing !== void 0 && existing.TopicArn === topicArn && JSON.stringify([...existing.Events ?? []].sort()) === JSON.stringify([...BUCKET_EVENTS].sort()) && existing.Filter === void 0;
1663
+ const { ResponseMetadata: _, ...rest } = current;
1664
+ return {
1665
+ config: {
1666
+ ...rest,
1667
+ TopicConfigurations: [...topics.filter((t) => t.Id !== own), wanted]
1668
+ },
1669
+ changed: !same
1670
+ };
1671
+ }
1672
+ /** S3 refused the entry because another one already covers these events. */
1673
+ var BucketNotificationsOverlap = class extends GkmError {
1674
+ bucket;
1675
+ detail;
1676
+ constructor(bucket, detail) {
1677
+ super(`'${bucket}' already sends object creates or deletes somewhere else, and S3 sends each event to one place only, so the deploy cannot add its own entry. Remove the other notification from the bucket, or give it a prefix, and deploy again. S3 said: ${detail}`);
1678
+ this.bucket = bucket;
1679
+ this.detail = detail;
1680
+ this.name = "BucketNotificationsOverlap";
1681
+ }
1682
+ };
1683
+ const defaultEventsClients = async (credential, region) => {
1684
+ const SNS = await import("@aws-sdk/client-sns");
1685
+ const SQS = await import("@aws-sdk/client-sqs");
1686
+ const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
1687
+ const config = await awsClientConfig(credential, region);
1688
+ const endpoint = awsEndpoint(process.env, "SNS");
1689
+ const sts = new STSClient({
1690
+ ...config,
1691
+ ...awsEndpoint(process.env, "STS") ? { endpoint: awsEndpoint(process.env, "STS") } : {}
1692
+ });
1693
+ const { Account } = await sts.send(new GetCallerIdentityCommand({}));
1694
+ sts.destroy();
1695
+ return {
1696
+ SNS,
1697
+ SQS,
1698
+ sns: new SNS.SNSClient({
1699
+ ...config,
1700
+ ...endpoint ? { endpoint } : {}
1701
+ }),
1702
+ sqs: new SQS.SQSClient({
1703
+ ...config,
1704
+ ...awsEndpoint(process.env, "SQS") ? { endpoint: awsEndpoint(process.env, "SQS") } : {}
1705
+ }),
1706
+ account: Account,
1707
+ region,
1708
+ ...endpoint ? { endpoint } : {}
1709
+ };
1710
+ };
1711
+ let makeEventsClients = defaultEventsClients;
1712
+ /** The stage's SNS, SQS and account, through the factory a test may replace. */
1713
+ function eventsClients(credential, region) {
1714
+ return makeEventsClients(credential, region);
1715
+ }
1716
+ function errorName$2(error) {
1717
+ const e = error;
1718
+ return e?.name ?? e?.Code ?? e?.code ?? "";
1719
+ }
1720
+ async function readOr$1(read, missing) {
1721
+ try {
1722
+ return await read();
1723
+ } catch (error) {
1724
+ if (missing.includes(errorName$2(error))) return void 0;
1725
+ throw error;
1726
+ }
1727
+ }
1728
+ /**
1729
+ * An SNS topic of the stage's, created where missing, whose policy lets
1730
+ * exactly one AWS service publish to it — put back where it drifted. A
1731
+ * watched bucket's topic is published to by S3; an inbox's by SES.
1732
+ */
1733
+ async function ensureTopic(ctx, clients, input) {
1734
+ const { SNS, sns, account, region } = clients;
1735
+ const { id, topicName } = input;
1736
+ const topicArn = `arn:aws:sns:${region}:${account}:${topicName}`;
1737
+ const topicEntry = {
1738
+ key: `sns-topic:${id}`,
1739
+ type: "sns-topic"
1740
+ };
1741
+ const topic = await readOr$1(() => sns.send(new SNS.GetTopicAttributesCommand({ TopicArn: topicArn })), ["NotFound", "NotFoundException"]);
1742
+ if (topic) await ctx.state.ready(topicEntry, topicArn);
1743
+ else await ctx.change({
1744
+ construct: id,
1745
+ resource: `SNS topic ${topicName}`,
1746
+ change: "create"
1747
+ }, async () => {
1748
+ await ctx.state.pending(topicEntry);
1749
+ await sns.send(new SNS.CreateTopicCommand({
1750
+ Name: topicName,
1751
+ Tags: identityTags(ctx, id)
1752
+ }));
1753
+ await ctx.state.ready(topicEntry, topicArn);
1754
+ });
1755
+ const topicPolicy = input.policy(topicArn);
1756
+ const currentTopicPolicy = topic?.Attributes?.Policy;
1757
+ if (!currentTopicPolicy || canonicalPolicy(JSON.parse(currentTopicPolicy)) !== canonicalPolicy(topicPolicy)) await ctx.change({
1758
+ construct: id,
1759
+ resource: `SNS topic ${topicName}`,
1760
+ change: `publishable by ${input.publisher} only`
1761
+ }, async () => {
1762
+ await sns.send(new SNS.SetTopicAttributesCommand({
1763
+ TopicArn: topicArn,
1764
+ AttributeName: "Policy",
1765
+ AttributeValue: JSON.stringify(topicPolicy)
1766
+ }));
1767
+ });
1768
+ return topicArn;
1769
+ }
1770
+ /**
1771
+ * The topic, its policy, the dead-letter queue and the bucket's notification
1772
+ * entry for one watched bucket — created where missing, put back where they
1773
+ * drifted.
1774
+ */
1775
+ async function ensureBucketEvents(ctx, s3, input) {
1776
+ const { id, bucket, region } = input;
1777
+ const clients = await makeEventsClients(ctx.credential, region);
1778
+ const { SQS, sns, sqs, account } = clients;
1779
+ const topicName = eventsTopicName(bucket);
1780
+ const topicArn = await ensureTopic(ctx, clients, {
1781
+ id,
1782
+ topicName,
1783
+ publisher: `'${bucket}'`,
1784
+ policy: (arn) => eventsTopicPolicy(arn, bucket, account)
1785
+ });
1786
+ const queueName = eventsDeadLetterName(bucket);
1787
+ const deadLetterArn = `arn:aws:sqs:${region}:${account}:${queueName}`;
1788
+ const queueEntry = {
1789
+ key: `sqs-queue:${id}-events-dlq`,
1790
+ type: "sqs-queue"
1791
+ };
1792
+ const queue = await readOr$1(() => sqs.send(new SQS.GetQueueUrlCommand({ QueueName: queueName })), ["QueueDoesNotExist", "AWS.SimpleQueueService.NonExistentQueue"]);
1793
+ let queueUrl = queue?.QueueUrl;
1794
+ if (queueUrl) await ctx.state.ready(queueEntry, deadLetterArn);
1795
+ else await ctx.change({
1796
+ construct: id,
1797
+ resource: `SQS queue ${queueName}`,
1798
+ change: "create"
1799
+ }, async () => {
1800
+ await ctx.state.pending(queueEntry);
1801
+ queueUrl = (await sqs.send(new SQS.CreateQueueCommand({
1802
+ QueueName: queueName,
1803
+ Attributes: { MessageRetentionPeriod: "1209600" },
1804
+ tags: Object.fromEntries(identityTags(ctx, id).map((t) => [t.Key, t.Value]))
1805
+ }))).QueueUrl;
1806
+ await ctx.state.ready(queueEntry, deadLetterArn);
1807
+ });
1808
+ const queuePolicy = eventsDeadLetterPolicy(deadLetterArn, topicArn);
1809
+ const currentQueuePolicy = queue?.QueueUrl ? (await sqs.send(new SQS.GetQueueAttributesCommand({
1810
+ QueueUrl: queue.QueueUrl,
1811
+ AttributeNames: ["Policy"]
1812
+ }))).Attributes?.Policy : void 0;
1813
+ if (!currentQueuePolicy || canonicalPolicy(JSON.parse(currentQueuePolicy)) !== canonicalPolicy(queuePolicy)) await ctx.change({
1814
+ construct: id,
1815
+ resource: `SQS queue ${queueName}`,
1816
+ change: `receives what ${topicName} cannot deliver`
1817
+ }, async () => {
1818
+ await sqs.send(new SQS.SetQueueAttributesCommand({
1819
+ QueueUrl: queueUrl,
1820
+ Attributes: { Policy: JSON.stringify(queuePolicy) }
1821
+ }));
1822
+ });
1823
+ const merged = mergedNotifications(await readOr$1(() => s3.s3.send(new s3.S3.GetBucketNotificationConfigurationCommand({ Bucket: bucket })), ["NoSuchBucket"]) ?? {}, id, topicArn);
1824
+ if (merged.changed) await ctx.change({
1825
+ construct: id,
1826
+ resource: `bucket ${bucket}`,
1827
+ change: `send object creates and deletes to ${topicName}`
1828
+ }, async () => {
1829
+ try {
1830
+ await s3.s3.send(new s3.S3.PutBucketNotificationConfigurationCommand({
1831
+ Bucket: bucket,
1832
+ NotificationConfiguration: merged.config
1833
+ }));
1834
+ } catch (error) {
1835
+ const message = error.message ?? "";
1836
+ if (/overlap/i.test(message)) throw new BucketNotificationsOverlap(bucket, message);
1837
+ throw error;
1838
+ }
1839
+ });
1840
+ sns.destroy();
1841
+ sqs.destroy();
1842
+ return {
1843
+ topicArn,
1844
+ deadLetterArn
1845
+ };
1846
+ }
1847
+ /**
1848
+ * A topic's connection string: its address, signed by the access key in a
1849
+ * bucket's URL — read off that URL, so a rotated key rotates this one with
1850
+ * it. A watched bucket's events key by default; an inbox's topic, signed by
1851
+ * its own bucket's key, otherwise.
1852
+ */
1853
+ async function ensureEventsKey(ctx, input) {
1854
+ const { id, topicArn, region } = input;
1855
+ const key = input.key ?? provideKey(id, "eventsConnectionString");
1856
+ const url = ctx.secrets[input.urlKey ?? provideKey(id, "url")];
1857
+ let parsed;
1858
+ try {
1859
+ parsed = url ? s3Url.parse(url) : void 0;
1860
+ } catch {
1861
+ parsed = void 0;
1862
+ }
1863
+ if (!parsed?.accessKeyId || !parsed.secretAccessKey) {
1864
+ await ctx.change({
1865
+ construct: id,
1866
+ resource: key,
1867
+ change: "set to the topic’s address"
1868
+ }, async () => {});
1869
+ return;
1870
+ }
1871
+ const { snsUrl } = await import("@geekmidas/events/sns");
1872
+ const endpoint = awsEndpoint(process.env, "SNS");
1873
+ const address = new URL(snsUrl.build({
1874
+ topicArn,
1875
+ region,
1876
+ ...endpoint ? { endpoint } : {}
1877
+ }));
1878
+ address.searchParams.set("accessKeyId", parsed.accessKeyId);
1879
+ address.searchParams.set("secretAccessKey", parsed.secretAccessKey);
1880
+ const value = address.toString();
1881
+ const entry = {
1882
+ key: `events-key:${id}`,
1883
+ type: "url"
1884
+ };
1885
+ if (ctx.secrets[key] === value) {
1886
+ await ctx.state.ready(entry, topicArn);
1887
+ return;
1888
+ }
1889
+ await ctx.change({
1890
+ construct: id,
1891
+ resource: key,
1892
+ change: `set to ${topicArn}`
1893
+ }, async () => {
1894
+ await ctx.writeSecrets({ [key]: value });
1895
+ await ctx.state.ready(entry, topicArn);
1896
+ });
1897
+ }
1898
+ /** Where SNS pushes to a worker: its own host on the stage's domain. */
1899
+ function workerPushHost(worker, domain) {
1900
+ return `${appKey(worker)}.${domain}`;
1901
+ }
1902
+ /**
1903
+ * One HTTP subscription per subscriber to the bucket's topic, at its route on
1904
+ * its worker's host, with the bucket's dead-letter queue — and each ARN
1905
+ * recorded, which is what the worker accepts deliveries under.
1906
+ *
1907
+ * Unfiltered: a bucket's notifications carry no `type` attribute, and the
1908
+ * subscriber's own filter — events, prefix, suffix — is what decides. Only a
1909
+ * compose stage pushes to a worker; any other is told so and left alone.
1910
+ */
1911
+ async function ensurePushSubscriptions(ctx, input) {
1912
+ const { id, events, region, watchers } = input;
1913
+ if (!deploysWithCompose(ctx.workspace)) {
1914
+ ctx.log(` '${id}' is watched, and only a compose stage pushes a bucket's changes to a worker: its subscribers receive nothing on '${ctx.stage}'`);
1915
+ return;
1916
+ }
1917
+ if (watchers.length === 0) return;
1918
+ const domain = ctx.workspace.domains?.[ctx.stage];
1919
+ if (!domain) throw new NoDomainForStage(ctx.stage);
1920
+ const { SNSConnection, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
1921
+ const { credentials } = await awsClientConfig(ctx.credential, region);
1922
+ const endpoint = awsEndpoint(process.env, "SNS");
1923
+ const byWorker = /* @__PURE__ */ new Map();
1924
+ for (const watcher of watchers) byWorker.set(watcher.worker, [...byWorker.get(watcher.worker) ?? [], watcher]);
1925
+ for (const [worker, own] of byWorker) {
1926
+ const host = workerPushHost(worker, domain);
1927
+ const endpoints = own.map(({ name }) => ({
1928
+ name,
1929
+ endpoint: `https://${host}${subscriberRoute(name)}`,
1930
+ deadLetterQueueArn: events.deadLetterArn
1931
+ }));
1932
+ const unrecorded = own.filter(({ name }) => ctx.state.record(subscriptionKey(worker, name))?.status !== "ready");
1933
+ if (ctx.dryRun) {
1934
+ if (unrecorded.length > 0) await ctx.change({
1935
+ construct: id,
1936
+ resource: `SNS subscriptions on ${host}`,
1937
+ change: `subscribe ${unrecorded.map((w) => w.name).join(", ")}`
1938
+ }, async () => {});
1939
+ continue;
1940
+ }
1941
+ const connection = new SNSConnection({
1942
+ topicArn: events.topicArn,
1943
+ region,
1944
+ ...endpoint ? { endpoint } : {},
1945
+ ...credentials ? { credentials } : {}
1946
+ });
1947
+ const result = await reconcileHttpSubscriptions(connection, {
1948
+ endpoints,
1949
+ ownedHost: host
1950
+ });
1951
+ await connection.close();
1952
+ for (const spec of endpoints) {
1953
+ const arn = result.subscriptions[spec.name];
1954
+ const pending = result.pending.includes(spec.name);
1955
+ if (ctx.state.record(subscriptionKey(worker, spec.name))?.id !== arn) ctx.log(` ✓ '${spec.name}' subscribed to ${events.topicArn.split(":").pop()} at ${spec.endpoint}`);
1956
+ const { key, type, data } = subscriptionResource({
1957
+ worker,
1958
+ name: spec.name,
1959
+ topicArn: events.topicArn,
1960
+ endpoint: spec.endpoint,
1961
+ deadLetterQueueArn: events.deadLetterArn,
1962
+ pending
1963
+ }, arn);
1964
+ await ctx.state.ready({
1965
+ key,
1966
+ type,
1967
+ ...data ? { data } : {}
1968
+ }, arn);
1969
+ }
1970
+ for (const arn of result.removed) ctx.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
1971
+ }
1972
+ }
1973
+ //#endregion
1974
+ //#region src/providers/s3/origins.ts
1975
+ /**
1976
+ * Which browser origins may call a bucket: the stage's sites that depend on
1977
+ * an API using it.
1978
+ *
1979
+ * The same reading of the graph an API's own CORS origins are — its callers —
1980
+ * taken one step further: a site that calls an API which hands it a presigned
1981
+ * upload URL is a site whose browser PUTs to the bucket. A site that reads the
1982
+ * bucket (or a file server over it) itself is one too. Nothing is written
1983
+ * down: add a site that calls the API and the next provision run allows it.
1984
+ */
1985
+ /** The keys a reader of this bucket holds: its URL, and each server's over it. */
1986
+ function bucketKeys(manifest, bucket) {
1987
+ return [provideKey(bucket, "url"), ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => provideKey(id, "url"))];
1988
+ }
1989
+ function bucketOrigins(input) {
1990
+ const { manifest, workspace, stage } = input;
1991
+ const keys = bucketKeys(manifest, input.bucket);
1992
+ const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "websocket-api" || d.kind === "site").filter(([id]) => {
1993
+ const env = appEnvKeys(manifest, appKey(id));
1994
+ return env !== void 0 && keys.some((key) => env.has(key));
1995
+ });
1996
+ const sites = /* @__PURE__ */ new Set();
1997
+ for (const [id, declaration] of readers) {
1998
+ if (declaration.kind === "site") {
1999
+ sites.add(id);
2000
+ continue;
2001
+ }
2002
+ for (const caller of dependentsOf(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
2003
+ }
2004
+ const origins = /* @__PURE__ */ new Set();
2005
+ const unresolved = [];
2006
+ for (const id of [...sites].sort()) {
2007
+ const name = appKey(id);
2008
+ const app = workspace.apps[name];
2009
+ if (!app) {
2010
+ unresolved.push(name);
2011
+ continue;
2012
+ }
2013
+ try {
2014
+ const host = resolveHost(name, app, stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
2015
+ origins.add(`https://${host}`);
2016
+ } catch (error) {
2017
+ if (!(error instanceof NoDomainForStage)) throw error;
2018
+ unresolved.push(name);
2019
+ }
2020
+ }
2021
+ return {
2022
+ origins: [...origins].sort(),
2023
+ unresolved
2024
+ };
2025
+ }
2026
+ //#endregion
2027
+ //#region src/providers/s3/index.ts
2028
+ function bucketConstructs(manifest) {
2029
+ return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
2030
+ id,
2031
+ versioned: d.versioned === true,
2032
+ ...bucketExpiry(manifest, id) ? { expire: bucketExpiry(manifest, id) } : {},
2033
+ servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
2034
+ id: sid,
2035
+ open: s.open ?? [],
2036
+ immutable: s.immutable ?? [],
2037
+ ...s.processors?.length ? { processors: [...new Set(s.processors.map((p) => p.prefix))].sort() } : {}
2038
+ })).sort((a, b) => a.id.localeCompare(b.id))
2039
+ })).sort((a, b) => a.id.localeCompare(b.id));
2040
+ }
2041
+ /**
2042
+ * The region the stage's buckets are created in: the entry's, the secrets
2043
+ * store's when it is in AWS, the credential's, `AWS_REGION`.
2044
+ */
2045
+ function s3Region(ctx, env = process.env) {
2046
+ const store = ctx.workspace.secrets?.store;
2047
+ const storeRegion = store && typeof store === "object" && "region" in store ? store.region : void 0;
2048
+ const region = ctx.config.region ?? storeRegion ?? ctx.credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
2049
+ if (!region) throw new S3RegionRequired(ctx.stage);
2050
+ return region;
2051
+ }
2052
+ /**
2053
+ * The address a file server over `bucket` serves on: the bucket's regional
2054
+ * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
2055
+ * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
2056
+ * its path-style address.
2057
+ */
2058
+ function bucketPublicUrl(bucket, region, endpoint) {
2059
+ if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
2060
+ return `https://${bucket}.s3.${region}.amazonaws.com`;
2061
+ }
2062
+ /** What an AWS SDK error is called, whichever field carries it. */
2063
+ function errorName$1(error) {
2064
+ const e = error;
2065
+ return e?.Code ?? e?.name ?? "";
2066
+ }
2067
+ /** The answer an SDK call failed with. */
2068
+ function s3Answer(error) {
2069
+ const e = error;
2070
+ const headers = Object.fromEntries(Object.entries(e?.$response?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
2071
+ const status = e?.$metadata?.httpStatusCode ?? e?.$response?.statusCode;
2072
+ const region = headers["x-amz-bucket-region"];
2073
+ const requestId = e?.$metadata?.requestId ?? headers["x-amz-request-id"];
2074
+ const id2 = e?.$metadata?.extendedRequestId ?? headers["x-amz-id-2"];
2075
+ return {
2076
+ ...status !== void 0 ? { status } : {},
2077
+ name: errorName$1(error) || "Error",
2078
+ message: e?.message ?? String(error),
2079
+ ...region ? { region } : {},
2080
+ ...requestId ? { requestId } : {},
2081
+ ...id2 ? { id2 } : {}
2082
+ };
2083
+ }
2084
+ /**
2085
+ * `HTTP 403 Unknown: UnknownError [x-amz-bucket-region: eu-west-1,
2086
+ * x-amz-request-id: …, x-amz-id-2: …]` — everything S3 said, for a message.
2087
+ */
2088
+ function describeAnswer(answer) {
2089
+ const said = answer.message && answer.message !== answer.name ? `${answer.name}: ${answer.message}` : answer.name;
2090
+ const headers = [
2091
+ answer.region && `x-amz-bucket-region: ${answer.region}`,
2092
+ answer.requestId && `x-amz-request-id: ${answer.requestId}`,
2093
+ answer.id2 && `x-amz-id-2: ${answer.id2}`
2094
+ ].filter(Boolean);
2095
+ return `${answer.status === void 0 ? "no response" : `HTTP ${answer.status}`} ${said}` + (headers.length > 0 ? ` [${headers.join(", ")}]` : "");
2096
+ }
2097
+ /** `HeadBucket`: the bucket's region when it answers, else what S3 said. */
2098
+ async function headBucket(S3, client, bucket) {
2099
+ try {
2100
+ const out = await client.send(new S3.HeadBucketCommand({ Bucket: bucket }));
2101
+ return {
2102
+ ok: true,
2103
+ ...out.BucketRegion ? { region: out.BucketRegion } : {}
2104
+ };
2105
+ } catch (error) {
2106
+ return {
2107
+ ok: false,
2108
+ ...s3Answer(error)
2109
+ };
2110
+ }
2111
+ }
2112
+ /** `GetBucketLocation`'s answer as a region: none is us-east-1, `EU` eu-west-1. */
2113
+ async function bucketLocation(S3, client, bucket) {
2114
+ try {
2115
+ const location = (await client.send(new S3.GetBucketLocationCommand({ Bucket: bucket }))).LocationConstraint;
2116
+ return { region: !location ? "us-east-1" : location === "EU" ? "eu-west-1" : location };
2117
+ } catch (error) {
2118
+ return { failed: s3Answer(error) };
2119
+ }
2120
+ }
2121
+ /**
2122
+ * Where `bucket` is: `HeadBucket`'s `x-amz-bucket-region` — on a 200, a 301
2123
+ * or a 400 alike — else `GetBucketLocation`.
2124
+ *
2125
+ * @throws {BucketRegionUnknown}
2126
+ */
2127
+ async function bucketRegion(clients, bucket) {
2128
+ const { S3, s3 } = clients;
2129
+ const head = await headBucket(S3, s3, bucket);
2130
+ if (head.region) return head.region;
2131
+ const location = await bucketLocation(S3, s3, bucket);
2132
+ if ("region" in location) return location.region;
2133
+ throw new BucketRegionUnknown(bucket, head.ok ? "HTTP 200 without x-amz-bucket-region" : describeAnswer(head), describeAnswer(location.failed));
2134
+ }
2135
+ /** A read whose "there is none" answer is one of `missing`. */
2136
+ async function readOr(read, missing) {
2137
+ try {
2138
+ return await read();
2139
+ } catch (error) {
2140
+ if (missing.includes(errorName$1(error))) return void 0;
2141
+ throw error;
2142
+ }
2143
+ }
2144
+ const defaultClients = async (credential, region) => {
2145
+ const S3 = await import("@aws-sdk/client-s3");
2146
+ const IAM = await import("@aws-sdk/client-iam");
2147
+ const config = await awsClientConfig(credential, region);
2148
+ const endpoint = awsEndpoint(process.env, "S3");
2149
+ return {
2150
+ S3,
2151
+ IAM,
2152
+ s3: new S3.S3Client({
2153
+ ...config,
2154
+ ...endpoint ? {
2155
+ endpoint,
2156
+ forcePathStyle: true
2157
+ } : {}
2158
+ }),
2159
+ iam: new IAM.IAMClient(config),
2160
+ region,
2161
+ ...endpoint ? { endpoint } : {}
2162
+ };
2163
+ };
2164
+ /** For tests: what makes the clients. */
2165
+ let makeClients = defaultClients;
2166
+ async function ensureS3(ctx) {
2167
+ const region = s3Region(ctx);
2168
+ const clients = await makeClients(ctx.credential, region);
2169
+ const watched = bucketWatchers(ctx.manifest);
2170
+ for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct, watched.get(construct.id));
2171
+ }
2172
+ async function ensureBucket(ctx, stageClients, construct, watchers) {
2173
+ const { id } = construct;
2174
+ const nameInput = {
2175
+ scope: ctx.identity.scope,
2176
+ stage: ctx.stage,
2177
+ id: appKey(id)
2178
+ };
2179
+ const versioning = ctx.config.versioning ?? construct.versioned;
2180
+ const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
2181
+ const located = await ensureBucketName(ctx, stageClients, id, bucketName(nameInput));
2182
+ const { bucket, exists } = located;
2183
+ let clients = stageClients;
2184
+ if (located.region !== stageClients.region) {
2185
+ clients = await makeClients(ctx.credential, located.region);
2186
+ ctx.log(` '${bucket}' is in ${located.region}, not ${stageClients.region}: '${id}' is reached and addressed there`);
2187
+ }
2188
+ const cdn = ctx.config.cdn !== false && construct.servers.length > 0 ? await ensureBucketCdn(ctx, {
2189
+ bucket,
2190
+ region: clients.region,
2191
+ servers: construct.servers,
2192
+ origins: bucketOrigins({
2193
+ workspace: ctx.workspace,
2194
+ manifest: ctx.manifest,
2195
+ stage: ctx.stage,
2196
+ bucket: id
2197
+ }).origins
2198
+ }) : void 0;
2199
+ await ensureBucketSettings(ctx, clients, {
2200
+ id,
2201
+ bucket,
2202
+ exists,
2203
+ versioning,
2204
+ open,
2205
+ ...cdn ? { cdn } : {},
2206
+ ...construct.expire ? { expire: construct.expire } : {}
2207
+ });
2208
+ const events = watchers ? await ensureBucketEvents(ctx, clients, {
2209
+ id,
2210
+ bucket,
2211
+ region: clients.region
2212
+ }) : void 0;
2213
+ const user = await ensureIamUser(ctx, clients, {
2214
+ id,
2215
+ user: iamUserName(nameInput),
2216
+ policyName: IAM_POLICY_NAME,
2217
+ policy: userPolicy(bucket, {
2218
+ versioning,
2219
+ ...events ? { eventsTopicArn: events.topicArn } : {}
2220
+ }),
2221
+ describe: "this bucket only"
2222
+ });
2223
+ await ensureAccessKey(ctx, clients, {
2224
+ id,
2225
+ bucket,
2226
+ urlKey: provideKey(id, "url"),
2227
+ ...user
2228
+ });
2229
+ if (events && watchers) {
2230
+ await ensureEventsKey(ctx, {
2231
+ id,
2232
+ topicArn: events.topicArn,
2233
+ region: clients.region
2234
+ });
2235
+ await ensurePushSubscriptions(ctx, {
2236
+ id,
2237
+ events,
2238
+ region: clients.region,
2239
+ watchers
2240
+ });
2241
+ }
2242
+ const bucketUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
2243
+ for (const server of construct.servers) {
2244
+ const publicUrl = cdn?.urls[server.id] ?? bucketUrl;
2245
+ const key = provideKey(server.id, "url");
2246
+ const entry = {
2247
+ key: `file-server:${server.id}`,
2248
+ type: "url"
2249
+ };
2250
+ const recorded = ctx.state.record(entry.key)?.id;
2251
+ const current = ctx.secrets[key];
2252
+ if (current === publicUrl) {
2253
+ await ctx.state.ready(entry, publicUrl);
2254
+ continue;
2255
+ }
2256
+ if (current !== void 0 && current !== recorded) {
2257
+ ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
2258
+ continue;
2259
+ }
2260
+ await ctx.change({
2261
+ construct: server.id,
2262
+ resource: key,
2263
+ change: `set to ${publicUrl}`
2264
+ }, async () => {
2265
+ await ctx.writeSecrets({ [key]: publicUrl });
2266
+ await ctx.state.ready(entry, publicUrl);
2267
+ });
2268
+ }
2269
+ }
2270
+ /**
2271
+ * The bucket's name: the recorded one, else the good name, else the good
2272
+ * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
2273
+ */
2274
+ /**
2275
+ * A private bucket a provider makes for a construct that owns one — an
2276
+ * inbox's — by the same steps as any of the stage's buckets: found or
2277
+ * created, its settings put back where they drifted, and reached by an IAM
2278
+ * user of its own whose key is written into `urlKey`. Nothing serves it and
2279
+ * nothing watches it.
2280
+ */
2281
+ async function ensureOwnedBucket(ctx, input) {
2282
+ const bucketCtx = ctx;
2283
+ const stageClients = await makeClients(ctx.credential, s3Region(bucketCtx));
2284
+ const nameInput = {
2285
+ scope: ctx.identity.scope,
2286
+ stage: ctx.stage,
2287
+ id: input.name
2288
+ };
2289
+ const located = await ensureBucketName(bucketCtx, stageClients, input.id, bucketName(nameInput));
2290
+ const clients = located.region === stageClients.region ? stageClients : await makeClients(ctx.credential, located.region);
2291
+ await ensureBucketSettings(bucketCtx, clients, {
2292
+ id: input.id,
2293
+ bucket: located.bucket,
2294
+ exists: located.exists,
2295
+ versioning: false,
2296
+ open: [],
2297
+ ...input.sesWrite ? { sesWrite: input.sesWrite } : {}
2298
+ });
2299
+ const user = await ensureIamUser(bucketCtx, clients, {
2300
+ id: input.id,
2301
+ user: iamUserName(nameInput),
2302
+ policyName: IAM_POLICY_NAME,
2303
+ policy: userPolicy(located.bucket, input.topicArn ? { eventsTopicArn: input.topicArn } : {}),
2304
+ describe: "this bucket only"
2305
+ });
2306
+ await ensureAccessKey(bucketCtx, clients, {
2307
+ id: input.id,
2308
+ bucket: located.bucket,
2309
+ urlKey: input.urlKey,
2310
+ ...user
2311
+ });
2312
+ return {
2313
+ bucket: located.bucket,
2314
+ region: clients.region
2315
+ };
2316
+ }
2317
+ async function ensureBucketName(ctx, clients, id, good) {
2318
+ const { S3, s3, region } = clients;
2319
+ const key = `s3-bucket:${id}`;
2320
+ const record = ctx.state.record(key);
2321
+ const entry = (name, where) => ({
2322
+ key,
2323
+ type: "s3-bucket",
2324
+ data: {
2325
+ name,
2326
+ region: where
2327
+ }
2328
+ });
2329
+ /**
2330
+ * Whether this account holds `name`: yes, no, or someone else does. Read
2331
+ * by status — a `HEAD` has no body, so its error is named `Unknown` — and,
2332
+ * when S3 says the bucket is in another region, asked again there.
2333
+ */
2334
+ const probe = async (name) => {
2335
+ let head = await headBucket(S3, s3, name);
2336
+ if (!head.ok && head.region && head.region !== region && (head.status === 301 || head.status === 400)) {
2337
+ const there = await makeClients(ctx.credential, head.region);
2338
+ head = await headBucket(there.S3, there.s3, name);
2339
+ }
2340
+ if (head.ok) return "ours";
2341
+ if (head.status === 404) return "none";
2342
+ if (head.status === 403) return "taken";
2343
+ throw new BucketProbeFailed(name, describeAnswer(head));
2344
+ };
2345
+ /** Where the bucket is now — read, not assumed: it may be adopted. */
2346
+ const located = async (name, made) => ctx.dryRun && made === "created" ? region : bucketRegion(clients, name);
2347
+ const create = async (name) => {
2348
+ if (ctx.dryRun) {
2349
+ const found = await probe(name);
2350
+ if (found === "none") {
2351
+ await ctx.change({
2352
+ construct: id,
2353
+ resource: `bucket ${name}`,
2354
+ change: `create in ${region}`
2355
+ }, async () => {});
2356
+ return "created";
2357
+ }
2358
+ return found;
2359
+ }
2360
+ await ctx.state.pending(entry(name, region));
2361
+ try {
2362
+ await s3.send(new S3.CreateBucketCommand({
2363
+ Bucket: name,
2364
+ ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
2365
+ }));
2366
+ } catch (error) {
2367
+ const code = errorName$1(error);
2368
+ if (code === "BucketAlreadyOwnedByYou") return "ours";
2369
+ if (code === "BucketAlreadyExists") return "taken";
2370
+ throw error;
2371
+ }
2372
+ await ctx.change({
2373
+ construct: id,
2374
+ resource: `bucket ${name}`,
2375
+ change: `create in ${region}`
2376
+ }, async () => {});
2377
+ return "created";
2378
+ };
2379
+ const adopt = async (name, where) => {
2380
+ const there = where === region ? clients : await makeClients(ctx.credential, where);
2381
+ const owner = (await readOr(() => there.s3.send(new there.S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === TAG_PROJECT)?.Value;
2382
+ if (owner && owner !== ctx.identity.key) throw new BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
2383
+ };
2384
+ if (record?.status === "ready" && record.id) {
2385
+ const found = await probe(record.id);
2386
+ if (found === "taken") throw new RecordedBucketUnreachable(id, record.id);
2387
+ const made = found === "ours" ? "ours" : await create(record.id);
2388
+ if (made === "taken") throw new RecordedBucketUnreachable(id, record.id);
2389
+ const where = await located(record.id, made);
2390
+ if (!ctx.dryRun) await ctx.state.ready(entry(record.id, where), record.id);
2391
+ return {
2392
+ bucket: record.id,
2393
+ exists: made === "ours",
2394
+ region: where
2395
+ };
2396
+ }
2397
+ const pending = record?.data?.name;
2398
+ const names = [
2399
+ ...typeof pending === "string" && pending !== good ? [pending] : [],
2400
+ good,
2401
+ ...Array.from({ length: 5 }, () => suffixedBucketName(good, randomSuffix()))
2402
+ ];
2403
+ const tried = [];
2404
+ for (const name of names) {
2405
+ tried.push(name);
2406
+ const made = await create(name);
2407
+ if (made === "taken") continue;
2408
+ const where = await located(name, made);
2409
+ if (made === "ours") await adopt(name, where);
2410
+ if (!ctx.dryRun) await ctx.state.ready(entry(name, where), name);
2411
+ if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
2412
+ return {
2413
+ bucket: name,
2414
+ exists: made === "ours",
2415
+ region: where
2416
+ };
2417
+ }
2418
+ throw new BucketNameUnavailable(id, tried.filter((n) => n !== pending));
2419
+ }
2420
+ /**
2421
+ * Tags, Block Public Access, encryption, policy, versioning, lifecycle and
2422
+ * CORS.
2423
+ */
2424
+ async function ensureBucketSettings(ctx, clients, input) {
2425
+ const { S3, s3 } = clients;
2426
+ const { id, bucket } = input;
2427
+ const Bucket = bucket;
2428
+ const fresh = ctx.dryRun && !input.exists;
2429
+ const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
2430
+ const set = (change, apply) => ctx.change({
2431
+ construct: id,
2432
+ resource: `bucket ${bucket}`,
2433
+ change
2434
+ }, () => apply().then(() => void 0));
2435
+ const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
2436
+ const ours = identityTags(ctx, id);
2437
+ const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
2438
+ if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
2439
+ Bucket,
2440
+ Tagging: { TagSet: [...others, ...ours].map((t) => ({
2441
+ Key: t.Key,
2442
+ Value: t.Value
2443
+ })) }
2444
+ })));
2445
+ const isOpen = input.open.length > 0 && !input.cdn;
2446
+ const block = publicAccessBlock(isOpen);
2447
+ const ensureBlock = async () => {
2448
+ const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
2449
+ 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({
2450
+ Bucket,
2451
+ PublicAccessBlockConfiguration: block
2452
+ })));
2453
+ };
2454
+ const policy = bucketPolicy(bucket, input.open, {
2455
+ ...input.cdn ? { cdn: input.cdn } : {},
2456
+ ...input.sesWrite ? { sesWrite: input.sesWrite } : {}
2457
+ });
2458
+ const ensurePolicy = async () => {
2459
+ const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
2460
+ if (!(current?.Policy !== void 0 && canonicalPolicy(JSON.parse(current.Policy)) === canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : input.cdn && input.open.length > 0 ? `policy: TLS only, CloudFront reads ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
2461
+ Bucket,
2462
+ Policy: JSON.stringify(policy)
2463
+ })));
2464
+ };
2465
+ if (isOpen) {
2466
+ await ensureBlock();
2467
+ await ensurePolicy();
2468
+ } else {
2469
+ await ensurePolicy();
2470
+ await ensureBlock();
2471
+ }
2472
+ 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({
2473
+ Bucket,
2474
+ ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
2475
+ })));
2476
+ const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
2477
+ if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
2478
+ Bucket,
2479
+ VersioningConfiguration: { Status: "Enabled" }
2480
+ })));
2481
+ else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
2482
+ Bucket,
2483
+ VersioningConfiguration: { Status: "Suspended" }
2484
+ })));
2485
+ const lifecycle = await read(() => s3.send(new S3.GetBucketLifecycleConfigurationCommand({ Bucket })), ["NoSuchLifecycleConfiguration"]);
2486
+ const merge = mergeLifecycle(lifecycle?.Rules, input.expire);
2487
+ if (merge.changed) await set(merge.describe, () => merge.rules.length > 0 ? s3.send(new S3.PutBucketLifecycleConfigurationCommand({
2488
+ Bucket,
2489
+ LifecycleConfiguration: { Rules: merge.rules }
2490
+ })) : s3.send(new S3.DeleteBucketLifecycleCommand({ Bucket })));
2491
+ const { origins, unresolved } = bucketOrigins({
2492
+ workspace: ctx.workspace,
2493
+ manifest: ctx.manifest,
2494
+ stage: ctx.stage,
2495
+ bucket: id
2496
+ });
2497
+ 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`);
2498
+ if (origins.length === 0) return;
2499
+ const rule = corsRule(origins);
2500
+ const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
2501
+ if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
2502
+ Bucket,
2503
+ CORSConfiguration: { CORSRules: [rule] }
2504
+ })));
2505
+ }
2506
+ function canonicalCors(rule) {
2507
+ const sorted = (list) => [...list ?? []].sort();
2508
+ return JSON.stringify({
2509
+ AllowedMethods: sorted(rule.AllowedMethods),
2510
+ AllowedOrigins: sorted(rule.AllowedOrigins),
2511
+ AllowedHeaders: sorted(rule.AllowedHeaders),
2512
+ ExposeHeaders: sorted(rule.ExposeHeaders),
2513
+ MaxAgeSeconds: rule.MaxAgeSeconds ?? null
2514
+ });
2515
+ }
2516
+ /**
2517
+ * Each provisioned bucket answers `HeadBucket` to the key in the stage's
2518
+ * secrets — the one the apps will use. A bucket whose URL carries no key is
2519
+ * not one this provider wrote, and the deploy's own check covers a URL that
2520
+ * is missing.
2521
+ *
2522
+ * A failure is read by its status, never its name — a `HEAD` has no body,
2523
+ * so SDK v3 calls a 301, 400 or 403 `Unknown` — and the message carries
2524
+ * everything S3 said: status, error, region, request ids.
2525
+ *
2526
+ * @throws {BucketRegionMismatch} the bucket is in another region than its URL says
2527
+ * @throws {ProvisionedBucketUnreachable}
2528
+ */
2529
+ async function verifyS3(ctx) {
2530
+ const S3 = await import("@aws-sdk/client-s3");
2531
+ for (const { id } of bucketConstructs(ctx.manifest)) {
2532
+ const urlKey = provideKey(id, "url");
2533
+ const url = ctx.secrets[urlKey];
2534
+ if (url === void 0) continue;
2535
+ const address = s3Url.parse(url);
2536
+ if (!address.accessKeyId || !address.secretAccessKey) continue;
2537
+ const asked = address.region ?? ctx.config.region ?? "us-east-1";
2538
+ const client = new S3.S3Client({
2539
+ region: asked,
2540
+ credentials: {
2541
+ accessKeyId: address.accessKeyId,
2542
+ secretAccessKey: address.secretAccessKey
2543
+ },
2544
+ ...address.endpoint ? { endpoint: address.endpoint } : {},
2545
+ ...address.forcePathStyle ? { forcePathStyle: true } : {}
2546
+ });
2547
+ try {
2548
+ const issuedAt = issuedJustNow(ctx.resources, id, address.accessKeyId);
2549
+ const { answer: head, waited } = await whileKeyIsNew(await headBucket(S3, client, address.bucket), {
2550
+ issuedAt,
2551
+ refused: (answer) => !answer.ok && answer.status === 403,
2552
+ ask: () => headBucket(S3, client, address.bucket),
2553
+ onWait: () => ctx.log?.(` ${id}: waiting for the new key ${address.accessKeyId} to become active…`)
2554
+ });
2555
+ if (head.ok) continue;
2556
+ const fail = (reason) => new ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, reason);
2557
+ const said = describeAnswer(head);
2558
+ if (head.status === 301 || head.status === 400 && head.region && head.region !== asked) {
2559
+ let where = head.region;
2560
+ let located = "";
2561
+ if (!where) {
2562
+ const location = await bucketLocation(S3, client, address.bucket);
2563
+ if ("region" in location) where = location.region;
2564
+ else located = `; GetBucketLocation answered ${describeAnswer(location.failed)}`;
2565
+ }
2566
+ if (where && where !== asked) throw new BucketRegionMismatch(id, address.bucket, ctx.stage, urlKey, where, address.region, asked, said);
2567
+ throw fail(`S3 redirected the request (${said}${located})`);
2568
+ }
2569
+ if (head.status === 404) throw fail(`it does not exist (${said})`);
2570
+ 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` : ""));
2571
+ throw fail(said);
2572
+ } finally {
2573
+ client.destroy();
2574
+ }
2575
+ }
2576
+ }
2577
+ const s3Provider = {
2578
+ kind: "objects",
2579
+ name: "s3",
2580
+ check: checkS3Config,
2581
+ provisioning: S3_PROVISIONING,
2582
+ credentials: awsProvisioningCredentials,
2583
+ runtimeKeys(manifest) {
2584
+ const watched = bucketWatchers(manifest);
2585
+ return bucketConstructs(manifest).flatMap((b) => [
2586
+ provideKey(b.id, "url"),
2587
+ ...watched.has(b.id) ? [provideKey(b.id, "eventsConnectionString")] : [],
2588
+ ...b.servers.map((s) => provideKey(s.id, "url"))
2589
+ ]);
2590
+ },
2591
+ ensure: ensureS3,
2592
+ verify: verifyS3
2593
+ };
2594
+ //#endregion
2595
+ //#region src/providers/ses/index.ts
2596
+ /**
2597
+ * The `ses` provider: what receives an inbox's mail on a deployed stage.
2598
+ *
2599
+ * `deploy.inbox.<stage> = { provider: 'ses', region? }` has the deploy create,
2600
+ * for each `Inbox`:
2601
+ *
2602
+ * - **its own bucket** — never one the stack or `deploy.objects` runs — by
2603
+ * the steps every bucket of the stage takes (`ensureOwnedBucket`), with SES
2604
+ * allowed to write under `messages/` and an IAM user of its own whose key
2605
+ * is the inbox's `<ID>_URL`;
2606
+ * - **its topic** on SNS, publishable by SES alone, whose `sns://` address —
2607
+ * signed by the same key — is the topic's connection string. The deploy's
2608
+ * push subscriptions for a topic on SNS (`topicPushes`) then subscribe each
2609
+ * inbox subscriber at its worker's route, unfiltered;
2610
+ * - **the stage's domain as an SES identity**, verified through Easy DKIM's
2611
+ * CNAMEs, and **MX records** pointing the domain — or every subdomain of it,
2612
+ * with `subdomains: true` — at the region's inbound endpoint, both through
2613
+ * the stage's DNS;
2614
+ * - **a receipt rule** in the region's *active* rule set: the inbox's
2615
+ * recipients, stored under `messages/` and announced on its topic. Never a
2616
+ * new set made active over another — only one is active per region, and
2617
+ * switching would stop every other stage's and app's rules. A set is made
2618
+ * active only where none is.
2619
+ *
2620
+ * A removed inbox's rule is deleted on the next deploy, by its name; nothing
2621
+ * else this provider did not make is touched.
2622
+ */
2623
+ /**
2624
+ * The regions SES receives mail in, each at `inbound-smtp.<region>.amazonaws.com`
2625
+ * — the AWS General Reference's "Email Receiving endpoints".
2626
+ */
2627
+ const SES_RECEIVING_REGIONS = [
2628
+ "us-east-1",
2629
+ "us-east-2",
2630
+ "us-west-1",
2631
+ "us-west-2",
2632
+ "af-south-1",
2633
+ "ap-southeast-3",
2634
+ "ap-south-1",
2635
+ "ap-northeast-3",
2636
+ "ap-northeast-2",
2637
+ "ap-southeast-1",
2638
+ "ap-southeast-2",
2639
+ "ap-northeast-1",
2640
+ "ca-central-1",
2641
+ "eu-central-1",
2642
+ "eu-west-1",
2643
+ "eu-west-2",
2644
+ "eu-south-1",
2645
+ "eu-west-3",
2646
+ "eu-north-1",
2647
+ "il-central-1",
2648
+ "me-south-1",
2649
+ "sa-east-1"
2650
+ ];
2651
+ /** Where mail for a domain is delivered in `region`: its MX target. */
2652
+ function inboundEndpoint(region) {
2653
+ return `inbound-smtp.${region}.amazonaws.com`;
2654
+ }
2655
+ /** Every inbox in the manifest. */
2656
+ function inboxConstructs(manifest) {
2657
+ return Object.values(manifest).filter((d) => d.kind === "inbox").sort((a, b) => a.id.localeCompare(b.id));
2658
+ }
2659
+ /** The name an inbox's receipt rule has: the prefix it is found by, and its id. */
2660
+ function receiptRuleName(scope, stage, inbox) {
2661
+ return `${rulePrefix(scope, stage)}${appKey(inbox)}`.slice(0, 64);
2662
+ }
2663
+ /** What every rule this stage made is named with. */
2664
+ function rulePrefix(scope, stage) {
2665
+ return `gkm-${scope}-${stage}-`.replace(/[^A-Za-z0-9_.-]/g, "-");
2666
+ }
2667
+ /** The topic SES announces an inbox's mail on: publishable by SES, from this account. */
2668
+ function receiptTopicPolicy(topicArn, account) {
2669
+ return {
2670
+ Version: "2012-10-17",
2671
+ Statement: [{
2672
+ Sid: "GkmSesPublishes",
2673
+ Effect: "Allow",
2674
+ Principal: { Service: "ses.amazonaws.com" },
2675
+ Action: "sns:Publish",
2676
+ Resource: topicArn,
2677
+ Condition: { StringEquals: { "aws:SourceAccount": account } }
2678
+ }]
2679
+ };
2680
+ }
2681
+ const defaultSesClients = async (credential, region) => {
2682
+ const SES = await import("@aws-sdk/client-ses");
2683
+ const config = await awsClientConfig(credential, region);
2684
+ const endpoint = awsEndpoint(process.env, "SES");
2685
+ return {
2686
+ SES,
2687
+ ses: new SES.SESClient({
2688
+ ...config,
2689
+ ...endpoint ? { endpoint } : {}
2690
+ })
2691
+ };
2692
+ };
2693
+ let makeSesClients = defaultSesClients;
2694
+ function errorName(error) {
2695
+ const e = error;
2696
+ return e?.name ?? e?.Code ?? e?.code ?? "";
2697
+ }
2698
+ /** The stage's domain, which every inbox receives on. */
2699
+ function stageDomain(ctx) {
2700
+ const domain = ctx.workspace.domains?.[ctx.stage];
2701
+ if (!domain) throw new NoDomainForStage(ctx.stage);
2702
+ return domain;
2703
+ }
2704
+ async function ensureSes(ctx) {
2705
+ const region = s3Region(ctx);
2706
+ if (!SES_RECEIVING_REGIONS.includes(region)) throw new SesReceivingUnsupported(ctx.stage, region, SES_RECEIVING_REGIONS);
2707
+ const inboxes = inboxConstructs(ctx.manifest);
2708
+ const { SES, ses } = await makeSesClients(ctx.credential, region);
2709
+ try {
2710
+ const ruleSet = await activeRuleSet(ctx, {
2711
+ SES,
2712
+ ses
2713
+ }, inboxes.length > 0);
2714
+ if (inboxes.length > 0) {
2715
+ const domain = stageDomain(ctx);
2716
+ await ensureIdentity(ctx, {
2717
+ SES,
2718
+ ses
2719
+ }, domain);
2720
+ const events = await eventsClients(ctx.credential, region);
2721
+ try {
2722
+ for (const inbox of inboxes) await ensureInbox(ctx, {
2723
+ SES,
2724
+ ses
2725
+ }, events, {
2726
+ inbox,
2727
+ domain,
2728
+ region,
2729
+ ruleSet
2730
+ });
2731
+ } finally {
2732
+ events.sns.destroy();
2733
+ events.sqs.destroy();
2734
+ }
2735
+ await ensureMx(ctx, inboxes, domain, region);
2736
+ }
2737
+ if (ruleSet) await retireRules(ctx, {
2738
+ SES,
2739
+ ses
2740
+ }, ruleSet, inboxes);
2741
+ } finally {
2742
+ ses.destroy();
2743
+ }
2744
+ }
2745
+ /**
2746
+ * The region's active rule set. Made — and made active — only where none is
2747
+ * active and an inbox needs one: activating a set deactivates whichever was.
2748
+ */
2749
+ async function activeRuleSet(ctx, { SES, ses }, needed) {
2750
+ const name = (await ses.send(new SES.DescribeActiveReceiptRuleSetCommand({}))).Metadata?.Name;
2751
+ if (name || !needed) return name;
2752
+ await ctx.change({
2753
+ construct: "inbox",
2754
+ resource: `SES receipt rule set gkm`,
2755
+ change: "create and make active — the region has none"
2756
+ }, async () => {
2757
+ try {
2758
+ await ses.send(new SES.CreateReceiptRuleSetCommand({ RuleSetName: "gkm" }));
2759
+ } catch (error) {
2760
+ if (errorName(error) !== "AlreadyExistsException") throw error;
2761
+ }
2762
+ await ses.send(new SES.SetActiveReceiptRuleSetCommand({ RuleSetName: "gkm" }));
2763
+ });
2764
+ return "gkm";
2765
+ }
2766
+ /**
2767
+ * The stage's domain as an SES identity, verified by Easy DKIM: its three
2768
+ * CNAMEs, through the stage's DNS. Receiving requires a verified domain.
2769
+ */
2770
+ async function ensureIdentity(ctx, { SES, ses }, domain) {
2771
+ let tokens = [];
2772
+ await ctx.change({
2773
+ construct: "inbox",
2774
+ resource: `SES identity ${domain}`,
2775
+ change: "verify with DKIM"
2776
+ }, async () => {
2777
+ tokens = (await ses.send(new SES.VerifyDomainDkimCommand({ Domain: domain }))).DkimTokens ?? [];
2778
+ });
2779
+ if (tokens.length === 0) return;
2780
+ await ctx.writeDns(tokens.map((token) => ({
2781
+ host: `${token}._domainkey.${domain}`,
2782
+ type: "CNAME",
2783
+ value: `${token}.dkim.amazonses.com`
2784
+ })));
2785
+ }
2786
+ /** One inbox: its bucket, its topic and their keys, and its receipt rule. */
2787
+ async function ensureInbox(ctx, { SES, ses }, events, input) {
2788
+ const { inbox, domain, region, ruleSet } = input;
2789
+ const name = `${appKey(inbox.id)}-mail`;
2790
+ const urlKey = provideKey(inbox.id, "url");
2791
+ const topicArn = await ensureTopic(ctx, events, {
2792
+ id: inbox.id,
2793
+ topicName: `gkm-${ctx.identity.scope}-${ctx.stage}-${name}`.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 256),
2794
+ publisher: "SES",
2795
+ policy: (arn) => receiptTopicPolicy(arn, events.account)
2796
+ });
2797
+ const { bucket } = await ensureOwnedBucket(ctx, {
2798
+ id: inbox.id,
2799
+ name,
2800
+ urlKey,
2801
+ sesWrite: {
2802
+ prefix: INBOX_MESSAGES_PREFIX,
2803
+ account: events.account
2804
+ },
2805
+ topicArn
2806
+ });
2807
+ await ensureEventsKey(ctx, {
2808
+ id: inbox.id,
2809
+ topicArn,
2810
+ region,
2811
+ key: provideKey(inbox.topic, "publisherConnectionString"),
2812
+ urlKey
2813
+ });
2814
+ const rule = {
2815
+ Name: receiptRuleName(ctx.identity.scope, ctx.stage, inbox.id),
2816
+ Enabled: true,
2817
+ TlsPolicy: "Optional",
2818
+ ScanEnabled: true,
2819
+ Recipients: receiptRecipients(inbox, domain),
2820
+ Actions: [{ S3Action: {
2821
+ BucketName: bucket,
2822
+ ObjectKeyPrefix: INBOX_MESSAGES_PREFIX,
2823
+ TopicArn: topicArn
2824
+ } }]
2825
+ };
2826
+ const current = await ses.send(new SES.DescribeReceiptRuleCommand({
2827
+ RuleSetName: ruleSet,
2828
+ RuleName: rule.Name
2829
+ })).then((found) => found.Rule, (error) => {
2830
+ if (errorName(error) === "RuleDoesNotExistException") return void 0;
2831
+ throw error;
2832
+ });
2833
+ const entry = {
2834
+ key: `ses-receipt-rule:${inbox.id}`,
2835
+ type: "ses-receipt-rule"
2836
+ };
2837
+ if (current && sameRule(current, rule)) {
2838
+ await ctx.state.ready(entry, rule.Name);
2839
+ return;
2840
+ }
2841
+ await ctx.change({
2842
+ construct: inbox.id,
2843
+ resource: `SES receipt rule ${rule.Name}`,
2844
+ change: current ? `receive at ${rule.Recipients.join(", ")}` : `create, receiving at ${rule.Recipients.join(", ")}`
2845
+ }, async () => {
2846
+ await ctx.state.pending(entry);
2847
+ await ses.send(current ? new SES.UpdateReceiptRuleCommand({
2848
+ RuleSetName: ruleSet,
2849
+ Rule: rule
2850
+ }) : new SES.CreateReceiptRuleCommand({
2851
+ RuleSetName: ruleSet,
2852
+ Rule: rule
2853
+ }));
2854
+ await ctx.state.ready(entry, rule.Name);
2855
+ });
2856
+ }
2857
+ function sameRule(current, wanted) {
2858
+ const s3 = current.Actions?.[0]?.S3Action;
2859
+ const want = wanted.Actions[0].S3Action;
2860
+ return current.Enabled === wanted.Enabled && current.TlsPolicy === wanted.TlsPolicy && current.ScanEnabled === wanted.ScanEnabled && current.Actions?.length === 1 && s3?.BucketName === want.BucketName && s3?.ObjectKeyPrefix === want.ObjectKeyPrefix && s3?.TopicArn === want.TopicArn && [...current.Recipients ?? []].sort().join() === [...wanted.Recipients].sort().join();
2861
+ }
2862
+ /**
2863
+ * MX records for the stage's domain — and, for an inbox on its tenants'
2864
+ * subdomains, for every subdomain — at the region's inbound endpoint.
2865
+ */
2866
+ async function ensureMx(ctx, inboxes, domain, region) {
2867
+ const hosts = /* @__PURE__ */ new Set();
2868
+ for (const inbox of inboxes) hosts.add(inbox.subdomains ? `*.${domain}` : domain);
2869
+ await ctx.writeDns([...hosts].sort().map((host) => ({
2870
+ host,
2871
+ type: "MX",
2872
+ value: inboundEndpoint(region),
2873
+ priority: 10
2874
+ })));
2875
+ }
2876
+ /** Delete the rules this stage made for inboxes no longer declared — only those. */
2877
+ async function retireRules(ctx, { SES, ses }, ruleSet, inboxes) {
2878
+ const prefix = rulePrefix(ctx.identity.scope, ctx.stage);
2879
+ const kept = new Set(inboxes.map((inbox) => receiptRuleName(ctx.identity.scope, ctx.stage, inbox.id)));
2880
+ const set = await ses.send(new SES.DescribeReceiptRuleSetCommand({ RuleSetName: ruleSet }));
2881
+ for (const rule of set.Rules ?? []) {
2882
+ if (!rule.Name?.startsWith(prefix) || kept.has(rule.Name)) continue;
2883
+ await ctx.change({
2884
+ construct: "inbox",
2885
+ resource: `SES receipt rule ${rule.Name}`,
2886
+ change: "delete — its inbox is no longer declared"
2887
+ }, async () => {
2888
+ await ses.send(new SES.DeleteReceiptRuleCommand({
2889
+ RuleSetName: ruleSet,
2890
+ RuleName: rule.Name
2891
+ }));
2892
+ });
2893
+ }
2894
+ }
2895
+ /**
2896
+ * The cheap check every deploy runs: the region receives mail, the stage has
2897
+ * a domain, and each inbox's keys are in the stage's secrets.
2898
+ */
2899
+ async function verifySes(ctx) {
2900
+ const region = s3Region(ctx);
2901
+ if (!SES_RECEIVING_REGIONS.includes(region)) throw new SesReceivingUnsupported(ctx.stage, region, SES_RECEIVING_REGIONS);
2902
+ const inboxes = inboxConstructs(ctx.manifest);
2903
+ if (inboxes.length === 0) return;
2904
+ stageDomain(ctx);
2905
+ for (const inbox of inboxes) {
2906
+ const missing = [provideKey(inbox.id, "url"), provideKey(inbox.topic, "publisherConnectionString")].filter((key) => ctx.secrets[key] === void 0);
2907
+ if (missing.length > 0) throw new InboxNotProvisioned(ctx.stage, inbox.id, missing);
2908
+ }
2909
+ }
2910
+ //#endregion
2911
+ //#region src/providers/registry.ts
2912
+ /**
2913
+ * The providers gkm ships, by kind and name — registered the way a deploy
2914
+ * target's built-ins are (`target/builtins.ts`). A provider from a package is
2915
+ * one more entry here once there is a loading story for it.
2916
+ */
2917
+ const BUILTIN_PROVIDERS = {
2918
+ objects: { s3: s3Provider },
2919
+ inbox: { ses: {
2920
+ kind: "inbox",
2921
+ name: "ses",
2922
+ check: checkSesConfig,
2923
+ provisioning: SES_PROVISIONING,
2924
+ credentials: awsProvisioningCredentials,
2925
+ runtimeKeys(manifest) {
2926
+ return inboxConstructs(manifest).flatMap((inbox) => [provideKey(inbox.id, "url"), provideKey(inbox.topic, "publisherConnectionString")]);
2927
+ },
2928
+ ensure: ensureSes,
2929
+ verify: verifySes
2930
+ } }
2931
+ };
2932
+ /** The provider `kind` names `name`, if gkm has one. */
2933
+ function builtinProvider(kind, name) {
2934
+ return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
2935
+ }
2936
+ //#endregion
2937
+ //#region src/providers/index.ts
2938
+ /** The constructs of a kind: `objects` is every bucket. */
2939
+ function constructsOf(manifest, kind) {
2940
+ return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
2941
+ }
2942
+ /**
2943
+ * What every deploy runs: each provider's `verify()` — the cheap check that
2944
+ * what it created is still there and the stage's key reaches it. Nothing on
2945
+ * the local stage, and nothing for a kind on `external` or `false` — a kind
2946
+ * the stage has none of is the deploy's readiness check's to refuse.
2947
+ */
2948
+ async function verifyStageProviders(input) {
2949
+ const verified = [];
2950
+ for (const kind of PROVIDER_KINDS) {
2951
+ if (constructsOf(input.manifest, kind).length === 0) continue;
2952
+ const choice = stageProvider(input.workspace, kind, input.stage);
2953
+ if (choice.mode !== "provider") continue;
2954
+ const provider = builtinProvider(kind, choice.name);
2955
+ await provider.verify({
2956
+ workspace: input.workspace,
2957
+ manifest: input.manifest,
2958
+ stage: input.stage,
2959
+ config: choice.config,
2960
+ secrets: input.secrets,
2961
+ ...input.resources ? { resources: input.resources } : {},
2962
+ ...input.log ? { log: input.log } : {}
2963
+ });
2964
+ verified.push(`${kind}: ${provider.name}`);
2965
+ }
2966
+ if (await verifyStageBackups(input)) verified.push("backups: s3");
2967
+ return verified;
2968
+ }
2969
+ /**
2970
+ * A stage whose provider creates its resources, and no credentials to create
2971
+ * them with. Raised before anything is created, built or started.
2972
+ */
2973
+ var ProviderCredentialsMissing = class extends GkmError {
2974
+ stage;
2975
+ kind;
2976
+ provider;
2977
+ ids;
2978
+ env;
2979
+ describe;
2980
+ login;
2981
+ constructor(stage, kind, provider, ids, env, describe, login) {
2982
+ 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'.`);
2983
+ this.stage = stage;
2984
+ this.kind = kind;
2985
+ this.provider = provider;
2986
+ this.ids = ids;
2987
+ this.env = env;
2988
+ this.describe = describe;
2989
+ this.login = login;
2990
+ this.name = "ProviderCredentialsMissing";
2991
+ }
2992
+ };
2993
+ /**
2994
+ * `ensure()` for every provider the stage configures — find or create, fix
2995
+ * drift, record in the stage's state, write the runtime keys into its
2996
+ * secrets. Run by the deploy, which holds the stage's lock. A provider with
2997
+ * no provisioning credentials stops the run with
2998
+ * {@link ProviderCredentialsMissing} before anything is created.
2999
+ */
3000
+ async function provisionStage(options) {
3001
+ const { workspace, stage, manifest } = options;
3002
+ const dryRun = options.dryRun === true;
3003
+ const env = options.env ?? process.env;
3004
+ const log = options.log ?? ((line) => console.log(line));
3005
+ const reports = [];
3006
+ const configured = [];
3007
+ for (const kind of PROVIDER_KINDS) {
3008
+ const choice = stageProvider(workspace, kind, stage);
3009
+ if (choice.mode !== "provider") {
3010
+ reports.push({
3011
+ kind,
3012
+ mode: choice.mode,
3013
+ actions: [],
3014
+ planned: []
3015
+ });
3016
+ continue;
3017
+ }
3018
+ const provider = builtinProvider(kind, choice.name);
3019
+ const report = {
3020
+ kind,
3021
+ mode: "provider",
3022
+ provider: provider.name,
3023
+ actions: [],
3024
+ planned: []
3025
+ };
3026
+ reports.push(report);
3027
+ const ids = constructsOf(manifest, kind);
3028
+ const credential = await provider.credentials({
3029
+ stage,
3030
+ env,
3031
+ ...options.profile ? { profile: options.profile } : {},
3032
+ ...options.home ? { home: options.home } : {}
3033
+ });
3034
+ if (ids.length === 0 && credential === void 0) continue;
3035
+ if (credential === void 0) throw new ProviderCredentialsMissing(stage, kind, provider.name, ids, provider.provisioning.env, provider.provisioning.describe, provider.provisioning.login);
3036
+ configured.push({
3037
+ kind,
3038
+ provider,
3039
+ config: choice.config,
3040
+ credential,
3041
+ report
3042
+ });
3043
+ }
3044
+ const backups = stageBackups(workspace, manifest, stage);
3045
+ if (configured.length === 0 && backups.mode !== "on") {
3046
+ if (backups.mode === "disabled") log(`💾 backups: off — deploy.backups.${stage} is false. Nothing is backed up, and nothing already backed up is deleted.`);
3047
+ return reports;
3048
+ }
3049
+ const identity = deployIdentity(workspace, stage);
3050
+ let secrets = (await options.secrets.read())?.custom ?? {};
3051
+ for (const entry of configured) entry.report.planned = entry.provider.runtimeKeys(manifest).filter((key) => secrets[key] === void 0);
3052
+ const state = dryRun ? await readOnlyState(options.state, stage) : journalState(await DeployJournal.open(options.state, stage, () => deploysWithCompose(workspace) ? createComposeState(stage) : createEmptyState(stage, "", "")));
3053
+ const writeSecrets = async (values) => {
3054
+ if (dryRun) return;
3055
+ const stored = await options.secrets.read() ?? initStageSecrets(stage);
3056
+ const next = {
3057
+ ...stored,
3058
+ custom: {
3059
+ ...stored.custom,
3060
+ ...values
3061
+ },
3062
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3063
+ };
3064
+ await options.secrets.write(next);
3065
+ secrets = next.custom;
3066
+ };
3067
+ for (const entry of configured) {
3068
+ log(`☁️ ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
3069
+ await entry.provider.ensure({
3070
+ workspace,
3071
+ manifest,
3072
+ ...options.subscribers ? { subscribers: options.subscribers } : {},
3073
+ stage,
3074
+ identity,
3075
+ config: entry.config,
3076
+ credential: entry.credential,
3077
+ get secrets() {
3078
+ return secrets;
3079
+ },
3080
+ state,
3081
+ dryRun,
3082
+ rotateKeys: options.rotateKeys === true,
3083
+ retireOldKeys: options.retireOldKeys === true,
3084
+ async change(action, apply) {
3085
+ if (!dryRun) await apply();
3086
+ entry.report.actions.push(action);
3087
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
3088
+ },
3089
+ writeSecrets,
3090
+ writeDns: (records) => writeProviderDns(records, {
3091
+ workspace,
3092
+ stage,
3093
+ dryRun,
3094
+ credentials: options.credentials ?? storedCredentials({
3095
+ env,
3096
+ ...options.home ? { home: options.home } : {}
3097
+ }),
3098
+ ...options.dnsProviderFor ? { providerFor: options.dnsProviderFor } : {},
3099
+ log
3100
+ }),
3101
+ log
3102
+ });
3103
+ if (entry.report.actions.length === 0) log(" up to date");
3104
+ }
3105
+ if (backups.mode === "on" || backups.mode === "disabled") {
3106
+ const report = {
3107
+ kind: "backups",
3108
+ mode: backups.mode === "on" ? "provider" : "none",
3109
+ actions: [],
3110
+ planned: backups.mode === "on" && secrets["BACKUPS_URL"] === void 0 ? [BACKUPS_URL_KEY] : []
3111
+ };
3112
+ reports.push(report);
3113
+ await ensureStageBackups({
3114
+ workspace,
3115
+ manifest,
3116
+ stage,
3117
+ ...options.profile ? { profile: options.profile } : {},
3118
+ ...options.home ? { home: options.home } : {},
3119
+ env,
3120
+ ctx: {
3121
+ identity,
3122
+ stage,
3123
+ state,
3124
+ dryRun,
3125
+ get secrets() {
3126
+ return secrets;
3127
+ },
3128
+ rotateKeys: options.rotateKeys === true,
3129
+ retireOldKeys: options.retireOldKeys === true,
3130
+ async change(action, apply) {
3131
+ if (!dryRun) await apply();
3132
+ report.actions.push(action);
3133
+ log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
3134
+ },
3135
+ writeSecrets,
3136
+ log
3137
+ }
3138
+ });
3139
+ if (backups.mode === "on" && report.actions.length === 0) log(" up to date");
3140
+ }
3141
+ return reports;
3142
+ }
3143
+ /** The journal as `ensure()` sees it. */
3144
+ function journalState(journal) {
3145
+ return {
3146
+ record: (key) => journal.record(key),
3147
+ pending: (entry) => journal.pending(entry),
3148
+ ready: (entry, id) => journal.ready(entry, id),
3149
+ lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
3150
+ };
3151
+ }
3152
+ /** What a dry run reads, and the writes it does not make. */
3153
+ async function readOnlyState(store, stage) {
3154
+ const stored = await store.read(stage);
3155
+ return {
3156
+ record: (key) => stored?.resources[key],
3157
+ pending: async () => {},
3158
+ ready: async () => {},
3159
+ ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
3160
+ };
3161
+ }
3162
+ //#endregion
3163
+ //#region src/secrets/stale.ts
3164
+ /**
3165
+ * Stored secrets an older gkm generated that now shadow a derived value.
3166
+ *
3167
+ * Before constructs, initialising a stage wrote an address for each app into
3168
+ * its custom secrets: `<APP>_DATABASE_URL` as a `postgresql://…@localhost`
3169
+ * URL with a password of its own, and `http://localhost:<port>` for a site or
3170
+ * an auth server. Those keys are now a construct's — `database.schema('AuthDatabase')`
3171
+ * provides `AUTH_DATABASE_URL`, `new BetterAuth('Auth')` provides `AUTH_URL`
3172
+ * — and a deploy derives them. A value the stage holds is a value set by hand,
3173
+ * and set by hand wins: the container is handed `localhost`, where nothing
3174
+ * answers, with a password no role has.
3175
+ *
3176
+ * So a deploy refuses such a stage rather than run it, naming each key and
3177
+ * the command that removes it. Nothing is deleted for the user: the value is
3178
+ * theirs, and only they can say it is stale. A URL that names a real host — a
3179
+ * managed database — is a deliberate choice and still wins.
3180
+ */
3181
+ /** The kinds whose URL an older gkm wrote into a stage's secrets. */
3182
+ const ADDRESSED = /* @__PURE__ */ new Set([
3183
+ "database",
3184
+ "database-reader",
3185
+ "database-schema",
3186
+ "rest-api",
3187
+ "site"
3188
+ ]);
3189
+ /** Hosts that are this machine — never anything, inside a container. */
3190
+ const LOOPBACK = /* @__PURE__ */ new Set([
3191
+ "localhost",
3192
+ "127.0.0.1",
3193
+ "[::1]",
3194
+ "::1"
3195
+ ]);
3196
+ /**
3197
+ * A stage holds a construct's address as a custom secret, pointing at
3198
+ * `localhost` — what an older `gkm secrets:init`, `gkm setup` or `gkm init`
3199
+ * generated. Set by hand wins over derived, so the app would be handed it.
3200
+ */
3201
+ var StaleStageSecrets = class extends GkmError {
3202
+ stage;
3203
+ stale;
3204
+ constructor(stage, stale) {
3205
+ const one = stale.length === 1;
3206
+ 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") + `
3207
+ 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.");
3208
+ this.stage = stage;
3209
+ this.stale = stale;
3210
+ this.name = "StaleStageSecrets";
3211
+ }
3212
+ };
3213
+ /** The host a stored value names, if it is a URL. */
3214
+ function hostOf(value) {
3215
+ try {
3216
+ return new URL(value).hostname;
3217
+ } catch {
3218
+ return;
3219
+ }
3220
+ }
3221
+ /**
3222
+ * Each stored key that a construct provides an address for, holding an
3223
+ * address on this machine.
3224
+ */
3225
+ function staleStageSecrets(manifest, supplied) {
3226
+ const stale = [];
3227
+ for (const [id, declaration] of Object.entries(manifest)) {
3228
+ if (!ADDRESSED.has(declaration.kind)) continue;
3229
+ const key = providedKeyFor(id, declaration.kind, "url");
3230
+ const value = supplied[key];
3231
+ if (value === void 0) continue;
3232
+ const host = hostOf(value);
3233
+ if (host === void 0 || !LOOPBACK.has(host)) continue;
3234
+ stale.push({
3235
+ key,
3236
+ construct: id,
3237
+ host
3238
+ });
3239
+ }
3240
+ return stale.sort((a, b) => a.key.localeCompare(b.key));
3241
+ }
3242
+ /**
3243
+ * Refuse a stage whose stored secrets would shadow a construct's address with
3244
+ * `localhost`.
3245
+ *
3246
+ * @throws {StaleStageSecrets} naming each key and the command removing it
3247
+ */
3248
+ function assertNoStaleSecrets(options) {
3249
+ const stale = staleStageSecrets(options.manifest, options.supplied);
3250
+ if (stale.length > 0) throw new StaleStageSecrets(options.stage, stale);
3251
+ }
3252
+ //#endregion
3253
+ //#region src/deploy/readiness.ts
3254
+ /**
3255
+ * Whether a stage is ready to be deployed: the one check, run once by every
3256
+ * deploy through a server target — after the stage's providers have created
3257
+ * what they create and written its keys, and before the target touches
3258
+ * anything.
3259
+ *
3260
+ * A build is not a deploy. Images carry no stage's keys, so a build-only run
3261
+ * (`gkm compose --build --push`) never calls this: a key the deploy itself
3262
+ * writes — a provider's bucket URL — is not there yet when CI builds, and
3263
+ * must not stop the build.
3264
+ */
3265
+ /**
3266
+ * The stage has every key it needs, read from its secrets as the providers
3267
+ * left them:
3268
+ *
3269
+ * 1. no kind it declares is one the stage set to `false`;
3270
+ * 2. its mail and storage are its own — or a dev service, where allowed,
3271
+ * reported once, loudly;
3272
+ * 3. what its providers created is still there, and its key reaches it;
3273
+ * 4. no key holds an address an older gkm stored for what a construct now
3274
+ * provides;
3275
+ * 5. each third party's credentials match their construct's schema.
3276
+ *
3277
+ * The local stage derives its mail and storage, so only 4 and 5 apply to it.
3278
+ *
3279
+ * @throws {StageProviderDisabled}
3280
+ * @throws {ExternalServicesNotConfigured} naming every missing key at once
3281
+ * @throws {StaleStageSecrets}
3282
+ * @throws {CredentialsInvalid}
3283
+ */
3284
+ async function assertStageReady(ctx) {
3285
+ const { workspace, manifest, stage } = ctx;
3286
+ const supplied = (await ctx.secrets.read())?.custom ?? {};
3287
+ if (stage !== workspace.stages.local) {
3288
+ assertStageProvidersEnabled(workspace, manifest, stage);
3289
+ const domain = workspace.domains?.[stage];
3290
+ const services = externalServices({
3291
+ stage,
3292
+ declarations: stageServiceDeclarations({ manifest }),
3293
+ supplied,
3294
+ allow: ctx.allowDevServices,
3295
+ ...domain ? { domain } : {},
3296
+ providers: stageProviderNotes(workspace, stage)
3297
+ });
3298
+ if (services.missing.length > 0) throw new ExternalServicesNotConfigured(stage, services.missing);
3299
+ reportDevServices(ctx, devServicesUsed(services));
3300
+ const verified = await verifyStageProviders({
3301
+ workspace,
3302
+ manifest,
3303
+ stage,
3304
+ secrets: supplied,
3305
+ resources: (await ctx.state.read(stage))?.resources ?? {},
3306
+ log: (line) => ctx.logger.info(line)
3307
+ });
3308
+ for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
3309
+ }
3310
+ assertNoStaleSecrets({
3311
+ manifest,
3312
+ stage,
3313
+ supplied
3314
+ });
3315
+ await assertStageCredentials({
3316
+ root: workspace.root,
3317
+ patterns: constructGlobs(workspace),
3318
+ manifest,
3319
+ stage,
3320
+ supplied
3321
+ });
3322
+ }
3323
+ //#endregion
3324
+ //#region src/deploy/orchestrate.ts
3325
+ /**
3326
+ * The run around a target: what every deploy does whatever it deploys
3327
+ * through.
3328
+ *
3329
+ * It loads the workspace, resolves the target, works out the apps and the
3330
+ * identity, takes the stage's lock, and calls the target's phases in order,
3331
+ * reporting each as it starts, finishes or fails. Everything that is about
3332
+ * *where* the stage goes is the target's.
3333
+ */
3334
+ /** Apps were asked for by name that the workspace does not have. */
3335
+ var UnknownDeployApps = class extends GkmError {
3336
+ apps;
3337
+ available;
3338
+ constructor(apps, available) {
3339
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
3340
+ this.apps = apps;
3341
+ this.available = available;
3342
+ this.name = "UnknownDeployApps";
3343
+ }
3344
+ };
3345
+ /** Every app asked for deploys through some other target. */
3346
+ var NoDeployableApps = class extends GkmError {
3347
+ stage;
3348
+ target;
3349
+ constructor(stage, target) {
3350
+ 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.`);
3351
+ this.stage = stage;
3352
+ this.target = target;
3353
+ this.name = "NoDeployableApps";
3354
+ }
3355
+ };
3356
+ /** A build-only run through a target with no build phase. */
3357
+ var TargetBuildsNothing = class extends GkmError {
3358
+ target;
3359
+ constructor(target) {
3360
+ 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).`);
3361
+ this.target = target;
3362
+ this.name = "TargetBuildsNothing";
3363
+ }
3364
+ };
3365
+ /** A failed rollback, after the failure that called for it. */
3366
+ var RollbackFailed = class extends Error {
3367
+ target;
3368
+ failure;
3369
+ constructor(target, failure, cause) {
3370
+ 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 });
3371
+ this.target = target;
3372
+ this.failure = failure;
3373
+ this.name = "RollbackFailed";
3374
+ }
3375
+ };
3376
+ /**
3377
+ * Generate image tag from stage and timestamp
3378
+ */
3379
+ function generateTag(stage) {
3380
+ return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
3381
+ }
3382
+ /** Why an app that deploys through another target is left out. */
3383
+ function elsewhere(target, stage) {
3384
+ const instead = builtinTarget(target)?.instead?.(stage);
3385
+ if (instead) return `it deploys through "${target}" — ${instead}`;
3386
+ return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
3387
+ }
3388
+ /**
3389
+ * Deploy a workspace's stage through its target.
3390
+ *
3391
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
3392
+ * exits: credentials come from `ctx.credentials`, progress goes to
3393
+ * `ctx.emit` and to `output`, and every failure is thrown.
3394
+ *
3395
+ * @internal
3396
+ */
3397
+ async function runDeploy(source, request, ctx) {
3398
+ const { stage } = request;
3399
+ const redactor = ctx.redactor ?? new Redactor();
3400
+ const emit = (event) => ctx.emit(event.type === "log" ? {
3401
+ ...event,
3402
+ message: redactor.redact(event.message)
3403
+ } : event);
3404
+ /** Run one phase between its events. */
3405
+ const phase = async (name, body) => {
3406
+ ctx.signal?.throwIfAborted();
3407
+ emit({
3408
+ type: "phase.started",
3409
+ phase: name
3410
+ });
3411
+ try {
3412
+ const value = await body();
3413
+ emit({
3414
+ type: "phase.finished",
3415
+ phase: name
3416
+ });
3417
+ return value;
3418
+ } catch (error) {
3419
+ emit({
3420
+ type: "phase.failed",
3421
+ phase: name,
3422
+ error: eventError(error)
3423
+ });
3424
+ throw error;
3425
+ }
3426
+ };
3427
+ ctx.signal?.throwIfAborted();
3428
+ emit({
3429
+ type: "phase.started",
3430
+ phase: "validate"
3431
+ });
3432
+ let prepared;
3433
+ try {
3434
+ prepared = await prepare(source, request, ctx, emit, redactor);
3435
+ } catch (error) {
3436
+ emit({
3437
+ type: "phase.failed",
3438
+ phase: "validate",
3439
+ error: eventError(error)
3440
+ });
3441
+ throw error;
3442
+ }
3443
+ const { resolved, phaseCtx, store } = prepared;
3444
+ const { target } = resolved;
3445
+ const resources = !ctx.buildOnly && phaseCtx.stage !== phaseCtx.workspace.stages.local;
3446
+ const provision = async () => {
3447
+ if (!request.skipDns && resolved.target.runtime === "server") try {
3448
+ await dnsCredentials(phaseCtx.stage, stageDnsDomains(phaseCtx.stage, phaseCtx.workspace.domains, phaseCtx.workspace.dns), ctx.credentials);
3449
+ } catch (error) {
3450
+ emit({
3451
+ type: "phase.failed",
3452
+ phase: "validate",
3453
+ error: eventError(error)
3454
+ });
3455
+ throw error;
3456
+ }
3457
+ await provisionResources(phaseCtx, request, ctx, store, emit);
3458
+ };
3459
+ if (ctx.dryRun) {
3460
+ if (resources) await provision();
3461
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
3462
+ await phase("plan", () => target.plan(phaseCtx, run));
3463
+ return target.result(phaseCtx, run);
3464
+ }
3465
+ if (ctx.buildOnly) {
3466
+ if (!target.build) throw new TargetBuildsNothing(resolved.name);
3467
+ const run = await validate(phaseCtx, emit, () => target.validate(phaseCtx));
3468
+ await phase("build", () => target.build(phaseCtx, run));
3469
+ return target.result(phaseCtx, run);
3470
+ }
3471
+ let lock;
3472
+ try {
3473
+ assertStateOutlivesRun(phaseCtx.workspace, stage, "deploy");
3474
+ lock = await store.lock(stage, { operation: "deploy" });
3475
+ } catch (error) {
3476
+ emit({
3477
+ type: "phase.failed",
3478
+ phase: "validate",
3479
+ error: eventError(error)
3480
+ });
3481
+ throw error;
3482
+ }
3483
+ try {
3484
+ try {
3485
+ await assertStateRoom(store, stage);
3486
+ } catch (error) {
3487
+ emit({
3488
+ type: "phase.failed",
3489
+ phase: "validate",
3490
+ error: eventError(error)
3491
+ });
3492
+ throw error;
3493
+ }
3494
+ if (resources) await provision();
3495
+ const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
3496
+ if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
3497
+ if (target.build) await phase("build", () => target.build(phaseCtx, run));
3498
+ let releasing = "release";
3499
+ try {
3500
+ await phase("release", () => target.release(phaseCtx, run));
3501
+ releasing = "verify";
3502
+ if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
3503
+ } catch (error) {
3504
+ if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
3505
+ if (!target.rollback) throw error;
3506
+ try {
3507
+ await phase("rollback", () => target.rollback(phaseCtx, run, {
3508
+ phase: releasing,
3509
+ error
3510
+ }));
3511
+ } catch (rollbackError) {
3512
+ throw new RollbackFailed(resolved.name, error, rollbackError);
3513
+ }
3514
+ throw error;
3515
+ }
3516
+ return await target.result(phaseCtx, run);
3517
+ } finally {
3518
+ await lock.release();
3519
+ }
3520
+ }
3521
+ /**
3522
+ * The stage's providers, run inside the validate phase. A dry run plans them
3523
+ * and, so the checks after it see the stage as the run would leave it, reads
3524
+ * the keys they would write as placeholders.
3525
+ */
3526
+ async function provisionResources(phaseCtx, request, ctx, store, emit) {
3527
+ try {
3528
+ const reports = await provisionStage({
3529
+ workspace: phaseCtx.workspace,
3530
+ stage: phaseCtx.stage,
3531
+ manifest: phaseCtx.manifest,
3532
+ ...phaseCtx.subscribers ? { subscribers: phaseCtx.subscribers } : {},
3533
+ secrets: phaseCtx.secrets,
3534
+ state: store,
3535
+ dryRun: ctx.dryRun,
3536
+ ...request.rotateKeys ? { rotateKeys: true } : {},
3537
+ ...request.retireOldKeys ? { retireOldKeys: true } : {},
3538
+ ...ctx.home ? { home: ctx.home } : {},
3539
+ credentials: ctx.credentials,
3540
+ log: (line) => phaseCtx.logger.info(line)
3541
+ });
3542
+ if (!ctx.dryRun) return;
3543
+ const planned = reports.flatMap((r) => r.planned);
3544
+ if (planned.length === 0) return;
3545
+ const secrets = phaseCtx.secrets;
3546
+ phaseCtx.secrets = {
3547
+ ...secrets,
3548
+ async read() {
3549
+ const stored = await secrets.read() ?? initStageSecrets(phaseCtx.stage);
3550
+ const custom = { ...stored.custom };
3551
+ for (const key of planned) custom[key] ??= PLANNED_BY_THE_DEPLOY;
3552
+ return {
3553
+ ...stored,
3554
+ custom
3555
+ };
3556
+ }
3557
+ };
3558
+ } catch (error) {
3559
+ emit({
3560
+ type: "phase.failed",
3561
+ phase: "validate",
3562
+ error: eventError(error)
3563
+ });
3564
+ throw error;
3565
+ }
3566
+ }
3567
+ /** What a dry run reads for a key its providers would write. */
3568
+ const PLANNED_BY_THE_DEPLOY = "s3://planned-by-this-deploy";
3569
+ /**
3570
+ * What a deploy validates: the stage ready to be deployed — every key it
3571
+ * needs, read as its providers left them — then what the target would run,
3572
+ * then whatever only the target checks. A build-only run validates the
3573
+ * target's run alone: it calls neither readiness check.
3574
+ */
3575
+ async function readyToDeploy(target, phaseCtx) {
3576
+ if (target.runtime === "server") await assertStageReady(phaseCtx);
3577
+ const run = await target.validate(phaseCtx);
3578
+ await target.ready?.(phaseCtx, run);
3579
+ return run;
3580
+ }
3581
+ /** `body`, then the run's `deploy.started`, inside the validate phase. */
3582
+ async function validate(phaseCtx, emit, body) {
3583
+ try {
3584
+ const run = await body();
3585
+ const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
3586
+ emit({
3587
+ type: "deploy.started",
3588
+ stage: phaseCtx.stage,
3589
+ target: phaseCtx.target,
3590
+ identity: phaseCtx.identity.key,
3591
+ tag: phaseCtx.tag,
3592
+ apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
3593
+ dryRun: phaseCtx.dryRun
3594
+ });
3595
+ emit({
3596
+ type: "phase.finished",
3597
+ phase: "validate"
3598
+ });
3599
+ return run;
3600
+ } catch (error) {
3601
+ emit({
3602
+ type: "phase.failed",
3603
+ phase: "validate",
3604
+ error: eventError(error)
3605
+ });
3606
+ throw error;
3607
+ }
3608
+ }
3609
+ /** Everything the phases are handed, worked out before the first of them. */
3610
+ async function prepare(source, request, ctx, emit, redactor) {
3611
+ const { stage } = request;
3612
+ const configured = typeof source === "function" ? await source() : source;
3613
+ const local = stage === configured.stages.local;
3614
+ if (!local) assertDeployedStage(configured.stages, stage);
3615
+ const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
3616
+ const resolved = await resolveTarget(targetName, {
3617
+ workspace: configured,
3618
+ stage,
3619
+ ...ctx.targets ? { host: ctx.targets } : {}
3620
+ });
3621
+ if (local && !resolved.target.capabilities.localStage) assertDeployedStage(configured.stages, stage);
3622
+ const options = await parseTargetOptions(resolved);
3623
+ const allowDevServices = request.allowDevServices === true;
3624
+ if (allowDevServices && resolved.target.runtime === "aws") throw new DevServicesNeedServerTarget(targetName);
3625
+ const background = {};
3626
+ const subscribers = {};
3627
+ const manifest = await discover({
3628
+ patterns: constructGlobs(configured),
3629
+ cwd: configured.root,
3630
+ background,
3631
+ subscribers
3632
+ });
3633
+ resolveStageTelemetry({
3634
+ ...configured.deploy?.telemetry ? { telemetry: configured.deploy.telemetry } : {},
3635
+ stage,
3636
+ local,
3637
+ target: targetName,
3638
+ runtime: resolved.target.runtime,
3639
+ selfHosted: resolved.target.capabilities.selfHostedTelemetry === true,
3640
+ used: usesTelemetry(manifest)
3641
+ });
3642
+ const units = derivedApps(manifest, configured);
3643
+ const workspace = Object.keys(units).length > 0 ? {
3644
+ ...configured,
3645
+ apps: units
3646
+ } : configured;
3647
+ const identity = deployIdentity(workspace, stage);
3648
+ const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
3649
+ cwd: workspace.root,
3650
+ stage
3651
+ }) : generateTag(stage));
3652
+ const buildOrder = getAppBuildOrder(workspace);
3653
+ let selected = buildOrder;
3654
+ if (request.apps && request.apps.length > 0) {
3655
+ const unknown = request.apps.filter((name) => !workspace.apps[name]);
3656
+ if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
3657
+ selected = buildOrder.filter((name) => request.apps.includes(name));
3658
+ }
3659
+ const skipped = [];
3660
+ const skip = (app, reason) => {
3661
+ skipped.push({
3662
+ app,
3663
+ reason
3664
+ });
3665
+ emit({
3666
+ type: "app.skipped",
3667
+ app,
3668
+ reason
3669
+ });
3670
+ };
3671
+ const byDefault = configured.deploy?.default ?? "dokploy";
3672
+ const apps = selected.filter((name) => {
3673
+ const own = workspace.apps[name].resolvedDeployTarget;
3674
+ const deploysThrough = own === byDefault ? targetName : own;
3675
+ if (deploysThrough === targetName) return true;
3676
+ skip(name, elsewhere(deploysThrough, stage));
3677
+ return false;
3678
+ });
3679
+ if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
3680
+ assertSitePasswords(configured, manifest, stage, apps, resolved.target.name);
3681
+ const store = await createStateStore({
3682
+ config: stage === workspace.stages.local ? void 0 : workspace.state,
3683
+ workspaceRoot: workspace.root,
3684
+ workspaceName: workspace.name,
3685
+ namespace: workspace.deploy?.namespace
3686
+ });
3687
+ const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
3688
+ const line = (level) => (message) => emit({
3689
+ type: "log",
3690
+ level,
3691
+ message
3692
+ });
3693
+ const logger = {
3694
+ info: line("info"),
3695
+ warn: line("warn"),
3696
+ error: line("error")
3697
+ };
3698
+ return {
3699
+ resolved,
3700
+ phaseCtx: {
3701
+ target: targetName,
3702
+ cwd: workspace.root,
3703
+ stage,
3704
+ tag,
3705
+ tagGiven: request.tag !== void 0,
3706
+ apps,
3707
+ skipped,
3708
+ identity,
3709
+ workspace,
3710
+ manifest,
3711
+ background,
3712
+ subscribers,
3713
+ options,
3714
+ dryRun: ctx.dryRun,
3715
+ atomic: request.atomic ?? false,
3716
+ allowDevServices,
3717
+ ...request.skipDns ? { skipDns: true } : {},
3718
+ credentials: ctx.credentials,
3719
+ state: store,
3720
+ secrets,
3721
+ logger,
3722
+ signal: ctx.signal ?? new AbortController().signal,
3723
+ childOutput: ctx.childOutput ?? "inherit",
3724
+ emit,
3725
+ skip,
3726
+ name: (resource) => applicationName(identity, resource)
3727
+ },
3728
+ store
3729
+ };
3730
+ }
3731
+ //#endregion
3732
+ //#region src/deploy/deploy.ts
3733
+ /**
3734
+ * `deploy()`: a deploy as a library call.
3735
+ *
3736
+ * `gkm deploy` could only be driven from an interactive terminal: it prompted
3737
+ * for what it lacked and exited the process on failure, worked out of
3738
+ * `process.cwd()`, and reported progress by printing. Here the caller says
3739
+ * where the project is, hands over the credentials and a signal, and gets back
3740
+ * a run — events to iterate while it goes, and a structured result at the end.
3741
+ * Nothing below this asks a person anything or ends the process; `gkm deploy`
3742
+ * is a thin wrapper that does both.
3743
+ */
3744
+ /**
3745
+ * Every event a run emits, kept so that each iteration — however late it
3746
+ * starts — sees the run from its first event to its last.
3747
+ */
3748
+ var EventLog = class {
3749
+ events = [];
3750
+ closed = false;
3751
+ waiting = [];
3752
+ push(event) {
3753
+ this.events.push(event);
3754
+ this.wake();
3755
+ }
3756
+ close() {
3757
+ this.closed = true;
3758
+ this.wake();
3759
+ }
3760
+ wake() {
3761
+ const waiting = this.waiting;
3762
+ this.waiting = [];
3763
+ for (const resume of waiting) resume();
3764
+ }
3765
+ async *iterate() {
3766
+ let next = 0;
3767
+ while (true) if (next < this.events.length) yield this.events[next++];
3768
+ else if (this.closed) return;
3769
+ else await new Promise((resume) => this.waiting.push(resume));
3770
+ }
3771
+ };
3772
+ function forward(logger, level, message) {
3773
+ if (!logger) return;
3774
+ if (level === "info") logger.info(message);
3775
+ else if (level === "error" && logger.error) logger.error(message);
3776
+ else logger.warn(message);
3777
+ }
3778
+ /**
3779
+ * Deploy a project's stage.
3780
+ *
3781
+ * ```ts
3782
+ * import { deploy } from '@geekmidas/cli/deploy';
3783
+ *
3784
+ * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
3785
+ * for await (const event of run) {
3786
+ * if (event.type === 'app.deployed') console.log(event.app, event.url);
3787
+ * }
3788
+ * const result = await run.result;
3789
+ * ```
3790
+ *
3791
+ * The run starts at once; iterating it is optional, and an iteration started
3792
+ * late still sees every event from the first.
3793
+ */
3794
+ function deploy(input) {
3795
+ const log = new EventLog();
3796
+ const redactor = new Redactor();
3797
+ const emit = (event) => {
3798
+ const masked = event.type === "log" ? {
3799
+ ...event,
3800
+ message: redactor.redact(event.message)
3801
+ } : event;
3802
+ log.push(masked);
3803
+ if (masked.type === "log") forward(input.logger, masked.level, masked.message);
3804
+ };
3805
+ const ctx = {
3806
+ emit,
3807
+ credentials: input.credentials ?? storedCredentials({ home: input.home ?? gkmHome() }),
3808
+ dryRun: input.dryRun ?? false,
3809
+ ...input.buildOnly ? { buildOnly: true } : {},
3810
+ home: input.home ?? gkmHome(),
3811
+ redactor,
3812
+ ...input.signal ? { signal: input.signal } : {},
3813
+ ...input.childOutput ? { childOutput: input.childOutput } : {},
3814
+ ...input.targets ? { targets: input.targets } : {}
3815
+ };
3816
+ const result = withOutput((level, message) => emit({
3817
+ type: "log",
3818
+ level,
3819
+ message
3820
+ }), async () => {
3821
+ try {
3822
+ input.signal?.throwIfAborted();
3823
+ const root = findWorkspaceRoot(resolve(input.cwd));
3824
+ const sandbox = input.sandbox ?? new LocalSandbox({ root });
3825
+ const inRun = (fn) => input.config ? withLoadedConfig(root, input.config, fn) : fn();
3826
+ const deployed = await inRun(() => withSandbox(sandbox, () => runDeploy(() => load(input, sandbox), {
3827
+ stage: input.stage,
3828
+ ...input.target ? { target: input.target } : {},
3829
+ ...input.tag ? { tag: input.tag } : {},
3830
+ ...input.apps ? { apps: input.apps } : {},
3831
+ ...input.atomic ? { atomic: true } : {},
3832
+ ...input.allowDevServices ? { allowDevServices: input.allowDevServices } : {},
3833
+ ...input.skipDns ? { skipDns: true } : {},
3834
+ ...input.rotateKeys ? { rotateKeys: true } : {},
3835
+ ...input.retireOldKeys ? { retireOldKeys: true } : {}
3836
+ }, ctx)));
3837
+ emit({
3838
+ type: "deploy.finished",
3839
+ result: deployed
3840
+ });
3841
+ return deployed;
3842
+ } catch (error) {
3843
+ emit({
3844
+ type: "deploy.failed",
3845
+ error: eventError(error)
3846
+ });
3847
+ throw error;
3848
+ } finally {
3849
+ log.close();
3850
+ }
3851
+ });
3852
+ result.catch(() => {});
3853
+ return {
3854
+ result,
3855
+ [Symbol.asyncIterator]: () => log.iterate()
3856
+ };
3857
+ }
3858
+ /**
3859
+ * The workspace at `input.cwd`. The stage is checked by the run, once it
3860
+ * knows the target: one that runs on this machine may take the local stage.
3861
+ */
3862
+ async function load(input, sandbox) {
3863
+ const { workspace } = await loadWorkspaceConfig(resolve(input.cwd), { sandbox });
3864
+ return workspace;
3865
+ }
3866
+ //#endregion
3867
+ export { UnknownDeployApps as a, bucketName as c, TargetBuildsNothing as i, iamUserName as l, NoDeployableApps as n, backupsUserName as o, RollbackFailed as r, IAM_USER_PATH as s, deploy as t };
3868
+
3869
+ //# sourceMappingURL=deploy-BI3fHnyb.mjs.map