@geekmidas/cli 10.0.0-alpha.19 → 10.0.0-alpha.190

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