@geekmidas/cli 10.0.0-alpha.77 → 10.0.0-alpha.78

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 (129) hide show
  1. package/dist/{LegacyStateStore-dyq07_Ir.mjs → LegacyStateStore-Ceq7A_75.mjs} +2 -2
  2. package/dist/{LegacyStateStore-dyq07_Ir.mjs.map → LegacyStateStore-Ceq7A_75.mjs.map} +1 -1
  3. package/dist/{LegacyStateStore-DwngfJxr.cjs → LegacyStateStore-Z-EKUGSX.cjs} +2 -2
  4. package/dist/{LegacyStateStore-DwngfJxr.cjs.map → LegacyStateStore-Z-EKUGSX.cjs.map} +1 -1
  5. package/dist/{LocalStateStore-B0NCde8Z.cjs → LocalStateStore-Bocb8dmZ.cjs} +2 -2
  6. package/dist/{LocalStateStore-B0NCde8Z.cjs.map → LocalStateStore-Bocb8dmZ.cjs.map} +1 -1
  7. package/dist/{LocalStateStore-DLxCCatI.mjs → LocalStateStore-C72bwpG2.mjs} +2 -2
  8. package/dist/{LocalStateStore-DLxCCatI.mjs.map → LocalStateStore-C72bwpG2.mjs.map} +1 -1
  9. package/dist/{S3StateStore-BOenb-3o.cjs → S3StateStore-35YfcdL_.cjs} +2 -2
  10. package/dist/{S3StateStore-BOenb-3o.cjs.map → S3StateStore-35YfcdL_.cjs.map} +1 -1
  11. package/dist/{S3StateStore-CGK_4hlo.mjs → S3StateStore-C9upSW5o.mjs} +2 -2
  12. package/dist/{S3StateStore-CGK_4hlo.mjs.map → S3StateStore-C9upSW5o.mjs.map} +1 -1
  13. package/dist/{SSMStateStore-DYeD__7p.cjs → SSMStateStore-W-Ps22AQ.cjs} +2 -2
  14. package/dist/{SSMStateStore-DYeD__7p.cjs.map → SSMStateStore-W-Ps22AQ.cjs.map} +1 -1
  15. package/dist/{SSMStateStore-B_5_RqY-.mjs → SSMStateStore-dOmFO6g1.mjs} +2 -2
  16. package/dist/{SSMStateStore-B_5_RqY-.mjs.map → SSMStateStore-dOmFO6g1.mjs.map} +1 -1
  17. package/dist/{add-DCsgtvDk.cjs → add-BvOICikp.cjs} +3 -3
  18. package/dist/{add-DCsgtvDk.cjs.map → add-BvOICikp.cjs.map} +1 -1
  19. package/dist/{add-EPQO-_dt.mjs → add-D2XKszYP.mjs} +3 -3
  20. package/dist/{add-EPQO-_dt.mjs.map → add-D2XKszYP.mjs.map} +1 -1
  21. package/dist/{bundler-5spPyduN.cjs → bundler-C6T-1OLT.cjs} +5 -5
  22. package/dist/{bundler-5spPyduN.cjs.map → bundler-C6T-1OLT.cjs.map} +1 -1
  23. package/dist/{bundler-DgO_EMVs.mjs → bundler-CtHzKqnZ.mjs} +5 -5
  24. package/dist/{bundler-DgO_EMVs.mjs.map → bundler-CtHzKqnZ.mjs.map} +1 -1
  25. package/dist/{cli-B74Ru-V1.mjs → cli-BgPyhx1i.mjs} +3 -3
  26. package/dist/{cli-B74Ru-V1.mjs.map → cli-BgPyhx1i.mjs.map} +1 -1
  27. package/dist/{cli-ZpFTMbGw.cjs → cli-K6Vj_pPW.cjs} +3 -3
  28. package/dist/{cli-ZpFTMbGw.cjs.map → cli-K6Vj_pPW.cjs.map} +1 -1
  29. package/dist/{compose-CePlrbUw.cjs → compose-B7MC19eC.cjs} +606 -55
  30. package/dist/compose-B7MC19eC.cjs.map +1 -0
  31. package/dist/{compose-IUuxRW0J.mjs → compose-DByK353T.mjs} +592 -59
  32. package/dist/compose-DByK353T.mjs.map +1 -0
  33. package/dist/{config-Ckmoj56i.d.mts → config-Bql0AmJt.d.mts} +3 -3
  34. package/dist/{config-Ckmoj56i.d.mts.map → config-Bql0AmJt.d.mts.map} +1 -1
  35. package/dist/{config-aAeLXH86.d.cts → config-DlNpHK8p.d.cts} +3 -3
  36. package/dist/{config-aAeLXH86.d.cts.map → config-DlNpHK8p.d.cts.map} +1 -1
  37. package/dist/config.cjs +1 -1
  38. package/dist/config.d.cts +3 -3
  39. package/dist/config.d.mts +3 -3
  40. package/dist/config.mjs +1 -1
  41. package/dist/deploy/public.cjs +6 -6
  42. package/dist/deploy/public.d.cts +3 -3
  43. package/dist/deploy/public.d.mts +3 -3
  44. package/dist/deploy/public.mjs +6 -6
  45. package/dist/{deploy-Q6X6RXRG.mjs → deploy-BerP7ppB.mjs} +5 -5
  46. package/dist/{deploy-Q6X6RXRG.mjs.map → deploy-BerP7ppB.mjs.map} +1 -1
  47. package/dist/{deploy-XHXi-_tL.cjs → deploy-Dt42xiQA.cjs} +5 -5
  48. package/dist/{deploy-XHXi-_tL.cjs.map → deploy-Dt42xiQA.cjs.map} +1 -1
  49. package/dist/{dokploy-MSsPBO-t.cjs → dokploy-NG9UrVrP.cjs} +2 -2
  50. package/dist/{dokploy-MSsPBO-t.cjs.map → dokploy-NG9UrVrP.cjs.map} +1 -1
  51. package/dist/{dokploy-BtP5XSrS.mjs → dokploy-ssZQRK2C.mjs} +2 -2
  52. package/dist/{dokploy-BtP5XSrS.mjs.map → dokploy-ssZQRK2C.mjs.map} +1 -1
  53. package/dist/{encryption-DY0na43R.cjs → encryption-CbMI24fI.cjs} +3 -3
  54. package/dist/{encryption-DY0na43R.cjs.map → encryption-CbMI24fI.cjs.map} +1 -1
  55. package/dist/{encryption-D4Ykywfr.mjs → encryption-De6MN0O5.mjs} +3 -3
  56. package/dist/{encryption-D4Ykywfr.mjs.map → encryption-De6MN0O5.mjs.map} +1 -1
  57. package/dist/{engine-y53kE_3H.cjs → engine-CoCsNoW_.cjs} +4 -4
  58. package/dist/{engine-y53kE_3H.cjs.map → engine-CoCsNoW_.cjs.map} +1 -1
  59. package/dist/{engine-BI2xjCKt.mjs → engine-DOjGIgl4.mjs} +4 -4
  60. package/dist/{engine-BI2xjCKt.mjs.map → engine-DOjGIgl4.mjs.map} +1 -1
  61. package/dist/{github-BBIqk1Jv.mjs → github-CwX9z89E.mjs} +3 -3
  62. package/dist/{github-BBIqk1Jv.mjs.map → github-CwX9z89E.mjs.map} +1 -1
  63. package/dist/{github-Bmb45xUQ.cjs → github-D9vGqdLk.cjs} +3 -3
  64. package/dist/{github-Bmb45xUQ.cjs.map → github-D9vGqdLk.cjs.map} +1 -1
  65. package/dist/{index-CNdSRwar.d.mts → index-BXO0vlme.d.mts} +2 -2
  66. package/dist/{index-C7Tma2m1.d.cts.map → index-BXO0vlme.d.mts.map} +1 -1
  67. package/dist/{index-C7Tma2m1.d.cts → index-Rs0Fua-q.d.cts} +2 -2
  68. package/dist/{index-CNdSRwar.d.mts.map → index-Rs0Fua-q.d.cts.map} +1 -1
  69. package/dist/index.cjs +46 -45
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.mjs +46 -45
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/{migrate-31JXUOaG.cjs → migrate-B4GBvCNY.cjs} +3 -3
  74. package/dist/{migrate-31JXUOaG.cjs.map → migrate-B4GBvCNY.cjs.map} +1 -1
  75. package/dist/{migrate-DWVl5PQK.mjs → migrate-BQ4wVKq_.mjs} +3 -3
  76. package/dist/{migrate-DWVl5PQK.mjs.map → migrate-BQ4wVKq_.mjs.map} +1 -1
  77. package/dist/{migrate-BUBsUiM3.mjs → migrate-CNKaQl3K.mjs} +3 -3
  78. package/dist/{migrate-BUBsUiM3.mjs.map → migrate-CNKaQl3K.mjs.map} +1 -1
  79. package/dist/{migrate-sny0NjKe.cjs → migrate-Cgoy58Sh.cjs} +3 -3
  80. package/dist/{migrate-sny0NjKe.cjs.map → migrate-Cgoy58Sh.cjs.map} +1 -1
  81. package/dist/openapi.cjs +1 -1
  82. package/dist/openapi.d.cts +1 -1
  83. package/dist/openapi.d.mts +1 -1
  84. package/dist/openapi.mjs +1 -1
  85. package/dist/reconcile/public.d.cts +1 -1
  86. package/dist/reconcile/public.d.mts +1 -1
  87. package/dist/{resolve-DokLtTUb.cjs → resolve-CEaqRBzY.cjs} +3 -3
  88. package/dist/{resolve-DokLtTUb.cjs.map → resolve-CEaqRBzY.cjs.map} +1 -1
  89. package/dist/{resolve-BF1ICosS.mjs → resolve-mvaystiE.mjs} +3 -3
  90. package/dist/{resolve-BF1ICosS.mjs.map → resolve-mvaystiE.mjs.map} +1 -1
  91. package/dist/{rollback-CpOWRR9H.cjs → rollback-F3P-rA-r.cjs} +5 -5
  92. package/dist/{rollback-CpOWRR9H.cjs.map → rollback-F3P-rA-r.cjs.map} +1 -1
  93. package/dist/{rollback-sg0ZhKGG.mjs → rollback-S2C-Y9pB.mjs} +5 -5
  94. package/dist/{rollback-sg0ZhKGG.mjs.map → rollback-S2C-Y9pB.mjs.map} +1 -1
  95. package/dist/{runtime-BozOkPtG.d.cts → runtime-D9AxGzrw.d.cts} +2 -2
  96. package/dist/{runtime-B5bYom9w.d.mts.map → runtime-D9AxGzrw.d.cts.map} +1 -1
  97. package/dist/{runtime-B5bYom9w.d.mts → runtime-Dflki3Vs.d.mts} +2 -2
  98. package/dist/{runtime-BozOkPtG.d.cts.map → runtime-Dflki3Vs.d.mts.map} +1 -1
  99. package/dist/{sniffer-Y6GQOCXB.cjs → sniffer-BjG-1mlD.cjs} +6 -6
  100. package/dist/{sniffer-Y6GQOCXB.cjs.map → sniffer-BjG-1mlD.cjs.map} +1 -1
  101. package/dist/{sniffer-DR8AlRCk.mjs → sniffer-ByWtH28i.mjs} +6 -6
  102. package/dist/{sniffer-DR8AlRCk.mjs.map → sniffer-ByWtH28i.mjs.map} +1 -1
  103. package/dist/{stale-yu2FkH3G.cjs → stale-BsiPJI7Y.cjs} +5 -5
  104. package/dist/stale-BsiPJI7Y.cjs.map +1 -0
  105. package/dist/{stale-DGzpiN5S.mjs → stale-C5FqIVc8.mjs} +5 -5
  106. package/dist/stale-C5FqIVc8.mjs.map +1 -0
  107. package/dist/target/public.cjs +1 -1
  108. package/dist/target/public.d.cts +2 -2
  109. package/dist/target/public.d.mts +2 -2
  110. package/dist/target/public.mjs +1 -1
  111. package/dist/{types-ct7pdQRf.d.cts → types-ByY0zi3n.d.cts} +42 -1
  112. package/dist/{types-ct7pdQRf.d.cts.map → types-ByY0zi3n.d.cts.map} +1 -1
  113. package/dist/{types-B9yWJAis.d.mts → types-DKxkXsKC.d.mts} +42 -1
  114. package/dist/{types-B9yWJAis.d.mts.map → types-DKxkXsKC.d.mts.map} +1 -1
  115. package/dist/workspace/index.cjs +1 -1
  116. package/dist/workspace/index.d.cts +2 -2
  117. package/dist/workspace/index.d.mts +2 -2
  118. package/dist/workspace/index.mjs +1 -1
  119. package/dist/{workspace-QUTqYmVy.mjs → workspace-BBdqmkch.mjs} +114 -17
  120. package/dist/workspace-BBdqmkch.mjs.map +1 -0
  121. package/dist/{workspace-DOm81oUo.cjs → workspace-Bp8FEkF-.cjs} +130 -15
  122. package/dist/workspace-Bp8FEkF-.cjs.map +1 -0
  123. package/package.json +15 -15
  124. package/dist/compose-CePlrbUw.cjs.map +0 -1
  125. package/dist/compose-IUuxRW0J.mjs.map +0 -1
  126. package/dist/stale-DGzpiN5S.mjs.map +0 -1
  127. package/dist/stale-yu2FkH3G.cjs.map +0 -1
  128. package/dist/workspace-DOm81oUo.cjs.map +0 -1
  129. package/dist/workspace-QUTqYmVy.mjs.map +0 -1
