@geekmidas/cli 10.0.0-alpha.17 → 10.0.0-alpha.171

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