@geekmidas/cli 10.0.0-alpha.92 → 10.0.0-alpha.93

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 (152) hide show
  1. package/dist/{GoDaddyProvider-CJwg2r_9.cjs → GoDaddyProvider-BZb-V14e.cjs} +2 -2
  2. package/dist/{GoDaddyProvider-CJwg2r_9.cjs.map → GoDaddyProvider-BZb-V14e.cjs.map} +1 -1
  3. package/dist/{GoDaddyProvider-BqYGk9XT.mjs → GoDaddyProvider-Mi3vptSR.mjs} +2 -2
  4. package/dist/{GoDaddyProvider-BqYGk9XT.mjs.map → GoDaddyProvider-Mi3vptSR.mjs.map} +1 -1
  5. package/dist/{LegacyStateStore-CeEwayMB.cjs → LegacyStateStore-BlYXQQSE.cjs} +44 -10
  6. package/dist/LegacyStateStore-BlYXQQSE.cjs.map +1 -0
  7. package/dist/LegacyStateStore-CtwO7fwy.mjs +123 -0
  8. package/dist/LegacyStateStore-CtwO7fwy.mjs.map +1 -0
  9. package/dist/{LocalStateStore-Y8XHdoCR.mjs → LocalStateStore-D40_SDmJ.mjs} +2 -2
  10. package/dist/{LocalStateStore-Y8XHdoCR.mjs.map → LocalStateStore-D40_SDmJ.mjs.map} +1 -1
  11. package/dist/{LocalStateStore-BMfseje2.cjs → LocalStateStore-oX_zxj9V.cjs} +2 -2
  12. package/dist/{LocalStateStore-BMfseje2.cjs.map → LocalStateStore-oX_zxj9V.cjs.map} +1 -1
  13. package/dist/{S3StateStore-BfoY4MvD.mjs → S3StateStore-BzS0IeSt.mjs} +2 -2
  14. package/dist/{S3StateStore-BfoY4MvD.mjs.map → S3StateStore-BzS0IeSt.mjs.map} +1 -1
  15. package/dist/{S3StateStore-BmMt2HhW.cjs → S3StateStore-DeI7jtvi.cjs} +2 -2
  16. package/dist/{S3StateStore-BmMt2HhW.cjs.map → S3StateStore-DeI7jtvi.cjs.map} +1 -1
  17. package/dist/{SSMStateStore-D9K62wM4.cjs → SSMStateStore-CaCtrzFL.cjs} +2 -2
  18. package/dist/{SSMStateStore-D9K62wM4.cjs.map → SSMStateStore-CaCtrzFL.cjs.map} +1 -1
  19. package/dist/{SSMStateStore-Bdyw_0Jj.mjs → SSMStateStore-k_Ew7TWx.mjs} +2 -2
  20. package/dist/{SSMStateStore-Bdyw_0Jj.mjs.map → SSMStateStore-k_Ew7TWx.mjs.map} +1 -1
  21. package/dist/{add-2Opn2VVE.mjs → add-CP1podDH.mjs} +2 -3
  22. package/dist/{add-2Opn2VVE.mjs.map → add-CP1podDH.mjs.map} +1 -1
  23. package/dist/{add-oN0b18HN.cjs → add-VcyJnsPX.cjs} +3 -4
  24. package/dist/{add-oN0b18HN.cjs.map → add-VcyJnsPX.cjs.map} +1 -1
  25. package/dist/{bundler-C-AdesaG.mjs → bundler-BWrh-AJH.mjs} +3 -3
  26. package/dist/{bundler-C-AdesaG.mjs.map → bundler-BWrh-AJH.mjs.map} +1 -1
  27. package/dist/{bundler-CXQDrhzN.cjs → bundler-Dfsr6KXU.cjs} +3 -3
  28. package/dist/{bundler-CXQDrhzN.cjs.map → bundler-Dfsr6KXU.cjs.map} +1 -1
  29. package/dist/{cli-BjhaVObS.mjs → cli-B8otnZfX.mjs} +4 -4
  30. package/dist/{cli-BjhaVObS.mjs.map → cli-B8otnZfX.mjs.map} +1 -1
  31. package/dist/{cli-BRZFYvdb.cjs → cli-DL19w4OE.cjs} +2 -2
  32. package/dist/{cli-BRZFYvdb.cjs.map → cli-DL19w4OE.cjs.map} +1 -1
  33. package/dist/compose-BHVKLluX.cjs +1523 -0
  34. package/dist/compose-BHVKLluX.cjs.map +1 -0
  35. package/dist/compose-DrEB_4F-.mjs +1476 -0
  36. package/dist/compose-DrEB_4F-.mjs.map +1 -0
  37. package/dist/{config-BJo8Wggp.d.mts → config-CHX5GOo3.d.mts} +4 -4
  38. package/dist/{config-BJo8Wggp.d.mts.map → config-CHX5GOo3.d.mts.map} +1 -1
  39. package/dist/{config-C9zx7KsX.d.cts → config-DCCcrOSo.d.cts} +4 -4
  40. package/dist/{config-C9zx7KsX.d.cts.map → config-DCCcrOSo.d.cts.map} +1 -1
  41. package/dist/config.d.cts +3 -3
  42. package/dist/config.d.mts +3 -3
  43. package/dist/deploy/public.cjs +6 -5
  44. package/dist/deploy/public.d.cts +6 -6
  45. package/dist/deploy/public.d.cts.map +1 -1
  46. package/dist/deploy/public.d.mts +6 -6
  47. package/dist/deploy/public.d.mts.map +1 -1
  48. package/dist/deploy/public.mjs +6 -6
  49. package/dist/{deploy-6ToUHJmM.cjs → deploy-C3Mhnmus.cjs} +4 -3
  50. package/dist/deploy-C3Mhnmus.cjs.map +1 -0
  51. package/dist/{deploy-yuJHlkY0.mjs → deploy-DYIyIUYd.mjs} +4 -3
  52. package/dist/deploy-DYIyIUYd.mjs.map +1 -0
  53. package/dist/{discover-CRMhvHG9.d.cts → discover-DqwlBVyY.d.mts} +2 -2
  54. package/dist/{discover-CRMhvHG9.d.cts.map → discover-DqwlBVyY.d.mts.map} +1 -1
  55. package/dist/{discover-G76EQ4vY.d.mts → discover-vk2r5giK.d.cts} +2 -2
  56. package/dist/{discover-G76EQ4vY.d.mts.map → discover-vk2r5giK.d.cts.map} +1 -1
  57. package/dist/{dokploy-BvbJ_A4Q.mjs → dokploy-o4I6vb9W.mjs} +2 -2
  58. package/dist/{dokploy-BvbJ_A4Q.mjs.map → dokploy-o4I6vb9W.mjs.map} +1 -1
  59. package/dist/{dokploy-Bvvfj2qe.cjs → dokploy-rivb1RFt.cjs} +2 -2
  60. package/dist/{dokploy-Bvvfj2qe.cjs.map → dokploy-rivb1RFt.cjs.map} +1 -1
  61. package/dist/{encryption-C9Jm9dfn.mjs → encryption-B6ilrT7p.mjs} +2 -2
  62. package/dist/{encryption-C9Jm9dfn.mjs.map → encryption-B6ilrT7p.mjs.map} +1 -1
  63. package/dist/{encryption-CgW167LO.cjs → encryption-D7zmwzWz.cjs} +2 -2
  64. package/dist/{encryption-CgW167LO.cjs.map → encryption-D7zmwzWz.cjs.map} +1 -1
  65. package/dist/{engine-Dj7ZKO8H.cjs → engine-Cfx8fEZU.cjs} +6 -5
  66. package/dist/engine-Cfx8fEZU.cjs.map +1 -0
  67. package/dist/{engine-C8Ye9MUm.mjs → engine-DjEcovm-.mjs} +6 -5
  68. package/dist/engine-DjEcovm-.mjs.map +1 -0
  69. package/dist/{github-B1k42hIt.mjs → github-CzBbs43W.mjs} +2 -2
  70. package/dist/{github-B1k42hIt.mjs.map → github-CzBbs43W.mjs.map} +1 -1
  71. package/dist/{github-BD051KZZ.cjs → github-zneTMvnO.cjs} +2 -2
  72. package/dist/{github-BD051KZZ.cjs.map → github-zneTMvnO.cjs.map} +1 -1
  73. package/dist/{index-D1pHwqkK.d.mts → index-BiYU7cUl.d.mts} +2 -2
  74. package/dist/{index-B5uuwx-Y.d.cts.map → index-BiYU7cUl.d.mts.map} +1 -1
  75. package/dist/{index-B5uuwx-Y.d.cts → index-Dm6V9bwh.d.cts} +2 -2
  76. package/dist/{index-D1pHwqkK.d.mts.map → index-Dm6V9bwh.d.cts.map} +1 -1
  77. package/dist/index.cjs +143 -184
  78. package/dist/index.cjs.map +1 -1
  79. package/dist/index.mjs +141 -181
  80. package/dist/index.mjs.map +1 -1
  81. package/dist/{migrate-IZsYyZ5F.mjs → migrate-BaC4w0sb.mjs} +2 -2
  82. package/dist/{migrate-IZsYyZ5F.mjs.map → migrate-BaC4w0sb.mjs.map} +1 -1
  83. package/dist/{migrate-D3VVsiHp.cjs → migrate-C8wTpakT.cjs} +2 -2
  84. package/dist/{migrate-D3VVsiHp.cjs.map → migrate-C8wTpakT.cjs.map} +1 -1
  85. package/dist/{migrate-BSbZ7-9n.mjs → migrate-CsBZKALY.mjs} +3 -3
  86. package/dist/{migrate-BSbZ7-9n.mjs.map → migrate-CsBZKALY.mjs.map} +1 -1
  87. package/dist/{migrate-f6JDjyCp.cjs → migrate-DFjbGnSr.cjs} +2 -2
  88. package/dist/{migrate-f6JDjyCp.cjs.map → migrate-DFjbGnSr.cjs.map} +1 -1
  89. package/dist/openapi.d.cts +1 -1
  90. package/dist/openapi.d.mts +1 -1
  91. package/dist/reconcile/public.d.cts +2 -2
  92. package/dist/reconcile/public.d.mts +2 -2
  93. package/dist/{reconcile-Dh1Jk7WE.mjs → reconcile--I7V4Klj.mjs} +2 -2
  94. package/dist/{reconcile-Dh1Jk7WE.mjs.map → reconcile--I7V4Klj.mjs.map} +1 -1
  95. package/dist/{resolve-Be4bF1w4.mjs → resolve-Ccjlpnd9.mjs} +3 -3
  96. package/dist/{resolve-Be4bF1w4.mjs.map → resolve-Ccjlpnd9.mjs.map} +1 -1
  97. package/dist/{resolve-DUp65SnJ.cjs → resolve-g8htuR80.cjs} +3 -3
  98. package/dist/{resolve-DUp65SnJ.cjs.map → resolve-g8htuR80.cjs.map} +1 -1
  99. package/dist/{rollback-DDHtd0GJ.cjs → rollback--ympG9ss.cjs} +5 -4
  100. package/dist/rollback--ympG9ss.cjs.map +1 -0
  101. package/dist/{rollback-D1d-fW0r.mjs → rollback-Drbg0OeR.mjs} +5 -4
  102. package/dist/rollback-Drbg0OeR.mjs.map +1 -0
  103. package/dist/{runtime-Es1V4e9M.d.mts → runtime-D_J3ExJn.d.cts} +2 -2
  104. package/dist/{runtime-DDrHlYe5.d.cts.map → runtime-D_J3ExJn.d.cts.map} +1 -1
  105. package/dist/{runtime-DDrHlYe5.d.cts → runtime-_wEVtshH.d.mts} +2 -2
  106. package/dist/{runtime-Es1V4e9M.d.mts.map → runtime-_wEVtshH.d.mts.map} +1 -1
  107. package/dist/{sandbox-C3WsTa5m.d.mts → sandbox-CPJq1Kia.d.mts} +2 -2
  108. package/dist/{sandbox-C3WsTa5m.d.mts.map → sandbox-CPJq1Kia.d.mts.map} +1 -1
  109. package/dist/{sandbox-MaxSeU92.d.cts → sandbox-JwuPAl7I.d.cts} +2 -2
  110. package/dist/{sandbox-MaxSeU92.d.cts.map → sandbox-JwuPAl7I.d.cts.map} +1 -1
  111. package/dist/secrets-DJteijZo.cjs +47 -0
  112. package/dist/secrets-DJteijZo.cjs.map +1 -0
  113. package/dist/secrets-DbPmAS4k.mjs +36 -0
  114. package/dist/secrets-DbPmAS4k.mjs.map +1 -0
  115. package/dist/{seeds-CvGQJnPO.mjs → seeds-BSL55F6q.mjs} +897 -59
  116. package/dist/seeds-BSL55F6q.mjs.map +1 -0
  117. package/dist/{seeds-BKoJYsE7.cjs → seeds-c-ByX9je.cjs} +1014 -80
  118. package/dist/seeds-c-ByX9je.cjs.map +1 -0
  119. package/dist/stack-1PeLJS2j.cjs +1346 -0
  120. package/dist/stack-1PeLJS2j.cjs.map +1 -0
  121. package/dist/stack-Co4uZkAo.mjs +1239 -0
  122. package/dist/stack-Co4uZkAo.mjs.map +1 -0
  123. package/dist/target/public.cjs +1 -1
  124. package/dist/target/public.d.cts +2 -2
  125. package/dist/target/public.d.mts +2 -2
  126. package/dist/target/public.mjs +1 -1
  127. package/dist/{terminal-Dtd6BZX9.mjs → terminal-C4XRdwnU.mjs} +2 -2
  128. package/dist/{terminal-Dtd6BZX9.mjs.map → terminal-C4XRdwnU.mjs.map} +1 -1
  129. package/dist/{types-Bk9st2cd.d.cts → types-B6lmD3en.d.mts} +77 -26
  130. package/dist/types-B6lmD3en.d.mts.map +1 -0
  131. package/dist/{types-B3Gqs175.d.mts → types-BibpiHKB.d.cts} +78 -25
  132. package/dist/types-BibpiHKB.d.cts.map +1 -0
  133. package/dist/workspace/index.d.cts +2 -2
  134. package/dist/workspace/index.d.mts +2 -2
  135. package/package.json +15 -15
  136. package/dist/LegacyStateStore-CeEwayMB.cjs.map +0 -1
  137. package/dist/LegacyStateStore-DdJ1bCRV.mjs +0 -89
  138. package/dist/LegacyStateStore-DdJ1bCRV.mjs.map +0 -1
  139. package/dist/compose-CTdVeeVk.mjs +0 -3151
  140. package/dist/compose-CTdVeeVk.mjs.map +0 -1
  141. package/dist/compose-fnYmPk_c.cjs +0 -3276
  142. package/dist/compose-fnYmPk_c.cjs.map +0 -1
  143. package/dist/deploy-6ToUHJmM.cjs.map +0 -1
  144. package/dist/deploy-yuJHlkY0.mjs.map +0 -1
  145. package/dist/engine-C8Ye9MUm.mjs.map +0 -1
  146. package/dist/engine-Dj7ZKO8H.cjs.map +0 -1
  147. package/dist/rollback-D1d-fW0r.mjs.map +0 -1
  148. package/dist/rollback-DDHtd0GJ.cjs.map +0 -1
  149. package/dist/seeds-BKoJYsE7.cjs.map +0 -1
  150. package/dist/seeds-CvGQJnPO.mjs.map +0 -1
  151. package/dist/types-B3Gqs175.d.mts.map +0 -1
  152. package/dist/types-Bk9st2cd.d.cts.map +0 -1