@@ -2,9 +2,9 @@ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
2
  const require_run = require("./run-fVZ-rLnc.cjs");
3
3
  const require_discover = require("./discover-D1It5r_h.cjs");
4
4
  const require_derive = require("./derive-DAbo49sm.cjs");
5
- const require_workspace = require("./workspace-DOm81oUo.cjs");
5
+ const require_workspace = require("./workspace-Bp8FEkF-.cjs");
6
6
  const require_define = require("./define-DzRz8FgH.cjs");
7
- const require_stale = require("./stale-yu2FkH3G.cjs");
7
+ const require_stale = require("./stale-BsiPJI7Y.cjs");
8
8
  const require_SubscriberGenerator = require("./SubscriberGenerator-CajwOa5W.cjs");
9
9
  const require_drivers = require("./drivers-BdvtCKc7.cjs");
10
10
  const require_databases = require("./databases-C2p5LGAp.cjs");
@@ -49,6 +49,27 @@ function runOptions(stack, env) {
49
49
  ...stack.signal ? { signal: stack.signal } : {}
50
50
  };
51
51
  }
52
+ /**
53
+ * The host ports a `docker ps` Ports column publishes: `0.0.0.0:443->443/tcp,
54
+ * [::]:443->443/tcp, 0.0.0.0:9000-9001->9000-9001/tcp`.
55
+ */
56
+ function publishedPorts(column) {
57
+ const ports = /* @__PURE__ */ new Set();
58
+ for (const match of column.matchAll(/(?:[\d.]+|\[[^\]]*\]):(\d+)(?:-(\d+))?->/g)) {
59
+ const first = Number(match[1]);
60
+ const last = match[2] ? Number(match[2]) : first;
61
+ for (let port = first; port <= last; port++) ports.add(port);
62
+ }
63
+ return [...ports];
64
+ }
65
+ /** Each line `docker ps` printed, as the containers holding `port`. */
66
+ function portHolders(output, port) {
67
+ return output.split("\n").filter(Boolean).map((line) => line.split(" ")).filter(([, , , column = ""]) => publishedPorts(column).includes(port)).map(([container = "", project, service]) => ({
68
+ container,
69
+ ...project ? { project } : {},
70
+ ...service ? { service } : {}
71
+ }));
72
+ }
52
73
  /** How long a stack has to pass its health checks. */
