@geekmidas/cli 10.0.0-alpha.18 → 10.0.0-alpha.180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (448) hide show
  1. package/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-B7pQA25B.mjs +124 -0
  11. package/dist/LegacyStateStore-B7pQA25B.mjs.map +1 -0
  12. package/dist/LegacyStateStore-l0hBdv-E.cjs +124 -0
  13. package/dist/LegacyStateStore-l0hBdv-E.cjs.map +1 -0
  14. package/dist/LocalStateStore-CP0UHL85.mjs +167 -0
  15. package/dist/LocalStateStore-CP0UHL85.mjs.map +1 -0
  16. package/dist/LocalStateStore-DEE0Kc_s.cjs +178 -0
  17. package/dist/LocalStateStore-DEE0Kc_s.cjs.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-DE0BNuXc.cjs +222 -0
  23. package/dist/S3StateStore-DE0BNuXc.cjs.map +1 -0
  24. package/dist/S3StateStore-vmxZWMKh.mjs +223 -0
  25. package/dist/S3StateStore-vmxZWMKh.mjs.map +1 -0
  26. package/dist/SSMStateStore-DQyXnX2M.mjs +205 -0
  27. package/dist/SSMStateStore-DQyXnX2M.mjs.map +1 -0
  28. package/dist/SSMStateStore-p4hBdTg3.cjs +204 -0
  29. package/dist/SSMStateStore-p4hBdTg3.cjs.map +1 -0
  30. package/dist/SubscriberGenerator-B3jHf26s.mjs +787 -0
  31. package/dist/SubscriberGenerator-B3jHf26s.mjs.map +1 -0
  32. package/dist/SubscriberGenerator-JhwVlWBS.cjs +852 -0
  33. package/dist/SubscriberGenerator-JhwVlWBS.cjs.map +1 -0
  34. package/dist/add-DEdpKya-.cjs +713 -0
  35. package/dist/add-DEdpKya-.cjs.map +1 -0
  36. package/dist/add-QBvDmVA-.mjs +711 -0
  37. package/dist/add-QBvDmVA-.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/apps-D0LULFmU.mjs +4650 -0
  43. package/dist/apps-D0LULFmU.mjs.map +1 -0
  44. package/dist/apps-qJ5FPJGQ.cjs +5174 -0
  45. package/dist/apps-qJ5FPJGQ.cjs.map +1 -0
  46. package/dist/aws-BXfiWNbi.cjs +108 -0
  47. package/dist/aws-BXfiWNbi.cjs.map +1 -0
  48. package/dist/aws-BjvSTTcE.mjs +97 -0
  49. package/dist/aws-BjvSTTcE.mjs.map +1 -0
  50. package/dist/awsStore-BYYCmXiq.mjs +121 -0
  51. package/dist/awsStore-BYYCmXiq.mjs.map +1 -0
  52. package/dist/awsStore-DKQUElJL.cjs +138 -0
  53. package/dist/awsStore-DKQUElJL.cjs.map +1 -0
  54. package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
  55. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  56. package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
  57. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  58. package/dist/backups/runner.cjs +519 -0
  59. package/dist/backups/runner.cjs.map +1 -0
  60. package/dist/backups/runner.d.cts +102 -0
  61. package/dist/backups/runner.d.cts.map +1 -0
  62. package/dist/backups/runner.d.mts +102 -0
  63. package/dist/backups/runner.d.mts.map +1 -0
  64. package/dist/backups/runner.mjs +506 -0
  65. package/dist/backups/runner.mjs.map +1 -0
  66. package/dist/{bundler-mjqGAvu1.cjs → bundler-BuBCXA0t.cjs} +67 -14
  67. package/dist/bundler-BuBCXA0t.cjs.map +1 -0
  68. package/dist/{bundler-mwH7WOb1.mjs → bundler-DZKdVVKZ.mjs} +68 -15
  69. package/dist/bundler-DZKdVVKZ.mjs.map +1 -0
  70. package/dist/cli-BCGkzaR1.cjs +80 -0
  71. package/dist/cli-BCGkzaR1.cjs.map +1 -0
  72. package/dist/cli-CgEbT00Q.mjs +80 -0
  73. package/dist/cli-CgEbT00Q.mjs.map +1 -0
  74. package/dist/clientTelemetry-BAwj6MOf.d.cts +10 -0
  75. package/dist/clientTelemetry-BAwj6MOf.d.cts.map +1 -0
  76. package/dist/clientTelemetry-CvamPJj_.d.mts +10 -0
  77. package/dist/clientTelemetry-CvamPJj_.d.mts.map +1 -0
  78. package/dist/compose-AO8u4mBI.cjs +3502 -0
  79. package/dist/compose-AO8u4mBI.cjs.map +1 -0
  80. package/dist/compose-C-yjexqX.cjs +2925 -0
  81. package/dist/compose-C-yjexqX.cjs.map +1 -0
  82. package/dist/compose-C23RpAaF.mjs +3389 -0
  83. package/dist/compose-C23RpAaF.mjs.map +1 -0
  84. package/dist/compose-DtfoUChm.mjs +2434 -0
  85. package/dist/compose-DtfoUChm.mjs.map +1 -0
  86. package/dist/config-BODxZemw.d.mts +291 -0
  87. package/dist/config-BODxZemw.d.mts.map +1 -0
  88. package/dist/config-C3U5HulX.d.cts +291 -0
  89. package/dist/config-C3U5HulX.d.cts.map +1 -0
  90. package/dist/config.cjs +457 -9
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -117
  93. package/dist/config.d.mts +4 -117
  94. package/dist/config.mjs +441 -3
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-D_85KW2k.mjs +236 -0
  97. package/dist/credentialSchemas-D_85KW2k.mjs.map +1 -0
  98. package/dist/credentialSchemas-DjK6xKMk.cjs +271 -0
  99. package/dist/credentialSchemas-DjK6xKMk.cjs.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-Bve0zBqT.cjs +154 -0
  105. package/dist/dbTunnel-Bve0zBqT.cjs.map +1 -0
  106. package/dist/dbTunnel-CnubkLBa.mjs +154 -0
  107. package/dist/dbTunnel-CnubkLBa.mjs.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 +211 -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 +144 -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-C2MKxzm9.cjs +3894 -0
  133. package/dist/deploy-C2MKxzm9.cjs.map +1 -0
  134. package/dist/deploy-Qq41vtpm.mjs +3838 -0
  135. package/dist/deploy-Qq41vtpm.mjs.map +1 -0
  136. package/dist/destroy-Bg4IUf_Z.mjs +789 -0
  137. package/dist/destroy-Bg4IUf_Z.mjs.map +1 -0
  138. package/dist/destroy-CCpnHI2v.cjs +790 -0
  139. package/dist/destroy-CCpnHI2v.cjs.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/dns-BAM8VH1v.mjs +1820 -0
  145. package/dist/dns-BAM8VH1v.mjs.map +1 -0
  146. package/dist/dns-D_0z9Tm1.cjs +2257 -0
  147. package/dist/dns-D_0z9Tm1.cjs.map +1 -0
  148. package/dist/docker-6EUbKrEl.cjs +1798 -0
  149. package/dist/docker-6EUbKrEl.cjs.map +1 -0
  150. package/dist/docker-DQoE3Fr7.mjs +1649 -0
  151. package/dist/docker-DQoE3Fr7.mjs.map +1 -0
  152. package/dist/dokploy-BD8NXy8y.cjs +38 -0
  153. package/dist/dokploy-BD8NXy8y.cjs.map +1 -0
  154. package/dist/dokploy-CU9iuc35.mjs +38 -0
  155. package/dist/dokploy-CU9iuc35.mjs.map +1 -0
  156. package/dist/drivers-BQRb3KsL.mjs +294 -0
  157. package/dist/drivers-BQRb3KsL.mjs.map +1 -0
  158. package/dist/drivers-DP7__dJX.cjs +377 -0
  159. package/dist/drivers-DP7__dJX.cjs.map +1 -0
  160. package/dist/eas-BhTOdQrE.cjs +337 -0
  161. package/dist/eas-BhTOdQrE.cjs.map +1 -0
  162. package/dist/eas-iYyg7Xjy.mjs +334 -0
  163. package/dist/eas-iYyg7Xjy.mjs.map +1 -0
  164. package/dist/emit-C4KSXOeS.mjs +153 -0
  165. package/dist/emit-C4KSXOeS.mjs.map +1 -0
  166. package/dist/emit-DiW0kbue.cjs +164 -0
  167. package/dist/emit-DiW0kbue.cjs.map +1 -0
  168. package/dist/encryption-hgmnMZw0.mjs +89 -0
  169. package/dist/encryption-hgmnMZw0.mjs.map +1 -0
  170. package/dist/encryption-yROMpM67.cjs +90 -0
  171. package/dist/encryption-yROMpM67.cjs.map +1 -0
  172. package/dist/engine-B4whsrrE.mjs +3217 -0
  173. package/dist/engine-B4whsrrE.mjs.map +1 -0
  174. package/dist/engine-D0XYdIiE.cjs +3330 -0
  175. package/dist/engine-D0XYdIiE.cjs.map +1 -0
  176. package/dist/errors-C9uIyIDt.mjs +27 -0
  177. package/dist/errors-C9uIyIDt.mjs.map +1 -0
  178. package/dist/errors-D1x8duqI.cjs +38 -0
  179. package/dist/errors-D1x8duqI.cjs.map +1 -0
  180. package/dist/github-CBkZF4PS.mjs +986 -0
  181. package/dist/github-CBkZF4PS.mjs.map +1 -0
  182. package/dist/github-D1-_OnGL.cjs +987 -0
  183. package/dist/github-D1-_OnGL.cjs.map +1 -0
  184. package/dist/googlePlay-Bwv8TVi8.mjs +931 -0
  185. package/dist/googlePlay-Bwv8TVi8.mjs.map +1 -0
  186. package/dist/googlePlay-s9dGfrrb.cjs +931 -0
  187. package/dist/googlePlay-s9dGfrrb.cjs.map +1 -0
  188. package/dist/iam-BzFyFf7T.mjs +442 -0
  189. package/dist/iam-BzFyFf7T.mjs.map +1 -0
  190. package/dist/iam-WIoKnLBp.cjs +521 -0
  191. package/dist/iam-WIoKnLBp.cjs.map +1 -0
  192. package/dist/{index-RCUizGxL.d.cts → index-BKgOlfK2.d.mts} +38 -14
  193. package/dist/index-BKgOlfK2.d.mts.map +1 -0
  194. package/dist/{index-B4H4XF7A.d.mts → index-zPzigXh-.d.cts} +38 -14
  195. package/dist/index-zPzigXh-.d.cts.map +1 -0
  196. package/dist/index.cjs +14502 -12767
  197. package/dist/index.cjs.map +1 -1
  198. package/dist/index.mjs +15137 -13400
  199. package/dist/index.mjs.map +1 -1
  200. package/dist/local-CFnHQgWC.cjs +241 -0
  201. package/dist/local-CFnHQgWC.cjs.map +1 -0
  202. package/dist/local-JOnTFJA5.mjs +224 -0
  203. package/dist/local-JOnTFJA5.mjs.map +1 -0
  204. package/dist/migrate-BtnpQocG.mjs +181 -0
  205. package/dist/migrate-BtnpQocG.mjs.map +1 -0
  206. package/dist/migrate-CGXrmZyV.cjs +272 -0
  207. package/dist/migrate-CGXrmZyV.cjs.map +1 -0
  208. package/dist/migrate-CxWXW-Lw.cjs +181 -0
  209. package/dist/migrate-CxWXW-Lw.cjs.map +1 -0
  210. package/dist/migrate-fLIgSpPB.mjs +267 -0
  211. package/dist/migrate-fLIgSpPB.mjs.map +1 -0
  212. package/dist/next.cjs +59 -0
  213. package/dist/next.cjs.map +1 -0
  214. package/dist/next.d.cts +44 -0
  215. package/dist/next.d.cts.map +1 -0
  216. package/dist/next.d.mts +44 -0
  217. package/dist/next.d.mts.map +1 -0
  218. package/dist/next.mjs +58 -0
  219. package/dist/next.mjs.map +1 -0
  220. package/dist/notes-ChYPaRLu.cjs +510 -0
  221. package/dist/notes-ChYPaRLu.cjs.map +1 -0
  222. package/dist/notes-LATU2vLI.mjs +409 -0
  223. package/dist/notes-LATU2vLI.mjs.map +1 -0
  224. package/dist/openapi.cjs +213 -7
  225. package/dist/openapi.cjs.map +1 -0
  226. package/dist/openapi.d.cts +27 -8
  227. package/dist/openapi.d.cts.map +1 -1
  228. package/dist/openapi.d.mts +27 -8
  229. package/dist/openapi.d.mts.map +1 -1
  230. package/dist/openapi.mjs +208 -2
  231. package/dist/openapi.mjs.map +1 -0
  232. package/dist/projectBucket-BIeh2HTj.cjs +263 -0
  233. package/dist/projectBucket-BIeh2HTj.cjs.map +1 -0
  234. package/dist/projectBucket-D_4zb_oh.mjs +222 -0
  235. package/dist/projectBucket-D_4zb_oh.mjs.map +1 -0
  236. package/dist/provider-BvjDbsTR.mjs +46 -0
  237. package/dist/provider-BvjDbsTR.mjs.map +1 -0
  238. package/dist/provider-DLhgo-mB.cjs +57 -0
  239. package/dist/provider-DLhgo-mB.cjs.map +1 -0
  240. package/dist/publish-Dc-1GQp8.cjs +124 -0
  241. package/dist/publish-Dc-1GQp8.cjs.map +1 -0
  242. package/dist/publish-DhzRYhVZ.mjs +123 -0
  243. package/dist/publish-DhzRYhVZ.mjs.map +1 -0
  244. package/dist/ready-BcV28QoW.mjs +375 -0
  245. package/dist/ready-BcV28QoW.mjs.map +1 -0
  246. package/dist/ready-ByQvw4-W.cjs +404 -0
  247. package/dist/ready-ByQvw4-W.cjs.map +1 -0
  248. package/dist/reconcile/public.cjs +3 -5
  249. package/dist/reconcile/public.d.cts +33 -89
  250. package/dist/reconcile/public.d.cts.map +1 -1
  251. package/dist/reconcile/public.d.mts +33 -89
  252. package/dist/reconcile/public.d.mts.map +1 -1
  253. package/dist/reconcile/public.mjs +3 -3
  254. package/dist/reconcile--I7V4Klj.mjs +34 -0
  255. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  256. package/dist/reconcile-CuCQBa5-.cjs +34 -0
  257. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  258. package/dist/resolve-CJvM2bUx.mjs +263 -0
  259. package/dist/resolve-CJvM2bUx.mjs.map +1 -0
  260. package/dist/resolve-DyUXmA0z.cjs +316 -0
  261. package/dist/resolve-DyUXmA0z.cjs.map +1 -0
  262. package/dist/rollback-BO1asWkd.mjs +136 -0
  263. package/dist/rollback-BO1asWkd.mjs.map +1 -0
  264. package/dist/rollback-Op8Tc5N-.cjs +165 -0
  265. package/dist/rollback-Op8Tc5N-.cjs.map +1 -0
  266. package/dist/runtime-CaejlcZt.d.mts +82 -0
  267. package/dist/runtime-CaejlcZt.d.mts.map +1 -0
  268. package/dist/runtime-D3jD4Dvn.d.cts +82 -0
  269. package/dist/runtime-D3jD4Dvn.d.cts.map +1 -0
  270. package/dist/s3-BbtwHSod.mjs +240 -0
  271. package/dist/s3-BbtwHSod.mjs.map +1 -0
  272. package/dist/s3-CwacPd8J.cjs +240 -0
  273. package/dist/s3-CwacPd8J.cjs.map +1 -0
  274. package/dist/sandbox/config-worker.cjs +43 -0
  275. package/dist/sandbox/config-worker.cjs.map +1 -0
  276. package/dist/sandbox/config-worker.d.cts +1 -0
  277. package/dist/sandbox/config-worker.d.mts +1 -0
  278. package/dist/sandbox/config-worker.mjs +44 -0
  279. package/dist/sandbox/config-worker.mjs.map +1 -0
  280. package/dist/sandbox/credentials-worker.cjs +53 -0
  281. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  282. package/dist/sandbox/credentials-worker.d.cts +1 -0
  283. package/dist/sandbox/credentials-worker.d.mts +1 -0
  284. package/dist/sandbox/credentials-worker.mjs +54 -0
  285. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  286. package/dist/sandbox/discover-worker.cjs +47 -0
  287. package/dist/sandbox/discover-worker.cjs.map +1 -0
  288. package/dist/sandbox/discover-worker.d.cts +1 -0
  289. package/dist/sandbox/discover-worker.d.mts +1 -0
  290. package/dist/sandbox/discover-worker.mjs +48 -0
  291. package/dist/sandbox/discover-worker.mjs.map +1 -0
  292. package/dist/sandbox/migrate-worker.cjs +75 -0
  293. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  294. package/dist/sandbox/migrate-worker.d.cts +1 -0
  295. package/dist/sandbox/migrate-worker.d.mts +1 -0
  296. package/dist/sandbox/migrate-worker.mjs +76 -0
  297. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  298. package/dist/{workspace-CRD9YinV.cjs → schemas-BCwKKA42.mjs} +399 -1179
  299. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  300. package/dist/{workspace-Bu3xNCej.mjs → schemas-BQ_v0lEX.cjs} +487 -982
  301. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  302. package/dist/secretsManager-CjTo6CRq.mjs +113 -0
  303. package/dist/secretsManager-CjTo6CRq.mjs.map +1 -0
  304. package/dist/secretsManager-CvmBGjdM.cjs +124 -0
  305. package/dist/secretsManager-CvmBGjdM.cjs.map +1 -0
  306. package/dist/seeds-Bc3niNVb.cjs +382 -0
  307. package/dist/seeds-Bc3niNVb.cjs.map +1 -0
  308. package/dist/seeds-Ccn0Ru2T.mjs +299 -0
  309. package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
  310. package/dist/serverSetup-BFdzPTIT.cjs +685 -0
  311. package/dist/serverSetup-BFdzPTIT.cjs.map +1 -0
  312. package/dist/serverSetup-CSxaZ7ha.mjs +685 -0
  313. package/dist/serverSetup-CSxaZ7ha.mjs.map +1 -0
  314. package/dist/sniffer-CwxpsSez.mjs +1824 -0
  315. package/dist/sniffer-CwxpsSez.mjs.map +1 -0
  316. package/dist/sniffer-D3gH7aJT.cjs +1997 -0
  317. package/dist/sniffer-D3gH7aJT.cjs.map +1 -0
  318. package/dist/snsSubscriptions-B8tGxND5.cjs +1135 -0
  319. package/dist/snsSubscriptions-B8tGxND5.cjs.map +1 -0
  320. package/dist/snsSubscriptions-n3sjbrRM.mjs +1010 -0
  321. package/dist/snsSubscriptions-n3sjbrRM.mjs.map +1 -0
  322. package/dist/sst-Cjocp7gi.cjs +501 -0
  323. package/dist/sst-Cjocp7gi.cjs.map +1 -0
  324. package/dist/sst-DeF0BfDA.mjs +478 -0
  325. package/dist/sst-DeF0BfDA.mjs.map +1 -0
  326. package/dist/stack-CyoRqyPt.mjs +1777 -0
  327. package/dist/stack-CyoRqyPt.mjs.map +1 -0
  328. package/dist/stack-Dr2FSxGm.cjs +1887 -0
  329. package/dist/stack-Dr2FSxGm.cjs.map +1 -0
  330. package/dist/stage-TAx0Gcq8.mjs +303 -0
  331. package/dist/stage-TAx0Gcq8.mjs.map +1 -0
  332. package/dist/stage-aTBLKonw.cjs +332 -0
  333. package/dist/stage-aTBLKonw.cjs.map +1 -0
  334. package/dist/stages-BeSQQQ4z.cjs +190 -0
  335. package/dist/stages-BeSQQQ4z.cjs.map +1 -0
  336. package/dist/stages-DjFKQv08.mjs +190 -0
  337. package/dist/stages-DjFKQv08.mjs.map +1 -0
  338. package/dist/target/public.cjs +15 -0
  339. package/dist/target/public.d.cts +28 -0
  340. package/dist/target/public.d.cts.map +1 -0
  341. package/dist/target/public.d.mts +28 -0
  342. package/dist/target/public.d.mts.map +1 -0
  343. package/dist/target/public.mjs +4 -0
  344. package/dist/terminal-Bk4PjXWY.mjs +85 -0
  345. package/dist/terminal-Bk4PjXWY.mjs.map +1 -0
  346. package/dist/terminal-DPf137EJ.cjs +85 -0
  347. package/dist/terminal-DPf137EJ.cjs.map +1 -0
  348. package/dist/{types-7R81hu0i.d.mts → types-CLxsw-QY.d.cts} +2135 -428
  349. package/dist/types-CLxsw-QY.d.cts.map +1 -0
  350. package/dist/{types-N7c2O2m7.d.cts → types-wLlwkSib.d.mts} +2133 -428
  351. package/dist/types-wLlwkSib.d.mts.map +1 -0
  352. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  353. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  354. package/dist/utils-D_fxUqvU.mjs +156 -0
  355. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  356. package/dist/vitest.cjs +65 -0
  357. package/dist/vitest.cjs.map +1 -0
  358. package/dist/vitest.d.cts +29 -0
  359. package/dist/vitest.d.cts.map +1 -0
  360. package/dist/vitest.d.mts +29 -0
  361. package/dist/vitest.d.mts.map +1 -0
  362. package/dist/vitest.mjs +65 -0
  363. package/dist/vitest.mjs.map +1 -0
  364. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  365. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  366. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  367. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  368. package/dist/workspace/index.cjs +6 -2
  369. package/dist/workspace/index.d.cts +3 -3
  370. package/dist/workspace/index.d.mts +3 -3
  371. package/dist/workspace/index.mjs +2 -2
  372. package/dist/workspace-DJjhfAGf.mjs +3027 -0
  373. package/dist/workspace-DJjhfAGf.mjs.map +1 -0
  374. package/dist/workspace-wTLnc1Ef.cjs +3577 -0
  375. package/dist/workspace-wTLnc1Ef.cjs.map +1 -0
  376. package/package.json +76 -13
  377. package/dist/HostingerProvider-BY26bWwB.mjs +0 -243
  378. package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
  379. package/dist/HostingerProvider-BZFGYYVA.cjs +0 -243
  380. package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
  381. package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
  382. package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
  383. package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
  384. package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
  385. package/dist/Route53Provider-Cvj40A8I.mjs +0 -209
  386. package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
  387. package/dist/Route53Provider-DVILBsvV.cjs +0 -209
  388. package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
  389. package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
  390. package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
  391. package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
  392. package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
  393. package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
  394. package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
  395. package/dist/bundler-mjqGAvu1.cjs.map +0 -1
  396. package/dist/bundler-mwH7WOb1.mjs.map +0 -1
  397. package/dist/config-DSXI480r.cjs +0 -467
  398. package/dist/config-DSXI480r.cjs.map +0 -1
  399. package/dist/config-DdKkoUE1.mjs +0 -414
  400. package/dist/config-DdKkoUE1.mjs.map +0 -1
  401. package/dist/config.d.cts.map +0 -1
  402. package/dist/config.d.mts.map +0 -1
  403. package/dist/credentials-C6Pfn6GY.cjs +0 -2939
  404. package/dist/credentials-C6Pfn6GY.cjs.map +0 -1
  405. package/dist/credentials-lbv-j0Be.mjs +0 -2802
  406. package/dist/credentials-lbv-j0Be.mjs.map +0 -1
  407. package/dist/discover-BERGFg8v.cjs +0 -288
  408. package/dist/discover-BERGFg8v.cjs.map +0 -1
  409. package/dist/discover-CK-n3w6b.mjs +0 -244
  410. package/dist/discover-CK-n3w6b.mjs.map +0 -1
  411. package/dist/emit-BdoPFjZf.cjs +0 -253
  412. package/dist/emit-BdoPFjZf.cjs.map +0 -1
  413. package/dist/emit-Bzq7JsMP.mjs +0 -224
  414. package/dist/emit-Bzq7JsMP.mjs.map +0 -1
  415. package/dist/generator-LfZU7NlU.mjs +0 -247
  416. package/dist/generator-LfZU7NlU.mjs.map +0 -1
  417. package/dist/generator-Wdfp0jCS.cjs +0 -282
  418. package/dist/generator-Wdfp0jCS.cjs.map +0 -1
  419. package/dist/github-DlIrXPee.mjs +0 -216
  420. package/dist/github-DlIrXPee.mjs.map +0 -1
  421. package/dist/github-n7N9yOff.cjs +0 -216
  422. package/dist/github-n7N9yOff.cjs.map +0 -1
  423. package/dist/index-B4H4XF7A.d.mts.map +0 -1
  424. package/dist/index-RCUizGxL.d.cts.map +0 -1
  425. package/dist/openapi-B8bu_OXN.cjs +0 -2038
  426. package/dist/openapi-B8bu_OXN.cjs.map +0 -1
  427. package/dist/openapi-DfjbhrsM.mjs +0 -1991
  428. package/dist/openapi-DfjbhrsM.mjs.map +0 -1
  429. package/dist/reconcile-Cq4cO83R.cjs +0 -136
  430. package/dist/reconcile-Cq4cO83R.cjs.map +0 -1
  431. package/dist/reconcile-fmoluZmZ.mjs +0 -113
  432. package/dist/reconcile-fmoluZmZ.mjs.map +0 -1
  433. package/dist/ssm-BKN1Cg4z.mjs +0 -60
  434. package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
  435. package/dist/ssm-FxeSAt35.cjs +0 -60
  436. package/dist/ssm-FxeSAt35.cjs.map +0 -1
  437. package/dist/storage-DgypfSD6.cjs +0 -351
  438. package/dist/storage-DgypfSD6.cjs.map +0 -1
  439. package/dist/storage-TP0x118M.mjs +0 -304
  440. package/dist/storage-TP0x118M.mjs.map +0 -1
  441. package/dist/transfer-2aRVVJ6I.mjs +0 -122
  442. package/dist/transfer-2aRVVJ6I.mjs.map +0 -1
  443. package/dist/transfer-C3WZVmj_.cjs +0 -151
  444. package/dist/transfer-C3WZVmj_.cjs.map +0 -1
  445. package/dist/types-7R81hu0i.d.mts.map +0 -1
  446. package/dist/types-N7c2O2m7.d.cts.map +0 -1
  447. package/dist/workspace-Bu3xNCej.mjs.map +0 -1
  448. package/dist/workspace-CRD9YinV.cjs.map +0 -1
