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