@@ -0,0 +1,1476 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
3
+ import { c as runOutput, s as run, x as gkmHome } from "./credentials-C4KII3PD.mjs";
4
+ import { r as discover } from "./discover-qjFapetL.mjs";
5
+ import { it as SERVER_IPV4_KEY, tt as ComposeTlsFileMissing } from "./workspace-Bzw7Zs82.mjs";
6
+ import { t as defineTarget } from "./define-6poNqm5O.mjs";
7
+ import { $t as bucketClient, C as HostNotPointingAtServer, D as serverAddressHint, Dt as constructGlobs, E as requiredServerAddress, Gt as applyPolicies, It as REDIS_SERVICE, Kt as applyPostgres, L as recordRelease, Ln as primaryPortKey, Mt as loadLocalCredentials, N as createComposeState, O as stackHosts, Qt as ensurePostgresLogin, T as isLocalHost, Wt as applyBuckets, Yt as postgresStatements, Zt as LEGACY_LOCAL_LOGIN, an as envFor, cn as imageLayout, en as pgClient, fn as findBuildRoot, gr as logsAccess, gt as reportDevServices, hr as LOGS_SERVICE, i as assertNoStaleSecrets, ir as imageRef, it as currentActor, k as systemLookup, n as reportDatabaseRuns, o as verifyStageProviders, r as reportPlannedSeeds, t as DeploySeedsFailed, u as DeployJournal, w as checkStackDns, y as ensureDockerignore } from "./seeds-BSL55F6q.mjs";
8
+ import { i as installedFrom } from "./drivers-CTaWrA_L.mjs";
9
+ import { _ as edgeComposeFile, a as composeStack, f as pinImages, g as EDGE_SERVICE, h as EDGE_PROJECT, i as composeProject, l as RegistryRequired, m as EDGE_NETWORK, n as LOGS_PORT_ENV, o as envFile, r as LOG_ROTATION, s as stackDir, t as EDGE_PORT_ENV, u as assertImagesExist, v as traefikStaticFile } from "./stack-Co4uZkAo.mjs";
10
+ import { t as deployedStackSecrets } from "./secrets-DbPmAS4k.mjs";
11
+ import { f as plannedSeeds, o as SeedFailed, p as seedDatabases, u as migrateDatabases } from "./databases-BeGP5eDh.mjs";
12
+ import { n as assertStageCredentials } from "./credentialSchemas-BJFvfkaz.mjs";
13
+ import { dirname, join } from "node:path";
14
+ import { existsSync } from "node:fs";
15
+ import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
16
+ import { hostname, userInfo } from "node:os";
17
+ import { spawn } from "node:child_process";
18
+ import { stringify } from "yaml";
19
+ import { request } from "node:https";
20
+ //#region src/compose/docker.ts
21
+ /**
22
+ * The Docker operations `gkm compose` needs, behind an interface.
23
+ *
24
+ * Small on purpose, like reconcile's: the rules about *when* each runs — the
25
+ * registry is asked before anything is pulled, nothing is started for a tag
26
+ * that is missing — are asserted against a fake, and this file is only the
27
+ * wiring to the real CLI.
28
+ *
29
+ * Every call is an argument array. Image refs, tags and paths come from the
30
+ * workspace, and none of them reaches a shell.
31
+ */
32
+ /** `output` as `spawn` reads it. */
33
+ const STDIO = {
34
+ inherit: "inherit",
35
+ stderr: [
36
+ "ignore",
37
+ 2,
38
+ 2
39
+ ],
40
+ ignore: "ignore"
41
+ };
42
+ /** How a stack's docker commands run: where it is, where output goes. */
43
+ function runOptions(stack, env) {
44
+ return {
45
+ cwd: stack.cwd,
46
+ stdio: STDIO[stack.output ?? "inherit"],
47
+ ...env ? { env } : {},
48
+ ...stack.signal ? { signal: stack.signal } : {}
49
+ };
50
+ }
51
+ /**
52
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
53
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
54
+ */
55
+ function publishedPorts(column) {
56
+ const ports = /* @__PURE__ */ new Set();
57
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
58
+ const first = Number(match[1]);
59
+ const last = match[2] ? Number(match[2]) : first;
60
+ for (let port = first; port <= last; port++) ports.add(port);
61
+ }
62
+ return [...ports];
63
+ }
64
+ /** Each line `docker ps` printed, as the containers holding `port`. */
65
+ function portHolders(output, port) {
66
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
67
+ container,
68
+ ...project ? { project } : {},
69
+ ...service ? { service } : {}
70
+ }));
71
+ }
72
+ /** How long a stack has to pass its health checks. */
73
+ const WAIT_TIMEOUT_S = 180;
74
+ /** `docker compose port` printed nothing a port can be read from. */
75
+ var ServicePortUnknown = class extends GkmError {
76
+ service;
77
+ inside;
78
+ output;
79
+ constructor(service, inside, output) {
80
+ super(`'${service}' publishes no host port for ${inside} (docker said: ${output.trim() || "nothing"}). Is it running? \`docker compose ps\` shows the stack.`);
81
+ this.service = service;
82
+ this.inside = inside;
83
+ this.output = output;
84
+ this.name = "ServicePortUnknown";
85
+ }
86
+ };
87
+ /**
88
+ * Whether `ref` names a registry on this machine's loopback — which the
89
+ * daemon pulls from and pushes to over plain HTTP by default, and `docker
90
+ * manifest inspect` reaches only when told `--insecure` (without it, a local
91
+ * registry's image is reported as no such manifest).
92
+ */
93
+ function isLoopbackRegistry(ref) {
94
+ const first = ref.split("/")[0];
95
+ if (!ref.includes("/") || !/[.:]|^localhost$/.test(first)) return false;
96
+ const host = first.replace(/:\d+$/, "");
97
+ return host === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(host);
98
+ }
99
+ /** `docker push` finished without saying what digest the registry stored. */
100
+ var PushDigestUnknown = class extends GkmError {
101
+ ref;
102
+ output;
103
+ constructor(ref, output) {
104
+ 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}\`.`);
105
+ this.ref = ref;
106
+ this.output = output;
107
+ this.name = "PushDigestUnknown";
108
+ }
109
+ };
110
+ /** The digest `docker push` reports last: `<tag>: digest: sha256:… size: …`. */
111
+ function pushedDigest(output) {
112
+ return [...output.matchAll(/digest: (sha256:[0-9a-f]{64})/g)].at(-1)?.[1];
113
+ }
114
+ function compose(stack, args) {
115
+ return [
116
+ "compose",
117
+ "-p",
118
+ stack.project,
119
+ "-f",
120
+ stack.file,
121
+ ...(stack.overrides ?? []).flatMap((file) => ["-f", file]),
122
+ ...args
123
+ ];
124
+ }
125
+ /** Run a program and keep everything it said, whatever it exits with. */
126
+ function capture(command, args, timeoutMs = 6e4) {
127
+ return new Promise((resolve, reject) => {
128
+ const child = spawn(command, [...args], {
129
+ stdio: [
130
+ "ignore",
131
+ "pipe",
132
+ "pipe"
133
+ ],
134
+ shell: false
135
+ });
136
+ let stdout = "";
137
+ let stderr = "";
138
+ child.stdout.on("data", (chunk) => {
139
+ stdout += chunk.toString();
140
+ });
141
+ child.stderr.on("data", (chunk) => {
142
+ stderr += chunk.toString();
143
+ });
144
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
145
+ timer.unref?.();
146
+ child.on("error", (error) => {
147
+ clearTimeout(timer);
148
+ reject(error);
149
+ });
150
+ child.on("close", (code) => {
151
+ clearTimeout(timer);
152
+ resolve({
153
+ code,
154
+ stdout,
155
+ stderr
156
+ });
157
+ });
158
+ });
159
+ }
160
+ /**
161
+ * Whether a failed `docker manifest inspect` means the tag is not there, as
162
+ * opposed to the registry not answering.
163
+ *
164
+ * Read off the message because that is all the CLI gives. Anything not
165
+ * recognisably "no such tag" is treated as the registry being unreachable:
166
+ * a registry that refused credentials must not be reported as a tag that was
167
+ * never pushed, or the fix offered would be the wrong one.
168
+ */
169
+ function isMissingManifest(output) {
170
+ return /no such manifest|manifest unknown|manifest for .* not found|not found: manifest/i.test(output);
171
+ }
172
+ const dockerCompose = {
173
+ async lookup(ref) {
174
+ const { code, stdout, stderr } = await capture("docker", [
175
+ "manifest",
176
+ "inspect",
177
+ ...isLoopbackRegistry(ref) ? ["--insecure"] : [],
178
+ ref
179
+ ]);
180
+ if (code === 0) return {
181
+ ref,
182
+ status: "found"
183
+ };
184
+ const output = `${stderr}\n${stdout}`.trim();
185
+ return isMissingManifest(output) ? {
186
+ ref,
187
+ status: "missing"
188
+ } : {
189
+ ref,
190
+ status: "unreachable",
191
+ detail: output
192
+ };
193
+ },
194
+ async build(stack, services) {
195
+ await run("docker", compose(stack, ["build", ...services]), runOptions(stack, {
196
+ ...process.env,
197
+ DOCKER_BUILDKIT: "1"
198
+ }));
199
+ },
200
+ async pull(stack, services) {
201
+ await run("docker", compose(stack, ["pull", ...services]), runOptions(stack));
202
+ },
203
+ async up(stack, services) {
204
+ await run("docker", compose(stack, [
205
+ "up",
206
+ "-d",
207
+ "--wait",
208
+ `--wait-timeout=${WAIT_TIMEOUT_S}`,
209
+ ...services ? [] : ["--remove-orphans"],
210
+ ...services ?? []
211
+ ]), runOptions(stack));
212
+ },
213
+ async down(stack) {
214
+ await run("docker", compose(stack, ["down"]), runOptions(stack));
215
+ },
216
+ async port(stack, service, inside) {
217
+ const output = await runOutput("docker", compose(stack, [
218
+ "port",
219
+ service,
220
+ String(inside)
221
+ ]), {
222
+ cwd: stack.cwd,
223
+ ...stack.signal ? { signal: stack.signal } : {}
224
+ });
225
+ const port = Number(output.trim().split(":").pop());
226
+ if (!Number.isInteger(port) || port <= 0) throw new ServicePortUnknown(service, inside, output);
227
+ return port;
228
+ },
229
+ async health(stack, service) {
230
+ const { code, stdout } = await capture("docker", [...compose(stack, [
231
+ "ps",
232
+ "--format",
233
+ "{{.Health}}",
234
+ service
235
+ ])]);
236
+ if (code !== 0) return void 0;
237
+ return stdout.trim().split("\n")[0] || void 0;
238
+ },
239
+ async copyOut(stack, service, from, to) {
240
+ await mkdir(dirname(to), { recursive: true });
241
+ await run("docker", compose(stack, [
242
+ "cp",
243
+ `${service}:${from}`,
244
+ to
245
+ ]), runOptions(stack));
246
+ },
247
+ async push(stack, ref) {
248
+ const output = await runOutput("docker", ["push", ref], {
249
+ cwd: stack.cwd,
250
+ ...stack.signal ? { signal: stack.signal } : {}
251
+ });
252
+ const digest = pushedDigest(output);
253
+ if (!digest) throw new PushDigestUnknown(ref, output);
254
+ return digest;
255
+ },
256
+ async digest(ref) {
257
+ const { code, stdout } = await capture("docker", [
258
+ "image",
259
+ "inspect",
260
+ "--format={{json .RepoDigests}} {{.Id}}",
261
+ ref
262
+ ]);
263
+ if (code !== 0) return void 0;
264
+ const [json = "[]", id] = stdout.trim().split(" ");
265
+ const repository = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
266
+ try {
267
+ const digests = JSON.parse(json);
268
+ const match = Array.isArray(digests) ? digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`)) : void 0;
269
+ if (match) return match.slice(repository.length + 1);
270
+ } catch {}
271
+ return id || void 0;
272
+ },
273
+ async ensureNetwork(name) {
274
+ const { code } = await capture("docker", [
275
+ "network",
276
+ "inspect",
277
+ name
278
+ ]);
279
+ if (code === 0) return;
280
+ const created = await capture("docker", [
281
+ "network",
282
+ "create",
283
+ name
284
+ ]);
285
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
286
+ },
287
+ async publishers(port) {
288
+ const { stdout } = await capture("docker", [
289
+ "ps",
290
+ "--format",
291
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
292
+ ]);
293
+ return portHolders(stdout, port);
294
+ }
295
+ };
296
+ /** `docker network create` failed. */
297
+ var NetworkCreateFailed = class extends Error {
298
+ network;
299
+ output;
300
+ constructor(network, output) {
301
+ 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.`);
302
+ this.network = network;
303
+ this.output = output;
304
+ this.name = "NetworkCreateFailed";
305
+ }
306
+ };
307
+ //#endregion
308
+ //#region src/compose/edge.ts
309
+ /**
310
+ * The server's shared Traefik edge, on disk and in Docker: started when a
311
+ * stack needs it, and each stack's routes written to — and removed from —
312
+ * the directory it watches.
313
+ *
314
+ * The edge lives in the deploy user's gkm home (`$GKM_HOME/edge`, else
315
+ * `~/.gkm/edge`): the user who runs `gkm compose` owns it, so nothing needs
316
+ * root, and it sits beside the stage keys that same user already keeps.
317
+ *
318
+ * ~/.gkm/edge/
319
+ * docker-compose.yml the edge's compose project (gkm-edge)
320
+ * traefik.yml its static configuration
321
+ * dynamic/<project>.yml one per stack: its routers, services, middlewares
322
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
323
+ */
324
+ /** The edge's directory on this machine. */
325
+ function edgeDir(env = process.env) {
326
+ return join(gkmHome(env), "edge");
327
+ }
328
+ /** The edge's compose project, as docker is asked about it. */
329
+ function edgeRef(dir, options = {}) {
330
+ return {
331
+ project: EDGE_PROJECT,
332
+ file: join(dir, "docker-compose.yml"),
333
+ cwd: dir,
334
+ ...options
335
+ };
336
+ }
337
+ /**
338
+ * Something other than the proxy a stack is set to holds the edge's ports.
339
+ *
340
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
341
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
342
+ * edge, or another stack's Caddy. Refused before anything is started, so the
343
+ * stack is never left half on one proxy and half on the other.
344
+ */
345
+ var ComposeProxyClash = class extends GkmError {
346
+ project;
347
+ proxy;
348
+ port;
349
+ holder;
350
+ constructor(project, proxy, port, holder) {
351
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
352
+ 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.`;
353
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
354
+ this.project = project;
355
+ this.proxy = proxy;
356
+ this.port = port;
357
+ this.holder = holder;
358
+ this.name = "ComposeProxyClash";
359
+ }
360
+ };
361
+ /**
362
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
363
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
364
+ */
365
+ async function assertEdgePorts(docker, options) {
366
+ const { project, proxy, ports } = options;
367
+ for (const port of [ports.https, ports.http]) for (const holder of await docker.publishers(port)) if (!(proxy === "traefik" ? holder.project === "gkm-edge" : holder.project === project && holder.service === "caddy")) throw new ComposeProxyClash(project, proxy, port, holder);
368
+ }
369
+ /** Write a file whole or not at all: a temporary file, then a rename. */
370
+ async function writeAtomic(path, content, mode = 420) {
371
+ const temporary = `${path}.${process.pid}.tmp`;
372
+ await writeFile(temporary, content, { mode });
373
+ await chmod(temporary, mode);
374
+ await rename(temporary, path);
375
+ }
376
+ /** Write a file only when its content changed; whether it did. */
377
+ async function writeIfChanged(path, content) {
378
+ if (await readFile(path, "utf-8").catch(() => void 0) === content) return false;
379
+ await writeAtomic(path, content);
380
+ return true;
381
+ }
382
+ /**
383
+ * The edge, up: its network, its files, and its container — started when it
384
+ * is not running, and recreated when its configuration changed. Idempotent:
385
+ * on a server where it already runs as configured, `up` changes nothing.
386
+ */
387
+ async function ensureEdge(docker, options) {
388
+ const { dir, ports } = options;
389
+ await mkdir(join(dir, "dynamic"), { recursive: true });
390
+ await mkdir(join(dir, "certs"), {
391
+ recursive: true,
392
+ mode: 448
393
+ });
394
+ const staticConfig = traefikStaticFile(ports);
395
+ await writeIfChanged(join(dir, "traefik.yml"), staticConfig);
396
+ await writeIfChanged(join(dir, "docker-compose.yml"), edgeComposeFile({
397
+ dir,
398
+ ports,
399
+ staticConfig,
400
+ logging: options.logging
401
+ }));
402
+ await docker.ensureNetwork(EDGE_NETWORK);
403
+ await docker.up(edgeRef(dir, {
404
+ ...options.output ? { output: options.output } : {},
405
+ ...options.signal ? { signal: options.signal } : {}
406
+ }), [EDGE_SERVICE]);
407
+ return [join(dir, "traefik.yml"), join(dir, "docker-compose.yml")];
408
+ }
409
+ /** A stack's file in the edge's directory. */
410
+ function routesFile(dir, project) {
411
+ return join(dir, "dynamic", `${project}.yml`);
412
+ }
413
+ /**
414
+ * Register a stack with the edge: its certificate first, where it has one,
415
+ * so the routes that need it never load without it — then its routes, in one
416
+ * rename the edge picks up whole.
417
+ */
418
+ async function writeEdgeRoutes(dir, project, routes, certificate) {
419
+ const files = [];
420
+ if (certificate) {
421
+ const certs = join(dir, "certs");
422
+ await mkdir(certs, {
423
+ recursive: true,
424
+ mode: 448
425
+ });
426
+ const crt = join(certs, `${project}.crt`);
427
+ const key = join(certs, `${project}.key`);
428
+ await copyFile(certificate.certFile, `${crt}.tmp`);
429
+ await rename(`${crt}.tmp`, crt);
430
+ await copyFile(certificate.keyFile, `${key}.tmp`);
431
+ await chmod(`${key}.tmp`, 384);
432
+ await rename(`${key}.tmp`, key);
433
+ files.push(crt, key);
434
+ } else await removeCertificate(dir, project);
435
+ await mkdir(join(dir, "dynamic"), { recursive: true });
436
+ const file = routesFile(dir, project);
437
+ await writeAtomic(file, routes);
438
+ files.push(file);
439
+ return files;
440
+ }
441
+ /** What a stack's file holds for the moment between emptying and removal. */
442
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
443
+ async function removeCertificate(dir, project) {
444
+ for (const ext of ["crt", "key"]) await rm(join(dir, "certs", `${project}.${ext}`), { force: true });
445
+ }
446
+ /**
447
+ * Unregister a stack: its routes, then its certificate. Whether there was
448
+ * anything to remove.
449
+ */
450
+ async function removeEdgeRoutes(dir, project) {
451
+ const file = routesFile(dir, project);
452
+ const existed = existsSync(file);
453
+ if (existed) await writeAtomic(file, UNREGISTERED);
454
+ await rm(file, { force: true });
455
+ await removeCertificate(dir, project);
456
+ return existed;
457
+ }
458
+ //#endregion
459
+ //#region src/target/compose/health.ts
460
+ /**
461
+ * Asking each app of a stack whether it answers — through Caddy, over HTTPS,
462
+ * the way a browser reaches it.
463
+ *
464
+ * `docker compose up --wait` already knows each container passed its own
465
+ * health check, asked on 127.0.0.1 inside it. What that cannot say is whether
466
+ * the stack is reachable: whether the edge routes the host to the app, and
467
+ * whether the certificate it presents is one a client accepts. So the check
468
+ * goes through the edge, by hostname, and verifies the certificate.
469
+ */
470
+ /** A request that got no answer in time. */
471
+ var HealthRequestTimedOut = class extends GkmError {
472
+ url;
473
+ timeoutMs;
474
+ constructor(url, timeoutMs) {
475
+ super(`${url} did not answer within ${timeoutMs}ms. Check the stack is up with \`docker compose ps\`.`);
476
+ this.url = url;
477
+ this.timeoutMs = timeoutMs;
478
+ this.name = "HealthRequestTimedOut";
479
+ }
480
+ };
481
+ /** The real probe: one HTTPS GET, the certificate verified. */
482
+ const httpsProbe = ({ url, ca, connectTo, connectPort, timeoutMs, signal }) => {
483
+ const target = new URL(url);
484
+ return new Promise((resolve, reject) => {
485
+ const req = request({
486
+ host: connectTo ?? target.hostname,
487
+ port: connectPort ?? (target.port || 443),
488
+ servername: target.hostname,
489
+ path: `${target.pathname}${target.search}`,
490
+ method: "GET",
491
+ headers: { host: target.host },
492
+ ...ca ? { ca } : {},
493
+ ...signal ? { signal } : {},
494
+ timeout: timeoutMs
495
+ }, (res) => {
496
+ res.resume();
497
+ res.on("end", () => resolve(res.statusCode ?? 0));
498
+ res.on("error", reject);
499
+ });
500
+ req.on("timeout", () => req.destroy(new HealthRequestTimedOut(url, timeoutMs)));
501
+ req.on("error", reject);
502
+ req.end();
503
+ });
504
+ };
505
+ /** Whether a status means the app answered as it should. */
506
+ function isHealthy(status) {
507
+ return status >= 200 && status < 400;
508
+ }
509
+ /** Apps that did not answer through the edge. */
510
+ var ComposeAppsUnhealthy = class extends GkmError {
511
+ project;
512
+ apps;
513
+ proxy;
514
+ constructor(project, apps, proxy = "caddy") {
515
+ const names = apps.map((a) => a.app).join(" ");
516
+ 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}\`.`));
517
+ this.project = project;
518
+ this.apps = apps;
519
+ this.proxy = proxy;
520
+ this.name = "ComposeAppsUnhealthy";
521
+ }
522
+ };
523
+ //#endregion
524
+ //#region src/target/compose/phases.ts
525
+ /**
526
+ * The compose target's phases: a stage as one Docker Compose stack behind
527
+ * Caddy, on the machine the deploy runs on.
528
+ *
529
+ * The order is the point of this file, and the rules it keeps are these:
530
+ *
531
+ * - A tag is checked before anything happens (`validate`). Every app's image
532
+ * is asked of the registry first; one missing image stops the run naming
533
+ * them all, and nothing is written, pulled or started.
534
+ * - The databases exist before the apps do (`provision`). Postgres comes up
535
+ * alone, its databases, roles and grants are created, its migrations
536
+ * applied and its seeds run from this machine, and only then do the apps
537
+ * start — so an app
538
+ * never boots against a schema that is not there yet.
539
+ * - What a stage runs is recorded (`release`). Each app's image, the tag it
540
+ * was released under and the digest it resolved to are written to the
541
+ * stage's state, so "what is this stage running" has an exact answer.
542
+ * - What was started answers (`verify`): each app is asked through Caddy,
543
+ * over HTTPS, with the certificate verified.
544
+ *
545
+ * Every image is built inside Docker from a pruned slice of the build root —
546
+ * the same Dockerfiles `gkm docker` writes — so nothing is built on this
547
+ * machine before `docker compose build`.
548
+ *
549
+ * Docker, the registry, Postgres and the health probe are
550
+ * injected, so the rules are asserted without a daemon; the defaults are the
551
+ * real ones.
552
+ */
553
+ /** `--push` without `--build`: there is nothing built here to push. */
554
+ var ComposePushNeedsBuild = class extends GkmError {
555
+ constructor() {
556
+ super("--push pushes the images this checkout builds, so it needs --build (and never --pull): gkm compose --stage <stage> --build --push --tag <tag>.");
557
+ this.name = "ComposePushNeedsBuild";
558
+ }
559
+ };
560
+ /** Digests to run by, on a run that pulls nothing. */
561
+ var ComposePinNeedsPull = class extends GkmError {
562
+ constructor() {
563
+ 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.");
564
+ this.name = "ComposePinNeedsPull";
565
+ }
566
+ };
567
+ /** A port variable that does not hold a port. */
568
+ var EdgePortInvalid = class extends GkmError {
569
+ variable;
570
+ value;
571
+ constructor(variable, value) {
572
+ super(`${variable}=${value} is not a port. Set it to a number between 1 and 65535, or unset it for the default.`);
573
+ this.variable = variable;
574
+ this.value = value;
575
+ this.name = "EdgePortInvalid";
576
+ }
577
+ };
578
+ /** A build with no commit to tag its images with. */
579
+ var NoGitRevision = class extends GkmError {
580
+ root;
581
+ constructor(root) {
582
+ 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.`);
583
+ this.root = root;
584
+ this.name = "NoGitRevision";
585
+ }
586
+ };
587
+ /**
588
+ * The project's own file merged over a stage's stack: `docker-compose.<stage>.yml`
589
+ * at the workspace root. What the generated file cannot know — a port bound
590
+ * to a tailnet address, another log driver — goes there, and is never
591
+ * overwritten.
592
+ */
593
+ function stackOverrideFile(root, stage) {
594
+ return join(root, `docker-compose.${stage}.yml`);
595
+ }
596
+ /** The commit HEAD is at, short — and `-dirty` when the tree has changes. */
597
+ async function gitRevision(root) {
598
+ let sha;
599
+ try {
600
+ sha = (await runOutput("git", [
601
+ "rev-parse",
602
+ "--short",
603
+ "HEAD"
604
+ ], { cwd: root })).trim();
605
+ } catch {
606
+ throw new NoGitRevision(root);
607
+ }
608
+ if (!sha) throw new NoGitRevision(root);
609
+ return (await runOutput("git", ["status", "--porcelain"], { cwd: root }).catch(() => "")).trim() ? `${sha}-dirty` : sha;
610
+ }
611
+ /** The edge's ports, from the environment — 443 and 80 when unset. */
612
+ function edgePorts(env = process.env) {
613
+ const read = (variable, fallback) => {
614
+ const value = env[variable];
615
+ if (value === void 0 || value === "") return fallback;
616
+ const port = Number(value);
617
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new EdgePortInvalid(variable, value);
618
+ return port;
619
+ };
620
+ const logs = env["GKM_COMPOSE_LOGS_PORT"] ? read(LOGS_PORT_ENV, 0) : void 0;
621
+ return {
622
+ https: read(EDGE_PORT_ENV.https, 443),
623
+ http: read(EDGE_PORT_ENV.http, 80),
624
+ ...logs ? { logs } : {}
625
+ };
626
+ }
627
+ /**
628
+ * The real ones. Each app is asked for three minutes before it counts as
629
+ * down: a deployed stage's first ACME certificate can take that long.
630
+ */
631
+ const defaultDeps = {
632
+ docker: dockerCompose,
633
+ revision: gitRevision,
634
+ sql: pgClient,
635
+ buckets: bucketClient,
636
+ logins: ensurePostgresLogin,
637
+ migrate: migrateDatabases,
638
+ seed: seedDatabases,
639
+ probe: httpsProbe,
640
+ healthAttempts: 90,
641
+ healthIntervalMs: 2e3,
642
+ env: process.env,
643
+ lookup: systemLookup
644
+ };
645
+ /**
646
+ * The stack the stage would run, and — for a tag — the registry's word that
647
+ * every image it names exists. Nothing is written: a missing image stops the
648
+ * run here, before a file, a secret or a container is touched.
649
+ */
650
+ async function validateCompose(ctx, deps, options = {}) {
651
+ const { workspace, stage, identity, tag } = ctx;
652
+ const root = workspace.root;
653
+ const mode = options.mode ?? (ctx.tagGiven ? "pull" : "build");
654
+ const push = options.push === true;
655
+ if (push && mode !== "build") throw new ComposePushNeedsBuild();
656
+ if (options.pin && mode !== "pull") throw new ComposePinNeedsPull();
657
+ const registry = workspace.deploy?.registry;
658
+ if (!registry && (push || mode === "pull")) throw new RegistryRequired(push ? "push" : "pull", imageRef(identity, ctx.apps[0] ?? workspace.name, void 0, tag));
659
+ const runnables = {};
660
+ const background = {};
661
+ const manifest = await discover({
662
+ patterns: constructGlobs(workspace),
663
+ cwd: root,
664
+ runnables,
665
+ background
666
+ });
667
+ const { secrets, generated } = await stageSecrets(ctx, manifest);
668
+ const server = push || stage === workspace.stages.local ? void 0 : requiredServerAddress(stage, workspace.domains?.[stage], secrets?.custom);
669
+ if (!push) {
670
+ assertNoStaleSecrets({
671
+ manifest,
672
+ stage,
673
+ supplied: secrets?.custom ?? {}
674
+ });
675
+ await assertStageCredentials({
676
+ root,
677
+ patterns: constructGlobs(workspace),
678
+ manifest,
679
+ stage,
680
+ supplied: secrets?.custom ?? {}
681
+ });
682
+ }
683
+ const layout = mode === "build" ? imageLayout(workspace) : void 0;
684
+ const composed = composeStack({
685
+ workspace,
686
+ manifest,
687
+ runnables,
688
+ background,
689
+ stage,
690
+ identity,
691
+ images: {
692
+ mode,
693
+ tag,
694
+ ...registry ? { registry } : {}
695
+ },
696
+ secrets,
697
+ ...stage === workspace.stages.local ? { localCredentials: (await loadLocalCredentials(workspace)).credentials } : {},
698
+ allowDevServices: ctx.allowDevServices,
699
+ ports: edgePorts(deps.env),
700
+ ...layout ? { layout } : {},
701
+ ...push ? { buildOnly: true } : {}
702
+ });
703
+ reportDevServices(ctx, composed.devServices);
704
+ if (!push && stage !== workspace.stages.local) {
705
+ const verified = await verifyStageProviders({
706
+ workspace,
707
+ manifest,
708
+ stage,
709
+ secrets: secrets?.custom ?? {}
710
+ });
711
+ for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
712
+ }
713
+ if (mode === "build") assertRedisClient(workspace, composed);
714
+ const stack = options.pin ? withPinnedImages(composed, options.pin.file, options.pin.digests) : composed;
715
+ if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, tag, [...stack.apps, ...stack.workers]);
716
+ if (stack.tls && !push) {
717
+ for (const file of [stack.tls.certFile, stack.tls.keyFile]) if (!existsSync(file)) throw new ComposeTlsFileMissing(stage, file);
718
+ }
719
+ if (!push && !stack.local) await checkDns(ctx, deps, stackHosts(stack).filter((host) => !isLocalHost(host)), server);
720
+ if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
721
+ if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
722
+ ctx.secrets.mask(stack.logs.password);
723
+ ctx.secrets.mask(stack.logs.appEnv.OTEL_EXPORTER_OTLP_HEADERS);
724
+ }
725
+ const dir = join(root, stackDir(stage));
726
+ const override = stackOverrideFile(root, stage);
727
+ const overrides = existsSync(override) ? [override] : [];
728
+ if (overrides.length > 0) ctx.logger.info(`🧩 Merging docker-compose.${stage}.yml over the generated stack`);
729
+ const recorded = push ? void 0 : await ctx.state.read(stage);
730
+ const previous = Object.fromEntries(Object.entries(recorded?.state.releases ?? {}).map(([name, releases]) => {
731
+ const { ref, tag, digest } = releases.current;
732
+ return [name, {
733
+ ref,
734
+ ...tag ? { tag } : {},
735
+ ...digest ? { digest } : {}
736
+ }];
737
+ }));
738
+ return {
739
+ mode,
740
+ push,
741
+ stack,
742
+ dir,
743
+ ref: {
744
+ project: composeProject(identity),
745
+ file: join(dir, "docker-compose.yml"),
746
+ ...overrides.length > 0 ? { overrides } : {},
747
+ cwd: root,
748
+ output: ctx.childOutput,
749
+ signal: ctx.signal
750
+ },
751
+ secrets,
752
+ generated,
753
+ previous,
754
+ files: [],
755
+ images: {},
756
+ changes: []
757
+ };
758
+ }
759
+ /** A stack whose caches are in Redis, built for an app that has no client. */
760
+ var RedisClientMissing = class extends GkmError {
761
+ apps;
762
+ constructor(apps) {
763
+ 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`);
764
+ this.apps = apps;
765
+ this.name = "RedisClientMissing";
766
+ }
767
+ };
768
+ /**
769
+ * Every backend and worker image built for a stack with a cache can resolve
770
+ * `ioredis` — listed by its app or a directory above it, the way Node and
771
+ * the image's install find it.
772
+ */
773
+ function assertRedisClient(workspace, stack) {
774
+ if (!stack.plan.resources.some((r) => r.kind === "cache")) return;
775
+ 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) => {
776
+ const app = workspace.apps[name];
777
+ return app && !installedFrom(join(workspace.root, app.path), "ioredis");
778
+ }).sort();
779
+ if (missing.length > 0) throw new RedisClientMissing(missing);
780
+ }
781
+ /**
782
+ * The stage's secrets — and, for a deployed stage, everything it generates
783
+ * once: its seed, and each declared secret and keyring. Kept only once the
784
+ * run goes ahead (`provision`), so a dry run, or a tag that is not there,
785
+ * leaves the stage's secrets as it found them.
786
+ */
787
+ /**
788
+ * The deploy-time DNS check: each public host resolved with the system
789
+ * resolver and compared with the server's address from the stage's secrets.
790
+ * A dry run warns rather than stops.
791
+ */
792
+ async function checkDns(ctx, deps, hosts, server) {
793
+ const { workspace, stage } = ctx;
794
+ if (hosts.length === 0) return;
795
+ if (ctx.skipDnsCheck) {
796
+ ctx.logger.info("🌐 DNS check skipped (--skip-dns-check)");
797
+ return;
798
+ }
799
+ if (!server) {
800
+ ctx.logger.info(`🌐 DNS check skipped: no ${SERVER_IPV4_KEY} in '${stage}''s secrets — ${serverAddressHint(stage)}`);
801
+ return;
802
+ }
803
+ try {
804
+ const ok = await checkStackDns({
805
+ stage,
806
+ hosts,
807
+ server,
808
+ dns: workspace.dns,
809
+ lookup: deps.lookup ?? systemLookup
810
+ });
811
+ ctx.logger.info(`🌐 ${ok.length} host${ok.length === 1 ? "" : "s"} resolve${ok.length === 1 ? "s" : ""} to ${server.ipv4}`);
812
+ } catch (error) {
813
+ if (ctx.dryRun && error instanceof HostNotPointingAtServer) {
814
+ ctx.logger.warn(`⚠ ${error.message}`);
815
+ return;
816
+ }
817
+ throw error;
818
+ }
819
+ }
820
+ async function stageSecrets(ctx, manifest) {
821
+ const stored = await ctx.secrets.read();
822
+ if (ctx.stage === ctx.workspace.stages.local) return {
823
+ secrets: stored,
824
+ generated: []
825
+ };
826
+ const { secrets, generated } = deployedStackSecrets(ctx.workspace, ctx.stage, stored, manifest);
827
+ if (secrets.seed) ctx.secrets.mask(secrets.seed);
828
+ for (const value of Object.values(secrets.custom ?? {})) ctx.secrets.mask(value);
829
+ return {
830
+ secrets,
831
+ generated
832
+ };
833
+ }
834
+ /**
835
+ * The stack with each app's and worker's image pinned to the digest the file
836
+ * names: the refs it is checked, pulled and recorded by, and the image each
837
+ * compose service runs.
838
+ */
839
+ function withPinnedImages(stack, file, digests) {
840
+ const apps = pinImages(file, digests, stack.apps);
841
+ const workers = pinImages(file, digests, stack.workers);
842
+ const services = { ...stack.compose.services };
843
+ for (const image of [...apps, ...workers]) services[image.name] = {
844
+ ...services[image.name],
845
+ image: image.ref
846
+ };
847
+ return {
848
+ ...stack,
849
+ apps,
850
+ workers,
851
+ compose: {
852
+ ...stack.compose,
853
+ services
854
+ }
855
+ };
856
+ }
857
+ /**
858
+ * A dry run: the stack's files, written so they can be read, and what a real
859
+ * run would do — no image is built or pulled, no container touched, nothing
860
+ * recorded and no secret kept.
861
+ */
862
+ async function planCompose(ctx, run) {
863
+ 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.`);
864
+ run.files = await writeStack(ctx.cwd, run.dir, run.stack);
865
+ printPlan(ctx, run);
866
+ if (!run.push && run.stack.infra.includes("postgres")) reportPlannedSeeds((await plannedSeeds({
867
+ root: ctx.workspace.root,
868
+ manifest: ctx.manifest
869
+ })).map(({ target, seeds }) => ({
870
+ folder: target.seeds,
871
+ seeds
872
+ })), (line) => ctx.logger.info(line));
873
+ const planned = (change) => {
874
+ run.changes.push(change);
875
+ ctx.emit({
876
+ type: "resource.planned",
877
+ ...change
878
+ });
879
+ };
880
+ for (const service of run.push ? [] : run.stack.infra) planned({
881
+ key: `service:${service}`,
882
+ resourceType: "service",
883
+ action: "ensure"
884
+ });
885
+ for (const app of run.stack.apps) {
886
+ planned({
887
+ key: `image:${app.name}`,
888
+ resourceType: "image",
889
+ action: run.mode === "build" ? "build" : "reuse",
890
+ id: app.ref
891
+ });
892
+ if (run.push) continue;
893
+ planned({
894
+ key: `service:${app.name}`,
895
+ resourceType: "service",
896
+ action: run.previous[app.name] ? "reuse" : "create"
897
+ });
898
+ }
899
+ for (const worker of run.stack.workers) {
900
+ planned({
901
+ key: `image:${worker.name}`,
902
+ resourceType: "image",
903
+ action: run.mode === "build" ? "build" : "reuse",
904
+ id: worker.ref
905
+ });
906
+ if (run.push) continue;
907
+ planned({
908
+ key: `service:${worker.name}`,
909
+ resourceType: "service",
910
+ action: run.previous[worker.name] ? "reuse" : "create"
911
+ });
912
+ }
913
+ if (!run.push) planned({
914
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
915
+ resourceType: "service",
916
+ action: "ensure"
917
+ });
918
+ }
919
+ /**
920
+ * What the apps run on: the stage's generated secrets kept, the stack's files
921
+ * written, its infrastructure started, and its databases, roles, grants and
922
+ * migrations applied.
923
+ */
924
+ async function provisionCompose(ctx, run, deps) {
925
+ const { stack, ref } = run;
926
+ if (run.push) return;
927
+ if (run.generated.length > 0 && run.secrets) {
928
+ await ctx.secrets.write(run.secrets);
929
+ ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
930
+ }
931
+ const ports = edgePorts(deps.env);
932
+ await assertEdgePorts(deps.docker, {
933
+ project: stack.project,
934
+ proxy: stack.proxy,
935
+ ports
936
+ });
937
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
938
+ printPlan(ctx, run);
939
+ if (stack.proxy === "traefik") {
940
+ const dir = edgeDir(deps.env);
941
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT}) from ${dir}…`);
942
+ run.files.push(...await ensureEdge(deps.docker, {
943
+ dir,
944
+ ports,
945
+ logging: {
946
+ driver: LOG_ROTATION.driver,
947
+ options: { ...LOG_ROTATION.options }
948
+ },
949
+ ...ref.output ? { output: ref.output } : {},
950
+ ...ref.signal ? { signal: ref.signal } : {}
951
+ }));
952
+ applied(ctx, run, {
953
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
954
+ resourceType: "service",
955
+ action: "ensure",
956
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
957
+ via: "found"
958
+ });
959
+ }
960
+ if (stack.infra.length > 0) {
961
+ ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
962
+ await deps.docker.up(ref, stack.infra);
963
+ for (const service of stack.infra) applied(ctx, run, {
964
+ key: `service:${service}`,
965
+ resourceType: "service",
966
+ action: "ensure",
967
+ id: `${stack.project}/${service}`,
968
+ via: Object.keys(run.previous).length > 0 ? "recorded" : "created"
969
+ });
970
+ }
971
+ if (stack.infra.includes("postgres")) await prepareDatabases(ctx, run, deps);
972
+ if (stack.storage && stack.infra.includes("minio")) await prepareBuckets(ctx, run, deps);
973
+ }
974
+ /**
975
+ * Create each bucket the stack's MinIO serves, and the open paths of each
976
+ * one a file server fronts — from this machine, on MinIO's loopback port,
977
+ * the way `gkm dev` creates them.
978
+ */
979
+ async function prepareBuckets(ctx, run, deps) {
980
+ const storage = run.stack.storage;
981
+ if (storage.buckets.length === 0) return;
982
+ const port = await deps.docker.port(run.ref, "minio", 9e3);
983
+ const client = deps.buckets(port, storage);
984
+ const created = [...await applyBuckets(client, storage.buckets), ...await applyPolicies(client, storage.policies)].filter((entry) => entry.created).length;
985
+ ctx.logger.info(`🪣 Buckets: ${storage.buckets.join(", ")}${created ? ` (${created} change(s))` : ""}`);
986
+ }
987
+ /**
988
+ * Create what the plan names in the stack's Postgres, migrate it, then run
989
+ * its seeds — every one, every time, as each construct's owner.
990
+ */
991
+ async function prepareDatabases(ctx, run, deps) {
992
+ const { stack } = run;
993
+ const workspace = ctx.workspace;
994
+ const port = await deps.docker.port(run.ref, "postgres", 5432);
995
+ const superuser = stack.credential.containers.postgres;
996
+ const login = await deps.logins({
997
+ port,
998
+ login: superuser,
999
+ legacy: [{
1000
+ user: LEGACY_LOCAL_LOGIN.user,
1001
+ password: superuser.password
1002
+ }, ...stack.local ? [LEGACY_LOCAL_LOGIN] : []]
1003
+ });
1004
+ if (login.notice) ctx.logger.info(login.notice);
1005
+ const statements = postgresStatements(stack.plan, workspace.name, stack.credential.seed);
1006
+ if (statements.length > 0) {
1007
+ ctx.logger.info("🗄️ Creating databases, roles and grants…");
1008
+ await applyPostgres(deps.sql(port, login.login), statements);
1009
+ }
1010
+ const sources = {};
1011
+ const manifest = await discover({
1012
+ patterns: constructGlobs(workspace),
1013
+ cwd: workspace.root,
1014
+ sources
1015
+ });
1016
+ const env = envFor(stack.plan, {
1017
+ ports: { [primaryPortKey("postgres")]: port },
1018
+ project: workspace.name,
1019
+ credentials: {
1020
+ ...stack.credential.containers,
1021
+ postgres: login.login
1022
+ },
1023
+ seed: stack.credential.seed
1024
+ });
1025
+ const options = {
1026
+ root: workspace.root,
1027
+ manifest,
1028
+ sources,
1029
+ env
1030
+ };
1031
+ const runs = await deps.migrate(options);
1032
+ const seeds = await deps.seed({
1033
+ ...options,
1034
+ stage: ctx.stage
1035
+ }).catch((error) => {
1036
+ if (error instanceof SeedFailed) throw new DeploySeedsFailed(ctx.stage, error.construct, error.seed, error);
1037
+ throw error;
1038
+ });
1039
+ reportDatabaseRuns(runs.map(({ target, applied }) => ({
1040
+ construct: target.id,
1041
+ folder: target.migrations,
1042
+ applied
1043
+ })), seeds.map(({ target, seeded }) => ({
1044
+ construct: target.id,
1045
+ folder: target.seeds,
1046
+ seeded
1047
+ })), (line) => ctx.logger.info(line), (event) => ctx.emit(event));
1048
+ }
1049
+ /**
1050
+ * Each app's image: built from this checkout — inside Docker, every one of
1051
+ * them, from a pruned slice of the build root — or pulled at the tag. Nothing
1052
+ * live changes.
1053
+ */
1054
+ async function buildCompose(ctx, run, deps) {
1055
+ const { stack, ref } = run;
1056
+ const images = [...stack.apps, ...stack.workers];
1057
+ const apps = images.map((image) => image.app);
1058
+ if (run.push) {
1059
+ run.files = await writeStack(ctx.cwd, run.dir, stack);
1060
+ printPlan(ctx, run);
1061
+ }
1062
+ if (run.mode === "build") {
1063
+ ctx.logger.info("\n🐳 Building images…");
1064
+ await deps.docker.build(ref, apps);
1065
+ } else {
1066
+ ctx.logger.info(`\n🐳 Pulling ${ctx.tag}…`);
1067
+ await deps.docker.pull(ref, apps);
1068
+ }
1069
+ if (run.push) ctx.logger.info("\n📤 Pushing images…");
1070
+ for (const image of images) {
1071
+ const digest = run.push ? await deps.docker.push(ref, image.ref) : await deps.docker.digest(image.ref);
1072
+ if (run.push) ctx.logger.info(` ${image.app.padEnd(12)} ${image.ref}@${digest}`);
1073
+ run.images[image.app] = {
1074
+ ref: image.ref,
1075
+ tag: image.tag,
1076
+ ...digest ? { digest } : {}
1077
+ };
1078
+ ctx.emit({
1079
+ type: "artifact.built",
1080
+ app: image.app,
1081
+ imageRef: image.ref,
1082
+ ...digest ? { digest } : {}
1083
+ });
1084
+ run.changes.push({
1085
+ key: `image:${image.app}`,
1086
+ resourceType: "image",
1087
+ action: run.mode === "build" ? "build" : "reuse",
1088
+ id: digest ?? image.ref
1089
+ });
1090
+ }
1091
+ }
1092
+ /**
1093
+ * The whole stack up — anything it no longer defines removed — and each
1094
+ * app's image recorded in the stage's state.
1095
+ */
1096
+ async function releaseCompose(ctx, run, deps) {
1097
+ const { stack, ref } = run;
1098
+ if (run.push) return;
1099
+ ctx.logger.info("\n🚀 Starting the stack…");
1100
+ await deps.docker.up(ref);
1101
+ const edge = edgeDir(deps.env);
1102
+ if (stack.proxy === "traefik" && stack.traefik) {
1103
+ const written = await writeEdgeRoutes(edge, stack.project, stack.traefik, stack.tls);
1104
+ run.files.push(...written);
1105
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
1106
+ } else await removeEdgeRoutes(edge, stack.project);
1107
+ if (stack.local) await deps.docker.copyOut(ref, "caddy", "/data/caddy/pki/authorities/local/root.crt", caFile(run)).catch(() => {});
1108
+ await recordImages(ctx, run);
1109
+ for (const app of stack.apps) {
1110
+ const image = run.images[app.name];
1111
+ applied(ctx, run, {
1112
+ key: `service:${app.name}`,
1113
+ resourceType: "service",
1114
+ action: "ensure",
1115
+ id: `${stack.project}/${app.name}`,
1116
+ via: run.previous[app.name] ? "recorded" : "created"
1117
+ });
1118
+ ctx.emit({
1119
+ type: "app.deployed",
1120
+ app: app.name,
1121
+ applicationId: `${stack.project}/${app.name}`,
1122
+ imageRef: image?.ref ?? app.ref,
1123
+ url: app.url
1124
+ });
1125
+ }
1126
+ for (const worker of stack.workers) applied(ctx, run, {
1127
+ key: `service:${worker.name}`,
1128
+ resourceType: "service",
1129
+ action: "ensure",
1130
+ id: `${stack.project}/${worker.name}`,
1131
+ via: run.previous[worker.name] ? "recorded" : "created"
1132
+ });
1133
+ ctx.logger.info(`\n✅ ${stack.project} is running:`);
1134
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url}`);
1135
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} worker ${worker.id}`);
1136
+ if (stack.local) ctx.logger.info(`\n🔐 Certificates are from Caddy's local CA: NODE_EXTRA_CA_CERTS=${join(stackDir(ctx.stage), "caddy-root.crt")}`);
1137
+ }
1138
+ /**
1139
+ * Each app's image in the stage's state — the same `images` a Dokploy deploy
1140
+ * records: the ref it runs, the tag it was released under, and the digest
1141
+ * the tag resolved to.
1142
+ */
1143
+ async function recordImages(ctx, run) {
1144
+ const journal = await DeployJournal.open(ctx.state, ctx.stage, () => createComposeState(ctx.stage));
1145
+ const by = currentActor();
1146
+ for (const app of [...run.stack.apps, ...run.stack.workers]) {
1147
+ const image = run.images[app.app] ?? {
1148
+ ref: app.ref,
1149
+ tag: app.tag
1150
+ };
1151
+ recordRelease(journal.state, app.app, image, by);
1152
+ }
1153
+ journal.state.identity = ctx.identity.key;
1154
+ await journal.save();
1155
+ }
1156
+ /**
1157
+ * Each app asked through Caddy, over HTTPS, the certificate verified: an API
1158
+ * at `/health`, a site at `/`. On the local stage the edge is this machine and
1159
+ * its certificates are Caddy's internal CA's, so the CA `release` copied out
1160
+ * is the one trusted and the request goes to 127.0.0.1.
1161
+ */
1162
+ async function verifyCompose(ctx, run, deps) {
1163
+ const { stack } = run;
1164
+ if (run.push) return;
1165
+ const ca = stack.local ? await readFile(caFile(run), "utf-8").catch(() => void 0) : void 0;
1166
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
1167
+ const edge = stack.local || stack.proxy === "traefik" ? {
1168
+ connectTo: "127.0.0.1",
1169
+ ...stack.local ? {} : { connectPort: edgePorts(deps.env).https }
1170
+ } : void 0;
1171
+ const results = await Promise.all(stack.apps.map((app) => checkApp(ctx, app, deps, {
1172
+ ca,
1173
+ edge
1174
+ })));
1175
+ results.push(...await Promise.all(stack.workers.map((worker) => checkContainer(ctx, run, deps, worker.name))));
1176
+ if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
1177
+ const down = results.filter((result) => !result.healthy).map(({ app, url, last }) => ({
1178
+ app,
1179
+ url,
1180
+ last
1181
+ }));
1182
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
1183
+ if (stack.logs) reportLogs(ctx, stack.logs, stack.local);
1184
+ }
1185
+ /**
1186
+ * A container's own health check, as Docker reports it: a worker's, which
1187
+ * has no route through the edge, and OpenObserve's — by default it has no
1188
+ * host there, and served publicly it answers only the addresses it allows,
1189
+ * which need not include this one.
1190
+ */
1191
+ async function checkContainer(ctx, run, deps, service) {
1192
+ const url = `docker:${service}`;
1193
+ let last = "not asked";
1194
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
1195
+ ctx.signal.throwIfAborted();
1196
+ const health = await deps.docker.health(run.ref, service).catch((error) => error instanceof Error ? error.message : String(error));
1197
+ last = health ?? "not running";
1198
+ const healthy = health === "healthy";
1199
+ ctx.emit({
1200
+ type: "health.checked",
1201
+ app: service,
1202
+ url,
1203
+ healthy,
1204
+ attempt
1205
+ });
1206
+ if (healthy) {
1207
+ ctx.logger.info(` ✓ ${service.padEnd(12)} ${url} (${last})`);
1208
+ return {
1209
+ app: service,
1210
+ url,
1211
+ last,
1212
+ healthy
1213
+ };
1214
+ }
1215
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
1216
+ }
1217
+ ctx.logger.warn(` ✗ ${service.padEnd(12)} ${url} (${last})`);
1218
+ return {
1219
+ app: service,
1220
+ url,
1221
+ last,
1222
+ healthy: false
1223
+ };
1224
+ }
1225
+ /** How to open the logs, printed — and as an event, for a headless caller. */
1226
+ function reportLogs(ctx, logs, local) {
1227
+ const lines = logsAccess(logs, {
1228
+ stage: ctx.stage,
1229
+ local,
1230
+ user: currentUser(),
1231
+ hostname: hostname()
1232
+ });
1233
+ ctx.logger.info(`\n${lines.join("\n")}`);
1234
+ ctx.emit({
1235
+ type: "logs.ready",
1236
+ service: LOGS_SERVICE,
1237
+ access: logs.public ? "public" : "tunnel",
1238
+ url: logs.url,
1239
+ ...logs.public ? { allow: [...logs.public.allow] } : { port: logs.port },
1240
+ email: logs.email
1241
+ });
1242
+ }
1243
+ /** This machine's user — a guess at who would SSH in. */
1244
+ function currentUser() {
1245
+ try {
1246
+ return userInfo().username;
1247
+ } catch {
1248
+ return process.env.USER ?? "user";
1249
+ }
1250
+ }
1251
+ async function checkApp(ctx, app, deps, options) {
1252
+ const url = `${app.url}${app.kind === "site" ? "/" : "/health"}`;
1253
+ let last = "not asked";
1254
+ for (let attempt = 1; attempt <= deps.healthAttempts; attempt++) {
1255
+ ctx.signal.throwIfAborted();
1256
+ let status;
1257
+ try {
1258
+ status = await deps.probe({
1259
+ url,
1260
+ ...options.ca ? { ca: options.ca } : {},
1261
+ ...options.edge,
1262
+ timeoutMs: 1e4,
1263
+ signal: ctx.signal
1264
+ });
1265
+ last = `HTTP ${status}`;
1266
+ } catch (error) {
1267
+ last = error instanceof Error ? error.message : String(error);
1268
+ }
1269
+ const healthy = status !== void 0 && isHealthy(status);
1270
+ ctx.emit({
1271
+ type: "health.checked",
1272
+ app: app.name,
1273
+ url,
1274
+ healthy,
1275
+ ...status !== void 0 ? { status } : {},
1276
+ attempt
1277
+ });
1278
+ if (healthy) {
1279
+ ctx.logger.info(` ✓ ${app.name.padEnd(12)} ${url} (${last})`);
1280
+ return {
1281
+ app: app.name,
1282
+ url,
1283
+ last,
1284
+ healthy
1285
+ };
1286
+ }
1287
+ if (attempt < deps.healthAttempts) await new Promise((resolve) => setTimeout(resolve, deps.healthIntervalMs));
1288
+ }
1289
+ ctx.logger.warn(` ✗ ${app.name.padEnd(12)} ${url} (${last})`);
1290
+ return {
1291
+ app: app.name,
1292
+ url,
1293
+ last,
1294
+ healthy: false
1295
+ };
1296
+ }
1297
+ function composeResult(ctx, run) {
1298
+ const apps = [...run.stack.apps.map((app) => {
1299
+ const image = run.images[app.name];
1300
+ return {
1301
+ appName: app.name,
1302
+ type: app.kind === "site" ? "web" : "backend",
1303
+ success: !ctx.dryRun,
1304
+ applicationId: `${run.stack.project}/${app.name}`,
1305
+ imageRef: image?.ref ?? app.ref,
1306
+ ...image?.digest ? { digest: image.digest } : {},
1307
+ url: app.url
1308
+ };
1309
+ }), ...run.stack.workers.map((worker) => {
1310
+ const image = run.images[worker.name];
1311
+ return {
1312
+ appName: worker.name,
1313
+ type: "backend",
1314
+ success: !ctx.dryRun,
1315
+ applicationId: `${run.stack.project}/${worker.name}`,
1316
+ imageRef: image?.ref ?? worker.ref,
1317
+ ...image?.digest ? { digest: image.digest } : {}
1318
+ };
1319
+ })];
1320
+ return {
1321
+ apps,
1322
+ projectId: run.stack.project,
1323
+ successCount: ctx.dryRun ? 0 : apps.length,
1324
+ failedCount: 0,
1325
+ stage: ctx.stage,
1326
+ identity: ctx.identity.key,
1327
+ tag: ctx.tag,
1328
+ dryRun: ctx.dryRun,
1329
+ environmentId: "",
1330
+ skipped: [...ctx.skipped],
1331
+ urls: Object.fromEntries(run.stack.apps.map((app) => [app.name, app.url])),
1332
+ changes: run.changes
1333
+ };
1334
+ }
1335
+ function caFile(run) {
1336
+ return join(run.dir, "caddy-root.crt");
1337
+ }
1338
+ function applied(ctx, run, change) {
1339
+ const { via, ...rest } = change;
1340
+ run.changes.push(rest);
1341
+ ctx.emit({
1342
+ type: "resource.applied",
1343
+ ...rest,
1344
+ via
1345
+ });
1346
+ }
1347
+ /** Write the stack's files: owner-only, since the env files hold secrets. */
1348
+ async function writeStack(root, dir, stack) {
1349
+ await mkdir(dir, {
1350
+ recursive: true,
1351
+ mode: 448
1352
+ });
1353
+ await chmod(dir, 448);
1354
+ const files = [];
1355
+ const write = async (path, content, mode = 420) => {
1356
+ await mkdir(dirname(path), { recursive: true });
1357
+ await writeFile(path, content, { mode });
1358
+ await chmod(path, mode);
1359
+ files.push(path);
1360
+ };
1361
+ await write(join(dir, "docker-compose.yml"), composeYaml(stack));
1362
+ if (stack.caddyfile !== void 0) {
1363
+ await write(join(dir, "Caddyfile"), stack.caddyfile);
1364
+ await rm(join(dir, "traefik.yml"), { force: true });
1365
+ } else await rm(join(dir, "Caddyfile"), { force: true });
1366
+ if (stack.traefik !== void 0) await write(join(dir, "traefik.yml"), stack.traefik);
1367
+ if (stack.proxy === "caddy" && stack.tls) {
1368
+ await mkdir(join(dir, "tls"), {
1369
+ recursive: true,
1370
+ mode: 448
1371
+ });
1372
+ await write(join(dir, "tls", "cert.pem"), await readFile(stack.tls.certFile, "utf-8"));
1373
+ await write(join(dir, "tls", "key.pem"), await readFile(stack.tls.keyFile, "utf-8"), 384);
1374
+ } else await rm(join(dir, "tls"), {
1375
+ recursive: true,
1376
+ force: true
1377
+ });
1378
+ for (const app of [...stack.apps, ...stack.workers]) if (app.env) await write(join(dir, `${app.name}.env`), envFile(app.env), 384);
1379
+ if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write(join(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
1380
+ if (stack.redis && stack.compose.services["redis"]?.env_file) await write(join(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
1381
+ for (const entry of await readdir(dir)) if (entry.endsWith(".credentials")) await rm(join(dir, entry));
1382
+ for (const [path, content] of Object.entries(stack.dockerfiles)) await write(join(root, path), content);
1383
+ await ensureDockerignore(findBuildRoot(root));
1384
+ return files;
1385
+ }
1386
+ function composeYaml(stack) {
1387
+ const stage = ` --stage ${stack.stage}`;
1388
+ return `# Generated by gkm compose from the construct manifest — do not edit.
1389
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
1390
+ # Each backend and worker reads exactly the keys in its own env file beside
1391
+ # this one.
1392
+ #
1393
+ # gkm compose${stage} start or update it
1394
+ # gkm compose${stage} --down stop it
1395
+ ${stringify(stack.compose, {
1396
+ lineWidth: 0,
1397
+ aliasDuplicateObjects: false
1398
+ })}`;
1399
+ }
1400
+ function printPlan(ctx, run) {
1401
+ const { stack, mode, files } = run;
1402
+ ctx.logger.info(`\n🧱 ${stack.project} — stage ${stack.stage}`);
1403
+ for (const app of stack.apps) ctx.logger.info(` ${app.name.padEnd(12)} ${app.url.padEnd(40)} ${mode} ${app.ref}`);
1404
+ for (const worker of stack.workers) ctx.logger.info(` ${worker.name.padEnd(12)} ${`worker ${worker.id} (no route)`.padEnd(40)} ${mode} ${worker.ref}`);
1405
+ if (stack.infra.length > 0) ctx.logger.info(` infrastructure: ${stack.infra.join(", ")}`);
1406
+ ctx.logger.info(`\n📝 Wrote ${files.length} file(s) under ${stackDir(stack.stage)}/`);
1407
+ }
1408
+ //#endregion
1409
+ //#region src/target/compose/index.ts
1410
+ /**
1411
+ * The built-in `compose` target: a stage as one Docker Compose stack behind
1412
+ * Caddy, on the machine that runs the deploy.
1413
+ *
1414
+ * ```bash
1415
+ * gkm deploy --target compose --stage production --tag v1.4.0 # what CI pushed
1416
+ * gkm deploy --target compose --stage production # built from here
1417
+ * gkm deploy --target compose --stage development # the local stage
1418
+ * ```
1419
+ *
1420
+ * - `validate`: the stack (`composeStack`, pure) and, for a tag, every image
1421
+ * looked up in the registry — `ImageTagNotFound` before anything changes
1422
+ * - `plan`: the stack's files and what a run would create or reuse
1423
+ * - `provision`: generated secrets kept, files written, infrastructure up,
1424
+ * databases, roles, grants and migrations
1425
+ * - `build`: each backend bundled on the host and every image built — or, for
1426
+ * a tag, pulled
1427
+ * - `release`: `up --wait --remove-orphans`, and each app's image, tag and
1428
+ * digest in the stage's state
1429
+ * - `verify`: each app asked through Caddy over HTTPS
1430
+ *
1431
+ * With `push` (`gkm compose --build --push`), run with `buildOnly`, it builds
1432
+ * every image and pushes it to `deploy.registry`, and does nothing else.
1433
+ *
1434
+ * `gkm compose` is this target with a few more switches (`--build`, `--pull`,
1435
+ * `--down`), run through the same `deploy()`.
1436
+ */
1437
+ var compose_exports = /* @__PURE__ */ __exportAll({ composeTarget: () => composeTarget });
1438
+ /** The compose target, with its Docker, bundler and probe as given. */
1439
+ function composeTarget(options = {}) {
1440
+ const { mode, push, pin, report, ...given } = options;
1441
+ const deps = {
1442
+ ...defaultDeps,
1443
+ ...given
1444
+ };
1445
+ return defineTarget({
1446
+ name: "compose",
1447
+ runtime: "server",
1448
+ capabilities: {
1449
+ rollback: false,
1450
+ migrations: "target",
1451
+ images: true,
1452
+ localStage: true,
1453
+ selfHostedTelemetry: true
1454
+ },
1455
+ credentials: [],
1456
+ tag: ({ cwd }) => deps.revision(cwd),
1457
+ validate: (ctx) => validateCompose(ctx, deps, {
1458
+ ...mode ? { mode } : {},
1459
+ ...push ? { push } : {},
1460
+ ...pin ? { pin } : {}
1461
+ }),
1462
+ plan: (ctx, run) => planCompose(ctx, run),
1463
+ provision: (ctx, run) => provisionCompose(ctx, run, deps),
1464
+ build: (ctx, run) => buildCompose(ctx, run, deps),
1465
+ release: (ctx, run) => releaseCompose(ctx, run, deps),
1466
+ verify: (ctx, run) => verifyCompose(ctx, run, deps),
1467
+ result: (ctx, run) => {
1468
+ report?.(run);
1469
+ return composeResult(ctx, run);
1470
+ }
1471
+ });
1472
+ }
1473
+ //#endregion
1474
+ export { stackOverrideFile as a, dockerCompose as c, ComposePushNeedsBuild as i, compose_exports as n, edgeDir as o, ComposePinNeedsPull as r, removeEdgeRoutes as s, composeTarget as t };
1475
+
1476
+ //# sourceMappingURL=compose-DrEB_4F-.mjs.map