@@ -0,0 +1,3389 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as GkmError } from "./errors-C9uIyIDt.mjs";
3
+ import { M as toEmbeddableSecrets, Y as imageRef, at as runOutput, d as createComposeState, et as stageTag, h as recordRelease, it as run, k as initStageSecrets, n as findRootDomain, r as normalizeDnsConfig } from "./dns-BAM8VH1v.mjs";
4
+ import { B as LOGS_PORT, Dt as ComposeTlsFileMissing, Ft as SERVER_IPV4_KEY, L as resolveStageTelemetry, Rt as isReservedStageKey } from "./workspace-DJjhfAGf.mjs";
5
+ import { A as imageLayout, K as nextPrerenderManifest, L as findBuildRoot, St as envFor, Tt as stageEnv, at as BACKUPS_SERVICE, b as bucketClient, ct as backupsRoleStatements, d as backendsOf, dt as applyBuckets, f as constructGlobs, ft as applyLifecycles, ht as applyPostgres, k as fromBuildRoot, l as workerEnvKeys, mt as applyPolicies, pt as applyNotifications, t as appEnvKeys, v as LEGACY_LOCAL_LOGIN, x as pgClient, y as ensurePostgresLogin, yt as postgresStatements } from "./apps-D0LULFmU.mjs";
6
+ import { t as defineTarget } from "./define-BfrNaY82.mjs";
7
+ import { E as withRedisPassword, R as usesTelemetry, _t as LogsPortTaken, gt as LOGS_SERVICE, m as loadLocalCredentials, ut as primaryPortKey, vt as logsAccess, w as runsRedis, wt as withLogsLogin, x as REDIS_SERVICE, y as withGeneratedSecrets } from "./compose-DtfoUChm.mjs";
8
+ import { o as installedFrom } from "./drivers-BQRb3KsL.mjs";
9
+ import { i as discover } from "./discover-Dfmn6HQ7.mjs";
10
+ import { a as composeProject, d as stackDir, i as LOOPBACK_SERVICES, l as envFile, m as withLogsPort, n as LOGS_PORT_ENV, o as composeStack, p as withCaddyConfigs, r as LOG_ROTATION, t as EDGE_PORT_ENV, u as replicaNames } from "./stack-CyoRqyPt.mjs";
11
+ import { a as ensureDockerignore } from "./docker-DQoE3Fr7.mjs";
12
+ import { a as provisionedTopics, c as subscriptionResource, f as isLocalHost, g as serverAddressHint, h as requiredServerAddress, i as confirmPendingSubscriptions, l as topicConnection, n as SUBSCRIPTION_TYPE, o as recordedPushSubscriptions, s as subscriptionKey, t as PushSubscriptionsUnconfirmed, u as HostNotPointingAtServer, v as stackHosts, x as systemLookup, y as stageDns } from "./snsSubscriptions-n3sjbrRM.mjs";
13
+ import { d as dnsResources, f as forgetDnsResource, i as currentActor, n as reportDatabaseRuns, p as recordDnsChanges, r as reportPlannedSeeds, s as DeployJournal, t as DeploySeedsFailed, u as dnsResourceKey } from "./seeds-Ccn0Ru2T.mjs";
14
+ import { f as plannedSeeds, o as SeedFailed, p as seedDatabases, u as migrateDatabases } from "./databases-CV22HzrI.mjs";
15
+ import { dirname, join, relative } from "node:path";
16
+ import { existsSync } from "node:fs";
17
+ import { chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
18
+ import { hostname, userInfo } from "node:os";
19
+ import { spawn } from "node:child_process";
20
+ import { createConnection, createServer } from "node:net";
21
+ import { createHash } from "node:crypto";
22
+ import { ensureLocalAuthority, ensureLocalCertificate, localCertificateNames, readLocalAuthority } from "@geekmidas/edge/certificates/local";
23
+ import { EDGE_AWS_CREDENTIALS, EDGE_CERTS_DIR, EDGE_DYNAMIC_DIR, EDGE_NETWORK, EDGE_PROJECT, EDGE_SERVICE, claimsOverlap, edgeComposeFile, readEdgeClaims, traefikStaticFile } from "@geekmidas/edge/proxy/traefik";
24
+ import { providedKeyFor } from "@geekmidas/manifest";
25
+ import { stringify } from "yaml";
26
+ import { request } from "node:http";
27
+ import { request as request$1 } from "node:https";
28
+ //#region src/compose/docker.ts
29
+ /**
30
+ * The Docker operations `gkm compose` needs, behind an interface.
31
+ *
32
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
33
+ * registry is asked before anything is pulled, nothing is started for a tag
34
+ * that is missing — are asserted against a fake, and this file is only the
35
+ * wiring to the real CLI.
36
+ *
37
+ * Every call is an argument array. Image refs, tags and paths come from the
38
+ * workspace, and none of them reaches a shell.
39
+ */
40
+ /** `output` as `spawn` reads it. */
41
+ const STDIO = {
42
+ inherit: "inherit",
43
+ stderr: [
44
+ "ignore",
45
+ 2,
46
+ 2
47
+ ],
48
+ ignore: "ignore"
49
+ };
50
+ /**
51
+ * The environment a docker command for `engine` runs with: this process's,
52
+ * with `DOCKER_HOST` pointing at the stack's engine when it is a server's.
53
+ */
54
+ function engineEnv(engine, extra = {}) {
55
+ if (!engine.host && Object.keys(extra).length === 0) return void 0;
56
+ return {
57
+ ...process.env,
58
+ ...extra,
59
+ ...engine.host ? { DOCKER_HOST: engine.host } : {}
60
+ };
61
+ }
62
+ /** How a stack's docker commands run: where it is, where output goes. */
63
+ function runOptions(stack, extra) {
64
+ const env = engineEnv(stack, extra);
65
+ return {
66
+ cwd: stack.cwd,
67
+ stdio: STDIO[stack.output ?? "inherit"],
68
+ ...env ? { env } : {},
69
+ ...stack.signal ? { signal: stack.signal } : {}
70
+ };
71
+ }
72
+ /** The network compose puts a project's services on. */
73
+ function projectNetwork(project) {
74
+ return `${project}_default`;
75
+ }
76
+ /**
77
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
78
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
79
+ */
80
+ function publishedPorts(column) {
81
+ const ports = /* @__PURE__ */ new Set();
82
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
83
+ const first = Number(match[1]);
84
+ const last = match[2] ? Number(match[2]) : first;
85
+ for (let port = first; port <= last; port++) ports.add(port);
86
+ }
87
+ return [...ports];
88
+ }
89
+ /**
90
+ * The host port a `docker ps` Ports column publishes for `inside`:
91
+ * `127.0.0.1:54321->5432/tcp` is 54321.
92
+ */
93
+ function publishedPort(column, inside) {
94
+ const match = new RegExp(`(?:[\\d.]+|\\[[^\\]]*\\]):(\\d+)->${inside}/tcp`).exec(column);
95
+ return match ? Number(match[1]) : void 0;
96
+ }
97
+ /** Each line `docker ps` printed, as the containers holding `port`. */
98
+ function portHolders(output, port) {
99
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
100
+ container,
101
+ ...project ? { project } : {},
102
+ ...service ? { service } : {}
103
+ }));
104
+ }
105
+ /** How long a stack has to pass its health checks. */
106
+ const WAIT_TIMEOUT_S = 180;
107
+ /** `docker` itself failed, before it could say anything about a service. */
108
+ var DockerUnreachable = class extends GkmError {
109
+ engine;
110
+ stderr;
111
+ constructor(engine, stderr) {
112
+ super(`Could not ask Docker on ${engine} which ports its services publish (docker said: ${stderr.trim() || "nothing"}). Check that \`DOCKER_HOST=${engine} docker ps\` works from here.`);
113
+ this.engine = engine;
114
+ this.stderr = stderr;
115
+ this.name = "DockerUnreachable";
116
+ }
117
+ };
118
+ /** `docker compose port` printed nothing a port can be read from. */
119
+ var ServicePortUnknown = class extends GkmError {
120
+ service;
121
+ inside;
122
+ output;
123
+ constructor(service, inside, output) {
124
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
125
+ this.service = service;
126
+ this.inside = inside;
127
+ this.output = output;
128
+ this.name = "ServicePortUnknown";
129
+ }
130
+ };
131
+ /**
132
+ * Whether `ref` names a registry on this machine's loopback — which the
133
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
134
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
135
+ * registry's image is reported as no such manifest).
136
+ */
137
+ function isLoopbackRegistry(ref) {
138
+ const first = ref.split("/")[0];
139
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
140
+ const host = first.replace(/:\d+$/, "");
141
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
142
+ }
143
+ /** `docker push` finished without saying what digest the registry stored. */
144
+ var PushDigestUnknown = class extends GkmError {
145
+ ref;
146
+ output;
147
+ constructor(ref, output) {
148
+ super(`Pushed ${ref}, but docker did not say which digest the registry stored (it said: ${output.trim().split("\n").slice(-3).join(" / ") || "nothing"}). Check the push with \`docker buildx imagetools inspect ${ref}\`.`);
149
+ this.ref = ref;
150
+ this.output = output;
151
+ this.name = "PushDigestUnknown";
152
+ }
153
+ };
154
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
155
+ function pushedDigest(output) {
156
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
157
+ }
158
+ function compose(stack, args) {
159
+ return [
160
+ "compose",
161
+ "-p",
162
+ stack.project,
163
+ "-f",
164
+ stack.file,
165
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
166
+ ...args
167
+ ];
168
+ }
169
+ /** Run a program and keep everything it said, whatever it exits with. */
170
+ function capture(command, args, options = {}) {
171
+ const { timeoutMs = 6e4 } = options;
172
+ return new Promise((resolve, reject) => {
173
+ const child = spawn(command, [...args], {
174
+ stdio: [
175
+ options.input === void 0 ? "ignore" : "pipe",
176
+ "pipe",
177
+ "pipe"
178
+ ],
179
+ shell: false,
180
+ ...options.env ? { env: options.env } : {}
181
+ });
182
+ if (options.input !== void 0) child.stdin?.end(options.input);
183
+ let stdout = "";
184
+ let stderr = "";
185
+ child.stdout?.on("data", (chunk) => {
186
+ stdout += chunk.toString();
187
+ });
188
+ child.stderr?.on("data", (chunk) => {
189
+ stderr += chunk.toString();
190
+ });
191
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
192
+ timer.unref?.();
193
+ child.on("error", (error) => {
194
+ clearTimeout(timer);
195
+ reject(error);
196
+ });
197
+ child.on("close", (code) => {
198
+ clearTimeout(timer);
199
+ resolve({
200
+ code,
201
+ stdout,
202
+ stderr
203
+ });
204
+ });
205
+ });
206
+ }
207
+ /**
208
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
209
+ * opposed to the registry not answering.
210
+ *
211
+ * Read off the message because that is all the CLI gives. Anything not
212
+ * recognisably "no such tag" is treated as the registry being unreachable:
213
+ * a registry that refused credentials must not be reported as a tag that was
214
+ * never pushed, or the fix offered would be the wrong one.
215
+ */
216
+ function isMissingManifest(output) {
217
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
218
+ }
219
+ const dockerCompose = {
220
+ async lookup(ref) {
221
+ const { code, stdout, stderr } = await capture("docker", [
222
+ "manifest",
223
+ "inspect",
224
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
225
+ ref
226
+ ]);
227
+ if (code === 0) return {
228
+ ref,
229
+ status: "found"
230
+ };
231
+ const output = `${stderr}\n${stdout}`.trim();
232
+ return isMissingManifest(output) ? {
233
+ ref,
234
+ status: "missing"
235
+ } : {
236
+ ref,
237
+ status: "unreachable",
238
+ detail: output
239
+ };
240
+ },
241
+ async build(stack, services) {
242
+ await run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
243
+ ...process.env,
244
+ DOCKER_BUILDKIT: "1"
245
+ }));
246
+ },
247
+ async pull(stack, services) {
248
+ await run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
249
+ },
250
+ async up(stack, services) {
251
+ await run("docker", compose(stack, [
252
+ "up",
253
+ "-d",
254
+ "--wait",
255
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
256
+ ...services ? [] : ["--remove-orphans"],
257
+ ...services ?? []
258
+ ]), runOptions(stack));
259
+ },
260
+ async down(stack, options) {
261
+ const args = ["down", ...options?.volumes ? ["--volumes"] : []];
262
+ await run("docker", existsSync(stack.file) ? compose(stack, args) : [
263
+ "compose",
264
+ "-p",
265
+ stack.project,
266
+ ...args
267
+ ], runOptions(stack));
268
+ },
269
+ async port(stack, service, inside) {
270
+ const env = engineEnv(stack);
271
+ const output = await runOutput("docker", compose(stack, [
272
+ "port",
273
+ service,
274
+ String(inside)
275
+ ]), {
276
+ cwd: stack.cwd,
277
+ ...env ? { env } : {},
278
+ ...stack.signal ? { signal: stack.signal } : {}
279
+ });
280
+ const port = Number(output.trim().split(":").pop());
281
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
282
+ return port;
283
+ },
284
+ async health(stack, service) {
285
+ const env = engineEnv(stack);
286
+ const { code, stdout } = await capture("docker", compose(stack, [
287
+ "ps",
288
+ "--format",
289
+ "{{.Health}}",
290
+ service
291
+ ]), env ? { env } : {});
292
+ if (code !== 0) return void 0;
293
+ return stdout.trim().split("\n")[0] || void 0;
294
+ },
295
+ async push(stack, ref) {
296
+ const output = await runOutput("docker", ["push", ref], {
297
+ cwd: stack.cwd,
298
+ ...stack.signal ? { signal: stack.signal } : {}
299
+ });
300
+ const digest = pushedDigest(output);
301
+ if (!digest) throw new PushDigestUnknown(ref, output);
302
+ return digest;
303
+ },
304
+ async digest(engine, ref) {
305
+ const env = engineEnv(engine);
306
+ const { code, stdout } = await capture("docker", [
307
+ "image",
308
+ "inspect",
309
+ "--format={{json .RepoDigests}} {{.Id}}",
310
+ ref
311
+ ], env ? { env } : {});
312
+ if (code !== 0) return void 0;
313
+ const [json = "[]", id] = stdout.trim().split(" ");
314
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
315
+ try {
316
+ const digests = JSON.parse(json);
317
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
318
+ if (match) return match.slice(repository.length + 1);
319
+ } catch {}
320
+ return id || void 0;
321
+ },
322
+ async ensureNetwork(engine, name) {
323
+ const env = engineEnv(engine);
324
+ const options = env ? { env } : {};
325
+ const { code } = await capture("docker", [
326
+ "network",
327
+ "inspect",
328
+ name
329
+ ], options);
330
+ if (code === 0) return;
331
+ const created = await capture("docker", [
332
+ "network",
333
+ "create",
334
+ name
335
+ ], options);
336
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
337
+ },
338
+ async publishers(engine, port) {
339
+ const env = engineEnv(engine);
340
+ const { stdout } = await capture("docker", [
341
+ "ps",
342
+ "--format",
343
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
344
+ ], env ? { env } : {});
345
+ return portHolders(stdout, port);
346
+ },
347
+ async exec(stack, service, command, input) {
348
+ const env = engineEnv(stack);
349
+ const options = env ? { env } : {};
350
+ const { stdout: ids } = await capture("docker", [
351
+ "ps",
352
+ "-q",
353
+ "--filter",
354
+ `label=com.docker.compose.project=${stack.project}`,
355
+ "--filter",
356
+ `label=com.docker.compose.service=${service}`
357
+ ], options);
358
+ const container = ids.trim().split("\n")[0];
359
+ if (!container) return {
360
+ code: null,
361
+ stdout: "",
362
+ stderr: `${service} is not running`
363
+ };
364
+ return capture("docker", [
365
+ "exec",
366
+ ...input === void 0 ? [] : ["-i"],
367
+ container,
368
+ ...command
369
+ ], {
370
+ ...options,
371
+ ...input === void 0 ? {} : { input }
372
+ });
373
+ },
374
+ async container(engine, project, service) {
375
+ const env = engineEnv(engine);
376
+ const { stdout } = await capture("docker", [
377
+ "ps",
378
+ "--filter",
379
+ `label=com.docker.compose.project=${project}`,
380
+ "--filter",
381
+ `label=com.docker.compose.service=${service}`,
382
+ "--format",
383
+ "{{.ID}} {{.Image}}"
384
+ ], env ? { env } : {});
385
+ const [id, image] = stdout.trim().split("\n")[0]?.split(" ") ?? [];
386
+ return id && image ? {
387
+ id,
388
+ image
389
+ } : void 0;
390
+ },
391
+ async published(engine, project, service, inside) {
392
+ const env = engineEnv(engine);
393
+ const { code, stdout, stderr } = await capture("docker", [
394
+ "ps",
395
+ "--filter",
396
+ `label=com.docker.compose.project=${project}`,
397
+ "--filter",
398
+ `label=com.docker.compose.service=${service}`,
399
+ "--format",
400
+ "{{.Ports}}"
401
+ ], env ? { env } : {});
402
+ if (code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", stderr);
403
+ return publishedPort(stdout, inside);
404
+ },
405
+ async stop(engine, project, keep) {
406
+ const env = engineEnv(engine);
407
+ const options = env ? { env } : {};
408
+ const listed = await capture("docker", [
409
+ "ps",
410
+ "--filter",
411
+ `label=com.docker.compose.project=${project}`,
412
+ "--format",
413
+ "{{.ID}} {{.Label \"com.docker.compose.service\"}}"
414
+ ], options);
415
+ if (listed.code !== 0) throw new DockerUnreachable(engine.host ?? "this machine", listed.stderr);
416
+ const ids = listed.stdout.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, service = ""]) => !keep.includes(service)).map(([id = ""]) => id).filter(Boolean);
417
+ if (ids.length === 0) return [];
418
+ const stopped = await capture("docker", ["stop", ...ids], {
419
+ ...options,
420
+ timeoutMs: 12e4
421
+ });
422
+ if (stopped.code !== 0) throw new ContainersNotStopped(project, ids, stopped.stderr);
423
+ return ids;
424
+ },
425
+ async start(engine, ids) {
426
+ if (ids.length === 0) return;
427
+ const env = engineEnv(engine);
428
+ const started = await capture("docker", ["start", ...ids], {
429
+ ...env ? { env } : {},
430
+ timeoutMs: 12e4
431
+ });
432
+ if (started.code !== 0) throw new ContainersNotStarted(ids, started.stderr);
433
+ },
434
+ runOnce(engine, options) {
435
+ return dockerExit([
436
+ "run",
437
+ "--rm",
438
+ ...options.stdin ? ["-i"] : [],
439
+ "--network",
440
+ options.network,
441
+ ...Object.keys(options.env ?? {}).flatMap((name) => ["-e", name]),
442
+ "--entrypoint",
443
+ "",
444
+ options.image,
445
+ ...options.command
446
+ ], {
447
+ env: engineEnv(engine, { ...options.env }) ?? process.env,
448
+ ...options.stdin ? { stdin: options.stdin } : {},
449
+ ...options.output ? { output: options.output } : {}
450
+ });
451
+ }
452
+ };
453
+ /** Spawn `docker`, its output where `output` says; resolve with the exit code. */
454
+ function dockerExit(args, options = {}) {
455
+ const output = STDIO[options.output ?? "inherit"];
456
+ const out = Array.isArray(output) ? output : [
457
+ output,
458
+ output,
459
+ output
460
+ ];
461
+ return new Promise((resolve, reject) => {
462
+ const child = spawn("docker", [...args], {
463
+ stdio: [
464
+ options.stdin ? "pipe" : "ignore",
465
+ out[1],
466
+ out[2]
467
+ ],
468
+ env: options.env ?? process.env,
469
+ shell: false
470
+ });
471
+ let stdinFailed;
472
+ if (options.stdin && child.stdin) {
473
+ options.stdin.on("error", (error) => {
474
+ stdinFailed = error;
475
+ child.stdin?.destroy(error);
476
+ });
477
+ child.stdin.on("error", () => {});
478
+ options.stdin.pipe(child.stdin);
479
+ }
480
+ child.on("error", reject);
481
+ child.on("close", (code) => {
482
+ if (stdinFailed) reject(new StdinNotDelivered(stdinFailed));
483
+ else resolve(code ?? 1);
484
+ });
485
+ });
486
+ }
487
+ /** What a command run with {@link dockerExit} read from stdin failed partway. */
488
+ var StdinNotDelivered = class extends GkmError {
489
+ reason;
490
+ constructor(reason) {
491
+ super(`The input to docker stopped before its end (${reason.message}), so the command only read part of it. Run it again.`);
492
+ this.reason = reason;
493
+ this.name = "StdinNotDelivered";
494
+ }
495
+ };
496
+ /** `docker stop` failed for some of a project's containers. */
497
+ var ContainersNotStopped = class extends GkmError {
498
+ project;
499
+ ids;
500
+ output;
501
+ constructor(project, ids, output) {
502
+ super(`Could not stop ${project}'s containers ${ids.join(", ")} (docker said: ${output.trim() || "nothing"}). Check \`docker ps\` on the stage's server.`);
503
+ this.project = project;
504
+ this.ids = ids;
505
+ this.output = output;
506
+ this.name = "ContainersNotStopped";
507
+ }
508
+ };
509
+ /** `docker start` failed for containers that were stopped. */
510
+ var ContainersNotStarted = class extends GkmError {
511
+ ids;
512
+ output;
513
+ constructor(ids, output) {
514
+ super(`Could not start the containers ${ids.join(", ")} again (docker said: ${output.trim() || "nothing"}). Start them on the stage's server with \`docker start ${ids.join(" ")}\`, or deploy the stage.`);
515
+ this.ids = ids;
516
+ this.output = output;
517
+ this.name = "ContainersNotStarted";
518
+ }
519
+ };
520
+ /** `docker network create` failed. */
521
+ var NetworkCreateFailed = class extends GkmError {
522
+ network;
523
+ output;
524
+ constructor(network, output) {
525
+ super(`Could not create the Docker network '${network}' (docker said: ${output.trim() || "nothing"}). Create it by hand with \`docker network create ${network}\` and run again.`);
526
+ this.network = network;
527
+ this.output = output;
528
+ this.name = "NetworkCreateFailed";
529
+ }
530
+ };
531
+ //#endregion
532
+ //#region src/compose/server.ts
533
+ /**
534
+ * Where a deployed compose stage runs: its server, reached over SSH.
535
+ *
536
+ * gkm never runs on the server. It runs where the deploy is started — a CI
537
+ * runner, a developer's machine — and drives the server's Docker engine over
538
+ * SSH (`DOCKER_HOST=ssh://user@host`), so the server holds Docker, an SSH
539
+ * login and nothing else: no gkm, no checkout, no cloud credentials.
540
+ *
541
+ * ```ts
542
+ * deploy: { compose: { server: { production: { user: 'deploy' } } } }
543
+ * ```
544
+ *
545
+ * The host is the stage's `GKM_SERVER_IPV4` secret — the address its DNS
546
+ * records already point at — unless `host` names another. The local stage is
547
+ * never given one: it runs on this machine's Docker.
548
+ *
549
+ * What the deploy needs from inside the server — Postgres and MinIO, published
550
+ * on the server's loopback alone — it reaches through an SSH tunnel on the same
551
+ * login, so neither is ever published publicly.
552
+ */
553
+ /** A deployed compose stage with nowhere to run. */
554
+ var ComposeServerMissing = class extends GkmError {
555
+ stage;
556
+ missing;
557
+ constructor(stage, missing) {
558
+ super(missing === "config" ? `'${stage}' is a deployed stage, and gkm deploys it to its server's Docker over SSH — it never starts a deployed stage on this machine's Docker. Name the login in gkm.config.ts: deploy: { compose: { server: { ${stage}: { user: 'deploy' } } } } — the host is the stage's ${SERVER_IPV4_KEY} secret (gkm secrets:set ${SERVER_IPV4_KEY} '<ip>' --stage ${stage}), or set host there too.` : `deploy.compose.server.${stage} names no host, and '${stage}' has no ${SERVER_IPV4_KEY} secret to default to. Set it: gkm secrets:set ${SERVER_IPV4_KEY} '<ip>' --stage ${stage} — or set deploy.compose.server.${stage}.host.`);
559
+ this.stage = stage;
560
+ this.missing = missing;
561
+ this.name = "ComposeServerMissing";
562
+ }
563
+ };
564
+ /** SSH to the stage's server failed before anything was changed there. */
565
+ var ComposeServerUnreachable = class extends GkmError {
566
+ target;
567
+ stderr;
568
+ constructor(target, stderr) {
569
+ super(`Could not reach Docker on ${target} over SSH (ssh said: ${stderr.trim() || "nothing"}). Check that \`ssh ${target} docker version\` works from here: the host key in ~/.ssh/known_hosts, the key in your agent or ~/.ssh/config, and the user in the server's docker group.`);
570
+ this.target = target;
571
+ this.stderr = stderr;
572
+ this.name = "ComposeServerUnreachable";
573
+ }
574
+ };
575
+ /** An SSH tunnel to a port on the server's loopback did not open. */
576
+ var ComposeTunnelFailed = class extends GkmError {
577
+ target;
578
+ remotePort;
579
+ stderr;
580
+ constructor(target, remotePort, stderr) {
581
+ super(`Could not open an SSH tunnel to 127.0.0.1:${remotePort} on ${target} (ssh said: ${stderr.trim() || "nothing"}). The server's sshd must allow TCP forwarding for the deploy user (AllowTcpForwarding yes, the default, or local), and its key in ~/.ssh/authorized_keys must too: a key installed with \`restrict\` refuses forwarding unless it also says \`port-forwarding\` (\`restrict,port-forwarding ssh-ed25519 …\`).`);
582
+ this.target = target;
583
+ this.remotePort = remotePort;
584
+ this.stderr = stderr;
585
+ this.name = "ComposeTunnelFailed";
586
+ }
587
+ };
588
+ /**
589
+ * The stage's server: its login from `deploy.compose.server.<stage>`, its
590
+ * host from there or the stage's `GKM_SERVER_IPV4`. Undefined for the local
591
+ * stage, which runs on this machine.
592
+ *
593
+ * @throws {ComposeServerMissing} for a deployed stage with no login or host
594
+ */
595
+ function composeServer(options) {
596
+ const { stage } = options;
597
+ if (options.local) return void 0;
598
+ const config = options.config?.[stage];
599
+ if (!config) throw new ComposeServerMissing(stage, "config");
600
+ const host = config.host ?? options.custom?.["GKM_SERVER_IPV4"]?.trim();
601
+ if (!host) throw new ComposeServerMissing(stage, "host");
602
+ return {
603
+ user: config.user,
604
+ host,
605
+ port: config.port ?? 22
606
+ };
607
+ }
608
+ /** `user@host`, as a person types it after `ssh`. */
609
+ function sshTarget(server) {
610
+ return `${server.user}@${server.host}`;
611
+ }
612
+ /** The server's Docker engine, as `DOCKER_HOST` names it. */
613
+ function dockerHost(server) {
614
+ const host = server.host.includes(":") ? `[${server.host}]` : server.host;
615
+ return `ssh://${server.user}@${host}${server.port === 22 ? "" : `:${server.port}`}`;
616
+ }
617
+ /** The arguments every `ssh` gkm runs starts with: no prompt, ever. */
618
+ function sshArgs(server) {
619
+ return [
620
+ "-o",
621
+ "BatchMode=yes",
622
+ "-o",
623
+ "ConnectTimeout=20",
624
+ "-p",
625
+ String(server.port),
626
+ sshTarget(server)
627
+ ];
628
+ }
629
+ async function freeLocalPort() {
630
+ const server = createServer();
631
+ await new Promise((resolve, reject) => {
632
+ server.once("error", reject);
633
+ server.listen(0, "127.0.0.1", resolve);
634
+ });
635
+ const address = server.address();
636
+ await new Promise((resolve) => server.close(resolve));
637
+ if (!address || typeof address === "string") return 0;
638
+ return address.port;
639
+ }
640
+ function connects(port) {
641
+ return new Promise((resolve) => {
642
+ const socket = createConnection({
643
+ host: "127.0.0.1",
644
+ port
645
+ });
646
+ socket.once("connect", () => {
647
+ socket.destroy();
648
+ resolve(true);
649
+ });
650
+ socket.once("error", () => resolve(false));
651
+ });
652
+ }
653
+ /** The real one: the system's `ssh`, with the user's keys and known hosts. */
654
+ const sshAccess = {
655
+ check(server) {
656
+ return new Promise((resolve, reject) => {
657
+ const child = spawn("ssh", [
658
+ ...sshArgs(server),
659
+ "docker",
660
+ "version",
661
+ "--format",
662
+ "{{.Server.Version}}"
663
+ ], { stdio: [
664
+ "ignore",
665
+ "ignore",
666
+ "pipe"
667
+ ] });
668
+ let stderr = "";
669
+ child.stderr.on("data", (chunk) => {
670
+ stderr += chunk.toString();
671
+ });
672
+ child.on("error", (error) => reject(new ComposeServerUnreachable(sshTarget(server), error.message)));
673
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeServerUnreachable(sshTarget(server), stderr)));
674
+ });
675
+ },
676
+ async tunnel(server, remotePort) {
677
+ const port = await freeLocalPort();
678
+ const child = spawn("ssh", [
679
+ "-N",
680
+ "-o",
681
+ "ExitOnForwardFailure=yes",
682
+ "-o",
683
+ "ControlPath=none",
684
+ "-L",
685
+ `127.0.0.1:${port}:127.0.0.1:${remotePort}`,
686
+ ...sshArgs(server)
687
+ ], { stdio: [
688
+ "ignore",
689
+ "ignore",
690
+ "pipe"
691
+ ] });
692
+ let stderr = "";
693
+ let exited = false;
694
+ child.stderr.on("data", (chunk) => {
695
+ stderr += chunk.toString();
696
+ });
697
+ child.on("exit", () => {
698
+ exited = true;
699
+ });
700
+ child.on("error", (error) => {
701
+ exited = true;
702
+ stderr += error.message;
703
+ });
704
+ const close = async () => {
705
+ if (exited) return;
706
+ const gone = new Promise((resolve) => child.once("exit", resolve));
707
+ child.kill("SIGTERM");
708
+ await gone;
709
+ };
710
+ for (let attempt = 0; attempt < 150; attempt++) {
711
+ if (exited) break;
712
+ if (await connects(port)) return {
713
+ port,
714
+ close
715
+ };
716
+ await new Promise((resolve) => setTimeout(resolve, 200));
717
+ }
718
+ await close();
719
+ throw new ComposeTunnelFailed(sshTarget(server), remotePort, stderr);
720
+ }
721
+ };
722
+ //#endregion
723
+ //#region src/compose/edge.ts
724
+ /**
725
+ * The server's shared Traefik edge, in Docker: started when a stack needs it,
726
+ * and each stack's routes written to — and removed from — the directory it
727
+ * watches.
728
+ *
729
+ * Everything goes through the server's Docker engine, never its filesystem:
730
+ * the edge's static configuration is handed to it inline, and the directories
731
+ * it watches are volumes each stack writes into with `docker exec`. So the
732
+ * deploy runs anywhere that reaches the engine — a CI runner over SSH — and
733
+ * nothing it writes depends on a path on that machine.
734
+ *
735
+ * gkm-edge (compose project — `GKM_EDGE_PROJECT` renames it)
736
+ * traefik.yml its static configuration (inline config)
737
+ * dynamic/<project>.yml one per stack: routers, services, middlewares
738
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
739
+ */
740
+ /** The edge's compose project, as docker is asked about it. */
741
+ function edgeRef(file, options = {}) {
742
+ return {
743
+ project: EDGE_PROJECT,
744
+ file,
745
+ cwd: dirname(file),
746
+ ...options
747
+ };
748
+ }
749
+ /** Writing to or removing from the edge's volumes failed. */
750
+ var EdgeWriteFailed = class extends GkmError {
751
+ path;
752
+ output;
753
+ constructor(path, output) {
754
+ super(`Could not write ${path} in the shared edge (${EDGE_PROJECT}): ${output.trim() || "it is not running"}. Check it with \`docker compose -p ${EDGE_PROJECT} ps\` on the server, and run gkm compose again.`);
755
+ this.path = path;
756
+ this.output = output;
757
+ this.name = "EdgeWriteFailed";
758
+ }
759
+ };
760
+ /**
761
+ * Something other than the proxy a stack is set to holds the edge's ports.
762
+ *
763
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
764
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
765
+ * edge, or another stack's Caddy. Refused before anything is started, so the
766
+ * stack is never left half on one proxy and half on the other.
767
+ */
768
+ var ComposeProxyClash = class extends GkmError {
769
+ project;
770
+ proxy;
771
+ port;
772
+ holder;
773
+ constructor(project, proxy, port, holder) {
774
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
775
+ const fix = proxy === "traefik" ? holder.project === project && holder.service === "caddy" ? `That is this stack's own Caddy, from before it was switched to proxy: 'traefik'. Move it once: stop it (docker compose -p ${project} stop caddy), then run gkm compose again — the shared edge takes 80/443 and the stack registers with it.` : `The shared edge needs ports 80 and 443. Stop ${holder.container}${holder.project ? ` (docker compose -p ${holder.project} down, or its own gkm compose --down)` : ""}, or move the edge with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.` : holder.project === EDGE_PROJECT ? `That is the server's shared Traefik edge, which other stacks register with. Set deploy.compose.proxy to 'traefik' for this stage so the stack registers with it too, or stop the edge once nothing uses it (docker compose -p ${EDGE_PROJECT} down).` : `Stop ${holder.container}, or publish this stack's Caddy elsewhere with GKM_COMPOSE_HTTPS_PORT/GKM_COMPOSE_HTTP_PORT.`;
776
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
777
+ this.project = project;
778
+ this.proxy = proxy;
779
+ this.port = port;
780
+ this.holder = holder;
781
+ this.name = "ComposeProxyClash";
782
+ }
783
+ };
784
+ /**
785
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
786
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
787
+ */
788
+ async function assertEdgePorts(docker, options) {
789
+ const { project, proxy, ports } = options;
790
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(options.engine, port)) if (!(proxy === "traefik" ? holder.project === EDGE_PROJECT : holder.project === project && holder.service === "caddy")) throw new ComposeProxyClash(project, proxy, port, holder);
791
+ }
792
+ /**
793
+ * Write a file into the edge's running container whole or not at all: a
794
+ * temporary name, then a rename. Not `.yml`: the edge reads only `.yml`,
795
+ * `.yaml` and `.toml` files, so it never sees one half written.
796
+ */
797
+ async function put(docker, edge, path, content, mode = "644") {
798
+ const result = await docker.exec(edge, EDGE_SERVICE, [
799
+ "sh",
800
+ "-c",
801
+ "set -e; t=\"$1.tmp\"; cat > \"$t\"; chmod \"$2\" \"$t\"; mv \"$t\" \"$1\"",
802
+ "sh",
803
+ path,
804
+ mode
805
+ ], content);
806
+ if (result.code !== 0) throw new EdgeWriteFailed(path, `${result.stderr}${result.stdout}`);
807
+ }
808
+ /** Remove files from the edge's container; whether the first was there. */
809
+ async function remove(docker, edge, paths) {
810
+ return (await docker.exec(edge, EDGE_SERVICE, [
811
+ "sh",
812
+ "-c",
813
+ "e=1; [ -f \"$1\" ] && e=0; rm -f \"$@\"; exit $e",
814
+ "sh",
815
+ ...paths
816
+ ])).code === 0;
817
+ }
818
+ /**
819
+ * The edge, up: its network and its container — started when it is not
820
+ * running, and recreated when its configuration changed. Idempotent: on a
821
+ * server where it already runs as configured, `up` changes nothing. Its
822
+ * compose file is written to `file`, on this machine: compose reads it here.
823
+ */
824
+ async function ensureEdge(docker, options) {
825
+ const { file, ports } = options;
826
+ const staticConfig = traefikStaticFile(ports);
827
+ const content = edgeComposeFile({
828
+ ports,
829
+ staticConfig,
830
+ logging: options.logging
831
+ });
832
+ await mkdir(dirname(file), { recursive: true });
833
+ if (await readFile(file, "utf-8").catch(() => void 0) !== content) await writeFile(file, content);
834
+ const ref = edgeRef(file, {
835
+ ...options.host ? { host: options.host } : {},
836
+ ...options.output ? { output: options.output } : {},
837
+ ...options.signal ? { signal: options.signal } : {}
838
+ });
839
+ await docker.ensureNetwork(ref, EDGE_NETWORK);
840
+ await docker.up(ref, [EDGE_SERVICE]);
841
+ return [file];
842
+ }
843
+ /** A file inside the edge's running container, or undefined where there is none. */
844
+ async function readEdgeFile(docker, edge, path) {
845
+ const result = await docker.exec(edge, EDGE_SERVICE, ["cat", path]);
846
+ return result.code === 0 ? result.stdout : void 0;
847
+ }
848
+ /** A file written into the edge's running container, whole, readable by it alone. */
849
+ async function writeEdgeSecret(docker, edge, path, content) {
850
+ await put(docker, edge, path, content, "600");
851
+ }
852
+ /**
853
+ * The edge restarted — what it reads once and keeps, a key among them, read
854
+ * again — and waited on until it is healthy. Its own restart policy brings
855
+ * it back; `up` waits for it.
856
+ */
857
+ async function restartEdge(docker, edge) {
858
+ await docker.exec(edge, EDGE_SERVICE, ["kill", "1"]);
859
+ await docker.up(edge, [EDGE_SERVICE]);
860
+ }
861
+ /** A stack's routes, inside the edge's container. */
862
+ function routesPath(project) {
863
+ return `${EDGE_DYNAMIC_DIR}/${project}.yml`;
864
+ }
865
+ /**
866
+ * A host this stack routes is already routed through the shared edge by
867
+ * another project: two routers for one host, and which stack serves it — and
868
+ * which gets its certificate — would be the edge's choice.
869
+ */
870
+ var EdgeHostClaimed = class extends GkmError {
871
+ host;
872
+ owner;
873
+ project;
874
+ edge;
875
+ constructor(host, owner, project, edge = EDGE_PROJECT) {
876
+ super(`${project} routes ${host}, and ${owner} already routes it through the shared edge (${edge}) on this server. A host is served by one stack only. Give ${project} another domain, or take ${owner} off the edge first: gkm compose --stage <stage> --down in its workspace (or remove ${routesPath(owner)} from the edge).`);
877
+ this.host = host;
878
+ this.owner = owner;
879
+ this.project = project;
880
+ this.edge = edge;
881
+ this.name = "EdgeHostClaimed";
882
+ }
883
+ };
884
+ /**
885
+ * Every other stack's claims on the edge, by project: each `dynamic/*.yml`
886
+ * but this project's, read through the engine. None where the edge is not
887
+ * running — nothing is routed through it.
888
+ */
889
+ async function edgeClaimsByProject(docker, edge, project) {
890
+ const claimed = /* @__PURE__ */ new Map();
891
+ const listed = await docker.exec(edge, EDGE_SERVICE, [
892
+ "ls",
893
+ "-1",
894
+ EDGE_DYNAMIC_DIR
895
+ ]);
896
+ if (listed.code !== 0) return claimed;
897
+ for (const name of listed.stdout.split("\n").map((line) => line.trim())) {
898
+ if (!name.endsWith(".yml")) continue;
899
+ const owner = name.slice(0, -4);
900
+ if (!owner || owner === project) continue;
901
+ const file = await readEdgeFile(docker, edge, routesPath(owner));
902
+ if (file === void 0) continue;
903
+ const claims = readEdgeClaims(file);
904
+ if (claims.length > 0) claimed.set(owner, claims);
905
+ }
906
+ return claimed;
907
+ }
908
+ /**
909
+ * Refuse a stack's routes when a host in them is routed through the edge by
910
+ * another project — checked before a deploy changes anything, and again
911
+ * before its routes are written. Its own file, from its last deploy, is
912
+ * replaced, never a clash.
913
+ */
914
+ async function assertEdgeHostsFree(docker, edge, project, routes) {
915
+ const mine = readEdgeClaims(routes);
916
+ if (mine.length === 0) return;
917
+ const others = await edgeClaimsByProject(docker, edge, project);
918
+ for (const [owner, theirs] of [...others].sort(([a], [b]) => a.localeCompare(b))) for (const claim of mine) for (const other of theirs) {
919
+ const host = claimsOverlap(claim, other);
920
+ if (host !== void 0) throw new EdgeHostClaimed(host, owner, project, edge.project);
921
+ }
922
+ }
923
+ function certificatePaths(project) {
924
+ return [`${EDGE_CERTS_DIR}/${project}.crt`, `${EDGE_CERTS_DIR}/${project}.key`];
925
+ }
926
+ /**
927
+ * Register a stack with the edge — refused, before anything is written, when
928
+ * another project routes one of its hosts: its certificate first, where it has one,
929
+ * so the routes that need it never load without it — then its routes, in one
930
+ * rename the edge picks up whole. The certificate — the stage's own, or the
931
+ * one gkm's local CA issued the local stage — is PEM read on this machine and
932
+ * written through the engine. The paths written, inside the edge.
933
+ */
934
+ async function writeEdgeRoutes(docker, edge, project, routes, certificate) {
935
+ await assertEdgeHostsFree(docker, edge, project, routes);
936
+ const written = [];
937
+ const [crt, key] = certificatePaths(project);
938
+ if (certificate) {
939
+ await put(docker, edge, crt, certificate.cert);
940
+ await put(docker, edge, key, certificate.key, "600");
941
+ written.push(crt, key);
942
+ } else await remove(docker, edge, [crt, key]);
943
+ await put(docker, edge, routesPath(project), routes);
944
+ written.push(routesPath(project));
945
+ return written;
946
+ }
947
+ /** What a stack's file holds for the moment between emptying and removal. */
948
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
949
+ /**
950
+ * Unregister a stack: its routes, then its certificate. Whether there was
951
+ * anything to remove — false, too, when the edge is not running.
952
+ */
953
+ async function removeEdgeRoutes(docker, edge, project) {
954
+ const file = routesPath(project);
955
+ if ((await docker.exec(edge, EDGE_SERVICE, [
956
+ "test",
957
+ "-f",
958
+ file
959
+ ])).code !== 0) return false;
960
+ await put(docker, edge, file, UNREGISTERED);
961
+ await remove(docker, edge, [file, ...certificatePaths(project)]);
962
+ return true;
963
+ }
964
+ //#endregion
965
+ //#region src/compose/acmeDns.ts
966
+ /**
967
+ * The key the server's shared Traefik edge answers Let's Encrypt's DNS
968
+ * challenge with, for a stage with a wildcard site.
969
+ *
970
+ * A wildcard certificate is issued only over the DNS challenge: the edge
971
+ * proves it holds `<domain>` by writing a TXT record at
972
+ * `_acme-challenge.<domain>`. So it needs a key that can write that record —
973
+ * and nothing else, because it lives on the server.
974
+ *
975
+ * - **The user**: one per server, under `/gkm/`, tagged with the server it
976
+ * is for. One that exists without that tag is someone else's, and is
977
+ * refused rather than taken over.
978
+ * - **Its policies**: one per stack on the server, named for its compose
979
+ * project, allowing `ChangeResourceRecordSets` on the stage's hosted zone
980
+ * for TXT records named `_acme-challenge.<domain>` alone — plus what
981
+ * finding the zone and waiting for the change take, which read and write
982
+ * nothing. Put back on every deploy.
983
+ * - **Its key**: written into the edge's container, never into the stage's
984
+ * secrets or onto the machine running the deploy. Issued when the edge
985
+ * has none, or holds one IAM no longer knows — and then the edge is
986
+ * restarted, since it keeps the key it first read.
987
+ */
988
+ /** Where gkm's IAM users live. */
989
+ const USER_PATH = "/gkm/";
990
+ /** The tag a server's edge user is found by. */
991
+ const TAG_EDGE = "gkm:edge";
992
+ /** The edge user's name for a server: stable, and safe for IAM. */
993
+ function edgeAcmeUser(server) {
994
+ return `gkm-edge-acme-${createHash("sha256").update(server).digest("hex").slice(0, 12)}`;
995
+ }
996
+ /**
997
+ * What one stage's wildcard certificate needs: its challenge record written
998
+ * in its zone, the change waited on, and the zone found by name — which is
999
+ * how the edge's ACME client finds it.
1000
+ */
1001
+ function acmeDnsPolicy(zoneId, domain) {
1002
+ return JSON.stringify({
1003
+ Version: "2012-10-17",
1004
+ Statement: [
1005
+ {
1006
+ Effect: "Allow",
1007
+ Action: "route53:ChangeResourceRecordSets",
1008
+ Resource: `arn:aws:route53:::hostedzone/${zoneId}`,
1009
+ Condition: { "ForAllValues:StringEquals": {
1010
+ "route53:ChangeResourceRecordSetsNormalizedRecordNames": [`_acme-challenge.${domain.toLowerCase()}`],
1011
+ "route53:ChangeResourceRecordSetsRecordTypes": ["TXT"]
1012
+ } }
1013
+ },
1014
+ {
1015
+ Effect: "Allow",
1016
+ Action: "route53:ListResourceRecordSets",
1017
+ Resource: `arn:aws:route53:::hostedzone/${zoneId}`
1018
+ },
1019
+ {
1020
+ Effect: "Allow",
1021
+ Action: "route53:GetChange",
1022
+ Resource: "arn:aws:route53:::change/*"
1023
+ },
1024
+ {
1025
+ Effect: "Allow",
1026
+ Action: "route53:ListHostedZonesByName",
1027
+ Resource: "*"
1028
+ }
1029
+ ]
1030
+ });
1031
+ }
1032
+ /** An IAM user by the edge user's name that gkm did not create for this server. */
1033
+ var EdgeAcmeUserNotOwned = class extends GkmError {
1034
+ user;
1035
+ server;
1036
+ constructor(user, server) {
1037
+ super(`The IAM user ${user} exists but is not tagged ${TAG_EDGE}=${server}, so gkm will not take it over to write the shared edge's DNS challenge records. Delete it, or tag it ${TAG_EDGE}=${server} if it is the one gkm created for this server.`);
1038
+ this.user = user;
1039
+ this.server = server;
1040
+ this.name = "EdgeAcmeUserNotOwned";
1041
+ }
1042
+ };
1043
+ /** A wildcard site's domain with no Route 53 hosted zone to answer it in. */
1044
+ var AcmeHostedZoneMissing = class extends GkmError {
1045
+ domain;
1046
+ constructor(domain) {
1047
+ super(`No Route 53 hosted zone holds ${domain}, so the shared edge cannot answer the DNS challenge for its wildcard certificate. Create the zone, or set hostedZoneId in its dns entry.`);
1048
+ this.domain = domain;
1049
+ this.name = "AcmeHostedZoneMissing";
1050
+ }
1051
+ };
1052
+ /**
1053
+ * The edge's key for `domain`'s challenge record: its user, this stack's
1054
+ * policy on it, and a key in the edge that IAM knows.
1055
+ *
1056
+ * @throws {EdgeAcmeUserNotOwned} when the user is someone else's
1057
+ * @throws {AcmeHostedZoneMissing} when no hosted zone holds the domain
1058
+ */
1059
+ async function ensureEdgeAcmeKey(docker, options) {
1060
+ const { clients, edge, server, project, domain } = options;
1061
+ const log = options.log ?? ((line) => console.log(line));
1062
+ const IAM = await import("@aws-sdk/client-iam");
1063
+ const user = edgeAcmeUser(server);
1064
+ const zoneId = options.hostedZoneId ?? await hostedZoneId(clients.route53, options.zone);
1065
+ if (!zoneId) throw new AcmeHostedZoneMissing(domain);
1066
+ if (options.dryRun) {
1067
+ log(`🔑 Would let ${EDGE_PROJECT} write _acme-challenge.${domain} TXT records in ${zoneId}, as IAM user ${user} (dry run — nothing is written)`);
1068
+ return {
1069
+ user,
1070
+ zoneId,
1071
+ issued: false
1072
+ };
1073
+ }
1074
+ if (!(await clients.iam.send(new IAM.GetUserCommand({ UserName: user })).catch((error) => {
1075
+ if (error?.name === "NoSuchEntity" || error?.name === "NoSuchEntityException") return;
1076
+ throw error;
1077
+ }))?.User) await clients.iam.send(new IAM.CreateUserCommand({
1078
+ UserName: user,
1079
+ Path: USER_PATH,
1080
+ Tags: [{
1081
+ Key: TAG_EDGE,
1082
+ Value: server
1083
+ }]
1084
+ }));
1085
+ else {
1086
+ const { Tags = [] } = await clients.iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
1087
+ if (!Tags.some((t) => t.Key === "gkm:edge" && t.Value === server)) throw new EdgeAcmeUserNotOwned(user, server);
1088
+ }
1089
+ await clients.iam.send(new IAM.PutUserPolicyCommand({
1090
+ UserName: user,
1091
+ PolicyName: project,
1092
+ PolicyDocument: acmeDnsPolicy(zoneId, domain)
1093
+ }));
1094
+ log(`🔑 ${EDGE_PROJECT} may write _acme-challenge.${domain} TXT records in ${zoneId}, and nothing else there, as IAM user ${user}`);
1095
+ const written = await readEdgeFile(docker, edge, EDGE_AWS_CREDENTIALS);
1096
+ const held = written?.match(/aws_access_key_id\s*=\s*(\S+)/)?.[1];
1097
+ const { AccessKeyMetadata = [] } = await clients.iam.send(new IAM.ListAccessKeysCommand({ UserName: user }));
1098
+ if (held && AccessKeyMetadata.some((k) => k.AccessKeyId === held)) return {
1099
+ user,
1100
+ zoneId,
1101
+ issued: false
1102
+ };
1103
+ for (const key of AccessKeyMetadata) {
1104
+ if (!key.AccessKeyId) continue;
1105
+ await clients.iam.send(new IAM.DeleteAccessKeyCommand({
1106
+ UserName: user,
1107
+ AccessKeyId: key.AccessKeyId
1108
+ }));
1109
+ }
1110
+ const { AccessKey } = await clients.iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }));
1111
+ await writeEdgeSecret(docker, edge, EDGE_AWS_CREDENTIALS, `# Written by gkm compose — the key ${EDGE_PROJECT} answers DNS challenges with.
1112
+ [default]
1113
+ aws_access_key_id = ${AccessKey?.AccessKeyId}
1114
+ aws_secret_access_key = ${AccessKey?.SecretAccessKey}
1115
+ `);
1116
+ log(`🔑 Wrote a new key for ${user} to ${EDGE_PROJECT} (${EDGE_AWS_CREDENTIALS})`);
1117
+ if (written !== void 0) await restartEdge(docker, edge);
1118
+ return {
1119
+ user,
1120
+ zoneId,
1121
+ issued: true
1122
+ };
1123
+ }
1124
+ /** The id of the hosted zone named exactly `zone`, if there is one. */
1125
+ async function hostedZoneId(route53, zone) {
1126
+ const { ListHostedZonesByNameCommand } = await import("@aws-sdk/client-route-53");
1127
+ const name = zone.endsWith(".") ? zone : `${zone}.`;
1128
+ const { HostedZones = [] } = await route53.send(new ListHostedZonesByNameCommand({
1129
+ DNSName: name,
1130
+ MaxItems: 1
1131
+ }));
1132
+ return HostedZones.find((z) => z.Name === name)?.Id?.replace("/hostedzone/", "");
1133
+ }
1134
+ //#endregion
1135
+ //#region src/compose/images.ts
1136
+ /**
1137
+ * Which image each app runs — and, for a tag, whether every one exists.
1138
+ *
1139
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
1140
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
1141
+ * image is asked of the registry before anything is pulled or the running
1142
+ * stack is touched, and one missing image stops the whole run naming every
1143
+ * one that is missing. Nor is a missing image quietly built instead — a build
1144
+ * of whatever is checked out here is not the release the tag names.
1145
+ */
1146
+ /** Images a tag names that the registry does not have. */
1147
+ var ImageTagNotFound = class extends GkmError {
1148
+ tag;
1149
+ refs;
1150
+ constructor(tag, refs) {
1151
+ super(`The registry has no image for ${refs.length === 1 ? "this app" : `${refs.length} apps`} at '${tag}':\n` + refs.map((ref) => ` - ${ref}`).join("\n") + `\nNothing was pulled or started. Push '${tag}' for every app from CI, pick a tag that exists, or run without --tag to build from this checkout.`);
1152
+ this.tag = tag;
1153
+ this.refs = refs;
1154
+ this.name = "ImageTagNotFound";
1155
+ }
1156
+ };
1157
+ /** The registry did not answer, or did not let this machine in. */
1158
+ var RegistryUnreachable = class extends GkmError {
1159
+ ref;
1160
+ detail;
1161
+ constructor(ref, detail) {
1162
+ super(`Could not ask the registry about ${ref}: ${detail || "no answer"}\nNothing was pulled or started. Check the registry is reachable and that this machine is logged in to it (\`docker login <registry>\`).`);
1163
+ this.ref = ref;
1164
+ this.detail = detail;
1165
+ this.name = "RegistryUnreachable";
1166
+ }
1167
+ };
1168
+ /**
1169
+ * A pinned image whose digest the registry would not give, while its tag it
1170
+ * would: the tag now names another image than the one the release pinned.
1171
+ *
1172
+ * Not a login problem — the registry answered for the tag. The tag was pushed
1173
+ * again (by another build of it), and the pinned image is gone, or cannot be
1174
+ * read, by its digest.
1175
+ */
1176
+ var PinnedImageMoved = class extends GkmError {
1177
+ ref;
1178
+ detail;
1179
+ constructor(ref, detail) {
1180
+ const [tagged, digest] = ref.split("@");
1181
+ super(`${tagged} is in the registry, but it resolves to a different image than the pinned ${digest}, and the registry would not give that digest${detail ? `: ${detail}` : ""}\nNothing was pulled or started. The tag was pushed again after this release's push; deploy with the digests file of a push whose images are still in the registry, or push this release again.`);
1182
+ this.ref = ref;
1183
+ this.detail = detail;
1184
+ this.name = "PinnedImageMoved";
1185
+ }
1186
+ };
1187
+ /**
1188
+ * The ref an image is asked of the registry by: a pinned one by its digest
1189
+ * alone (`<image>@sha256:…`), so a tag moved since the push cannot change the
1190
+ * answer; any other by its tag.
1191
+ */
1192
+ function lookupRef(ref) {
1193
+ const [tagged, digest] = ref.split("@");
1194
+ if (!digest) return ref;
1195
+ return `${tagged.replace(/:[\w][\w.-]*$/, "")}@${digest}`;
1196
+ }
1197
+ /**
1198
+ * Assert every image exists, before anything else happens.
1199
+ *
1200
+ * Asked all at once and reported all at once: a release missing two images is
1201
+ * one problem with two names, and finding the second only after fixing the
1202
+ * first is a slower way to learn the same thing.
1203
+ *
1204
+ * A pinned image is asked for by its digest. When the registry will not give
1205
+ * it, its tag is asked too: a tag that answers means the registry is reachable
1206
+ * and the tag names another image, and that is what is reported.
1207
+ *
1208
+ * @throws {PinnedImageMoved} when a pinned digest fails and its tag answers
1209
+ * @throws {RegistryUnreachable} when the registry cannot say
1210
+ * @throws {ImageTagNotFound} listing every missing image
1211
+ */
1212
+ async function assertImagesExist(docker, tag, images) {
1213
+ const lookups = await Promise.all(images.map(async (image) => ({
1214
+ image,
1215
+ lookup: await docker.lookup(lookupRef(image.ref))
1216
+ })));
1217
+ for (const { image, lookup } of lookups) {
1218
+ if (lookup.status === "found" || !image.ref.includes("@")) continue;
1219
+ if ((await docker.lookup(image.ref.split("@")[0])).status === "found") throw new PinnedImageMoved(image.ref, lookup.status === "unreachable" ? lookup.detail : "");
1220
+ }
1221
+ for (const { lookup } of lookups) if (lookup.status === "unreachable") throw new RegistryUnreachable(lookup.ref, lookup.detail);
1222
+ const missing = lookups.filter(({ lookup }) => lookup.status === "missing").map(({ image }) => image.ref);
1223
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
1224
+ }
1225
+ /**
1226
+ * A push or a pull with no `deploy.registry` to push to or pull from.
1227
+ *
1228
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
1229
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
1230
+ * from, somebody else's account. It is never a fallback.
1231
+ */
1232
+ var RegistryRequired = class extends GkmError {
1233
+ operation;
1234
+ ref;
1235
+ constructor(operation, ref) {
1236
+ super(`${operation === "push" ? "Pushing" : "Pulling"} images needs a registry, and gkm.config.ts sets no deploy.registry: '${ref}' would be ${operation === "push" ? "pushed to" : "pulled from"} Docker Hub. Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` + (operation === "pull" ? " To run images built here instead, pass --build." : ""));
1237
+ this.operation = operation;
1238
+ this.ref = ref;
1239
+ this.name = "RegistryRequired";
1240
+ }
1241
+ };
1242
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
1243
+ function pinnedRef(ref, digest) {
1244
+ return `${ref.split("@")[0]}@${digest}`;
1245
+ }
1246
+ /** A digests file with no entry for an app the stack runs. */
1247
+ var ImageDigestMissing = class extends GkmError {
1248
+ file;
1249
+ apps;
1250
+ constructor(file, apps) {
1251
+ super(`${file} pins no digest for ${apps.join(", ")}. Use the file the same release's \`gkm compose --build --push --digests-file\` wrote, or run without --digests-file to pull by tag.`);
1252
+ this.file = file;
1253
+ this.apps = apps;
1254
+ this.name = "ImageDigestMissing";
1255
+ }
1256
+ };
1257
+ /** A digests file entry that is not this app's image. */
1258
+ var ImageDigestMismatch = class extends GkmError {
1259
+ app;
1260
+ expected;
1261
+ found;
1262
+ constructor(app, expected, found) {
1263
+ super(`The digests file pins '${app}' to ${found}, but this release runs ${expected}. It was written for another registry, project, stage or tag; use the file this stage's push of this tag wrote.`);
1264
+ this.app = app;
1265
+ this.expected = expected;
1266
+ this.found = found;
1267
+ this.name = "ImageDigestMismatch";
1268
+ }
1269
+ };
1270
+ /** A digests file that is not a JSON object of app to pinned ref. */
1271
+ var ImageDigestsInvalid = class extends GkmError {
1272
+ file;
1273
+ detail;
1274
+ constructor(file, detail) {
1275
+ super(`${file} is not a digests file (${detail}). It should be the JSON object \`gkm compose --build --push --digests-file\` writes: { "api": "<registry>/<image>:<tag>@sha256:…" }.`);
1276
+ this.file = file;
1277
+ this.detail = detail;
1278
+ this.name = "ImageDigestsInvalid";
1279
+ }
1280
+ };
1281
+ /** Parse a digests file's content, checking its shape. */
1282
+ function parseDigests(file, content) {
1283
+ let parsed;
1284
+ try {
1285
+ parsed = JSON.parse(content);
1286
+ } catch (error) {
1287
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
1288
+ }
1289
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
1290
+ for (const [app, value] of Object.entries(parsed)) if (typeof value !== "string" || !/@sha256:[0-9a-f]{64}$/.test(value)) throw new ImageDigestsInvalid(file, `'${app}' is not an <image>:<tag>@sha256:… ref`);
1291
+ return parsed;
1292
+ }
1293
+ /**
1294
+ * Each image pinned to the digest the file names for it.
1295
+ *
1296
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
1297
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
1298
+ */
1299
+ function pinImages(file, digests, images) {
1300
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
1301
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
1302
+ return images.map((image) => {
1303
+ const pinned = digests[image.app];
1304
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
1305
+ return {
1306
+ ...image,
1307
+ ref: pinned
1308
+ };
1309
+ });
1310
+ }
1311
+ //#endregion
1312
+ //#region src/compose/secrets.ts
1313
+ function deployedStackSecrets(workspace, stage, stored, manifest) {
1314
+ const withSeed = withGeneratedSecrets(stored ?? initStageSecrets(stage), manifest);
1315
+ const withLogs = resolveStageTelemetry({
1316
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1317
+ stage,
1318
+ local: false,
1319
+ target: "compose",
1320
+ runtime: "server",
1321
+ selfHosted: true,
1322
+ used: usesTelemetry(manifest)
1323
+ })?.provider === "self-hosted" ? withLogsLogin(withSeed.secrets, workspace.domains?.[stage]) : {
1324
+ secrets: withSeed.secrets,
1325
+ generated: []
1326
+ };
1327
+ const withRedis = runsRedis(manifest, withLogs.secrets.custom ?? {}) ? withRedisPassword(withLogs.secrets) : {
1328
+ secrets: withLogs.secrets,
1329
+ generated: []
1330
+ };
1331
+ return {
1332
+ secrets: withRedis.secrets,
1333
+ generated: [
1334
+ ...withSeed.generated,
1335
+ ...withLogs.generated,
1336
+ ...withRedis.generated
1337
+ ]
1338
+ };
1339
+ }
1340
+ //#endregion
1341
+ //#region src/target/compose/health.ts
1342
+ /**
1343
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
1344
+ * the way a browser reaches it.
1345
+ *
1346
+ * `docker compose up --wait` already knows each container passed its own
1347
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
1348
+ * the stack is reachable: whether the edge routes the host to the app, and
1349
+ * whether the certificate it presents is one a client accepts. So the check
1350
+ * goes through the edge, by hostname, and verifies the certificate.
1351
+ */
1352
+ /** A request that got no answer in time. */
1353
+ var HealthRequestTimedOut = class extends GkmError {
1354
+ url;
1355
+ timeoutMs;
1356
+ constructor(url, timeoutMs) {
1357
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
1358
+ this.url = url;
1359
+ this.timeoutMs = timeoutMs;
1360
+ this.name = "HealthRequestTimedOut";
1361
+ }
1362
+ };
1363
+ /** The most of a body read — a sitemap may be 50 MB, and none needs to be. */
1364
+ const EDGE_BODY_LIMIT = 10485760;
1365
+ /** A body larger than {@link EDGE_BODY_LIMIT}. */
1366
+ var EdgeResponseTooLarge = class extends GkmError {
1367
+ url;
1368
+ limit;
1369
+ constructor(url, limit) {
1370
+ super(`${url} answered with more than ${limit} bytes, which is more than gkm reads. Split it — a sitemap index can list several sitemaps.`);
1371
+ this.url = url;
1372
+ this.limit = limit;
1373
+ this.name = "EdgeResponseTooLarge";
1374
+ }
1375
+ };
1376
+ /**
1377
+ * The real request: one GET to the edge — over HTTPS, the certificate
1378
+ * verified, for an `https:` URL, and plain HTTP for an `http:` one — with
1379
+ * the URL's host as SNI and `Host` wherever it connects.
1380
+ */
1381
+ const edgeFetch = ({ url, ca, connectTo, connectPort, authorization, timeoutMs, signal, read, headers }) => {
1382
+ const target = new URL(url);
1383
+ const secure = target.protocol === "https:";
1384
+ const request$2 = secure ? request$1 : request;
1385
+ return new Promise((resolve, reject) => {
1386
+ const req = request$2({
1387
+ host: connectTo ?? target.hostname,
1388
+ port: connectPort ?? (target.port || (secure ? 443 : 80)),
1389
+ ...secure ? { servername: target.hostname } : {},
1390
+ path: `${target.pathname}${target.search}`,
1391
+ method: "GET",
1392
+ headers: {
1393
+ ...headers,
1394
+ host: target.host,
1395
+ ...authorization ? { authorization } : {}
1396
+ },
1397
+ ...secure && ca ? { ca } : {},
1398
+ ...signal ? { signal } : {},
1399
+ timeout: timeoutMs
1400
+ }, (res) => {
1401
+ const answered = {
1402
+ status: res.statusCode ?? 0,
1403
+ headers: res.headers
1404
+ };
1405
+ if (!read) {
1406
+ res.resume();
1407
+ res.on("end", () => resolve({
1408
+ ...answered,
1409
+ body: ""
1410
+ }));
1411
+ res.on("error", reject);
1412
+ return;
1413
+ }
1414
+ const chunks = [];
1415
+ let size = 0;
1416
+ res.on("data", (chunk) => {
1417
+ size += chunk.length;
1418
+ if (size > 10485760) {
1419
+ req.destroy(new EdgeResponseTooLarge(url, EDGE_BODY_LIMIT));
1420
+ return;
1421
+ }
1422
+ chunks.push(chunk);
1423
+ });
1424
+ res.on("end", () => resolve({
1425
+ ...answered,
1426
+ body: Buffer.concat(chunks).toString("utf-8")
1427
+ }));
1428
+ res.on("error", reject);
1429
+ });
1430
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
1431
+ req.on("error", reject);
1432
+ req.end();
1433
+ });
1434
+ };
1435
+ /** The real probe: one GET through the edge, answered by its status. */
1436
+ const httpsProbe = (request) => edgeFetch(request).then(({ status }) => status);
1437
+ /** Whether a status means the app answered as it should. */
1438
+ function isHealthy(status) {
1439
+ return status >= 200 && status < 400;
1440
+ }
1441
+ /**
1442
+ * Apps that are not healthy. `via` says which check said so:
1443
+ * - `edge`: verify asked each app through the edge, by its host, and it did
1444
+ * not answer as it should (a worker, with no route, by its container's
1445
+ * health);
1446
+ * - `docker`: `up --wait` failed, and these containers' own health checks
1447
+ * had not passed — the rest of the stack was released and routed first.
1448
+ * One class either way, so a caller matches one failure: apps not healthy.
1449
+ */
1450
+ var ComposeAppsUnhealthy = class extends GkmError {
1451
+ project;
1452
+ apps;
1453
+ proxy;
1454
+ via;
1455
+ constructor(project, apps, proxy = "caddy", via = "edge") {
1456
+ const names = apps.map((a) => a.app).join(" ");
1457
+ super(via === "docker" ? `${project} started, but ${apps.length === 1 ? "this container's health check has" : "these containers' health checks have"} not passed. The rest of the stack is up and routed:\n` + apps.map(({ app, last }) => ` - ${app}: Docker reports it ${last}`).join("\n") + `\nSee why with \`docker compose -p ${project} ps ${names}\` and \`docker compose -p ${project} logs ${names}\`, fix the app, and deploy again.` : `${project} started, but ${apps.length === 1 ? "this app does" : "these apps do"} not answer through ${proxy === "caddy" ? "Caddy" : "the shared Traefik edge"}:\n` + apps.map(({ url, last }) => ` - ${url}: ${last}`).join("\n") + (proxy === "caddy" ? `\nSee why with \`docker compose -p ${project} logs caddy ${names}\`.` : `\nSee why with \`docker compose -p ${EDGE_PROJECT} logs traefik\` and \`docker compose -p ${project} logs ${names}\`.`));
1458
+ this.project = project;
1459
+ this.apps = apps;
1460
+ this.proxy = proxy;
1461
+ this.via = via;
1462
+ this.name = "ComposeAppsUnhealthy";
1463
+ }
1464
+ };
1465
+ //#endregion
1466
+ //#region src/target/compose/topicSubscriptions.ts
1467
+ /**
1468
+ * Every topic subscriber the stack pushes to: a subscriber whose connection
1469
+ * key is a topic's publisher string — a bucket's events key is not — and
1470
+ * whose value on this stage is an SNS one.
1471
+ */
1472
+ function topicPushes(stack, manifest) {
1473
+ const topicKeys = new Set(Object.values(manifest).filter((declaration) => declaration.kind === "topic").map((topic) => providedKeyFor(topic.id, topic.kind, "publisherConnectionString")));
1474
+ const pushes = [];
1475
+ for (const worker of stack.workers) for (const subscriber of worker.push?.subscribers ?? []) {
1476
+ if (!topicKeys.has(subscriber.connectionKey)) continue;
1477
+ const connectionString = worker.env?.[subscriber.connectionKey];
1478
+ if (!connectionString?.startsWith("sns:")) continue;
1479
+ pushes.push({
1480
+ worker: worker.id,
1481
+ name: subscriber.name,
1482
+ endpoint: subscriber.endpoint,
1483
+ connectionKey: subscriber.connectionKey,
1484
+ connectionString,
1485
+ ...subscriber.events ? { events: subscriber.events } : {}
1486
+ });
1487
+ }
1488
+ return pushes;
1489
+ }
1490
+ /** The subscriptions recorded for hand-set topics: those with a key. */
1491
+ function recordedTopicSubscriptions(resources) {
1492
+ return Object.values(resources ?? {}).filter((record) => record.type === "sns-subscription" && typeof record.data?.connectionKey === "string");
1493
+ }
1494
+ /**
1495
+ * Converge each hand-set topic's subscriptions on the subscribers pushed to:
1496
+ * subscribe, bring filters up to date, unsubscribe a route on the worker's
1497
+ * host no subscriber wants any more — and record each ARN, forgetting what
1498
+ * was removed.
1499
+ *
1500
+ * @returns each worker's subscriptions, by export — what it is handed
1501
+ */
1502
+ async function ensureTopicSubscriptions(input) {
1503
+ const { snsUrl, reconcileHttpSubscriptions } = await import("@geekmidas/events/sns");
1504
+ const groups = /* @__PURE__ */ new Map();
1505
+ const group = (topicArn, host, connectionKey) => {
1506
+ const id = `${topicArn}|${host}`;
1507
+ const found = groups.get(id);
1508
+ if (found) return found;
1509
+ const created = {
1510
+ topicArn,
1511
+ host,
1512
+ connectionKey,
1513
+ pushes: [],
1514
+ recorded: []
1515
+ };
1516
+ groups.set(id, created);
1517
+ return created;
1518
+ };
1519
+ for (const push of input.pushes) {
1520
+ const { topicArn } = snsUrl.parse(push.connectionString);
1521
+ const into = group(topicArn, new URL(push.endpoint).host, push.connectionKey);
1522
+ into.connectionString = push.connectionString;
1523
+ into.pushes.push(push);
1524
+ }
1525
+ for (const record of recordedTopicSubscriptions(input.recorded)) group(String(record.data?.topicArn), new URL(String(record.data?.endpoint)).host, String(record.data?.connectionKey)).recorded.push(record);
1526
+ const provisioned = provisionedTopics(input.recorded);
1527
+ const wanted = new Set(input.pushes.map(({ worker, name }) => subscriptionKey(worker, name)));
1528
+ const arns = {};
1529
+ for (const { topicArn, host, connectionKey, ...members } of groups.values()) {
1530
+ const stale = members.recorded.filter((r) => !wanted.has(r.key));
1531
+ const named = members.connectionString ?? input.secrets[connectionKey];
1532
+ if (!named?.startsWith("sns:")) {
1533
+ for (const record of stale) {
1534
+ input.log(` – forgot ${record.data?.endpoint}: '${connectionKey}' no longer names an SNS topic to unsubscribe it from`);
1535
+ await input.forget(record.key);
1536
+ }
1537
+ continue;
1538
+ }
1539
+ const address = new URL(named);
1540
+ address.searchParams.set("topicArn", topicArn);
1541
+ const connection = await topicConnection({
1542
+ connectionKey,
1543
+ connectionString: address.toString(),
1544
+ stage: input.stage,
1545
+ env: input.env,
1546
+ provisioned: provisioned.has(topicArn)
1547
+ });
1548
+ const result = await reconcileHttpSubscriptions(connection, {
1549
+ endpoints: members.pushes.map((push) => ({
1550
+ name: push.name,
1551
+ endpoint: push.endpoint,
1552
+ ...push.events ? { events: push.events } : {}
1553
+ })),
1554
+ ownedHost: host
1555
+ });
1556
+ await connection.close();
1557
+ for (const push of members.pushes) {
1558
+ const arn = result.subscriptions[push.name];
1559
+ const key = subscriptionKey(push.worker, push.name);
1560
+ if (input.recorded?.[key]?.id !== arn) input.log(` ✓ '${push.name}' subscribed to ${topicArn.split(":").pop()} at ${push.endpoint}`);
1561
+ await input.record(subscriptionResource({
1562
+ worker: push.worker,
1563
+ name: push.name,
1564
+ topicArn,
1565
+ endpoint: push.endpoint,
1566
+ connectionKey: push.connectionKey,
1567
+ pending: result.pending.includes(push.name),
1568
+ ...push.events ? { events: push.events } : {}
1569
+ }, arn));
1570
+ arns[push.worker] = {
1571
+ ...arns[push.worker],
1572
+ [push.name]: arn
1573
+ };
1574
+ }
1575
+ for (const arn of result.removed) input.log(` – unsubscribed ${arn}: no subscriber wants it any more`);
1576
+ for (const record of stale) await input.forget(record.key);
1577
+ }
1578
+ return arns;
1579
+ }
1580
+ /**
1581
+ * How long one page has to answer: a first render fetches from the site's
1582
+ * APIs, so it is given longer than a health check is.
1583
+ */
1584
+ const WARMUP_TIMEOUT_MS = 3e4;
1585
+ /**
1586
+ * Next's on-demand revalidation header: a request carrying the build's
1587
+ * preview-mode id is rendered afresh whatever the page's cache says.
1588
+ */
1589
+ const NEXT_REVALIDATE_HEADER = "x-prerender-revalidate";
1590
+ /**
1591
+ * What Next answered a request from: `HIT` and `STALE` are a cached copy —
1592
+ * on a fresh deploy, the build's — and the request rendered nothing.
1593
+ */
1594
+ const NEXT_CACHE_HEADER = "x-nextjs-cache";
1595
+ const FROM_CACHE = /* @__PURE__ */ new Set(["HIT", "STALE"]);
1596
+ /**
1597
+ * Asks the site for its `/sitemap.xml` — a sitemap index's sitemaps followed
1598
+ * one level — then for `/` and every page it lists, up to `maxUrls` pages in
1599
+ * all, `concurrency` at a time. The sitemap comes first so that, rendered
1600
+ * again with `headers`, it lists what the deployed APIs hold. Only pages on
1601
+ * the site's own origin are asked: a sitemap may list another's, which this
1602
+ * deploy did not start.
1603
+ */
1604
+ async function warmSite(options) {
1605
+ const { fetch, edge = {}, maxUrls = 500, concurrency = 4, timeoutMs = WARMUP_TIMEOUT_MS, headers } = options;
1606
+ const origin = new URL(options.url).origin;
1607
+ const result = {
1608
+ warmed: [],
1609
+ cached: [],
1610
+ warnings: [],
1611
+ leftOut: 0
1612
+ };
1613
+ /** One GET; a failure is a warning, and `undefined`. */
1614
+ const get = async (url, read) => {
1615
+ try {
1616
+ const response = await fetch({
1617
+ url,
1618
+ ...edge,
1619
+ ...headers ? { headers } : {},
1620
+ timeoutMs,
1621
+ read
1622
+ });
1623
+ const cache = response.headers?.[NEXT_CACHE_HEADER];
1624
+ if (typeof cache === "string" && FROM_CACHE.has(cache.toUpperCase())) result.cached.push(url);
1625
+ return response;
1626
+ } catch (error) {
1627
+ if (edge.signal?.aborted) throw error;
1628
+ result.warnings.push({
1629
+ url,
1630
+ reason: error instanceof HealthRequestTimedOut ? `no answer within ${error.timeoutMs}ms` : error instanceof Error ? error.message : String(error)
1631
+ });
1632
+ return;
1633
+ }
1634
+ };
1635
+ const warm = async (url) => {
1636
+ const response = await get(url, false);
1637
+ if (!response) return;
1638
+ if (isHealthy(response.status)) result.warmed.push(url);
1639
+ else result.warnings.push({
1640
+ url,
1641
+ reason: `HTTP ${response.status}`
1642
+ });
1643
+ };
1644
+ /** A sitemap's `<loc>`s, or none where it has none — or did not answer. */
1645
+ const sitemap = async (url) => {
1646
+ const response = await get(url, true);
1647
+ if (!response) return void 0;
1648
+ if (response.status >= 400 && response.status < 500) return void 0;
1649
+ if (!isHealthy(response.status)) {
1650
+ result.warnings.push({
1651
+ url,
1652
+ reason: `HTTP ${response.status}`
1653
+ });
1654
+ return;
1655
+ }
1656
+ return readSitemap(response.body);
1657
+ };
1658
+ const root = `${origin}/`;
1659
+ const pages = /* @__PURE__ */ new Set([root]);
1660
+ const sameOrigin = (loc) => {
1661
+ if (!URL.canParse(loc, root)) return void 0;
1662
+ const url = new URL(loc, root);
1663
+ url.hash = "";
1664
+ return url.origin === origin ? url.href : void 0;
1665
+ };
1666
+ const list = (locs) => {
1667
+ for (const loc of locs) {
1668
+ const url = sameOrigin(loc);
1669
+ if (url) pages.add(url);
1670
+ }
1671
+ };
1672
+ const top = await sitemap(`${origin}/sitemap.xml`);
1673
+ if (top?.kind === "index") {
1674
+ const read = await pool([...new Set(top.locs.map(sameOrigin).filter((u) => u !== void 0))], concurrency, sitemap);
1675
+ for (const child of read) if (child?.kind === "urlset") list(child.locs);
1676
+ } else if (top) list(top.locs);
1677
+ await warm(root);
1678
+ const listed = [...pages].slice(1);
1679
+ const room = Math.max(0, maxUrls - 1);
1680
+ result.leftOut = Math.max(0, listed.length - room);
1681
+ await pool(listed.slice(0, room), concurrency, warm);
1682
+ return result;
1683
+ }
1684
+ /**
1685
+ * Prints the preview-mode id of the prerender manifest at `argv[1]`, and
1686
+ * nothing else of it: the manifest's signing and encryption keys never leave
1687
+ * the container. Exit 3 when the manifest has no id.
1688
+ */
1689
+ const PRINT_PREVIEW_MODE_ID = [
1690
+ "let m;",
1691
+ "try { m = JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8')); }",
1692
+ "catch (e) { process.stderr.write(String(e && e.message)); process.exit(2); }",
1693
+ "const id = m && m.preview && m.preview.previewModeId;",
1694
+ "if (typeof id !== 'string' || id === '') process.exit(3);",
1695
+ "process.stdout.write(id);"
1696
+ ].join(" ");
1697
+ /**
1698
+ * The preview-mode id of a running Next site, from the prerender manifest
1699
+ * of its image — `manifest`, a path inside the container — by running the
1700
+ * image's own `node` in it through `exec` (`docker exec`, on whichever
1701
+ * engine runs the stack). Never read from this machine's disk: the image
1702
+ * that runs is the one whose id counts.
1703
+ *
1704
+ * The id is a secret of the site's: it is returned to the warm-up and
1705
+ * nowhere else — never logged, never written.
1706
+ */
1707
+ async function nextPreviewModeId(exec, manifest) {
1708
+ const { code, stdout, stderr } = await exec([
1709
+ "node",
1710
+ "-e",
1711
+ PRINT_PREVIEW_MODE_ID,
1712
+ manifest
1713
+ ]);
1714
+ if (code === 0 && stdout) return { id: stdout };
1715
+ if (code === 3 || code === 0) return { reason: `${manifest} has no preview.previewModeId, which this version of Next may not write` };
1716
+ const said = stderr.trim().split("\n")[0];
1717
+ if (code === null) return { reason: said || "its container is not running" };
1718
+ return { reason: `could not read ${manifest} in its container (${said || `exit ${code}`})` };
1719
+ }
1720
+ /**
1721
+ * Reads a sitemap (sitemaps.org): each entry's `<loc>`, entity-decoded or
1722
+ * from CDATA. Only an unprefixed `<loc>` is an entry's — an `<image:loc>` is
1723
+ * an image on a page, not a page.
1724
+ */
1725
+ function readSitemap(xml) {
1726
+ const kind = /<(?:[\w-]+:)?sitemapindex[\s>]/.test(xml) ? "index" : "urlset";
1727
+ const locs = [];
1728
+ for (const match of xml.matchAll(/<loc>\s*(?:<!\[CDATA\[([\s\S]*?)\]\]>|([\s\S]*?))\s*<\/loc>/g)) {
1729
+ const loc = match[1] ?? decodeEntities(match[2] ?? "");
1730
+ if (loc.trim()) locs.push(loc.trim());
1731
+ }
1732
+ return {
1733
+ kind,
1734
+ locs
1735
+ };
1736
+ }
1737
+ const ENTITIES = {
1738
+ amp: "&",
1739
+ lt: "<",
1740
+ gt: ">",
1741
+ quot: "\"",
1742
+ apos: "'"
1743
+ };
1744
+ function decodeEntities(text) {
1745
+ return text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (whole, entity) => {
1746
+ if (entity[0] === "#") {
1747
+ const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
1748
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
1749
+ }
1750
+ return ENTITIES[entity.toLowerCase()] ?? whole;
1751
+ });
1752
+ }
1753
+ /** Each item through `run`, at most `size` at once, results in order. */
1754
+ async function pool(items, size, run) {
1755
+ const results = new Array(items.length);
1756
+ let next = 0;
1757
+ const worker = async () => {
1758
+ while (next < items.length) {
1759
+ const index = next++;
1760
+ results[index] = await run(items[index]);
1761
+ }
1762
+ };
1763
+ await Promise.all(Array.from({ length: Math.min(size, items.length) }, worker));
1764
+ return results;
1765
+ }
1766
+ //#endregion
1767
+ //#region src/target/compose/phases.ts
1768
+ /**
1769
+ * The compose target's phases: a stage as one Docker Compose stack behind
1770
+ * Caddy — the local stage on this machine's Docker, a deployed stage on its
1771
+ * server's, driven over SSH (`compose/server.ts`) from wherever the deploy
1772
+ * runs.
1773
+ *
1774
+ * The order is the point of this file, and the rules it keeps are these:
1775
+ *
1776
+ * - A tag is checked before anything happens (`validate`). Every app's image
1777
+ * is asked of the registry first; one missing image stops the run naming
1778
+ * them all, and nothing is written, pulled or started.
1779
+ * - The databases exist before the apps do (`provision`). Postgres comes up
1780
+ * alone, its databases, roles and grants are created, its migrations
1781
+ * applied and its seeds run from this machine — through an SSH tunnel to a
1782
+ * server's loopback — and only then do the apps
1783
+ * start — so an app
1784
+ * never boots against a schema that is not there yet.
1785
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
1786
+ * was released under and the digest it resolved to are written to the
1787
+ * stage's state, so "what is this stage running" has an exact answer.
1788
+ * - What was started answers (`verify`): each app is asked through Caddy,
1789
+ * over HTTPS, with the certificate verified. Then each server-rendered site
1790
+ * is warmed (`warmup.ts`): a page that fails to warm is said, never failed.
1791
+ *
1792
+ * Every image is built inside Docker from a pruned slice of the build root —
1793
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
1794
+ * machine before `docker compose build`.
1795
+ *
1796
+ * Docker, the registry, Postgres and the health probe are
1797
+ * injected, so the rules are asserted without a daemon; the defaults are the
1798
+ * real ones.
1799
+ */
1800
+ /** `--push` without `--build`: there is nothing built here to push. */
1801
+ var ComposePushNeedsBuild = class extends GkmError {
1802
+ constructor() {
1803
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
1804
+ this.name = "ComposePushNeedsBuild";
1805
+ }
1806
+ };
1807
+ /** Digests to run by, on a run that pulls nothing. */
1808
+ var ComposePinNeedsPull = class extends GkmError {
1809
+ constructor() {
1810
+ super("--digests-file pins the images a release pulls, so it needs --tag (or --pull) — or, with --build --push, it is where the pushed digests are written.");
1811
+ this.name = "ComposePinNeedsPull";
1812
+ }
1813
+ };
1814
+ /** A port variable that does not hold a port. */
1815
+ var EdgePortInvalid = class extends GkmError {
1816
+ variable;
1817
+ value;
1818
+ constructor(variable, value) {
1819
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
1820
+ this.variable = variable;
1821
+ this.value = value;
1822
+ this.name = "EdgePortInvalid";
1823
+ }
1824
+ };
1825
+ /**
1826
+ * A site that pre-renders against its stage (`prerender: 'stage'`) whose
1827
+ * APIs do not answer, so it is not built: pages built without their data
1828
+ * would ship, and nothing at runtime could fill them.
1829
+ */
1830
+ var SitePrerenderApisDown = class extends GkmError {
1831
+ site;
1832
+ apis;
1833
+ via;
1834
+ constructor(site, apis, via) {
1835
+ const lines = apis.map(({ app, url, last }) => via === "docker" ? ` - ${app}: Docker reports it ${last}` : ` - ${url}: ${last}`).join("\n");
1836
+ super(`'${site}' pre-renders from its stage's APIs (prerender: 'stage'), and ${apis.length === 1 ? "this one does" : "these do"} not answer, so it was not built:\n${lines}\n` + (via === "push" ? "An image pushed for it is built against the stage as it runs now: deploy the stage first, then build and push the site." : "Fix the API and deploy again."));
1837
+ this.site = site;
1838
+ this.apis = apis;
1839
+ this.via = via;
1840
+ this.name = "SitePrerenderApisDown";
1841
+ }
1842
+ };
1843
+ /** A build with no commit to tag its images with. */
1844
+ var NoGitRevision = class extends GkmError {
1845
+ root;
1846
+ constructor(root) {
1847
+ super(`Images built here are tagged with the commit they were built from, and ${root} is not in a git repository with a commit. Commit, or pass --tag to name the images yourself.`);
1848
+ this.root = root;
1849
+ this.name = "NoGitRevision";
1850
+ }
1851
+ };
1852
+ /**
1853
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
1854
+ * at the workspace root. What the generated file cannot know — a port bound
1855
+ * to a tailnet address, another log driver — goes there, and is never
1856
+ * overwritten.
1857
+ */
1858
+ function stackOverrideFile(root, stage) {
1859
+ return join(root, `docker-compose.${stage}.yml`);
1860
+ }
1861
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
1862
+ async function gitRevision(root) {
1863
+ let sha;
1864
+ try {
1865
+ sha = (await runOutput("git", [
1866
+ "rev-parse",
1867
+ "--short",
1868
+ "HEAD"
1869
+ ], { cwd: root })).trim();
1870
+ } catch {
1871
+ throw new NoGitRevision(root);
1872
+ }
1873
+ if (!sha) throw new NoGitRevision(root);
1874
+ return (await runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
1875
+ }
1876
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
1877
+ function edgePorts(env = process.env) {
1878
+ const read = (variable, fallback) => {
1879
+ const value = env[variable];
1880
+ if (value === void 0 || value === "") return fallback;
1881
+ const port = Number(value);
1882
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
1883
+ return port;
1884
+ };
1885
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(LOGS_PORT_ENV, 0) : void 0;
1886
+ return {
1887
+ https: read(EDGE_PORT_ENV.https, 443),
1888
+ http: read(EDGE_PORT_ENV.http, 80),
1889
+ ...logs ? { logs } : {}
1890
+ };
1891
+ }
1892
+ /**
1893
+ * The real ones. Each app is asked for three minutes before it counts as
1894
+ * down: a deployed stage's first ACME certificate can take that long.
1895
+ */
1896
+ const defaultDeps = {
1897
+ docker: dockerCompose,
1898
+ revision: gitRevision,
1899
+ sql: pgClient,
1900
+ buckets: bucketClient,
1901
+ logins: ensurePostgresLogin,
1902
+ migrate: migrateDatabases,
1903
+ seed: seedDatabases,
1904
+ probe: httpsProbe,
1905
+ fetch: edgeFetch,
1906
+ healthAttempts: 90,
1907
+ healthIntervalMs: 2e3,
1908
+ env: process.env,
1909
+ lookup: systemLookup,
1910
+ server: sshAccess
1911
+ };
1912
+ /**
1913
+ * The stack the stage would run, and — for a tag — the registry's word that
1914
+ * every image it names exists. Nothing is written: a missing image stops the
1915
+ * run here, before a file, a secret or a container is touched.
1916
+ */
1917
+ async function validateCompose(ctx, deps, options = {}) {
1918
+ const { workspace, stage, identity, tag } = ctx;
1919
+ const root = workspace.root;
1920
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
1921
+ const push = options.push === true;
1922
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
1923
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
1924
+ const registry = workspace.deploy?.registry;
1925
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, stageTag(tag, stage)));
1926
+ const background = {};
1927
+ const subscribers = {};
1928
+ const manifest = await discover({
1929
+ patterns: constructGlobs(workspace),
1930
+ cwd: root,
1931
+ background,
1932
+ subscribers
1933
+ });
1934
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
1935
+ const recorded = push ? void 0 : await ctx.state.read(stage);
1936
+ const layout = mode === "build" ? imageLayout(workspace) : void 0;
1937
+ const input = {
1938
+ workspace,
1939
+ manifest,
1940
+ background,
1941
+ subscribers,
1942
+ stage,
1943
+ identity,
1944
+ images: {
1945
+ mode,
1946
+ tag,
1947
+ ...registry ? { registry } : {}
1948
+ },
1949
+ secrets,
1950
+ ...stage === workspace.stages.local ? { localCredentials: (await loadLocalCredentials(workspace)).credentials } : {},
1951
+ allowDevServices: ctx.allowDevServices,
1952
+ ports: edgePorts(deps.env),
1953
+ ...layout ? { layout } : {},
1954
+ ...push ? { buildOnly: true } : {},
1955
+ ...mode === "build" ? { prerenderRun: (/* @__PURE__ */ new Date()).toISOString() } : {}
1956
+ };
1957
+ const recordedArns = recordedPushSubscriptions(recorded?.resources);
1958
+ const planned = push ? void 0 : composeStack({
1959
+ ...input,
1960
+ recordingSubscriptions: true
1961
+ });
1962
+ const pushes = planned ? topicPushes(planned, manifest) : [];
1963
+ const topics = planned && (pushes.length > 0 || recordedTopicSubscriptions(recorded?.resources).length > 0) ? {
1964
+ pushes,
1965
+ recorded: recorded?.resources
1966
+ } : void 0;
1967
+ const composed = topics && planned ? planned : composeStack({
1968
+ ...input,
1969
+ pushSubscriptions: recordedArns
1970
+ });
1971
+ if (mode === "build") assertRedisClient(workspace, composed, manifest);
1972
+ const pinned = (unpinned) => options.pin ? withPinnedImages(unpinned, options.pin.file, options.pin.digests) : unpinned;
1973
+ const stack = pinned(composed);
1974
+ for (const warning of stack.warnings) ctx.logger.warn(`⚠ ${warning}`);
1975
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, stageTag(tag, stage), [
1976
+ ...stack.apps,
1977
+ ...stack.workers,
1978
+ ...stack.processors
1979
+ ]);
1980
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
1981
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
1982
+ ctx.secrets.mask(stack.logs.password);
1983
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
1984
+ }
1985
+ if (!push && !stack.local) requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
1986
+ const server = push ? void 0 : composeServer({
1987
+ stage,
1988
+ local: stack.local,
1989
+ config: workspace.deploy?.compose?.server,
1990
+ custom: secrets?.custom
1991
+ });
1992
+ const dir = join(root, stackDir(stage));
1993
+ const override = stackOverrideFile(root, stage);
1994
+ const overrides = existsSync(override) ? [override] : [];
1995
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
1996
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
1997
+ const { ref, tag, digest } = releases.current;
1998
+ return [name, {
1999
+ ref,
2000
+ ...tag ? { tag } : {},
2001
+ ...digest ? { digest } : {}
2002
+ }];
2003
+ }));
2004
+ return {
2005
+ mode,
2006
+ push,
2007
+ stack,
2008
+ ...topics ? { topicSubscriptions: {
2009
+ ...topics,
2010
+ restack: (arns) => {
2011
+ const merged = { ...recordedArns };
2012
+ for (const [worker, own] of Object.entries(arns)) merged[worker] = {
2013
+ ...merged[worker],
2014
+ ...own
2015
+ };
2016
+ return pinned(composeStack({
2017
+ ...input,
2018
+ pushSubscriptions: merged
2019
+ }));
2020
+ }
2021
+ } } : {},
2022
+ ...server ? { server } : {},
2023
+ dir,
2024
+ ref: {
2025
+ project: composeProject(identity),
2026
+ file: join(dir, "docker-compose.yml"),
2027
+ ...overrides.length > 0 ? { overrides } : {},
2028
+ cwd: root,
2029
+ ...server ? { host: dockerHost(server) } : {},
2030
+ output: ctx.childOutput,
2031
+ signal: ctx.signal
2032
+ },
2033
+ secrets,
2034
+ generated,
2035
+ previous,
2036
+ files: [],
2037
+ images: {},
2038
+ changes: []
2039
+ };
2040
+ }
2041
+ /**
2042
+ * What only a compose deploy checks before it changes anything, once the
2043
+ * stage's own keys are: the stage's own certificate is there, and every
2044
+ * public host points at the stage's server — its records written where a
2045
+ * provider holds them, then confirmed — before Caddy or Traefik ask Let's
2046
+ * Encrypt for a certificate it could not issue. A build-only run never asks.
2047
+ */
2048
+ async function readyCompose(ctx, run, deps) {
2049
+ const { stack } = run;
2050
+ if (stack.tls) {
2051
+ const { certFile, keyFile, caFile } = stack.tls;
2052
+ for (const file of [
2053
+ certFile,
2054
+ keyFile,
2055
+ ...caFile ? [caFile] : []
2056
+ ]) if (!existsSync(file)) throw new ComposeTlsFileMissing(ctx.stage, file);
2057
+ }
2058
+ if (stack.local) {
2059
+ await edgeHostsFree(ctx, run, deps);
2060
+ return;
2061
+ }
2062
+ if (run.server && !ctx.dryRun && !run.push) await deps.server.check(run.server);
2063
+ await edgeHostsFree(ctx, run, deps);
2064
+ await logsPortOnServer(ctx, run, deps);
2065
+ const prune = await stageHostsDns(ctx, deps, stackHosts(stack).filter((host) => !isLocalHost(host)), run.secrets?.custom, stack.wildcard?.host);
2066
+ if (prune) run.pruneDns = prune;
2067
+ }
2068
+ /**
2069
+ * No host the stack routes through the shared edge is routed there by another
2070
+ * project — asked of the edge on the stage's engine before a record, a
2071
+ * secret, an image or a container is touched, so a clash fails the deploy
2072
+ * with nothing changed. Asked again as the routes are written
2073
+ * (`writeEdgeRoutes`), for an edge that was not running yet.
2074
+ */
2075
+ async function edgeHostsFree(ctx, run, deps) {
2076
+ const { stack, ref } = run;
2077
+ if (ctx.dryRun || run.push) return;
2078
+ if (stack.proxy !== "traefik" || !stack.traefik) return;
2079
+ await assertEdgeHostsFree(deps.docker, edgeRef(edgeFile(run), {
2080
+ ...ref.host ? { host: ref.host } : {},
2081
+ ...ref.output ? { output: ref.output } : {}
2082
+ }), stack.project, stack.traefik);
2083
+ }
2084
+ /** How many ports past the first a stage's OpenObserve is tried on. */
2085
+ const LOGS_PORT_TRIES = 100;
2086
+ /**
2087
+ * The loopback port the stack's OpenObserve is published on, settled against
2088
+ * what every other stack on the server publishes — before anything is
2089
+ * written, so two stages on one machine cannot both take `5080` and fail at
2090
+ * `up`.
2091
+ *
2092
+ * - A port the stage named is refused when another project holds it.
2093
+ * - Otherwise the stack keeps the port it already publishes, or takes the
2094
+ * first from the default up that no other project holds — and the stack,
2095
+ * its tunnel line included, is moved onto it.
2096
+ *
2097
+ * Asked of the server's engine, so not on a dry run, a push, or the local
2098
+ * stage; nor for a log UI served through the edge, which publishes nothing.
2099
+ *
2100
+ * @throws {LogsPortTaken}
2101
+ */
2102
+ async function logsPortOnServer(ctx, run, deps) {
2103
+ const logs = run.stack.logs;
2104
+ if (!logs || logs.public || run.stack.local) return;
2105
+ if (ctx.dryRun || run.push || !run.server) return;
2106
+ const engine = run.ref.host ? { host: run.ref.host } : {};
2107
+ const project = run.ref.project;
2108
+ const holder = async (port) => {
2109
+ const others = (await deps.docker.publishers(engine, port)).filter((held) => held.project !== project);
2110
+ return others[0] && (others[0].project ?? others[0].container);
2111
+ };
2112
+ if (logs.portSet) {
2113
+ const taken = await holder(logs.port);
2114
+ if (taken) throw new LogsPortTaken(ctx.stage, logs.port, taken, true);
2115
+ return;
2116
+ }
2117
+ const kept = await deps.docker.published(engine, project, LOGS_SERVICE, LOGS_PORT);
2118
+ let port = kept;
2119
+ if (port === void 0) {
2120
+ let taken;
2121
+ for (let next = logs.port; next < logs.port + LOGS_PORT_TRIES; next++) {
2122
+ taken = await holder(next);
2123
+ if (!taken) {
2124
+ port = next;
2125
+ break;
2126
+ }
2127
+ }
2128
+ if (port === void 0) throw new LogsPortTaken(ctx.stage, logs.port, taken ?? "", false);
2129
+ }
2130
+ if (port !== logs.port) {
2131
+ ctx.logger.info(kept === void 0 ? `📜 OpenObserve: ${logs.port} is another stack's on this server, so "${ctx.stage}" publishes ${port}` : `📜 OpenObserve: "${ctx.stage}" keeps ${port}, the port it already publishes`);
2132
+ run.stack = withLogsPort(run.stack, port);
2133
+ }
2134
+ }
2135
+ /** A stack whose caches are in Redis, built for an app that has no client. */
2136
+ var RedisClientMissing = class extends GkmError {
2137
+ apps;
2138
+ constructor(apps) {
2139
+ super(`The stack keeps every cache in Redis, and ${apps.join(", ")} ${apps.length === 1 ? "does" : "do"} not depend on ioredis, the client the generated server reaches it with. Add it to the workspace: pnpm add ioredis`);
2140
+ this.apps = apps;
2141
+ this.name = "RedisClientMissing";
2142
+ }
2143
+ };
2144
+ /**
2145
+ * Every backend and worker image whose process reaches a cache can resolve
2146
+ * `ioredis` — listed by its app or a directory above it, the way Node and
2147
+ * the image's install find it. A process that reaches no cache registers no
2148
+ * cache driver, so it needs no client.
2149
+ */
2150
+ function assertRedisClient(workspace, stack, manifest) {
2151
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
2152
+ const cacheKeys = Object.values(manifest).filter((d) => d.kind === "cache").flatMap((d) => d.provides ?? []);
2153
+ const reachesCache = (keys) => cacheKeys.some((key) => keys?.has(key));
2154
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => (app.kind === "rest-api" || app.kind === "websocket-api") && reachesCache(appEnvKeys(manifest, app.name))).map((a) => a.name), ...stack.workers.filter((worker) => reachesCache(workerEnvKeys(manifest, worker.id))).map((worker) => worker.host)])].filter((name) => {
2155
+ const app = workspace.apps[name];
2156
+ return app && !installedFrom(join(workspace.root, app.path), "ioredis");
2157
+ }).sort();
2158
+ if (missing.length > 0) throw new RedisClientMissing(missing);
2159
+ }
2160
+ /**
2161
+ * The deploy's DNS step, for a deployed stage: its server's address — required
2162
+ * where it serves a real domain — then its own hosts written through each
2163
+ * domain's provider in `dns` where they differ, read back from it, and
2164
+ * recorded in the stage's state; hosts no provider writes resolved with the
2165
+ * system resolver. A dry run prints the plan and writes nothing, and warns
2166
+ * rather than stops. Returns the prune of the records gkm wrote for hosts the
2167
+ * stage no longer serves — which a dry run prints there and then.
2168
+ *
2169
+ * @throws {ServerAddressMissing} when the stage has a domain and no address
2170
+ * @throws {ServerAddressInvalid} for a value that is not an address
2171
+ * @throws {HostNotPointingAtServer} when a host is not the server
2172
+ */
2173
+ /**
2174
+ * The records the stack's DNS step weighs against its plan: every one gkm
2175
+ * wrote for the stage's hosts, and each a provider asked for on an earlier
2176
+ * deploy and not on this one — which the plan does not have either, so it is
2177
+ * pruned once the stack answers. One a provider asked for this run is not
2178
+ * the stack's to prune; nor is any provider's, when the providers did not
2179
+ * run.
2180
+ */
2181
+ function recordedForStack(recorded, providerDns) {
2182
+ const asked = new Set(providerDns ?? []);
2183
+ return recorded.filter((record) => record.source !== "provider" || providerDns !== void 0 && !asked.has(dnsResourceKey(record.fqdn, record.type)));
2184
+ }
2185
+ async function stageHostsDns(ctx, deps, hosts, custom, wildcard) {
2186
+ const { workspace, stage } = ctx;
2187
+ const server = requiredServerAddress(stage, workspace.domains?.[stage], custom);
2188
+ if (hosts.length === 0) return;
2189
+ if (ctx.skipDns) {
2190
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
2191
+ return;
2192
+ }
2193
+ if (!server) {
2194
+ ctx.logger.info(`🌐 DNS skipped: no ${SERVER_IPV4_KEY} in '${stage}''s secrets — ${serverAddressHint(stage)}`);
2195
+ return;
2196
+ }
2197
+ const log = (line) => ctx.logger.info(line);
2198
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
2199
+ try {
2200
+ const stored = await ctx.state.read(stage);
2201
+ const result = await stageDns({
2202
+ stage,
2203
+ hosts,
2204
+ server,
2205
+ dns: workspace.dns,
2206
+ recorded: recordedForStack(dnsResources(stored?.resources ?? {}), ctx.providerDns),
2207
+ ...wildcard ? { wildcard } : {},
2208
+ credentials: ctx.credentials,
2209
+ log,
2210
+ lookup: deps.lookup ?? systemLookup,
2211
+ ...ctx.dryRun ? { dryRun: true } : {},
2212
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
2213
+ });
2214
+ if (!ctx.dryRun) {
2215
+ const journal = await DeployJournal.open(ctx.state, stage, () => createComposeState(stage));
2216
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
2217
+ await recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
2218
+ }
2219
+ const parts = [result.confirmed.length > 0 ? `${result.confirmed.length} host${result.confirmed.length === 1 ? "" : "s"} confirmed by the DNS provider` : "", result.resolved.length > 0 ? `${result.resolved.length} host${result.resolved.length === 1 ? "" : "s"} resolve${result.resolved.length === 1 ? "s" : ""} to ${server.ipv4}` : ""].filter(Boolean);
2220
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
2221
+ if (ctx.dryRun) {
2222
+ await result.prune();
2223
+ return;
2224
+ }
2225
+ return result.recorded.stale.length > 0 ? result.prune : void 0;
2226
+ } catch (error) {
2227
+ if (ctx.dryRun && error instanceof HostNotPointingAtServer) {
2228
+ ctx.logger.warn(`⚠ ${error.message}`);
2229
+ return;
2230
+ }
2231
+ throw error;
2232
+ }
2233
+ }
2234
+ /**
2235
+ * The records gkm wrote for hosts the stage no longer serves, deleted once it
2236
+ * answers on its new ones — and forgotten from its state, deleted or not:
2237
+ * none is gkm's to manage any more.
2238
+ */
2239
+ async function pruneStageDns(ctx, run) {
2240
+ if (!run.pruneDns) return;
2241
+ const pruned = await run.pruneDns();
2242
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
2243
+ for (const { record } of pruned) await forgetDnsResource(journal, record);
2244
+ const deleted = pruned.filter((p) => p.action === "delete").length;
2245
+ if (deleted > 0) ctx.logger.info(`🌐 ${deleted} record${deleted === 1 ? "" : "s"} deleted`);
2246
+ }
2247
+ /**
2248
+ * The stage's secrets — and, for a deployed stage, everything it generates
2249
+ * once: its seed, and each declared secret and keyring. Kept only once the
2250
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
2251
+ * leaves the stage's secrets as it found them.
2252
+ */
2253
+ async function stageSecrets(ctx, manifest) {
2254
+ const stored = await ctx.secrets.read();
2255
+ if (ctx.stage === ctx.workspace.stages.local) return {
2256
+ secrets: stored,
2257
+ generated: []
2258
+ };
2259
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
2260
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
2261
+ for (const [key, value] of Object.entries(secrets.custom ?? {})) if (!isReservedStageKey(key) && key !== "ZO_ROOT_USER_EMAIL") ctx.secrets.mask(value);
2262
+ return {
2263
+ secrets,
2264
+ generated
2265
+ };
2266
+ }
2267
+ /**
2268
+ * The stack with each app's and worker's image pinned to the digest the file
2269
+ * names: the refs it is checked, pulled and recorded by, and the image each
2270
+ * compose service runs.
2271
+ */
2272
+ function withPinnedImages(stack, file, digests) {
2273
+ const apps = pinImages(file, digests, stack.apps);
2274
+ const workers = pinImages(file, digests, stack.workers);
2275
+ const processors = pinImages(file, digests, stack.processors);
2276
+ const services = { ...stack.compose.services };
2277
+ for (const image of [
2278
+ ...apps,
2279
+ ...workers,
2280
+ ...processors
2281
+ ]) services[image.name] = {
2282
+ ...services[image.name],
2283
+ image: image.ref
2284
+ };
2285
+ return {
2286
+ ...stack,
2287
+ apps,
2288
+ workers,
2289
+ processors,
2290
+ compose: {
2291
+ ...stack.compose,
2292
+ services
2293
+ }
2294
+ };
2295
+ }
2296
+ /**
2297
+ * A dry run: the stack's files, written so they can be read, and what a real
2298
+ * run would do — no image is built or pulled, no container touched, nothing
2299
+ * recorded and no secret kept.
2300
+ */
2301
+ async function planCompose(ctx, run) {
2302
+ if (run.generated.length > 0) ctx.logger.info(`🔑 "${ctx.stage}" has no ${run.generated.join(", ")} yet; this dry run used values it did not keep.`);
2303
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
2304
+ printPlan(ctx, run);
2305
+ if (!run.push && run.stack.infra.includes("postgres")) reportPlannedSeeds((await plannedSeeds({
2306
+ root: ctx.workspace.root,
2307
+ manifest: ctx.manifest
2308
+ })).map(({ target, seeds }) => ({
2309
+ folder: target.seeds,
2310
+ seeds
2311
+ })), (line) => ctx.logger.info(line));
2312
+ const planned = (change) => {
2313
+ run.changes.push(change);
2314
+ ctx.emit({
2315
+ type: "resource.planned",
2316
+ ...change
2317
+ });
2318
+ };
2319
+ for (const service of run.push ? [] : run.stack.infra) planned({
2320
+ key: `service:${service}`,
2321
+ resourceType: "service",
2322
+ action: "ensure"
2323
+ });
2324
+ for (const app of run.stack.apps) {
2325
+ planned({
2326
+ key: `image:${app.name}`,
2327
+ resourceType: "image",
2328
+ action: run.mode === "build" ? "build" : "reuse",
2329
+ id: app.ref
2330
+ });
2331
+ if (run.push) continue;
2332
+ planned({
2333
+ key: `service:${app.name}`,
2334
+ resourceType: "service",
2335
+ action: run.previous[app.name] ? "reuse" : "create"
2336
+ });
2337
+ }
2338
+ for (const worker of [...run.stack.workers, ...run.stack.processors]) {
2339
+ planned({
2340
+ key: `image:${worker.name}`,
2341
+ resourceType: "image",
2342
+ action: run.mode === "build" ? "build" : "reuse",
2343
+ id: worker.ref
2344
+ });
2345
+ if (run.push) continue;
2346
+ planned({
2347
+ key: `service:${worker.name}`,
2348
+ resourceType: "service",
2349
+ action: run.previous[worker.name] ? "reuse" : "create"
2350
+ });
2351
+ }
2352
+ for (const push of run.topicSubscriptions?.pushes ?? []) {
2353
+ const key = subscriptionKey(push.worker, push.name);
2354
+ const id = run.topicSubscriptions?.recorded?.[key]?.id;
2355
+ planned({
2356
+ key,
2357
+ resourceType: SUBSCRIPTION_TYPE,
2358
+ action: id ? "reuse" : "create",
2359
+ ...id ? { id } : {}
2360
+ });
2361
+ }
2362
+ if (!run.push) planned({
2363
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
2364
+ resourceType: "service",
2365
+ action: "ensure"
2366
+ });
2367
+ }
2368
+ /**
2369
+ * The shared edge's key for the stage's wildcard certificate: the DNS
2370
+ * challenge's record, and nothing else, through the stage domain's Route 53
2371
+ * entry — before the stack's routes ask for the certificate.
2372
+ */
2373
+ async function edgeAcmeKey(ctx, run, deps) {
2374
+ const { workspace, stage } = ctx;
2375
+ const domain = workspace.domains?.[stage];
2376
+ const dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};
2377
+ const zone = domain ? findRootDomain(domain, dns) : null;
2378
+ const config = zone ? dns[zone] : void 0;
2379
+ if (!domain || !zone || config?.provider !== "route53") return;
2380
+ const route53 = config;
2381
+ const server = requiredServerAddress(stage, domain, run.secrets?.custom)?.ipv4 ?? run.server?.host ?? "local";
2382
+ const clients = await (deps.acmeClients ?? defaultAcmeClients)(route53);
2383
+ await ensureEdgeAcmeKey(deps.docker, {
2384
+ clients,
2385
+ edge: edgeRef(edgeFile(run), {
2386
+ ...run.ref.host ? { host: run.ref.host } : {},
2387
+ ...run.ref.output ? { output: run.ref.output } : {}
2388
+ }),
2389
+ server,
2390
+ project: run.stack.project,
2391
+ domain,
2392
+ zone,
2393
+ ...route53.hostedZoneId ? { hostedZoneId: route53.hostedZoneId } : {},
2394
+ ...ctx.dryRun ? { dryRun: true } : {},
2395
+ log: (line) => ctx.logger.info(line)
2396
+ });
2397
+ }
2398
+ /** IAM and Route 53 through the AWS SDK's own chain, or the entry's profile. */
2399
+ async function defaultAcmeClients(config) {
2400
+ const [{ IAMClient }, { Route53Client }, { fromIni }] = await Promise.all([
2401
+ import("@aws-sdk/client-iam"),
2402
+ import("@aws-sdk/client-route-53"),
2403
+ import("@aws-sdk/credential-providers")
2404
+ ]);
2405
+ const options = {
2406
+ region: config.region ?? "us-east-1",
2407
+ ...config.profile ? { credentials: fromIni({ profile: config.profile }) } : {}
2408
+ };
2409
+ return {
2410
+ iam: new IAMClient(options),
2411
+ route53: new Route53Client(options)
2412
+ };
2413
+ }
2414
+ /**
2415
+ * What the apps run on: the stage's generated secrets kept, the stack's files
2416
+ * written, its infrastructure started, and its databases, roles, grants and
2417
+ * migrations applied.
2418
+ */
2419
+ async function provisionCompose(ctx, run, deps) {
2420
+ const { ref } = run;
2421
+ if (run.push) return;
2422
+ if (run.generated.length > 0 && run.secrets) {
2423
+ await ctx.secrets.write(run.secrets);
2424
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
2425
+ }
2426
+ const ports = edgePorts(deps.env);
2427
+ await assertEdgePorts(deps.docker, {
2428
+ project: run.stack.project,
2429
+ proxy: run.stack.proxy,
2430
+ ports,
2431
+ engine: ref
2432
+ });
2433
+ if (run.topicSubscriptions) await subscribeTopics(ctx, run, deps);
2434
+ const { stack } = run;
2435
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2436
+ printPlan(ctx, run);
2437
+ if (stack.proxy === "traefik") {
2438
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT})…`);
2439
+ run.files.push(...await ensureEdge(deps.docker, {
2440
+ file: edgeFile(run),
2441
+ ports,
2442
+ ...ref.host ? { host: ref.host } : {},
2443
+ logging: {
2444
+ driver: LOG_ROTATION.driver,
2445
+ options: { ...LOG_ROTATION.options }
2446
+ },
2447
+ ...ref.output ? { output: ref.output } : {},
2448
+ ...ref.signal ? { signal: ref.signal } : {}
2449
+ }));
2450
+ applied(ctx, run, {
2451
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
2452
+ resourceType: "service",
2453
+ action: "ensure",
2454
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
2455
+ via: "found"
2456
+ });
2457
+ if (stack.wildcard?.tls === "dns") await edgeAcmeKey(ctx, run, deps);
2458
+ }
2459
+ if (stack.infra.length > 0) {
2460
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
2461
+ await deps.docker.up(ref, stack.infra);
2462
+ for (const service of stack.infra) applied(ctx, run, {
2463
+ key: `service:${service}`,
2464
+ resourceType: "service",
2465
+ action: "ensure",
2466
+ id: `${stack.project}/${service}`,
2467
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
2468
+ });
2469
+ }
2470
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
2471
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
2472
+ }
2473
+ /**
2474
+ * Subscribe each topic subscriber SNS pushes to — for a topic the stage set
2475
+ * to SNS by hand — record the ARNs, and compose the stack again with them,
2476
+ * before a file is written.
2477
+ */
2478
+ async function subscribeTopics(ctx, run, deps) {
2479
+ const { pushes, recorded, restack } = run.topicSubscriptions;
2480
+ if (pushes.length > 0) ctx.logger.info("\n📮 SNS subscriptions for the stage's own topics");
2481
+ run.stack = restack(await ensureTopicSubscriptions({
2482
+ pushes,
2483
+ recorded,
2484
+ secrets: run.secrets?.custom ?? {},
2485
+ stage: ctx.stage,
2486
+ env: deps.env,
2487
+ record: async (resource) => {
2488
+ await ctx.state.putResource(ctx.stage, resource);
2489
+ applied(ctx, run, {
2490
+ key: resource.key,
2491
+ resourceType: SUBSCRIPTION_TYPE,
2492
+ action: "ensure",
2493
+ id: resource.id,
2494
+ via: recorded?.[resource.key]?.id === resource.id ? "recorded" : "created"
2495
+ });
2496
+ },
2497
+ forget: async (key) => {
2498
+ await ctx.state.deleteResource(ctx.stage, key);
2499
+ },
2500
+ log: (line) => ctx.logger.info(line)
2501
+ }));
2502
+ }
2503
+ /**
2504
+ * Create each bucket the stack's MinIO serves, and the open paths of each
2505
+ * one a file server fronts — from this machine, on MinIO's loopback port,
2506
+ * the way `gkm dev` creates them.
2507
+ */
2508
+ async function prepareBuckets(ctx, run, deps) {
2509
+ const storage = run.stack.storage;
2510
+ if (storage.buckets.length === 0) return;
2511
+ const tunnel = await reach(run, deps, "minio", LOOPBACK_SERVICES.minio);
2512
+ let done;
2513
+ try {
2514
+ const client = deps.buckets(tunnel.port, storage);
2515
+ done = [
2516
+ ...await applyBuckets(client, storage.buckets),
2517
+ ...await applyPolicies(client, storage.policies),
2518
+ ...await applyLifecycles(client, storage.lifecycles),
2519
+ ...await applyNotifications(client, storage.objects, new Set(storage.webhooks.map((hook) => hook.bucket)))
2520
+ ];
2521
+ } finally {
2522
+ await tunnel.close();
2523
+ }
2524
+ const created = done.filter((entry) => entry.created).length;
2525
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
2526
+ }
2527
+ /**
2528
+ * Create what the plan names in the stack's Postgres, migrate it, then run
2529
+ * its seeds — every one, every time, as each construct's owner.
2530
+ *
2531
+ * Every service the stack publishes on its loopback is reached, not only
2532
+ * Postgres: a seed runs project code, and project code that uploads a file
2533
+ * reaches the stack's MinIO as well.
2534
+ */
2535
+ async function prepareDatabases(ctx, run, deps) {
2536
+ const tunnels = [];
2537
+ try {
2538
+ const ports = {};
2539
+ for (const [service, inside] of Object.entries(LOOPBACK_SERVICES)) {
2540
+ if (!run.stack.infra.includes(service)) continue;
2541
+ const tunnel = await reach(run, deps, service, inside);
2542
+ tunnels.push(tunnel);
2543
+ ports[primaryPortKey(service)] = tunnel.port;
2544
+ }
2545
+ await migrateAndSeed(ctx, run, deps, ports);
2546
+ } finally {
2547
+ await Promise.all(tunnels.map((tunnel) => tunnel.close()));
2548
+ }
2549
+ }
2550
+ /**
2551
+ * A port a stack's service publishes on its engine's loopback, reachable
2552
+ * from this machine: the published port itself on the local stage, and on a
2553
+ * server an SSH tunnel to it over the deploy's own login — so Postgres and
2554
+ * MinIO are never published beyond the server's loopback.
2555
+ *
2556
+ * Migrations and seeds run here, in this process, with the project's own
2557
+ * Kysely — the way `gkm migrate` runs them — through that port. No image
2558
+ * needs to carry them, and nothing is run on the server but the stack.
2559
+ */
2560
+ async function reach(run, deps, service, inside) {
2561
+ const published = await deps.docker.port(run.ref, service, inside);
2562
+ if (!run.server) return {
2563
+ port: published,
2564
+ close: async () => {}
2565
+ };
2566
+ return deps.server.tunnel(run.server, published);
2567
+ }
2568
+ async function migrateAndSeed(ctx, run, deps, ports) {
2569
+ const { stack } = run;
2570
+ const workspace = ctx.workspace;
2571
+ const port = ports[primaryPortKey("postgres")];
2572
+ const superuser = stack.credential.containers.postgres;
2573
+ const login = await deps.logins({
2574
+ port,
2575
+ login: superuser,
2576
+ legacy: [{
2577
+ user: LEGACY_LOCAL_LOGIN.user,
2578
+ password: superuser.password
2579
+ }, ...stack.local ? [LEGACY_LOCAL_LOGIN] : []]
2580
+ });
2581
+ if (login.notice) ctx.logger.info(login.notice);
2582
+ const statements = [...postgresStatements(stack.plan, workspace.name, stack.credential.seed), ...stack.backups ? backupsRoleStatements(stack.backups) : []];
2583
+ if (statements.length > 0) {
2584
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
2585
+ await applyPostgres(deps.sql(port, login.login), statements);
2586
+ }
2587
+ const sources = {};
2588
+ const manifest = await discover({
2589
+ patterns: constructGlobs(workspace),
2590
+ cwd: workspace.root,
2591
+ sources
2592
+ });
2593
+ const custom = run.secrets?.custom ?? {};
2594
+ const resolved = envFor(stack.plan, {
2595
+ ...stack.resolution,
2596
+ ports,
2597
+ credentials: {
2598
+ ...stack.resolution.credentials,
2599
+ postgres: login.login
2600
+ }
2601
+ });
2602
+ const env = stageEnv(run.secrets ? toEmbeddableSecrets(run.secrets) : {}, Object.fromEntries(Object.entries(resolved).filter(([key]) => custom[key] === void 0)));
2603
+ const options = {
2604
+ root: workspace.root,
2605
+ manifest,
2606
+ sources,
2607
+ env
2608
+ };
2609
+ const runs = await deps.migrate(options);
2610
+ const seeds = await deps.seed({
2611
+ ...options,
2612
+ stage: ctx.stage,
2613
+ backends: backendsOf(workspace)
2614
+ }).catch((error) => {
2615
+ if (error instanceof SeedFailed) throw new DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
2616
+ throw error;
2617
+ });
2618
+ reportDatabaseRuns(runs.map(({ target, applied }) => ({
2619
+ construct: target.id,
2620
+ folder: target.migrations,
2621
+ applied
2622
+ })), seeds.map(({ target, seeded }) => ({
2623
+ construct: target.id,
2624
+ folder: target.seeds,
2625
+ seeded
2626
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
2627
+ }
2628
+ /**
2629
+ * Each app's image: built from this checkout — inside Docker, every one of
2630
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
2631
+ * live changes.
2632
+ */
2633
+ async function buildCompose(ctx, run, deps) {
2634
+ const { stack, ref } = run;
2635
+ const images = [
2636
+ ...stack.apps,
2637
+ ...stack.workers,
2638
+ ...stack.processors
2639
+ ];
2640
+ const apps = images.map((image) => image.app);
2641
+ if (run.push) {
2642
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2643
+ printPlan(ctx, run);
2644
+ }
2645
+ const prerendered = prerenderedHere(run);
2646
+ if (run.push) await stageAnswers(ctx, run, deps, prerendered);
2647
+ const held = new Set(run.push ? [] : prerendered.map(({ app }) => app));
2648
+ const now = images.filter((image) => !held.has(image.app));
2649
+ if (run.mode === "build") {
2650
+ ctx.logger.info("\n🐳 Building images…");
2651
+ await deps.docker.build(ref, now.map((image) => image.app));
2652
+ } else {
2653
+ ctx.logger.info(`\n🐳 Pulling ${stageTag(ctx.tag, ctx.stage)}…`);
2654
+ await deps.docker.pull(ref, apps);
2655
+ }
2656
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
2657
+ await recordBuilt(ctx, run, deps, now);
2658
+ }
2659
+ /**
2660
+ * Each image's tag as it resolved — the registry's digest for a pushed or
2661
+ * pulled image, or, for one built here and never pushed, its content id —
2662
+ * in the run, and said.
2663
+ */
2664
+ async function recordBuilt(ctx, run, deps, images) {
2665
+ const { ref } = run;
2666
+ for (const image of images) {
2667
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(ref, image.ref);
2668
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
2669
+ run.images[image.app] = {
2670
+ ref: image.ref,
2671
+ tag: image.tag,
2672
+ ...digest ? { digest } : {}
2673
+ };
2674
+ ctx.emit({
2675
+ type: "artifact.built",
2676
+ app: image.app,
2677
+ imageRef: image.ref,
2678
+ ...digest ? { digest } : {}
2679
+ });
2680
+ run.changes.push({
2681
+ key: `image:${image.app}`,
2682
+ resourceType: "image",
2683
+ action: run.mode === "build" ? "build" : "reuse",
2684
+ id: digest ?? image.ref
2685
+ });
2686
+ }
2687
+ }
2688
+ /**
2689
+ * The whole stack up — anything it no longer defines removed — and each
2690
+ * app's image recorded in the stage's state.
2691
+ */
2692
+ async function releaseCompose(ctx, run, deps) {
2693
+ const { stack, ref } = run;
2694
+ if (run.push) return;
2695
+ const edge = edgeRef(edgeFile(run), {
2696
+ ...ref.host ? { host: ref.host } : {},
2697
+ ...ref.output ? { output: ref.output } : {}
2698
+ });
2699
+ if (stack.proxy === "traefik" && stack.traefik) {
2700
+ const written = await writeEdgeRoutes(deps.docker, edge, stack.project, stack.traefik, await edgeCertificate(run.dir, stack));
2701
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
2702
+ } else if (!stack.local || existsSync(edgeFile(run))) await removeEdgeRoutes(deps.docker, edge, stack.project);
2703
+ const prerendered = prerenderedHere(run);
2704
+ if (prerendered.length > 0) await buildAgainstStage(ctx, run, deps, prerendered);
2705
+ ctx.logger.info("\n🚀 Starting the stack…");
2706
+ const down = await deps.docker.up(ref).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error));
2707
+ const isDown = new Set(down.map(({ app }) => app));
2708
+ await recordImages(ctx, run);
2709
+ for (const app of stack.apps) {
2710
+ if (isDown.has(app.name)) continue;
2711
+ const image = run.images[app.name];
2712
+ applied(ctx, run, {
2713
+ key: `service:${app.name}`,
2714
+ resourceType: "service",
2715
+ action: "ensure",
2716
+ id: `${stack.project}/${app.name}`,
2717
+ via: run.previous[app.name] ? "recorded" : "created"
2718
+ });
2719
+ ctx.emit({
2720
+ type: "app.deployed",
2721
+ app: app.name,
2722
+ applicationId: `${stack.project}/${app.name}`,
2723
+ imageRef: image?.ref ?? app.ref,
2724
+ url: app.url
2725
+ });
2726
+ }
2727
+ for (const worker of [...stack.workers, ...stack.processors]) {
2728
+ if (isDown.has(worker.name)) continue;
2729
+ applied(ctx, run, {
2730
+ key: `service:${worker.name}`,
2731
+ resourceType: "service",
2732
+ action: "ensure",
2733
+ id: `${stack.project}/${worker.name}`,
2734
+ via: run.previous[worker.name] ? "recorded" : "created"
2735
+ });
2736
+ }
2737
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
2738
+ for (const app of stack.apps) {
2739
+ if (isDown.has(app.name)) continue;
2740
+ ctx.logger.info(` ${app.name.padEnd(12)} ${app.url}${app.auth ? ` 🔒 user: ${app.auth.user}, password: gkm secrets:show --stage ${ctx.stage} --reveal → ${app.auth.key}` : ""}`);
2741
+ }
2742
+ if (stack.mailInbox) ctx.logger.info(` ${"mail".padEnd(12)} ${stack.mailInbox.url} (inbox)`);
2743
+ for (const worker of stack.workers) {
2744
+ if (isDown.has(worker.name)) continue;
2745
+ ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
2746
+ }
2747
+ for (const unit of stack.processors) {
2748
+ if (isDown.has(unit.name)) continue;
2749
+ ctx.logger.info(` ${unit.name.padEnd(12)} processors of ${unit.id}`);
2750
+ }
2751
+ if (stack.authority) ctx.logger.info(`\n🔐 Certificates are from gkm's local CA ("gkm trust" trusts it here): NODE_EXTRA_CA_CERTS=${stack.authority.certFile}`);
2752
+ else if (stack.local && stack.tls) ctx.logger.info(stack.tls.caFile ? `\n🔐 Certificates are the stage's own (deploy.compose.tls), from the CA in ${stack.tls.caFile}: NODE_EXTRA_CA_CERTS=${stack.tls.caFile}` : `\n🔐 Certificates are the stage's own (deploy.compose.tls): ${stack.tls.certFile}. Set its caFile to the root it chains to, so gkm and the stack's containers trust it.`);
2753
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy, "docker");
2754
+ }
2755
+ /**
2756
+ * After `up --wait` failed: each app's and worker's service that is not
2757
+ * healthy once its health settles — waited on while it is still starting,
2758
+ * as `--wait` stops at the first that is not. None means the failure was not
2759
+ * health's, and it is thrown as it was.
2760
+ */
2761
+ async function unhealthyAfterUp(ctx, run, deps, error, except = /* @__PURE__ */ new Set()) {
2762
+ const { stack } = run;
2763
+ const services = [
2764
+ ...stack.apps.flatMap(replicaNames),
2765
+ ...stack.workers.map((worker) => worker.name),
2766
+ ...stack.processors.map((unit) => unit.name)
2767
+ ].filter((service) => !except.has(service));
2768
+ const down = (await Promise.all(services.map(async (service) => {
2769
+ let last;
2770
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2771
+ ctx.signal.throwIfAborted();
2772
+ last = await deps.docker.health(run.ref, service).catch(() => void 0);
2773
+ if (last !== "starting") break;
2774
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2775
+ }
2776
+ return {
2777
+ app: service,
2778
+ url: `docker:${service}`,
2779
+ last
2780
+ };
2781
+ }))).filter(({ last }) => last !== "healthy").map(({ app, url, last }) => ({
2782
+ app,
2783
+ url,
2784
+ last: last ?? "not running"
2785
+ }));
2786
+ if (down.length === 0) throw error;
2787
+ ctx.logger.warn(`\n⚠️ ${down.map(({ app }) => app).join(", ")} did not turn healthy; the rest of the stack is released and routed.`);
2788
+ return down;
2789
+ }
2790
+ /**
2791
+ * Where a check through the edge connects: this machine for the local stage,
2792
+ * a deployed stage's server on its published port — or, for a push, which
2793
+ * has no server, wherever the host resolves.
2794
+ */
2795
+ function edgeTarget(run, deps) {
2796
+ if (run.stack.local) return { connectTo: "127.0.0.1" };
2797
+ if (run.server) return {
2798
+ connectTo: run.server.host,
2799
+ connectPort: edgePorts(deps.env).https
2800
+ };
2801
+ }
2802
+ /**
2803
+ * The sites this run builds against their stage's running APIs
2804
+ * (`prerender: 'stage'`). None for a run that pulls: a pulled image was built
2805
+ * against the stage when it was pushed.
2806
+ */
2807
+ function prerenderedHere(run) {
2808
+ if (run.mode !== "build") return [];
2809
+ return run.stack.apps.filter((app) => app.prerender && app.build);
2810
+ }
2811
+ /**
2812
+ * A site that pre-renders against its stage, built once its APIs answer:
2813
+ * every service of the stack started but those sites — `up --wait`, so each
2814
+ * is healthy by its own check — then each API the site depends on asked
2815
+ * through the edge, as a browser reaches it, and only then the site built.
2816
+ * The full `up` that follows starts it.
2817
+ */
2818
+ async function buildAgainstStage(ctx, run, deps, sites) {
2819
+ const { stack, ref } = run;
2820
+ const held = new Set(sites.flatMap(replicaNames));
2821
+ const services = Object.keys(stack.compose.services).filter((service) => !held.has(service));
2822
+ ctx.logger.info(`\n🚀 Starting the stack, but ${listNames(sites)}, built once its APIs answer…`);
2823
+ const down = await deps.docker.up(ref, services).then(() => [], (error) => unhealthyAfterUp(ctx, run, deps, error, held));
2824
+ for (const site of sites) {
2825
+ const against = new Set(site.prerender?.against);
2826
+ const blocking = down.filter(({ app }) => against.has(app));
2827
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, "docker");
2828
+ }
2829
+ await stageAnswers(ctx, run, deps, sites);
2830
+ ctx.logger.info(`\n🐳 Building ${listNames(sites)} against the stage's APIs…`);
2831
+ await deps.docker.build(ref, sites.map((site) => site.app));
2832
+ await recordBuilt(ctx, run, deps, sites);
2833
+ }
2834
+ /** `web` — or `docs and web`. */
2835
+ function listNames(apps) {
2836
+ const names = apps.map(({ name }) => name);
2837
+ return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0] ?? "";
2838
+ }
2839
+ /**
2840
+ * Each API a site pre-rendered against its stage depends on, asked through
2841
+ * the edge as `verify` asks it — the address the site's build fetches from.
2842
+ * Any that does not answer fails the run before the site is built: a build
2843
+ * that cannot reach them bakes in pages without their data.
2844
+ */
2845
+ async function stageAnswers(ctx, run, deps, sites) {
2846
+ const { stack } = run;
2847
+ const names = new Set(sites.flatMap((site) => site.prerender?.against ?? []));
2848
+ const apps = stack.apps.filter((app) => names.has(app.name));
2849
+ if (apps.length === 0) return;
2850
+ ctx.logger.info(`\n🩺 Checking the APIs ${listNames(sites)} ${sites.length > 1 ? "pre-render" : "pre-renders"} from…`);
2851
+ const ca = await verifyAuthority(stack);
2852
+ const edge = edgeTarget(run, deps);
2853
+ const results = await Promise.all(apps.map((app) => app.id === stack.wildcard?.site && !run.push ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2854
+ ca,
2855
+ edge
2856
+ })));
2857
+ const down = new Map(results.filter((r) => !r.healthy).map((r) => [r.app, r]));
2858
+ for (const site of sites) {
2859
+ const blocking = (site.prerender?.against ?? []).flatMap((name) => {
2860
+ const result = down.get(name);
2861
+ return result ? [result] : [];
2862
+ });
2863
+ if (blocking.length > 0) throw new SitePrerenderApisDown(site.name, blocking, run.push ? "push" : "edge");
2864
+ }
2865
+ }
2866
+ /**
2867
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
2868
+ * records: the ref it runs, the tag it was released under, and the digest
2869
+ * the tag resolved to.
2870
+ */
2871
+ async function recordImages(ctx, run) {
2872
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
2873
+ const by = currentActor();
2874
+ for (const app of [
2875
+ ...run.stack.apps,
2876
+ ...run.stack.workers,
2877
+ ...run.stack.processors
2878
+ ]) {
2879
+ const image = run.images[app.app] ?? {
2880
+ ref: app.ref,
2881
+ tag: app.tag
2882
+ };
2883
+ recordRelease(journal.state, app.app, image, by);
2884
+ }
2885
+ journal.state.identity = ctx.identity.key;
2886
+ await journal.save();
2887
+ }
2888
+ /**
2889
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
2890
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
2891
+ * its certificate is from gkm's local CA, so that root is the one trusted and
2892
+ * the request goes to 127.0.0.1.
2893
+ */
2894
+ async function verifyCompose(ctx, run, deps) {
2895
+ const { stack } = run;
2896
+ if (run.push) return;
2897
+ const ca = await verifyAuthority(stack);
2898
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
2899
+ const edge = edgeTarget(run, deps);
2900
+ const results = await Promise.all(stack.apps.map((app) => app.id === stack.wildcard?.site ? checkContainer(ctx, run, deps, app.name) : checkApp(ctx, app, deps, {
2901
+ ca,
2902
+ edge
2903
+ })));
2904
+ results.push(...await Promise.all([...stack.workers, ...stack.processors].map((worker) => checkContainer(ctx, run, deps, worker.name))));
2905
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
2906
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
2907
+ app,
2908
+ url,
2909
+ last
2910
+ }));
2911
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
2912
+ await pruneStageDns(ctx, run);
2913
+ await confirmSubscriptions(ctx, run, deps);
2914
+ await warmSites(ctx, run, deps, {
2915
+ ca,
2916
+ edge
2917
+ });
2918
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local, run.server);
2919
+ }
2920
+ /**
2921
+ * Each server-rendered site (`next`, `tanstack`) asked for its sitemap, its
2922
+ * `/` and every page the sitemap lists, through the edge as `checkApp` asks
2923
+ * it — see `warmup.ts`. Its image was built with no API reachable, so each
2924
+ * page renders on its first request: this is that request, made before any
2925
+ * visitor's. A Next site is asked with its on-demand revalidation header,
2926
+ * so a page its build cached (empty) is rendered again from the deployed
2927
+ * APIs rather than served from that cache.
2928
+ *
2929
+ * Only ever said, never failed on: every app is already healthy, and a page
2930
+ * that did not warm renders on the next request for it.
2931
+ */
2932
+ async function warmSites(ctx, run, deps, options) {
2933
+ const { stack } = run;
2934
+ const sites = stack.apps.filter((app) => app.kind === "site" && (app.variant === "next" || app.variant === "tanstack"));
2935
+ if (sites.length === 0) return;
2936
+ ctx.logger.info("\n🔥 Warming each server-rendered site…");
2937
+ for (const app of sites) {
2938
+ if (app.id === stack.wildcard?.site) {
2939
+ ctx.logger.info(` – ${app.name.padEnd(12)} serves every subdomain: there is no one host to warm, so it is skipped`);
2940
+ continue;
2941
+ }
2942
+ try {
2943
+ const headers = app.variant === "next" ? await forceRender(ctx, run, deps, app) : {};
2944
+ const { warmed, cached, warnings, leftOut } = await warmSite({
2945
+ url: app.url,
2946
+ fetch: deps.fetch ?? edgeFetch,
2947
+ headers,
2948
+ edge: {
2949
+ ...options.ca ? { ca: options.ca } : {},
2950
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
2951
+ ...options.edge,
2952
+ signal: ctx.signal
2953
+ }
2954
+ });
2955
+ const said = `warmed ${warmed.length} page(s)${cached.length > 0 ? `, ${cached.length} served from the build cache` : ""}${warnings.length > 0 ? `, ${warnings.length} warning(s)` : ""}`;
2956
+ if (warnings.length === 0) ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${said}${cached.length > 0 ? `: ${listed(cached)}` : ""}`);
2957
+ else {
2958
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} ${said}:`);
2959
+ for (const { url, reason } of warnings) ctx.logger.warn(` ${url}: ${reason}`);
2960
+ if (cached.length > 0) ctx.logger.warn(` served from the build cache: ${listed(cached)}`);
2961
+ }
2962
+ if (leftOut > 0) ctx.logger.info(` ${leftOut} more page(s) in its sitemap were not asked: at most 500 are warmed per site`);
2963
+ } catch (error) {
2964
+ if (ctx.signal.aborted) throw error;
2965
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} not warmed: ${error instanceof Error ? error.message : String(error)}`);
2966
+ }
2967
+ }
2968
+ }
2969
+ /** The most pages a summary names; the rest are counted. */
2970
+ const LISTED_PAGES = 10;
2971
+ /** Pages by path, `/about`, the first {@link LISTED_PAGES} of them. */
2972
+ function listed(urls) {
2973
+ const paths = urls.map((url) => {
2974
+ const { pathname, search } = new URL(url);
2975
+ return `${pathname}${search}`;
2976
+ });
2977
+ const shown = paths.slice(0, LISTED_PAGES).join(", ");
2978
+ return paths.length > LISTED_PAGES ? `${shown} and ${paths.length - LISTED_PAGES} more` : shown;
2979
+ }
2980
+ /**
2981
+ * The header that has a Next site render each warmed page whatever its
2982
+ * cache says: `x-prerender-revalidate` with the preview-mode id of the image
2983
+ * running — read in its container, through the stack's Docker engine, at
2984
+ * the path the generated Dockerfile puts the standalone output at. Where the
2985
+ * id cannot be read, said once, and the site is warmed with plain requests.
2986
+ */
2987
+ async function forceRender(ctx, run, deps, app) {
2988
+ let reason;
2989
+ try {
2990
+ const root = ctx.workspace.root;
2991
+ const gkmRoot = relative(findBuildRoot(root), root) || ".";
2992
+ const lookup = await nextPreviewModeId((command) => deps.docker.exec(run.ref, app.name, command), nextPrerenderManifest(fromBuildRoot({ gkmRoot }, app.path)));
2993
+ if ("id" in lookup) return { [NEXT_REVALIDATE_HEADER]: lookup.id };
2994
+ reason = lookup.reason;
2995
+ } catch (error) {
2996
+ if (ctx.signal.aborted) throw error;
2997
+ reason = error instanceof Error ? error.message : String(error);
2998
+ }
2999
+ ctx.logger.warn(` ⚠ ${app.name.padEnd(12)} can't force ISR pages to render: ${reason}. Warming with plain requests; a page Next cached at build is served from that cache until its revalidate window ends.`);
3000
+ return {};
3001
+ }
3002
+ /**
3003
+ * The SNS subscriptions the stage's providers made before the workers were
3004
+ * up: each still pending is subscribed again, so SNS resends its
3005
+ * confirmation to a worker now there to answer it, and waited on. One still
3006
+ * pending after that is said, not failed on — every app is healthy, and
3007
+ * rolling them back would not confirm it.
3008
+ */
3009
+ async function confirmSubscriptions(ctx, run, deps) {
3010
+ const stored = await ctx.state.read(ctx.stage);
3011
+ const left = await (deps.confirmSubscriptions ?? confirmPendingSubscriptions)({
3012
+ workspace: ctx.workspace,
3013
+ stage: ctx.stage,
3014
+ secrets: run.secrets?.custom ?? {},
3015
+ resources: stored?.resources,
3016
+ env: deps.env,
3017
+ log: (line) => ctx.logger.info(line),
3018
+ record: async (record) => {
3019
+ const { updatedAt: _, updatedBy: __, ...input } = record;
3020
+ await ctx.state.putResource(ctx.stage, input);
3021
+ }
3022
+ });
3023
+ if (left.length > 0) ctx.logger.warn(`⚠ ${new PushSubscriptionsUnconfirmed(left).message}`);
3024
+ }
3025
+ /**
3026
+ * A container's own health check, as Docker reports it: a worker's, which
3027
+ * has no route through the edge, and OpenObserve's — by default it has no
3028
+ * host there, and served publicly it answers only the addresses it allows,
3029
+ * which need not include this one.
3030
+ */
3031
+ async function checkContainer(ctx, run, deps, service) {
3032
+ const url = `docker:${service}`;
3033
+ let last = "not asked";
3034
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3035
+ ctx.signal.throwIfAborted();
3036
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
3037
+ last = health ?? "not running";
3038
+ const healthy = health === "healthy";
3039
+ ctx.emit({
3040
+ type: "health.checked",
3041
+ app: service,
3042
+ url,
3043
+ healthy,
3044
+ attempt
3045
+ });
3046
+ if (healthy) {
3047
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
3048
+ return {
3049
+ app: service,
3050
+ url,
3051
+ last,
3052
+ healthy
3053
+ };
3054
+ }
3055
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3056
+ }
3057
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
3058
+ return {
3059
+ app: service,
3060
+ url,
3061
+ last,
3062
+ healthy: false
3063
+ };
3064
+ }
3065
+ /** A login, as the `Authorization` header that carries it. */
3066
+ function basicAuthorization(auth) {
3067
+ return `Basic ${Buffer.from(`${auth.user}:${auth.password}`).toString("base64")}`;
3068
+ }
3069
+ /** How to open the logs, printed — and as an event, for a headless caller. */
3070
+ function reportLogs(ctx, logs, local, server) {
3071
+ const lines = logsAccess(logs, {
3072
+ stage: ctx.stage,
3073
+ local,
3074
+ user: server?.user ?? currentUser(),
3075
+ hostname: server?.host ?? hostname(),
3076
+ ...server ? { known: true } : {}
3077
+ });
3078
+ ctx.logger.info(`\n${lines.join("\n")}`);
3079
+ ctx.emit({
3080
+ type: "logs.ready",
3081
+ service: LOGS_SERVICE,
3082
+ access: logs.public ? "public" : "tunnel",
3083
+ url: logs.url,
3084
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
3085
+ email: logs.email
3086
+ });
3087
+ }
3088
+ /** This machine's user — a guess at who would SSH in. */
3089
+ function currentUser() {
3090
+ try {
3091
+ return userInfo().username;
3092
+ } catch {
3093
+ return process.env.USER ?? "user";
3094
+ }
3095
+ }
3096
+ async function checkApp(ctx, app, deps, options) {
3097
+ const url = `${app.url.replace(/^ws/, "http")}${app.kind === "site" ? "/" : "/health"}`;
3098
+ let last = "not asked";
3099
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
3100
+ ctx.signal.throwIfAborted();
3101
+ let status;
3102
+ try {
3103
+ status = await deps.probe({
3104
+ url,
3105
+ ...options.ca ? { ca: options.ca } : {},
3106
+ ...app.auth ? { authorization: basicAuthorization(app.auth) } : {},
3107
+ ...options.edge,
3108
+ timeoutMs: 1e4,
3109
+ signal: ctx.signal
3110
+ });
3111
+ last = `HTTP ${status}`;
3112
+ } catch (error) {
3113
+ last = error instanceof Error ? error.message : String(error);
3114
+ }
3115
+ const healthy = status !== void 0 && isHealthy(status);
3116
+ ctx.emit({
3117
+ type: "health.checked",
3118
+ app: app.name,
3119
+ url,
3120
+ healthy,
3121
+ ...status !== void 0 ? { status } : {},
3122
+ attempt
3123
+ });
3124
+ if (healthy) {
3125
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
3126
+ return {
3127
+ app: app.name,
3128
+ url,
3129
+ last,
3130
+ healthy
3131
+ };
3132
+ }
3133
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
3134
+ }
3135
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
3136
+ return {
3137
+ app: app.name,
3138
+ url,
3139
+ last,
3140
+ healthy: false
3141
+ };
3142
+ }
3143
+ function composeResult(ctx, run) {
3144
+ const apps = [...run.stack.apps.map((app) => {
3145
+ const image = run.images[app.name];
3146
+ return {
3147
+ appName: app.name,
3148
+ type: app.kind === "site" ? "web" : "backend",
3149
+ success: !ctx.dryRun,
3150
+ applicationId: `${run.stack.project}/${app.name}`,
3151
+ imageRef: image?.ref ?? app.ref,
3152
+ ...image?.digest ? { digest: image.digest } : {},
3153
+ url: app.url
3154
+ };
3155
+ }), ...[...run.stack.workers, ...run.stack.processors].map((worker) => {
3156
+ const image = run.images[worker.name];
3157
+ return {
3158
+ appName: worker.name,
3159
+ type: "backend",
3160
+ success: !ctx.dryRun,
3161
+ applicationId: `${run.stack.project}/${worker.name}`,
3162
+ imageRef: image?.ref ?? worker.ref,
3163
+ ...image?.digest ? { digest: image.digest } : {}
3164
+ };
3165
+ })];
3166
+ return {
3167
+ apps,
3168
+ projectId: run.stack.project,
3169
+ successCount: ctx.dryRun ? 0 : apps.length,
3170
+ failedCount: 0,
3171
+ stage: ctx.stage,
3172
+ identity: ctx.identity.key,
3173
+ tag: stageTag(ctx.tag, ctx.stage),
3174
+ dryRun: ctx.dryRun,
3175
+ environmentId: "",
3176
+ skipped: [...ctx.skipped],
3177
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
3178
+ changes: run.changes
3179
+ };
3180
+ }
3181
+ /** The shared edge's compose file, as this machine hands it to compose. */
3182
+ function edgeFile(run) {
3183
+ return join(run.dir, `${EDGE_PROJECT}.yml`);
3184
+ }
3185
+ function applied(ctx, run, change) {
3186
+ const { via, ...rest } = change;
3187
+ run.changes.push(rest);
3188
+ ctx.emit({
3189
+ type: "resource.applied",
3190
+ ...rest,
3191
+ via
3192
+ });
3193
+ }
3194
+ /**
3195
+ * The root the check after a start trusts, PEM: gkm's on the local stage that
3196
+ * set no certificate of its own, and otherwise the one the stage's own names
3197
+ * (`deploy.compose.tls.<stage>.caFile`). Undefined — Node's own roots, and
3198
+ * `NODE_EXTRA_CA_CERTS` — for a certificate that names none: a public CA's.
3199
+ */
3200
+ async function verifyAuthority(stack) {
3201
+ if (stack.authority) return (await readLocalAuthority(stack.authority)).cert;
3202
+ if (stack.tls?.caFile) return readFile(stack.tls.caFile, "utf-8");
3203
+ }
3204
+ /**
3205
+ * The certificate the stack's proxy serves, PEM: the stage's own where it set
3206
+ * one, the one gkm's local CA issued the local stage otherwise, and none — a
3207
+ * deployed stage's comes from Let's Encrypt — when neither.
3208
+ */
3209
+ async function edgeCertificate(dir, stack) {
3210
+ if (stack.tls) return {
3211
+ cert: await readFile(stack.tls.certFile, "utf-8"),
3212
+ key: await readFile(stack.tls.keyFile, "utf-8")
3213
+ };
3214
+ if (stack.authority) return localEdgeCertificate(dir, stack, stack.authority);
3215
+ }
3216
+ /** Where the local stage's edge certificate is kept, between runs. */
3217
+ const LOCAL_EDGE_CERTIFICATE = "local-edge.pem";
3218
+ /**
3219
+ * The local stage's edge certificate, from gkm's local CA: the one kept in
3220
+ * the stack's directory while it still covers every host, so an unchanged
3221
+ * stack does not recreate its Caddy for a new certificate each run.
3222
+ */
3223
+ async function localEdgeCertificate(dir, stack, authority) {
3224
+ const { cert, key } = await ensureLocalCertificate(await ensureLocalAuthority(authority), localCertificateNames(stack.resolution.project ?? "", stackHosts(stack)), join(dir, LOCAL_EDGE_CERTIFICATE));
3225
+ return {
3226
+ cert,
3227
+ key
3228
+ };
3229
+ }
3230
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
3231
+ async function writeStack(root, dir, stack) {
3232
+ await mkdir(dir, {
3233
+ recursive: true,
3234
+ mode: 448
3235
+ });
3236
+ await chmod(dir, 448);
3237
+ const files = [];
3238
+ const write = async (path, content, mode = 420) => {
3239
+ await mkdir(dirname(path), { recursive: true });
3240
+ await writeFile(path, content, { mode });
3241
+ await chmod(path, mode);
3242
+ files.push(path);
3243
+ };
3244
+ const issued = await edgeCertificate(dir, stack);
3245
+ const tls = stack.proxy === "caddy" ? issued : void 0;
3246
+ const compose = stack.caddyfile !== void 0 ? withCaddyConfigs(stack.compose, {
3247
+ caddyfile: stack.caddyfile,
3248
+ ...tls ? { tls } : {}
3249
+ }) : stack.compose;
3250
+ await write(join(dir, "docker-compose.yml"), composeYaml(stack, compose), tls ? 384 : 420);
3251
+ if (stack.caddyfile !== void 0) {
3252
+ await write(join(dir, "Caddyfile"), stack.caddyfile);
3253
+ await rm(join(dir, "traefik.yml"), { force: true });
3254
+ } else await rm(join(dir, "Caddyfile"), { force: true });
3255
+ if (stack.traefik !== void 0) await write(join(dir, "traefik.yml"), stack.traefik);
3256
+ await rm(join(dir, "tls"), {
3257
+ recursive: true,
3258
+ force: true
3259
+ });
3260
+ for (const app of [
3261
+ ...stack.apps,
3262
+ ...stack.workers,
3263
+ ...stack.processors
3264
+ ]) if (app.env) await write(join(dir, `${app.name}.env`), envFile(app.env), 384);
3265
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write(join(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
3266
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write(join(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
3267
+ if (stack.backups) {
3268
+ for (const [name, content] of Object.entries(stack.backups.files)) await write(join(dir, BACKUPS_SERVICE, name), content);
3269
+ if (stack.compose.services["backups"]?.env_file) await write(join(dir, `${BACKUPS_SERVICE}.env`), envFile(stack.backups.env), 384);
3270
+ } else {
3271
+ await rm(join(dir, BACKUPS_SERVICE), {
3272
+ recursive: true,
3273
+ force: true
3274
+ });
3275
+ await rm(join(dir, `${BACKUPS_SERVICE}.env`), { force: true });
3276
+ }
3277
+ for (const entry of await readdir(dir)) if (entry.endsWith(".credentials")) await rm(join(dir, entry));
3278
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write(join(root, path), content);
3279
+ await ensureDockerignore(findBuildRoot(root));
3280
+ return files;
3281
+ }
3282
+ function composeYaml(stack, compose) {
3283
+ const stage = ` --stage ${stack.stage}`;
3284
+ return `# Generated by gkm compose from the construct manifest — do not edit.
3285
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
3286
+ # Each backend and worker reads exactly the keys in its own env file beside
3287
+ # this one.
3288
+ #
3289
+ # gkm compose${stage} start or update it
3290
+ # gkm compose${stage} --down stop it
3291
+ ${stringify(compose, {
3292
+ lineWidth: 0,
3293
+ aliasDuplicateObjects: false
3294
+ })}`;
3295
+ }
3296
+ function printPlan(ctx, run) {
3297
+ const { stack, mode, files } = run;
3298
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
3299
+ if (run.server) ctx.logger.info(` → ${sshTarget(run.server)} (docker over ssh)`);
3300
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
3301
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
3302
+ for (const unit of stack.processors) ctx.logger.info(` ${unit.name.padEnd(12)} ${`processors of ${unit.id}`.padEnd(40)} ${mode} ${unit.ref}`);
3303
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
3304
+ if (stack.backups) ctx.logger.info(` ${BACKUPS_SERVICE.padEnd(12)} ${stack.backups.databases.map((d) => d.file).join(", ")} — ${stack.backups.backups.describe}, to ${stack.backups.prefix}/`);
3305
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${stackDir(stack.stage)}/`);
3306
+ }
3307
+ //#endregion
3308
+ //#region src/target/compose/index.ts
3309
+ /**
3310
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
3311
+ * Caddy — the local stage on the machine that runs the deploy, a deployed
3312
+ * stage on its server's Docker engine, over SSH (`deploy.compose.server`).
3313
+ *
3314
+ * ```bash
3315
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
3316
+ * gkm deploy --target compose --stage production # built from here
3317
+ * gkm deploy --target compose --stage development # the local stage
3318
+ * ```
3319
+ *
3320
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
3321
+ * looked up in the registry — `ImageTagNotFound` before anything changes
3322
+ * - `ready`: a deploy's own checks, after the stage's keys are — the stage's
3323
+ * certificate, its server's address, and every public host's DNS
3324
+ * - `plan`: the stack's files and what a run would create or reuse
3325
+ * - `provision`: generated secrets kept, files written, infrastructure up,
3326
+ * databases, roles, grants and migrations
3327
+ * - `build`: each backend bundled on the host and every image built — or, for
3328
+ * a tag, pulled. A site that pre-renders against its stage
3329
+ * (`prerender: 'stage'`) is held back, but for a push, which first asks the
3330
+ * running stage's APIs and builds it against them
3331
+ * - `release`: the stack's routes on the shared edge; a held-back site built
3332
+ * once the rest of the stack is up and its APIs answer through the edge;
3333
+ * then `up --wait
3334
+ * --remove-orphans`, and each app's image, tag and digest in the stage's
3335
+ * state — an app that never turns healthy fails it only once the rest is
3336
+ * released and routed
3337
+ * - `verify`: each app asked through Caddy over HTTPS, then each
3338
+ * server-rendered site warmed — its `/` and its sitemap's pages asked, a
3339
+ * failure only warned of
3340
+ *
3341
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
3342
+ * every image and pushes it to `deploy.registry`, and does nothing else: no
3343
+ * readiness check runs, so a stage whose keys the deploy has yet to write
3344
+ * still builds.
3345
+ *
3346
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
3347
+ * `--down`), run through the same `deploy()`.
3348
+ */
3349
+ var compose_exports = /* @__PURE__ */ __exportAll({ composeTarget: () => composeTarget });
3350
+ /** The compose target, with its Docker, bundler and probe as given. */
3351
+ function composeTarget(options = {}) {
3352
+ const { mode, push, pin, report, ...given } = options;
3353
+ const deps = {
3354
+ ...defaultDeps,
3355
+ ...given
3356
+ };
3357
+ return defineTarget({
3358
+ name: "compose",
3359
+ runtime: "server",
3360
+ capabilities: {
3361
+ rollback: false,
3362
+ migrations: "target",
3363
+ images: true,
3364
+ localStage: true,
3365
+ selfHostedTelemetry: true
3366
+ },
3367
+ credentials: [],
3368
+ tag: ({ cwd }) => deps.revision(cwd),
3369
+ validate: (ctx) => validateCompose(ctx, deps, {
3370
+ ...mode ? { mode } : {},
3371
+ ...push ? { push } : {},
3372
+ ...pin ? { pin } : {}
3373
+ }),
3374
+ ready: (ctx, run) => readyCompose(ctx, run, deps),
3375
+ plan: (ctx, run) => planCompose(ctx, run),
3376
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
3377
+ build: (ctx, run) => buildCompose(ctx, run, deps),
3378
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
3379
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
3380
+ result: (ctx, run) => {
3381
+ report?.(run);
3382
+ return composeResult(ctx, run);
3383
+ }
3384
+ });
3385
+ }
3386
+ //#endregion
3387
+ export { ContainersNotStopped as _, edgePorts as a, parseDigests as c, removeEdgeRoutes as d, composeServer as f, ContainersNotStarted as g, sshTarget as h, ComposePushNeedsBuild as i, pinnedRef as l, sshAccess as m, compose_exports as n, stackOverrideFile as o, dockerHost as p, ComposePinNeedsPull as r, deployedStackSecrets as s, composeTarget as t, edgeRef as u, dockerCompose as v, projectNetwork as y };
3388
+
3389
+ //# sourceMappingURL=compose-C23RpAaF.mjs.map