53
74
  const WAIT_TIMEOUT_S = 180;
54
75
  /** `docker compose port` printed nothing a port can be read from. */
@@ -249,8 +270,389 @@ const dockerCompose = {
249
270
  if (match) return match.slice(repository.length + 1);
250
271
  } catch {}
251
272
  return id || void 0;
273
+ },
274
+ async ensureNetwork(name) {
275
+ const { code } = await capture("docker", [
276
+ "network",
277
+ "inspect",
278
+ name
279
+ ]);
280
+ if (code === 0) return;
281
+ const created = await capture("docker", [
282
+ "network",
283
+ "create",
284
+ name
285
+ ]);
286
+ if (created.code !== 0 && !/already exists/.test(created.stderr)) throw new NetworkCreateFailed(name, created.stderr);
287
+ },
288
+ async publishers(port) {
289
+ const { stdout } = await capture("docker", [
290
+ "ps",
291
+ "--format",
292
+ "{{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.service\"}} {{.Ports}}"
293
+ ]);
294
+ return portHolders(stdout, port);
295
+ }
296
+ };
297
+ /** `docker network create` failed. */
298
+ var NetworkCreateFailed = class extends Error {
299
+ network;
300
+ output;
301
+ constructor(network, output) {
302
+ 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.`);
303
+ this.network = network;
304
+ this.output = output;
305
+ this.name = "NetworkCreateFailed";
306
+ }
307
+ };
308
+ //#endregion
309
+ //#region src/compose/traefik.ts
310
+ /**
311
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
312
+ * with, and what one stack registers with it.
313
+ *
314
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
315
+ * HTTPS. It is configured through its file provider alone: each stack writes
316
+ * one file — its routers, services and middlewares, every name prefixed with
317
+ * its compose project — into a directory the edge watches, and removes it
318
+ * when it stops. There is no Docker socket: the edge never learns what runs
319
+ * on the server except from those files.
320
+ *
321
+ * The edge and the stacks meet on one external Docker network. Only a
322
+ * stack's public services join it, each under an alias prefixed with its
323
+ * project (`<project>-api`), because the network is shared: a bare service
324
+ * name there would be answered by every stack's `api`.
325
+ *
326
+ * Pure: the documents are data, and the edge's side effects are `edge.ts`'s.
327
+ */
328
+ /**
329
+ * The image, pinned: the edge is every stack's way in, so a new version is a
330
+ * change to this line, not whatever `latest` is on the day a server starts.
331
+ */
332
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
333
+ /** The edge's compose project, one per server. */
334
+ const EDGE_PROJECT = "gkm-edge";
335
+ /** The external network the edge and every stack's public services share. */
336
+ const EDGE_NETWORK = "gkm-edge";
337
+ /** The edge's compose service. */
338
+ const EDGE_SERVICE = "traefik";
339
+ /** Inside the edge's container: what it watches, and where certificates are. */
340
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
341
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
342
+ /** The certificate resolver every deployed route without its own certificate uses. */
343
+ const ACME_RESOLVER = "letsencrypt";
344
+ /** The internal entrypoint the edge's health check asks; never published. */
345
+ const PING_PORT = 8082;
346
+ /** A stack's service, as the edge — and the stack itself — reach it. */
347
+ function edgeAlias(project, service) {
348
+ return `${project}-${service}`;
349
+ }
350
+ /** A stack's certificate, as the edge's container reads it. */
351
+ function edgeCertificatePaths(project) {
352
+ return {
353
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
354
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
355
+ };
356
+ }
357
+ /**
358
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
359
+ * the directory it watches. No API and no dashboard — nothing about the edge
360
+ * is reachable but the routes stacks register.
361
+ */
362
+ function traefikStatic(ports) {
363
+ return {
364
+ global: {
365
+ checkNewVersion: false,
366
+ sendAnonymousUsage: false
367
+ },
368
+ entryPoints: {
369
+ web: {
370
+ address: ":80",
371
+ http: { redirections: { entryPoint: {
372
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
373
+ scheme: "https",
374
+ permanent: true
375
+ } } }
376
+ },
377
+ websecure: { address: ":443" },
378
+ ping: { address: `:${PING_PORT}` }
379
+ },
380
+ ping: { entryPoint: "ping" },
381
+ providers: { file: {
382
+ directory: EDGE_DYNAMIC_DIR,
383
+ watch: true
384
+ } },
385
+ certificatesResolvers: { [ACME_RESOLVER]: { acme: {
386
+ storage: "/acme/acme.json",
387
+ httpChallenge: { entryPoint: "web" }
388
+ } } },
389
+ log: { level: "INFO" }
390
+ };
391
+ }
392
+ /** The edge's compose document. */
393
+ function edgeCompose(options) {
394
+ const { dir, ports } = options;
395
+ return {
396
+ name: EDGE_PROJECT,
397
+ services: { [EDGE_SERVICE]: {
398
+ image: TRAEFIK_IMAGE,
399
+ restart: "unless-stopped",
400
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
401
+ volumes: [
402
+ `${dir}/traefik.yml:/etc/traefik/traefik.yml:ro`,
403
+ `${dir}/dynamic:${EDGE_DYNAMIC_DIR}:ro`,
404
+ `${dir}/certs:${EDGE_CERTS_DIR}:ro`,
405
+ "acme:/acme"
406
+ ],
407
+ labels: { "dev.geekmidas.edge.config": (0, node_crypto.createHash)("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
408
+ networks: ["edge"],
409
+ healthcheck: {
410
+ test: [
411
+ "CMD",
412
+ "traefik",
413
+ "healthcheck",
414
+ "--ping"
415
+ ],
416
+ interval: "10s",
417
+ timeout: "5s",
418
+ retries: 5
419
+ },
420
+ logging: options.logging
421
+ } },
422
+ volumes: { acme: {} },
423
+ networks: { edge: {
424
+ name: EDGE_NETWORK,
425
+ external: true
426
+ } }
427
+ };
428
+ }
429
+ /** A stack's dynamic configuration, as an object. */
430
+ function traefikDynamic(routes, options) {
431
+ const { project, tls } = options;
432
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
433
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
434
+ const routers = {};
435
+ const services = {};
436
+ const middlewares = {};
437
+ for (const route of routes) {
438
+ const chain = [];
439
+ if (route.allow) {
440
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
441
+ chain.push(name(route, "allow"));
442
+ }
443
+ if (route.prefix) {
444
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
445
+ chain.push(name(route, "prefix"));
446
+ }
447
+ routers[name(route)] = {
448
+ rule: `Host(\`${route.host}\`)`,
449
+ entryPoints: ["websecure"],
450
+ service: name(route),
451
+ ...chain.length > 0 ? { middlewares: chain } : {},
452
+ tls: tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {}
453
+ };
454
+ services[name(route)] = { loadBalancer: {
455
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
456
+ ...route.prefix ? { passHostHeader: false } : {},
457
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
458
+ ...route.health ? { healthCheck: {
459
+ path: route.health,
460
+ interval: "5s",
461
+ timeout: "3s"
462
+ } } : {}
463
+ } };
464
+ }
465
+ return {
466
+ http: {
467
+ routers,
468
+ services,
469
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
470
+ },
471
+ ...tls.kind === "files" ? { tls: { certificates: [{
472
+ certFile: tls.certFile,
473
+ keyFile: tls.keyFile
474
+ }] } } : {}
475
+ };
476
+ }
477
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
478
+ function traefikDynamicFile(routes, options) {
479
+ return `# Generated by gkm compose for ${options.project} — do not edit.
480
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
481
+ # one is removed by gkm compose --down.
482
+ ${yaml$1(traefikDynamic(routes, options))}`;
483
+ }
484
+ /** The edge's static configuration file. */
485
+ function traefikStaticFile(ports) {
486
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
487
+ ${yaml$1(traefikStatic(ports))}`;
488
+ }
489
+ /** The edge's compose file. */
490
+ function edgeComposeFile(options) {
491
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
492
+ #
493
+ # Started by the first stack that runs with proxy: 'traefik', and left
494
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
495
+ #
496
+ # docker compose -p ${EDGE_PROJECT} -f ${options.dir}/docker-compose.yml down
497
+ ${yaml$1(edgeCompose(options))}`;
498
+ }
499
+ function yaml$1(value) {
500
+ return (0, yaml.stringify)(value, {
501
+ lineWidth: 0,
502
+ aliasDuplicateObjects: false
503
+ });
504
+ }
505
+ //#endregion
506
+ //#region src/compose/edge.ts
507
+ /**
508
+ * The server's shared Traefik edge, on disk and in Docker: started when a
509
+ * stack needs it, and each stack's routes written to — and removed from —
510
+ * the directory it watches.
511
+ *
512
+ * The edge lives in the deploy user's gkm home (`$GKM_HOME/edge`, else
513
+ * `~/.gkm/edge`): the user who runs `gkm compose` owns it, so nothing needs
514
+ * root, and it sits beside the stage keys that same user already keeps.
515
+ *
516
+ * ~/.gkm/edge/
517
+ * docker-compose.yml the edge's compose project (gkm-edge)
518
+ * traefik.yml its static configuration
519
+ * dynamic/<project>.yml one per stack: its routers, services, middlewares
520
+ * certs/<project>.crt|.key a stack's own certificate, where it has one
521
+ */
522
+ /** The edge's directory on this machine. */
523
+ function edgeDir(env = process.env) {
524
+ return (0, node_path.join)(require_run.gkmHome(env), "edge");
525
+ }
526
+ /** The edge's compose project, as docker is asked about it. */
527
+ function edgeRef(dir, options = {}) {
528
+ return {
529
+ project: EDGE_PROJECT,
530
+ file: (0, node_path.join)(dir, "docker-compose.yml"),
531
+ cwd: dir,
532
+ ...options
533
+ };
534
+ }
535
+ /**
536
+ * Something other than the proxy a stack is set to holds the edge's ports.
537
+ *
538
+ * With `proxy: 'traefik'`, the stack's own Caddy — still running from before
539
+ * the switch — or any other container; with `proxy: 'caddy'`, the shared
540
+ * edge, or another stack's Caddy. Refused before anything is started, so the
541
+ * stack is never left half on one proxy and half on the other.
542
+ */
543
+ var ComposeProxyClash = class extends Error {
544
+ project;
545
+ proxy;
546
+ port;
547
+ holder;
548
+ constructor(project, proxy, port, holder) {
549
+ const by = holder.project ? `${holder.container} (compose project ${holder.project})` : holder.container;
550
+ 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.`;
551
+ super(`${project} is set to proxy: '${proxy}', and port ${port} is held by ${by}. ${fix}`);
552
+ this.project = project;
553
+ this.proxy = proxy;
554
+ this.port = port;
555
+ this.holder = holder;
556
+ this.name = "ComposeProxyClash";
252
557
  }
253
558
  };
559
+ /**
560
+ * Refuse a stack whose edge ports are held by anything but its own proxy:
561
+ * the shared edge for `'traefik'`, the stack's own Caddy for `'caddy'`.
562
+ */
563
+ async function assertEdgePorts(docker, options) {
564
+ const { project, proxy, ports } = options;
565
+ 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);
566
+ }
567
+ /** Write a file whole or not at all: a temporary file, then a rename. */
568
+ async function writeAtomic(path, content, mode = 420) {
569
+ const temporary = `${path}.${process.pid}.tmp`;
570
+ await (0, node_fs_promises.writeFile)(temporary, content, { mode });
571
+ await (0, node_fs_promises.chmod)(temporary, mode);
572
+ await (0, node_fs_promises.rename)(temporary, path);
573
+ }
574
+ /** Write a file only when its content changed; whether it did. */
575
+ async function writeIfChanged(path, content) {
576
+ if (await (0, node_fs_promises.readFile)(path, "utf-8").catch(() => void 0) === content) return false;
577
+ await writeAtomic(path, content);
578
+ return true;
579
+ }
580
+ /**
581
+ * The edge, up: its network, its files, and its container — started when it
582
+ * is not running, and recreated when its configuration changed. Idempotent:
583
+ * on a server where it already runs as configured, `up` changes nothing.
584
+ */
585
+ async function ensureEdge(docker, options) {
586
+ const { dir, ports } = options;
587
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(dir, "dynamic"), { recursive: true });
588
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(dir, "certs"), {
589
+ recursive: true,
590
+ mode: 448
591
+ });
592
+ const staticConfig = traefikStaticFile(ports);
593
+ await writeIfChanged((0, node_path.join)(dir, "traefik.yml"), staticConfig);
594
+ await writeIfChanged((0, node_path.join)(dir, "docker-compose.yml"), edgeComposeFile({
595
+ dir,
596
+ ports,
597
+ staticConfig,
598
+ logging: options.logging
599
+ }));
600
+ await docker.ensureNetwork(EDGE_NETWORK);
601
+ await docker.up(edgeRef(dir, {
602
+ ...options.output ? { output: options.output } : {},
603
+ ...options.signal ? { signal: options.signal } : {}
604
+ }), [EDGE_SERVICE]);
605
+ return [(0, node_path.join)(dir, "traefik.yml"), (0, node_path.join)(dir, "docker-compose.yml")];
606
+ }
607
+ /** A stack's file in the edge's directory. */
608
+ function routesFile(dir, project) {
609
+ return (0, node_path.join)(dir, "dynamic", `${project}.yml`);
610
+ }
611
+ /**
612
+ * Register a stack with the edge: its certificate first, where it has one,
613
+ * so the routes that need it never load without it — then its routes, in one
614
+ * rename the edge picks up whole.
615
+ */
616
+ async function writeEdgeRoutes(dir, project, routes, certificate) {
617
+ const files = [];
618
+ if (certificate) {
619
+ const certs = (0, node_path.join)(dir, "certs");
620
+ await (0, node_fs_promises.mkdir)(certs, {
621
+ recursive: true,
622
+ mode: 448
623
+ });
624
+ const crt = (0, node_path.join)(certs, `${project}.crt`);
625
+ const key = (0, node_path.join)(certs, `${project}.key`);
626
+ await (0, node_fs_promises.copyFile)(certificate.certFile, `${crt}.tmp`);
627
+ await (0, node_fs_promises.rename)(`${crt}.tmp`, crt);
628
+ await (0, node_fs_promises.copyFile)(certificate.keyFile, `${key}.tmp`);
629
+ await (0, node_fs_promises.chmod)(`${key}.tmp`, 384);
630
+ await (0, node_fs_promises.rename)(`${key}.tmp`, key);
631
+ files.push(crt, key);
632
+ } else await removeCertificate(dir, project);
633
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(dir, "dynamic"), { recursive: true });
634
+ const file = routesFile(dir, project);
635
+ await writeAtomic(file, routes);
636
+ files.push(file);
637
+ return files;
638
+ }
639
+ /** What a stack's file holds for the moment between emptying and removal. */
640
+ const UNREGISTERED = "# Unregistered by gkm compose --down.\n";
641
+ async function removeCertificate(dir, project) {
642
+ for (const ext of ["crt", "key"]) await (0, node_fs_promises.rm)((0, node_path.join)(dir, "certs", `${project}.${ext}`), { force: true });
643
+ }
644
+ /**
645
+ * Unregister a stack: its routes, then its certificate. Whether there was
646
+ * anything to remove.
647
+ */
648
+ async function removeEdgeRoutes(dir, project) {
649
+ const file = routesFile(dir, project);
650
+ const existed = (0, node_fs.existsSync)(file);
651
+ if (existed) await writeAtomic(file, UNREGISTERED);
652
+ await (0, node_fs_promises.rm)(file, { force: true });
653
+ await removeCertificate(dir, project);
654
+ return existed;
655
+ }
254
656
  //#endregion
255
657
  //#region src/compose/images.ts
256
658
  /**
@@ -715,9 +1117,16 @@ function redisService(redis) {
715
1117
  }
716
1118
  //#endregion
717
1119
  //#region src/compose/caddyfile.ts
1120
+ /** Where Caddy reads a stage's own certificate, inside its container. */
1121
+ const CADDY_TLS_DIR = "/etc/caddy/tls";
1122
+ /** An upstream on the stack's own network: its service name. */
1123
+ function address({ service, port }) {
1124
+ return `${service}:${port}`;
1125
+ }
718
1126
  /** The Caddyfile for a stack's edge. */
719
- function edgeCaddyfile(sites, options) {
720
- const global = options.local ? `{
1127
+ function edgeCaddyfile(routes, options) {
1128
+ const { tls } = options;
1129
+ const global = tls.kind === "internal" ? `{
721
1130
  # No ACME and no public DNS: the CA is Caddy's own and the names resolve
722
1131
  # to this machine.
723
1132
  local_certs
@@ -725,27 +1134,30 @@ function edgeCaddyfile(sites, options) {
725
1134
  }` : options.email ? `{
726
1135
  email ${options.email}
727
1136
  }` : "";
728
- const blocks = sites.map(({ host, upstream, rewrite, allow }) => `https://${host} {${options.local ? `
1137
+ const certificate = tls.kind === "internal" ? `
729
1138
  tls internal
730
- ` : ""}${allow ? `
1139
+ ` : tls.kind === "files" ? `
1140
+ tls ${tls.certFile} ${tls.keyFile}
1141
+ ` : "";
1142
+ const blocks = routes.map(({ host, upstreams, prefix, allow, streaming }) => `https://${host} {${certificate}${allow ? `
731
1143
  # Only these addresses — the peer Caddy sees, never a header a client
732
1144
  # could set. Everything else is refused before it reaches the upstream.
733
1145
  @denied not remote_ip ${allow.join(" ")}
734
1146
  respond @denied 403
735
- ` : ""}${rewrite ? `
1147
+ ` : ""}${prefix ? `
736
1148
  # A bucket, served at a host of its own: the bucket is a prefix on MinIO,
737
1149
  # which routes and signs on the Host header — so it is sent the upstream's.
738
- reverse_proxy ${upstream} {
739
- rewrite ${rewrite}
1150
+ reverse_proxy ${upstreams.map(address).join(" ")} {
1151
+ rewrite ${prefix}{uri}
740
1152
  header_up Host {upstream_hostport}
741
1153
  }` : `
742
1154
  # Host and X-Forwarded-* are passed through as Caddy does by default, so
743
1155
  # an app builds redirects, cookies and links on the address a caller used.
744
- reverse_proxy ${upstream} {
1156
+ reverse_proxy ${upstreams.map(address).join(" ")}${streaming ? ` {
745
1157
  # Never buffer: a streamed response — server-sent events, a Next.js
746
1158
  # RSC payload — reaches the client as each chunk is written.
747
1159
  flush_interval -1
748
- }`}
1160
+ }` : ""}`}
749
1161
  }`);
750
1162
  return `${HEADER}${global ? `${global}\n\n` : ""}${blocks.join("\n\n")}\n`;
751
1163
  }
@@ -907,6 +1319,8 @@ function composeStack(input) {
907
1319
  const custom = input.secrets?.custom ?? {};
908
1320
  const https = input.ports?.https ?? 443;
909
1321
  const http = input.ports?.http ?? 80;
1322
+ const proxy = require_workspace.proxyFor(workspace.deploy?.compose, stage, local);
1323
+ const certificate = local ? void 0 : require_workspace.certificateFor(workspace.deploy?.compose, stage, workspace.root);
910
1324
  const plan = require_stale.planFor(manifest, stage, (0, _geekmidas_manifest.provisionOrder)(manifest), {
911
1325
  localStage: workspace.stages.local,
912
1326
  events: require_SubscriberGenerator.DEFAULT_EVENTS.server,
@@ -950,7 +1364,7 @@ function composeStack(input) {
950
1364
  for (const worker of workers) reads.set(worker.name, [...require_stale.workerEnvKeys(manifest, worker.id, input.runnables) ?? []]);
951
1365
  const domain = workspace.deploy?.domains?.[stage];
952
1366
  const logsConfig = require_workspace.resolveLogs(workspace.deploy?.compose?.logs);
953
- const logs = logsConfig ? stackLogs({
1367
+ const logsBase = logsConfig ? stackLogs({
954
1368
  config: logsConfig,
955
1369
  stage,
956
1370
  local,
@@ -976,7 +1390,7 @@ function composeStack(input) {
976
1390
  local,
977
1391
  custom
978
1392
  });
979
- const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logs ? [LOGS_SERVICE] : []].sort();
1393
+ const infra = [...plan.containers.filter((c) => !NOT_RUN[c]).filter((c) => c !== "minio" || services.minio.length > 0).filter((c) => c !== "mailpit" || services.mailpit.length > 0).filter((c) => c !== "redis" || redis !== void 0), ...logsBase ? [LOGS_SERVICE] : []].sort();
980
1394
  const storage = infra.includes("minio") ? (() => {
981
1395
  const buckets = services.minio.map((id) => byId.get(id)?.name).filter((name) => Boolean(name)).sort();
982
1396
  return {
@@ -986,20 +1400,6 @@ function composeStack(input) {
986
1400
  policies: require_stale.bucketPolicies(plan).filter((p) => buckets.includes(p.bucket))
987
1401
  };
988
1402
  })() : void 0;
989
- const derivation = {
990
- project: workspace.name,
991
- master: credential.master,
992
- ...credential.seed ? { seed: credential.seed } : {},
993
- ...!local && domain ? { mailFrom: `noreply@${domain}` } : {}
994
- };
995
- const outside = require_stale.networkEnv(plan, {
996
- ...derivation,
997
- addresses: Object.fromEntries(apps.map((app) => [app.id, app.url]))
998
- });
999
- const inside = require_stale.networkEnv(plan, {
1000
- ...derivation,
1001
- addresses: Object.fromEntries(apps.map((app) => [app.id, `http://${app.name}:${app.port}`]))
1002
- });
1003
1403
  const fileServers = /* @__PURE__ */ new Map();
1004
1404
  if (storage) for (const resource of plan.resources) {
1005
1405
  if (resource.kind !== "file-server" || !resource.of) continue;
@@ -1015,13 +1415,45 @@ function composeStack(input) {
1015
1415
  }
1016
1416
  fileServers.set(resource.id, {
1017
1417
  url: `https://${host}${local && https !== 443 ? `:${https}` : ""}`,
1018
- site: {
1418
+ route: {
1419
+ name: `files-${require_derive.appKey(resource.id)}`,
1019
1420
  host,
1020
- upstream: "minio:9000",
1021
- rewrite: `/${bucket.name}{uri}`
1421
+ upstreams: [{
1422
+ service: "minio",
1423
+ port: 9e3
1424
+ }],
1425
+ streaming: false,
1426
+ prefix: `/${bucket.name}`
1022
1427
  }
1023
1428
  });
1024
1429
  }
1430
+ const edgeServices = new Set(proxy === "traefik" ? [
1431
+ ...apps.map((app) => app.name),
1432
+ ...fileServers.size > 0 ? ["minio"] : [],
1433
+ ...logsBase?.host && logsBase.public ? [LOGS_SERVICE] : []
1434
+ ] : []);
1435
+ const hostOf = (service) => edgeServices.has(service) ? edgeAlias(project, service) : service;
1436
+ const logs = logsBase && {
1437
+ ...logsBase,
1438
+ appEnv: {
1439
+ ...logsBase.appEnv,
1440
+ OTEL_EXPORTER_OTLP_ENDPOINT: logsBase.appEnv.OTEL_EXPORTER_OTLP_ENDPOINT.replace(`//openobserve:`, `//${hostOf("openobserve")}:`)
1441
+ }
1442
+ };
1443
+ const derivation = {
1444
+ project: workspace.name,
1445
+ master: credential.master,
1446
+ ...credential.seed ? { seed: credential.seed } : {},
1447
+ ...!local && domain ? { mailFrom: `noreply@${domain}` } : {}
1448
+ };
1449
+ const outside = require_stale.networkEnv(plan, {
1450
+ ...derivation,
1451
+ addresses: Object.fromEntries(apps.map((app) => [app.id, app.url]))
1452
+ }, hostOf);
1453
+ const inside = require_stale.networkEnv(plan, {
1454
+ ...derivation,
1455
+ addresses: Object.fromEntries(apps.map((app) => [app.id, `http://${hostOf(app.name)}:${app.port}`]))
1456
+ }, hostOf);
1025
1457
  const surfaceUrls = new Map(plan.resources.filter((r) => r.kind === "rest-api" || r.kind === "site").map((r) => [r.envKey, r.id]));
1026
1458
  const appById = new Map(apps.map((app) => [app.id, app]));
1027
1459
  /**
@@ -1078,7 +1510,7 @@ function composeStack(input) {
1078
1510
  const values = valuesFor(app, keys);
1079
1511
  const trusted = (0, _geekmidas_manifest.provideKey)(app.id, "trustedOrigins");
1080
1512
  if (keys.has(trusted)) {
1081
- const internal = (byId.get(app.id)?.callers ?? []).map((caller) => appById.get(caller)).filter((caller) => caller?.kind === "rest-api").map((caller) => `http://${caller.name}:${caller.port}`);
1513
+ 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}`);
1082
1514
  const origins = [...(values[trusted] ?? "").split(",").filter(Boolean), ...internal];
1083
1515
  values[trusted] = [...new Set(origins)].join(",");
1084
1516
  }
@@ -1112,6 +1544,14 @@ function composeStack(input) {
1112
1544
  };
1113
1545
  for (const [key, value] of Object.entries(worker.env)) if (/[\r\n]/.test(value)) throw new EnvValueMultiline(worker.name, key);
1114
1546
  }
1547
+ const deployedTls = certificate ? {
1548
+ kind: "files",
1549
+ ...proxy === "caddy" ? {
1550
+ certFile: `${CADDY_TLS_DIR}/cert.pem`,
1551
+ keyFile: `${CADDY_TLS_DIR}/key.pem`
1552
+ } : edgeCertificatePaths(project)
1553
+ } : { kind: "acme" };
1554
+ const tls = local ? { kind: "internal" } : deployedTls;
1115
1555
  const layout = input.layout ?? defaultLayout(workspace.root);
1116
1556
  const compose = stackFile({
1117
1557
  project,
@@ -1128,20 +1568,34 @@ function composeStack(input) {
1128
1568
  composeDir: (0, node_path.join)(workspace.root, stackDir(stage)),
1129
1569
  buildRoot: layout.buildRoot,
1130
1570
  workspaceRoot: workspace.root,
1131
- envFiles: !input.buildOnly
1571
+ envFiles: !input.buildOnly,
1572
+ proxy,
1573
+ edge: new Map([...edgeServices].map((service) => [service, hostOf(service)])),
1574
+ tls: certificate !== void 0
1132
1575
  });
1133
- const caddyfile = edgeCaddyfile([
1576
+ const routes = [
1134
1577
  ...apps.map((app) => ({
1578
+ name: app.name,
1135
1579
  host: app.host,
1136
- upstream: `${app.name}:${app.port}`
1580
+ upstreams: [{
1581
+ service: app.name,
1582
+ port: app.port
1583
+ }],
1584
+ streaming: true,
1585
+ health: app.kind === "site" ? "/" : "/health"
1137
1586
  })),
1138
- ...[...fileServers.values()].map(({ site }) => site),
1587
+ ...[...fileServers.values()].map(({ route }) => route),
1139
1588
  ...logs?.host && logs.public ? [{
1589
+ name: LOGS_SERVICE,
1140
1590
  host: logs.host,
1141
- upstream: `${LOGS_SERVICE}:${require_workspace.LOGS_PORT}`,
1591
+ upstreams: [{
1592
+ service: LOGS_SERVICE,
1593
+ port: require_workspace.LOGS_PORT
1594
+ }],
1595
+ streaming: true,
1142
1596
  allow: logs.public.allow
1143
1597
  }] : []
1144
- ], { local });
1598
+ ];
1145
1599
  const dockerfiles = {};
1146
1600
  for (const app of apps) {
1147
1601
  if (!app.build) continue;
@@ -1173,7 +1627,13 @@ function composeStack(input) {
1173
1627
  workers,
1174
1628
  infra,
1175
1629
  compose,
1176
- caddyfile,
1630
+ proxy,
1631
+ routes,
1632
+ ...proxy === "caddy" ? { caddyfile: edgeCaddyfile(routes, { tls }) } : { traefik: traefikDynamicFile(routes, {
1633
+ project,
1634
+ tls: deployedTls
1635
+ }) },
1636
+ ...certificate ? { tls: certificate } : {},
1177
1637
  dockerfiles,
1178
1638
  plan,
1179
1639
  credential,
@@ -1292,8 +1752,10 @@ function stackFile(options) {
1292
1752
  const services = {};
1293
1753
  const volumes = {
1294
1754
  ...derived.volumes,
1295
- "caddy-data": {},
1296
- "caddy-config": {},
1755
+ ...options.proxy === "caddy" ? {
1756
+ "caddy-data": {},
1757
+ "caddy-config": {}
1758
+ } : {},
1297
1759
  ...options.logs ? { "openobserve-data": {} } : {}
1298
1760
  };
1299
1761
  for (const name of infra) {
@@ -1359,14 +1821,15 @@ function stackFile(options) {
1359
1821
  ...infra.length ? { depends_on: Object.fromEntries(infra.map((name) => [name, HEALTHY])) } : {},
1360
1822
  healthcheck: probe(worker.port, "/health")
1361
1823
  };
1362
- services.caddy = {
1824
+ if (options.proxy === "caddy") services.caddy = {
1363
1825
  image: require_stale.DEFAULT_IMAGES.caddy,
1364
1826
  restart: "unless-stopped",
1365
1827
  ports: [`${options.https}:443`, `${options.http}:80`],
1366
1828
  volumes: [
1367
1829
  "./Caddyfile:/etc/caddy/Caddyfile:ro",
1368
1830
  "caddy-data:/data",
1369
- "caddy-config:/config"
1831
+ "caddy-config:/config",
1832
+ ...options.tls ? [`./tls:${CADDY_TLS_DIR}:ro`] : []
1370
1833
  ],
1371
1834
  depends_on: Object.fromEntries(apps.map((app) => [app.name, HEALTHY])),
1372
1835
  healthcheck: {
@@ -1380,6 +1843,14 @@ function stackFile(options) {
1380
1843
  retries: 5
1381
1844
  }
1382
1845
  };
1846
+ for (const [service, alias] of options.edge) {
1847
+ const definition = services[service];
1848
+ if (!definition) continue;
1849
+ definition.networks = {
1850
+ default: { aliases: [alias] },
1851
+ edge: { aliases: [alias] }
1852
+ };
1853
+ }
1383
1854
  for (const service of Object.values(services)) {
1384
1855
  if (!options.envFiles) delete service.env_file;
1385
1856
  service.logging = {
@@ -1390,7 +1861,11 @@ function stackFile(options) {
1390
1861
  return {
1391
1862
  name: project,
1392
1863
  services,
1393
- volumes
1864
+ volumes,
1865
+ ...options.edge.size > 0 ? { networks: { edge: {
1866
+ name: EDGE_NETWORK,
1867
+ external: true
1868
+ } } } : {}
1394
1869
  };
1395
1870
  }
1396
1871
  /**
@@ -1437,12 +1912,12 @@ var HealthRequestTimedOut = class extends Error {
1437
1912
  }
1438
1913
  };
1439
1914
  /** The real probe: one HTTPS GET, the certificate verified. */
1440
- const httpsProbe = ({ url, ca, connectTo, timeoutMs, signal }) => {
1915
+ const httpsProbe = ({ url, ca, connectTo, connectPort, timeoutMs, signal }) => {
1441
1916
  const target = new URL(url);
1442
1917
  return new Promise((resolve, reject) => {
1443
1918
  const req = (0, node_https.request)({
1444
1919
  host: connectTo ?? target.hostname,
1445
- port: target.port || 443,
1920
+ port: connectPort ?? (target.port || 443),
1446
1921
  servername: target.hostname,
1447
1922
  path: `${target.pathname}${target.search}`,
1448
1923
  method: "GET",
@@ -1468,10 +1943,13 @@ function isHealthy(status) {
1468
1943
  var ComposeAppsUnhealthy = class extends Error {
1469
1944
  project;
1470
1945
  apps;
1471
- constructor(project, apps) {
1472
- super(`${project} started, but ${apps.length === 1 ? "this app does" : "these apps do"} not answer through Caddy:\n` + apps.map(({ url, last }) => ` - ${url}: ${last}`).join("\n") + `\nSee why with \`docker compose -p ${project} logs caddy ${apps.map((a) => a.app).join(" ")}\`.`);
1946
+ proxy;
1947
+ constructor(project, apps, proxy = "caddy") {
1948
+ const names = apps.map((a) => a.app).join(" ");
1949
+ 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}\`.`));
1473
1950
  this.project = project;
1474
1951
  this.apps = apps;
1952
+ this.proxy = proxy;
1475
1953
  this.name = "ComposeAppsUnhealthy";
1476
1954
  }
1477
1955
  };
@@ -1651,6 +2129,9 @@ async function validateCompose(ctx, deps, options = {}) {
1651
2129
  if (mode === "build") assertRedisClient(workspace, composed);
1652
2130
  const stack = options.pin ? withPinnedImages(composed, options.pin.file, options.pin.digests) : composed;
1653
2131
  if (mode === "pull" && !ctx.dryRun) await assertImagesExist(deps.docker, tag, [...stack.apps, ...stack.workers]);
2132
+ if (stack.tls && !push) {
2133
+ for (const file of [stack.tls.certFile, stack.tls.keyFile]) if (!(0, node_fs.existsSync)(file)) throw new require_workspace.ComposeTlsFileMissing(stage, file);
2134
+ }
1654
2135
  if (stack.redis && !stack.local) ctx.secrets.mask(stack.redis.password);
1655
2136
  if (stack.logs && (!stack.local || stack.logs.passwordFromSecrets)) {
1656
2137
  ctx.secrets.mask(stack.logs.password);
@@ -1819,7 +2300,7 @@ async function planCompose(ctx, run) {
1819
2300
  });
1820
2301
  }
1821
2302
  if (!run.push) planned({
1822
- key: "service:caddy",
2303
+ key: run.stack.proxy === "caddy" ? "service:caddy" : `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
1823
2304
  resourceType: "service",
1824
2305
  action: "ensure"
1825
2306
  });
@@ -1836,8 +2317,35 @@ async function provisionCompose(ctx, run, deps) {
1836
2317
  await ctx.secrets.write(run.secrets);
1837
2318
  ctx.logger.info(`🔑 Generated for "${ctx.stage}" (${ctx.secrets.store}): ${run.generated.join(", ")}`);
1838
2319
  }
2320
+ const ports = edgePorts(deps.env);
2321
+ await assertEdgePorts(deps.docker, {
2322
+ project: stack.project,
2323
+ proxy: stack.proxy,
2324
+ ports
2325
+ });
1839
2326
  run.files = await writeStack(ctx.cwd, run.dir, stack);
1840
2327
  printPlan(ctx, run);
2328
+ if (stack.proxy === "traefik") {
2329
+ const dir = edgeDir(deps.env);
2330
+ ctx.logger.info(`\n🌐 Starting the shared edge (${EDGE_PROJECT}) from ${dir}…`);
2331
+ run.files.push(...await ensureEdge(deps.docker, {
2332
+ dir,
2333
+ ports,
2334
+ logging: {
2335
+ driver: LOG_ROTATION.driver,
2336
+ options: { ...LOG_ROTATION.options }
2337
+ },
2338
+ ...ref.output ? { output: ref.output } : {},
2339
+ ...ref.signal ? { signal: ref.signal } : {}
2340
+ }));
2341
+ applied(ctx, run, {
2342
+ key: `service:${EDGE_PROJECT}/${EDGE_SERVICE}`,
2343
+ resourceType: "service",
2344
+ action: "ensure",
2345
+ id: `${EDGE_PROJECT}/${EDGE_SERVICE}`,
2346
+ via: "found"
2347
+ });
2348
+ }
1841
2349
  if (stack.infra.length > 0) {
1842
2350
  ctx.logger.info(`\n🗄️ Starting ${stack.infra.join(", ")}…`);
1843
2351
  await deps.docker.up(ref, stack.infra);
@@ -1947,6 +2455,12 @@ async function releaseCompose(ctx, run, deps) {
1947
2455
  if (run.push) return;
1948
2456
  ctx.logger.info("\n🚀 Starting the stack…");
1949
2457
  await deps.docker.up(ref);
2458
+ const edge = edgeDir(deps.env);
2459
+ if (stack.proxy === "traefik" && stack.traefik) {
2460
+ const written = await writeEdgeRoutes(edge, stack.project, stack.traefik, stack.tls);
2461
+ run.files.push(...written);
2462
+ ctx.logger.info(`🌐 Registered ${stack.routes.length} route(s) with ${EDGE_PROJECT}: ${written.at(-1)}`);
2463
+ } else await removeEdgeRoutes(edge, stack.project);
1950
2464
  if (stack.local) await deps.docker.copyOut(ref, "caddy", "/data/caddy/pki/authorities/local/root.crt", caFile(run)).catch(() => {});
1951
2465
  await recordImages(ctx, run);
1952
2466
  for (const app of stack.apps) {
@@ -2005,10 +2519,14 @@ async function verifyCompose(ctx, run, deps) {
2005
2519
  const { stack } = run;
2006
2520
  if (run.push) return;
2007
2521
  const ca = stack.local ? await (0, node_fs_promises.readFile)(caFile(run), "utf-8").catch(() => void 0) : void 0;
2008
- ctx.logger.info("\n🩺 Checking each app through Caddy…");
2522
+ ctx.logger.info(`\n🩺 Checking each app through ${stack.proxy === "caddy" ? "Caddy" : "the shared edge"}…`);
2523
+ const edge = stack.local || stack.proxy === "traefik" ? {
2524
+ connectTo: "127.0.0.1",
2525
+ ...stack.local ? {} : { connectPort: edgePorts(deps.env).https }
2526
+ } : void 0;
2009
2527
  const results = await Promise.all(stack.apps.map((app) => checkApp(ctx, app, deps, {
2010
2528
  ca,
2011
- local: stack.local
2529
+ edge
2012
2530
  })));
2013
2531
  results.push(...await Promise.all(stack.workers.map((worker) => checkContainer(ctx, run, deps, worker.name))));
2014
2532
  if (stack.logs) results.push(await checkContainer(ctx, run, deps, LOGS_SERVICE));
@@ -2017,7 +2535,7 @@ async function verifyCompose(ctx, run, deps) {
2017
2535
  url,
2018
2536
  last
2019
2537
  }));
2020
- if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down);
2538
+ if (down.length > 0) throw new ComposeAppsUnhealthy(stack.project, down, stack.proxy);
2021
2539
  if (stack.logs) reportLogs(ctx, stack.logs, stack.local);
2022
2540
  }
2023
2541
  /**
@@ -2096,7 +2614,7 @@ async function checkApp(ctx, app, deps, options) {
2096
2614
  status = await deps.probe({
2097
2615
  url,
2098
2616
  ...options.ca ? { ca: options.ca } : {},
2099
- ...options.local ? { connectTo: "127.0.0.1" } : {},
2617
+ ...options.edge,
2100
2618
  timeoutMs: 1e4,
2101
2619
  signal: ctx.signal
2102
2620
  });
@@ -2197,7 +2715,22 @@ async function writeStack(root, dir, stack) {
2197
2715
  files.push(path);
2198
2716
  };
2199
2717
  await write((0, node_path.join)(dir, "docker-compose.yml"), composeYaml(stack));
2200
- await write((0, node_path.join)(dir, "Caddyfile"), stack.caddyfile);
2718
+ if (stack.caddyfile !== void 0) {
2719
+ await write((0, node_path.join)(dir, "Caddyfile"), stack.caddyfile);
2720
+ await (0, node_fs_promises.rm)((0, node_path.join)(dir, "traefik.yml"), { force: true });
2721
+ } else await (0, node_fs_promises.rm)((0, node_path.join)(dir, "Caddyfile"), { force: true });
2722
+ if (stack.traefik !== void 0) await write((0, node_path.join)(dir, "traefik.yml"), stack.traefik);
2723
+ if (stack.proxy === "caddy" && stack.tls) {
2724
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(dir, "tls"), {
2725
+ recursive: true,
2726
+ mode: 448
2727
+ });
2728
+ await write((0, node_path.join)(dir, "tls", "cert.pem"), await (0, node_fs_promises.readFile)(stack.tls.certFile, "utf-8"));
2729
+ await write((0, node_path.join)(dir, "tls", "key.pem"), await (0, node_fs_promises.readFile)(stack.tls.keyFile, "utf-8"), 384);
2730
+ } else await (0, node_fs_promises.rm)((0, node_path.join)(dir, "tls"), {
2731
+ recursive: true,
2732
+ force: true
2733
+ });
2201
2734
  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);
2202
2735
  if (stack.logs && stack.compose.services["openobserve"]?.env_file) await write((0, node_path.join)(dir, `${LOGS_SERVICE}.env`), envFile(stack.logs.env), 384);
2203
2736
  if (stack.redis && stack.compose.services["redis"]?.env_file) await write((0, node_path.join)(dir, `${REDIS_SERVICE}.env`), envFile(stack.redis.env), 384);
@@ -2209,7 +2742,7 @@ async function writeStack(root, dir, stack) {
2209
2742
  function composeYaml(stack) {
2210
2743
  const stage = ` --stage ${stack.stage}`;
2211
2744
  return `# Generated by gkm compose from the construct manifest — do not edit.
2212
- # The ${stack.stage} stage's APIs and sites behind one Caddy, and its workers.
2745
+ # The ${stack.stage} stage's APIs and sites behind ${stack.proxy === "caddy" ? "one Caddy" : `the shared Traefik edge (${EDGE_PROJECT})`}, and its workers.
2213
2746
  # Each backend and worker reads exactly the keys in its own env file beside
2214
2747
  # this one.
2215
2748
  #
@@ -2305,6 +2838,12 @@ Object.defineProperty(exports, "ComposePushNeedsBuild", {
2305
2838
  return ComposePushNeedsBuild;
2306
2839
  }
2307
2840
  });
2841
+ Object.defineProperty(exports, "EDGE_PROJECT", {
2842
+ enumerable: true,
2843
+ get: function() {
2844
+ return EDGE_PROJECT;
2845
+ }
2846
+ });
2308
2847
  Object.defineProperty(exports, "composeProject", {
2309
2848
  enumerable: true,
2310
2849
  get: function() {
@@ -2329,6 +2868,12 @@ Object.defineProperty(exports, "dockerCompose", {
2329
2868
  return dockerCompose;
2330
2869
  }
2331
2870
  });
2871
+ Object.defineProperty(exports, "edgeDir", {
2872
+ enumerable: true,
2873
+ get: function() {
2874
+ return edgeDir;
2875
+ }
2876
+ });
2332
2877
  Object.defineProperty(exports, "parseDigests", {
2333
2878
  enumerable: true,
2334
2879
  get: function() {
@@ -2341,6 +2886,12 @@ Object.defineProperty(exports, "pinnedRef", {
2341
2886
  return pinnedRef;
2342
2887
  }
2343
2888
  });
2889
+ Object.defineProperty(exports, "removeEdgeRoutes", {
2890
+ enumerable: true,
2891
+ get: function() {
2892
+ return removeEdgeRoutes;
2893
+ }
2894
+ });
2344
2895
  Object.defineProperty(exports, "stackDir", {
2345
2896
  enumerable: true,
2346
2897
  get: function() {
@@ -2354,4 +2905,4 @@ Object.defineProperty(exports, "stackOverrideFile", {
2354
2905
  }
2355
2906
  });
2356
2907
 
2357
- //# sourceMappingURL=compose-CePlrbUw.cjs.map
2908
+ //# sourceMappingURL=compose-B7MC19eC.cjs.map