@geekmidas/cli 10.0.0-alpha.1 → 10.0.0-alpha.100

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 (491) hide show
  1. package/README.md +326 -421
  2. package/bin/adjacent-tsconfig.mjs +97 -0
  3. package/bin/gkm.mjs +16 -2
  4. package/bin/owning-tsconfig-jsx-register.mjs +18 -0
  5. package/bin/owning-tsconfig-jsx.mjs +108 -0
  6. package/dist/EndpointGenerator-Br97xgs_.mjs +1031 -0
  7. package/dist/EndpointGenerator-Br97xgs_.mjs.map +1 -0
  8. package/dist/EndpointGenerator-By5_tYE9.cjs +1090 -0
  9. package/dist/EndpointGenerator-By5_tYE9.cjs.map +1 -0
  10. package/dist/GoDaddyProvider-CVnzcWX5.mjs +388 -0
  11. package/dist/GoDaddyProvider-CVnzcWX5.mjs.map +1 -0
  12. package/dist/GoDaddyProvider-DS4Wgu0c.cjs +388 -0
  13. package/dist/GoDaddyProvider-DS4Wgu0c.cjs.map +1 -0
  14. package/dist/{HostingerProvider-Cft7lEYr.mjs → HostingerProvider-BNpS9aRJ.mjs} +29 -25
  15. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +1 -0
  16. package/dist/{HostingerProvider-h3EbEp-Z.cjs → HostingerProvider-DR1iws1P.cjs} +29 -25
  17. package/dist/HostingerProvider-DR1iws1P.cjs.map +1 -0
  18. package/dist/LegacyStateStore-C2Xlqy4v.mjs +124 -0
  19. package/dist/LegacyStateStore-C2Xlqy4v.mjs.map +1 -0
  20. package/dist/LegacyStateStore-CoHPQMLO.cjs +124 -0
  21. package/dist/LegacyStateStore-CoHPQMLO.cjs.map +1 -0
  22. package/dist/LocalStateStore-BGDzf2f8.cjs +178 -0
  23. package/dist/LocalStateStore-BGDzf2f8.cjs.map +1 -0
  24. package/dist/LocalStateStore-By59pUve.mjs +167 -0
  25. package/dist/LocalStateStore-By59pUve.mjs.map +1 -0
  26. package/dist/OpenApiTsGenerator-BgSX_Z-e.cjs +541 -0
  27. package/dist/OpenApiTsGenerator-BgSX_Z-e.cjs.map +1 -0
  28. package/dist/OpenApiTsGenerator-C8aTX--y.mjs +536 -0
  29. package/dist/OpenApiTsGenerator-C8aTX--y.mjs.map +1 -0
  30. package/dist/{Route53Provider-di2fMM5N.cjs → Route53Provider-Bllus2NR.cjs} +21 -22
  31. package/dist/Route53Provider-Bllus2NR.cjs.map +1 -0
  32. package/dist/{Route53Provider-RdpUDJQk.mjs → Route53Provider-QXxjkZO1.mjs} +13 -13
  33. package/dist/Route53Provider-QXxjkZO1.mjs.map +1 -0
  34. package/dist/S3StateStore-CU485pYn.mjs +223 -0
  35. package/dist/S3StateStore-CU485pYn.mjs.map +1 -0
  36. package/dist/S3StateStore-Re4LfDTl.cjs +222 -0
  37. package/dist/S3StateStore-Re4LfDTl.cjs.map +1 -0
  38. package/dist/SSMStateStore-BquRBbUG.mjs +205 -0
  39. package/dist/SSMStateStore-BquRBbUG.mjs.map +1 -0
  40. package/dist/SSMStateStore-CLX4Dm5d.cjs +204 -0
  41. package/dist/SSMStateStore-CLX4Dm5d.cjs.map +1 -0
  42. package/dist/SubscriberGenerator-1-IsjIwF.mjs +449 -0
  43. package/dist/SubscriberGenerator-1-IsjIwF.mjs.map +1 -0
  44. package/dist/SubscriberGenerator-BlIOdbi-.cjs +490 -0
  45. package/dist/SubscriberGenerator-BlIOdbi-.cjs.map +1 -0
  46. package/dist/add-Blv6Q_YA.mjs +718 -0
  47. package/dist/add-Blv6Q_YA.mjs.map +1 -0
  48. package/dist/add-C6RhiCBX.cjs +720 -0
  49. package/dist/add-C6RhiCBX.cjs.map +1 -0
  50. package/dist/appPorts-C9z9Pzn9.mjs +223 -0
  51. package/dist/appPorts-C9z9Pzn9.mjs.map +1 -0
  52. package/dist/appPorts-Cu79hJF6.cjs +264 -0
  53. package/dist/appPorts-Cu79hJF6.cjs.map +1 -0
  54. package/dist/aws-8QQ8n-t6.mjs +89 -0
  55. package/dist/aws-8QQ8n-t6.mjs.map +1 -0
  56. package/dist/aws-DY9NqQIT.cjs +100 -0
  57. package/dist/aws-DY9NqQIT.cjs.map +1 -0
  58. package/dist/awsStore-Bx5nCFnS.mjs +121 -0
  59. package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
  60. package/dist/awsStore-u3ehhMoY.cjs +138 -0
  61. package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
  62. package/dist/{backup-provisioner-Bgj5Vi_L.mjs → backup-provisioner-C8DnCmxK.mjs} +11 -8
  63. package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
  64. package/dist/{backup-provisioner-BrsHwYG0.cjs → backup-provisioner-oDEsPj02.cjs} +22 -20
  65. package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
  66. package/dist/backups/runner.cjs +519 -0
  67. package/dist/backups/runner.cjs.map +1 -0
  68. package/dist/backups/runner.d.cts +102 -0
  69. package/dist/backups/runner.d.cts.map +1 -0
  70. package/dist/backups/runner.d.mts +102 -0
  71. package/dist/backups/runner.d.mts.map +1 -0
  72. package/dist/backups/runner.mjs +506 -0
  73. package/dist/backups/runner.mjs.map +1 -0
  74. package/dist/{bundler-Be8Zg4Wd.mjs → bundler-Cquc0e8N.mjs} +36 -32
  75. package/dist/bundler-Cquc0e8N.mjs.map +1 -0
  76. package/dist/{bundler-BY1OmV1e.cjs → bundler-DAeBIOlG.cjs} +38 -35
  77. package/dist/bundler-DAeBIOlG.cjs.map +1 -0
  78. package/dist/cli-DbeqYBTs.cjs +71 -0
  79. package/dist/cli-DbeqYBTs.cjs.map +1 -0
  80. package/dist/cli-tWfeiYmO.mjs +71 -0
  81. package/dist/cli-tWfeiYmO.mjs.map +1 -0
  82. package/dist/compose-BftbEv0b.mjs +3154 -0
  83. package/dist/compose-BftbEv0b.mjs.map +1 -0
  84. package/dist/compose-C_mfrSVH.cjs +3267 -0
  85. package/dist/compose-C_mfrSVH.cjs.map +1 -0
  86. package/dist/config-D48erO2j.d.mts +269 -0
  87. package/dist/config-D48erO2j.d.mts.map +1 -0
  88. package/dist/config-DHDtsQrB.d.cts +269 -0
  89. package/dist/config-DHDtsQrB.d.cts.map +1 -0
  90. package/dist/config.cjs +421 -11
  91. package/dist/config.cjs.map +1 -0
  92. package/dist/config.d.cts +4 -120
  93. package/dist/config.d.mts +4 -120
  94. package/dist/config.mjs +405 -4
  95. package/dist/config.mjs.map +1 -0
  96. package/dist/credentialSchemas-DDda4Mmm.cjs +272 -0
  97. package/dist/credentialSchemas-DDda4Mmm.cjs.map +1 -0
  98. package/dist/credentialSchemas-DvitraL-.mjs +237 -0
  99. package/dist/credentialSchemas-DvitraL-.mjs.map +1 -0
  100. package/dist/credentials-B5N5yKk6.mjs +267 -0
  101. package/dist/credentials-B5N5yKk6.mjs.map +1 -0
  102. package/dist/credentials-Zqr3QQYB.cjs +350 -0
  103. package/dist/credentials-Zqr3QQYB.cjs.map +1 -0
  104. package/dist/databases-BeGP5eDh.mjs +495 -0
  105. package/dist/databases-BeGP5eDh.mjs.map +1 -0
  106. package/dist/databases-DGALFDG3.cjs +598 -0
  107. package/dist/databases-DGALFDG3.cjs.map +1 -0
  108. package/dist/define-6poNqm5O.mjs +106 -0
  109. package/dist/define-6poNqm5O.mjs.map +1 -0
  110. package/dist/define-crmMcXFS.cjs +153 -0
  111. package/dist/define-crmMcXFS.cjs.map +1 -0
  112. package/dist/deploy/public.cjs +212 -0
  113. package/dist/deploy/public.cjs.map +1 -0
  114. package/dist/deploy/public.d.cts +653 -0
  115. package/dist/deploy/public.d.cts.map +1 -0
  116. package/dist/deploy/public.d.mts +653 -0
  117. package/dist/deploy/public.d.mts.map +1 -0
  118. package/dist/deploy/public.mjs +145 -0
  119. package/dist/deploy/public.mjs.map +1 -0
  120. package/dist/deploy/sniffer-envkit-patch.cjs +18 -10
  121. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  122. package/dist/deploy/sniffer-envkit-patch.d.cts +0 -2
  123. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  124. package/dist/deploy/sniffer-envkit-patch.d.mts +0 -2
  125. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  126. package/dist/deploy/sniffer-envkit-patch.mjs +10 -2
  127. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  128. package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
  129. package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
  130. package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
  131. package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
  132. package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
  133. package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
  134. package/dist/deploy/sniffer-hooks.cjs +13 -7
  135. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  136. package/dist/deploy/sniffer-hooks.d.cts +1 -2
  137. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  138. package/dist/deploy/sniffer-hooks.d.mts +1 -2
  139. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  140. package/dist/deploy/sniffer-hooks.mjs +10 -3
  141. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  142. package/dist/deploy/sniffer-loader.cjs +16 -7
  143. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  144. package/dist/deploy/sniffer-loader.d.cts +1 -1
  145. package/dist/deploy/sniffer-loader.d.mts +1 -1
  146. package/dist/deploy/sniffer-loader.mjs +14 -3
  147. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  148. package/dist/deploy/sniffer-routes-worker.cjs +11 -11
  149. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  150. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  151. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  152. package/dist/deploy/sniffer-routes-worker.mjs +4 -4
  153. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  154. package/dist/deploy/sniffer-worker.cjs +15 -6
  155. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  156. package/dist/deploy/sniffer-worker.d.cts +1 -3
  157. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  158. package/dist/deploy/sniffer-worker.d.mts +1 -3
  159. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  160. package/dist/deploy/sniffer-worker.mjs +15 -4
  161. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  162. package/dist/deploy-BSilGXuR.mjs +2317 -0
  163. package/dist/deploy-BSilGXuR.mjs.map +1 -0
  164. package/dist/deploy-CktQpmpU.cjs +2390 -0
  165. package/dist/deploy-CktQpmpU.cjs.map +1 -0
  166. package/dist/derive-B4vDpzgP.mjs +150 -0
  167. package/dist/derive-B4vDpzgP.mjs.map +1 -0
  168. package/dist/derive-DAbo49sm.cjs +161 -0
  169. package/dist/derive-DAbo49sm.cjs.map +1 -0
  170. package/dist/discover-BfhVW_kT.cjs +600 -0
  171. package/dist/discover-BfhVW_kT.cjs.map +1 -0
  172. package/dist/discover-CvTtV5ZD.d.cts +108 -0
  173. package/dist/discover-CvTtV5ZD.d.cts.map +1 -0
  174. package/dist/discover-W2kab9Lc.d.mts +108 -0
  175. package/dist/discover-W2kab9Lc.d.mts.map +1 -0
  176. package/dist/discover-kziEht4W.mjs +527 -0
  177. package/dist/discover-kziEht4W.mjs.map +1 -0
  178. package/dist/dns-CQZQL3gj.mjs +926 -0
  179. package/dist/dns-CQZQL3gj.mjs.map +1 -0
  180. package/dist/dns-KPxvcCdL.cjs +1057 -0
  181. package/dist/dns-KPxvcCdL.cjs.map +1 -0
  182. package/dist/dokploy-B7eMa6Pa.cjs +38 -0
  183. package/dist/dokploy-B7eMa6Pa.cjs.map +1 -0
  184. package/dist/dokploy-Dguhz3Uo.mjs +38 -0
  185. package/dist/dokploy-Dguhz3Uo.mjs.map +1 -0
  186. package/dist/drivers-BLU1fNs_.cjs +200 -0
  187. package/dist/drivers-BLU1fNs_.cjs.map +1 -0
  188. package/dist/drivers-C08LL4E8.mjs +177 -0
  189. package/dist/drivers-C08LL4E8.mjs.map +1 -0
  190. package/dist/{emit-CiZS_5Ub.mjs → emit-C1e8qD08.mjs} +13 -26
  191. package/dist/emit-C1e8qD08.mjs.map +1 -0
  192. package/dist/{emit-CbcRolsa.cjs → emit-Dmc1nvdS.cjs} +31 -57
  193. package/dist/emit-Dmc1nvdS.cjs.map +1 -0
  194. package/dist/encryption-CixpDF6e.mjs +89 -0
  195. package/dist/encryption-CixpDF6e.mjs.map +1 -0
  196. package/dist/encryption-DrhCX7G6.cjs +90 -0
  197. package/dist/encryption-DrhCX7G6.cjs.map +1 -0
  198. package/dist/engine-32gL2ju3.mjs +3082 -0
  199. package/dist/engine-32gL2ju3.mjs.map +1 -0
  200. package/dist/engine-CQgycl7o.cjs +3195 -0
  201. package/dist/engine-CQgycl7o.cjs.map +1 -0
  202. package/dist/errors-D8Gwp5kU.mjs +23 -0
  203. package/dist/errors-D8Gwp5kU.mjs.map +1 -0
  204. package/dist/errors-DMC4Umsb.cjs +34 -0
  205. package/dist/errors-DMC4Umsb.cjs.map +1 -0
  206. package/dist/github-DYQ5wvod.mjs +829 -0
  207. package/dist/github-DYQ5wvod.mjs.map +1 -0
  208. package/dist/github-DkSCUoWS.cjs +829 -0
  209. package/dist/github-DkSCUoWS.cjs.map +1 -0
  210. package/dist/identity-CBXr4wNi.mjs +129 -0
  211. package/dist/identity-CBXr4wNi.mjs.map +1 -0
  212. package/dist/identity-CbLfgQNT.cjs +182 -0
  213. package/dist/identity-CbLfgQNT.cjs.map +1 -0
  214. package/dist/{index-BThUzEIp.d.mts → index-8OfpOtSI.d.cts} +39 -24
  215. package/dist/index-8OfpOtSI.d.cts.map +1 -0
  216. package/dist/{index-CHB4tSzX.d.cts → index-Dpji6Bxq.d.mts} +39 -24
  217. package/dist/index-Dpji6Bxq.d.mts.map +1 -0
  218. package/dist/index.cjs +10483 -11859
  219. package/dist/index.cjs.map +1 -1
  220. package/dist/index.d.cts +1 -1
  221. package/dist/index.d.mts +1 -1
  222. package/dist/index.mjs +10527 -11915
  223. package/dist/index.mjs.map +1 -1
  224. package/dist/local-BwC2v2Y8.mjs +224 -0
  225. package/dist/local-BwC2v2Y8.mjs.map +1 -0
  226. package/dist/local-DNhnkugT.cjs +241 -0
  227. package/dist/local-DNhnkugT.cjs.map +1 -0
  228. package/dist/migrate-BoJxKbfR.mjs +181 -0
  229. package/dist/migrate-BoJxKbfR.mjs.map +1 -0
  230. package/dist/migrate-CJTyeBul.cjs +271 -0
  231. package/dist/migrate-CJTyeBul.cjs.map +1 -0
  232. package/dist/migrate-CxmkvMbw.mjs +266 -0
  233. package/dist/migrate-CxmkvMbw.mjs.map +1 -0
  234. package/dist/migrate-ISBZNDKU.cjs +181 -0
  235. package/dist/migrate-ISBZNDKU.cjs.map +1 -0
  236. package/dist/openapi.cjs +214 -8
  237. package/dist/openapi.cjs.map +1 -0
  238. package/dist/openapi.d.cts +72 -15
  239. package/dist/openapi.d.cts.map +1 -1
  240. package/dist/openapi.d.mts +72 -15
  241. package/dist/openapi.d.mts.map +1 -1
  242. package/dist/openapi.mjs +208 -5
  243. package/dist/openapi.mjs.map +1 -0
  244. package/dist/projectBucket-BBbQ1lHF.cjs +263 -0
  245. package/dist/projectBucket-BBbQ1lHF.cjs.map +1 -0
  246. package/dist/projectBucket-C_DN4WzF.mjs +222 -0
  247. package/dist/projectBucket-C_DN4WzF.mjs.map +1 -0
  248. package/dist/provider-BqpjG9QM.cjs +57 -0
  249. package/dist/provider-BqpjG9QM.cjs.map +1 -0
  250. package/dist/provider-CEOKk8NS.mjs +46 -0
  251. package/dist/provider-CEOKk8NS.mjs.map +1 -0
  252. package/dist/ready-BtxiI7Qb.cjs +403 -0
  253. package/dist/ready-BtxiI7Qb.cjs.map +1 -0
  254. package/dist/ready-CzHNHhI6.mjs +374 -0
  255. package/dist/ready-CzHNHhI6.mjs.map +1 -0
  256. package/dist/reconcile/public.cjs +3 -5
  257. package/dist/reconcile/public.d.cts +11 -87
  258. package/dist/reconcile/public.d.cts.map +1 -1
  259. package/dist/reconcile/public.d.mts +11 -87
  260. package/dist/reconcile/public.d.mts.map +1 -1
  261. package/dist/reconcile/public.mjs +3 -4
  262. package/dist/{reconcile-CFs8C_1a.mjs → reconcile--I7V4Klj.mjs} +4 -7
  263. package/dist/reconcile--I7V4Klj.mjs.map +1 -0
  264. package/dist/{reconcile-D0pimNiy.cjs → reconcile-CuCQBa5-.cjs} +5 -8
  265. package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
  266. package/dist/resolve-Bei6BMbw.mjs +263 -0
  267. package/dist/resolve-Bei6BMbw.mjs.map +1 -0
  268. package/dist/resolve-qm7FrBj_.cjs +316 -0
  269. package/dist/resolve-qm7FrBj_.cjs.map +1 -0
  270. package/dist/rollback-BJ3H4kQ8.mjs +136 -0
  271. package/dist/rollback-BJ3H4kQ8.mjs.map +1 -0
  272. package/dist/rollback-Bt4xRXtq.cjs +165 -0
  273. package/dist/rollback-Bt4xRXtq.cjs.map +1 -0
  274. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  275. package/dist/{chunk-CUT6urMc.cjs → rolldown-runtime-C0BPl7ul.cjs} +23 -10
  276. package/dist/run-BJLIerMM.mjs +133 -0
  277. package/dist/run-BJLIerMM.mjs.map +1 -0
  278. package/dist/run-fVZ-rLnc.cjs +174 -0
  279. package/dist/run-fVZ-rLnc.cjs.map +1 -0
  280. package/dist/runtime-ACdfK59n.d.cts +82 -0
  281. package/dist/runtime-ACdfK59n.d.cts.map +1 -0
  282. package/dist/runtime-YyQuekxi.d.mts +82 -0
  283. package/dist/runtime-YyQuekxi.d.mts.map +1 -0
  284. package/dist/s3-CrPoA89T.cjs +215 -0
  285. package/dist/s3-CrPoA89T.cjs.map +1 -0
  286. package/dist/s3-DQXZdmCM.mjs +215 -0
  287. package/dist/s3-DQXZdmCM.mjs.map +1 -0
  288. package/dist/sandbox/config-worker.cjs +43 -0
  289. package/dist/sandbox/config-worker.cjs.map +1 -0
  290. package/dist/sandbox/config-worker.d.cts +1 -0
  291. package/dist/sandbox/config-worker.d.mts +1 -0
  292. package/dist/sandbox/config-worker.mjs +44 -0
  293. package/dist/sandbox/config-worker.mjs.map +1 -0
  294. package/dist/sandbox/credentials-worker.cjs +54 -0
  295. package/dist/sandbox/credentials-worker.cjs.map +1 -0
  296. package/dist/sandbox/credentials-worker.d.cts +1 -0
  297. package/dist/sandbox/credentials-worker.d.mts +1 -0
  298. package/dist/sandbox/credentials-worker.mjs +55 -0
  299. package/dist/sandbox/credentials-worker.mjs.map +1 -0
  300. package/dist/sandbox/discover-worker.cjs +47 -0
  301. package/dist/sandbox/discover-worker.cjs.map +1 -0
  302. package/dist/sandbox/discover-worker.d.cts +1 -0
  303. package/dist/sandbox/discover-worker.d.mts +1 -0
  304. package/dist/sandbox/discover-worker.mjs +48 -0
  305. package/dist/sandbox/discover-worker.mjs.map +1 -0
  306. package/dist/sandbox/migrate-worker.cjs +75 -0
  307. package/dist/sandbox/migrate-worker.cjs.map +1 -0
  308. package/dist/sandbox/migrate-worker.d.cts +1 -0
  309. package/dist/sandbox/migrate-worker.d.mts +1 -0
  310. package/dist/sandbox/migrate-worker.mjs +76 -0
  311. package/dist/sandbox/migrate-worker.mjs.map +1 -0
  312. package/dist/sandbox-C4g1eG31.d.mts +104 -0
  313. package/dist/sandbox-C4g1eG31.d.mts.map +1 -0
  314. package/dist/sandbox-CHv3OYXg.cjs +165 -0
  315. package/dist/sandbox-CHv3OYXg.cjs.map +1 -0
  316. package/dist/sandbox-CbVB7uOD.mjs +118 -0
  317. package/dist/sandbox-CbVB7uOD.mjs.map +1 -0
  318. package/dist/sandbox-CdKgQ3XU.d.cts +104 -0
  319. package/dist/sandbox-CdKgQ3XU.d.cts.map +1 -0
  320. package/dist/schemas-BCwKKA42.mjs +5961 -0
  321. package/dist/schemas-BCwKKA42.mjs.map +1 -0
  322. package/dist/schemas-BQ_v0lEX.cjs +6068 -0
  323. package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
  324. package/dist/secretsManager-CQORubp9.mjs +97 -0
  325. package/dist/secretsManager-CQORubp9.mjs.map +1 -0
  326. package/dist/secretsManager-RAGcEDX1.cjs +108 -0
  327. package/dist/secretsManager-RAGcEDX1.cjs.map +1 -0
  328. package/dist/seeds-CHIPcMrY.cjs +9115 -0
  329. package/dist/seeds-CHIPcMrY.cjs.map +1 -0
  330. package/dist/seeds-E4nUeXTl.mjs +8148 -0
  331. package/dist/seeds-E4nUeXTl.mjs.map +1 -0
  332. package/dist/sniffer-bUiSXLMj.mjs +1825 -0
  333. package/dist/sniffer-bUiSXLMj.mjs.map +1 -0
  334. package/dist/sniffer-n3TkX6JD.cjs +1998 -0
  335. package/dist/sniffer-n3TkX6JD.cjs.map +1 -0
  336. package/dist/sst-B-Uz4cvm.cjs +464 -0
  337. package/dist/sst-B-Uz4cvm.cjs.map +1 -0
  338. package/dist/sst-C1pxbFEd.mjs +441 -0
  339. package/dist/sst-C1pxbFEd.mjs.map +1 -0
  340. package/dist/stages-DJrOYLZ-.mjs +176 -0
  341. package/dist/stages-DJrOYLZ-.mjs.map +1 -0
  342. package/dist/stages-_3RVNG83.cjs +176 -0
  343. package/dist/stages-_3RVNG83.cjs.map +1 -0
  344. package/dist/target/public.cjs +15 -0
  345. package/dist/target/public.d.cts +28 -0
  346. package/dist/target/public.d.cts.map +1 -0
  347. package/dist/target/public.d.mts +28 -0
  348. package/dist/target/public.d.mts.map +1 -0
  349. package/dist/target/public.mjs +4 -0
  350. package/dist/terminal-Bs_lNQhL.mjs +85 -0
  351. package/dist/terminal-Bs_lNQhL.mjs.map +1 -0
  352. package/dist/terminal-CsQz4oT0.cjs +85 -0
  353. package/dist/terminal-CsQz4oT0.cjs.map +1 -0
  354. package/dist/types-B6UXlEkf.d.cts +7650 -0
  355. package/dist/types-B6UXlEkf.d.cts.map +1 -0
  356. package/dist/types-HqVPddRK.d.mts +7649 -0
  357. package/dist/types-HqVPddRK.d.mts.map +1 -0
  358. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  359. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  360. package/dist/utils-D_fxUqvU.mjs +156 -0
  361. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  362. package/dist/vitest.cjs +65 -0
  363. package/dist/vitest.cjs.map +1 -0
  364. package/dist/vitest.d.cts +29 -0
  365. package/dist/vitest.d.cts.map +1 -0
  366. package/dist/vitest.d.mts +29 -0
  367. package/dist/vitest.d.mts.map +1 -0
  368. package/dist/vitest.mjs +65 -0
  369. package/dist/vitest.mjs.map +1 -0
  370. package/dist/workerRuntime-BXfhbe13.cjs +108 -0
  371. package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
  372. package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
  373. package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
  374. package/dist/workspace/index.cjs +8 -4
  375. package/dist/workspace/index.d.cts +3 -3
  376. package/dist/workspace/index.d.mts +3 -3
  377. package/dist/workspace/index.mjs +2 -3
  378. package/dist/workspace-BwqQnool.cjs +2806 -0
  379. package/dist/workspace-BwqQnool.cjs.map +1 -0
  380. package/dist/workspace-D1QbNd55.mjs +2394 -0
  381. package/dist/workspace-D1QbNd55.mjs.map +1 -0
  382. package/package.json +73 -40
  383. package/dist/CachedStateProvider-BLo7zv7S.cjs +0 -3
  384. package/dist/CachedStateProvider-BxoAm-B2.mjs +0 -3
  385. package/dist/CachedStateProvider-CqPdW7CB.cjs +0 -60
  386. package/dist/CachedStateProvider-CqPdW7CB.cjs.map +0 -1
  387. package/dist/CachedStateProvider-DTniehMP.mjs +0 -54
  388. package/dist/CachedStateProvider-DTniehMP.mjs.map +0 -1
  389. package/dist/HostingerProvider-Cft7lEYr.mjs.map +0 -1
  390. package/dist/HostingerProvider-h3EbEp-Z.cjs.map +0 -1
  391. package/dist/LocalStateProvider-Bn6tS-oL.mjs +0 -42
  392. package/dist/LocalStateProvider-Bn6tS-oL.mjs.map +0 -1
  393. package/dist/LocalStateProvider-Db9SEjyH.cjs +0 -43
  394. package/dist/LocalStateProvider-Db9SEjyH.cjs.map +0 -1
  395. package/dist/Route53Provider-RdpUDJQk.mjs.map +0 -1
  396. package/dist/Route53Provider-di2fMM5N.cjs.map +0 -1
  397. package/dist/SSMStateProvider-BRt2py-A.mjs +0 -66
  398. package/dist/SSMStateProvider-BRt2py-A.mjs.map +0 -1
  399. package/dist/SSMStateProvider-DyX8s9HI.cjs +0 -66
  400. package/dist/SSMStateProvider-DyX8s9HI.cjs.map +0 -1
  401. package/dist/backup-provisioner-Bgj5Vi_L.mjs.map +0 -1
  402. package/dist/backup-provisioner-BrsHwYG0.cjs.map +0 -1
  403. package/dist/bundler-BY1OmV1e.cjs.map +0 -1
  404. package/dist/bundler-Be8Zg4Wd.mjs.map +0 -1
  405. package/dist/chunk-Duj1WY3L.mjs +0 -7
  406. package/dist/config-D8o6I_7Z.mjs +0 -469
  407. package/dist/config-D8o6I_7Z.mjs.map +0 -1
  408. package/dist/config-DbPE1KXF.cjs +0 -535
  409. package/dist/config-DbPE1KXF.cjs.map +0 -1
  410. package/dist/config.d.cts.map +0 -1
  411. package/dist/config.d.mts.map +0 -1
  412. package/dist/credentials-B5zRHdAl.mjs +0 -141
  413. package/dist/credentials-B5zRHdAl.mjs.map +0 -1
  414. package/dist/credentials-BapzjyV5.cjs +0 -195
  415. package/dist/credentials-BapzjyV5.cjs.map +0 -1
  416. package/dist/credentials-Dh0Q6HzY.mjs +0 -2548
  417. package/dist/credentials-Dh0Q6HzY.mjs.map +0 -1
  418. package/dist/credentials-K961ThG3.cjs +0 -2680
  419. package/dist/credentials-K961ThG3.cjs.map +0 -1
  420. package/dist/discover-CAlFgYec.mjs +0 -229
  421. package/dist/discover-CAlFgYec.mjs.map +0 -1
  422. package/dist/discover-DTmFeloL.cjs +0 -271
  423. package/dist/discover-DTmFeloL.cjs.map +0 -1
  424. package/dist/dokploy-api-BS2xnJLZ.mjs +0 -3
  425. package/dist/dokploy-api-BsVH0y_s.cjs +0 -718
  426. package/dist/dokploy-api-BsVH0y_s.cjs.map +0 -1
  427. package/dist/dokploy-api-BuxDRo3l.cjs +0 -3
  428. package/dist/dokploy-api-aTFPz7_4.mjs +0 -706
  429. package/dist/dokploy-api-aTFPz7_4.mjs.map +0 -1
  430. package/dist/emit-CbcRolsa.cjs.map +0 -1
  431. package/dist/emit-CiZS_5Ub.mjs.map +0 -1
  432. package/dist/encryption-C6jaU0hE.cjs +0 -54
  433. package/dist/encryption-C6jaU0hE.cjs.map +0 -1
  434. package/dist/encryption-CHzzeR8a.cjs +0 -4
  435. package/dist/encryption-CQUncu7v.mjs +0 -3
  436. package/dist/encryption-D-abyhZx.mjs +0 -42
  437. package/dist/encryption-D-abyhZx.mjs.map +0 -1
  438. package/dist/fullstack-secrets-C-GGohke.cjs +0 -111
  439. package/dist/fullstack-secrets-C-GGohke.cjs.map +0 -1
  440. package/dist/fullstack-secrets-D1o9-G5l.mjs +0 -87
  441. package/dist/fullstack-secrets-D1o9-G5l.mjs.map +0 -1
  442. package/dist/generator-CNzBw7g5.cjs +0 -289
  443. package/dist/generator-CNzBw7g5.cjs.map +0 -1
  444. package/dist/generator-VE2JrFlY.mjs +0 -253
  445. package/dist/generator-VE2JrFlY.mjs.map +0 -1
  446. package/dist/index-BThUzEIp.d.mts.map +0 -1
  447. package/dist/index-CHB4tSzX.d.cts.map +0 -1
  448. package/dist/openapi-CgpMWMmM.mjs +0 -1962
  449. package/dist/openapi-CgpMWMmM.mjs.map +0 -1
  450. package/dist/openapi-CljONd_M.cjs +0 -1998
  451. package/dist/openapi-CljONd_M.cjs.map +0 -1
  452. package/dist/openapi-react-query-Byltvm_7.mjs +0 -167
  453. package/dist/openapi-react-query-Byltvm_7.mjs.map +0 -1
  454. package/dist/openapi-react-query-CmJ1xDbn.cjs +0 -173
  455. package/dist/openapi-react-query-CmJ1xDbn.cjs.map +0 -1
  456. package/dist/openapi-react-query.cjs +0 -4
  457. package/dist/openapi-react-query.d.cts +0 -11
  458. package/dist/openapi-react-query.d.cts.map +0 -1
  459. package/dist/openapi-react-query.d.mts +0 -11
  460. package/dist/openapi-react-query.d.mts.map +0 -1
  461. package/dist/openapi-react-query.mjs +0 -4
  462. package/dist/reconcile-CFs8C_1a.mjs.map +0 -1
  463. package/dist/reconcile-D0pimNiy.cjs.map +0 -1
  464. package/dist/setup-CJiQM2pX.cjs +0 -473
  465. package/dist/setup-CJiQM2pX.cjs.map +0 -1
  466. package/dist/setup-DMtU3p41.cjs +0 -11
  467. package/dist/setup-DOsYueeQ.mjs +0 -443
  468. package/dist/setup-DOsYueeQ.mjs.map +0 -1
  469. package/dist/setup-DSutDAlt.mjs +0 -11
  470. package/dist/storage-BJmzYxt8.cjs +0 -363
  471. package/dist/storage-BJmzYxt8.cjs.map +0 -1
  472. package/dist/storage-BM9hGpgv.cjs +0 -7
  473. package/dist/storage-Bi24WfoW.mjs +0 -297
  474. package/dist/storage-Bi24WfoW.mjs.map +0 -1
  475. package/dist/storage-CYlGwWTj.mjs +0 -3
  476. package/dist/sync-CmEuNZsB.mjs +0 -76
  477. package/dist/sync-CmEuNZsB.mjs.map +0 -1
  478. package/dist/sync-D306yOWu.cjs +0 -4
  479. package/dist/sync-SizaChmC.cjs +0 -93
  480. package/dist/sync-SizaChmC.cjs.map +0 -1
  481. package/dist/sync-hOqAWHR6.mjs +0 -3
  482. package/dist/types-C-arnQ1r.d.mts +0 -2184
  483. package/dist/types-C-arnQ1r.d.mts.map +0 -1
  484. package/dist/types-abJQuk7m.d.cts +0 -2184
  485. package/dist/types-abJQuk7m.d.cts.map +0 -1
  486. package/dist/workspace-7FqprxuJ.mjs +0 -4323
  487. package/dist/workspace-7FqprxuJ.mjs.map +0 -1
  488. package/dist/workspace-8acupeaI.cjs +0 -9
  489. package/dist/workspace-XvqO9jIv.cjs +0 -4472
  490. package/dist/workspace-XvqO9jIv.cjs.map +0 -1
  491. package/dist/workspace-yP5AHnrn.mjs +0 -8
