@geekmidas/cli 10.0.0-alpha.97 → 10.0.0-alpha.99

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