@@ -0,0 +1,3154 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
3
+ import { a as runOutput, i as run } from "./run-BJLIerMM.mjs";
4
+ import { B as LOGS_PORT, I as otlpTelemetryEnv, L as resolveStageTelemetry, at as certificateFor, ft as SERVER_IPV4_KEY, ht as isReservedStageKey, it as ComposeTlsFileMissing, ot as proxyFor, z as telemetryEnv } from "./workspace-D1QbNd55.mjs";
5
+ import { a as serverAddressHint, h as stackBackups, i as requiredServerAddress, l as systemLookup, m as backupsService, o as stackHosts, p as backupsRoleStatements, r as isLocalHost, s as stageDns, t as HostNotPointingAtServer, u as BACKUPS_SERVICE, x as stageBackups } from "./dns-CQZQL3gj.mjs";
6
+ import { t as defineTarget } from "./define-6poNqm5O.mjs";
7
+ import { $ as devServicesUsed, $t as applyBuckets, An as scopeTelemetryEnv, Cn as envFor, En as planFor, Fn as hostFor, Gn as logsAccess, Gt as imageLayout, Hn as primaryPortKey, I as appDockerfile, In as DEFAULT_IMAGES, Jn as withLogsPassword, K as validateImageRef, Kn as logsService, Kt as TURBO_VERSION, M as stageProviderNotes, Mn as telemetryOf, Nn as usesTelemetry, Pn as EMULATOR_ACCESS_KEY_ID, Qt as workerUnits, R as ensureDockerignore, Sn as withRedisPassword, St as composeFor, Wn as LOGS_SERVICE, Wt as composeBuildPaths, Xn as isMainFrontendApp, Yn as NoDomainForStage, Yt as findBuildRoot, Zn as resolveHost, _ as createComposeState, _n as REDIS_SERVICE, _t as LEGACY_LOCAL_LOGIN, at as appEnvKeys, bn as runsRedis, bt as pgClient, ct as workerEnvKeys, dt as constructGlobs, en as applyPolicies, et as externalServices, gn as withGeneratedSecrets, in as postgresStatements, it as suppliedOnly, kn as isTelemetryKey, ln as postgresSuperuser, n as reportDatabaseRuns, nn as bucketPolicies, o as recordDnsChanges, on as LOCAL_RABBITMQ_USER, qn as stackLogs, qt as WORKER_PORT, r as reportPlannedSeeds, rt as stageServiceDeclarations, s as currentActor, sn as loadLocalCredentials, st as networkEnv, t as DeploySeedsFailed, tn as applyPostgres, u as DeployJournal, vn as STACK_CACHE, vt as ensurePostgresLogin, wn as localRolePassword, x as recordRelease, xn as stackRedis, yn as redisService, yt as bucketClient, z as workerDockerfile, zn as portKeys, zt as initStageSecrets } from "./seeds-E4nUeXTl.mjs";
8
+ import { t as appKey } from "./derive-B4vDpzgP.mjs";
9
+ import { i as DEFAULT_EVENTS } from "./SubscriberGenerator-1-IsjIwF.mjs";
10
+ import { a as imageRef } from "./identity-CBXr4wNi.mjs";
11
+ import { r as discover } from "./discover-kziEht4W.mjs";
12
+ import { i as installedFrom } from "./drivers-C08LL4E8.mjs";
13
+ import { f as plannedSeeds, o as SeedFailed, p as seedDatabases, u as migrateDatabases } from "./databases-BeGP5eDh.mjs";
14
+ import { dirname, join } from "node:path";
15
+ import { existsSync } from "node:fs";
16
+ import { chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
17
+ import { hostname, userInfo } from "node:os";
18
+ import { spawn } from "node:child_process";
19
+ import { createConnection, createServer } from "node:net";
20
+ import { createHash } from "node:crypto";
21
+ import { CLIENT_IP_HEADER, provideKey, provisionOrder, publicEnvFor } from "@geekmidas/manifest";
22
+ import { stringify } from "yaml";
23
+ import { request } from "node:https";
24
+ //#region src/compose/docker.ts
25
+ /**
26
+ * The Docker operations `gkm compose` needs, behind an interface.
27
+ *
28
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
29
+ * registry is asked before anything is pulled, nothing is started for a tag
30
+ * that is missing — are asserted against a fake, and this file is only the
31
+ * wiring to the real CLI.
32
+ *
33
+ * Every call is an argument array. Image refs, tags and paths come from the
34
+ * workspace, and none of them reaches a shell.
35
+ */
36
+ /** `output` as `spawn` reads it. */
37
+ const STDIO = {
38
+ inherit: "inherit",
39
+ stderr: [
40
+ "ignore",
41
+ 2,
42
+ 2
43
+ ],
44
+ ignore: "ignore"
45
+ };
46
+ /**
47
+ * The environment a docker command for `engine` runs with: this process's,
48
+ * with `DOCKER_HOST` pointing at the stack's engine when it is a server's.
49
+ */
50
+ function engineEnv(engine, extra = {}) {
51
+ if (!engine.host && Object.keys(extra).length === 0) return void 0;
52
+ return {
53
+ ...process.env,
54
+ ...extra,
55
+ ...engine.host ? { DOCKER_HOST: engine.host } : {}
56
+ };
57
+ }
58
+ /** How a stack's docker commands run: where it is, where output goes. */
59
+ function runOptions(stack, extra) {
60
+ const env = engineEnv(stack, extra);
61
+ return {
62
+ cwd: stack.cwd,
63
+ stdio: STDIO[stack.output ?? "inherit"],
64
+ ...env ? { env } : {},
65
+ ...stack.signal ? { signal: stack.signal } : {}
66
+ };
67
+ }
68
+ /** The network compose puts a project's services on. */
69
+ function projectNetwork(project) {
70
+ return `${project}_default`;
71
+ }
72
+ /**
73
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
74
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
75
+ */
76
+ function publishedPorts(column) {
77
+ const ports = /* @__PURE__ */ new Set();
78
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
79
+ const first = Number(match[1]);
80
+ const last = match[2] ? Number(match[2]) : first;
81
+ for (let port = first; port <= last; port++) ports.add(port);
82
+ }
83
+ return [...ports];
84
+ }
85
+ /** Each line `docker ps` printed, as the containers holding `port`. */
86
+ function portHolders(output, port) {
87
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
88
+ container,
89
+ ...project ? { project } : {},
90
+ ...service ? { service } : {}
91
+ }));
92
+ }
93
+ /** How long a stack has to pass its health checks. */
94
+ const WAIT_TIMEOUT_S = 180;
95
+ /** `docker compose port` printed nothing a port can be read from. */
96
+ var ServicePortUnknown = class extends GkmError {
97
+ service;
98
+ inside;
99
+ output;
100
+ constructor(service, inside, output) {
101
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
102
+ this.service = service;
103
+ this.inside = inside;
104
+ this.output = output;
105
+ this.name = "ServicePortUnknown";
106
+ }
107
+ };
108
+ /**
109
+ * Whether `ref` names a registry on this machine's loopback — which the
110
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
111
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
112
+ * registry's image is reported as no such manifest).
113
+ */
114
+ function isLoopbackRegistry(ref) {
115
+ const first = ref.split("/")[0];
116
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
117
+ const host = first.replace(/:\d+$/, "");
118
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
119
+ }
120
+ /** `docker push` finished without saying what digest the registry stored. */
121
+ var PushDigestUnknown = class extends GkmError {
122
+ ref;
123
+ output;
124
+ constructor(ref, output) {
125
+ 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}\`.`);
126
+ this.ref = ref;
127
+ this.output = output;
128
+ this.name = "PushDigestUnknown";
129
+ }
130
+ };
131
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
132
+ function pushedDigest(output) {
133
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
134
+ }
135
+ function compose(stack, args) {
136
+ return [
137
+ "compose",
138
+ "-p",
139
+ stack.project,
140
+ "-f",
141
+ stack.file,
142
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
143
+ ...args
144
+ ];
145
+ }
146
+ /** Run a program and keep everything it said, whatever it exits with. */
147
+ function capture(command, args, options = {}) {
148
+ const { timeoutMs = 6e4 } = options;
149
+ return new Promise((resolve, reject) => {
150
+ const child = spawn(command, [...args], {
151
+ stdio: [
152
+ options.input === void 0 ? "ignore" : "pipe",
153
+ "pipe",
154
+ "pipe"
155
+ ],
156
+ shell: false,
157
+ ...options.env ? { env: options.env } : {}
158
+ });
159
+ if (options.input !== void 0) child.stdin?.end(options.input);
160
+ let stdout = "";
161
+ let stderr = "";
162
+ child.stdout?.on("data", (chunk) => {
163
+ stdout += chunk.toString();
164
+ });
165
+ child.stderr?.on("data", (chunk) => {
166
+ stderr += chunk.toString();
167
+ });
168
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
169
+ timer.unref?.();
170
+ child.on("error", (error) => {
171
+ clearTimeout(timer);
172
+ reject(error);
173
+ });
174
+ child.on("close", (code) => {
175
+ clearTimeout(timer);
176
+ resolve({
177
+ code,
178
+ stdout,
179
+ stderr
180
+ });
181
+ });
182
+ });
183
+ }
184
+ /**
185
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
186
+ * opposed to the registry not answering.
187
+ *
188
+ * Read off the message because that is all the CLI gives. Anything not
189
+ * recognisably "no such tag" is treated as the registry being unreachable:
190
+ * a registry that refused credentials must not be reported as a tag that was
191
+ * never pushed, or the fix offered would be the wrong one.
192
+ */
193
+ function isMissingManifest(output) {
194
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
195
+ }
196
+ const dockerCompose = {
197
+ async lookup(ref) {
198
+ const { code, stdout, stderr } = await capture("docker", [
199
+ "manifest",
200
+ "inspect",
201
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
202
+ ref
203
+ ]);
204
+ if (code === 0) return {
205
+ ref,
206
+ status: "found"
207
+ };
208
+ const output = `${stderr}\n${stdout}`.trim();
209
+ return isMissingManifest(output) ? {
210
+ ref,
211
+ status: "missing"
212
+ } : {
213
+ ref,
214
+ status: "unreachable",
215
+ detail: output
216
+ };
217
+ },
218
+ async build(stack, services) {
219
+ await run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
220
+ ...process.env,
221
+ DOCKER_BUILDKIT: "1"
222
+ }));
223
+ },
224
+ async pull(stack, services) {
225
+ await run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
226
+ },
227
+ async up(stack, services) {
228
+ await run("docker", compose(stack, [
229
+ "up",
230
+ "-d",
231
+ "--wait",
232
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
233
+ ...services ? [] : ["--remove-orphans"],
234
+ ...services ?? []
235
+ ]), runOptions(stack));
236
+ },
237
+ async down(stack) {
238
+ await run("docker", compose(stack, ["down"]), runOptions(stack));
239
+ },
240
+ async port(stack, service, inside) {
241
+ const env = engineEnv(stack);
242
+ const output = await runOutput("docker", compose(stack, [
243
+ "port",
244
+ service,
245
+ String(inside)
246
+ ]), {
247
+ cwd: stack.cwd,
248
+ ...env ? { env } : {},
249
+ ...stack.signal ? { signal: stack.signal } : {}
250
+ });
251
+ const port = Number(output.trim().split(":").pop());
252
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
253
+ return port;
254
+ },
255
+ async health(stack, service) {
256
+ const env = engineEnv(stack);
257
+ const { code, stdout } = await capture("docker", compose(stack, [
258
+ "ps",
259
+ "--format",
260
+ "{{.Health}}",
261
+ service
262
+ ]), env ? { env } : {});
263
+ if (code !== 0) return void 0;
264
+ return stdout.trim().split("\n")[0] || void 0;
265
+ },
266
+ async copyOut(stack, service, from, to) {
267
+ await mkdir(dirname(to), { recursive: true });
268
+ await run("docker", compose(stack, [
269
+ "cp",
270
+ `${service}:${from}`,
271
+ to
272
+ ]), runOptions(stack));
273
+ },
274
+ async push(stack, ref) {
275
+ const output = await runOutput("docker", ["push", ref], {
276
+ cwd: stack.cwd,
277
+ ...stack.signal ? { signal: stack.signal } : {}
278
+ });
279
+ const digest = pushedDigest(output);
280
+ if (!digest) throw new PushDigestUnknown(ref, output);
281
+ return digest;
282
+ },
283
+ async digest(engine, ref) {
284
+ const env = engineEnv(engine);
285
+ const { code, stdout } = await capture("docker", [
286
+ "image",
287
+ "inspect",
288
+ "--format={{json .RepoDigests}} {{.Id}}",
289
+ ref
290
+ ], env ? { env } : {});
291
+ if (code !== 0) return void 0;
292
+ const [json = "[]", id] = stdout.trim().split(" ");
293
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
294
+ try {
295
+ const digests = JSON.parse(json);
296
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
297
+ if (match) return match.slice(repository.length + 1);
298
+ } catch {}
299
+ return id || void 0;
300
+ },
301
+ async ensureNetwork(engine, name) {
302
+ const env = engineEnv(engine);
303
+ const options = env ? { env } : {};
304
+ const { code } = await capture("docker", [
305
+ "network",
306
+ "inspect",
307
+ name
308
+ ], options);
309
+ if (code === 0) return;
310
+ const created = await capture("docker", [
311
+ "network",
312
+ "create",
313
+ name
314
+ ], options);
315
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
316
+ },
317
+ async publishers(engine, port) {
318
+ const env = engineEnv(engine);
319
+ const { stdout } = await capture("docker", [
320
+ "ps",
321
+ "--format",
322
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
323
+ ], env ? { env } : {});
324
+ return portHolders(stdout, port);
325
+ },
326
+ async exec(stack, service, command, input) {
327
+ const env = engineEnv(stack);
328
+ const options = env ? { env } : {};
329
+ const { stdout: ids } = await capture("docker", [
330
+ "ps",
331
+ "-q",
332
+ "--filter",
333
+ `label=com.docker.compose.project=${stack.project}`,
334
+ "--filter",
335
+ `label=com.docker.compose.service=${service}`
336
+ ], options);
337
+ const container = ids.trim().split("\n")[0];
338
+ if (!container) return {
339
+ code: null,
340
+ stdout: "",
341
+ stderr: `${service} is not running`
342
+ };
343
+ return capture("docker", [
344
+ "exec",
345
+ ...input === void 0 ? [] : ["-i"],
346
+ container,
347
+ ...command
348
+ ], {
349
+ ...options,
350
+ ...input === void 0 ? {} : { input }
351
+ });
352
+ },
353
+ async container(engine, project, service) {
354
+ const env = engineEnv(engine);
355
+ const { stdout } = await capture("docker", [
356
+ "ps",
357
+ "--filter",
358
+ `label=com.docker.compose.project=${project}`,
359
+ "--filter",
360
+ `label=com.docker.compose.service=${service}`,
361
+ "--format",
362
+ "{{.ID}} {{.Image}}"
363
+ ], env ? { env } : {});
364
+ const [id, image] = stdout.trim().split("\n")[0]?.split(" ") ?? [];
365
+ return id && image ? {
366
+ id,
367
+ image
368
+ } : void 0;
369
+ },
370
+ runOnce(engine, options) {
371
+ return dockerExit([
372
+ "run",
373
+ "--rm",
374
+ ...options.stdin ? ["-i"] : [],
375
+ "--network",
376
+ options.network,
377
+ ...Object.keys(options.env ?? {}).flatMap((name) => ["-e", name]),
378
+ "--entrypoint",
379
+ "",
380
+ options.image,
381
+ ...options.command
382
+ ], {
383
+ env: engineEnv(engine, { ...options.env }) ?? process.env,
384
+ ...options.stdin ? { stdin: options.stdin } : {},
385
+ ...options.output ? { output: options.output } : {}
386
+ });
387
+ }
388
+ };
389
+ /** Spawn `docker`, its output where `output` says; resolve with the exit code. */
390
+ function dockerExit(args, options = {}) {
391
+ const output = STDIO[options.output ?? "inherit"];
392
+ const out = Array.isArray(output) ? output : [
393
+ output,
394
+ output,
395
+ output
396
+ ];
397
+ return new Promise((resolve, reject) => {
398
+ const child = spawn("docker", [...args], {
399
+ stdio: [
400
+ options.stdin ? "pipe" : "ignore",
401
+ out[1],
402
+ out[2]
403
+ ],
404
+ env: options.env ?? process.env,
405
+ shell: false
406
+ });
407
+ if (options.stdin && child.stdin) {
408
+ options.stdin.on("error", (error) => child.stdin?.destroy(error));
409
+ child.stdin.on("error", () => {});
410
+ options.stdin.pipe(child.stdin);
411
+ }
412
+ child.on("error", reject);
413
+ child.on("close", (code) => resolve(code ?? 1));
414
+ });
415
+ }
416
+ /** `docker network create` failed. */
417
+ var NetworkCreateFailed = class extends GkmError {
418
+ network;
419
+ output;
420
+ constructor(network, output) {
421
+ 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.`);
422
+ this.network = network;
423
+ this.output = output;
424
+ this.name = "NetworkCreateFailed";
425
+ }
426
+ };
427
+ //#endregion
428
+ //#region src/compose/server.ts
429
+ /**
430
+ * Where a deployed compose stage runs: its server, reached over SSH.
431
+ *
432
+ * gkm never runs on the server. It runs where the deploy is started — a CI
433
+ * runner, a developer's machine — and drives the server's Docker engine over
434
+ * SSH (`DOCKER_HOST=ssh://user@host`), so the server holds Docker, an SSH
435
+ * login and nothing else: no gkm, no checkout, no cloud credentials.
436
+ *
437
+ * ```ts
438
+ * deploy: { compose: { server: { production: { user: 'deploy' } } } }
439
+ * ```
440
+ *
441
+ * The host is the stage's `GKM_SERVER_IPV4` secret — the address its DNS
442
+ * records already point at — unless `host` names another. The local stage is
443
+ * never given one: it runs on this machine's Docker.
444
+ *
445
+ * What the deploy needs from inside the server — Postgres and MinIO, published
446
+ * on the server's loopback alone — it reaches through an SSH tunnel on the same
447
+ * login, so neither is ever published publicly.
448
+ */
449
+ /** A deployed compose stage with nowhere to run. */
450
+ var ComposeServerMissing = class extends GkmError {
451
+ stage;
452
+ missing;
453
+ constructor(stage, missing) {
454
+ 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.`);
455
+ this.stage = stage;
456
+ this.missing = missing;
457
+ this.name = "ComposeServerMissing";
458
+ }
459
+ };
460
+ /** SSH to the stage's server failed before anything was changed there. */
461
+ var ComposeServerUnreachable = class extends GkmError {
462
+ target;
463
+ stderr;
464
+ constructor(target, stderr) {
465
+ 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.`);
466
+ this.target = target;
467
+ this.stderr = stderr;
468
+ this.name = "ComposeServerUnreachable";
469
+ }
470
+ };
471
+ /** An SSH tunnel to a port on the server's loopback did not open. */
472
+ var ComposeTunnelFailed = class extends GkmError {
473
+ target;
474
+ remotePort;
475
+ stderr;
476
+ constructor(target, remotePort, stderr) {
477
+ 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 (AllowTcpForwarding yes, the default) for the deploy user.`);
478
+ this.target = target;
479
+ this.remotePort = remotePort;
480
+ this.stderr = stderr;
481
+ this.name = "ComposeTunnelFailed";
482
+ }
483
+ };
484
+ /**
485
+ * The stage's server: its login from `deploy.compose.server.<stage>`, its
486
+ * host from there or the stage's `GKM_SERVER_IPV4`. Undefined for the local
487
+ * stage, which runs on this machine.
488
+ *
489
+ * @throws {ComposeServerMissing} for a deployed stage with no login or host
490
+ */
491
+ function composeServer(options) {
492
+ const { stage } = options;
493
+ if (options.local) return void 0;
494
+ const config = options.config?.[stage];
495
+ if (!config) throw new ComposeServerMissing(stage, "config");
496
+ const host = config.host ?? options.custom?.["GKM_SERVER_IPV4"]?.trim();
497
+ if (!host) throw new ComposeServerMissing(stage, "host");
498
+ return {
499
+ user: config.user,
500
+ host,
501
+ port: config.port ?? 22
502
+ };
503
+ }
504
+ /** `user@host`, as a person types it after `ssh`. */
505
+ function sshTarget(server) {
506
+ return `${server.user}@${server.host}`;
507
+ }
508
+ /** The server's Docker engine, as `DOCKER_HOST` names it. */
509
+ function dockerHost(server) {
510
+ const host = server.host.includes(":") ? `[${server.host}]` : server.host;
511
+ return `ssh://${server.user}@${host}${server.port === 22 ? "" : `:${server.port}`}`;
512
+ }
513
+ /** The arguments every `ssh` gkm runs starts with: no prompt, ever. */
514
+ function sshArgs(server) {
515
+ return [
516
+ "-o",
517
+ "BatchMode=yes",
518
+ "-o",
519
+ "ConnectTimeout=20",
520
+ "-p",
521
+ String(server.port),
522
+ sshTarget(server)
523
+ ];
524
+ }
525
+ async function freeLocalPort() {
526
+ const server = createServer();
527
+ await new Promise((resolve, reject) => {
528
+ server.once("error", reject);
529
+ server.listen(0, "127.0.0.1", resolve);
530
+ });
531
+ const address = server.address();
532
+ await new Promise((resolve) => server.close(resolve));
533
+ if (!address || typeof address === "string") return 0;
534
+ return address.port;
535
+ }
536
+ function connects(port) {
537
+ return new Promise((resolve) => {
538
+ const socket = createConnection({
539
+ host: "127.0.0.1",
540
+ port
541
+ });
542
+ socket.once("connect", () => {
543
+ socket.destroy();
544
+ resolve(true);
545
+ });
546
+ socket.once("error", () => resolve(false));
547
+ });
548
+ }
549
+ /** The real one: the system's `ssh`, with the user's keys and known hosts. */
550
+ const sshAccess = {
551
+ check(server) {
552
+ return new Promise((resolve, reject) => {
553
+ const child = spawn("ssh", [
554
+ ...sshArgs(server),
555
+ "docker",
556
+ "version",
557
+ "--format",
558
+ "{{.Server.Version}}"
559
+ ], { stdio: [
560
+ "ignore",
561
+ "ignore",
562
+ "pipe"
563
+ ] });
564
+ let stderr = "";
565
+ child.stderr.on("data", (chunk) => {
566
+ stderr += chunk.toString();
567
+ });
568
+ child.on("error", (error) => reject(new ComposeServerUnreachable(sshTarget(server), error.message)));
569
+ child.on("close", (code) => code === 0 ? resolve() : reject(new ComposeServerUnreachable(sshTarget(server), stderr)));
570
+ });
571
+ },
572
+ async tunnel(server, remotePort) {
573
+ const port = await freeLocalPort();
574
+ const child = spawn("ssh", [
575
+ "-N",
576
+ "-o",
577
+ "ExitOnForwardFailure=yes",
578
+ "-o",
579
+ "ControlPath=none",
580
+ "-L",
581
+ `127.0.0.1:${port}:127.0.0.1:${remotePort}`,
582
+ ...sshArgs(server)
583
+ ], { stdio: [
584
+ "ignore",
585
+ "ignore",
586
+ "pipe"
587
+ ] });
588
+ let stderr = "";
589
+ let exited = false;
590
+ child.stderr.on("data", (chunk) => {
591
+ stderr += chunk.toString();
592
+ });
593
+ child.on("exit", () => {
594
+ exited = true;
595
+ });
596
+ child.on("error", (error) => {
597
+ exited = true;
598
+ stderr += error.message;
599
+ });
600
+ const close = async () => {
601
+ if (exited) return;
602
+ const gone = new Promise((resolve) => child.once("exit", resolve));
603
+ child.kill("SIGTERM");
604
+ await gone;
605
+ };
606
+ for (let attempt = 0; attempt < 150; attempt++) {
607
+ if (exited) break;
608
+ if (await connects(port)) return {
609
+ port,
610
+ close
611
+ };
612
+ await new Promise((resolve) => setTimeout(resolve, 200));
613
+ }
614
+ await close();
615
+ throw new ComposeTunnelFailed(sshTarget(server), remotePort, stderr);
616
+ }
617
+ };
618
+ //#endregion
619
+ //#region src/compose/caddyfile.ts
620
+ /**
621
+ * The stack's own edge, rendered for Caddy: one site block per route.
622
+ *
623
+ * Deployed, each host is the stage's real domain and Caddy gets it a
624
+ * certificate from Let's Encrypt on first request — the same automatic HTTPS
625
+ * it does anywhere, with nothing to configure but the name — or serves the
626
+ * stage's own certificate (`deploy.compose.tls`). Locally the hosts are
627
+ * `*.localhost` and the certificates come from Caddy's own CA, as the `gkm
628
+ * dev` edge does, so a local stack is `https://` like a deployed one.
629
+ *
630
+ * Pure: the routes are data (`routes.ts`), and rendering them is one string.
631
+ */
632
+ /** Where Caddy reads a stage's own certificate, inside its container. */
633
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
634
+ /** An upstream on the stack's own network: its service name. */
635
+ function address({ service, port }) {
636
+ return `${service}:${port}`;
637
+ }
638
+ /** The Caddyfile for a stack's edge. */
639
+ function edgeCaddyfile(routes, options) {
640
+ const { tls } = options;
641
+ const global = tls.kind === "internal" ? `{
642
+ # No ACME and no public DNS: the CA is Caddy's own and the names resolve
643
+ # to this machine.
644
+ local_certs
645
+ auto_https disable_redirects
646
+ }` : options.email ? `{
647
+ email ${options.email}
648
+ }` : "";
649
+ const certificate = tls.kind === "internal" ? `
650
+ tls internal
651
+ ` : tls.kind === "files" ? `
652
+ tls ${tls.certFile} ${tls.keyFile}
653
+ ` : "";
654
+ const blocks = routes.map(({ host, upstreams, prefix, allow, streaming }) => `https://${host} {${certificate}
655
+ # gkm's own header, which only a service of this stack may send: the auth
656
+ # server rate-limits by the client address it carries.
657
+ request_header -${CLIENT_IP_HEADER}
658
+ ${allow ? `
659
+ # Only these addresses — the peer Caddy sees, never a header a client
660
+ # could set. Everything else is refused before it reaches the upstream.
661
+ @denied not remote_ip ${allow.join(" ")}
662
+ respond @denied 403
663
+ ` : ""}${prefix ? `
664
+ # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
665
+ # which routes and signs on the Host header — so it is sent the upstream's.
666
+ reverse_proxy ${upstreams.map(address).join(" ")} {
667
+ rewrite ${prefix}{uri}
668
+ header_up Host {upstream_hostport}
669
+ }` : `
670
+ # Host and X-Forwarded-* are passed through as Caddy does by default, so
671
+ # an app builds redirects, cookies and links on the address a caller used.
672
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming ? ` {
673
+ # Never buffer: a streamed response — server-sent events, a Next.js
674
+ # RSC payload — reaches the client as each chunk is written.
675
+ flush_interval -1
676
+ }` : ""}`}
677
+ }`);
678
+ return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
679
+ }
680
+ const HEADER = `# Generated by gkm compose from the construct manifest — do not edit.
681
+ #
682
+ # One host per API and site, each in front of its own container, one per
683
+ # file server in front of the stack's MinIO, and — when its logs are served
684
+ # publicly — one for OpenObserve, to the addresses it allows.
685
+ `;
686
+ //#endregion
687
+ //#region src/compose/images.ts
688
+ /**
689
+ * Which image each app runs — and, for a tag, whether every one exists.
690
+ *
691
+ * A tag is a release's identity: `--tag=v1.4.0` means the images CI pushed as
692
+ * v1.4.0, and nothing else. So a stack is never half rolled out: every app's
693
+ * image is asked of the registry before anything is pulled or the running
694
+ * stack is touched, and one missing image stops the whole run naming every
695
+ * one that is missing. Nor is a missing image quietly built instead — a build
696
+ * of whatever is checked out here is not the release the tag names.
697
+ */
698
+ /**
699
+ * The tag a site's image carries for a release.
700
+ *
701
+ * A site's public URLs are inlined when it is built, so one bundle serves one
702
+ * stage: `v1.4.0-production` and `v1.4.0-staging` are two images of the same
703
+ * commit. A backend reads its URLs at runtime, so one image serves every stage
704
+ * and its tag is the release's alone.
705
+ */
706
+ function siteTag(tag, stage) {
707
+ return `${tag}-${stage}`;
708
+ }
709
+ /** Images a tag names that the registry does not have. */
710
+ var ImageTagNotFound = class extends GkmError {
711
+ tag;
712
+ refs;
713
+ constructor(tag, refs) {
714
+ super(`The registry has no image for ${refs.length === 1 ? "this app" : `${refs.length} apps`} at '${tag}':\n` + refs.map((ref) => ` - ${ref}`).join("\n") + `\nNothing was pulled or started. Push '${tag}' for every app from CI, pick a tag that exists, or run without --tag to build from this checkout.`);
715
+ this.tag = tag;
716
+ this.refs = refs;
717
+ this.name = "ImageTagNotFound";
718
+ }
719
+ };
720
+ /** The registry did not answer, or did not let this machine in. */
721
+ var RegistryUnreachable = class extends GkmError {
722
+ ref;
723
+ detail;
724
+ constructor(ref, detail) {
725
+ super(`Could not ask the registry about ${ref}: ${detail || "no answer"}\nNothing was pulled or started. Check the registry is reachable and that this machine is logged in to it (\`docker login <registry>\`).`);
726
+ this.ref = ref;
727
+ this.detail = detail;
728
+ this.name = "RegistryUnreachable";
729
+ }
730
+ };
731
+ /**
732
+ * Assert every image exists, before anything else happens.
733
+ *
734
+ * Asked all at once and reported all at once: a release missing two images is
735
+ * one problem with two names, and finding the second only after fixing the
736
+ * first is a slower way to learn the same thing.
737
+ *
738
+ * @throws {RegistryUnreachable} when the registry cannot say
739
+ * @throws {ImageTagNotFound} listing every missing image
740
+ */
741
+ async function assertImagesExist(docker, tag, images) {
742
+ const lookups = await Promise.all(images.map((image) => docker.lookup(image.ref)));
743
+ const unreachable = lookups.find((lookup) => lookup.status === "unreachable");
744
+ if (unreachable?.status === "unreachable") throw new RegistryUnreachable(unreachable.ref, unreachable.detail);
745
+ const missing = lookups.filter((lookup) => lookup.status === "missing").map((lookup) => lookup.ref);
746
+ if (missing.length > 0) throw new ImageTagNotFound(tag, missing);
747
+ }
748
+ /**
749
+ * A push or a pull with no `deploy.registry` to push to or pull from.
750
+ *
751
+ * Without one an image is named `<namespace>/<project>-<app>:<tag>`, which
752
+ * Docker resolves to Docker Hub — so a release would be pushed to, or pulled
753
+ * from, somebody else's account. It is never a fallback.
754
+ */
755
+ var RegistryRequired = class extends GkmError {
756
+ operation;
757
+ ref;
758
+ constructor(operation, ref) {
759
+ super(`${operation === "push" ? "Pushing" : "Pulling"} images needs a registry, and gkm.config.ts sets no deploy.registry: '${ref}' would be ${operation === "push" ? "pushed to" : "pulled from"} Docker Hub. Set deploy.registry (e.g. registry: 'ghcr.io/acme') in gkm.config.ts.` + (operation === "pull" ? " To run images built here instead, pass --build." : ""));
760
+ this.operation = operation;
761
+ this.ref = ref;
762
+ this.name = "RegistryRequired";
763
+ }
764
+ };
765
+ /** An image pinned to its digest: `<ref>@sha256:…`. */
766
+ function pinnedRef(ref, digest) {
767
+ return `${ref.split("@")[0]}@${digest}`;
768
+ }
769
+ /** A digests file with no entry for an app the stack runs. */
770
+ var ImageDigestMissing = class extends GkmError {
771
+ file;
772
+ apps;
773
+ constructor(file, apps) {
774
+ super(`${file} pins no digest for ${apps.join(", ")}. Use the file the same release's \`gkm compose --build --push --digests-file\` wrote, or run without --digests-file to pull by tag.`);
775
+ this.file = file;
776
+ this.apps = apps;
777
+ this.name = "ImageDigestMissing";
778
+ }
779
+ };
780
+ /** A digests file entry that is not this app's image. */
781
+ var ImageDigestMismatch = class extends GkmError {
782
+ app;
783
+ expected;
784
+ found;
785
+ constructor(app, expected, found) {
786
+ super(`The digests file pins '${app}' to ${found}, but this release runs ${expected}. It was written for another registry, project, stage or tag; use the file this stage's push of this tag wrote.`);
787
+ this.app = app;
788
+ this.expected = expected;
789
+ this.found = found;
790
+ this.name = "ImageDigestMismatch";
791
+ }
792
+ };
793
+ /** A digests file that is not a JSON object of app to pinned ref. */
794
+ var ImageDigestsInvalid = class extends GkmError {
795
+ file;
796
+ detail;
797
+ constructor(file, detail) {
798
+ super(`${file} is not a digests file (${detail}). It should be the JSON object \`gkm compose --build --push --digests-file\` writes: { "api": "<registry>/<image>:<tag>@sha256:…" }.`);
799
+ this.file = file;
800
+ this.detail = detail;
801
+ this.name = "ImageDigestsInvalid";
802
+ }
803
+ };
804
+ /** Parse a digests file's content, checking its shape. */
805
+ function parseDigests(file, content) {
806
+ let parsed;
807
+ try {
808
+ parsed = JSON.parse(content);
809
+ } catch (error) {
810
+ throw new ImageDigestsInvalid(file, error instanceof Error ? error.message : String(error));
811
+ }
812
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new ImageDigestsInvalid(file, "not a JSON object");
813
+ for (const [app, value] of Object.entries(parsed)) if (typeof value !== "string" || !/@sha256:[0-9a-f]{64}$/.test(value)) throw new ImageDigestsInvalid(file, `'${app}' is not an <image>:<tag>@sha256:… ref`);
814
+ return parsed;
815
+ }
816
+ /**
817
+ * Each image pinned to the digest the file names for it.
818
+ *
819
+ * @throws {ImageDigestMissing} naming every app the file has no entry for
820
+ * @throws {ImageDigestMismatch} when an entry is another image or tag
821
+ */
822
+ function pinImages(file, digests, images) {
823
+ const missing = images.filter((image) => !digests[image.app]).map((image) => image.app);
824
+ if (missing.length > 0) throw new ImageDigestMissing(file, missing);
825
+ return images.map((image) => {
826
+ const pinned = digests[image.app];
827
+ if (pinned.split("@")[0] !== image.ref) throw new ImageDigestMismatch(image.app, image.ref, pinned);
828
+ return {
829
+ ...image,
830
+ ref: pinned
831
+ };
832
+ });
833
+ }
834
+ //#endregion
835
+ //#region src/compose/traefik.ts
836
+ /**
837
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
838
+ * with, and what one stack registers with it.
839
+ *
840
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
841
+ * HTTPS. It is configured through its file provider alone: each stack writes
842
+ * one file — its routers, services and middlewares, every name prefixed with
843
+ * its compose project — into a directory the edge watches, and removes it
844
+ * when it stops. There is no Docker socket: the edge never learns what runs
845
+ * on the server except from those files.
846
+ *
847
+ * The edge and the stacks meet on one external Docker network. Only a
848
+ * stack's public services join it, each under an alias prefixed with its
849
+ * project (`<project>-api`), because the network is shared: a bare service
850
+ * name there would be answered by every stack's `api`.
851
+ *
852
+ * Pure: the documents are data, and the edge's side effects are `edge.ts`'s.
853
+ */
854
+ /**
855
+ * The image, pinned: the edge is every stack's way in, so a new version is a
856
+ * change to this line, not whatever `latest` is on the day a server starts.
857
+ */
858
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
859
+ /** The edge's compose project, one per server. */
860
+ const EDGE_PROJECT = "gkm-edge";
861
+ /** The external network the edge and every stack's public services share. */
862
+ const EDGE_NETWORK = "gkm-edge";
863
+ /** The edge's compose service. */
864
+ const EDGE_SERVICE = "traefik";
865
+ /** Inside the edge's container: what it watches, and where certificates are. */
866
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
867
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
868
+ /** The certificate resolver every deployed route without its own certificate uses. */
869
+ const ACME_RESOLVER = "letsencrypt";
870
+ /** The internal entrypoint the edge's health check asks; never published. */
871
+ const PING_PORT = 8082;
872
+ /** A stack's service, as the edge — and the stack itself — reach it. */
873
+ function edgeAlias(project, service) {
874
+ return `${project}-${service}`;
875
+ }
876
+ /** A stack's certificate, as the edge's container reads it. */
877
+ function edgeCertificatePaths(project) {
878
+ return {
879
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
880
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
881
+ };
882
+ }
883
+ /**
884
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
885
+ * the directory it watches. No API and no dashboard — nothing about the edge
886
+ * is reachable but the routes stacks register.
887
+ */
888
+ function traefikStatic(ports) {
889
+ return {
890
+ global: {
891
+ checkNewVersion: false,
892
+ sendAnonymousUsage: false
893
+ },
894
+ entryPoints: {
895
+ web: {
896
+ address: ":80",
897
+ http: { redirections: { entryPoint: {
898
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
899
+ scheme: "https",
900
+ permanent: true
901
+ } } }
902
+ },
903
+ websecure: { address: ":443" },
904
+ ping: { address: `:${PING_PORT}` }
905
+ },
906
+ ping: { entryPoint: "ping" },
907
+ providers: { file: {
908
+ directory: EDGE_DYNAMIC_DIR,
909
+ watch: true
910
+ } },
911
+ certificatesResolvers: { [ACME_RESOLVER]: { acme: {
912
+ storage: "/acme/acme.json",
913
+ httpChallenge: { entryPoint: "web" }
914
+ } } },
915
+ log: { level: "INFO" }
916
+ };
917
+ }
918
+ /** The edge's compose document. */
919
+ function edgeCompose(options) {
920
+ const { ports } = options;
921
+ return {
922
+ name: EDGE_PROJECT,
923
+ services: { [EDGE_SERVICE]: {
924
+ image: TRAEFIK_IMAGE,
925
+ restart: "unless-stopped",
926
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
927
+ configs: [{
928
+ source: "traefik",
929
+ target: "/etc/traefik/traefik.yml"
930
+ }],
931
+ volumes: [
932
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
933
+ `certs:${EDGE_CERTS_DIR}`,
934
+ "acme:/acme"
935
+ ],
936
+ labels: { "dev.geekmidas.edge.config": createHash("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
937
+ networks: ["edge"],
938
+ healthcheck: {
939
+ test: [
940
+ "CMD",
941
+ "traefik",
942
+ "healthcheck",
943
+ "--ping"
944
+ ],
945
+ interval: "10s",
946
+ timeout: "5s",
947
+ retries: 5
948
+ },
949
+ logging: options.logging
950
+ } },
951
+ configs: { traefik: { content: options.staticConfig } },
952
+ volumes: {
953
+ acme: {},
954
+ dynamic: {},
955
+ certs: {}
956
+ },
957
+ networks: { edge: {
958
+ name: EDGE_NETWORK,
959
+ external: true
960
+ } }
961
+ };
962
+ }
963
+ /** A stack's dynamic configuration, as an object. */
964
+ function traefikDynamic(routes, options) {
965
+ const { project, tls } = options;
966
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
967
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
968
+ const routers = {};
969
+ const services = {};
970
+ const middlewares = {};
971
+ const strip = `${project}-strip-gkm-headers`;
972
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
973
+ for (const route of routes) {
974
+ const chain = [strip];
975
+ if (route.allow) {
976
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
977
+ chain.push(name(route, "allow"));
978
+ }
979
+ if (route.prefix) {
980
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
981
+ chain.push(name(route, "prefix"));
982
+ }
983
+ routers[name(route)] = {
984
+ rule: `Host(\`${route.host}\`)`,
985
+ entryPoints: ["websecure"],
986
+ service: name(route),
987
+ middlewares: chain,
988
+ tls: tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {}
989
+ };
990
+ services[name(route)] = { loadBalancer: {
991
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
992
+ ...route.prefix ? { passHostHeader: false } : {},
993
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
994
+ ...route.health ? { healthCheck: {
995
+ path: route.health,
996
+ interval: "5s",
997
+ timeout: "3s"
998
+ } } : {}
999
+ } };
1000
+ }
1001
+ return {
1002
+ http: {
1003
+ routers,
1004
+ services,
1005
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
1006
+ },
1007
+ ...tls.kind === "files" ? { tls: { certificates: [{
1008
+ certFile: tls.certFile,
1009
+ keyFile: tls.keyFile
1010
+ }] } } : {}
1011
+ };
1012
+ }
1013
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
1014
+ function traefikDynamicFile(routes, options) {
1015
+ return `# Generated by gkm compose for ${options.project} — do not edit.
1016
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
1017
+ # one is removed by gkm compose --down.
1018
+ ${yaml(traefikDynamic(routes, options))}`;
1019
+ }
1020
+ /** The edge's static configuration file. */
1021
+ function traefikStaticFile(ports) {
1022
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1023
+ ${yaml(traefikStatic(ports))}`;
1024
+ }
1025
+ /** The edge's compose file. */
1026
+ function edgeComposeFile(options) {
1027
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
1028
+ #
1029
+ # Started by the first stack that runs with proxy: 'traefik', and left
1030
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
1031
+ #
1032
+ # docker compose -p ${EDGE_PROJECT} down
1033
+ ${yaml(edgeCompose(options))}`;
1034
+ }
1035
+ function yaml(value) {
1036
+ return stringify(value, {
1037
+ lineWidth: 0,
1038
+ aliasDuplicateObjects: false
1039
+ });
1040
+ }
1041
+ //#endregion
1042
+ //#region src/compose/stack.ts
1043
+ /**
1044
+ * The stack a workspace runs as for one stage — pure.
1045
+ *
1046
+ * Everything `gkm compose` writes is decided here, as data: the compose file,
1047
+ * the Caddyfile, one env file per backend, and the image each app runs. The
1048
+ * command around it reads the workspace, asks the registry, writes the files
1049
+ * and starts Docker; none of those decide anything, so all of it can be
1050
+ * asserted without a daemon.
1051
+ *
1052
+ * The values come from the same derivations every other target uses. The
1053
+ * plan is reconcile's `planFor`, the keys an app reads are `appEnvKeys`, and
1054
+ * every URL is `envFor`'s — asked twice, once with each app at its public
1055
+ * address and once on the compose network, because a browser and a sibling
1056
+ * service reach the same API by different names.
1057
+ */
1058
+ /** Where a stack's files are written, relative to the workspace root. */
1059
+ function stackDir(stage) {
1060
+ return `.gkm/compose/${stage}`;
1061
+ }
1062
+ /**
1063
+ * The compose project a stage's stack runs as.
1064
+ *
1065
+ * The deploy identity's scope, so two workspaces with one name in different
1066
+ * namespaces never share containers or volumes — and the stage, so a
1067
+ * machine can run two stages side by side.
1068
+ */
1069
+ function composeProject(identity) {
1070
+ return `${identity.scope}-${identity.stage}`;
1071
+ }
1072
+ /** The ports the edge is published on, and the variables that move them. */
1073
+ const EDGE_PORT_ENV = {
1074
+ https: "GKM_COMPOSE_HTTPS_PORT",
1075
+ http: "GKM_COMPOSE_HTTP_PORT"
1076
+ };
1077
+ /**
1078
+ * The variable that moves the local stage's OpenObserve off its loopback
1079
+ * port, 5080 — which the local stage takes from nowhere else, since it
1080
+ * ignores `deploy.telemetry`. Another stack, or another tool, may hold 5080.
1081
+ */
1082
+ const LOGS_PORT_ENV = "GKM_COMPOSE_LOGS_PORT";
1083
+ /**
1084
+ * Containers this target does not run.
1085
+ *
1086
+ * The AWS emulator never applies: a stack is a server target, whose events
1087
+ * are pg-boss. Reconcile's Caddy fronts `gkm dev`'s host processes; the stack
1088
+ * brings its own edge.
1089
+ *
1090
+ * MinIO and Mailpit run on the local stage always, and on a deployed stage
1091
+ * only where `--allow-dev-services` allowed them and its secrets configure no
1092
+ * real bucket or mail server — see `devServices.ts`.
1093
+ */
1094
+ const NOT_RUN = {
1095
+ localstack: true,
1096
+ caddy: true
1097
+ };
1098
+ /** The kinds a deployed stage takes from its secrets, or a dev service. */
1099
+ const SERVICE_KINDS = {
1100
+ email: "email",
1101
+ objects: "objects",
1102
+ "file-server": "file-server"
1103
+ };
1104
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
1105
+ const MINIO_REGION = "us-east-1";
1106
+ /** The S3 client's credentials, read beside a bucket's URL when it has them. */
1107
+ const STORAGE_KEYS = [
1108
+ "AWS_ACCESS_KEY_ID",
1109
+ "AWS_SECRET_ACCESS_KEY",
1110
+ "AWS_REGION"
1111
+ ];
1112
+ /**
1113
+ * Every service's Docker logs, rotated. The json-file driver keeps a
1114
+ * container's output in one file that grows until the disk is full — on a
1115
+ * small server, in weeks. Three files of 10 MB each per container is enough
1116
+ * to see what happened and never fills anything. A project's own override
1117
+ * file that sets `logging` wins over it.
1118
+ */
1119
+ const LOG_ROTATION = {
1120
+ driver: "json-file",
1121
+ options: {
1122
+ "max-size": "10m",
1123
+ "max-file": "3"
1124
+ }
1125
+ };
1126
+ /**
1127
+ * The stack with Caddy's files inline: its Caddyfile and, where the stage has
1128
+ * one, its own certificate — `configs` with their `content`, which compose
1129
+ * copies into the container through the engine's API. Nothing is mounted from
1130
+ * a path, so the stack runs the same on a server's engine, over SSH, as on
1131
+ * this machine's. Their hash is a label: a changed file is a changed service,
1132
+ * which `up` recreates (compose does not, for a config's content alone).
1133
+ */
1134
+ function withCaddyConfigs(compose, files) {
1135
+ const caddy = compose.services.caddy;
1136
+ if (!caddy) return compose;
1137
+ const configs = {
1138
+ caddyfile: { content: files.caddyfile },
1139
+ ...files.tls ? {
1140
+ "tls-cert": { content: files.tls.cert },
1141
+ "tls-key": { content: files.tls.key }
1142
+ } : {}
1143
+ };
1144
+ const hash = createHash("sha256");
1145
+ for (const [name, { content }] of Object.entries(configs)) hash.update(`${name}\0${content}\0`);
1146
+ return {
1147
+ ...compose,
1148
+ services: {
1149
+ ...compose.services,
1150
+ caddy: {
1151
+ ...caddy,
1152
+ configs: [{
1153
+ source: "caddyfile",
1154
+ target: "/etc/caddy/Caddyfile"
1155
+ }, ...files.tls ? [{
1156
+ source: "tls-cert",
1157
+ target: `${CADDY_TLS_DIR}/cert.pem`
1158
+ }, {
1159
+ source: "tls-key",
1160
+ target: `${CADDY_TLS_DIR}/key.pem`,
1161
+ mode: 256
1162
+ }] : []],
1163
+ labels: {
1164
+ ...caddy.labels,
1165
+ "dev.geekmidas.caddy.config": hash.digest("hex").slice(0, 16)
1166
+ }
1167
+ }
1168
+ },
1169
+ configs: {
1170
+ ...compose.configs,
1171
+ ...configs
1172
+ }
1173
+ };
1174
+ }
1175
+ /** The local stage's stack, without the logins `gkm dev` generates. */
1176
+ var LocalCredentialsMissing = class extends GkmError {
1177
+ stage;
1178
+ constructor(stage) {
1179
+ super(`The local stage '${stage}' runs with this machine's generated logins, and none were passed. Load them with loadLocalCredentials(workspace) and pass them as localCredentials.`);
1180
+ this.stage = stage;
1181
+ this.name = "LocalCredentialsMissing";
1182
+ }
1183
+ };
1184
+ /**
1185
+ * A deployed stage's container logins, derived from its seed like its role
1186
+ * passwords — so every deploy of the stage computes the same ones, and no one
1187
+ * reading the repo can.
1188
+ */
1189
+ function derivedCredentials(project, plan, seed) {
1190
+ const derive = (purpose) => localRolePassword(project, plan, purpose, seed);
1191
+ return {
1192
+ postgres: {
1193
+ user: postgresSuperuser(project),
1194
+ password: derive("master")
1195
+ },
1196
+ minio: {
1197
+ user: `${project}-minio`,
1198
+ password: derive("minio")
1199
+ },
1200
+ rabbitmq: {
1201
+ user: LOCAL_RABBITMQ_USER,
1202
+ password: derive("rabbitmq")
1203
+ },
1204
+ redis: { password: derive("redis") },
1205
+ cacheToken: derive("cache-token"),
1206
+ emulator: {
1207
+ accessKeyId: EMULATOR_ACCESS_KEY_ID,
1208
+ secretAccessKey: derive("emulator")
1209
+ },
1210
+ logs: {
1211
+ email: `admin@${project}`,
1212
+ password: derive("logs")
1213
+ }
1214
+ };
1215
+ }
1216
+ /** A value only the stage's secrets can hold, and they do not. */
1217
+ var StageSecretMissing = class extends GkmError {
1218
+ app;
1219
+ key;
1220
+ stage;
1221
+ constructor(app, key, stage) {
1222
+ super(`'${app}' reads ${key}, and the stage '${stage}' has none. Nothing in the stack can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
1223
+ this.app = app;
1224
+ this.key = key;
1225
+ this.stage = stage;
1226
+ this.name = "StageSecretMissing";
1227
+ }
1228
+ };
1229
+ /** A deployed stage's secrets with no seed to derive its passwords from. */
1230
+ var StageSeedMissing = class extends GkmError {
1231
+ stage;
1232
+ constructor(stage) {
1233
+ super(`The stage '${stage}' has no seed in its secrets, and a deployed stage's database passwords are derived from it. Run gkm compose --stage ${stage} without --dry-run once, or gkm deploy, to generate it.`);
1234
+ this.stage = stage;
1235
+ this.name = "StageSeedMissing";
1236
+ }
1237
+ };
1238
+ /** A workspace with no API and no site to run. */
1239
+ var NothingToCompose = class extends GkmError {
1240
+ root;
1241
+ constructor(root) {
1242
+ super(`${root} declares no RestApi, no site and no Worker with work to do, so a stack would run nothing. Mobile apps ship through their own toolchain.`);
1243
+ this.root = root;
1244
+ this.name = "NothingToCompose";
1245
+ }
1246
+ };
1247
+ /** A value that cannot be written to an env file a line at a time. */
1248
+ var EnvValueMultiline = class extends GkmError {
1249
+ app;
1250
+ key;
1251
+ constructor(app, key) {
1252
+ super(`${key} for '${app}' spans more than one line, and an env file holds one value per line. Store it on one line — base64, or JSON — and decode it where it is read.`);
1253
+ this.app = app;
1254
+ this.key = key;
1255
+ this.name = "EnvValueMultiline";
1256
+ }
1257
+ };
1258
+ /** The services a stack's apps wait on and the edge waits on in turn. */
1259
+ const HEALTHY = { condition: "service_healthy" };
1260
+ /**
1261
+ * An app's health check: its own server, asked on 127.0.0.1 — not
1262
+ * `localhost`, which resolves to `::1` first in an Alpine container while a
1263
+ * server may listen on IPv4 alone.
1264
+ */
1265
+ function probe(port, path) {
1266
+ return {
1267
+ test: [
1268
+ "CMD",
1269
+ "wget",
1270
+ "-q",
1271
+ "-O",
1272
+ "/dev/null",
1273
+ `http://127.0.0.1:${port}${path}`
1274
+ ],
1275
+ interval: "5s",
1276
+ timeout: "3s",
1277
+ retries: 20,
1278
+ start_period: "10s"
1279
+ };
1280
+ }
1281
+ /**
1282
+ * What a stage's stack provisions: reconcile's plan, with a server target's
1283
+ * backends whatever `deploy.default` says — the stack is one machine running
1284
+ * containers, so events are pg-boss beside the declared database, and every
1285
+ * cache, one declared from that database included, is in the stack's own
1286
+ * Redis.
1287
+ */
1288
+ function stackPlan(workspace, manifest, stage) {
1289
+ return planFor(manifest, stage, provisionOrder(manifest), {
1290
+ localStage: workspace.stages.local,
1291
+ events: DEFAULT_EVENTS.server,
1292
+ cache: STACK_CACHE,
1293
+ edge: false
1294
+ });
1295
+ }
1296
+ /** The stack for one stage. */
1297
+ function composeStack(input) {
1298
+ const { workspace, manifest, stage, identity } = input;
1299
+ const local = stage === workspace.stages.local;
1300
+ const project = composeProject(identity);
1301
+ const custom = input.secrets?.custom ?? {};
1302
+ const https = input.ports?.https ?? 443;
1303
+ const http = input.ports?.http ?? 80;
1304
+ const proxy = proxyFor(workspace.deploy?.compose, stage, local);
1305
+ const certificate = local ? void 0 : certificateFor(workspace.deploy?.compose, stage, workspace.root);
1306
+ const plan = stackPlan(workspace, manifest, stage);
1307
+ const byId = new Map(plan.resources.map((r) => [r.id, r]));
1308
+ if (local && !input.localCredentials) throw new LocalCredentialsMissing(stage);
1309
+ const seed = local ? input.localCredentials.seed : input.secrets?.seed;
1310
+ if (!seed) throw new StageSeedMissing(stage);
1311
+ const containers = local ? input.localCredentials : derivedCredentials(workspace.name, plan, seed);
1312
+ const credential = {
1313
+ containers: {
1314
+ ...containers,
1315
+ minio: {
1316
+ user: custom.AWS_ACCESS_KEY_ID ?? containers.minio.user,
1317
+ password: custom.AWS_SECRET_ACCESS_KEY ?? containers.minio.password
1318
+ }
1319
+ },
1320
+ seed
1321
+ };
1322
+ const apps = stackApps(workspace, manifest, plan, {
1323
+ local,
1324
+ stage,
1325
+ https,
1326
+ identity,
1327
+ images: input.images
1328
+ });
1329
+ const workers = stackWorkers(workerUnits(workspace, manifest, input.background ?? {}), {
1330
+ stage,
1331
+ identity,
1332
+ images: input.images
1333
+ });
1334
+ if (apps.length === 0 && workers.length === 0) throw new NothingToCompose(workspace.root);
1335
+ const owners = /* @__PURE__ */ new Map();
1336
+ for (const resource of plan.resources) {
1337
+ owners.set(resource.envKey, resource);
1338
+ if (resource.kind === "email") {
1339
+ owners.set(provideKey(resource.id, "from"), resource);
1340
+ owners.set(provideKey(resource.id, "inboxUrl"), resource);
1341
+ }
1342
+ if (resource.kind === "external-api") owners.set(provideKey(resource.id, "credentials"), resource);
1343
+ }
1344
+ const domain = workspace.domains?.[stage];
1345
+ const telemetry = resolveStageTelemetry({
1346
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
1347
+ stage,
1348
+ local,
1349
+ target: "compose",
1350
+ runtime: "server",
1351
+ selfHosted: true,
1352
+ used: usesTelemetry(manifest)
1353
+ });
1354
+ const logsBase = telemetry?.provider === "self-hosted" ? stackLogs({
1355
+ config: local && input.ports?.logs ? {
1356
+ ...telemetry.selfHosted,
1357
+ port: input.ports.logs
1358
+ } : telemetry.selfHosted,
1359
+ stage,
1360
+ local,
1361
+ project: workspace.name,
1362
+ ...domain ? { domain } : {},
1363
+ custom,
1364
+ https,
1365
+ ...local ? { localLogin: input.localCredentials.logs } : {}
1366
+ }) : void 0;
1367
+ const services = local ? {
1368
+ missing: [],
1369
+ minio: plan.resources.filter((r) => r.kind === "objects").map((r) => r.id),
1370
+ mailpit: plan.resources.filter((r) => r.kind === "email").map((r) => r.id)
1371
+ } : externalServices({
1372
+ stage,
1373
+ declarations: stageServiceDeclarations({
1374
+ manifest,
1375
+ ...input.runnables ? { runnables: input.runnables } : {}
1376
+ }),
1377
+ supplied: custom,
1378
+ allow: input.allowDevServices === true,
1379
+ ...domain ? { domain } : {},
1380
+ providers: stageProviderNotes(workspace, stage)
1381
+ });
1382
+ const redis = stackRedis({
1383
+ plan,
1384
+ stage,
1385
+ local,
1386
+ custom,
1387
+ ...local ? { localPassword: input.localCredentials.redis.password } : {}
1388
+ });
1389
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== LOGS_SERVICE).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [LOGS_SERVICE] : []].sort();
1390
+ const storage = infra.includes("minio") ? (() => {
1391
+ const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
1392
+ return {
1393
+ ...credential.containers.minio,
1394
+ buckets,
1395
+ policies: bucketPolicies(plan).filter((p) => buckets.includes(p.bucket))
1396
+ };
1397
+ })() : void 0;
1398
+ const fileServers = /* @__PURE__ */ new Map();
1399
+ if (storage) for (const resource of plan.resources) {
1400
+ if (resource.kind !== "file-server" || !resource.of) continue;
1401
+ if (!services.minio.includes(resource.of)) continue;
1402
+ if (custom[resource.envKey] !== void 0) continue;
1403
+ const bucket = byId.get(resource.of);
1404
+ if (!bucket) continue;
1405
+ let host;
1406
+ if (local) host = hostFor(resource, workspace.name);
1407
+ else {
1408
+ if (!domain) throw new NoDomainForStage(stage);
1409
+ host = `${resource.subdomain ?? appKey(resource.id)}.${domain}`;
1410
+ }
1411
+ fileServers.set(resource.id, {
1412
+ url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1413
+ route: {
1414
+ name: `files-${appKey(resource.id)}`,
1415
+ host,
1416
+ upstreams: [{
1417
+ service: "minio",
1418
+ port: 9e3
1419
+ }],
1420
+ streaming: false,
1421
+ prefix: `/${bucket.name}`
1422
+ }
1423
+ });
1424
+ }
1425
+ const edgeServices = new Set(proxy === "traefik" ? [
1426
+ ...apps.map((app) => app.name),
1427
+ ...fileServers.size > 0 ? ["minio"] : [],
1428
+ ...logsBase?.host && logsBase.public ? [LOGS_SERVICE] : []
1429
+ ] : []);
1430
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1431
+ const logs = logsBase && {
1432
+ ...logsBase,
1433
+ appEnv: {
1434
+ ...logsBase.appEnv,
1435
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1436
+ }
1437
+ };
1438
+ const derivation = {
1439
+ project: workspace.name,
1440
+ credentials: credential.containers,
1441
+ seed: credential.seed,
1442
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {}
1443
+ };
1444
+ const outside = networkEnv(plan, {
1445
+ ...derivation,
1446
+ addresses: Object.fromEntries(apps.map((app) => [app.id, app.url]))
1447
+ }, hostOf);
1448
+ const inside = networkEnv(plan, {
1449
+ ...derivation,
1450
+ addresses: Object.fromEntries(apps.map((app) => [app.id, `http://${hostOf(app.name)}:${app.port}`]))
1451
+ }, hostOf);
1452
+ const surfaceUrls = new Map(plan.resources.filter((r) => r.kind === "rest-api" || r.kind === "site").map((r) => [r.envKey, r.id]));
1453
+ const appById = new Map(apps.map((app) => [app.id, app]));
1454
+ /**
1455
+ * What a key resolves to for one app, from the stage's secrets where only
1456
+ * they can hold it, and the derivations otherwise.
1457
+ */
1458
+ const valueFor = (app, key, owner) => {
1459
+ if (isReservedStageKey(key)) return void 0;
1460
+ if (owner && SERVICE_KINDS[owner.kind]) {
1461
+ if (custom[key] !== void 0) return custom[key];
1462
+ if (owner.kind === "file-server") return fileServers.get(owner.id)?.url;
1463
+ return outside[key];
1464
+ }
1465
+ if (owner && suppliedOnly(owner.kind, owner.id, key, local)) {
1466
+ const value = custom[key];
1467
+ if (value === void 0) throw new StageSecretMissing(app.name, key, stage);
1468
+ return value;
1469
+ }
1470
+ if (custom[key] !== void 0) return custom[key];
1471
+ if (owner?.kind === "cache") return redis?.urls[key];
1472
+ const surface = surfaceUrls.get(key);
1473
+ if (app.kind === "rest-api" && surface && surface !== app.id) return inside[key];
1474
+ return outside[key];
1475
+ };
1476
+ const telemetryValues = logs ? telemetryEnv({
1477
+ endpoint: logs.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT,
1478
+ headers: logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS
1479
+ }, telemetry?.sampleRate ?? 1) : telemetry?.provider === "otlp" ? otlpTelemetryEnv(telemetry) : void 0;
1480
+ /** Each key one backend process reads, resolved for this stage. */
1481
+ const valuesFor = (app, keys) => {
1482
+ const values = {};
1483
+ for (const key of [...keys].sort()) {
1484
+ if (isTelemetryKey(key)) continue;
1485
+ const owner = owners.get(key) ?? storageOwner(key, plan);
1486
+ if (!local && owner?.kind === "email" && key.endsWith("_INBOX_URL")) continue;
1487
+ if (STORAGE_KEYS.includes(key)) {
1488
+ const value = custom[key] ?? storageValue(key, storage);
1489
+ if (value !== void 0) values[key] = value;
1490
+ continue;
1491
+ }
1492
+ const value = valueFor(app, key, owner);
1493
+ if (value !== void 0) values[key] = value;
1494
+ }
1495
+ return values;
1496
+ };
1497
+ for (const app of apps) {
1498
+ if (app.kind === "site") {
1499
+ const site = manifest[app.id];
1500
+ if (site?.kind !== "site") continue;
1501
+ const args = {};
1502
+ for (const [key, source] of Object.entries(publicEnvFor(site, manifest))) {
1503
+ const value = valueFor(app, source, owners.get(source));
1504
+ if (value !== void 0) args[key] = value;
1505
+ }
1506
+ if (app.build && Object.keys(args).length > 0) app.build.args = args;
1507
+ continue;
1508
+ }
1509
+ if (input.buildOnly) continue;
1510
+ const keys = appEnvKeys(manifest, app.name, input.runnables) ?? /* @__PURE__ */ new Set();
1511
+ const values = valuesFor(app, keys);
1512
+ const trusted = provideKey(app.id, "trustedOrigins");
1513
+ if (keys.has(trusted)) {
1514
+ const internal = (byId.get(app.id)?.callers ?? []).map((caller) => appById.get(caller)).filter((caller) => caller?.kind === "rest-api").map((caller) => `http://${hostOf(caller.name)}:${caller.port}`);
1515
+ const origins = [...(values[trusted] ?? "").split(",").filter(Boolean), ...internal];
1516
+ values[trusted] = [...new Set(origins)].join(",");
1517
+ }
1518
+ app.env = {
1519
+ ...scopeTelemetryEnv(values, {
1520
+ uses: telemetryOf(manifest, app.id) !== void 0,
1521
+ serviceName: app.name,
1522
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1523
+ }),
1524
+ NODE_ENV: "production",
1525
+ PORT: String(app.port),
1526
+ STAGE: stage
1527
+ };
1528
+ for (const [key, value] of Object.entries(app.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(app.name, key);
1529
+ }
1530
+ for (const worker of input.buildOnly ? [] : workers) {
1531
+ const keys = workerEnvKeys(manifest, worker.id, input.runnables) ?? /* @__PURE__ */ new Set();
1532
+ worker.env = {
1533
+ ...scopeTelemetryEnv(valuesFor({
1534
+ name: worker.name,
1535
+ id: worker.id,
1536
+ kind: "rest-api"
1537
+ }, keys), {
1538
+ uses: telemetryOf(manifest, worker.id) !== void 0,
1539
+ serviceName: worker.name,
1540
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1541
+ }),
1542
+ NODE_ENV: "production",
1543
+ PORT: String(worker.port),
1544
+ STAGE: stage
1545
+ };
1546
+ for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1547
+ }
1548
+ const deployedTls = certificate ? {
1549
+ kind: "files",
1550
+ ...proxy === "caddy" ? {
1551
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1552
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1553
+ } : edgeCertificatePaths(project)
1554
+ } : { kind: "acme" };
1555
+ const tls = local ? { kind: "internal" } : deployedTls;
1556
+ const backupsChoice = input.buildOnly ? void 0 : stageBackups(workspace, manifest, stage);
1557
+ const backups = backupsChoice?.mode === "on" && infra.includes("postgres") ? stackBackups({
1558
+ workspace,
1559
+ stage,
1560
+ project,
1561
+ plan,
1562
+ backups: backupsChoice.backups,
1563
+ custom,
1564
+ seed,
1565
+ superuser: credential.containers.postgres,
1566
+ ...telemetryValues ? { telemetry: telemetryValues } : {}
1567
+ }) : void 0;
1568
+ const layout = input.layout ?? defaultLayout(workspace.root);
1569
+ const compose = stackFile({
1570
+ project,
1571
+ plan,
1572
+ infra,
1573
+ apps,
1574
+ workers,
1575
+ credentials: credential.containers,
1576
+ ...storage ? { storage } : {},
1577
+ ...logs ? { logs } : {},
1578
+ ...redis ? { redis } : {},
1579
+ ...backups ? { backups } : {},
1580
+ https,
1581
+ http,
1582
+ composeDir: join(workspace.root, stackDir(stage)),
1583
+ buildRoot: layout.buildRoot,
1584
+ workspaceRoot: workspace.root,
1585
+ envFiles: !input.buildOnly,
1586
+ proxy,
1587
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)]))
1588
+ });
1589
+ const routes = [
1590
+ ...apps.map((app) => ({
1591
+ name: app.name,
1592
+ host: app.host,
1593
+ upstreams: [{
1594
+ service: app.name,
1595
+ port: app.port
1596
+ }],
1597
+ streaming: true,
1598
+ health: app.kind === "site" ? "/" : "/health"
1599
+ })),
1600
+ ...[...fileServers.values()].map(({ route }) => route),
1601
+ ...logs?.host && logs.public ? [{
1602
+ name: LOGS_SERVICE,
1603
+ host: logs.host,
1604
+ upstreams: [{
1605
+ service: LOGS_SERVICE,
1606
+ port: LOGS_PORT
1607
+ }],
1608
+ streaming: true,
1609
+ allow: logs.public.allow
1610
+ }] : []
1611
+ ];
1612
+ const dockerfiles = {};
1613
+ for (const app of apps) {
1614
+ if (!app.build) continue;
1615
+ dockerfiles[app.build.dockerfile] = appDockerfile(app.name, workspace.apps[app.name], {
1616
+ layout,
1617
+ workspaceRoot: workspace.root,
1618
+ apps: workspace.apps,
1619
+ manifest,
1620
+ cache: STACK_CACHE,
1621
+ workspace,
1622
+ stage
1623
+ });
1624
+ }
1625
+ for (const worker of workers) {
1626
+ if (!worker.build) continue;
1627
+ dockerfiles[worker.build.dockerfile] = workerDockerfile({
1628
+ id: worker.id,
1629
+ name: worker.name,
1630
+ app: worker.host
1631
+ }, workspace.apps[worker.host], {
1632
+ layout,
1633
+ workspaceRoot: workspace.root,
1634
+ cache: STACK_CACHE
1635
+ });
1636
+ }
1637
+ return {
1638
+ project,
1639
+ stage,
1640
+ local,
1641
+ apps,
1642
+ workers,
1643
+ infra,
1644
+ compose,
1645
+ proxy,
1646
+ routes,
1647
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, { tls }) } : { traefik: traefikDynamicFile(routes, {
1648
+ project,
1649
+ tls: deployedTls
1650
+ }) },
1651
+ ...certificate ? { tls: certificate } : {},
1652
+ dockerfiles,
1653
+ plan,
1654
+ credential,
1655
+ ...storage ? { storage } : {},
1656
+ devServices: local ? [] : devServicesUsed(services),
1657
+ ...logs ? { logs } : {},
1658
+ ...telemetry ? { telemetry } : {},
1659
+ ...redis ? { redis } : {},
1660
+ ...backups ? { backups } : {}
1661
+ };
1662
+ }
1663
+ /** The stack's MinIO's value for one of the S3 client's keys. */
1664
+ function storageValue(key, storage) {
1665
+ if (!storage) return void 0;
1666
+ if (key === "AWS_ACCESS_KEY_ID") return storage.user;
1667
+ if (key === "AWS_SECRET_ACCESS_KEY") return storage.password;
1668
+ if (key === "AWS_REGION") return MINIO_REGION;
1669
+ }
1670
+ /** Which bucket an S3 credential key belongs to — the first one declared. */
1671
+ function storageOwner(key, plan) {
1672
+ if (!STORAGE_KEYS.includes(key)) return void 0;
1673
+ return plan.resources.find((r) => r.kind === "objects");
1674
+ }
1675
+ /** The apps a stack runs: every API and every site, at its stage address. */
1676
+ function stackApps(workspace, manifest, plan, options) {
1677
+ const apps = [];
1678
+ const resources = new Map(plan.resources.map((r) => [r.id, r]));
1679
+ for (const [id, declaration] of Object.entries(manifest)) {
1680
+ if (declaration.kind !== "rest-api" && declaration.kind !== "site") continue;
1681
+ const name = appKey(id);
1682
+ const app = workspace.apps[name];
1683
+ const resource = resources.get(id);
1684
+ if (!app || !resource || !app.port) continue;
1685
+ const host = hostOf(name, app, workspace, resource, options);
1686
+ const tag = declaration.kind === "site" ? siteTag(options.images.tag, options.stage) : options.images.tag;
1687
+ const ref = validateImageRef(imageRef(options.identity, name, options.images.registry, tag));
1688
+ apps.push({
1689
+ app: name,
1690
+ name,
1691
+ id,
1692
+ kind: declaration.kind,
1693
+ path: app.path,
1694
+ port: app.port,
1695
+ host,
1696
+ url: `https://${host}${options.local && options.https !== 443 ? `:${options.https}` : ""}`,
1697
+ ref,
1698
+ tag,
1699
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${name}` } } : {}
1700
+ });
1701
+ }
1702
+ return apps.sort((a, b) => a.name.localeCompare(b.name));
1703
+ }
1704
+ /** Each worker's image, and where it is built from. */
1705
+ function stackWorkers(units, options) {
1706
+ return units.map((unit) => ({
1707
+ app: unit.name,
1708
+ name: unit.name,
1709
+ id: unit.id,
1710
+ host: unit.app,
1711
+ port: WORKER_PORT,
1712
+ ref: validateImageRef(imageRef(options.identity, unit.name, options.images.registry, options.images.tag)),
1713
+ tag: options.images.tag,
1714
+ ...options.images.mode === "build" ? { build: { dockerfile: `${stackDir(options.stage)}/Dockerfile.${unit.name}` } } : {}
1715
+ }));
1716
+ }
1717
+ /**
1718
+ * The host an app answers on for a stage: the `gkm dev` edge's
1719
+ * `*.localhost` names for the local stage, and the stage's domain — by the
1720
+ * same rule a deploy follows — for any other.
1721
+ */
1722
+ function hostOf(name, app, workspace, resource, options) {
1723
+ if (options.local) return hostFor(resource, workspace.name);
1724
+ return resolveHost(name, app, options.stage, workspace.domains, isMainFrontendApp(name, app, workspace.apps));
1725
+ }
1726
+ /** The compose document: the infrastructure, the apps, and the edge. */
1727
+ function stackFile(options) {
1728
+ const { project, plan, apps } = options;
1729
+ const infra = options.infra.filter((name) => name !== LOGS_SERVICE);
1730
+ const derived = composeFor({
1731
+ ...plan,
1732
+ containers: [...infra]
1733
+ }, {
1734
+ project,
1735
+ ports: Object.fromEntries(portKeys(infra, plan.fakes).map((key) => [key, 0])),
1736
+ credentials: options.credentials
1737
+ });
1738
+ const services = {};
1739
+ const volumes = {
1740
+ ...derived.volumes,
1741
+ ...options.proxy === "caddy" ? {
1742
+ "caddy-data": {},
1743
+ "caddy-config": {}
1744
+ } : {},
1745
+ ...options.logs ? { "openobserve-data": {} } : {}
1746
+ };
1747
+ for (const name of infra) {
1748
+ const { ports: _ports, depends_on, profiles: _profiles, ...service } = derived.services[name];
1749
+ services[name] = {
1750
+ ...service,
1751
+ ...depends_on?.length ? { depends_on: Object.fromEntries(depends_on.map((dep) => [dep, HEALTHY])) } : {}
1752
+ };
1753
+ }
1754
+ const postgres = services.postgres;
1755
+ if (postgres) postgres.ports = ["127.0.0.1::5432"];
1756
+ const minio = services.minio;
1757
+ if (minio && options.storage) {
1758
+ minio.environment = {
1759
+ ...minio.environment,
1760
+ MINIO_ROOT_USER: options.storage.user,
1761
+ MINIO_ROOT_PASSWORD: options.storage.password
1762
+ };
1763
+ minio.ports = ["127.0.0.1::9000"];
1764
+ }
1765
+ if (services["redis"] && options.redis) services[REDIS_SERVICE] = redisService(options.redis);
1766
+ if (options.logs) services[LOGS_SERVICE] = logsService(options.logs);
1767
+ if (options.backups) services[BACKUPS_SERVICE] = backupsService(options.backups, options.envFiles);
1768
+ for (const app of apps) services[app.name] = {
1769
+ image: app.ref,
1770
+ ...app.build ? { build: {
1771
+ ...composeBuildPaths({
1772
+ composeDir: options.composeDir,
1773
+ buildRoot: options.buildRoot,
1774
+ workspaceRoot: options.workspaceRoot,
1775
+ dockerfile: app.build.dockerfile
1776
+ }),
1777
+ ...app.build.args ? { args: app.build.args } : {}
1778
+ } } : {},
1779
+ restart: "unless-stopped",
1780
+ ...app.kind === "rest-api" ? {
1781
+ env_file: [{
1782
+ path: `./${app.name}.env`,
1783
+ format: "raw"
1784
+ }],
1785
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {}
1786
+ } : {},
1787
+ healthcheck: probe(app.port, app.kind === "site" ? "/" : "/health")
1788
+ };
1789
+ for (const worker of options.workers) services[worker.name] = {
1790
+ image: worker.ref,
1791
+ ...worker.build ? { build: composeBuildPaths({
1792
+ composeDir: options.composeDir,
1793
+ buildRoot: options.buildRoot,
1794
+ workspaceRoot: options.workspaceRoot,
1795
+ dockerfile: worker.build.dockerfile
1796
+ }) } : {},
1797
+ restart: "unless-stopped",
1798
+ env_file: [{
1799
+ path: `./${worker.name}.env`,
1800
+ format: "raw"
1801
+ }],
1802
+ ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
1803
+ healthcheck: probe(worker.port, "/health")
1804
+ };
1805
+ if (options.proxy === "caddy") services.caddy = {
1806
+ image: DEFAULT_IMAGES.caddy,
1807
+ restart: "unless-stopped",
1808
+ ports: [`${options.https}:443`, `${options.http}:80`],
1809
+ volumes: ["caddy-data:/data", "caddy-config:/config"],
1810
+ depends_on: Object.fromEntries(apps.map((app) => [app.name, HEALTHY])),
1811
+ healthcheck: {
1812
+ test: [
1813
+ "CMD",
1814
+ "caddy",
1815
+ "version"
1816
+ ],
1817
+ interval: "10s",
1818
+ timeout: "5s",
1819
+ retries: 5
1820
+ }
1821
+ };
1822
+ for (const [service, alias] of options.edge) {
1823
+ const definition = services[service];
1824
+ if (!definition) continue;
1825
+ definition.networks = {
1826
+ default: { aliases: [alias] },
1827
+ edge: { aliases: [alias] }
1828
+ };
1829
+ }
1830
+ for (const service of Object.values(services)) {
1831
+ if (!options.envFiles) delete service.env_file;
1832
+ service.logging = {
1833
+ driver: LOG_ROTATION.driver,
1834
+ options: { ...LOG_ROTATION.options }
1835
+ };
1836
+ }
1837
+ return {
1838
+ name: project,
1839
+ services,
1840
+ volumes,
1841
+ ...options.edge.size > 0 ? { networks: { edge: {
1842
+ name: EDGE_NETWORK,
1843
+ external: true
1844
+ } } } : {}
1845
+ };
1846
+ }
1847
+ /**
1848
+ * A build without a layout: the workspace is the build root, with pnpm.
1849
+ * What a caller that never looked at the filesystem gets.
1850
+ */
1851
+ function defaultLayout(root) {
1852
+ return {
1853
+ buildRoot: root,
1854
+ gkmRoot: ".",
1855
+ tools: {
1856
+ packageManager: "pnpm",
1857
+ turboVersion: TURBO_VERSION,
1858
+ monorepo: true
1859
+ },
1860
+ gkmPaths: ["gkm.config.*"]
1861
+ };
1862
+ }
1863
+ /** Render an app's env file: one `KEY=value` per line, read raw by compose. */
1864
+ function envFile(env) {
1865
+ return `${Object.entries(env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n")}\n`;
1866
+ }
1867
+ //#endregion
1868
+ //#region src/compose/edge.ts
1869
+ /**
1870
+ * The server's shared Traefik edge, in Docker: started when a stack needs it,
1871
+ * and each stack's routes written to — and removed from — the directory it
1872
+ * watches.
1873
+ *
1874
+ * Everything goes through the server's Docker engine, never its filesystem:
1875
+ * the edge's static configuration is handed to it inline, and the directories
1876
+ * it watches are volumes each stack writes into with `docker exec`. So the
1877
+ * deploy runs anywhere that reaches the engine — a CI runner over SSH — and
1878
+ * nothing it writes depends on a path on that machine.
1879
+ *
1880
+ * gkm-edge (compose project)
1881
+ * traefik.yml its static configuration (inline config)
1882
+ * dynamic/<project>.yml one per stack: routers, services, middlewares
1883
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
1884
+ */
1885
+ /** The edge's compose project, as docker is asked about it. */
1886
+ function edgeRef(file, options = {}) {
1887
+ return {
1888
+ project: EDGE_PROJECT,
1889
+ file,
1890
+ cwd: dirname(file),
1891
+ ...options
1892
+ };
1893
+ }
1894
+ /** Writing to or removing from the edge's volumes failed. */
1895
+ var EdgeWriteFailed = class extends GkmError {
1896
+ path;
1897
+ output;
1898
+ constructor(path, output) {
1899
+ 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.`);
1900
+ this.path = path;
1901
+ this.output = output;
1902
+ this.name = "EdgeWriteFailed";
1903
+ }
1904
+ };
1905
+ /**
1906
+ * Something other than the proxy a stack is set to holds the edge's ports.
1907
+ *
1908
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
1909
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
1910
+ * edge, or another stack's Caddy. Refused before anything is started, so the
1911
+ * stack is never left half on one proxy and half on the other.
1912
+ */
1913
+ var ComposeProxyClash = class extends GkmError {
1914
+ project;
1915
+ proxy;
1916
+ port;
1917
+ holder;
1918
+ constructor(project, proxy, port, holder) {
1919
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
1920
+ 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 === "gkm-edge" ? `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.`;
1921
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
1922
+ this.project = project;
1923
+ this.proxy = proxy;
1924
+ this.port = port;
1925
+ this.holder = holder;
1926
+ this.name = "ComposeProxyClash";
1927
+ }
1928
+ };
1929
+ /**
1930
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
1931
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
1932
+ */
1933
+ async function assertEdgePorts(docker, options) {
1934
+ const { project, proxy, ports } = options;
1935
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(options.engine, port)) if (!(proxy === "traefik" ? holder.project === "gkm-edge" : holder.project === project && holder.service === "caddy")) throw new ComposeProxyClash(project, proxy, port, holder);
1936
+ }
1937
+ /**
1938
+ * Write a file into the edge's running container whole or not at all: a
1939
+ * temporary name, then a rename. Not `.yml`: the edge reads only `.yml`,
1940
+ * `.yaml` and `.toml` files, so it never sees one half written.
1941
+ */
1942
+ async function put(docker, edge, path, content, mode = "644") {
1943
+ const result = await docker.exec(edge, EDGE_SERVICE, [
1944
+ "sh",
1945
+ "-c",
1946
+ "set -e; t=\"$1.tmp\"; cat > \"$t\"; chmod \"$2\" \"$t\"; mv \"$t\" \"$1\"",
1947
+ "sh",
1948
+ path,
1949
+ mode
1950
+ ], content);
1951
+ if (result.code !== 0) throw new EdgeWriteFailed(path, `${result.stderr}${result.stdout}`);
1952
+ }
1953
+ /** Remove files from the edge's container; whether the first was there. */
1954
+ async function remove(docker, edge, paths) {
1955
+ return (await docker.exec(edge, EDGE_SERVICE, [
1956
+ "sh",
1957
+ "-c",
1958
+ "e=1; [ -f \"$1\" ] && e=0; rm -f \"$@\"; exit $e",
1959
+ "sh",
1960
+ ...paths
1961
+ ])).code === 0;
1962
+ }
1963
+ /**
1964
+ * The edge, up: its network and its container — started when it is not
1965
+ * running, and recreated when its configuration changed. Idempotent: on a
1966
+ * server where it already runs as configured, `up` changes nothing. Its
1967
+ * compose file is written to `file`, on this machine: compose reads it here.
1968
+ */
1969
+ async function ensureEdge(docker, options) {
1970
+ const { file, ports } = options;
1971
+ const content = edgeComposeFile({
1972
+ ports,
1973
+ staticConfig: traefikStaticFile(ports),
1974
+ logging: options.logging
1975
+ });
1976
+ await mkdir(dirname(file), { recursive: true });
1977
+ if (await readFile(file, "utf-8").catch(() => void 0) !== content) await writeFile(file, content);
1978
+ const ref = edgeRef(file, {
1979
+ ...options.host ? { host: options.host } : {},
1980
+ ...options.output ? { output: options.output } : {},
1981
+ ...options.signal ? { signal: options.signal } : {}
1982
+ });
1983
+ await docker.ensureNetwork(ref, EDGE_NETWORK);
1984
+ await docker.up(ref, [EDGE_SERVICE]);
1985
+ return [file];
1986
+ }
1987
+ /** A stack's routes, inside the edge's container. */
1988
+ function routesPath(project) {
1989
+ return `${EDGE_DYNAMIC_DIR}/${project}.yml`;
1990
+ }
1991
+ function certificatePaths(project) {
1992
+ return [`${EDGE_CERTS_DIR}/${project}.crt`, `${EDGE_CERTS_DIR}/${project}.key`];
1993
+ }
1994
+ /**
1995
+ * Register a stack with the edge: its certificate first, where it has one,
1996
+ * so the routes that need it never load without it — then its routes, in one
1997
+ * rename the edge picks up whole. The certificate is read here and written
1998
+ * through the engine. The paths written, inside the edge.
1999
+ */
2000
+ async function writeEdgeRoutes(docker, edge, project, routes, certificate) {
2001
+ const written = [];
2002
+ const [crt, key] = certificatePaths(project);
2003
+ if (certificate) {
2004
+ await put(docker, edge, crt, await readFile(certificate.certFile, "utf-8"));
2005
+ await put(docker, edge, key, await readFile(certificate.keyFile, "utf-8"), "600");
2006
+ written.push(crt, key);
2007
+ } else await remove(docker, edge, [crt, key]);
2008
+ await put(docker, edge, routesPath(project), routes);
2009
+ written.push(routesPath(project));
2010
+ return written;
2011
+ }
2012
+ /** What a stack's file holds for the moment between emptying and removal. */
2013
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
2014
+ /**
2015
+ * Unregister a stack: its routes, then its certificate. Whether there was
2016
+ * anything to remove — false, too, when the edge is not running.
2017
+ */
2018
+ async function removeEdgeRoutes(docker, edge, project) {
2019
+ const file = routesPath(project);
2020
+ if ((await docker.exec(edge, "traefik", [
2021
+ "test",
2022
+ "-f",
2023
+ file
2024
+ ])).code !== 0) return false;
2025
+ await put(docker, edge, file, UNREGISTERED);
2026
+ await remove(docker, edge, [file, ...certificatePaths(project)]);
2027
+ return true;
2028
+ }
2029
+ //#endregion
2030
+ //#region src/compose/secrets.ts
2031
+ function deployedStackSecrets(workspace, stage, stored, manifest) {
2032
+ const withSeed = withGeneratedSecrets(stored ?? initStageSecrets(stage), manifest);
2033
+ const withLogs = resolveStageTelemetry({
2034
+ ...workspace.deploy?.telemetry ? { telemetry: workspace.deploy.telemetry } : {},
2035
+ stage,
2036
+ local: false,
2037
+ target: "compose",
2038
+ runtime: "server",
2039
+ selfHosted: true,
2040
+ used: usesTelemetry(manifest)
2041
+ })?.provider === "self-hosted" ? withLogsPassword(withSeed.secrets) : {
2042
+ secrets: withSeed.secrets,
2043
+ generated: []
2044
+ };
2045
+ const withRedis = runsRedis(manifest, withLogs.secrets.custom ?? {}) ? withRedisPassword(withLogs.secrets) : {
2046
+ secrets: withLogs.secrets,
2047
+ generated: []
2048
+ };
2049
+ return {
2050
+ secrets: withRedis.secrets,
2051
+ generated: [
2052
+ ...withSeed.generated,
2053
+ ...withLogs.generated,
2054
+ ...withRedis.generated
2055
+ ]
2056
+ };
2057
+ }
2058
+ //#endregion
2059
+ //#region src/target/compose/health.ts
2060
+ /**
2061
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
2062
+ * the way a browser reaches it.
2063
+ *
2064
+ * `docker compose up --wait` already knows each container passed its own
2065
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
2066
+ * the stack is reachable: whether the edge routes the host to the app, and
2067
+ * whether the certificate it presents is one a client accepts. So the check
2068
+ * goes through the edge, by hostname, and verifies the certificate.
2069
+ */
2070
+ /** A request that got no answer in time. */
2071
+ var HealthRequestTimedOut = class extends GkmError {
2072
+ url;
2073
+ timeoutMs;
2074
+ constructor(url, timeoutMs) {
2075
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
2076
+ this.url = url;
2077
+ this.timeoutMs = timeoutMs;
2078
+ this.name = "HealthRequestTimedOut";
2079
+ }
2080
+ };
2081
+ /** The real probe: one HTTPS GET, the certificate verified. */
2082
+ const httpsProbe = ({ url, ca, connectTo, connectPort, timeoutMs, signal }) => {
2083
+ const target = new URL(url);
2084
+ return new Promise((resolve, reject) => {
2085
+ const req = request({
2086
+ host: connectTo ?? target.hostname,
2087
+ port: connectPort ?? (target.port || 443),
2088
+ servername: target.hostname,
2089
+ path: `${target.pathname}${target.search}`,
2090
+ method: "GET",
2091
+ headers: { host: target.host },
2092
+ ...ca ? { ca } : {},
2093
+ ...signal ? { signal } : {},
2094
+ timeout: timeoutMs
2095
+ }, (res) => {
2096
+ res.resume();
2097
+ res.on("end", () => resolve(res.statusCode ?? 0));
2098
+ res.on("error", reject);
2099
+ });
2100
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
2101
+ req.on("error", reject);
2102
+ req.end();
2103
+ });
2104
+ };
2105
+ /** Whether a status means the app answered as it should. */
2106
+ function isHealthy(status) {
2107
+ return status >= 200 && status < 400;
2108
+ }
2109
+ /** Apps that did not answer through the edge. */
2110
+ var ComposeAppsUnhealthy = class extends GkmError {
2111
+ project;
2112
+ apps;
2113
+ proxy;
2114
+ constructor(project, apps, proxy = "caddy") {
2115
+ const names = apps.map((a) => a.app).join(" ");
2116
+ super(`${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 gkm-edge logs traefik\` and \`docker compose -p ${project} logs ${names}\`.`));
2117
+ this.project = project;
2118
+ this.apps = apps;
2119
+ this.proxy = proxy;
2120
+ this.name = "ComposeAppsUnhealthy";
2121
+ }
2122
+ };
2123
+ //#endregion
2124
+ //#region src/target/compose/phases.ts
2125
+ /**
2126
+ * The compose target's phases: a stage as one Docker Compose stack behind
2127
+ * Caddy — the local stage on this machine's Docker, a deployed stage on its
2128
+ * server's, driven over SSH (`compose/server.ts`) from wherever the deploy
2129
+ * runs.
2130
+ *
2131
+ * The order is the point of this file, and the rules it keeps are these:
2132
+ *
2133
+ * - A tag is checked before anything happens (`validate`). Every app's image
2134
+ * is asked of the registry first; one missing image stops the run naming
2135
+ * them all, and nothing is written, pulled or started.
2136
+ * - The databases exist before the apps do (`provision`). Postgres comes up
2137
+ * alone, its databases, roles and grants are created, its migrations
2138
+ * applied and its seeds run from this machine — through an SSH tunnel to a
2139
+ * server's loopback — and only then do the apps
2140
+ * start — so an app
2141
+ * never boots against a schema that is not there yet.
2142
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
2143
+ * was released under and the digest it resolved to are written to the
2144
+ * stage's state, so "what is this stage running" has an exact answer.
2145
+ * - What was started answers (`verify`): each app is asked through Caddy,
2146
+ * over HTTPS, with the certificate verified.
2147
+ *
2148
+ * Every image is built inside Docker from a pruned slice of the build root —
2149
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
2150
+ * machine before `docker compose build`.
2151
+ *
2152
+ * Docker, the registry, Postgres and the health probe are
2153
+ * injected, so the rules are asserted without a daemon; the defaults are the
2154
+ * real ones.
2155
+ */
2156
+ /** `--push` without `--build`: there is nothing built here to push. */
2157
+ var ComposePushNeedsBuild = class extends GkmError {
2158
+ constructor() {
2159
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
2160
+ this.name = "ComposePushNeedsBuild";
2161
+ }
2162
+ };
2163
+ /** Digests to run by, on a run that pulls nothing. */
2164
+ var ComposePinNeedsPull = class extends GkmError {
2165
+ constructor() {
2166
+ 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.");
2167
+ this.name = "ComposePinNeedsPull";
2168
+ }
2169
+ };
2170
+ /** A port variable that does not hold a port. */
2171
+ var EdgePortInvalid = class extends GkmError {
2172
+ variable;
2173
+ value;
2174
+ constructor(variable, value) {
2175
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
2176
+ this.variable = variable;
2177
+ this.value = value;
2178
+ this.name = "EdgePortInvalid";
2179
+ }
2180
+ };
2181
+ /** A build with no commit to tag its images with. */
2182
+ var NoGitRevision = class extends GkmError {
2183
+ root;
2184
+ constructor(root) {
2185
+ 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.`);
2186
+ this.root = root;
2187
+ this.name = "NoGitRevision";
2188
+ }
2189
+ };
2190
+ /**
2191
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
2192
+ * at the workspace root. What the generated file cannot know — a port bound
2193
+ * to a tailnet address, another log driver — goes there, and is never
2194
+ * overwritten.
2195
+ */
2196
+ function stackOverrideFile(root, stage) {
2197
+ return join(root, `docker-compose.${stage}.yml`);
2198
+ }
2199
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
2200
+ async function gitRevision(root) {
2201
+ let sha;
2202
+ try {
2203
+ sha = (await runOutput("git", [
2204
+ "rev-parse",
2205
+ "--short",
2206
+ "HEAD"
2207
+ ], { cwd: root })).trim();
2208
+ } catch {
2209
+ throw new NoGitRevision(root);
2210
+ }
2211
+ if (!sha) throw new NoGitRevision(root);
2212
+ return (await runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
2213
+ }
2214
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
2215
+ function edgePorts(env = process.env) {
2216
+ const read = (variable, fallback) => {
2217
+ const value = env[variable];
2218
+ if (value === void 0 || value === "") return fallback;
2219
+ const port = Number(value);
2220
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
2221
+ return port;
2222
+ };
2223
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(LOGS_PORT_ENV, 0) : void 0;
2224
+ return {
2225
+ https: read(EDGE_PORT_ENV.https, 443),
2226
+ http: read(EDGE_PORT_ENV.http, 80),
2227
+ ...logs ? { logs } : {}
2228
+ };
2229
+ }
2230
+ /**
2231
+ * The real ones. Each app is asked for three minutes before it counts as
2232
+ * down: a deployed stage's first ACME certificate can take that long.
2233
+ */
2234
+ const defaultDeps = {
2235
+ docker: dockerCompose,
2236
+ revision: gitRevision,
2237
+ sql: pgClient,
2238
+ buckets: bucketClient,
2239
+ logins: ensurePostgresLogin,
2240
+ migrate: migrateDatabases,
2241
+ seed: seedDatabases,
2242
+ probe: httpsProbe,
2243
+ healthAttempts: 90,
2244
+ healthIntervalMs: 2e3,
2245
+ env: process.env,
2246
+ lookup: systemLookup,
2247
+ server: sshAccess
2248
+ };
2249
+ /**
2250
+ * The stack the stage would run, and — for a tag — the registry's word that
2251
+ * every image it names exists. Nothing is written: a missing image stops the
2252
+ * run here, before a file, a secret or a container is touched.
2253
+ */
2254
+ async function validateCompose(ctx, deps, options = {}) {
2255
+ const { workspace, stage, identity, tag } = ctx;
2256
+ const root = workspace.root;
2257
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
2258
+ const push = options.push === true;
2259
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
2260
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
2261
+ const registry = workspace.deploy?.registry;
2262
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, tag));
2263
+ const runnables = {};
2264
+ const background = {};
2265
+ const manifest = await discover({
2266
+ patterns: constructGlobs(workspace),
2267
+ cwd: root,
2268
+ runnables,
2269
+ background
2270
+ });
2271
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
2272
+ const layout = mode === "build" ? imageLayout(workspace) : void 0;
2273
+ const composed = composeStack({
2274
+ workspace,
2275
+ manifest,
2276
+ runnables,
2277
+ background,
2278
+ stage,
2279
+ identity,
2280
+ images: {
2281
+ mode,
2282
+ tag,
2283
+ ...registry ? { registry } : {}
2284
+ },
2285
+ secrets,
2286
+ ...stage === workspace.stages.local ? { localCredentials: (await loadLocalCredentials(workspace)).credentials } : {},
2287
+ allowDevServices: ctx.allowDevServices,
2288
+ ports: edgePorts(deps.env),
2289
+ ...layout ? { layout } : {},
2290
+ ...push ? { buildOnly: true } : {}
2291
+ });
2292
+ if (mode === "build") assertRedisClient(workspace, composed);
2293
+ const stack = options.pin ? withPinnedImages(composed, options.pin.file, options.pin.digests) : composed;
2294
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, tag, [...stack.apps, ...stack.workers]);
2295
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
2296
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
2297
+ ctx.secrets.mask(stack.logs.password);
2298
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
2299
+ }
2300
+ if (!push && !stack.local) requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
2301
+ const server = push ? void 0 : composeServer({
2302
+ stage,
2303
+ local: stack.local,
2304
+ config: workspace.deploy?.compose?.server,
2305
+ custom: secrets?.custom
2306
+ });
2307
+ const dir = join(root, stackDir(stage));
2308
+ const override = stackOverrideFile(root, stage);
2309
+ const overrides = existsSync(override) ? [override] : [];
2310
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
2311
+ const recorded = push ? void 0 : await ctx.state.read(stage);
2312
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
2313
+ const { ref, tag, digest } = releases.current;
2314
+ return [name, {
2315
+ ref,
2316
+ ...tag ? { tag } : {},
2317
+ ...digest ? { digest } : {}
2318
+ }];
2319
+ }));
2320
+ return {
2321
+ mode,
2322
+ push,
2323
+ stack,
2324
+ ...server ? { server } : {},
2325
+ dir,
2326
+ ref: {
2327
+ project: composeProject(identity),
2328
+ file: join(dir, "docker-compose.yml"),
2329
+ ...overrides.length > 0 ? { overrides } : {},
2330
+ cwd: root,
2331
+ ...server ? { host: dockerHost(server) } : {},
2332
+ output: ctx.childOutput,
2333
+ signal: ctx.signal
2334
+ },
2335
+ secrets,
2336
+ generated,
2337
+ previous,
2338
+ files: [],
2339
+ images: {},
2340
+ changes: []
2341
+ };
2342
+ }
2343
+ /**
2344
+ * What only a compose deploy checks before it changes anything, once the
2345
+ * stage's own keys are: the stage's own certificate is there, and every
2346
+ * public host points at the stage's server — its records written where a
2347
+ * provider holds them, then confirmed — before Caddy or Traefik ask Let's
2348
+ * Encrypt for a certificate it could not issue. A build-only run never asks.
2349
+ */
2350
+ async function readyCompose(ctx, run, deps) {
2351
+ const { stack } = run;
2352
+ if (stack.tls) {
2353
+ for (const file of [stack.tls.certFile, stack.tls.keyFile]) if (!existsSync(file)) throw new ComposeTlsFileMissing(ctx.stage, file);
2354
+ }
2355
+ if (stack.local) return;
2356
+ if (run.server && !ctx.dryRun && !run.push) await deps.server.check(run.server);
2357
+ await stageHostsDns(ctx, deps, stackHosts(stack).filter((host) => !isLocalHost(host)), run.secrets?.custom);
2358
+ }
2359
+ /** A stack whose caches are in Redis, built for an app that has no client. */
2360
+ var RedisClientMissing = class extends GkmError {
2361
+ apps;
2362
+ constructor(apps) {
2363
+ 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`);
2364
+ this.apps = apps;
2365
+ this.name = "RedisClientMissing";
2366
+ }
2367
+ };
2368
+ /**
2369
+ * Every backend and worker image built for a stack with a cache can resolve
2370
+ * `ioredis` — listed by its app or a directory above it, the way Node and
2371
+ * the image's install find it.
2372
+ */
2373
+ function assertRedisClient(workspace, stack) {
2374
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
2375
+ const missing = [.../* @__PURE__ */ new Set([...stack.apps.filter((app) => app.kind === "rest-api").map((a) => a.name), ...stack.workers.map((worker) => worker.host)])].filter((name) => {
2376
+ const app = workspace.apps[name];
2377
+ return app && !installedFrom(join(workspace.root, app.path), "ioredis");
2378
+ }).sort();
2379
+ if (missing.length > 0) throw new RedisClientMissing(missing);
2380
+ }
2381
+ /**
2382
+ * The deploy's DNS step, for a deployed stage: its server's address — required
2383
+ * where it serves a real domain — then its own hosts written through each
2384
+ * domain's provider in `dns` where they differ, read back from it, and
2385
+ * recorded in the stage's state; hosts no provider writes resolved with the
2386
+ * system resolver. A dry run prints the plan and writes nothing, and warns
2387
+ * rather than stops.
2388
+ *
2389
+ * @throws {ServerAddressMissing} when the stage has a domain and no address
2390
+ * @throws {ServerAddressInvalid} for a value that is not an address
2391
+ * @throws {HostNotPointingAtServer} when a host is not the server
2392
+ */
2393
+ async function stageHostsDns(ctx, deps, hosts, custom) {
2394
+ const { workspace, stage } = ctx;
2395
+ const server = requiredServerAddress(stage, workspace.domains?.[stage], custom);
2396
+ if (hosts.length === 0) return;
2397
+ if (ctx.skipDns) {
2398
+ ctx.logger.info("🌐 DNS skipped (--skip-dns): no record is written or checked");
2399
+ return;
2400
+ }
2401
+ if (!server) {
2402
+ ctx.logger.info(`🌐 DNS skipped: no ${SERVER_IPV4_KEY} in '${stage}''s secrets — ${serverAddressHint(stage)}`);
2403
+ return;
2404
+ }
2405
+ const log = (line) => ctx.logger.info(line);
2406
+ if (workspace.dns) log(`🌐 DNS for '${stage}' → ${server.ipv4}${server.ipv6 ? ` / ${server.ipv6}` : ""}${ctx.dryRun ? " (dry run — nothing is written)" : ""}`);
2407
+ try {
2408
+ const result = await stageDns({
2409
+ stage,
2410
+ hosts,
2411
+ server,
2412
+ dns: workspace.dns,
2413
+ credentials: ctx.credentials,
2414
+ log,
2415
+ lookup: deps.lookup ?? systemLookup,
2416
+ ...ctx.dryRun ? { dryRun: true } : {},
2417
+ ...deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}
2418
+ });
2419
+ if (!ctx.dryRun) {
2420
+ const journal = await DeployJournal.open(ctx.state, stage, () => createComposeState(stage));
2421
+ const providers = new Map(result.plan.domains.map((d) => [d.domain, d.provider]));
2422
+ await recordDnsChanges(journal, result.changes, (domain) => providers.get(domain));
2423
+ }
2424
+ 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);
2425
+ if (parts.length > 0) log(`🌐 ${parts.join(", ")}`);
2426
+ } catch (error) {
2427
+ if (ctx.dryRun && error instanceof HostNotPointingAtServer) {
2428
+ ctx.logger.warn(`⚠ ${error.message}`);
2429
+ return;
2430
+ }
2431
+ throw error;
2432
+ }
2433
+ }
2434
+ /**
2435
+ * The stage's secrets — and, for a deployed stage, everything it generates
2436
+ * once: its seed, and each declared secret and keyring. Kept only once the
2437
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
2438
+ * leaves the stage's secrets as it found them.
2439
+ */
2440
+ async function stageSecrets(ctx, manifest) {
2441
+ const stored = await ctx.secrets.read();
2442
+ if (ctx.stage === ctx.workspace.stages.local) return {
2443
+ secrets: stored,
2444
+ generated: []
2445
+ };
2446
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
2447
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
2448
+ for (const [key, value] of Object.entries(secrets.custom ?? {})) if (!isReservedStageKey(key)) ctx.secrets.mask(value);
2449
+ return {
2450
+ secrets,
2451
+ generated
2452
+ };
2453
+ }
2454
+ /**
2455
+ * The stack with each app's and worker's image pinned to the digest the file
2456
+ * names: the refs it is checked, pulled and recorded by, and the image each
2457
+ * compose service runs.
2458
+ */
2459
+ function withPinnedImages(stack, file, digests) {
2460
+ const apps = pinImages(file, digests, stack.apps);
2461
+ const workers = pinImages(file, digests, stack.workers);
2462
+ const services = { ...stack.compose.services };
2463
+ for (const image of [...apps, ...workers]) services[image.name] = {
2464
+ ...services[image.name],
2465
+ image: image.ref
2466
+ };
2467
+ return {
2468
+ ...stack,
2469
+ apps,
2470
+ workers,
2471
+ compose: {
2472
+ ...stack.compose,
2473
+ services
2474
+ }
2475
+ };
2476
+ }
2477
+ /**
2478
+ * A dry run: the stack's files, written so they can be read, and what a real
2479
+ * run would do — no image is built or pulled, no container touched, nothing
2480
+ * recorded and no secret kept.
2481
+ */
2482
+ async function planCompose(ctx, run) {
2483
+ 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.`);
2484
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
2485
+ printPlan(ctx, run);
2486
+ if (!run.push && run.stack.infra.includes("postgres")) reportPlannedSeeds((await plannedSeeds({
2487
+ root: ctx.workspace.root,
2488
+ manifest: ctx.manifest
2489
+ })).map(({ target, seeds }) => ({
2490
+ folder: target.seeds,
2491
+ seeds
2492
+ })), (line) => ctx.logger.info(line));
2493
+ const planned = (change) => {
2494
+ run.changes.push(change);
2495
+ ctx.emit({
2496
+ type: "resource.planned",
2497
+ ...change
2498
+ });
2499
+ };
2500
+ for (const service of run.push ? [] : run.stack.infra) planned({
2501
+ key: `service:${service}`,
2502
+ resourceType: "service",
2503
+ action: "ensure"
2504
+ });
2505
+ for (const app of run.stack.apps) {
2506
+ planned({
2507
+ key: `image:${app.name}`,
2508
+ resourceType: "image",
2509
+ action: run.mode === "build" ? "build" : "reuse",
2510
+ id: app.ref
2511
+ });
2512
+ if (run.push) continue;
2513
+ planned({
2514
+ key: `service:${app.name}`,
2515
+ resourceType: "service",
2516
+ action: run.previous[app.name] ? "reuse" : "create"
2517
+ });
2518
+ }
2519
+ for (const worker of run.stack.workers) {
2520
+ planned({
2521
+ key: `image:${worker.name}`,
2522
+ resourceType: "image",
2523
+ action: run.mode === "build" ? "build" : "reuse",
2524
+ id: worker.ref
2525
+ });
2526
+ if (run.push) continue;
2527
+ planned({
2528
+ key: `service:${worker.name}`,
2529
+ resourceType: "service",
2530
+ action: run.previous[worker.name] ? "reuse" : "create"
2531
+ });
2532
+ }
2533
+ if (!run.push) planned({
2534
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
2535
+ resourceType: "service",
2536
+ action: "ensure"
2537
+ });
2538
+ }
2539
+ /**
2540
+ * What the apps run on: the stage's generated secrets kept, the stack's files
2541
+ * written, its infrastructure started, and its databases, roles, grants and
2542
+ * migrations applied.
2543
+ */
2544
+ async function provisionCompose(ctx, run, deps) {
2545
+ const { stack, ref } = run;
2546
+ if (run.push) return;
2547
+ if (run.generated.length > 0 && run.secrets) {
2548
+ await ctx.secrets.write(run.secrets);
2549
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
2550
+ }
2551
+ const ports = edgePorts(deps.env);
2552
+ await assertEdgePorts(deps.docker, {
2553
+ project: stack.project,
2554
+ proxy: stack.proxy,
2555
+ ports,
2556
+ engine: ref
2557
+ });
2558
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2559
+ printPlan(ctx, run);
2560
+ if (stack.proxy === "traefik") {
2561
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT})…`);
2562
+ run.files.push(...await ensureEdge(deps.docker, {
2563
+ file: edgeFile(run),
2564
+ ports,
2565
+ ...ref.host ? { host: ref.host } : {},
2566
+ logging: {
2567
+ driver: LOG_ROTATION.driver,
2568
+ options: { ...LOG_ROTATION.options }
2569
+ },
2570
+ ...ref.output ? { output: ref.output } : {},
2571
+ ...ref.signal ? { signal: ref.signal } : {}
2572
+ }));
2573
+ applied(ctx, run, {
2574
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
2575
+ resourceType: "service",
2576
+ action: "ensure",
2577
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
2578
+ via: "found"
2579
+ });
2580
+ }
2581
+ if (stack.infra.length > 0) {
2582
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
2583
+ await deps.docker.up(ref, stack.infra);
2584
+ for (const service of stack.infra) applied(ctx, run, {
2585
+ key: `service:${service}`,
2586
+ resourceType: "service",
2587
+ action: "ensure",
2588
+ id: `${stack.project}/${service}`,
2589
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
2590
+ });
2591
+ }
2592
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
2593
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
2594
+ }
2595
+ /**
2596
+ * Create each bucket the stack's MinIO serves, and the open paths of each
2597
+ * one a file server fronts — from this machine, on MinIO's loopback port,
2598
+ * the way `gkm dev` creates them.
2599
+ */
2600
+ async function prepareBuckets(ctx, run, deps) {
2601
+ const storage = run.stack.storage;
2602
+ if (storage.buckets.length === 0) return;
2603
+ const tunnel = await reach(run, deps, "minio", 9e3);
2604
+ let done;
2605
+ try {
2606
+ const client = deps.buckets(tunnel.port, storage);
2607
+ done = [...await applyBuckets(client, storage.buckets), ...await applyPolicies(client, storage.policies)];
2608
+ } finally {
2609
+ await tunnel.close();
2610
+ }
2611
+ const created = done.filter((entry) => entry.created).length;
2612
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
2613
+ }
2614
+ /**
2615
+ * Create what the plan names in the stack's Postgres, migrate it, then run
2616
+ * its seeds — every one, every time, as each construct's owner.
2617
+ */
2618
+ async function prepareDatabases(ctx, run, deps) {
2619
+ const tunnel = await reach(run, deps, "postgres", 5432);
2620
+ try {
2621
+ await migrateAndSeed(ctx, run, deps, tunnel.port);
2622
+ } finally {
2623
+ await tunnel.close();
2624
+ }
2625
+ }
2626
+ /**
2627
+ * A port a stack's service publishes on its engine's loopback, reachable
2628
+ * from this machine: the published port itself on the local stage, and on a
2629
+ * server an SSH tunnel to it over the deploy's own login — so Postgres and
2630
+ * MinIO are never published beyond the server's loopback.
2631
+ *
2632
+ * Migrations and seeds run here, in this process, with the project's own
2633
+ * Kysely — the way `gkm migrate` runs them — through that port. No image
2634
+ * needs to carry them, and nothing is run on the server but the stack.
2635
+ */
2636
+ async function reach(run, deps, service, inside) {
2637
+ const published = await deps.docker.port(run.ref, service, inside);
2638
+ if (!run.server) return {
2639
+ port: published,
2640
+ close: async () => {}
2641
+ };
2642
+ return deps.server.tunnel(run.server, published);
2643
+ }
2644
+ async function migrateAndSeed(ctx, run, deps, port) {
2645
+ const { stack } = run;
2646
+ const workspace = ctx.workspace;
2647
+ const superuser = stack.credential.containers.postgres;
2648
+ const login = await deps.logins({
2649
+ port,
2650
+ login: superuser,
2651
+ legacy: [{
2652
+ user: LEGACY_LOCAL_LOGIN.user,
2653
+ password: superuser.password
2654
+ }, ...stack.local ? [LEGACY_LOCAL_LOGIN] : []]
2655
+ });
2656
+ if (login.notice) ctx.logger.info(login.notice);
2657
+ const statements = [...postgresStatements(stack.plan, workspace.name, stack.credential.seed), ...stack.backups ? backupsRoleStatements(stack.backups) : []];
2658
+ if (statements.length > 0) {
2659
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
2660
+ await applyPostgres(deps.sql(port, login.login), statements);
2661
+ }
2662
+ const sources = {};
2663
+ const manifest = await discover({
2664
+ patterns: constructGlobs(workspace),
2665
+ cwd: workspace.root,
2666
+ sources
2667
+ });
2668
+ const env = envFor(stack.plan, {
2669
+ ports: { [primaryPortKey("postgres")]: port },
2670
+ project: workspace.name,
2671
+ credentials: {
2672
+ ...stack.credential.containers,
2673
+ postgres: login.login
2674
+ },
2675
+ seed: stack.credential.seed
2676
+ });
2677
+ const options = {
2678
+ root: workspace.root,
2679
+ manifest,
2680
+ sources,
2681
+ env
2682
+ };
2683
+ const runs = await deps.migrate(options);
2684
+ const seeds = await deps.seed({
2685
+ ...options,
2686
+ stage: ctx.stage
2687
+ }).catch((error) => {
2688
+ if (error instanceof SeedFailed) throw new DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
2689
+ throw error;
2690
+ });
2691
+ reportDatabaseRuns(runs.map(({ target, applied }) => ({
2692
+ construct: target.id,
2693
+ folder: target.migrations,
2694
+ applied
2695
+ })), seeds.map(({ target, seeded }) => ({
2696
+ construct: target.id,
2697
+ folder: target.seeds,
2698
+ seeded
2699
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
2700
+ }
2701
+ /**
2702
+ * Each app's image: built from this checkout — inside Docker, every one of
2703
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
2704
+ * live changes.
2705
+ */
2706
+ async function buildCompose(ctx, run, deps) {
2707
+ const { stack, ref } = run;
2708
+ const images = [...stack.apps, ...stack.workers];
2709
+ const apps = images.map((image) => image.app);
2710
+ if (run.push) {
2711
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
2712
+ printPlan(ctx, run);
2713
+ }
2714
+ if (run.mode === "build") {
2715
+ ctx.logger.info("\n🐳 Building images…");
2716
+ await deps.docker.build(ref, apps);
2717
+ } else {
2718
+ ctx.logger.info(`\n🐳 Pulling ${ctx.tag}…`);
2719
+ await deps.docker.pull(ref, apps);
2720
+ }
2721
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
2722
+ for (const image of images) {
2723
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(ref, image.ref);
2724
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
2725
+ run.images[image.app] = {
2726
+ ref: image.ref,
2727
+ tag: image.tag,
2728
+ ...digest ? { digest } : {}
2729
+ };
2730
+ ctx.emit({
2731
+ type: "artifact.built",
2732
+ app: image.app,
2733
+ imageRef: image.ref,
2734
+ ...digest ? { digest } : {}
2735
+ });
2736
+ run.changes.push({
2737
+ key: `image:${image.app}`,
2738
+ resourceType: "image",
2739
+ action: run.mode === "build" ? "build" : "reuse",
2740
+ id: digest ?? image.ref
2741
+ });
2742
+ }
2743
+ }
2744
+ /**
2745
+ * The whole stack up — anything it no longer defines removed — and each
2746
+ * app's image recorded in the stage's state.
2747
+ */
2748
+ async function releaseCompose(ctx, run, deps) {
2749
+ const { stack, ref } = run;
2750
+ if (run.push) return;
2751
+ ctx.logger.info("\n🚀 Starting the stack…");
2752
+ await deps.docker.up(ref);
2753
+ const edge = edgeRef(edgeFile(run), {
2754
+ ...ref.host ? { host: ref.host } : {},
2755
+ ...ref.output ? { output: ref.output } : {}
2756
+ });
2757
+ if (stack.proxy === "traefik" && stack.traefik) {
2758
+ const written = await writeEdgeRoutes(deps.docker, edge, stack.project, stack.traefik, stack.tls);
2759
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
2760
+ } else if (!stack.local) await removeEdgeRoutes(deps.docker, edge, stack.project);
2761
+ if (stack.local) await deps.docker.copyOut(ref, "caddy", "/data/caddy/pki/authorities/local/root.crt", caFile(run)).catch(() => {});
2762
+ await recordImages(ctx, run);
2763
+ for (const app of stack.apps) {
2764
+ const image = run.images[app.name];
2765
+ applied(ctx, run, {
2766
+ key: `service:${app.name}`,
2767
+ resourceType: "service",
2768
+ action: "ensure",
2769
+ id: `${stack.project}/${app.name}`,
2770
+ via: run.previous[app.name] ? "recorded" : "created"
2771
+ });
2772
+ ctx.emit({
2773
+ type: "app.deployed",
2774
+ app: app.name,
2775
+ applicationId: `${stack.project}/${app.name}`,
2776
+ imageRef: image?.ref ?? app.ref,
2777
+ url: app.url
2778
+ });
2779
+ }
2780
+ for (const worker of stack.workers) applied(ctx, run, {
2781
+ key: `service:${worker.name}`,
2782
+ resourceType: "service",
2783
+ action: "ensure",
2784
+ id: `${stack.project}/${worker.name}`,
2785
+ via: run.previous[worker.name] ? "recorded" : "created"
2786
+ });
2787
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
2788
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url}`);
2789
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
2790
+ if (stack.local) ctx.logger.info(`\n🔐 Certificates are from Caddy's local CA: NODE_EXTRA_CA_CERTS=${join(stackDir(ctx.stage), "caddy-root.crt")}`);
2791
+ }
2792
+ /**
2793
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
2794
+ * records: the ref it runs, the tag it was released under, and the digest
2795
+ * the tag resolved to.
2796
+ */
2797
+ async function recordImages(ctx, run) {
2798
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
2799
+ const by = currentActor();
2800
+ for (const app of [...run.stack.apps, ...run.stack.workers]) {
2801
+ const image = run.images[app.app] ?? {
2802
+ ref: app.ref,
2803
+ tag: app.tag
2804
+ };
2805
+ recordRelease(journal.state, app.app, image, by);
2806
+ }
2807
+ journal.state.identity = ctx.identity.key;
2808
+ await journal.save();
2809
+ }
2810
+ /**
2811
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
2812
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
2813
+ * its certificates are Caddy's internal CA's, so the CA `release` copied out
2814
+ * is the one trusted and the request goes to 127.0.0.1.
2815
+ */
2816
+ async function verifyCompose(ctx, run, deps) {
2817
+ const { stack } = run;
2818
+ if (run.push) return;
2819
+ const ca = stack.local ? await readFile(caFile(run), "utf-8").catch(() => void 0) : void 0;
2820
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
2821
+ const edge = stack.local ? { connectTo: "127.0.0.1" } : run.server ? {
2822
+ connectTo: run.server.host,
2823
+ connectPort: edgePorts(deps.env).https
2824
+ } : void 0;
2825
+ const results = await Promise.all(stack.apps.map((app) => checkApp(ctx, app, deps, {
2826
+ ca,
2827
+ edge
2828
+ })));
2829
+ results.push(...await Promise.all(stack.workers.map((worker) => checkContainer(ctx, run, deps, worker.name))));
2830
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
2831
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
2832
+ app,
2833
+ url,
2834
+ last
2835
+ }));
2836
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
2837
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local, run.server);
2838
+ }
2839
+ /**
2840
+ * A container's own health check, as Docker reports it: a worker's, which
2841
+ * has no route through the edge, and OpenObserve's — by default it has no
2842
+ * host there, and served publicly it answers only the addresses it allows,
2843
+ * which need not include this one.
2844
+ */
2845
+ async function checkContainer(ctx, run, deps, service) {
2846
+ const url = `docker:${service}`;
2847
+ let last = "not asked";
2848
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2849
+ ctx.signal.throwIfAborted();
2850
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
2851
+ last = health ?? "not running";
2852
+ const healthy = health === "healthy";
2853
+ ctx.emit({
2854
+ type: "health.checked",
2855
+ app: service,
2856
+ url,
2857
+ healthy,
2858
+ attempt
2859
+ });
2860
+ if (healthy) {
2861
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
2862
+ return {
2863
+ app: service,
2864
+ url,
2865
+ last,
2866
+ healthy
2867
+ };
2868
+ }
2869
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2870
+ }
2871
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
2872
+ return {
2873
+ app: service,
2874
+ url,
2875
+ last,
2876
+ healthy: false
2877
+ };
2878
+ }
2879
+ /** How to open the logs, printed — and as an event, for a headless caller. */
2880
+ function reportLogs(ctx, logs, local, server) {
2881
+ const lines = logsAccess(logs, {
2882
+ stage: ctx.stage,
2883
+ local,
2884
+ user: server?.user ?? currentUser(),
2885
+ hostname: server?.host ?? hostname(),
2886
+ ...server ? { known: true } : {}
2887
+ });
2888
+ ctx.logger.info(`\n${lines.join("\n")}`);
2889
+ ctx.emit({
2890
+ type: "logs.ready",
2891
+ service: LOGS_SERVICE,
2892
+ access: logs.public ? "public" : "tunnel",
2893
+ url: logs.url,
2894
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
2895
+ email: logs.email
2896
+ });
2897
+ }
2898
+ /** This machine's user — a guess at who would SSH in. */
2899
+ function currentUser() {
2900
+ try {
2901
+ return userInfo().username;
2902
+ } catch {
2903
+ return process.env.USER ?? "user";
2904
+ }
2905
+ }
2906
+ async function checkApp(ctx, app, deps, options) {
2907
+ const url = `${app.url}${app.kind === "site" ? "/" : "/health"}`;
2908
+ let last = "not asked";
2909
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
2910
+ ctx.signal.throwIfAborted();
2911
+ let status;
2912
+ try {
2913
+ status = await deps.probe({
2914
+ url,
2915
+ ...options.ca ? { ca: options.ca } : {},
2916
+ ...options.edge,
2917
+ timeoutMs: 1e4,
2918
+ signal: ctx.signal
2919
+ });
2920
+ last = `HTTP ${status}`;
2921
+ } catch (error) {
2922
+ last = error instanceof Error ? error.message : String(error);
2923
+ }
2924
+ const healthy = status !== void 0 && isHealthy(status);
2925
+ ctx.emit({
2926
+ type: "health.checked",
2927
+ app: app.name,
2928
+ url,
2929
+ healthy,
2930
+ ...status !== void 0 ? { status } : {},
2931
+ attempt
2932
+ });
2933
+ if (healthy) {
2934
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
2935
+ return {
2936
+ app: app.name,
2937
+ url,
2938
+ last,
2939
+ healthy
2940
+ };
2941
+ }
2942
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
2943
+ }
2944
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
2945
+ return {
2946
+ app: app.name,
2947
+ url,
2948
+ last,
2949
+ healthy: false
2950
+ };
2951
+ }
2952
+ function composeResult(ctx, run) {
2953
+ const apps = [...run.stack.apps.map((app) => {
2954
+ const image = run.images[app.name];
2955
+ return {
2956
+ appName: app.name,
2957
+ type: app.kind === "site" ? "web" : "backend",
2958
+ success: !ctx.dryRun,
2959
+ applicationId: `${run.stack.project}/${app.name}`,
2960
+ imageRef: image?.ref ?? app.ref,
2961
+ ...image?.digest ? { digest: image.digest } : {},
2962
+ url: app.url
2963
+ };
2964
+ }), ...run.stack.workers.map((worker) => {
2965
+ const image = run.images[worker.name];
2966
+ return {
2967
+ appName: worker.name,
2968
+ type: "backend",
2969
+ success: !ctx.dryRun,
2970
+ applicationId: `${run.stack.project}/${worker.name}`,
2971
+ imageRef: image?.ref ?? worker.ref,
2972
+ ...image?.digest ? { digest: image.digest } : {}
2973
+ };
2974
+ })];
2975
+ return {
2976
+ apps,
2977
+ projectId: run.stack.project,
2978
+ successCount: ctx.dryRun ? 0 : apps.length,
2979
+ failedCount: 0,
2980
+ stage: ctx.stage,
2981
+ identity: ctx.identity.key,
2982
+ tag: ctx.tag,
2983
+ dryRun: ctx.dryRun,
2984
+ environmentId: "",
2985
+ skipped: [...ctx.skipped],
2986
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
2987
+ changes: run.changes
2988
+ };
2989
+ }
2990
+ function caFile(run) {
2991
+ return join(run.dir, "caddy-root.crt");
2992
+ }
2993
+ /** The shared edge's compose file, as this machine hands it to compose. */
2994
+ function edgeFile(run) {
2995
+ return join(run.dir, `${EDGE_PROJECT}.yml`);
2996
+ }
2997
+ function applied(ctx, run, change) {
2998
+ const { via, ...rest } = change;
2999
+ run.changes.push(rest);
3000
+ ctx.emit({
3001
+ type: "resource.applied",
3002
+ ...rest,
3003
+ via
3004
+ });
3005
+ }
3006
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
3007
+ async function writeStack(root, dir, stack) {
3008
+ await mkdir(dir, {
3009
+ recursive: true,
3010
+ mode: 448
3011
+ });
3012
+ await chmod(dir, 448);
3013
+ const files = [];
3014
+ const write = async (path, content, mode = 420) => {
3015
+ await mkdir(dirname(path), { recursive: true });
3016
+ await writeFile(path, content, { mode });
3017
+ await chmod(path, mode);
3018
+ files.push(path);
3019
+ };
3020
+ const tls = stack.proxy === "caddy" && stack.tls ? {
3021
+ cert: await readFile(stack.tls.certFile, "utf-8"),
3022
+ key: await readFile(stack.tls.keyFile, "utf-8")
3023
+ } : void 0;
3024
+ const compose = stack.caddyfile !== void 0 ? withCaddyConfigs(stack.compose, {
3025
+ caddyfile: stack.caddyfile,
3026
+ ...tls ? { tls } : {}
3027
+ }) : stack.compose;
3028
+ await write(join(dir, "docker-compose.yml"), composeYaml(stack, compose), tls ? 384 : 420);
3029
+ if (stack.caddyfile !== void 0) {
3030
+ await write(join(dir, "Caddyfile"), stack.caddyfile);
3031
+ await rm(join(dir, "traefik.yml"), { force: true });
3032
+ } else await rm(join(dir, "Caddyfile"), { force: true });
3033
+ if (stack.traefik !== void 0) await write(join(dir, "traefik.yml"), stack.traefik);
3034
+ await rm(join(dir, "tls"), {
3035
+ recursive: true,
3036
+ force: true
3037
+ });
3038
+ for (const app of [...stack.apps, ...stack.workers]) if (app.env) await write(join(dir, `${app.name}.env`), envFile(app.env), 384);
3039
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write(join(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
3040
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write(join(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
3041
+ if (stack.backups) {
3042
+ for (const [name, content] of Object.entries(stack.backups.files)) await write(join(dir, BACKUPS_SERVICE, name), content);
3043
+ if (stack.compose.services["backups"]?.env_file) await write(join(dir, `${BACKUPS_SERVICE}.env`), envFile(stack.backups.env), 384);
3044
+ } else {
3045
+ await rm(join(dir, BACKUPS_SERVICE), {
3046
+ recursive: true,
3047
+ force: true
3048
+ });
3049
+ await rm(join(dir, `${BACKUPS_SERVICE}.env`), { force: true });
3050
+ }
3051
+ for (const entry of await readdir(dir)) if (entry.endsWith(".credentials")) await rm(join(dir, entry));
3052
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write(join(root, path), content);
3053
+ await ensureDockerignore(findBuildRoot(root));
3054
+ return files;
3055
+ }
3056
+ function composeYaml(stack, compose) {
3057
+ const stage = ` --stage ${stack.stage}`;
3058
+ return `# Generated by gkm compose from the construct manifest — do not edit.
3059
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
3060
+ # Each backend and worker reads exactly the keys in its own env file beside
3061
+ # this one.
3062
+ #
3063
+ # gkm compose${stage} start or update it
3064
+ # gkm compose${stage} --down stop it
3065
+ ${stringify(compose, {
3066
+ lineWidth: 0,
3067
+ aliasDuplicateObjects: false
3068
+ })}`;
3069
+ }
3070
+ function printPlan(ctx, run) {
3071
+ const { stack, mode, files } = run;
3072
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
3073
+ if (run.server) ctx.logger.info(` → ${sshTarget(run.server)} (docker over ssh)`);
3074
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
3075
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
3076
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
3077
+ 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}/`);
3078
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${stackDir(stack.stage)}/`);
3079
+ }
3080
+ //#endregion
3081
+ //#region src/target/compose/index.ts
3082
+ /**
3083
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
3084
+ * Caddy — the local stage on the machine that runs the deploy, a deployed
3085
+ * stage on its server's Docker engine, over SSH (`deploy.compose.server`).
3086
+ *
3087
+ * ```bash
3088
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
3089
+ * gkm deploy --target compose --stage production # built from here
3090
+ * gkm deploy --target compose --stage development # the local stage
3091
+ * ```
3092
+ *
3093
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
3094
+ * looked up in the registry — `ImageTagNotFound` before anything changes
3095
+ * - `ready`: a deploy's own checks, after the stage's keys are — the stage's
3096
+ * certificate, its server's address, and every public host's DNS
3097
+ * - `plan`: the stack's files and what a run would create or reuse
3098
+ * - `provision`: generated secrets kept, files written, infrastructure up,
3099
+ * databases, roles, grants and migrations
3100
+ * - `build`: each backend bundled on the host and every image built — or, for
3101
+ * a tag, pulled
3102
+ * - `release`: `up --wait --remove-orphans`, and each app's image, tag and
3103
+ * digest in the stage's state
3104
+ * - `verify`: each app asked through Caddy over HTTPS
3105
+ *
3106
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
3107
+ * every image and pushes it to `deploy.registry`, and does nothing else: no
3108
+ * readiness check runs, so a stage whose keys the deploy has yet to write
3109
+ * still builds.
3110
+ *
3111
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
3112
+ * `--down`), run through the same `deploy()`.
3113
+ */
3114
+ var compose_exports = /* @__PURE__ */ __exportAll({ composeTarget: () => composeTarget });
3115
+ /** The compose target, with its Docker, bundler and probe as given. */
3116
+ function composeTarget(options = {}) {
3117
+ const { mode, push, pin, report, ...given } = options;
3118
+ const deps = {
3119
+ ...defaultDeps,
3120
+ ...given
3121
+ };
3122
+ return defineTarget({
3123
+ name: "compose",
3124
+ runtime: "server",
3125
+ capabilities: {
3126
+ rollback: false,
3127
+ migrations: "target",
3128
+ images: true,
3129
+ localStage: true,
3130
+ selfHostedTelemetry: true
3131
+ },
3132
+ credentials: [],
3133
+ tag: ({ cwd }) => deps.revision(cwd),
3134
+ validate: (ctx) => validateCompose(ctx, deps, {
3135
+ ...mode ? { mode } : {},
3136
+ ...push ? { push } : {},
3137
+ ...pin ? { pin } : {}
3138
+ }),
3139
+ ready: (ctx, run) => readyCompose(ctx, run, deps),
3140
+ plan: (ctx, run) => planCompose(ctx, run),
3141
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
3142
+ build: (ctx, run) => buildCompose(ctx, run, deps),
3143
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
3144
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
3145
+ result: (ctx, run) => {
3146
+ report?.(run);
3147
+ return composeResult(ctx, run);
3148
+ }
3149
+ });
3150
+ }
3151
+ //#endregion
3152
+ export { sshTarget as _, stackOverrideFile as a, composeProject as c, stackPlan as d, EDGE_PROJECT as f, dockerHost as g, composeServer as h, ComposePushNeedsBuild as i, derivedCredentials as l, pinnedRef as m, compose_exports as n, edgeRef as o, parseDigests as p, ComposePinNeedsPull as r, removeEdgeRoutes as s, composeTarget as t, stackDir as u, dockerCompose as v, projectNetwork as y };
3153
+
3154
+ //# sourceMappingURL=compose-BftbEv0b.mjs.map