@geekmidas/cli 10.0.0-alpha.64 → 10.0.0-alpha.65
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.
- package/README.md +1 -1
- package/dist/{HostingerProvider-Bx2lHHvu.cjs → HostingerProvider-Dlmbfass.cjs} +3 -3
- package/dist/{HostingerProvider-Bx2lHHvu.cjs.map → HostingerProvider-Dlmbfass.cjs.map} +1 -1
- package/dist/{HostingerProvider-Cd4aS5Kj.mjs → HostingerProvider-x9gQTAGZ.mjs} +2 -2
- package/dist/{HostingerProvider-Cd4aS5Kj.mjs.map → HostingerProvider-x9gQTAGZ.mjs.map} +1 -1
- package/dist/{LegacyStateStore-C2abV49N.cjs → LegacyStateStore-BGoo__sO.cjs} +2 -2
- package/dist/{LegacyStateStore-C2abV49N.cjs.map → LegacyStateStore-BGoo__sO.cjs.map} +1 -1
- package/dist/{LegacyStateStore-DIgkGaUP.mjs → LegacyStateStore-BUu1nQ5u.mjs} +2 -2
- package/dist/{LegacyStateStore-DIgkGaUP.mjs.map → LegacyStateStore-BUu1nQ5u.mjs.map} +1 -1
- package/dist/{LocalStateStore-DiJqKyPy.cjs → LocalStateStore-93urXyQe.cjs} +2 -2
- package/dist/{LocalStateStore-DiJqKyPy.cjs.map → LocalStateStore-93urXyQe.cjs.map} +1 -1
- package/dist/{LocalStateStore-Cy1ZBW7U.mjs → LocalStateStore-BRhMQRuy.mjs} +2 -2
- package/dist/{LocalStateStore-Cy1ZBW7U.mjs.map → LocalStateStore-BRhMQRuy.mjs.map} +1 -1
- package/dist/{S3StateStore-Ds0V1Lgm.cjs → S3StateStore-F4dxw6kS.cjs} +2 -2
- package/dist/{S3StateStore-Ds0V1Lgm.cjs.map → S3StateStore-F4dxw6kS.cjs.map} +1 -1
- package/dist/{S3StateStore-D3x6ivBL.mjs → S3StateStore-pw1GhWwt.mjs} +2 -2
- package/dist/{S3StateStore-D3x6ivBL.mjs.map → S3StateStore-pw1GhWwt.mjs.map} +1 -1
- package/dist/{SSMStateStore-CLipvx47.cjs → SSMStateStore-Bt9acuAF.cjs} +2 -2
- package/dist/{SSMStateStore-CLipvx47.cjs.map → SSMStateStore-Bt9acuAF.cjs.map} +1 -1
- package/dist/{SSMStateStore-DfF174xQ.mjs → SSMStateStore-Dmj7zzFO.mjs} +2 -2
- package/dist/{SSMStateStore-DfF174xQ.mjs.map → SSMStateStore-Dmj7zzFO.mjs.map} +1 -1
- package/dist/{bundler-C8uJf324.cjs → bundler-D6MlIfBT.cjs} +3 -3
- package/dist/{bundler-C8uJf324.cjs.map → bundler-D6MlIfBT.cjs.map} +1 -1
- package/dist/{bundler-DYgm9xsd.mjs → bundler-D_14JLZF.mjs} +3 -3
- package/dist/{bundler-DYgm9xsd.mjs.map → bundler-D_14JLZF.mjs.map} +1 -1
- package/dist/{cli-D3jofJ6j.cjs → cli-BfH1deAT.cjs} +6 -6
- package/dist/{cli-D3jofJ6j.cjs.map → cli-BfH1deAT.cjs.map} +1 -1
- package/dist/{cli-Bogz-zEj.mjs → cli-P56vvrDQ.mjs} +5 -5
- package/dist/{cli-Bogz-zEj.mjs.map → cli-P56vvrDQ.mjs.map} +1 -1
- package/dist/compose-391oEKj1.cjs +1982 -0
- package/dist/compose-391oEKj1.cjs.map +1 -0
- package/dist/compose-DprE3ASm.mjs +1862 -0
- package/dist/compose-DprE3ASm.mjs.map +1 -0
- package/dist/{config-DqNRiQOp.d.mts → config-BonvTW8p.d.mts} +3 -3
- package/dist/{config-Be-4_I6H.d.cts.map → config-BonvTW8p.d.mts.map} +1 -1
- package/dist/{config-Be-4_I6H.d.cts → config-V_X_BMpm.d.cts} +3 -3
- package/dist/{config-DqNRiQOp.d.mts.map → config-V_X_BMpm.d.cts.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.d.cts +3 -3
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/{credentials-B70vmLcm.cjs → credentials-Bzbg23n8.cjs} +176 -3
- package/dist/credentials-Bzbg23n8.cjs.map +1 -0
- package/dist/{credentials-s0wMeZBU.mjs → credentials-Dq1MnWQf.mjs} +128 -3
- package/dist/credentials-Dq1MnWQf.mjs.map +1 -0
- package/dist/{define-CYs0PEfZ.mjs → define-DR8xGYfL.mjs} +5 -1
- package/dist/define-DR8xGYfL.mjs.map +1 -0
- package/dist/{define-zUsP72ym.cjs → define-DzRz8FgH.cjs} +5 -1
- package/dist/define-DzRz8FgH.cjs.map +1 -0
- package/dist/deploy/public.cjs +18 -18
- package/dist/deploy/public.cjs.map +1 -1
- package/dist/deploy/public.d.cts +7 -4
- package/dist/deploy/public.d.cts.map +1 -1
- package/dist/deploy/public.d.mts +7 -4
- package/dist/deploy/public.d.mts.map +1 -1
- package/dist/deploy/public.mjs +11 -11
- package/dist/{deploy-Dc2LBJaK.mjs → deploy-9MBG_QLd.mjs} +8 -7
- package/dist/deploy-9MBG_QLd.mjs.map +1 -0
- package/dist/{deploy-yUcR2OlW.cjs → deploy-B80idPUZ.cjs} +11 -10
- package/dist/deploy-B80idPUZ.cjs.map +1 -0
- package/dist/{deploy-ZRXIPp1c.mjs → deploy-CZ5nlpsu.mjs} +13 -119
- package/dist/deploy-CZ5nlpsu.mjs.map +1 -0
- package/dist/{deploy-55rJkdKz.cjs → deploy-Cy8igpQF.cjs} +39 -145
- package/dist/deploy-Cy8igpQF.cjs.map +1 -0
- package/dist/{dokploy-CepdXuMl.mjs → dokploy-BdtBePjp.mjs} +3 -3
- package/dist/{dokploy-CepdXuMl.mjs.map → dokploy-BdtBePjp.mjs.map} +1 -1
- package/dist/{dokploy-D1d37rvM.cjs → dokploy-iFY8MY-L.cjs} +3 -3
- package/dist/{dokploy-D1d37rvM.cjs.map → dokploy-iFY8MY-L.cjs.map} +1 -1
- package/dist/{encryption-C9X98u2F.cjs → encryption-B1wJwgae.cjs} +5 -5
- package/dist/{encryption-C9X98u2F.cjs.map → encryption-B1wJwgae.cjs.map} +1 -1
- package/dist/{encryption-CKHjMpCr.mjs → encryption-DF_hgIpl.mjs} +4 -4
- package/dist/{encryption-CKHjMpCr.mjs.map → encryption-DF_hgIpl.mjs.map} +1 -1
- package/dist/{github-D-byNI7T.mjs → github-B0YYE98x.mjs} +3 -3
- package/dist/{github-D-byNI7T.mjs.map → github-B0YYE98x.mjs.map} +1 -1
- package/dist/{github-Dd3tMa1u.cjs → github-CYcmTdFs.cjs} +3 -3
- package/dist/{github-Dd3tMa1u.cjs.map → github-CYcmTdFs.cjs.map} +1 -1
- package/dist/{index-CfE9Y885.d.cts → index-DPUAGJaK.d.cts} +16 -3
- package/dist/index-DPUAGJaK.d.cts.map +1 -0
- package/dist/{index-CJ2qsSpp.d.mts → index-DwKD_8lt.d.mts} +16 -3
- package/dist/index-DwKD_8lt.d.mts.map +1 -0
- package/dist/index.cjs +233 -1667
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +196 -1614
- package/dist/index.mjs.map +1 -1
- package/dist/{local-C7wnrcYK.cjs → local-BdH4XN0E.cjs} +1 -178
- package/dist/local-BdH4XN0E.cjs.map +1 -0
- package/dist/{local-Cd8ZYQG3.mjs → local-CWR4Y_kW.mjs} +3 -126
- package/dist/local-CWR4Y_kW.mjs.map +1 -0
- package/dist/{migrate-B4gngTLe.mjs → migrate-B2qL5wj4.mjs} +6 -5
- package/dist/{migrate-B4gngTLe.mjs.map → migrate-B2qL5wj4.mjs.map} +1 -1
- package/dist/{migrate-tx9-P9uz.cjs → migrate-q4pPAXtO.cjs} +19 -18
- package/dist/{migrate-tx9-P9uz.cjs.map → migrate-q4pPAXtO.cjs.map} +1 -1
- package/dist/openapi.d.cts +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/provider-C9_-45d5.cjs +56 -0
- package/dist/provider-C9_-45d5.cjs.map +1 -0
- package/dist/provider-q4lsYzYG.mjs +45 -0
- package/dist/provider-q4lsYzYG.mjs.map +1 -0
- package/dist/reconcile/public.d.cts +1 -1
- package/dist/reconcile/public.d.mts +1 -1
- package/dist/resolve-DLkIXTct.mjs +262 -0
- package/dist/resolve-DLkIXTct.mjs.map +1 -0
- package/dist/resolve-N_i4XNd-.cjs +315 -0
- package/dist/resolve-N_i4XNd-.cjs.map +1 -0
- package/dist/{runtime-CJEYK4Gz.d.mts → runtime-BnD7Nn96.d.cts} +2 -2
- package/dist/{runtime-CJEYK4Gz.d.mts.map → runtime-BnD7Nn96.d.cts.map} +1 -1
- package/dist/{runtime-Cjq1jlVX.d.cts → runtime-j-tmFL65.d.mts} +2 -2
- package/dist/{runtime-Cjq1jlVX.d.cts.map → runtime-j-tmFL65.d.mts.map} +1 -1
- package/dist/sniffer-BSwaL-dX.cjs +2236 -0
- package/dist/sniffer-BSwaL-dX.cjs.map +1 -0
- package/dist/sniffer-BZ-OJO4Y.mjs +2068 -0
- package/dist/sniffer-BZ-OJO4Y.mjs.map +1 -0
- package/dist/{sst-Cper040I.mjs → sst-B2HbrDR3.mjs} +4 -4
- package/dist/{sst-Cper040I.mjs.map → sst-B2HbrDR3.mjs.map} +1 -1
- package/dist/{sst-BdALKEas.cjs → sst-DcfsVH6x.cjs} +4 -4
- package/dist/{sst-BdALKEas.cjs.map → sst-DcfsVH6x.cjs.map} +1 -1
- package/dist/{sniffer-49KPbDgq.mjs → state-B8YwmUZU.mjs} +878 -2465
- package/dist/state-B8YwmUZU.mjs.map +1 -0
- package/dist/{sniffer-ByhbEW5A.cjs → state-DF26e_lo.cjs} +811 -2525
- package/dist/state-DF26e_lo.cjs.map +1 -0
- package/dist/{store-D_2ByRtW.cjs → store-CJF1Tqkq.cjs} +2 -2
- package/dist/{store-D_2ByRtW.cjs.map → store-CJF1Tqkq.cjs.map} +1 -1
- package/dist/{store-BaaonhkJ.mjs → store-CLiHnqOY.mjs} +2 -2
- package/dist/{store-BaaonhkJ.mjs.map → store-CLiHnqOY.mjs.map} +1 -1
- package/dist/target/public.cjs +6 -6
- package/dist/target/public.d.cts +2 -2
- package/dist/target/public.d.mts +2 -2
- package/dist/target/public.mjs +3 -3
- package/dist/terminal-Bs5E1oxm.cjs +88 -0
- package/dist/terminal-Bs5E1oxm.cjs.map +1 -0
- package/dist/terminal-CfbiYUbZ.mjs +84 -0
- package/dist/terminal-CfbiYUbZ.mjs.map +1 -0
- package/dist/{types-B_bEQvb9.d.mts → types-BCzMWBb6.d.mts} +43 -11
- package/dist/types-BCzMWBb6.d.mts.map +1 -0
- package/dist/{types-DkrDOMxw.d.cts → types-ByMWkXKP.d.cts} +43 -11
- package/dist/types-ByMWkXKP.d.cts.map +1 -0
- package/dist/workspace/index.cjs +3 -1
- package/dist/workspace/index.d.cts +3 -3
- package/dist/workspace/index.d.mts +3 -3
- package/dist/workspace/index.mjs +2 -2
- package/dist/{workspace-BwgWJK7h.cjs → workspace-BewAHZIo.cjs} +38 -3
- package/dist/workspace-BewAHZIo.cjs.map +1 -0
- package/dist/{workspace-Bwit4q9O.mjs → workspace-C06_pW4g.mjs} +27 -4
- package/dist/workspace-C06_pW4g.mjs.map +1 -0
- package/package.json +13 -13
- package/dist/credentials-B70vmLcm.cjs.map +0 -1
- package/dist/credentials-s0wMeZBU.mjs.map +0 -1
- package/dist/define-CYs0PEfZ.mjs.map +0 -1
- package/dist/define-zUsP72ym.cjs.map +0 -1
- package/dist/deploy-55rJkdKz.cjs.map +0 -1
- package/dist/deploy-Dc2LBJaK.mjs.map +0 -1
- package/dist/deploy-ZRXIPp1c.mjs.map +0 -1
- package/dist/deploy-yUcR2OlW.cjs.map +0 -1
- package/dist/index-CJ2qsSpp.d.mts.map +0 -1
- package/dist/index-CfE9Y885.d.cts.map +0 -1
- package/dist/local-C7wnrcYK.cjs.map +0 -1
- package/dist/local-Cd8ZYQG3.mjs.map +0 -1
- package/dist/resolve-BXsNQjMR.cjs +0 -220
- package/dist/resolve-BXsNQjMR.cjs.map +0 -1
- package/dist/resolve-DZ2IJ0qY.mjs +0 -173
- package/dist/resolve-DZ2IJ0qY.mjs.map +0 -1
- package/dist/runtime-BGNDrHzh.cjs +0 -163
- package/dist/runtime-BGNDrHzh.cjs.map +0 -1
- package/dist/runtime-Cmn-FeYO.mjs +0 -134
- package/dist/runtime-Cmn-FeYO.mjs.map +0 -1
- package/dist/sniffer-49KPbDgq.mjs.map +0 -1
- package/dist/sniffer-ByhbEW5A.cjs.map +0 -1
- package/dist/terminal-Bdv--jhY.cjs +0 -481
- package/dist/terminal-Bdv--jhY.cjs.map +0 -1
- package/dist/terminal-D7Ntz6WE.mjs +0 -440
- package/dist/terminal-D7Ntz6WE.mjs.map +0 -1
- package/dist/types-B_bEQvb9.d.mts.map +0 -1
- package/dist/types-DkrDOMxw.d.cts.map +0 -1
- package/dist/workspace-BwgWJK7h.cjs.map +0 -1
- package/dist/workspace-Bwit4q9O.mjs.map +0 -1
|
@@ -1,27 +1,23 @@
|
|
|
1
1
|
import { n as __require, t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { d as output, r as discover
|
|
4
|
-
import { i as activeSandbox } from "./sandbox-Dm247NGx.mjs";
|
|
2
|
+
import { s as run$1 } from "./local-CWR4Y_kW.mjs";
|
|
3
|
+
import { d as output, r as discover } from "./discover-LMrqsWSU.mjs";
|
|
5
4
|
import { t as appKey } from "./derive-B4vDpzgP.mjs";
|
|
6
|
-
import {
|
|
5
|
+
import { O as TEST_STAGE, h as getPublicEnvPrefix, n as allConstructGlobs } from "./workspace-C06_pW4g.mjs";
|
|
7
6
|
import { ConfigNotFound, NotInAnApp, loadConfig, loadWorkspaceAppInfo, loadWorkspaceConfig } from "./config.mjs";
|
|
8
7
|
import { i as toEmbeddableSecrets } from "./storage-BzaUxmqe.mjs";
|
|
9
|
-
import { i as FileSecretsStore, n as secretsStoreFor } from "./store-
|
|
10
|
-
import {
|
|
8
|
+
import { i as FileSecretsStore, n as secretsStoreFor } from "./store-CLiHnqOY.mjs";
|
|
9
|
+
import { c as runtimeOf } from "./resolve-DLkIXTct.mjs";
|
|
11
10
|
import { i as DEFAULT_STORAGE, n as DEFAULT_CACHE, r as DEFAULT_EVENTS$1, t as readFakes } from "./fakes-C9RiT6XG.mjs";
|
|
12
11
|
import { basename, dirname, join, parse, resolve } from "node:path";
|
|
13
|
-
import { stdin, stdout } from "node:process";
|
|
14
|
-
import * as readline from "node:readline/promises";
|
|
15
12
|
import { copyFileSync, existsSync, readFileSync, unlinkSync } from "node:fs";
|
|
16
13
|
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
17
|
-
import {
|
|
14
|
+
import { networkInterfaces } from "node:os";
|
|
18
15
|
import { promisify } from "node:util";
|
|
19
16
|
import { DEFAULT_POSTGRES_VERSION, cacheTable, cookieDomain, dependenciesOf, dependentsOf, externalApiUrl, kebabCase, mobileOrigins, provideKey, providedKeyFor, provisionOrder, publicEnvFor, schemeBase } from "@geekmidas/manifest";
|
|
20
|
-
import { fileURLToPath } from "node:url";
|
|
21
17
|
import { execFile, spawn } from "node:child_process";
|
|
22
18
|
import { createServer } from "node:net";
|
|
23
19
|
import { config } from "dotenv";
|
|
24
|
-
import {
|
|
20
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
25
21
|
import { formatKeyring, generateKeyring } from "@geekmidas/constructs/encryption";
|
|
26
22
|
import { ownerRole, readerRole, roleStatements } from "@geekmidas/db/pg/roles";
|
|
27
23
|
import * as snsUrl from "@geekmidas/events/sns/url";
|
|
@@ -32,191 +28,6 @@ import { CreateQueueCommand, GetQueueUrlCommand, SQSClient } from "@aws-sdk/clie
|
|
|
32
28
|
import { Client } from "pg";
|
|
33
29
|
import { stringify } from "yaml";
|
|
34
30
|
import { cacheTableStatements } from "@geekmidas/cache/postgres";
|
|
35
|
-
//#region src/prompt.ts
|
|
36
|
-
/**
|
|
37
|
-
* Asking the person at the terminal.
|
|
38
|
-
*
|
|
39
|
-
* CLI layer only: a command's action may prompt, nothing it calls may. A
|
|
40
|
-
* library call (`deploy()`) that needs something it was not given raises a
|
|
41
|
-
* named error instead, and the command decides whether to ask.
|
|
42
|
-
*/
|
|
43
|
-
/** A prompt was needed with no terminal to ask at. */
|
|
44
|
-
var PromptNeedsTerminal = class extends Error {
|
|
45
|
-
question;
|
|
46
|
-
instead;
|
|
47
|
-
constructor(question, instead) {
|
|
48
|
-
super(`Interactive input required. ${instead}`);
|
|
49
|
-
this.question = question;
|
|
50
|
-
this.instead = instead;
|
|
51
|
-
this.name = "PromptNeedsTerminal";
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
/** Whether there is a person at a terminal to ask. */
|
|
55
|
-
function canPrompt() {
|
|
56
|
-
return process.stdin.isTTY === true;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Ask `message` and resolve with the line typed — without echoing it when
|
|
60
|
-
* `hidden`. Ctrl+C at a hidden prompt exits, as it would anywhere else in a
|
|
61
|
-
* terminal program: raw mode has taken the signal away from the shell.
|
|
62
|
-
*/
|
|
63
|
-
async function prompt(message, options) {
|
|
64
|
-
if (!canPrompt()) throw new PromptNeedsTerminal(message, options.instead);
|
|
65
|
-
if (options.hidden) {
|
|
66
|
-
process.stdout.write(message);
|
|
67
|
-
return new Promise((resolve, reject) => {
|
|
68
|
-
let value = "";
|
|
69
|
-
const cleanup = () => {
|
|
70
|
-
process.stdin.setRawMode(false);
|
|
71
|
-
process.stdin.pause();
|
|
72
|
-
process.stdin.removeListener("data", onData);
|
|
73
|
-
process.stdin.removeListener("error", onError);
|
|
74
|
-
};
|
|
75
|
-
const onError = (err) => {
|
|
76
|
-
cleanup();
|
|
77
|
-
reject(err);
|
|
78
|
-
};
|
|
79
|
-
const onData = (char) => {
|
|
80
|
-
const c = char.toString();
|
|
81
|
-
if (c === "\n" || c === "\r") {
|
|
82
|
-
cleanup();
|
|
83
|
-
process.stdout.write("\n");
|
|
84
|
-
resolve(value);
|
|
85
|
-
} else if (c === "") {
|
|
86
|
-
cleanup();
|
|
87
|
-
process.stdout.write("\n");
|
|
88
|
-
process.exit(1);
|
|
89
|
-
} else if (c === "" || c === "\b") {
|
|
90
|
-
if (value.length > 0) value = value.slice(0, -1);
|
|
91
|
-
} else value += c;
|
|
92
|
-
};
|
|
93
|
-
process.stdin.setRawMode(true);
|
|
94
|
-
process.stdin.resume();
|
|
95
|
-
process.stdin.on("data", onData);
|
|
96
|
-
process.stdin.on("error", onError);
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
const rl = readline.createInterface({
|
|
100
|
-
input: stdin,
|
|
101
|
-
output: stdout
|
|
102
|
-
});
|
|
103
|
-
try {
|
|
104
|
-
return await rl.question(message);
|
|
105
|
-
} finally {
|
|
106
|
-
rl.close();
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
//#endregion
|
|
110
|
-
//#region src/auth/index.ts
|
|
111
|
-
const logger$2 = console;
|
|
112
|
-
/**
|
|
113
|
-
* Validate Dokploy token by making a test API call
|
|
114
|
-
*/
|
|
115
|
-
async function validateDokployToken(endpoint, token) {
|
|
116
|
-
const { DokployApi } = await Promise.resolve().then(() => dokploy_api_exports);
|
|
117
|
-
return new DokployApi({
|
|
118
|
-
baseUrl: endpoint,
|
|
119
|
-
token
|
|
120
|
-
}).validateToken();
|
|
121
|
-
}
|
|
122
|
-
/** What answers a login prompt without a terminal. */
|
|
123
|
-
const LOGIN_INSTEAD = "Please provide --token option.";
|
|
124
|
-
/**
|
|
125
|
-
* Login to a service
|
|
126
|
-
*/
|
|
127
|
-
async function loginCommand(options) {
|
|
128
|
-
const { provider, token: providedToken, endpoint: providedEndpoint } = options;
|
|
129
|
-
if (provider === "dokploy") {
|
|
130
|
-
logger$2.log("\n🔐 Logging in to Dokploy...\n");
|
|
131
|
-
let endpoint = providedEndpoint;
|
|
132
|
-
if (!endpoint) endpoint = await prompt("Dokploy URL (e.g., https://dokploy.example.com): ", { instead: LOGIN_INSTEAD });
|
|
133
|
-
endpoint = endpoint.replace(/\/$/, "");
|
|
134
|
-
try {
|
|
135
|
-
new URL(endpoint);
|
|
136
|
-
} catch {
|
|
137
|
-
logger$2.error("Invalid URL format");
|
|
138
|
-
process.exit(1);
|
|
139
|
-
}
|
|
140
|
-
let token = providedToken;
|
|
141
|
-
if (!token) {
|
|
142
|
-
logger$2.log(`\nGenerate a token at: ${endpoint}/settings/profile\n`);
|
|
143
|
-
token = await prompt("API Token: ", {
|
|
144
|
-
hidden: true,
|
|
145
|
-
instead: LOGIN_INSTEAD
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
if (!token) {
|
|
149
|
-
logger$2.error("Token is required");
|
|
150
|
-
process.exit(1);
|
|
151
|
-
}
|
|
152
|
-
logger$2.log("\nValidating credentials...");
|
|
153
|
-
if (!await validateDokployToken(endpoint, token)) {
|
|
154
|
-
logger$2.error("\n✗ Invalid credentials. Please check your token and try again.");
|
|
155
|
-
process.exit(1);
|
|
156
|
-
}
|
|
157
|
-
await storeDokployCredentials(token, endpoint);
|
|
158
|
-
logger$2.log("\n✓ Successfully logged in to Dokploy!");
|
|
159
|
-
logger$2.log(` Endpoint: ${endpoint}`);
|
|
160
|
-
logger$2.log(` Credentials stored in: ${getCredentialsPath()}`);
|
|
161
|
-
logger$2.log("\nYou can now use deploy commands without setting DOKPLOY_API_TOKEN.");
|
|
162
|
-
}
|
|
163
|
-
if (provider === "hostinger") {
|
|
164
|
-
logger$2.log("\n🔐 Logging in to Hostinger...\n");
|
|
165
|
-
let token = providedToken;
|
|
166
|
-
if (!token) {
|
|
167
|
-
logger$2.log("\nGenerate a token at: https://hpanel.hostinger.com/profile/api\n");
|
|
168
|
-
token = await prompt("API Token: ", {
|
|
169
|
-
hidden: true,
|
|
170
|
-
instead: LOGIN_INSTEAD
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
if (!token) {
|
|
174
|
-
logger$2.error("Token is required");
|
|
175
|
-
process.exit(1);
|
|
176
|
-
}
|
|
177
|
-
await storeHostingerToken(token);
|
|
178
|
-
logger$2.log("\n✓ Hostinger token stored.");
|
|
179
|
-
logger$2.log(` Credentials stored in: ${getCredentialsPath()}`);
|
|
180
|
-
logger$2.log(" Not validated here: every DNS endpoint is scoped to a domain, so the\n first deploy that touches DNS is where a bad token reports itself.");
|
|
181
|
-
logger$2.log("\nYou can now use it as a DNS provider without setting HOSTINGER_API_TOKEN.");
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Logout from a service
|
|
186
|
-
*/
|
|
187
|
-
async function logoutCommand(options) {
|
|
188
|
-
const { provider = "dokploy" } = options;
|
|
189
|
-
if (provider === "all") {
|
|
190
|
-
if (await removeDokployCredentials()) logger$2.log("\n✓ Logged out from all services");
|
|
191
|
-
else logger$2.log("\nNo stored credentials found");
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
if (provider === "dokploy") {
|
|
195
|
-
if (await removeDokployCredentials()) logger$2.log("\n✓ Logged out from Dokploy");
|
|
196
|
-
else logger$2.log("\nNo Dokploy credentials found");
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Show current login status
|
|
201
|
-
*/
|
|
202
|
-
async function whoamiCommand() {
|
|
203
|
-
logger$2.log("\n📋 Current credentials:\n");
|
|
204
|
-
const dokploy = await getDokployCredentials();
|
|
205
|
-
if (dokploy) {
|
|
206
|
-
logger$2.log(" Dokploy:");
|
|
207
|
-
logger$2.log(` Endpoint: ${dokploy.endpoint}`);
|
|
208
|
-
logger$2.log(` Token: ${maskToken(dokploy.token)}`);
|
|
209
|
-
} else logger$2.log(" Dokploy: Not logged in");
|
|
210
|
-
logger$2.log(`\n Credentials file: ${getCredentialsPath()}`);
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Mask a token for display
|
|
214
|
-
*/
|
|
215
|
-
function maskToken(token) {
|
|
216
|
-
if (token.length <= 8) return "****";
|
|
217
|
-
return `${token.slice(0, 4)}...${token.slice(-4)}`;
|
|
218
|
-
}
|
|
219
|
-
//#endregion
|
|
220
31
|
//#region src/credentials/index.ts
|
|
221
32
|
const logger$1 = console;
|
|
222
33
|
/**
|
|
@@ -453,17 +264,6 @@ async function prepareEntryCredentials(options) {
|
|
|
453
264
|
};
|
|
454
265
|
}
|
|
455
266
|
//#endregion
|
|
456
|
-
//#region src/workspace/client-generator.ts
|
|
457
|
-
/**
|
|
458
|
-
* Normalize routes to an array of patterns.
|
|
459
|
-
* Handles a glob or a list of them.
|
|
460
|
-
* @internal Exported for use in dev command
|
|
461
|
-
*/
|
|
462
|
-
function normalizeRoutes(routes) {
|
|
463
|
-
if (!routes) return [];
|
|
464
|
-
return Array.isArray(routes) ? routes : [routes];
|
|
465
|
-
}
|
|
466
|
-
//#endregion
|
|
467
267
|
//#region src/reconcile/containers.ts
|
|
468
268
|
/**
|
|
469
269
|
* What gkm knows about each container it can derive.
|
|
@@ -3358,877 +3158,637 @@ function localAddress(port) {
|
|
|
3358
3158
|
return `http://localhost:${port}`;
|
|
3359
3159
|
}
|
|
3360
3160
|
//#endregion
|
|
3361
|
-
//#region src/
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
});
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
/**
|
|
3372
|
-
* Encrypt secrets for embedding in a bundle.
|
|
3373
|
-
* Uses AES-256-GCM with a randomly generated ephemeral key.
|
|
3374
|
-
*
|
|
3375
|
-
* @param secrets - Key-value pairs to encrypt
|
|
3376
|
-
* @returns Encrypted payload with ephemeral master key
|
|
3377
|
-
*/
|
|
3378
|
-
function encryptSecrets(secrets) {
|
|
3379
|
-
const masterKey = randomBytes(KEY_LENGTH);
|
|
3380
|
-
const iv = randomBytes(IV_LENGTH);
|
|
3381
|
-
const plaintext = JSON.stringify(secrets);
|
|
3382
|
-
const cipher = createCipheriv(ALGORITHM, masterKey, iv);
|
|
3383
|
-
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
|
|
3384
|
-
const authTag = cipher.getAuthTag();
|
|
3385
|
-
return {
|
|
3386
|
-
encrypted: Buffer.concat([ciphertext, authTag]).toString("base64"),
|
|
3387
|
-
iv: iv.toString("hex"),
|
|
3388
|
-
masterKey: masterKey.toString("hex")
|
|
3389
|
-
};
|
|
3390
|
-
}
|
|
3161
|
+
//#region src/deploy/domain.ts
|
|
3162
|
+
/** A stage was deployed that `deploy.domains` gives no domain. */
|
|
3163
|
+
var NoDomainForStage = class extends Error {
|
|
3164
|
+
stage;
|
|
3165
|
+
constructor(stage) {
|
|
3166
|
+
super(`No domain for stage "${stage}". Add it to gkm.config.ts: deploy: { domains: { ${stage}: 'example.com' } }.`);
|
|
3167
|
+
this.stage = stage;
|
|
3168
|
+
this.name = "NoDomainForStage";
|
|
3169
|
+
}
|
|
3170
|
+
};
|
|
3391
3171
|
/**
|
|
3392
|
-
*
|
|
3393
|
-
*
|
|
3172
|
+
* The hostname an app answers on for a stage.
|
|
3173
|
+
*
|
|
3174
|
+
* 1. An explicit `app.domain` — a string, or one per stage — wins.
|
|
3175
|
+
* 2. Otherwise from the stage's base domain in `deploy.domains`: the root site
|
|
3176
|
+
* answers on the domain itself, and every other app on
|
|
3177
|
+
* `{subdomain}.{domain}` — its declaration's `subdomain`, or its own name.
|
|
3178
|
+
*
|
|
3179
|
+
* @throws {NoDomainForStage} when `deploy.domains` names no domain for it
|
|
3394
3180
|
*/
|
|
3395
|
-
function
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
}
|
|
3181
|
+
function resolveHost(appName, app, stage, domains, isMainFrontend) {
|
|
3182
|
+
if (app.domain) {
|
|
3183
|
+
if (typeof app.domain === "string") return app.domain;
|
|
3184
|
+
if (app.domain[stage]) return app.domain[stage];
|
|
3185
|
+
}
|
|
3186
|
+
const baseDomain = domains?.[stage];
|
|
3187
|
+
if (!baseDomain) throw new NoDomainForStage(stage);
|
|
3188
|
+
if (isMainFrontend) return baseDomain;
|
|
3189
|
+
return `${app.subdomain ?? appName}.${baseDomain}`;
|
|
3400
3190
|
}
|
|
3401
3191
|
/**
|
|
3402
|
-
*
|
|
3403
|
-
*
|
|
3192
|
+
* Whether this app is the site the base domain points at — see `rootSite`,
|
|
3193
|
+
* which the local edge asks too.
|
|
3404
3194
|
*
|
|
3405
|
-
*
|
|
3406
|
-
* build used — and match it against the one they hold — without the output
|
|
3407
|
-
* carrying a value that decrypts every secret of the stage.
|
|
3195
|
+
* @throws {AmbiguousRootSite} when several sites could be the root and none says it is
|
|
3408
3196
|
*/
|
|
3409
|
-
function
|
|
3410
|
-
|
|
3197
|
+
function isMainFrontendApp(appName, app, allApps) {
|
|
3198
|
+
if (app.type !== "web") return false;
|
|
3199
|
+
return rootSite(Object.entries(allApps).filter(([, a]) => a.type === "web").map(([name, a]) => ({
|
|
3200
|
+
name,
|
|
3201
|
+
root: a.root
|
|
3202
|
+
}))) === appName;
|
|
3411
3203
|
}
|
|
3412
|
-
//#endregion
|
|
3413
|
-
//#region src/deploy/generated.ts
|
|
3414
3204
|
/**
|
|
3415
|
-
*
|
|
3416
|
-
* provision and nobody else issues.
|
|
3417
|
-
*
|
|
3418
|
-
* - **A seed**, which salts every password a deploy derives — a database's
|
|
3419
|
-
* master and roles, a bucket's root user. Derived from repo facts alone
|
|
3420
|
-
* (project, stage, construct id), those passwords were computable by anyone
|
|
3421
|
-
* who could read the repo.
|
|
3422
|
-
* - **Each `secret` construct's value** — an auth server's signing secret —
|
|
3423
|
-
* random, rather than derived.
|
|
3424
|
-
* - **Each `encryption` construct's keyring** — one random key and an index
|
|
3425
|
-
* key. Later keys are added by `gkm encryption:rotate`, never by a deploy.
|
|
3205
|
+
* Get public URL arg names from app dependencies.
|
|
3426
3206
|
*
|
|
3427
|
-
*
|
|
3428
|
-
*
|
|
3429
|
-
* a
|
|
3430
|
-
* `gkm secrets:set` is kept, never replaced.
|
|
3431
|
-
*/
|
|
3432
|
-
/**
|
|
3433
|
-
* The stage's secrets with its seed and every declared `secret`'s value
|
|
3434
|
-
* present, generating what is missing. Pure: the caller writes the result
|
|
3435
|
-
* back to the stage's store when `generated` is not empty.
|
|
3207
|
+
* @param app - The web/mobile app configuration
|
|
3208
|
+
* @returns Array of arg names like 'NEXT_PUBLIC_API_URL', or [] for frameworks
|
|
3209
|
+
* without a public prefix (e.g. Remix).
|
|
3436
3210
|
*/
|
|
3437
|
-
function
|
|
3438
|
-
const
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
if (declaration?.kind !== "secret" && declaration?.kind !== "encryption") continue;
|
|
3442
|
-
const key = declaration.provides?.[0];
|
|
3443
|
-
if (!key || custom[key]) continue;
|
|
3444
|
-
custom[key] = declaration.kind === "encryption" ? generateKeyring() : random();
|
|
3445
|
-
generated.push(key);
|
|
3446
|
-
}
|
|
3447
|
-
const seed = secrets.seed ?? random();
|
|
3448
|
-
if (!secrets.seed) generated.push("seed");
|
|
3449
|
-
return {
|
|
3450
|
-
secrets: generated.length ? {
|
|
3451
|
-
...secrets,
|
|
3452
|
-
seed,
|
|
3453
|
-
custom,
|
|
3454
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3455
|
-
} : secrets,
|
|
3456
|
-
generated
|
|
3457
|
-
};
|
|
3458
|
-
}
|
|
3459
|
-
/** 256 bits, URL-safe. */
|
|
3460
|
-
function random() {
|
|
3461
|
-
return randomBytes(32).toString("base64url");
|
|
3211
|
+
function getPublicUrlArgNames(app) {
|
|
3212
|
+
const prefix = getPublicEnvPrefix(app.framework);
|
|
3213
|
+
if (!prefix) return [];
|
|
3214
|
+
return app.dependencies.map((dep) => `${prefix}${dep.toUpperCase()}_URL`);
|
|
3462
3215
|
}
|
|
3463
3216
|
//#endregion
|
|
3464
|
-
//#region src/
|
|
3217
|
+
//#region src/docker/imageRef.ts
|
|
3465
3218
|
/**
|
|
3466
|
-
*
|
|
3219
|
+
* An image reference, checked before it reaches `docker`.
|
|
3220
|
+
*
|
|
3221
|
+
* The parts come from the workspace — a registry in `gkm.config.ts`, an image
|
|
3222
|
+
* name from the project, a tag from `--tag` — and an argument array already
|
|
3223
|
+
* keeps them out of a shell. What it cannot do is stop `docker` reading a value
|
|
3224
|
+
* that starts with `-` as one of its own flags, so a ref is held to Docker's
|
|
3225
|
+
* own grammar (distribution/reference) and anything else is refused by name
|
|
3226
|
+
* before a build starts.
|
|
3467
3227
|
*/
|
|
3468
|
-
|
|
3469
|
-
|
|
3228
|
+
const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
|
|
3229
|
+
const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
|
|
3230
|
+
const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
|
|
3231
|
+
const REFERENCE = new RegExp(`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::[\\w][\\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,})?$`);
|
|
3232
|
+
/** Docker refuses a repository name longer than this. */
|
|
3233
|
+
const MAX_NAME_LENGTH = 255;
|
|
3234
|
+
/** A value that is not an image reference was about to be built or pushed. */
|
|
3235
|
+
var ImageRefInvalid = class extends Error {
|
|
3236
|
+
ref;
|
|
3237
|
+
constructor(ref) {
|
|
3238
|
+
super(`'${ref}' is not a valid image reference. An image is \`[registry/]name[:tag]\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`);
|
|
3239
|
+
this.ref = ref;
|
|
3240
|
+
this.name = "ImageRefInvalid";
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
|
|
3244
|
+
function validateImageRef(ref) {
|
|
3245
|
+
const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
|
|
3246
|
+
if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
|
|
3247
|
+
return ref;
|
|
3470
3248
|
}
|
|
3471
3249
|
//#endregion
|
|
3472
|
-
//#region src/
|
|
3250
|
+
//#region src/docker/templates.ts
|
|
3251
|
+
const LOCKFILES = [
|
|
3252
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
3253
|
+
["bun.lockb", "bun"],
|
|
3254
|
+
["yarn.lock", "yarn"],
|
|
3255
|
+
["package-lock.json", "npm"]
|
|
3256
|
+
];
|
|
3473
3257
|
/**
|
|
3474
|
-
*
|
|
3475
|
-
*
|
|
3476
|
-
* `StateProvider` reads and writes a whole stage at once, with nothing to stop
|
|
3477
|
-
* two runs of the same stage from overwriting each other and nowhere to record
|
|
3478
|
-
* a resource the moment it exists. A `StateStore` adds the three things a
|
|
3479
|
-
* deploy needs to be safe against crashes and concurrent runs:
|
|
3480
|
-
*
|
|
3481
|
-
* - `lock(stage)`: one run per stage. A second gets `StateLocked`, naming the
|
|
3482
|
-
* holder, instead of racing the first.
|
|
3483
|
-
* - Versioned `read` and conditional `write`: a write names the version it was
|
|
3484
|
-
* based on, and raises `StateVersionConflict` when the stored state moved on
|
|
3485
|
-
* underneath it, so nothing is lost silently even without the lock.
|
|
3486
|
-
* - Per-resource records: `putResource` journals one resource at a time, so a
|
|
3487
|
-
* run that dies half way leaves behind the ids of everything it created.
|
|
3488
|
-
*
|
|
3489
|
-
* Built-in stores: `LocalStateStore`, `SSMStateStore`, `S3StateStore`. A
|
|
3490
|
-
* custom `StateProvider` is wrapped by `LegacyStateStore`, which keeps it
|
|
3491
|
-
* working but cannot lock.
|
|
3258
|
+
* Detect package manager from lockfiles
|
|
3259
|
+
* Walks up the directory tree to find lockfile (for monorepos)
|
|
3492
3260
|
*/
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
super(`Deploy state for stage '${stage}' is locked by ${by} (${location}). Wait for that run to finish; if it crashed, release the lock with \`gkm state:unlock --stage ${stage}\`.`);
|
|
3500
|
-
this.stage = stage;
|
|
3501
|
-
this.holder = holder;
|
|
3502
|
-
this.location = location;
|
|
3503
|
-
this.name = "StateLocked";
|
|
3504
|
-
}
|
|
3505
|
-
};
|
|
3506
|
-
var StateVersionConflict = class extends Error {
|
|
3507
|
-
stage;
|
|
3508
|
-
expectedVersion;
|
|
3509
|
-
actualVersion;
|
|
3510
|
-
constructor(stage, expectedVersion, actualVersion) {
|
|
3511
|
-
super(`Deploy state for stage '${stage}' changed since it was read (expected ${expectedVersion ? `version ${expectedVersion}` : "no state"}, found ${actualVersion ? `version ${actualVersion}` : "no state"}). Another run wrote it: read the state again and re-apply the change, and hold the stage's lock so runs take turns.`);
|
|
3512
|
-
this.stage = stage;
|
|
3513
|
-
this.expectedVersion = expectedVersion;
|
|
3514
|
-
this.actualVersion = actualVersion;
|
|
3515
|
-
this.name = "StateVersionConflict";
|
|
3516
|
-
}
|
|
3517
|
-
};
|
|
3518
|
-
var StageStateMissing = class extends Error {
|
|
3519
|
-
stage;
|
|
3520
|
-
constructor(stage) {
|
|
3521
|
-
super(`There is no deploy state for stage '${stage}' to record a resource in. Write the stage's state first (write with expectedVersion: null).`);
|
|
3522
|
-
this.stage = stage;
|
|
3523
|
-
this.name = "StageStateMissing";
|
|
3524
|
-
}
|
|
3525
|
-
};
|
|
3526
|
-
var StateUnreadable = class extends Error {
|
|
3527
|
-
stage;
|
|
3528
|
-
location;
|
|
3529
|
-
constructor(stage, location, cause) {
|
|
3530
|
-
super(`Deploy state for stage '${stage}' at ${location} is not valid JSON. Restore it from a backup (or the provider's history) rather than deploying without it — a deploy without state recreates every resource.`, { cause });
|
|
3531
|
-
this.stage = stage;
|
|
3532
|
-
this.location = location;
|
|
3533
|
-
this.name = "StateUnreadable";
|
|
3534
|
-
}
|
|
3535
|
-
};
|
|
3536
|
-
var StateSchemaTooNew = class extends Error {
|
|
3537
|
-
stage;
|
|
3538
|
-
schemaVersion;
|
|
3539
|
-
constructor(stage, schemaVersion) {
|
|
3540
|
-
super(`Deploy state for stage '${stage}' has schema version ${String(schemaVersion)}, newer than this @geekmidas/cli understands (2). Upgrade @geekmidas/cli to the version that wrote it.`);
|
|
3541
|
-
this.stage = stage;
|
|
3542
|
-
this.schemaVersion = schemaVersion;
|
|
3543
|
-
this.name = "StateSchemaTooNew";
|
|
3261
|
+
function detectPackageManager(cwd = process.cwd()) {
|
|
3262
|
+
let dir = cwd;
|
|
3263
|
+
const root = parse(dir).root;
|
|
3264
|
+
while (dir !== root) {
|
|
3265
|
+
for (const [lockfile, pm] of LOCKFILES) if (existsSync(join(dir, lockfile))) return pm;
|
|
3266
|
+
dir = dirname(dir);
|
|
3544
3267
|
}
|
|
3545
|
-
|
|
3268
|
+
for (const [lockfile, pm] of LOCKFILES) if (existsSync(join(root, lockfile))) return pm;
|
|
3269
|
+
return "pnpm";
|
|
3270
|
+
}
|
|
3546
3271
|
/**
|
|
3547
|
-
*
|
|
3548
|
-
*
|
|
3549
|
-
* says so.
|
|
3272
|
+
* Find the lockfile path by walking up the directory tree
|
|
3273
|
+
* Returns the full path to the lockfile, or null if not found
|
|
3550
3274
|
*/
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
}
|
|
3559
|
-
|
|
3560
|
-
provider;
|
|
3561
|
-
constructor(provider) {
|
|
3562
|
-
super(`The '${provider}' state provider keys state by workspace name. Set "name" in gkm.config.ts.`);
|
|
3563
|
-
this.provider = provider;
|
|
3564
|
-
this.name = "StateStoreNeedsWorkspaceName";
|
|
3565
|
-
}
|
|
3566
|
-
};
|
|
3567
|
-
var UnknownStateProvider = class extends Error {
|
|
3568
|
-
config;
|
|
3569
|
-
constructor(config) {
|
|
3570
|
-
super(`Unknown state provider ${JSON.stringify(config)}. Use 'local', 'ssm', 's3', or an object implementing StateStore or StateProvider.`);
|
|
3571
|
-
this.config = config;
|
|
3572
|
-
this.name = "UnknownStateProvider";
|
|
3573
|
-
}
|
|
3574
|
-
};
|
|
3575
|
-
/** A lock or write that could not get at the state backend in time. */
|
|
3576
|
-
var StateStoreBusy = class extends Error {
|
|
3577
|
-
stage;
|
|
3578
|
-
location;
|
|
3579
|
-
constructor(stage, location) {
|
|
3580
|
-
super(`Timed out waiting to write deploy state for stage '${stage}' (${location}). If no other gkm process is running, remove ${location}.`);
|
|
3581
|
-
this.stage = stage;
|
|
3582
|
-
this.location = location;
|
|
3583
|
-
this.name = "StateStoreBusy";
|
|
3275
|
+
function findLockfilePath(cwd = process.cwd()) {
|
|
3276
|
+
let dir = cwd;
|
|
3277
|
+
const root = parse(dir).root;
|
|
3278
|
+
while (dir !== root) {
|
|
3279
|
+
for (const [lockfile] of LOCKFILES) {
|
|
3280
|
+
const lockfilePath = join(dir, lockfile);
|
|
3281
|
+
if (existsSync(lockfilePath)) return lockfilePath;
|
|
3282
|
+
}
|
|
3283
|
+
dir = dirname(dir);
|
|
3584
3284
|
}
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
try {
|
|
3589
|
-
parsed = JSON.parse(body);
|
|
3590
|
-
} catch (error) {
|
|
3591
|
-
throw new StateUnreadable(stage, location, error);
|
|
3285
|
+
for (const [lockfile] of LOCKFILES) {
|
|
3286
|
+
const lockfilePath = join(root, lockfile);
|
|
3287
|
+
if (existsSync(lockfilePath)) return lockfilePath;
|
|
3592
3288
|
}
|
|
3593
|
-
|
|
3594
|
-
const schemaVersion = parsed.schemaVersion;
|
|
3595
|
-
if (schemaVersion === void 0) return {
|
|
3596
|
-
schemaVersion: 1,
|
|
3597
|
-
state: parsed
|
|
3598
|
-
};
|
|
3599
|
-
if (schemaVersion === 2) return {
|
|
3600
|
-
schemaVersion: 2,
|
|
3601
|
-
document: parsed
|
|
3602
|
-
};
|
|
3603
|
-
throw new StateSchemaTooNew(stage, schemaVersion);
|
|
3604
|
-
}
|
|
3605
|
-
function encodeDocument(document) {
|
|
3606
|
-
return JSON.stringify(document, null, 2);
|
|
3289
|
+
return null;
|
|
3607
3290
|
}
|
|
3608
3291
|
/**
|
|
3609
|
-
*
|
|
3610
|
-
* so the first journaled deploy after an upgrade adopts them rather than
|
|
3611
|
-
* treating them as unknown.
|
|
3292
|
+
* Check if we're in a monorepo (lockfile is in a parent directory)
|
|
3612
3293
|
*/
|
|
3613
|
-
function
|
|
3614
|
-
const
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
if (!id) return;
|
|
3618
|
-
const key = name ? `${type}:${name}` : type;
|
|
3619
|
-
resources[key] = {
|
|
3620
|
-
key,
|
|
3621
|
-
type,
|
|
3622
|
-
id,
|
|
3623
|
-
status: "ready",
|
|
3624
|
-
updatedAt: now
|
|
3625
|
-
};
|
|
3626
|
-
};
|
|
3627
|
-
seed("project", null, state.projectId);
|
|
3628
|
-
seed("environment", null, state.environmentId);
|
|
3629
|
-
for (const [app, id] of Object.entries(state.applications ?? {})) seed("application", app, id);
|
|
3630
|
-
seed("postgres", null, state.services?.postgresId);
|
|
3631
|
-
seed("redis", null, state.services?.redisId);
|
|
3632
|
-
seed("backup-destination", null, state.backups?.destinationId);
|
|
3633
|
-
return {
|
|
3634
|
-
schemaVersion: 2,
|
|
3635
|
-
stage,
|
|
3636
|
-
serial: 1,
|
|
3637
|
-
state,
|
|
3638
|
-
resources,
|
|
3639
|
-
updatedAt: now
|
|
3640
|
-
};
|
|
3641
|
-
}
|
|
3642
|
-
function newLockHolder(options) {
|
|
3643
|
-
let owner = "unknown";
|
|
3644
|
-
try {
|
|
3645
|
-
owner = userInfo().username;
|
|
3646
|
-
} catch {}
|
|
3647
|
-
return {
|
|
3648
|
-
id: randomUUID(),
|
|
3649
|
-
owner,
|
|
3650
|
-
host: hostname(),
|
|
3651
|
-
pid: process.pid,
|
|
3652
|
-
acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3653
|
-
operation: options?.operation
|
|
3654
|
-
};
|
|
3655
|
-
}
|
|
3656
|
-
function contentVersion(body) {
|
|
3657
|
-
return createHash("sha256").update(body).digest("hex").slice(0, 16);
|
|
3658
|
-
}
|
|
3659
|
-
/**
|
|
3660
|
-
* A store over a backend that can read and conditionally write one blob per
|
|
3661
|
-
* stage, and create a lock object only if it does not exist. Migration and
|
|
3662
|
-
* resource records are the same for every such backend, so they live here.
|
|
3663
|
-
*/
|
|
3664
|
-
var DocumentStateStore = class {
|
|
3665
|
-
async lock(stage, options) {
|
|
3666
|
-
const holder = newLockHolder(options);
|
|
3667
|
-
await this.createLock(stage, holder);
|
|
3668
|
-
let released = false;
|
|
3669
|
-
return {
|
|
3670
|
-
stage,
|
|
3671
|
-
holder,
|
|
3672
|
-
release: async () => {
|
|
3673
|
-
if (released) return;
|
|
3674
|
-
released = true;
|
|
3675
|
-
await this.removeLock(stage, holder);
|
|
3676
|
-
}
|
|
3677
|
-
};
|
|
3678
|
-
}
|
|
3679
|
-
async forceUnlock(stage) {
|
|
3680
|
-
const holder = await this.readLock(stage);
|
|
3681
|
-
await this.removeLock(stage, null);
|
|
3682
|
-
return holder;
|
|
3683
|
-
}
|
|
3684
|
-
async read(stage) {
|
|
3685
|
-
const current = await this.readDocument(stage);
|
|
3686
|
-
if (!current) return null;
|
|
3687
|
-
return {
|
|
3688
|
-
state: current.document.state,
|
|
3689
|
-
resources: current.document.resources,
|
|
3690
|
-
version: current.version
|
|
3691
|
-
};
|
|
3692
|
-
}
|
|
3693
|
-
async write(stage, state, options) {
|
|
3694
|
-
if (options.expectedVersion === null) {
|
|
3695
|
-
const document = {
|
|
3696
|
-
schemaVersion: 2,
|
|
3697
|
-
stage,
|
|
3698
|
-
serial: 1,
|
|
3699
|
-
state,
|
|
3700
|
-
resources: {},
|
|
3701
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3702
|
-
};
|
|
3703
|
-
return this.writeRaw(stage, encodeDocument(document), null);
|
|
3704
|
-
}
|
|
3705
|
-
return this.mutate(stage, options.expectedVersion, (document) => ({
|
|
3706
|
-
...document,
|
|
3707
|
-
state
|
|
3708
|
-
}));
|
|
3709
|
-
}
|
|
3710
|
-
async putResource(stage, record, options) {
|
|
3711
|
-
return this.mutate(stage, options?.expectedVersion, (document) => ({
|
|
3712
|
-
...document,
|
|
3713
|
-
resources: {
|
|
3714
|
-
...document.resources,
|
|
3715
|
-
[record.key]: {
|
|
3716
|
-
...record,
|
|
3717
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3718
|
-
}
|
|
3719
|
-
}
|
|
3720
|
-
}));
|
|
3721
|
-
}
|
|
3722
|
-
async deleteResource(stage, key, options) {
|
|
3723
|
-
return this.mutate(stage, options?.expectedVersion, (document) => {
|
|
3724
|
-
const { [key]: _removed, ...resources } = document.resources;
|
|
3725
|
-
return {
|
|
3726
|
-
...document,
|
|
3727
|
-
resources
|
|
3728
|
-
};
|
|
3729
|
-
});
|
|
3730
|
-
}
|
|
3731
|
-
async mutate(stage, expectedVersion, change) {
|
|
3732
|
-
const current = await this.readDocument(stage);
|
|
3733
|
-
if (!current) {
|
|
3734
|
-
if (expectedVersion !== void 0) throw new StateVersionConflict(stage, expectedVersion, null);
|
|
3735
|
-
throw new StageStateMissing(stage);
|
|
3736
|
-
}
|
|
3737
|
-
if (expectedVersion !== void 0 && current.version !== expectedVersion) throw new StateVersionConflict(stage, expectedVersion, current.version);
|
|
3738
|
-
const next = change(current.document);
|
|
3739
|
-
next.serial = current.document.serial + 1;
|
|
3740
|
-
next.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3741
|
-
return this.writeRaw(stage, encodeDocument(next), current.version);
|
|
3742
|
-
}
|
|
3743
|
-
/**
|
|
3744
|
-
* Reads the stage's document, migrating v1 in place on the way. The
|
|
3745
|
-
* migration is itself a conditional write: if another run migrated (or
|
|
3746
|
-
* wrote) first, its result is read instead.
|
|
3747
|
-
*/
|
|
3748
|
-
async readDocument(stage, attempt = 0) {
|
|
3749
|
-
const raw = await this.readRaw(stage);
|
|
3750
|
-
if (!raw) return null;
|
|
3751
|
-
const decoded = decodeDocument(stage, raw.body, this.location(stage));
|
|
3752
|
-
if (decoded.schemaVersion === 2) return {
|
|
3753
|
-
document: decoded.document,
|
|
3754
|
-
version: raw.version
|
|
3755
|
-
};
|
|
3756
|
-
await this.writeV1Backup(stage, raw.body);
|
|
3757
|
-
const document = migrateV1(stage, decoded.state);
|
|
3758
|
-
try {
|
|
3759
|
-
return {
|
|
3760
|
-
document,
|
|
3761
|
-
version: await this.writeRaw(stage, encodeDocument(document), raw.version)
|
|
3762
|
-
};
|
|
3763
|
-
} catch (error) {
|
|
3764
|
-
if (error instanceof StateVersionConflict && attempt < 2) return this.readDocument(stage, attempt + 1);
|
|
3765
|
-
throw error;
|
|
3766
|
-
}
|
|
3767
|
-
}
|
|
3768
|
-
};
|
|
3769
|
-
function isStateStore(value) {
|
|
3770
|
-
return typeof value === "object" && value !== null && typeof value.lock === "function" && typeof value.read === "function" && typeof value.write === "function" && typeof value.putResource === "function";
|
|
3294
|
+
function isMonorepo(cwd = process.cwd()) {
|
|
3295
|
+
const lockfilePath = findLockfilePath(cwd);
|
|
3296
|
+
if (!lockfilePath) return false;
|
|
3297
|
+
return dirname(lockfilePath) !== cwd;
|
|
3771
3298
|
}
|
|
3772
3299
|
/**
|
|
3773
|
-
*
|
|
3774
|
-
*
|
|
3775
|
-
* - none / `'local'`: `LocalStateStore` under `.gkm/`
|
|
3776
|
-
* - `'ssm'`: `SSMStateStore`, with no local cache — SSM is read directly, so
|
|
3777
|
-
* a stale local copy can never win over it
|
|
3778
|
-
* - `'s3'`: `S3StateStore`
|
|
3779
|
-
* - a `StateStore` object: used as is
|
|
3780
|
-
* - a `StateProvider` object: wrapped by `LegacyStateStore`
|
|
3300
|
+
* Check if turbo.json exists (walks up directory tree)
|
|
3781
3301
|
*/
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
if (isStateStore(config.provider)) return config.provider;
|
|
3789
|
-
if (isStateProvider(config.provider)) {
|
|
3790
|
-
const { LegacyStateStore } = await import("./LegacyStateStore-DIgkGaUP.mjs");
|
|
3791
|
-
return new LegacyStateStore(config.provider, { warn: options.warn });
|
|
3792
|
-
}
|
|
3793
|
-
if (config.provider === "ssm") {
|
|
3794
|
-
if (!workspaceName) throw new StateStoreNeedsWorkspaceName("ssm");
|
|
3795
|
-
const { SSMStateStore } = await import("./SSMStateStore-DfF174xQ.mjs");
|
|
3796
|
-
const ssm = config;
|
|
3797
|
-
return SSMStateStore.create({
|
|
3798
|
-
workspaceName,
|
|
3799
|
-
region: ssm.region,
|
|
3800
|
-
profile: ssm.profile
|
|
3801
|
-
});
|
|
3802
|
-
}
|
|
3803
|
-
if (config.provider === "s3") {
|
|
3804
|
-
if (!workspaceName) throw new StateStoreNeedsWorkspaceName("s3");
|
|
3805
|
-
const { S3StateStore } = await import("./S3StateStore-D3x6ivBL.mjs");
|
|
3806
|
-
const s3 = config;
|
|
3807
|
-
return S3StateStore.create({
|
|
3808
|
-
workspaceName,
|
|
3809
|
-
bucket: s3.bucket,
|
|
3810
|
-
prefix: s3.prefix,
|
|
3811
|
-
region: s3.region,
|
|
3812
|
-
profile: s3.profile
|
|
3813
|
-
});
|
|
3302
|
+
function hasTurboConfig(cwd = process.cwd()) {
|
|
3303
|
+
let dir = cwd;
|
|
3304
|
+
const root = parse(dir).root;
|
|
3305
|
+
while (dir !== root) {
|
|
3306
|
+
if (existsSync(join(dir, "turbo.json"))) return true;
|
|
3307
|
+
dir = dirname(dir);
|
|
3814
3308
|
}
|
|
3815
|
-
|
|
3309
|
+
return existsSync(join(root, "turbo.json"));
|
|
3816
3310
|
}
|
|
3817
|
-
//#endregion
|
|
3818
|
-
//#region src/deploy/state.ts
|
|
3819
3311
|
/**
|
|
3820
|
-
*
|
|
3312
|
+
* Get install command for turbo builds (without frozen lockfile)
|
|
3313
|
+
* Turbo prune creates a subset that may not perfectly match the lockfile
|
|
3821
3314
|
*/
|
|
3822
|
-
function
|
|
3315
|
+
function getTurboInstallCmd(pm) {
|
|
3823
3316
|
return {
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
services: {},
|
|
3830
|
-
lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3831
|
-
};
|
|
3832
|
-
}
|
|
3833
|
-
/**
|
|
3834
|
-
* Set application ID in state (mutates state)
|
|
3835
|
-
*/
|
|
3836
|
-
function setApplicationId(state, appName, applicationId) {
|
|
3837
|
-
state.applications[appName] = applicationId;
|
|
3838
|
-
}
|
|
3839
|
-
/**
|
|
3840
|
-
* Record the image an app was deployed with (mutates state)
|
|
3841
|
-
*/
|
|
3842
|
-
function setDeployedImage(state, appName, image) {
|
|
3843
|
-
state.images = {
|
|
3844
|
-
...state.images,
|
|
3845
|
-
[appName]: image
|
|
3846
|
-
};
|
|
3847
|
-
}
|
|
3848
|
-
/**
|
|
3849
|
-
* Get a generated secret for an app
|
|
3850
|
-
*/
|
|
3851
|
-
function getGeneratedSecret(state, appName, secretName) {
|
|
3852
|
-
return state?.generatedSecrets?.[appName]?.[secretName];
|
|
3853
|
-
}
|
|
3854
|
-
/**
|
|
3855
|
-
* Set a generated secret for an app (mutates state)
|
|
3856
|
-
*/
|
|
3857
|
-
function setGeneratedSecret(state, appName, secretName, value) {
|
|
3858
|
-
if (!state.generatedSecrets) state.generatedSecrets = {};
|
|
3859
|
-
if (!state.generatedSecrets[appName]) state.generatedSecrets[appName] = {};
|
|
3860
|
-
state.generatedSecrets[appName][secretName] = value;
|
|
3317
|
+
pnpm: "pnpm install",
|
|
3318
|
+
npm: "npm install",
|
|
3319
|
+
yarn: "yarn install",
|
|
3320
|
+
bun: "bun install"
|
|
3321
|
+
}[pm];
|
|
3861
3322
|
}
|
|
3862
3323
|
/**
|
|
3863
|
-
*
|
|
3324
|
+
* Get package manager specific commands and paths
|
|
3864
3325
|
*/
|
|
3865
|
-
function
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
|
|
3326
|
+
function getPmConfig(pm) {
|
|
3327
|
+
return {
|
|
3328
|
+
pnpm: {
|
|
3329
|
+
install: "corepack enable && corepack prepare pnpm@latest --activate",
|
|
3330
|
+
lockfile: "pnpm-lock.yaml",
|
|
3331
|
+
fetch: "pnpm fetch",
|
|
3332
|
+
installCmd: "pnpm install --frozen-lockfile --offline",
|
|
3333
|
+
cacheTarget: "/root/.local/share/pnpm/store",
|
|
3334
|
+
cacheId: "pnpm",
|
|
3335
|
+
run: "pnpm",
|
|
3336
|
+
exec: "pnpm exec",
|
|
3337
|
+
dlx: "pnpm dlx",
|
|
3338
|
+
addGlobal: "pnpm add -g"
|
|
3339
|
+
},
|
|
3340
|
+
npm: {
|
|
3341
|
+
install: "",
|
|
3342
|
+
lockfile: "package-lock.json",
|
|
3343
|
+
fetch: "",
|
|
3344
|
+
installCmd: "npm ci",
|
|
3345
|
+
cacheTarget: "/root/.npm",
|
|
3346
|
+
cacheId: "npm",
|
|
3347
|
+
run: "npm run",
|
|
3348
|
+
exec: "npx",
|
|
3349
|
+
dlx: "npx",
|
|
3350
|
+
addGlobal: "npm install -g"
|
|
3351
|
+
},
|
|
3352
|
+
yarn: {
|
|
3353
|
+
install: "corepack enable && corepack prepare yarn@stable --activate",
|
|
3354
|
+
lockfile: "yarn.lock",
|
|
3355
|
+
fetch: "",
|
|
3356
|
+
installCmd: "yarn install --frozen-lockfile",
|
|
3357
|
+
cacheTarget: "/root/.yarn/cache",
|
|
3358
|
+
cacheId: "yarn",
|
|
3359
|
+
run: "yarn",
|
|
3360
|
+
exec: "yarn exec",
|
|
3361
|
+
dlx: "yarn dlx",
|
|
3362
|
+
addGlobal: "yarn global add"
|
|
3363
|
+
},
|
|
3364
|
+
bun: {
|
|
3365
|
+
install: "npm install -g bun",
|
|
3366
|
+
lockfile: "bun.lockb",
|
|
3367
|
+
fetch: "",
|
|
3368
|
+
installCmd: "bun install --frozen-lockfile",
|
|
3369
|
+
cacheTarget: "/root/.bun/install/cache",
|
|
3370
|
+
cacheId: "bun",
|
|
3371
|
+
run: "bun run",
|
|
3372
|
+
exec: "bunx",
|
|
3373
|
+
dlx: "bunx",
|
|
3374
|
+
addGlobal: "bun add -g"
|
|
3375
|
+
}
|
|
3376
|
+
}[pm];
|
|
3871
3377
|
}
|
|
3872
3378
|
/**
|
|
3873
|
-
*
|
|
3379
|
+
* Generate a multi-stage Dockerfile for building from source
|
|
3380
|
+
* Optimized for build speed with:
|
|
3381
|
+
* - BuildKit cache mounts for package manager store
|
|
3382
|
+
* - pnpm fetch for better layer caching (when using pnpm)
|
|
3383
|
+
* - Optional turbo prune for monorepos
|
|
3874
3384
|
*/
|
|
3875
|
-
function
|
|
3876
|
-
|
|
3385
|
+
function generateMultiStageDockerfile(options) {
|
|
3386
|
+
const { baseImage, port, healthCheckPath, turbo, turboPackage, packageManager } = options;
|
|
3387
|
+
if (turbo) return generateTurboDockerfile({
|
|
3388
|
+
...options,
|
|
3389
|
+
turboPackage: turboPackage ?? "api"
|
|
3390
|
+
});
|
|
3391
|
+
const pm = getPmConfig(packageManager);
|
|
3392
|
+
return `# syntax=docker/dockerfile:1
|
|
3393
|
+
# Stage 1: Dependencies
|
|
3394
|
+
FROM ${baseImage} AS deps
|
|
3395
|
+
|
|
3396
|
+
WORKDIR /app
|
|
3397
|
+
${pm.install ? `\n# Install ${packageManager}\nRUN ${pm.install}\n` : ""}
|
|
3398
|
+
${packageManager === "pnpm" ? `# Copy lockfile first for better caching
|
|
3399
|
+
COPY ${pm.lockfile} ./
|
|
3400
|
+
|
|
3401
|
+
# Fetch dependencies (downloads to virtual store, cached separately)
|
|
3402
|
+
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
3403
|
+
${pm.fetch}
|
|
3404
|
+
|
|
3405
|
+
# Copy package.json after fetch
|
|
3406
|
+
COPY package.json ./
|
|
3407
|
+
|
|
3408
|
+
# Install from cache (fast - no network needed)
|
|
3409
|
+
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
3410
|
+
${pm.installCmd}` : `# Copy package files
|
|
3411
|
+
COPY package.json ${pm.lockfile} ./
|
|
3412
|
+
|
|
3413
|
+
# Install dependencies with cache
|
|
3414
|
+
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
3415
|
+
${pm.installCmd}`}
|
|
3416
|
+
|
|
3417
|
+
# Stage 2: Build
|
|
3418
|
+
FROM deps AS builder
|
|
3419
|
+
|
|
3420
|
+
WORKDIR /app
|
|
3421
|
+
|
|
3422
|
+
# Copy source (deps already installed)
|
|
3423
|
+
COPY . .
|
|
3424
|
+
|
|
3425
|
+
# Build any workspace packages the app depends on.
|
|
3426
|
+
#
|
|
3427
|
+
# A no-op for a project whose dependencies come from a registry, and required
|
|
3428
|
+
# for one whose CLI is a sibling package: \`turbo prune\` honours .gitignore, so a
|
|
3429
|
+
# workspace package's \`dist\` never reaches the image and its bin has nothing to
|
|
3430
|
+
# import. \`--if-present\` is what makes the same Dockerfile correct for both.
|
|
3431
|
+
RUN ${pm.run} --if-present build
|
|
3432
|
+
|
|
3433
|
+
# Build production server using gkm
|
|
3434
|
+
RUN ${pm.exec} gkm build --provider server --production
|
|
3435
|
+
|
|
3436
|
+
# Stage 3: Production
|
|
3437
|
+
FROM ${baseImage} AS runner
|
|
3438
|
+
|
|
3439
|
+
WORKDIR /app
|
|
3440
|
+
|
|
3441
|
+
# Install tini for proper signal handling as PID 1
|
|
3442
|
+
RUN apk add --no-cache tini
|
|
3443
|
+
|
|
3444
|
+
# Create non-root user
|
|
3445
|
+
RUN addgroup --system --gid 1001 nodejs && \\
|
|
3446
|
+
adduser --system --uid 1001 hono
|
|
3447
|
+
|
|
3448
|
+
# Copy bundled server
|
|
3449
|
+
COPY --from=builder --chown=hono:nodejs /app/.gkm/server/dist/server.mjs ./
|
|
3450
|
+
|
|
3451
|
+
# Environment
|
|
3452
|
+
ENV NODE_ENV=production
|
|
3453
|
+
ENV PORT=${port}
|
|
3454
|
+
|
|
3455
|
+
# Health check
|
|
3456
|
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
3457
|
+
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
3458
|
+
|
|
3459
|
+
# Switch to non-root user
|
|
3460
|
+
USER hono
|
|
3461
|
+
|
|
3462
|
+
EXPOSE ${port}
|
|
3463
|
+
|
|
3464
|
+
# Use tini as entrypoint to handle PID 1 responsibilities
|
|
3465
|
+
ENTRYPOINT ["/sbin/tini", "--"]
|
|
3466
|
+
CMD ["node", "server.mjs"]
|
|
3467
|
+
`;
|
|
3877
3468
|
}
|
|
3878
3469
|
/**
|
|
3879
|
-
*
|
|
3470
|
+
* Generate a Dockerfile optimized for Turbo monorepos
|
|
3471
|
+
* Uses turbo prune to create minimal Docker context
|
|
3880
3472
|
*/
|
|
3881
|
-
function
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3473
|
+
function generateTurboDockerfile(options) {
|
|
3474
|
+
const { baseImage, port, healthCheckPath, turboPackage, packageManager } = options;
|
|
3475
|
+
const pm = getPmConfig(packageManager);
|
|
3476
|
+
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
3477
|
+
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
3478
|
+
return `# syntax=docker/dockerfile:1
|
|
3479
|
+
# Stage 1: Prune monorepo
|
|
3480
|
+
FROM ${baseImage} AS pruner
|
|
3481
|
+
|
|
3482
|
+
WORKDIR /app
|
|
3483
|
+
|
|
3484
|
+
${installPm}
|
|
3485
|
+
|
|
3486
|
+
COPY . .
|
|
3487
|
+
|
|
3488
|
+
# Prune to only include necessary packages
|
|
3489
|
+
RUN ${packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo"} prune ${turboPackage} --docker
|
|
3490
|
+
|
|
3491
|
+
# Stage 2: Install dependencies
|
|
3492
|
+
FROM ${baseImage} AS deps
|
|
3493
|
+
|
|
3494
|
+
WORKDIR /app
|
|
3495
|
+
|
|
3496
|
+
${installPm}
|
|
3497
|
+
|
|
3498
|
+
# Copy pruned lockfile and package.jsons
|
|
3499
|
+
COPY --from=pruner /app/out/${pm.lockfile} ./
|
|
3500
|
+
COPY --from=pruner /app/out/json/ ./
|
|
3501
|
+
|
|
3502
|
+
# Install dependencies (no frozen-lockfile since turbo prune creates a subset)
|
|
3503
|
+
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
3504
|
+
${turboInstallCmd}
|
|
3505
|
+
|
|
3506
|
+
# Stage 3: Build
|
|
3507
|
+
FROM deps AS builder
|
|
3508
|
+
|
|
3509
|
+
WORKDIR /app
|
|
3510
|
+
|
|
3511
|
+
# Copy pruned source
|
|
3512
|
+
COPY --from=pruner /app/out/full/ ./
|
|
3513
|
+
|
|
3514
|
+
# Build any workspace packages the app depends on.
|
|
3515
|
+
#
|
|
3516
|
+
# A no-op for a project whose dependencies come from a registry, and required
|
|
3517
|
+
# for one whose CLI is a sibling package: \`turbo prune\` honours .gitignore, so a
|
|
3518
|
+
# workspace package's \`dist\` never reaches the image and its bin has nothing to
|
|
3519
|
+
# import. \`--if-present\` is what makes the same Dockerfile correct for both.
|
|
3520
|
+
RUN ${pm.run} --if-present build
|
|
3521
|
+
|
|
3522
|
+
# Build production server using gkm
|
|
3523
|
+
RUN ${pm.exec} gkm build --provider server --production
|
|
3524
|
+
|
|
3525
|
+
# Stage 4: Production
|
|
3526
|
+
FROM ${baseImage} AS runner
|
|
3527
|
+
|
|
3528
|
+
WORKDIR /app
|
|
3529
|
+
|
|
3530
|
+
RUN apk add --no-cache tini
|
|
3531
|
+
|
|
3532
|
+
RUN addgroup --system --gid 1001 nodejs && \\
|
|
3533
|
+
adduser --system --uid 1001 hono
|
|
3534
|
+
|
|
3535
|
+
COPY --from=builder --chown=hono:nodejs /app/.gkm/server/dist/server.mjs ./
|
|
3536
|
+
|
|
3537
|
+
ENV NODE_ENV=production
|
|
3538
|
+
ENV PORT=${port}
|
|
3539
|
+
|
|
3540
|
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
3541
|
+
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
3542
|
+
|
|
3543
|
+
USER hono
|
|
3544
|
+
|
|
3545
|
+
EXPOSE ${port}
|
|
3546
|
+
|
|
3547
|
+
ENTRYPOINT ["/sbin/tini", "--"]
|
|
3548
|
+
CMD ["node", "server.mjs"]
|
|
3549
|
+
`;
|
|
3894
3550
|
}
|
|
3895
3551
|
/**
|
|
3896
|
-
*
|
|
3552
|
+
* Generate a slim Dockerfile for pre-built bundles
|
|
3897
3553
|
*/
|
|
3898
|
-
function
|
|
3899
|
-
|
|
3554
|
+
function generateSlimDockerfile(options) {
|
|
3555
|
+
const { baseImage, port, healthCheckPath, bundle = ".gkm/server/dist/server.mjs" } = options;
|
|
3556
|
+
return `# Slim Dockerfile for pre-built production bundle
|
|
3557
|
+
FROM ${baseImage}
|
|
3558
|
+
|
|
3559
|
+
WORKDIR /app
|
|
3560
|
+
|
|
3561
|
+
# Install tini for proper signal handling as PID 1
|
|
3562
|
+
# Handles SIGTERM propagation and zombie process reaping
|
|
3563
|
+
RUN apk add --no-cache tini
|
|
3564
|
+
|
|
3565
|
+
# Create non-root user
|
|
3566
|
+
RUN addgroup --system --gid 1001 nodejs && \\
|
|
3567
|
+
adduser --system --uid 1001 hono
|
|
3568
|
+
|
|
3569
|
+
# Copy pre-built bundle
|
|
3570
|
+
COPY ${bundle} ./
|
|
3571
|
+
|
|
3572
|
+
# Environment
|
|
3573
|
+
ENV NODE_ENV=production
|
|
3574
|
+
ENV PORT=${port}
|
|
3575
|
+
|
|
3576
|
+
# Health check
|
|
3577
|
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
3578
|
+
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
3579
|
+
|
|
3580
|
+
# Switch to non-root user
|
|
3581
|
+
USER hono
|
|
3582
|
+
|
|
3583
|
+
EXPOSE ${port}
|
|
3584
|
+
|
|
3585
|
+
# Use tini as entrypoint to handle PID 1 responsibilities
|
|
3586
|
+
ENTRYPOINT ["/sbin/tini", "--"]
|
|
3587
|
+
CMD ["node", "server.mjs"]
|
|
3588
|
+
`;
|
|
3900
3589
|
}
|
|
3901
3590
|
/**
|
|
3902
|
-
*
|
|
3591
|
+
* Generate .dockerignore file
|
|
3903
3592
|
*/
|
|
3904
|
-
function
|
|
3905
|
-
|
|
3593
|
+
function generateDockerignore() {
|
|
3594
|
+
return `# Dependencies
|
|
3595
|
+
node_modules
|
|
3596
|
+
.pnpm-store
|
|
3597
|
+
|
|
3598
|
+
# Build output (except what we need)
|
|
3599
|
+
.gkm/aws*
|
|
3600
|
+
.gkm/server/*.ts
|
|
3601
|
+
!.gkm/server/dist
|
|
3602
|
+
|
|
3603
|
+
# The key gkm build --stage encrypted secrets with: runtime env only, never
|
|
3604
|
+
# the build context
|
|
3605
|
+
.gkm/server/master.key
|
|
3606
|
+
|
|
3607
|
+
# gkm compose's stacks: each app's env file holds its stage's secrets
|
|
3608
|
+
.gkm/compose
|
|
3609
|
+
|
|
3610
|
+
# IDE and editor
|
|
3611
|
+
.idea
|
|
3612
|
+
.vscode
|
|
3613
|
+
*.swp
|
|
3614
|
+
*.swo
|
|
3615
|
+
|
|
3616
|
+
# Git
|
|
3617
|
+
.git
|
|
3618
|
+
.gitignore
|
|
3619
|
+
|
|
3620
|
+
# Logs
|
|
3621
|
+
*.log
|
|
3622
|
+
npm-debug.log*
|
|
3623
|
+
pnpm-debug.log*
|
|
3624
|
+
|
|
3625
|
+
# Test files
|
|
3626
|
+
**/*.test.ts
|
|
3627
|
+
**/*.spec.ts
|
|
3628
|
+
**/__tests__
|
|
3629
|
+
coverage
|
|
3630
|
+
|
|
3631
|
+
# Documentation
|
|
3632
|
+
docs
|
|
3633
|
+
*.md
|
|
3634
|
+
!README.md
|
|
3635
|
+
|
|
3636
|
+
# Environment files (handle secrets separately)
|
|
3637
|
+
.env
|
|
3638
|
+
.env.*
|
|
3639
|
+
!.env.example
|
|
3640
|
+
|
|
3641
|
+
# Docker files (don't copy recursively)
|
|
3642
|
+
Dockerfile*
|
|
3643
|
+
docker-compose*
|
|
3644
|
+
.dockerignore
|
|
3645
|
+
`;
|
|
3906
3646
|
}
|
|
3907
3647
|
/**
|
|
3908
|
-
*
|
|
3648
|
+
* Generate docker-entrypoint.sh for custom startup logic
|
|
3909
3649
|
*/
|
|
3910
|
-
function
|
|
3911
|
-
|
|
3650
|
+
function generateDockerEntrypoint() {
|
|
3651
|
+
return `#!/bin/sh
|
|
3652
|
+
set -e
|
|
3653
|
+
|
|
3654
|
+
# Run any custom startup scripts here
|
|
3655
|
+
# Example: wait for database
|
|
3656
|
+
# until nc -z $DB_HOST $DB_PORT; do
|
|
3657
|
+
# echo "Waiting for database..."
|
|
3658
|
+
# sleep 1
|
|
3659
|
+
# done
|
|
3660
|
+
|
|
3661
|
+
# Execute the main command
|
|
3662
|
+
exec "$@"
|
|
3663
|
+
`;
|
|
3912
3664
|
}
|
|
3913
|
-
//#endregion
|
|
3914
|
-
//#region src/deploy/domain.ts
|
|
3915
|
-
/** A stage was deployed that `deploy.domains` gives no domain. */
|
|
3916
|
-
var NoDomainForStage = class extends Error {
|
|
3917
|
-
stage;
|
|
3918
|
-
constructor(stage) {
|
|
3919
|
-
super(`No domain for stage "${stage}". Add it to gkm.config.ts: deploy: { domains: { ${stage}: 'example.com' } }.`);
|
|
3920
|
-
this.stage = stage;
|
|
3921
|
-
this.name = "NoDomainForStage";
|
|
3922
|
-
}
|
|
3923
|
-
};
|
|
3924
3665
|
/**
|
|
3925
|
-
*
|
|
3926
|
-
*
|
|
3927
|
-
* 1. An explicit `app.domain` — a string, or one per stage — wins.
|
|
3928
|
-
* 2. Otherwise from the stage's base domain in `deploy.domains`: the root site
|
|
3929
|
-
* answers on the domain itself, and every other app on
|
|
3930
|
-
* `{subdomain}.{domain}` — its declaration's `subdomain`, or its own name.
|
|
3931
|
-
*
|
|
3932
|
-
* @throws {NoDomainForStage} when `deploy.domains` names no domain for it
|
|
3666
|
+
* Resolve Docker configuration from GkmConfig with defaults
|
|
3933
3667
|
*/
|
|
3934
|
-
function
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
return `${app.subdomain ?? appName}.${baseDomain}`;
|
|
3668
|
+
function resolveDockerConfig(config) {
|
|
3669
|
+
const docker = config.docker ?? {};
|
|
3670
|
+
return {
|
|
3671
|
+
registry: docker.registry ?? "",
|
|
3672
|
+
imageName: docker.imageName ?? config.name ?? "api",
|
|
3673
|
+
baseImage: docker.baseImage ?? "node:22-alpine",
|
|
3674
|
+
port: docker.port ?? 3e3
|
|
3675
|
+
};
|
|
3943
3676
|
}
|
|
3944
3677
|
/**
|
|
3945
|
-
*
|
|
3946
|
-
*
|
|
3947
|
-
*
|
|
3948
|
-
* @throws {AmbiguousRootSite} when several sites could be the root and none says it is
|
|
3678
|
+
* Generate a Dockerfile for Next.js frontend apps using standalone output.
|
|
3679
|
+
* Uses turbo prune for monorepo optimization.
|
|
3680
|
+
* @internal Exported for testing
|
|
3949
3681
|
*/
|
|
3950
|
-
function
|
|
3951
|
-
|
|
3952
|
-
return rootSite(Object.entries(allApps).filter(([, a]) => a.type === "web").map(([name, a]) => ({
|
|
3953
|
-
name,
|
|
3954
|
-
root: a.root
|
|
3955
|
-
}))) === appName;
|
|
3956
|
-
}
|
|
3957
|
-
/**
|
|
3958
|
-
* Get public URL arg names from app dependencies.
|
|
3959
|
-
*
|
|
3960
|
-
* @param app - The web/mobile app configuration
|
|
3961
|
-
* @returns Array of arg names like 'NEXT_PUBLIC_API_URL', or [] for frameworks
|
|
3962
|
-
* without a public prefix (e.g. Remix).
|
|
3963
|
-
*/
|
|
3964
|
-
function getPublicUrlArgNames(app) {
|
|
3965
|
-
const prefix = getPublicEnvPrefix(app.framework);
|
|
3966
|
-
if (!prefix) return [];
|
|
3967
|
-
return app.dependencies.map((dep) => `${prefix}${dep.toUpperCase()}_URL`);
|
|
3968
|
-
}
|
|
3969
|
-
//#endregion
|
|
3970
|
-
//#region src/docker/imageRef.ts
|
|
3971
|
-
/**
|
|
3972
|
-
* An image reference, checked before it reaches `docker`.
|
|
3973
|
-
*
|
|
3974
|
-
* The parts come from the workspace — a registry in `gkm.config.ts`, an image
|
|
3975
|
-
* name from the project, a tag from `--tag` — and an argument array already
|
|
3976
|
-
* keeps them out of a shell. What it cannot do is stop `docker` reading a value
|
|
3977
|
-
* that starts with `-` as one of its own flags, so a ref is held to Docker's
|
|
3978
|
-
* own grammar (distribution/reference) and anything else is refused by name
|
|
3979
|
-
* before a build starts.
|
|
3980
|
-
*/
|
|
3981
|
-
const DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
|
|
3982
|
-
const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
|
|
3983
|
-
const PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
|
|
3984
|
-
const REFERENCE = new RegExp(`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::[\\w][\\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,})?$`);
|
|
3985
|
-
/** Docker refuses a repository name longer than this. */
|
|
3986
|
-
const MAX_NAME_LENGTH = 255;
|
|
3987
|
-
/** A value that is not an image reference was about to be built or pushed. */
|
|
3988
|
-
var ImageRefInvalid = class extends Error {
|
|
3989
|
-
ref;
|
|
3990
|
-
constructor(ref) {
|
|
3991
|
-
super(`'${ref}' is not a valid image reference. An image is \`[registry/]name[:tag]\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`);
|
|
3992
|
-
this.ref = ref;
|
|
3993
|
-
this.name = "ImageRefInvalid";
|
|
3994
|
-
}
|
|
3995
|
-
};
|
|
3996
|
-
/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */
|
|
3997
|
-
function validateImageRef(ref) {
|
|
3998
|
-
const name = ref.split("@")[0].replace(/:[\w][\w.-]*$/, "");
|
|
3999
|
-
if (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) throw new ImageRefInvalid(ref);
|
|
4000
|
-
return ref;
|
|
4001
|
-
}
|
|
4002
|
-
//#endregion
|
|
4003
|
-
//#region src/docker/templates.ts
|
|
4004
|
-
const LOCKFILES = [
|
|
4005
|
-
["pnpm-lock.yaml", "pnpm"],
|
|
4006
|
-
["bun.lockb", "bun"],
|
|
4007
|
-
["yarn.lock", "yarn"],
|
|
4008
|
-
["package-lock.json", "npm"]
|
|
4009
|
-
];
|
|
4010
|
-
/**
|
|
4011
|
-
* Detect package manager from lockfiles
|
|
4012
|
-
* Walks up the directory tree to find lockfile (for monorepos)
|
|
4013
|
-
*/
|
|
4014
|
-
function detectPackageManager(cwd = process.cwd()) {
|
|
4015
|
-
let dir = cwd;
|
|
4016
|
-
const root = parse(dir).root;
|
|
4017
|
-
while (dir !== root) {
|
|
4018
|
-
for (const [lockfile, pm] of LOCKFILES) if (existsSync(join(dir, lockfile))) return pm;
|
|
4019
|
-
dir = dirname(dir);
|
|
4020
|
-
}
|
|
4021
|
-
for (const [lockfile, pm] of LOCKFILES) if (existsSync(join(root, lockfile))) return pm;
|
|
4022
|
-
return "pnpm";
|
|
4023
|
-
}
|
|
4024
|
-
/**
|
|
4025
|
-
* Find the lockfile path by walking up the directory tree
|
|
4026
|
-
* Returns the full path to the lockfile, or null if not found
|
|
4027
|
-
*/
|
|
4028
|
-
function findLockfilePath(cwd = process.cwd()) {
|
|
4029
|
-
let dir = cwd;
|
|
4030
|
-
const root = parse(dir).root;
|
|
4031
|
-
while (dir !== root) {
|
|
4032
|
-
for (const [lockfile] of LOCKFILES) {
|
|
4033
|
-
const lockfilePath = join(dir, lockfile);
|
|
4034
|
-
if (existsSync(lockfilePath)) return lockfilePath;
|
|
4035
|
-
}
|
|
4036
|
-
dir = dirname(dir);
|
|
4037
|
-
}
|
|
4038
|
-
for (const [lockfile] of LOCKFILES) {
|
|
4039
|
-
const lockfilePath = join(root, lockfile);
|
|
4040
|
-
if (existsSync(lockfilePath)) return lockfilePath;
|
|
4041
|
-
}
|
|
4042
|
-
return null;
|
|
4043
|
-
}
|
|
4044
|
-
/**
|
|
4045
|
-
* Check if we're in a monorepo (lockfile is in a parent directory)
|
|
4046
|
-
*/
|
|
4047
|
-
function isMonorepo(cwd = process.cwd()) {
|
|
4048
|
-
const lockfilePath = findLockfilePath(cwd);
|
|
4049
|
-
if (!lockfilePath) return false;
|
|
4050
|
-
return dirname(lockfilePath) !== cwd;
|
|
4051
|
-
}
|
|
4052
|
-
/**
|
|
4053
|
-
* Check if turbo.json exists (walks up directory tree)
|
|
4054
|
-
*/
|
|
4055
|
-
function hasTurboConfig(cwd = process.cwd()) {
|
|
4056
|
-
let dir = cwd;
|
|
4057
|
-
const root = parse(dir).root;
|
|
4058
|
-
while (dir !== root) {
|
|
4059
|
-
if (existsSync(join(dir, "turbo.json"))) return true;
|
|
4060
|
-
dir = dirname(dir);
|
|
4061
|
-
}
|
|
4062
|
-
return existsSync(join(root, "turbo.json"));
|
|
4063
|
-
}
|
|
4064
|
-
/**
|
|
4065
|
-
* Get install command for turbo builds (without frozen lockfile)
|
|
4066
|
-
* Turbo prune creates a subset that may not perfectly match the lockfile
|
|
4067
|
-
*/
|
|
4068
|
-
function getTurboInstallCmd(pm) {
|
|
4069
|
-
return {
|
|
4070
|
-
pnpm: "pnpm install",
|
|
4071
|
-
npm: "npm install",
|
|
4072
|
-
yarn: "yarn install",
|
|
4073
|
-
bun: "bun install"
|
|
4074
|
-
}[pm];
|
|
4075
|
-
}
|
|
4076
|
-
/**
|
|
4077
|
-
* Get package manager specific commands and paths
|
|
4078
|
-
*/
|
|
4079
|
-
function getPmConfig(pm) {
|
|
4080
|
-
return {
|
|
4081
|
-
pnpm: {
|
|
4082
|
-
install: "corepack enable && corepack prepare pnpm@latest --activate",
|
|
4083
|
-
lockfile: "pnpm-lock.yaml",
|
|
4084
|
-
fetch: "pnpm fetch",
|
|
4085
|
-
installCmd: "pnpm install --frozen-lockfile --offline",
|
|
4086
|
-
cacheTarget: "/root/.local/share/pnpm/store",
|
|
4087
|
-
cacheId: "pnpm",
|
|
4088
|
-
run: "pnpm",
|
|
4089
|
-
exec: "pnpm exec",
|
|
4090
|
-
dlx: "pnpm dlx",
|
|
4091
|
-
addGlobal: "pnpm add -g"
|
|
4092
|
-
},
|
|
4093
|
-
npm: {
|
|
4094
|
-
install: "",
|
|
4095
|
-
lockfile: "package-lock.json",
|
|
4096
|
-
fetch: "",
|
|
4097
|
-
installCmd: "npm ci",
|
|
4098
|
-
cacheTarget: "/root/.npm",
|
|
4099
|
-
cacheId: "npm",
|
|
4100
|
-
run: "npm run",
|
|
4101
|
-
exec: "npx",
|
|
4102
|
-
dlx: "npx",
|
|
4103
|
-
addGlobal: "npm install -g"
|
|
4104
|
-
},
|
|
4105
|
-
yarn: {
|
|
4106
|
-
install: "corepack enable && corepack prepare yarn@stable --activate",
|
|
4107
|
-
lockfile: "yarn.lock",
|
|
4108
|
-
fetch: "",
|
|
4109
|
-
installCmd: "yarn install --frozen-lockfile",
|
|
4110
|
-
cacheTarget: "/root/.yarn/cache",
|
|
4111
|
-
cacheId: "yarn",
|
|
4112
|
-
run: "yarn",
|
|
4113
|
-
exec: "yarn exec",
|
|
4114
|
-
dlx: "yarn dlx",
|
|
4115
|
-
addGlobal: "yarn global add"
|
|
4116
|
-
},
|
|
4117
|
-
bun: {
|
|
4118
|
-
install: "npm install -g bun",
|
|
4119
|
-
lockfile: "bun.lockb",
|
|
4120
|
-
fetch: "",
|
|
4121
|
-
installCmd: "bun install --frozen-lockfile",
|
|
4122
|
-
cacheTarget: "/root/.bun/install/cache",
|
|
4123
|
-
cacheId: "bun",
|
|
4124
|
-
run: "bun run",
|
|
4125
|
-
exec: "bunx",
|
|
4126
|
-
dlx: "bunx",
|
|
4127
|
-
addGlobal: "bun add -g"
|
|
4128
|
-
}
|
|
4129
|
-
}[pm];
|
|
4130
|
-
}
|
|
4131
|
-
/**
|
|
4132
|
-
* Generate a multi-stage Dockerfile for building from source
|
|
4133
|
-
* Optimized for build speed with:
|
|
4134
|
-
* - BuildKit cache mounts for package manager store
|
|
4135
|
-
* - pnpm fetch for better layer caching (when using pnpm)
|
|
4136
|
-
* - Optional turbo prune for monorepos
|
|
4137
|
-
*/
|
|
4138
|
-
function generateMultiStageDockerfile(options) {
|
|
4139
|
-
const { baseImage, port, healthCheckPath, turbo, turboPackage, packageManager } = options;
|
|
4140
|
-
if (turbo) return generateTurboDockerfile({
|
|
4141
|
-
...options,
|
|
4142
|
-
turboPackage: turboPackage ?? "api"
|
|
4143
|
-
});
|
|
3682
|
+
function generateNextjsDockerfile(options) {
|
|
3683
|
+
const { baseImage, port, appPath, turboPackage, packageManager, publicUrlArgs = ["NEXT_PUBLIC_API_URL", "NEXT_PUBLIC_AUTH_URL"] } = options;
|
|
4144
3684
|
const pm = getPmConfig(packageManager);
|
|
3685
|
+
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
3686
|
+
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
3687
|
+
const turboCmd = packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo";
|
|
3688
|
+
const publicUrlArgDeclarations = publicUrlArgs.map((arg) => `ARG ${arg}=""`).join("\n");
|
|
3689
|
+
const publicUrlEnvDeclarations = publicUrlArgs.map((arg) => `ENV ${arg}=$${arg}`).join("\n");
|
|
4145
3690
|
return `# syntax=docker/dockerfile:1
|
|
4146
|
-
#
|
|
4147
|
-
FROM ${baseImage} AS deps
|
|
3691
|
+
# Next.js standalone Dockerfile with turbo prune optimization
|
|
4148
3692
|
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
${packageManager === "pnpm" ? `# Copy lockfile first for better caching
|
|
4152
|
-
COPY ${pm.lockfile} ./
|
|
3693
|
+
# Stage 1: Prune monorepo
|
|
3694
|
+
FROM ${baseImage} AS pruner
|
|
4153
3695
|
|
|
4154
|
-
|
|
4155
|
-
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4156
|
-
${pm.fetch}
|
|
3696
|
+
WORKDIR /app
|
|
4157
3697
|
|
|
4158
|
-
|
|
4159
|
-
COPY package.json ./
|
|
3698
|
+
${installPm}
|
|
4160
3699
|
|
|
4161
|
-
|
|
4162
|
-
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4163
|
-
${pm.installCmd}` : `# Copy package files
|
|
4164
|
-
COPY package.json ${pm.lockfile} ./
|
|
3700
|
+
COPY . .
|
|
4165
3701
|
|
|
4166
|
-
#
|
|
4167
|
-
RUN
|
|
4168
|
-
${pm.installCmd}`}
|
|
3702
|
+
# Prune to only include necessary packages
|
|
3703
|
+
RUN ${turboCmd} prune ${turboPackage} --docker
|
|
4169
3704
|
|
|
4170
|
-
# Stage 2:
|
|
4171
|
-
FROM
|
|
3705
|
+
# Stage 2: Install dependencies
|
|
3706
|
+
FROM ${baseImage} AS deps
|
|
4172
3707
|
|
|
4173
3708
|
WORKDIR /app
|
|
4174
3709
|
|
|
4175
|
-
|
|
4176
|
-
COPY . .
|
|
3710
|
+
${installPm}
|
|
4177
3711
|
|
|
4178
|
-
#
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
# for one whose CLI is a sibling package: \`turbo prune\` honours .gitignore, so a
|
|
4182
|
-
# workspace package's \`dist\` never reaches the image and its bin has nothing to
|
|
4183
|
-
# import. \`--if-present\` is what makes the same Dockerfile correct for both.
|
|
4184
|
-
RUN ${pm.run} --if-present build
|
|
3712
|
+
# Copy pruned lockfile and package.jsons
|
|
3713
|
+
COPY --from=pruner /app/out/${pm.lockfile} ./
|
|
3714
|
+
COPY --from=pruner /app/out/json/ ./
|
|
4185
3715
|
|
|
4186
|
-
#
|
|
4187
|
-
RUN
|
|
3716
|
+
# Install dependencies
|
|
3717
|
+
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
3718
|
+
${turboInstallCmd}
|
|
4188
3719
|
|
|
4189
|
-
# Stage 3:
|
|
4190
|
-
FROM
|
|
3720
|
+
# Stage 3: Build
|
|
3721
|
+
FROM deps AS builder
|
|
4191
3722
|
|
|
4192
3723
|
WORKDIR /app
|
|
4193
3724
|
|
|
4194
|
-
#
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
# Create non-root user
|
|
4198
|
-
RUN addgroup --system --gid 1001 nodejs && \\
|
|
4199
|
-
adduser --system --uid 1001 hono
|
|
3725
|
+
# Build-time args for public API URLs (populated by gkm deploy)
|
|
3726
|
+
# These get baked into the Next.js build as public environment variables
|
|
3727
|
+
${publicUrlArgDeclarations}
|
|
4200
3728
|
|
|
4201
|
-
#
|
|
4202
|
-
|
|
3729
|
+
# Convert ARGs to ENVs for Next.js build
|
|
3730
|
+
${publicUrlEnvDeclarations}
|
|
4203
3731
|
|
|
4204
|
-
#
|
|
3732
|
+
# Copy pruned source
|
|
3733
|
+
COPY --from=pruner /app/out/full/ ./
|
|
3734
|
+
|
|
3735
|
+
# Copy workspace root configs for turbo builds (turbo prune doesn't include root configs)
|
|
3736
|
+
# Using wildcard to make it optional for single-app projects
|
|
3737
|
+
COPY --from=pruner /app/tsconfig.* ./
|
|
3738
|
+
|
|
3739
|
+
# Ensure public directory exists (may be empty for scaffolded projects)
|
|
3740
|
+
RUN mkdir -p ${appPath}/public
|
|
3741
|
+
|
|
3742
|
+
# Set Next.js to produce standalone output
|
|
3743
|
+
ENV NEXT_TELEMETRY_DISABLED=1
|
|
3744
|
+
|
|
3745
|
+
# Build the application
|
|
3746
|
+
RUN ${turboCmd} run build --filter=${turboPackage}
|
|
3747
|
+
|
|
3748
|
+
# Stage 4: Production
|
|
3749
|
+
FROM ${baseImage} AS runner
|
|
3750
|
+
|
|
3751
|
+
WORKDIR /app
|
|
3752
|
+
|
|
3753
|
+
# Install tini for proper signal handling
|
|
3754
|
+
RUN apk add --no-cache tini
|
|
3755
|
+
|
|
3756
|
+
# Create non-root user
|
|
3757
|
+
RUN addgroup --system --gid 1001 nodejs && \\
|
|
3758
|
+
adduser --system --uid 1001 nextjs
|
|
3759
|
+
|
|
3760
|
+
# Set environment
|
|
4205
3761
|
ENV NODE_ENV=production
|
|
3762
|
+
ENV NEXT_TELEMETRY_DISABLED=1
|
|
4206
3763
|
ENV PORT=${port}
|
|
3764
|
+
ENV HOSTNAME="0.0.0.0"
|
|
4207
3765
|
|
|
4208
|
-
#
|
|
4209
|
-
|
|
4210
|
-
|
|
3766
|
+
# Copy static files and standalone output
|
|
3767
|
+
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/standalone ./
|
|
3768
|
+
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/static ./${appPath}/.next/static
|
|
3769
|
+
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/public ./${appPath}/public
|
|
4211
3770
|
|
|
4212
|
-
|
|
4213
|
-
USER hono
|
|
3771
|
+
USER nextjs
|
|
4214
3772
|
|
|
4215
3773
|
EXPOSE ${port}
|
|
4216
3774
|
|
|
4217
|
-
# Use tini as entrypoint to handle PID 1 responsibilities
|
|
4218
3775
|
ENTRYPOINT ["/sbin/tini", "--"]
|
|
4219
|
-
CMD ["node", "server.
|
|
3776
|
+
CMD ["node", "${appPath}/server.js"]
|
|
4220
3777
|
`;
|
|
4221
3778
|
}
|
|
4222
3779
|
/**
|
|
4223
|
-
* Generate a Dockerfile
|
|
4224
|
-
* Uses turbo prune
|
|
3780
|
+
* Generate a Dockerfile for backend apps in a workspace.
|
|
3781
|
+
* Uses turbo prune for monorepo optimization.
|
|
3782
|
+
* @internal Exported for testing
|
|
4225
3783
|
*/
|
|
4226
|
-
function
|
|
4227
|
-
const { baseImage, port,
|
|
3784
|
+
function generateBackendDockerfile(options) {
|
|
3785
|
+
const { baseImage, port, appPath, turboPackage, packageManager, healthCheckPath = "/health" } = options;
|
|
4228
3786
|
const pm = getPmConfig(packageManager);
|
|
4229
3787
|
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
4230
3788
|
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
4231
3789
|
return `# syntax=docker/dockerfile:1
|
|
3790
|
+
# Backend Dockerfile with turbo prune optimization
|
|
3791
|
+
|
|
4232
3792
|
# Stage 1: Prune monorepo
|
|
4233
3793
|
FROM ${baseImage} AS pruner
|
|
4234
3794
|
|
|
@@ -4252,7 +3812,7 @@ ${installPm}
|
|
|
4252
3812
|
COPY --from=pruner /app/out/${pm.lockfile} ./
|
|
4253
3813
|
COPY --from=pruner /app/out/json/ ./
|
|
4254
3814
|
|
|
4255
|
-
# Install dependencies
|
|
3815
|
+
# Install dependencies
|
|
4256
3816
|
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4257
3817
|
${turboInstallCmd}
|
|
4258
3818
|
|
|
@@ -4264,6 +3824,22 @@ WORKDIR /app
|
|
|
4264
3824
|
# Copy pruned source
|
|
4265
3825
|
COPY --from=pruner /app/out/full/ ./
|
|
4266
3826
|
|
|
3827
|
+
# Copy workspace root configs for turbo builds (turbo prune doesn't include root configs)
|
|
3828
|
+
# Using wildcard to make it optional for single-app projects
|
|
3829
|
+
COPY --from=pruner /app/gkm.config.* ./
|
|
3830
|
+
COPY --from=pruner /app/tsconfig.* ./
|
|
3831
|
+
|
|
3832
|
+
# Write encrypted credentials for gkm build to embed.
|
|
3833
|
+
# A build secret (\`docker build --secret id=gkm_credentials,src=…\`), not an
|
|
3834
|
+
# ARG: an ARG is recorded in the image history. Two lines, ciphertext then IV;
|
|
3835
|
+
# absent when the app has no secrets.
|
|
3836
|
+
RUN --mount=type=secret,id=gkm_credentials,required=false \
|
|
3837
|
+
if [ -s /run/secrets/gkm_credentials ]; then \
|
|
3838
|
+
mkdir -p ${appPath}/.gkm && \
|
|
3839
|
+
sed -n 1p /run/secrets/gkm_credentials > ${appPath}/.gkm/credentials.enc && \
|
|
3840
|
+
sed -n 2p /run/secrets/gkm_credentials > ${appPath}/.gkm/credentials.iv; \
|
|
3841
|
+
fi
|
|
3842
|
+
|
|
4267
3843
|
# Build any workspace packages the app depends on.
|
|
4268
3844
|
#
|
|
4269
3845
|
# A no-op for a project whose dependencies come from a registry, and required
|
|
@@ -4273,7 +3849,7 @@ COPY --from=pruner /app/out/full/ ./
|
|
|
4273
3849
|
RUN ${pm.run} --if-present build
|
|
4274
3850
|
|
|
4275
3851
|
# Build production server using gkm
|
|
4276
|
-
RUN ${pm.exec} gkm build --provider server --production
|
|
3852
|
+
RUN cd ${appPath} && ${pm.exec} gkm build --provider server --production
|
|
4277
3853
|
|
|
4278
3854
|
# Stage 4: Production
|
|
4279
3855
|
FROM ${baseImage} AS runner
|
|
@@ -4285,163 +3861,36 @@ RUN apk add --no-cache tini
|
|
|
4285
3861
|
RUN addgroup --system --gid 1001 nodejs && \\
|
|
4286
3862
|
adduser --system --uid 1001 hono
|
|
4287
3863
|
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
ENV NODE_ENV=production
|
|
4291
|
-
ENV PORT=${port}
|
|
4292
|
-
|
|
4293
|
-
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
4294
|
-
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
4295
|
-
|
|
4296
|
-
USER hono
|
|
4297
|
-
|
|
4298
|
-
EXPOSE ${port}
|
|
4299
|
-
|
|
4300
|
-
ENTRYPOINT ["/sbin/tini", "--"]
|
|
4301
|
-
CMD ["node", "server.mjs"]
|
|
4302
|
-
`;
|
|
4303
|
-
}
|
|
4304
|
-
/**
|
|
4305
|
-
* Generate a slim Dockerfile for pre-built bundles
|
|
4306
|
-
*/
|
|
4307
|
-
function generateSlimDockerfile(options) {
|
|
4308
|
-
const { baseImage, port, healthCheckPath, bundle = ".gkm/server/dist/server.mjs" } = options;
|
|
4309
|
-
return `# Slim Dockerfile for pre-built production bundle
|
|
4310
|
-
FROM ${baseImage}
|
|
4311
|
-
|
|
4312
|
-
WORKDIR /app
|
|
4313
|
-
|
|
4314
|
-
# Install tini for proper signal handling as PID 1
|
|
4315
|
-
# Handles SIGTERM propagation and zombie process reaping
|
|
4316
|
-
RUN apk add --no-cache tini
|
|
4317
|
-
|
|
4318
|
-
# Create non-root user
|
|
4319
|
-
RUN addgroup --system --gid 1001 nodejs && \\
|
|
4320
|
-
adduser --system --uid 1001 hono
|
|
4321
|
-
|
|
4322
|
-
# Copy pre-built bundle
|
|
4323
|
-
COPY ${bundle} ./
|
|
3864
|
+
# Copy bundled server
|
|
3865
|
+
COPY --from=builder --chown=hono:nodejs /app/${appPath}/.gkm/server/dist/server.mjs ./
|
|
4324
3866
|
|
|
4325
|
-
# Environment
|
|
4326
3867
|
ENV NODE_ENV=production
|
|
4327
3868
|
ENV PORT=${port}
|
|
4328
3869
|
|
|
4329
|
-
# Health check
|
|
4330
3870
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
4331
3871
|
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
4332
3872
|
|
|
4333
|
-
# Switch to non-root user
|
|
4334
3873
|
USER hono
|
|
4335
3874
|
|
|
4336
3875
|
EXPOSE ${port}
|
|
4337
3876
|
|
|
4338
|
-
# Use tini as entrypoint to handle PID 1 responsibilities
|
|
4339
3877
|
ENTRYPOINT ["/sbin/tini", "--"]
|
|
4340
3878
|
CMD ["node", "server.mjs"]
|
|
4341
3879
|
`;
|
|
4342
3880
|
}
|
|
4343
3881
|
/**
|
|
4344
|
-
* Generate .
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
return `# Dependencies
|
|
4348
|
-
node_modules
|
|
4349
|
-
.pnpm-store
|
|
4350
|
-
|
|
4351
|
-
# Build output (except what we need)
|
|
4352
|
-
.gkm/aws*
|
|
4353
|
-
.gkm/server/*.ts
|
|
4354
|
-
!.gkm/server/dist
|
|
4355
|
-
|
|
4356
|
-
# The key gkm build --stage encrypted secrets with: runtime env only, never
|
|
4357
|
-
# the build context
|
|
4358
|
-
.gkm/server/master.key
|
|
4359
|
-
|
|
4360
|
-
# gkm compose's stacks: each app's env file holds its stage's secrets
|
|
4361
|
-
.gkm/compose
|
|
4362
|
-
|
|
4363
|
-
# IDE and editor
|
|
4364
|
-
.idea
|
|
4365
|
-
.vscode
|
|
4366
|
-
*.swp
|
|
4367
|
-
*.swo
|
|
4368
|
-
|
|
4369
|
-
# Git
|
|
4370
|
-
.git
|
|
4371
|
-
.gitignore
|
|
4372
|
-
|
|
4373
|
-
# Logs
|
|
4374
|
-
*.log
|
|
4375
|
-
npm-debug.log*
|
|
4376
|
-
pnpm-debug.log*
|
|
4377
|
-
|
|
4378
|
-
# Test files
|
|
4379
|
-
**/*.test.ts
|
|
4380
|
-
**/*.spec.ts
|
|
4381
|
-
**/__tests__
|
|
4382
|
-
coverage
|
|
4383
|
-
|
|
4384
|
-
# Documentation
|
|
4385
|
-
docs
|
|
4386
|
-
*.md
|
|
4387
|
-
!README.md
|
|
4388
|
-
|
|
4389
|
-
# Environment files (handle secrets separately)
|
|
4390
|
-
.env
|
|
4391
|
-
.env.*
|
|
4392
|
-
!.env.example
|
|
4393
|
-
|
|
4394
|
-
# Docker files (don't copy recursively)
|
|
4395
|
-
Dockerfile*
|
|
4396
|
-
docker-compose*
|
|
4397
|
-
.dockerignore
|
|
4398
|
-
`;
|
|
4399
|
-
}
|
|
4400
|
-
/**
|
|
4401
|
-
* Generate docker-entrypoint.sh for custom startup logic
|
|
4402
|
-
*/
|
|
4403
|
-
function generateDockerEntrypoint() {
|
|
4404
|
-
return `#!/bin/sh
|
|
4405
|
-
set -e
|
|
4406
|
-
|
|
4407
|
-
# Run any custom startup scripts here
|
|
4408
|
-
# Example: wait for database
|
|
4409
|
-
# until nc -z $DB_HOST $DB_PORT; do
|
|
4410
|
-
# echo "Waiting for database..."
|
|
4411
|
-
# sleep 1
|
|
4412
|
-
# done
|
|
4413
|
-
|
|
4414
|
-
# Execute the main command
|
|
4415
|
-
exec "$@"
|
|
4416
|
-
`;
|
|
4417
|
-
}
|
|
4418
|
-
/**
|
|
4419
|
-
* Resolve Docker configuration from GkmConfig with defaults
|
|
4420
|
-
*/
|
|
4421
|
-
function resolveDockerConfig(config) {
|
|
4422
|
-
const docker = config.docker ?? {};
|
|
4423
|
-
return {
|
|
4424
|
-
registry: docker.registry ?? "",
|
|
4425
|
-
imageName: docker.imageName ?? config.name ?? "api",
|
|
4426
|
-
baseImage: docker.baseImage ?? "node:22-alpine",
|
|
4427
|
-
port: docker.port ?? 3e3
|
|
4428
|
-
};
|
|
4429
|
-
}
|
|
4430
|
-
/**
|
|
4431
|
-
* Generate a Dockerfile for Next.js frontend apps using standalone output.
|
|
4432
|
-
* Uses turbo prune for monorepo optimization.
|
|
3882
|
+
* Generate a Dockerfile for apps with a custom entry point.
|
|
3883
|
+
* Uses esbuild to bundle the entry point into dist/index.mjs with all dependencies.
|
|
3884
|
+
* This is used for apps that don't use gkm routes (e.g., Better Auth servers).
|
|
4433
3885
|
* @internal Exported for testing
|
|
4434
3886
|
*/
|
|
4435
|
-
function
|
|
4436
|
-
const { baseImage, port, appPath, turboPackage, packageManager,
|
|
3887
|
+
function generateEntryDockerfile(options) {
|
|
3888
|
+
const { baseImage, port, appPath, entry, turboPackage, packageManager, healthCheckPath = "/health" } = options;
|
|
4437
3889
|
const pm = getPmConfig(packageManager);
|
|
4438
3890
|
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
4439
3891
|
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
4440
|
-
const turboCmd = packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo";
|
|
4441
|
-
const publicUrlArgDeclarations = publicUrlArgs.map((arg) => `ARG ${arg}=""`).join("\n");
|
|
4442
|
-
const publicUrlEnvDeclarations = publicUrlArgs.map((arg) => `ENV ${arg}=$${arg}`).join("\n");
|
|
4443
3892
|
return `# syntax=docker/dockerfile:1
|
|
4444
|
-
#
|
|
3893
|
+
# Entry-based Dockerfile with turbo prune + tsdown bundling
|
|
4445
3894
|
|
|
4446
3895
|
# Stage 1: Prune monorepo
|
|
4447
3896
|
FROM ${baseImage} AS pruner
|
|
@@ -4453,7 +3902,7 @@ ${installPm}
|
|
|
4453
3902
|
COPY . .
|
|
4454
3903
|
|
|
4455
3904
|
# Prune to only include necessary packages
|
|
4456
|
-
RUN ${
|
|
3905
|
+
RUN ${packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo"} prune ${turboPackage} --docker
|
|
4457
3906
|
|
|
4458
3907
|
# Stage 2: Install dependencies
|
|
4459
3908
|
FROM ${baseImage} AS deps
|
|
@@ -4470,18 +3919,11 @@ COPY --from=pruner /app/out/json/ ./
|
|
|
4470
3919
|
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4471
3920
|
${turboInstallCmd}
|
|
4472
3921
|
|
|
4473
|
-
# Stage 3: Build
|
|
3922
|
+
# Stage 3: Build with tsdown
|
|
4474
3923
|
FROM deps AS builder
|
|
4475
3924
|
|
|
4476
3925
|
WORKDIR /app
|
|
4477
3926
|
|
|
4478
|
-
# Build-time args for public API URLs (populated by gkm deploy)
|
|
4479
|
-
# These get baked into the Next.js build as public environment variables
|
|
4480
|
-
${publicUrlArgDeclarations}
|
|
4481
|
-
|
|
4482
|
-
# Convert ARGs to ENVs for Next.js build
|
|
4483
|
-
${publicUrlEnvDeclarations}
|
|
4484
|
-
|
|
4485
3927
|
# Copy pruned source
|
|
4486
3928
|
COPY --from=pruner /app/out/full/ ./
|
|
4487
3929
|
|
|
@@ -4489,222 +3931,27 @@ COPY --from=pruner /app/out/full/ ./
|
|
|
4489
3931
|
# Using wildcard to make it optional for single-app projects
|
|
4490
3932
|
COPY --from=pruner /app/tsconfig.* ./
|
|
4491
3933
|
|
|
4492
|
-
#
|
|
4493
|
-
|
|
4494
|
-
|
|
4495
|
-
#
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
# Set environment
|
|
4514
|
-
ENV NODE_ENV=production
|
|
4515
|
-
ENV NEXT_TELEMETRY_DISABLED=1
|
|
4516
|
-
ENV PORT=${port}
|
|
4517
|
-
ENV HOSTNAME="0.0.0.0"
|
|
4518
|
-
|
|
4519
|
-
# Copy static files and standalone output
|
|
4520
|
-
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/standalone ./
|
|
4521
|
-
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/static ./${appPath}/.next/static
|
|
4522
|
-
COPY --from=builder --chown=nextjs:nodejs /app/${appPath}/public ./${appPath}/public
|
|
4523
|
-
|
|
4524
|
-
USER nextjs
|
|
4525
|
-
|
|
4526
|
-
EXPOSE ${port}
|
|
4527
|
-
|
|
4528
|
-
ENTRYPOINT ["/sbin/tini", "--"]
|
|
4529
|
-
CMD ["node", "${appPath}/server.js"]
|
|
4530
|
-
`;
|
|
4531
|
-
}
|
|
4532
|
-
/**
|
|
4533
|
-
* Generate a Dockerfile for backend apps in a workspace.
|
|
4534
|
-
* Uses turbo prune for monorepo optimization.
|
|
4535
|
-
* @internal Exported for testing
|
|
4536
|
-
*/
|
|
4537
|
-
function generateBackendDockerfile(options) {
|
|
4538
|
-
const { baseImage, port, appPath, turboPackage, packageManager, healthCheckPath = "/health" } = options;
|
|
4539
|
-
const pm = getPmConfig(packageManager);
|
|
4540
|
-
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
4541
|
-
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
4542
|
-
return `# syntax=docker/dockerfile:1
|
|
4543
|
-
# Backend Dockerfile with turbo prune optimization
|
|
4544
|
-
|
|
4545
|
-
# Stage 1: Prune monorepo
|
|
4546
|
-
FROM ${baseImage} AS pruner
|
|
4547
|
-
|
|
4548
|
-
WORKDIR /app
|
|
4549
|
-
|
|
4550
|
-
${installPm}
|
|
4551
|
-
|
|
4552
|
-
COPY . .
|
|
4553
|
-
|
|
4554
|
-
# Prune to only include necessary packages
|
|
4555
|
-
RUN ${packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo"} prune ${turboPackage} --docker
|
|
4556
|
-
|
|
4557
|
-
# Stage 2: Install dependencies
|
|
4558
|
-
FROM ${baseImage} AS deps
|
|
4559
|
-
|
|
4560
|
-
WORKDIR /app
|
|
4561
|
-
|
|
4562
|
-
${installPm}
|
|
4563
|
-
|
|
4564
|
-
# Copy pruned lockfile and package.jsons
|
|
4565
|
-
COPY --from=pruner /app/out/${pm.lockfile} ./
|
|
4566
|
-
COPY --from=pruner /app/out/json/ ./
|
|
4567
|
-
|
|
4568
|
-
# Install dependencies
|
|
4569
|
-
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4570
|
-
${turboInstallCmd}
|
|
4571
|
-
|
|
4572
|
-
# Stage 3: Build
|
|
4573
|
-
FROM deps AS builder
|
|
4574
|
-
|
|
4575
|
-
WORKDIR /app
|
|
4576
|
-
|
|
4577
|
-
# Copy pruned source
|
|
4578
|
-
COPY --from=pruner /app/out/full/ ./
|
|
4579
|
-
|
|
4580
|
-
# Copy workspace root configs for turbo builds (turbo prune doesn't include root configs)
|
|
4581
|
-
# Using wildcard to make it optional for single-app projects
|
|
4582
|
-
COPY --from=pruner /app/gkm.config.* ./
|
|
4583
|
-
COPY --from=pruner /app/tsconfig.* ./
|
|
4584
|
-
|
|
4585
|
-
# Write encrypted credentials for gkm build to embed.
|
|
4586
|
-
# A build secret (\`docker build --secret id=gkm_credentials,src=…\`), not an
|
|
4587
|
-
# ARG: an ARG is recorded in the image history. Two lines, ciphertext then IV;
|
|
4588
|
-
# absent when the app has no secrets.
|
|
4589
|
-
RUN --mount=type=secret,id=gkm_credentials,required=false \
|
|
4590
|
-
if [ -s /run/secrets/gkm_credentials ]; then \
|
|
4591
|
-
mkdir -p ${appPath}/.gkm && \
|
|
4592
|
-
sed -n 1p /run/secrets/gkm_credentials > ${appPath}/.gkm/credentials.enc && \
|
|
4593
|
-
sed -n 2p /run/secrets/gkm_credentials > ${appPath}/.gkm/credentials.iv; \
|
|
4594
|
-
fi
|
|
4595
|
-
|
|
4596
|
-
# Build any workspace packages the app depends on.
|
|
4597
|
-
#
|
|
4598
|
-
# A no-op for a project whose dependencies come from a registry, and required
|
|
4599
|
-
# for one whose CLI is a sibling package: \`turbo prune\` honours .gitignore, so a
|
|
4600
|
-
# workspace package's \`dist\` never reaches the image and its bin has nothing to
|
|
4601
|
-
# import. \`--if-present\` is what makes the same Dockerfile correct for both.
|
|
4602
|
-
RUN ${pm.run} --if-present build
|
|
4603
|
-
|
|
4604
|
-
# Build production server using gkm
|
|
4605
|
-
RUN cd ${appPath} && ${pm.exec} gkm build --provider server --production
|
|
4606
|
-
|
|
4607
|
-
# Stage 4: Production
|
|
4608
|
-
FROM ${baseImage} AS runner
|
|
4609
|
-
|
|
4610
|
-
WORKDIR /app
|
|
4611
|
-
|
|
4612
|
-
RUN apk add --no-cache tini
|
|
4613
|
-
|
|
4614
|
-
RUN addgroup --system --gid 1001 nodejs && \\
|
|
4615
|
-
adduser --system --uid 1001 hono
|
|
4616
|
-
|
|
4617
|
-
# Copy bundled server
|
|
4618
|
-
COPY --from=builder --chown=hono:nodejs /app/${appPath}/.gkm/server/dist/server.mjs ./
|
|
4619
|
-
|
|
4620
|
-
ENV NODE_ENV=production
|
|
4621
|
-
ENV PORT=${port}
|
|
4622
|
-
|
|
4623
|
-
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
|
|
4624
|
-
CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1
|
|
4625
|
-
|
|
4626
|
-
USER hono
|
|
4627
|
-
|
|
4628
|
-
EXPOSE ${port}
|
|
4629
|
-
|
|
4630
|
-
ENTRYPOINT ["/sbin/tini", "--"]
|
|
4631
|
-
CMD ["node", "server.mjs"]
|
|
4632
|
-
`;
|
|
4633
|
-
}
|
|
4634
|
-
/**
|
|
4635
|
-
* Generate a Dockerfile for apps with a custom entry point.
|
|
4636
|
-
* Uses esbuild to bundle the entry point into dist/index.mjs with all dependencies.
|
|
4637
|
-
* This is used for apps that don't use gkm routes (e.g., Better Auth servers).
|
|
4638
|
-
* @internal Exported for testing
|
|
4639
|
-
*/
|
|
4640
|
-
function generateEntryDockerfile(options) {
|
|
4641
|
-
const { baseImage, port, appPath, entry, turboPackage, packageManager, healthCheckPath = "/health" } = options;
|
|
4642
|
-
const pm = getPmConfig(packageManager);
|
|
4643
|
-
const installPm = pm.install ? `RUN ${pm.install}` : "";
|
|
4644
|
-
const turboInstallCmd = getTurboInstallCmd(packageManager);
|
|
4645
|
-
return `# syntax=docker/dockerfile:1
|
|
4646
|
-
# Entry-based Dockerfile with turbo prune + tsdown bundling
|
|
4647
|
-
|
|
4648
|
-
# Stage 1: Prune monorepo
|
|
4649
|
-
FROM ${baseImage} AS pruner
|
|
4650
|
-
|
|
4651
|
-
WORKDIR /app
|
|
4652
|
-
|
|
4653
|
-
${installPm}
|
|
4654
|
-
|
|
4655
|
-
COPY . .
|
|
4656
|
-
|
|
4657
|
-
# Prune to only include necessary packages
|
|
4658
|
-
RUN ${packageManager === "pnpm" ? "pnpm dlx turbo" : "npx turbo"} prune ${turboPackage} --docker
|
|
4659
|
-
|
|
4660
|
-
# Stage 2: Install dependencies
|
|
4661
|
-
FROM ${baseImage} AS deps
|
|
4662
|
-
|
|
4663
|
-
WORKDIR /app
|
|
4664
|
-
|
|
4665
|
-
${installPm}
|
|
4666
|
-
|
|
4667
|
-
# Copy pruned lockfile and package.jsons
|
|
4668
|
-
COPY --from=pruner /app/out/${pm.lockfile} ./
|
|
4669
|
-
COPY --from=pruner /app/out/json/ ./
|
|
4670
|
-
|
|
4671
|
-
# Install dependencies
|
|
4672
|
-
RUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\
|
|
4673
|
-
${turboInstallCmd}
|
|
4674
|
-
|
|
4675
|
-
# Stage 3: Build with tsdown
|
|
4676
|
-
FROM deps AS builder
|
|
4677
|
-
|
|
4678
|
-
WORKDIR /app
|
|
4679
|
-
|
|
4680
|
-
# Copy pruned source
|
|
4681
|
-
COPY --from=pruner /app/out/full/ ./
|
|
4682
|
-
|
|
4683
|
-
# Copy workspace root configs for turbo builds (turbo prune doesn't include root configs)
|
|
4684
|
-
# Using wildcard to make it optional for single-app projects
|
|
4685
|
-
COPY --from=pruner /app/tsconfig.* ./
|
|
4686
|
-
|
|
4687
|
-
# Bundle entry point with esbuild (outputs to dist/index.mjs)
|
|
4688
|
-
# Creates a fully standalone bundle with all dependencies included
|
|
4689
|
-
# Use define to embed credentials if present.
|
|
4690
|
-
# They arrive as a build secret (\`docker build --secret id=gkm_credentials,src=…\`),
|
|
4691
|
-
# not an ARG: an ARG is recorded in the image history. Two lines, ciphertext
|
|
4692
|
-
# then IV; absent when the app has no secrets.
|
|
4693
|
-
RUN --mount=type=secret,id=gkm_credentials,required=false \
|
|
4694
|
-
cd ${appPath} && \
|
|
4695
|
-
if [ -s /run/secrets/gkm_credentials ]; then \
|
|
4696
|
-
CREDS=$(sed -n 1p /run/secrets/gkm_credentials) && \
|
|
4697
|
-
IV=$(sed -n 2p /run/secrets/gkm_credentials) && \
|
|
4698
|
-
npx esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \
|
|
4699
|
-
--outfile=dist/index.mjs --packages=bundle \
|
|
4700
|
-
--banner:js='import { createRequire } from "module"; const require = createRequire(import.meta.url);' \
|
|
4701
|
-
--define:__GKM_ENCRYPTED_CREDENTIALS__="'\\"$CREDS\\"'" \
|
|
4702
|
-
--define:__GKM_CREDENTIALS_IV__="'\\"$IV\\"'"; \
|
|
4703
|
-
else \
|
|
4704
|
-
npx esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \
|
|
4705
|
-
--outfile=dist/index.mjs --packages=bundle \
|
|
4706
|
-
--banner:js='import { createRequire } from "module"; const require = createRequire(import.meta.url);'; \
|
|
4707
|
-
fi
|
|
3934
|
+
# Bundle entry point with esbuild (outputs to dist/index.mjs)
|
|
3935
|
+
# Creates a fully standalone bundle with all dependencies included
|
|
3936
|
+
# Use define to embed credentials if present.
|
|
3937
|
+
# They arrive as a build secret (\`docker build --secret id=gkm_credentials,src=…\`),
|
|
3938
|
+
# not an ARG: an ARG is recorded in the image history. Two lines, ciphertext
|
|
3939
|
+
# then IV; absent when the app has no secrets.
|
|
3940
|
+
RUN --mount=type=secret,id=gkm_credentials,required=false \
|
|
3941
|
+
cd ${appPath} && \
|
|
3942
|
+
if [ -s /run/secrets/gkm_credentials ]; then \
|
|
3943
|
+
CREDS=$(sed -n 1p /run/secrets/gkm_credentials) && \
|
|
3944
|
+
IV=$(sed -n 2p /run/secrets/gkm_credentials) && \
|
|
3945
|
+
npx esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \
|
|
3946
|
+
--outfile=dist/index.mjs --packages=bundle \
|
|
3947
|
+
--banner:js='import { createRequire } from "module"; const require = createRequire(import.meta.url);' \
|
|
3948
|
+
--define:__GKM_ENCRYPTED_CREDENTIALS__="'\\"$CREDS\\"'" \
|
|
3949
|
+
--define:__GKM_CREDENTIALS_IV__="'\\"$IV\\"'"; \
|
|
3950
|
+
else \
|
|
3951
|
+
npx esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \
|
|
3952
|
+
--outfile=dist/index.mjs --packages=bundle \
|
|
3953
|
+
--banner:js='import { createRequire } from "module"; const require = createRequire(import.meta.url);'; \
|
|
3954
|
+
fi
|
|
4708
3955
|
|
|
4709
3956
|
# Stage 4: Production
|
|
4710
3957
|
FROM ${baseImage} AS runner
|
|
@@ -5085,1167 +4332,333 @@ async function workspaceDockerCommand(workspace, manifest) {
|
|
|
5085
4332
|
imageName
|
|
5086
4333
|
});
|
|
5087
4334
|
}
|
|
5088
|
-
const dockerignore = generateDockerignore();
|
|
5089
|
-
const dockerignorePath = join(workspace.root, ".dockerignore");
|
|
5090
|
-
await writeFile(dockerignorePath, dockerignore);
|
|
5091
|
-
logger.log(`\n Generated: .dockerignore (workspace root)`);
|
|
5092
|
-
const composePath = await writeConstructsCompose(workspace);
|
|
5093
|
-
logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
|
|
5094
|
-
logger.log("\n📋 Build commands:");
|
|
5095
|
-
for (const result of results) {
|
|
5096
|
-
const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
|
|
5097
|
-
logger.log(` ${icon} docker build -f .gkm/docker/Dockerfile.${result.appName} -t ${result.imageName} .`);
|
|
5098
|
-
}
|
|
5099
|
-
printRunInstructions(workspace);
|
|
5100
|
-
return {
|
|
5101
|
-
apps: results,
|
|
5102
|
-
dockerCompose: composePath,
|
|
5103
|
-
dockerignore: dockerignorePath
|
|
5104
|
-
};
|
|
5105
|
-
}
|
|
5106
|
-
/**
|
|
5107
|
-
* A site's Dockerfile, with an `ARG` for every key its bundler inlines.
|
|
5108
|
-
*
|
|
5109
|
-
* The keys come from the site's declaration where there is one — every
|
|
5110
|
-
* public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an
|
|
5111
|
-
* `ARG` the Dockerfile does not declare is a build argument the build drops,
|
|
5112
|
-
* leaving the bundle with an empty URL.
|
|
5113
|
-
*/
|
|
5114
|
-
function siteDockerfile(appName, app, options) {
|
|
5115
|
-
const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
|
|
5116
|
-
const publicUrlArgs = declared?.kind === "site" && options.manifest ? Object.keys(publicEnvFor(declared, options.manifest)) : getPublicUrlArgNames(app);
|
|
5117
|
-
const webOpts = {
|
|
5118
|
-
imageName: appName,
|
|
5119
|
-
baseImage: "node:22-alpine",
|
|
5120
|
-
port: app.port,
|
|
5121
|
-
appPath: app.path,
|
|
5122
|
-
turboPackage: options.turboPackage,
|
|
5123
|
-
packageManager: options.packageManager,
|
|
5124
|
-
publicUrlArgs
|
|
5125
|
-
};
|
|
5126
|
-
switch (app.framework) {
|
|
5127
|
-
case "vite": return generateViteStaticDockerfile(webOpts);
|
|
5128
|
-
case "tanstack-start":
|
|
5129
|
-
case "remix": return generateNodeWebDockerfile(webOpts);
|
|
5130
|
-
default: return generateNextjsDockerfile(webOpts);
|
|
5131
|
-
}
|
|
5132
|
-
}
|
|
5133
|
-
/**
|
|
5134
|
-
* The package name turbo prunes an app by: its package.json's, or its name.
|
|
5135
|
-
*/
|
|
5136
|
-
function appPackageName(root, appName, path) {
|
|
5137
|
-
return getAppPackageName(join(root, path)) ?? appName;
|
|
5138
|
-
}
|
|
5139
|
-
/**
|
|
5140
|
-
* Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
|
|
5141
|
-
* the apps beside the containers their constructs derive.
|
|
5142
|
-
*
|
|
5143
|
-
* Through reconcile rather than a second generator, so what `gkm docker`
|
|
5144
|
-
* describes and what `gkm dev` runs cannot disagree. Nothing is started.
|
|
5145
|
-
*/
|
|
5146
|
-
async function writeConstructsCompose(workspace) {
|
|
5147
|
-
await reconcileWorkspace(workspace, {
|
|
5148
|
-
stage: workspace.stages.local,
|
|
5149
|
-
start: false
|
|
5150
|
-
});
|
|
5151
|
-
logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
|
|
5152
|
-
return join(workspace.root, COMPOSE_PATH);
|
|
5153
|
-
}
|
|
5154
|
-
function printRunInstructions(workspace) {
|
|
5155
|
-
const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
|
|
5156
|
-
logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
|
|
5157
|
-
logger.log(" gkm setup # starts the containers and creates what they hold");
|
|
5158
|
-
logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
|
|
5159
|
-
}
|
|
5160
|
-
//#endregion
|
|
5161
|
-
//#region src/deploy/dokploy-api.ts
|
|
5162
|
-
var dokploy_api_exports = /* @__PURE__ */ __exportAll({
|
|
5163
|
-
DEFAULT_DOKPLOY_TIMEOUT_MS: () => DEFAULT_DOKPLOY_TIMEOUT_MS,
|
|
5164
|
-
DokployApi: () => DokployApi,
|
|
5165
|
-
DokployApiError: () => DokployApiError,
|
|
5166
|
-
DokployRequestTimedOut: () => DokployRequestTimedOut
|
|
5167
|
-
});
|
|
5168
|
-
/** Per request, so a stalled server fails the deploy, not the CI job. */
|
|
5169
|
-
const DEFAULT_DOKPLOY_TIMEOUT_MS = 3e4;
|
|
5170
|
-
/**
|
|
5171
|
-
* Dokploy accepted the connection but did not answer in time.
|
|
5172
|
-
*
|
|
5173
|
-
* Not retried: a request that arrived and stalled may still be acted on, and
|
|
5174
|
-
* sending it again could repeat a deploy or a create the server is already
|
|
5175
|
-
* doing.
|
|
5176
|
-
*/
|
|
5177
|
-
var DokployRequestTimedOut = class extends Error {
|
|
5178
|
-
baseUrl;
|
|
5179
|
-
endpoint;
|
|
5180
|
-
timeoutMs;
|
|
5181
|
-
constructor(baseUrl, endpoint, timeoutMs) {
|
|
5182
|
-
super(`Dokploy at ${baseUrl} did not answer ${endpoint} within ${timeoutMs}ms. Check that the Dokploy server is healthy, or raise \`timeoutMs\` if this call is known to be slow.`);
|
|
5183
|
-
this.baseUrl = baseUrl;
|
|
5184
|
-
this.endpoint = endpoint;
|
|
5185
|
-
this.timeoutMs = timeoutMs;
|
|
5186
|
-
this.name = "DokployRequestTimedOut";
|
|
5187
|
-
}
|
|
5188
|
-
};
|
|
5189
|
-
/**
|
|
5190
|
-
* Waits `ms` between retries, or rejects with the signal's reason the moment
|
|
5191
|
-
* it aborts — a caller who gave up should not sit through the backoff.
|
|
5192
|
-
*/
|
|
5193
|
-
function pause(ms, signal) {
|
|
5194
|
-
return new Promise((resolve, reject) => {
|
|
5195
|
-
if (signal?.aborted) {
|
|
5196
|
-
reject(signal.reason);
|
|
5197
|
-
return;
|
|
5198
|
-
}
|
|
5199
|
-
const onAbort = () => {
|
|
5200
|
-
clearTimeout(timer);
|
|
5201
|
-
reject(signal?.reason);
|
|
5202
|
-
};
|
|
5203
|
-
const timer = setTimeout(() => {
|
|
5204
|
-
signal?.removeEventListener("abort", onAbort);
|
|
5205
|
-
resolve();
|
|
5206
|
-
}, ms);
|
|
5207
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5208
|
-
});
|
|
5209
|
-
}
|
|
5210
|
-
var DokployApiError = class extends Error {
|
|
5211
|
-
status;
|
|
5212
|
-
statusText;
|
|
5213
|
-
issues;
|
|
5214
|
-
constructor(message, status, statusText, issues) {
|
|
5215
|
-
super(message);
|
|
5216
|
-
this.status = status;
|
|
5217
|
-
this.statusText = statusText;
|
|
5218
|
-
this.issues = issues;
|
|
5219
|
-
this.name = "DokployApiError";
|
|
5220
|
-
}
|
|
5221
|
-
};
|
|
5222
|
-
/**
|
|
5223
|
-
* Dokploy API client
|
|
5224
|
-
*/
|
|
5225
|
-
var DokployApi = class {
|
|
5226
|
-
baseUrl;
|
|
5227
|
-
token;
|
|
5228
|
-
timeoutMs;
|
|
5229
|
-
signal;
|
|
5230
|
-
constructor(options) {
|
|
5231
|
-
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
5232
|
-
this.token = options.token;
|
|
5233
|
-
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
5234
|
-
this.signal = options.signal;
|
|
5235
|
-
}
|
|
5236
|
-
/**
|
|
5237
|
-
* Make a GET request to the Dokploy API
|
|
5238
|
-
*/
|
|
5239
|
-
async get(endpoint) {
|
|
5240
|
-
return this.request("GET", endpoint);
|
|
5241
|
-
}
|
|
5242
|
-
/**
|
|
5243
|
-
* Make a POST request to the Dokploy API
|
|
5244
|
-
*/
|
|
5245
|
-
async post(endpoint, body) {
|
|
5246
|
-
return this.request("POST", endpoint, body);
|
|
5247
|
-
}
|
|
5248
|
-
/**
|
|
5249
|
-
* Make a request to the Dokploy API
|
|
5250
|
-
*/
|
|
5251
|
-
async request(method, endpoint, body) {
|
|
5252
|
-
const url = `${this.baseUrl}/api/${endpoint}`;
|
|
5253
|
-
let response;
|
|
5254
|
-
let timeout;
|
|
5255
|
-
let lastError;
|
|
5256
|
-
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
5257
|
-
this.signal?.throwIfAborted();
|
|
5258
|
-
timeout = AbortSignal.timeout(this.timeoutMs);
|
|
5259
|
-
try {
|
|
5260
|
-
response = await fetch(url, {
|
|
5261
|
-
method,
|
|
5262
|
-
headers: {
|
|
5263
|
-
"Content-Type": "application/json",
|
|
5264
|
-
"x-api-key": this.token
|
|
5265
|
-
},
|
|
5266
|
-
body: body ? JSON.stringify(body) : void 0,
|
|
5267
|
-
signal: this.signal ? AbortSignal.any([this.signal, timeout]) : timeout
|
|
5268
|
-
});
|
|
5269
|
-
break;
|
|
5270
|
-
} catch (error) {
|
|
5271
|
-
const stopped = this.stopped(timeout, endpoint);
|
|
5272
|
-
if (stopped) throw stopped;
|
|
5273
|
-
lastError = error;
|
|
5274
|
-
if (attempt === 3) break;
|
|
5275
|
-
await pause(attempt * 750, this.signal);
|
|
5276
|
-
}
|
|
5277
|
-
}
|
|
5278
|
-
if (!response || !timeout) {
|
|
5279
|
-
const detail = lastError instanceof Error ? lastError.message : String(lastError);
|
|
5280
|
-
throw new DokployApiError(`Could not reach Dokploy at ${this.baseUrl} (${endpoint}): ${detail}`, 0, "Network error");
|
|
5281
|
-
}
|
|
5282
|
-
try {
|
|
5283
|
-
return await this.read(response);
|
|
5284
|
-
} catch (error) {
|
|
5285
|
-
throw this.stopped(timeout, endpoint) ?? error;
|
|
5286
|
-
}
|
|
5287
|
-
}
|
|
5288
|
-
/**
|
|
5289
|
-
* What a request cut short should reject with: the caller's own reason
|
|
5290
|
-
* when they aborted, `DokployRequestTimedOut` when the deadline passed,
|
|
5291
|
-
* nothing when it was neither.
|
|
5292
|
-
*/
|
|
5293
|
-
stopped(timeout, endpoint) {
|
|
5294
|
-
if (this.signal?.aborted) return this.signal.reason;
|
|
5295
|
-
if (timeout.aborted) return new DokployRequestTimedOut(this.baseUrl, endpoint, this.timeoutMs);
|
|
5296
|
-
}
|
|
5297
|
-
/** Turns a response into its JSON body, or a `DokployApiError`. */
|
|
5298
|
-
async read(response) {
|
|
5299
|
-
if (!response.ok) {
|
|
5300
|
-
let errorMessage = `Dokploy API error: ${response.status} ${response.statusText}`;
|
|
5301
|
-
let issues;
|
|
5302
|
-
try {
|
|
5303
|
-
const errorBody = await response.json();
|
|
5304
|
-
if (errorBody.message) errorMessage = `Dokploy API error: ${errorBody.message}`;
|
|
5305
|
-
if (errorBody.issues?.length) {
|
|
5306
|
-
issues = errorBody.issues;
|
|
5307
|
-
errorMessage += `\n Issues: ${errorBody.issues.map((i) => i.message).join(", ")}`;
|
|
5308
|
-
}
|
|
5309
|
-
} catch {}
|
|
5310
|
-
throw new DokployApiError(errorMessage, response.status, response.statusText, issues);
|
|
5311
|
-
}
|
|
5312
|
-
const text = await response.text();
|
|
5313
|
-
if (!text || text.trim() === "") return;
|
|
5314
|
-
return JSON.parse(text);
|
|
5315
|
-
}
|
|
5316
|
-
/**
|
|
5317
|
-
* Every external port published on this server, across every project.
|
|
5318
|
-
*
|
|
5319
|
-
* Dokploy knows what it has bound; guessing does not. A port that looks free
|
|
5320
|
-
* from here can be held by a service in a project this deploy has never
|
|
5321
|
-
* heard of — which surfaces as `Port 5432 is already in use by container
|
|
5322
|
-
* "…"`, naming something the caller cannot see.
|
|
5323
|
-
*
|
|
5324
|
-
* `project.all` is a summary, so each project is fetched: the per-service
|
|
5325
|
-
* `externalPort` only appears on `project.one`.
|
|
5326
|
-
*/
|
|
5327
|
-
async publishedPorts() {
|
|
5328
|
-
const ports = /* @__PURE__ */ new Set();
|
|
5329
|
-
const projects = await this.listProjects();
|
|
5330
|
-
for (const project of projects) {
|
|
5331
|
-
const details = await this.getProject(project.projectId);
|
|
5332
|
-
for (const environment of details.environments ?? []) {
|
|
5333
|
-
const resources = [
|
|
5334
|
-
...environment.postgres ?? [],
|
|
5335
|
-
...environment.redis ?? [],
|
|
5336
|
-
...environment.applications ?? []
|
|
5337
|
-
];
|
|
5338
|
-
for (const resource of resources) if (typeof resource.externalPort === "number") ports.add(resource.externalPort);
|
|
5339
|
-
}
|
|
5340
|
-
}
|
|
5341
|
-
return ports;
|
|
5342
|
-
}
|
|
5343
|
-
/**
|
|
5344
|
-
* Validate the API token by making a test request
|
|
5345
|
-
*/
|
|
5346
|
-
async validateToken() {
|
|
5347
|
-
try {
|
|
5348
|
-
await this.get("project.all");
|
|
5349
|
-
return true;
|
|
5350
|
-
} catch {
|
|
5351
|
-
return false;
|
|
5352
|
-
}
|
|
5353
|
-
}
|
|
5354
|
-
/**
|
|
5355
|
-
* List all projects
|
|
5356
|
-
*/
|
|
5357
|
-
async listProjects() {
|
|
5358
|
-
return this.get("project.all");
|
|
5359
|
-
}
|
|
5360
|
-
/**
|
|
5361
|
-
* Get a single project by ID
|
|
5362
|
-
*/
|
|
5363
|
-
async getProject(projectId) {
|
|
5364
|
-
return this.get(`project.one?projectId=${projectId}`);
|
|
5365
|
-
}
|
|
5366
|
-
/**
|
|
5367
|
-
* Create a new project
|
|
5368
|
-
*/
|
|
5369
|
-
async createProject(name, description) {
|
|
5370
|
-
return this.post("project.create", {
|
|
5371
|
-
name,
|
|
5372
|
-
description: description ?? `Created by gkm CLI`
|
|
5373
|
-
});
|
|
5374
|
-
}
|
|
5375
|
-
/**
|
|
5376
|
-
* Change a project's name or description.
|
|
5377
|
-
*
|
|
5378
|
-
* The name is sent with the description because `project.update` validates
|
|
5379
|
-
* the whole project on some Dokploy versions, and a missing name fails it.
|
|
5380
|
-
*/
|
|
5381
|
-
async updateProject(projectId, updates) {
|
|
5382
|
-
await this.post("project.update", {
|
|
5383
|
-
projectId,
|
|
5384
|
-
...updates
|
|
5385
|
-
});
|
|
5386
|
-
}
|
|
5387
|
-
/**
|
|
5388
|
-
* Delete a project and all its resources
|
|
5389
|
-
*/
|
|
5390
|
-
async deleteProject(projectId) {
|
|
5391
|
-
await this.post("project.remove", { projectId });
|
|
5392
|
-
}
|
|
5393
|
-
/**
|
|
5394
|
-
* Create an environment in a project
|
|
5395
|
-
*/
|
|
5396
|
-
async createEnvironment(projectId, name, description) {
|
|
5397
|
-
return this.post("environment.create", {
|
|
5398
|
-
projectId,
|
|
5399
|
-
name,
|
|
5400
|
-
description: description ?? `${name} environment`
|
|
5401
|
-
});
|
|
5402
|
-
}
|
|
5403
|
-
/**
|
|
5404
|
-
* List all applications in a project
|
|
5405
|
-
*/
|
|
5406
|
-
async listApplications(projectId) {
|
|
5407
|
-
return this.listInProject(projectId, (env) => env.applications);
|
|
5408
|
-
}
|
|
5409
|
-
/**
|
|
5410
|
-
* Everything of one kind in a project, across its environments.
|
|
5411
|
-
*
|
|
5412
|
-
* From `project.one`, because the per-kind `*.all?projectId=` endpoints
|
|
5413
|
-
* return **404** on current Dokploy: resources live under environments now.
|
|
5414
|
-
* Those calls used to be wrapped in `catch { return [] }`, which turned "I
|
|
5415
|
-
* could not ask" into "there are none" — and for a find-or-create that is
|
|
5416
|
-
* the worst available answer. Every deploy created a second application, a
|
|
5417
|
-
* second Postgres and a second Redis, silently, for as long as the project
|
|
5418
|
-
* existed.
|
|
5419
|
-
*
|
|
5420
|
-
* A failure here is not swallowed: creating a duplicate is worse than
|
|
5421
|
-
* stopping.
|
|
5422
|
-
*/
|
|
5423
|
-
async listInProject(projectId, pick) {
|
|
5424
|
-
return ((await this.getProject(projectId)).environments ?? []).flatMap((environment) => (pick(environment) ?? []).map((resource) => ({
|
|
5425
|
-
...resource,
|
|
5426
|
-
environmentId: environment.environmentId
|
|
5427
|
-
})));
|
|
5428
|
-
}
|
|
5429
|
-
/**
|
|
5430
|
-
* Find an application by name in a project
|
|
5431
|
-
*/
|
|
5432
|
-
async findApplicationByName(projectId, name, environmentId) {
|
|
5433
|
-
const applications = await this.listApplications(projectId);
|
|
5434
|
-
const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
|
|
5435
|
-
return applications.find((app) => (!environmentId || app.environmentId === environmentId) && (app.name === name || app.appName === normalizedName));
|
|
5436
|
-
}
|
|
5437
|
-
/**
|
|
5438
|
-
* Create a new application
|
|
5439
|
-
*/
|
|
5440
|
-
async createApplication(name, projectId, environmentId) {
|
|
5441
|
-
return this.post("application.create", {
|
|
5442
|
-
name,
|
|
5443
|
-
projectId,
|
|
5444
|
-
environmentId,
|
|
5445
|
-
appName: name.toLowerCase().replace(/[^a-z0-9-]/g, "-")
|
|
5446
|
-
});
|
|
5447
|
-
}
|
|
5448
|
-
/**
|
|
5449
|
-
* Find or create an application by name
|
|
5450
|
-
*/
|
|
5451
|
-
async findOrCreateApplication(name, projectId, environmentId) {
|
|
5452
|
-
const existing = await this.findApplicationByName(projectId, name, environmentId);
|
|
5453
|
-
if (existing) return {
|
|
5454
|
-
application: existing,
|
|
5455
|
-
created: false
|
|
5456
|
-
};
|
|
5457
|
-
return {
|
|
5458
|
-
application: await this.createApplication(name, projectId, environmentId),
|
|
5459
|
-
created: true
|
|
5460
|
-
};
|
|
5461
|
-
}
|
|
5462
|
-
/**
|
|
5463
|
-
* Get an application by ID
|
|
5464
|
-
*/
|
|
5465
|
-
async getApplication(applicationId) {
|
|
5466
|
-
try {
|
|
5467
|
-
return await this.get(`application.one?applicationId=${applicationId}`);
|
|
5468
|
-
} catch {
|
|
5469
|
-
return null;
|
|
5470
|
-
}
|
|
5471
|
-
}
|
|
5472
|
-
/**
|
|
5473
|
-
* Update an application
|
|
5474
|
-
*/
|
|
5475
|
-
async updateApplication(applicationId, updates) {
|
|
5476
|
-
await this.post("application.update", {
|
|
5477
|
-
applicationId,
|
|
5478
|
-
...updates
|
|
5479
|
-
});
|
|
5480
|
-
}
|
|
5481
|
-
/**
|
|
5482
|
-
* Save environment variables for an application
|
|
5483
|
-
*/
|
|
5484
|
-
async saveApplicationEnv(applicationId, env, options) {
|
|
5485
|
-
await this.post("application.saveEnvironment", {
|
|
5486
|
-
applicationId,
|
|
5487
|
-
env,
|
|
5488
|
-
buildArgs: options?.buildArgs ?? null,
|
|
5489
|
-
buildSecrets: options?.buildSecrets ?? null,
|
|
5490
|
-
createEnvFile: false
|
|
5491
|
-
});
|
|
5492
|
-
}
|
|
5493
|
-
/**
|
|
5494
|
-
* Configure application to use Docker provider (pull from registry)
|
|
5495
|
-
*
|
|
5496
|
-
* For private registries, either:
|
|
5497
|
-
* - Use `registryId` if the registry is configured in Dokploy
|
|
5498
|
-
* - Or provide `username`, `password`, and `registryUrl` directly
|
|
5499
|
-
*/
|
|
5500
|
-
async saveDockerProvider(applicationId, dockerImage, options) {
|
|
5501
|
-
await this.post("application.saveDockerProvider", {
|
|
5502
|
-
applicationId,
|
|
5503
|
-
dockerImage,
|
|
5504
|
-
...options,
|
|
5505
|
-
username: options?.username ?? null,
|
|
5506
|
-
password: options?.password ?? null,
|
|
5507
|
-
registryUrl: options?.registryUrl ?? null
|
|
5508
|
-
});
|
|
5509
|
-
}
|
|
5510
|
-
/**
|
|
5511
|
-
* Deploy an application
|
|
5512
|
-
*/
|
|
5513
|
-
async deployApplication(applicationId) {
|
|
5514
|
-
await this.post("application.deploy", { applicationId });
|
|
5515
|
-
}
|
|
5516
|
-
/**
|
|
5517
|
-
* Delete an application
|
|
5518
|
-
*/
|
|
5519
|
-
async deleteApplication(applicationId) {
|
|
5520
|
-
await this.post("application.remove", { applicationId });
|
|
5521
|
-
}
|
|
5522
|
-
/**
|
|
5523
|
-
* List all registries
|
|
5524
|
-
*/
|
|
5525
|
-
async listRegistries() {
|
|
5526
|
-
return this.get("registry.all");
|
|
5527
|
-
}
|
|
5528
|
-
/**
|
|
5529
|
-
* Create a new registry
|
|
5530
|
-
*/
|
|
5531
|
-
async createRegistry(registryName, registryUrl, username, password, options) {
|
|
5532
|
-
return this.post("registry.create", {
|
|
5533
|
-
registryName,
|
|
5534
|
-
registryUrl,
|
|
5535
|
-
username,
|
|
5536
|
-
password,
|
|
5537
|
-
imagePrefix: options?.imagePrefix
|
|
5538
|
-
});
|
|
5539
|
-
}
|
|
5540
|
-
/**
|
|
5541
|
-
* Get a registry by ID
|
|
5542
|
-
*/
|
|
5543
|
-
async getRegistry(registryId) {
|
|
5544
|
-
return this.get(`registry.one?registryId=${registryId}`);
|
|
5545
|
-
}
|
|
5546
|
-
/**
|
|
5547
|
-
* Update a registry
|
|
5548
|
-
*/
|
|
5549
|
-
async updateRegistry(registryId, updates) {
|
|
5550
|
-
await this.post("registry.update", {
|
|
5551
|
-
registryId,
|
|
5552
|
-
...updates
|
|
5553
|
-
});
|
|
5554
|
-
}
|
|
5555
|
-
/**
|
|
5556
|
-
* Delete a registry
|
|
5557
|
-
*/
|
|
5558
|
-
async deleteRegistry(registryId) {
|
|
5559
|
-
await this.post("registry.remove", { registryId });
|
|
5560
|
-
}
|
|
5561
|
-
/**
|
|
5562
|
-
* List all Postgres databases in a project
|
|
5563
|
-
*/
|
|
5564
|
-
async listPostgres(projectId) {
|
|
5565
|
-
return this.listInProject(projectId, (env) => env.postgres);
|
|
5566
|
-
}
|
|
5567
|
-
/**
|
|
5568
|
-
* Find a Postgres database by name in a project
|
|
5569
|
-
*/
|
|
5570
|
-
async findPostgresByName(projectId, name) {
|
|
5571
|
-
const databases = await this.listPostgres(projectId);
|
|
5572
|
-
const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
|
|
5573
|
-
const match = databases.find((db) => db.name === name || db.appName === normalizedName);
|
|
5574
|
-
if (!match) return void 0;
|
|
5575
|
-
return this.getPostgres(match.postgresId);
|
|
5576
|
-
}
|
|
5577
|
-
/**
|
|
5578
|
-
* Create a new Postgres database
|
|
5579
|
-
*/
|
|
5580
|
-
async createPostgres(name, projectId, environmentId, options) {
|
|
5581
|
-
return this.post("postgres.create", {
|
|
5582
|
-
name,
|
|
5583
|
-
projectId,
|
|
5584
|
-
environmentId,
|
|
5585
|
-
appName: options?.appName ?? name.toLowerCase().replace(/[^a-z0-9-]/g, "-"),
|
|
5586
|
-
databaseName: options?.databaseName,
|
|
5587
|
-
databaseUser: options?.databaseUser ?? "postgres",
|
|
5588
|
-
databasePassword: options?.databasePassword,
|
|
5589
|
-
dockerImage: options?.dockerImage ?? "postgres:18",
|
|
5590
|
-
description: options?.description ?? `Postgres database for ${name}`
|
|
5591
|
-
});
|
|
5592
|
-
}
|
|
5593
|
-
/**
|
|
5594
|
-
* Find or create a Postgres database by name
|
|
5595
|
-
*/
|
|
5596
|
-
async findOrCreatePostgres(name, projectId, environmentId, options) {
|
|
5597
|
-
const existing = await this.findPostgresByName(projectId, name);
|
|
5598
|
-
if (existing) return {
|
|
5599
|
-
postgres: existing,
|
|
5600
|
-
created: false
|
|
5601
|
-
};
|
|
5602
|
-
return {
|
|
5603
|
-
postgres: await this.createPostgres(name, projectId, environmentId, options),
|
|
5604
|
-
created: true
|
|
5605
|
-
};
|
|
5606
|
-
}
|
|
5607
|
-
/**
|
|
5608
|
-
* Get a Postgres database by ID
|
|
5609
|
-
*/
|
|
5610
|
-
async getPostgres(postgresId) {
|
|
5611
|
-
return this.get(`postgres.one?postgresId=${postgresId}`);
|
|
5612
|
-
}
|
|
5613
|
-
/**
|
|
5614
|
-
* Deploy a Postgres database
|
|
5615
|
-
*/
|
|
5616
|
-
async deployPostgres(postgresId) {
|
|
5617
|
-
await this.post("postgres.deploy", { postgresId });
|
|
5618
|
-
}
|
|
5619
|
-
/**
|
|
5620
|
-
* Save environment variables for Postgres
|
|
5621
|
-
*/
|
|
5622
|
-
async savePostgresEnv(postgresId, env) {
|
|
5623
|
-
await this.post("postgres.saveEnvironment", {
|
|
5624
|
-
postgresId,
|
|
5625
|
-
env
|
|
5626
|
-
});
|
|
5627
|
-
}
|
|
5628
|
-
/**
|
|
5629
|
-
* Set external port for Postgres (for external access)
|
|
5630
|
-
*/
|
|
5631
|
-
async savePostgresExternalPort(postgresId, externalPort) {
|
|
5632
|
-
await this.post("postgres.saveExternalPort", {
|
|
5633
|
-
postgresId,
|
|
5634
|
-
externalPort
|
|
5635
|
-
});
|
|
5636
|
-
}
|
|
5637
|
-
/**
|
|
5638
|
-
* Update Postgres configuration
|
|
5639
|
-
*/
|
|
5640
|
-
async updatePostgres(postgresId, updates) {
|
|
5641
|
-
await this.post("postgres.update", {
|
|
5642
|
-
postgresId,
|
|
5643
|
-
...updates
|
|
5644
|
-
});
|
|
5645
|
-
}
|
|
5646
|
-
/**
|
|
5647
|
-
* Delete a Postgres database
|
|
5648
|
-
*/
|
|
5649
|
-
async deletePostgres(postgresId) {
|
|
5650
|
-
await this.post("postgres.remove", { postgresId });
|
|
5651
|
-
}
|
|
5652
|
-
/**
|
|
5653
|
-
* The compose stacks in a project.
|
|
5654
|
-
*
|
|
5655
|
-
* Dokploy has first-class primitives for Postgres and Redis and none for
|
|
5656
|
-
* MinIO, so an object store is a compose stack — the one kind whose contents
|
|
5657
|
-
* this target writes rather than configures.
|
|
5658
|
-
*/
|
|
5659
|
-
async listCompose(projectId) {
|
|
5660
|
-
return this.listInProject(projectId, (env) => env.compose);
|
|
5661
|
-
}
|
|
5662
|
-
/** A compose stack by name, hydrated — `project.one` returns summaries. */
|
|
5663
|
-
async findComposeByName(projectId, name) {
|
|
5664
|
-
const summary = (await this.listCompose(projectId)).find((compose) => compose.name === name);
|
|
5665
|
-
return summary ? this.getCompose(summary.composeId) : void 0;
|
|
5666
|
-
}
|
|
5667
|
-
async getCompose(composeId) {
|
|
5668
|
-
return this.get(`compose.one?composeId=${composeId}`);
|
|
5669
|
-
}
|
|
5670
|
-
/**
|
|
5671
|
-
* A compose stack carrying the file this target wrote.
|
|
5672
|
-
*
|
|
5673
|
-
* Created empty and then updated, because `compose.create` takes no file:
|
|
5674
|
-
* it defaults to `sourceType: 'github'` and expects a repository. `raw` is
|
|
5675
|
-
* what makes the file ours.
|
|
5676
|
-
*/
|
|
5677
|
-
async findOrCreateCompose(name, projectId, environmentId, composeFile) {
|
|
5678
|
-
const existing = await this.findComposeByName(projectId, name);
|
|
5679
|
-
const compose = existing ?? await this.post("compose.create", {
|
|
5680
|
-
name,
|
|
5681
|
-
environmentId,
|
|
5682
|
-
composeType: "docker-compose"
|
|
5683
|
-
});
|
|
5684
|
-
await this.post("compose.update", {
|
|
5685
|
-
composeId: compose.composeId,
|
|
5686
|
-
sourceType: "raw",
|
|
5687
|
-
composeFile
|
|
5688
|
-
});
|
|
5689
|
-
return {
|
|
5690
|
-
compose,
|
|
5691
|
-
created: !existing
|
|
5692
|
-
};
|
|
5693
|
-
}
|
|
5694
|
-
async deployCompose(composeId) {
|
|
5695
|
-
await this.post("compose.deploy", { composeId });
|
|
5696
|
-
}
|
|
5697
|
-
async deleteCompose(composeId) {
|
|
5698
|
-
await this.post("compose.delete", {
|
|
5699
|
-
composeId,
|
|
5700
|
-
deleteVolumes: false
|
|
5701
|
-
});
|
|
5702
|
-
}
|
|
5703
|
-
/**
|
|
5704
|
-
* List all Redis instances in a project
|
|
5705
|
-
*/
|
|
5706
|
-
async listRedis(projectId) {
|
|
5707
|
-
return this.listInProject(projectId, (env) => env.redis);
|
|
5708
|
-
}
|
|
5709
|
-
/**
|
|
5710
|
-
* Find a Redis instance by name in a project
|
|
5711
|
-
*/
|
|
5712
|
-
async findRedisByName(projectId, name) {
|
|
5713
|
-
const instances = await this.listRedis(projectId);
|
|
5714
|
-
const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
|
|
5715
|
-
const match = instances.find((redis) => redis.name === name || redis.appName === normalizedName);
|
|
5716
|
-
return match ? this.getRedis(match.redisId) : void 0;
|
|
5717
|
-
}
|
|
5718
|
-
/**
|
|
5719
|
-
* Create a new Redis instance
|
|
5720
|
-
*/
|
|
5721
|
-
async createRedis(name, projectId, environmentId, options) {
|
|
5722
|
-
return this.post("redis.create", {
|
|
5723
|
-
name,
|
|
5724
|
-
projectId,
|
|
5725
|
-
environmentId,
|
|
5726
|
-
appName: options?.appName ?? name.toLowerCase().replace(/[^a-z0-9-]/g, "-"),
|
|
5727
|
-
databasePassword: options?.databasePassword,
|
|
5728
|
-
dockerImage: options?.dockerImage ?? "redis:8",
|
|
5729
|
-
description: options?.description ?? `Redis instance for ${name}`
|
|
5730
|
-
});
|
|
5731
|
-
}
|
|
5732
|
-
/**
|
|
5733
|
-
* Find or create a Redis instance by name
|
|
5734
|
-
*/
|
|
5735
|
-
async findOrCreateRedis(name, projectId, environmentId, options) {
|
|
5736
|
-
const existing = await this.findRedisByName(projectId, name);
|
|
5737
|
-
if (existing) return {
|
|
5738
|
-
redis: existing,
|
|
5739
|
-
created: false
|
|
5740
|
-
};
|
|
5741
|
-
return {
|
|
5742
|
-
redis: await this.createRedis(name, projectId, environmentId, options),
|
|
5743
|
-
created: true
|
|
5744
|
-
};
|
|
5745
|
-
}
|
|
5746
|
-
/**
|
|
5747
|
-
* Get a Redis instance by ID
|
|
5748
|
-
*/
|
|
5749
|
-
async getRedis(redisId) {
|
|
5750
|
-
return this.get(`redis.one?redisId=${redisId}`);
|
|
5751
|
-
}
|
|
5752
|
-
/**
|
|
5753
|
-
* Deploy a Redis instance
|
|
5754
|
-
*/
|
|
5755
|
-
async deployRedis(redisId) {
|
|
5756
|
-
await this.post("redis.deploy", { redisId });
|
|
5757
|
-
}
|
|
5758
|
-
/**
|
|
5759
|
-
* Save environment variables for Redis
|
|
5760
|
-
*/
|
|
5761
|
-
async saveRedisEnv(redisId, env) {
|
|
5762
|
-
await this.post("redis.saveEnvironment", {
|
|
5763
|
-
redisId,
|
|
5764
|
-
env
|
|
5765
|
-
});
|
|
5766
|
-
}
|
|
5767
|
-
/**
|
|
5768
|
-
* Set external port for Redis (for external access)
|
|
5769
|
-
*/
|
|
5770
|
-
async saveRedisExternalPort(redisId, externalPort) {
|
|
5771
|
-
await this.post("redis.saveExternalPort", {
|
|
5772
|
-
redisId,
|
|
5773
|
-
externalPort
|
|
5774
|
-
});
|
|
5775
|
-
}
|
|
5776
|
-
/**
|
|
5777
|
-
* Update Redis configuration
|
|
5778
|
-
*/
|
|
5779
|
-
async updateRedis(redisId, updates) {
|
|
5780
|
-
await this.post("redis.update", {
|
|
5781
|
-
redisId,
|
|
5782
|
-
...updates
|
|
5783
|
-
});
|
|
5784
|
-
}
|
|
5785
|
-
/**
|
|
5786
|
-
* Delete a Redis instance
|
|
5787
|
-
*/
|
|
5788
|
-
async deleteRedis(redisId) {
|
|
5789
|
-
await this.post("redis.remove", { redisId });
|
|
5790
|
-
}
|
|
5791
|
-
/**
|
|
5792
|
-
* Create a new domain for an application
|
|
5793
|
-
*/
|
|
5794
|
-
async createDomain(options) {
|
|
5795
|
-
return this.post("domain.create", options);
|
|
5796
|
-
}
|
|
5797
|
-
/**
|
|
5798
|
-
* Update an existing domain
|
|
5799
|
-
*/
|
|
5800
|
-
async updateDomain(domainId, updates) {
|
|
5801
|
-
await this.post("domain.update", {
|
|
5802
|
-
domainId,
|
|
5803
|
-
...updates
|
|
5804
|
-
});
|
|
5805
|
-
}
|
|
5806
|
-
/**
|
|
5807
|
-
* Delete a domain
|
|
5808
|
-
*/
|
|
5809
|
-
async deleteDomain(domainId) {
|
|
5810
|
-
await this.post("domain.delete", { domainId });
|
|
5811
|
-
}
|
|
5812
|
-
/**
|
|
5813
|
-
* Get a domain by ID
|
|
5814
|
-
*/
|
|
5815
|
-
async getDomain(domainId) {
|
|
5816
|
-
return this.get(`domain.one?domainId=${domainId}`);
|
|
5817
|
-
}
|
|
5818
|
-
/**
|
|
5819
|
-
* Get all domains for an application
|
|
5820
|
-
*/
|
|
5821
|
-
async getDomainsByApplicationId(applicationId) {
|
|
5822
|
-
return this.get(`domain.byApplicationId?applicationId=${applicationId}`);
|
|
5823
|
-
}
|
|
5824
|
-
/**
|
|
5825
|
-
* Validate a domain and trigger SSL certificate generation
|
|
5826
|
-
*
|
|
5827
|
-
* This should be called after DNS records are created and propagated.
|
|
5828
|
-
* It triggers Let's Encrypt certificate generation for HTTPS domains.
|
|
5829
|
-
*
|
|
5830
|
-
* @param domain - The domain hostname to validate (e.g., 'api.example.com')
|
|
5831
|
-
*/
|
|
5832
|
-
async validateDomain(domain) {
|
|
5833
|
-
return this.post("domain.validateDomain", { domain });
|
|
5834
|
-
}
|
|
5835
|
-
/**
|
|
5836
|
-
* Auto-generate a domain name for an application
|
|
5837
|
-
*/
|
|
5838
|
-
async generateDomain(appName, serverId) {
|
|
5839
|
-
return this.post("domain.generateDomain", {
|
|
5840
|
-
appName,
|
|
5841
|
-
serverId
|
|
5842
|
-
});
|
|
5843
|
-
}
|
|
5844
|
-
/**
|
|
5845
|
-
* List all backup destinations
|
|
5846
|
-
*/
|
|
5847
|
-
async listDestinations() {
|
|
5848
|
-
return this.get("destination.all");
|
|
5849
|
-
}
|
|
5850
|
-
/**
|
|
5851
|
-
* Get a destination by ID
|
|
5852
|
-
*/
|
|
5853
|
-
async getDestination(destinationId) {
|
|
5854
|
-
return this.get(`destination.one?destinationId=${destinationId}`);
|
|
5855
|
-
}
|
|
5856
|
-
/**
|
|
5857
|
-
* Create a new S3 backup destination
|
|
5858
|
-
*/
|
|
5859
|
-
async createDestination(options) {
|
|
5860
|
-
return this.post("destination.create", { ...options });
|
|
5861
|
-
}
|
|
5862
|
-
/**
|
|
5863
|
-
* Find a destination by name
|
|
5864
|
-
*/
|
|
5865
|
-
async findDestinationByName(name) {
|
|
5866
|
-
return (await this.listDestinations()).find((d) => d.name === name);
|
|
5867
|
-
}
|
|
5868
|
-
/**
|
|
5869
|
-
* Find or create a destination by name
|
|
5870
|
-
*/
|
|
5871
|
-
async findOrCreateDestination(name, options) {
|
|
5872
|
-
const existing = await this.findDestinationByName(name);
|
|
5873
|
-
if (existing) return {
|
|
5874
|
-
destination: existing,
|
|
5875
|
-
created: false
|
|
5876
|
-
};
|
|
5877
|
-
return {
|
|
5878
|
-
destination: await this.createDestination({
|
|
5879
|
-
name,
|
|
5880
|
-
...options
|
|
5881
|
-
}),
|
|
5882
|
-
created: true
|
|
5883
|
-
};
|
|
5884
|
-
}
|
|
5885
|
-
/**
|
|
5886
|
-
* Update a destination
|
|
5887
|
-
*/
|
|
5888
|
-
async updateDestination(destinationId, updates) {
|
|
5889
|
-
await this.post("destination.update", {
|
|
5890
|
-
destinationId,
|
|
5891
|
-
...updates
|
|
5892
|
-
});
|
|
5893
|
-
}
|
|
5894
|
-
/**
|
|
5895
|
-
* Delete a destination
|
|
5896
|
-
*/
|
|
5897
|
-
async deleteDestination(destinationId) {
|
|
5898
|
-
await this.post("destination.remove", { destinationId });
|
|
5899
|
-
}
|
|
5900
|
-
/**
|
|
5901
|
-
* Test connection to a destination
|
|
5902
|
-
*/
|
|
5903
|
-
async testDestinationConnection(destinationId) {
|
|
5904
|
-
return this.post("destination.testConnection", { destinationId });
|
|
5905
|
-
}
|
|
5906
|
-
/**
|
|
5907
|
-
* Create a backup schedule for postgres
|
|
5908
|
-
*/
|
|
5909
|
-
async createPostgresBackup(options) {
|
|
5910
|
-
return this.post("backup.create", {
|
|
5911
|
-
...options,
|
|
5912
|
-
databaseType: "postgres"
|
|
5913
|
-
});
|
|
5914
|
-
}
|
|
5915
|
-
/**
|
|
5916
|
-
* List backups for a postgres database
|
|
5917
|
-
*/
|
|
5918
|
-
async listPostgresBackups(postgresId) {
|
|
5919
|
-
return this.get(`backup.all?postgresId=${postgresId}&databaseType=postgres`);
|
|
5920
|
-
}
|
|
5921
|
-
/**
|
|
5922
|
-
* Get a backup by ID
|
|
5923
|
-
*/
|
|
5924
|
-
async getBackup(backupId) {
|
|
5925
|
-
return this.get(`backup.one?backupId=${backupId}`);
|
|
5926
|
-
}
|
|
5927
|
-
/**
|
|
5928
|
-
* Update a backup schedule
|
|
5929
|
-
*/
|
|
5930
|
-
async updateBackup(backupId, updates) {
|
|
5931
|
-
await this.post("backup.update", {
|
|
5932
|
-
backupId,
|
|
5933
|
-
...updates
|
|
5934
|
-
});
|
|
5935
|
-
}
|
|
5936
|
-
/**
|
|
5937
|
-
* Delete a backup schedule
|
|
5938
|
-
*/
|
|
5939
|
-
async deleteBackup(backupId) {
|
|
5940
|
-
await this.post("backup.remove", { backupId });
|
|
5941
|
-
}
|
|
5942
|
-
/**
|
|
5943
|
-
* Trigger a manual backup run
|
|
5944
|
-
*/
|
|
5945
|
-
async runBackupManually(backupId) {
|
|
5946
|
-
await this.post("backup.manualBackup", { backupId });
|
|
4335
|
+
const dockerignore = generateDockerignore();
|
|
4336
|
+
const dockerignorePath = join(workspace.root, ".dockerignore");
|
|
4337
|
+
await writeFile(dockerignorePath, dockerignore);
|
|
4338
|
+
logger.log(`\n Generated: .dockerignore (workspace root)`);
|
|
4339
|
+
const composePath = await writeConstructsCompose(workspace);
|
|
4340
|
+
logger.log(`\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`);
|
|
4341
|
+
logger.log("\n📋 Build commands:");
|
|
4342
|
+
for (const result of results) {
|
|
4343
|
+
const icon = result.type === "backend" ? "⚙️" : result.type === "mobile" ? "📱" : "🌐";
|
|
4344
|
+
logger.log(` ${icon} docker build -f .gkm/docker/Dockerfile.${result.appName} -t ${result.imageName} .`);
|
|
5947
4345
|
}
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
4346
|
+
printRunInstructions(workspace);
|
|
4347
|
+
return {
|
|
4348
|
+
apps: results,
|
|
4349
|
+
dockerCompose: composePath,
|
|
4350
|
+
dockerignore: dockerignorePath
|
|
4351
|
+
};
|
|
4352
|
+
}
|
|
5953
4353
|
/**
|
|
5954
|
-
*
|
|
5955
|
-
* Handles both dev (.ts with tsx) and production (.mjs from dist).
|
|
5956
|
-
*
|
|
5957
|
-
* In production: sniffer.ts is bundled into dist/index.mjs, but sniffer helper
|
|
5958
|
-
* files are output to dist/deploy/ as standalone modules for subprocess loading.
|
|
4354
|
+
* A site's Dockerfile, with an `ARG` for every key its bundler inlines.
|
|
5959
4355
|
*
|
|
5960
|
-
*
|
|
4356
|
+
* The keys come from the site's declaration where there is one — every
|
|
4357
|
+
* public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an
|
|
4358
|
+
* `ARG` the Dockerfile does not declare is a build argument the build drops,
|
|
4359
|
+
* leaving the bundle with an empty URL.
|
|
5961
4360
|
*/
|
|
5962
|
-
function
|
|
5963
|
-
const
|
|
5964
|
-
|
|
5965
|
-
const
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
4361
|
+
function siteDockerfile(appName, app, options) {
|
|
4362
|
+
const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && appKey(id) === appName)?.[1] : void 0;
|
|
4363
|
+
const publicUrlArgs = declared?.kind === "site" && options.manifest ? Object.keys(publicEnvFor(declared, options.manifest)) : getPublicUrlArgNames(app);
|
|
4364
|
+
const webOpts = {
|
|
4365
|
+
imageName: appName,
|
|
4366
|
+
baseImage: "node:22-alpine",
|
|
4367
|
+
port: app.port,
|
|
4368
|
+
appPath: app.path,
|
|
4369
|
+
turboPackage: options.turboPackage,
|
|
4370
|
+
packageManager: options.packageManager,
|
|
4371
|
+
publicUrlArgs
|
|
4372
|
+
};
|
|
4373
|
+
switch (app.framework) {
|
|
4374
|
+
case "vite": return generateViteStaticDockerfile(webOpts);
|
|
4375
|
+
case "tanstack-start":
|
|
4376
|
+
case "remix": return generateNodeWebDockerfile(webOpts);
|
|
4377
|
+
default: return generateNextjsDockerfile(webOpts);
|
|
4378
|
+
}
|
|
5970
4379
|
}
|
|
5971
4380
|
/**
|
|
5972
|
-
*
|
|
5973
|
-
* nothing of the deploy's: the deploy's Dokploy token, registry login and AWS
|
|
5974
|
-
* keys stay where they are. A worker that outlives the timeout is killed, and
|
|
5975
|
-
* comes back as the error the caller reports.
|
|
4381
|
+
* The package name turbo prunes an app by: its package.json's, or its name.
|
|
5976
4382
|
*/
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
try {
|
|
5980
|
-
const result = await sandbox.exec("node", nodeArgs, {
|
|
5981
|
-
cwd,
|
|
5982
|
-
env: { ...sandbox.env },
|
|
5983
|
-
timeoutMs: run.timeoutMs ?? 3e4,
|
|
5984
|
-
output: "capture"
|
|
5985
|
-
});
|
|
5986
|
-
return {
|
|
5987
|
-
stdout: result.stdout,
|
|
5988
|
-
stderr: result.stderr,
|
|
5989
|
-
code: result.exitCode
|
|
5990
|
-
};
|
|
5991
|
-
} catch (error) {
|
|
5992
|
-
return { error: error instanceof Error ? error : new Error(String(error)) };
|
|
5993
|
-
}
|
|
5994
|
-
}
|
|
5995
|
-
/** The worker's JSON answer: the last object on stdout naming `envVars`. */
|
|
5996
|
-
function snifferAnswer(stdout) {
|
|
5997
|
-
try {
|
|
5998
|
-
const jsonMatch = stdout.match(/\{[^{}]*"envVars"[^{}]*\}[^{]*$/);
|
|
5999
|
-
return jsonMatch ? JSON.parse(jsonMatch[0]) : void 0;
|
|
6000
|
-
} catch {
|
|
6001
|
-
return;
|
|
6002
|
-
}
|
|
4383
|
+
function appPackageName(root, appName, path) {
|
|
4384
|
+
return getAppPackageName(join(root, path)) ?? appName;
|
|
6003
4385
|
}
|
|
6004
4386
|
/**
|
|
6005
|
-
*
|
|
4387
|
+
* Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with
|
|
4388
|
+
* the apps beside the containers their constructs derive.
|
|
6006
4389
|
*
|
|
6007
|
-
*
|
|
6008
|
-
*
|
|
6009
|
-
|
|
6010
|
-
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
|
|
4390
|
+
* Through reconcile rather than a second generator, so what `gkm docker`
|
|
4391
|
+
* describes and what `gkm dev` runs cannot disagree. Nothing is started.
|
|
4392
|
+
*/
|
|
4393
|
+
async function writeConstructsCompose(workspace) {
|
|
4394
|
+
await reconcileWorkspace(workspace, {
|
|
4395
|
+
stage: workspace.stages.local,
|
|
4396
|
+
start: false
|
|
4397
|
+
});
|
|
4398
|
+
logger.log(` Generated: ${COMPOSE_PATH} (project root)`);
|
|
4399
|
+
return join(workspace.root, COMPOSE_PATH);
|
|
4400
|
+
}
|
|
4401
|
+
function printRunInstructions(workspace) {
|
|
4402
|
+
const project = existsSync(join(workspace.root, "docker-compose.yml")) ? " -f docker-compose.yml" : "";
|
|
4403
|
+
logger.log("\n📋 Run everything (the apps sit behind the \"apps\" profile):");
|
|
4404
|
+
logger.log(" gkm setup # starts the containers and creates what they hold");
|
|
4405
|
+
logger.log(` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`);
|
|
4406
|
+
}
|
|
4407
|
+
//#endregion
|
|
4408
|
+
//#region src/deploy/generated.ts
|
|
4409
|
+
/**
|
|
4410
|
+
* The values a deployed stage generates once and keeps: what nothing can
|
|
4411
|
+
* provision and nobody else issues.
|
|
6014
4412
|
*
|
|
6015
|
-
*
|
|
6016
|
-
*
|
|
4413
|
+
* - **A seed**, which salts every password a deploy derives — a database's
|
|
4414
|
+
* master and roles, a bucket's root user. Derived from repo facts alone
|
|
4415
|
+
* (project, stage, construct id), those passwords were computable by anyone
|
|
4416
|
+
* who could read the repo.
|
|
4417
|
+
* - **Each `secret` construct's value** — an auth server's signing secret —
|
|
4418
|
+
* random, rather than derived.
|
|
4419
|
+
* - **Each `encryption` construct's keyring** — one random key and an index
|
|
4420
|
+
* key. Later keys are added by `gkm encryption:rotate`, never by a deploy.
|
|
6017
4421
|
*
|
|
6018
|
-
*
|
|
6019
|
-
*
|
|
6020
|
-
*
|
|
6021
|
-
*
|
|
6022
|
-
|
|
4422
|
+
* Both are generated on the first deploy that needs them and written to the
|
|
4423
|
+
* stage's store, so every later deploy reads the same values: sessions survive
|
|
4424
|
+
* a redeploy, and a role's password does not move. A value set by hand with
|
|
4425
|
+
* `gkm secrets:set` is kept, never replaced.
|
|
4426
|
+
*/
|
|
4427
|
+
/**
|
|
4428
|
+
* The stage's secrets with its seed and every declared `secret`'s value
|
|
4429
|
+
* present, generating what is missing. Pure: the caller writes the result
|
|
4430
|
+
* back to the stage's store when `generated` is not empty.
|
|
6023
4431
|
*/
|
|
6024
|
-
|
|
6025
|
-
const
|
|
6026
|
-
const
|
|
6027
|
-
|
|
6028
|
-
|
|
4432
|
+
function withGeneratedSecrets(secrets, manifest) {
|
|
4433
|
+
const generated = [];
|
|
4434
|
+
const custom = { ...secrets.custom };
|
|
4435
|
+
for (const declaration of Object.values(manifest)) {
|
|
4436
|
+
if (declaration?.kind !== "secret" && declaration?.kind !== "encryption") continue;
|
|
4437
|
+
const key = declaration.provides?.[0];
|
|
4438
|
+
if (!key || custom[key]) continue;
|
|
4439
|
+
custom[key] = declaration.kind === "encryption" ? generateKeyring() : random();
|
|
4440
|
+
generated.push(key);
|
|
4441
|
+
}
|
|
4442
|
+
const seed = secrets.seed ?? random();
|
|
4443
|
+
if (!secrets.seed) generated.push("seed");
|
|
4444
|
+
return {
|
|
4445
|
+
secrets: generated.length ? {
|
|
4446
|
+
...secrets,
|
|
4447
|
+
seed,
|
|
4448
|
+
custom,
|
|
4449
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4450
|
+
} : secrets,
|
|
4451
|
+
generated
|
|
6029
4452
|
};
|
|
6030
|
-
|
|
6031
|
-
|
|
6032
|
-
|
|
6033
|
-
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
|
|
6037
|
-
|
|
6038
|
-
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
4453
|
+
}
|
|
4454
|
+
/** 256 bits, URL-safe. */
|
|
4455
|
+
function random() {
|
|
4456
|
+
return randomBytes(32).toString("base64url");
|
|
4457
|
+
}
|
|
4458
|
+
//#endregion
|
|
4459
|
+
//#region src/deploy/journal.ts
|
|
4460
|
+
var DeployJournal = class DeployJournal {
|
|
4461
|
+
store;
|
|
4462
|
+
stage;
|
|
4463
|
+
state;
|
|
4464
|
+
resources;
|
|
4465
|
+
version;
|
|
4466
|
+
existed;
|
|
4467
|
+
constructor(store, stage, state, resources, version, existed) {
|
|
4468
|
+
this.store = store;
|
|
4469
|
+
this.stage = stage;
|
|
4470
|
+
this.state = state;
|
|
4471
|
+
this.resources = resources;
|
|
4472
|
+
this.version = version;
|
|
4473
|
+
this.existed = existed;
|
|
4474
|
+
}
|
|
4475
|
+
/**
|
|
4476
|
+
* The stage's journal — its stored state, or `initial` written as the
|
|
4477
|
+
* stage's first state, so there is somewhere to record the very first
|
|
4478
|
+
* resource before it is created.
|
|
4479
|
+
*/
|
|
4480
|
+
static async open(store, stage, initial) {
|
|
4481
|
+
const stored = await store.read(stage);
|
|
4482
|
+
if (stored) return new DeployJournal(store, stage, stored.state, stored.resources, stored.version, true);
|
|
4483
|
+
const state = initial();
|
|
4484
|
+
const version = await store.write(stage, state, { expectedVersion: null });
|
|
4485
|
+
return new DeployJournal(store, stage, state, {}, version, false);
|
|
4486
|
+
}
|
|
4487
|
+
record(key) {
|
|
4488
|
+
return this.resources[key];
|
|
4489
|
+
}
|
|
4490
|
+
/** The keys a previous run marked `pending` and never saw created. */
|
|
4491
|
+
unfinished() {
|
|
4492
|
+
return Object.values(this.resources).filter((record) => record.status === "pending").map((record) => record.key);
|
|
4493
|
+
}
|
|
4494
|
+
/** Records that `entry` is about to be created. */
|
|
4495
|
+
async pending(entry) {
|
|
4496
|
+
await this.put({
|
|
4497
|
+
...entry,
|
|
4498
|
+
status: "pending"
|
|
4499
|
+
});
|
|
4500
|
+
}
|
|
4501
|
+
/** Records `entry` as existing with `id`; a no-op if it already is. */
|
|
4502
|
+
async ready(entry, id) {
|
|
4503
|
+
const current = this.resources[entry.key];
|
|
4504
|
+
if (current?.status === "ready" && current.id === id) return;
|
|
4505
|
+
await this.put({
|
|
4506
|
+
...entry,
|
|
4507
|
+
status: "ready",
|
|
4508
|
+
id
|
|
4509
|
+
});
|
|
4510
|
+
}
|
|
4511
|
+
/**
|
|
4512
|
+
* The resource `entry` names: by its recorded id, else by looking it up,
|
|
4513
|
+
* else created — with `pending` written before the create and `ready`
|
|
4514
|
+
* after, so a run that dies in between leaves a record the next run
|
|
4515
|
+
* resolves by looking the resource up rather than creating another.
|
|
4516
|
+
*/
|
|
4517
|
+
async ensure(entry, steps) {
|
|
4518
|
+
const record = this.resources[entry.key];
|
|
4519
|
+
let staleId;
|
|
4520
|
+
if (record?.status === "ready" && record.id && steps.get) {
|
|
4521
|
+
const known = await steps.get(record.id);
|
|
4522
|
+
if (known) {
|
|
4523
|
+
await this.ready(entry, steps.id(known));
|
|
4524
|
+
return {
|
|
4525
|
+
resource: known,
|
|
4526
|
+
via: "recorded"
|
|
4527
|
+
};
|
|
6044
4528
|
}
|
|
6045
|
-
|
|
4529
|
+
staleId = record.id;
|
|
4530
|
+
}
|
|
4531
|
+
const existing = await steps.find();
|
|
4532
|
+
if (existing) {
|
|
4533
|
+
await this.ready(entry, steps.id(existing));
|
|
6046
4534
|
return {
|
|
6047
|
-
|
|
6048
|
-
|
|
6049
|
-
|
|
4535
|
+
resource: existing,
|
|
4536
|
+
via: record?.status === "pending" ? "resumed" : "found",
|
|
4537
|
+
...staleId ? { staleId } : {}
|
|
6050
4538
|
};
|
|
6051
4539
|
}
|
|
4540
|
+
await this.pending(entry);
|
|
4541
|
+
const created = await steps.create();
|
|
4542
|
+
await this.ready(entry, steps.id(created));
|
|
6052
4543
|
return {
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
|
|
6056
|
-
};
|
|
6057
|
-
}
|
|
6058
|
-
if (app.entry) {
|
|
6059
|
-
const result = await sniffEntryFile(app.entry, app.path, workspacePath, run);
|
|
6060
|
-
if (logWarnings && result.error) output.warn(`[sniffer] ${appName}: Entry file threw error during sniffing (env vars still captured): ${result.error.message}`);
|
|
6061
|
-
return {
|
|
6062
|
-
appName,
|
|
6063
|
-
requiredEnvVars: applyMarkOptional(result.envVars, result.optionalEnvVars, markOptional),
|
|
6064
|
-
optionalEnvVars: result.optionalEnvVars
|
|
6065
|
-
};
|
|
6066
|
-
}
|
|
6067
|
-
if (app.routes) {
|
|
6068
|
-
const result = await sniffRouteFiles(normalizeRoutes(app.routes), app.path, workspacePath, run);
|
|
6069
|
-
if (logWarnings && result.error) output.warn(`[sniffer] ${appName}: Route sniffing threw error (env vars still captured): ${result.error.message}`);
|
|
6070
|
-
return {
|
|
6071
|
-
appName,
|
|
6072
|
-
requiredEnvVars: applyMarkOptional(result.envVars, result.optionalEnvVars, markOptional),
|
|
6073
|
-
optionalEnvVars: result.optionalEnvVars
|
|
4544
|
+
resource: created,
|
|
4545
|
+
via: "created",
|
|
4546
|
+
...staleId ? { staleId } : {}
|
|
6074
4547
|
};
|
|
6075
4548
|
}
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
4549
|
+
/** Writes the stage's state, keeping its resource records. */
|
|
4550
|
+
async save() {
|
|
4551
|
+
this.state.lastDeployedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4552
|
+
this.version = await this.store.write(this.stage, this.state, { expectedVersion: this.version });
|
|
4553
|
+
}
|
|
4554
|
+
async put(record) {
|
|
4555
|
+
this.version = await this.store.putResource(this.stage, record, { expectedVersion: this.version });
|
|
4556
|
+
this.resources = {
|
|
4557
|
+
...this.resources,
|
|
4558
|
+
[record.key]: {
|
|
4559
|
+
...record,
|
|
4560
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4561
|
+
}
|
|
6086
4562
|
};
|
|
6087
4563
|
}
|
|
4564
|
+
};
|
|
4565
|
+
//#endregion
|
|
4566
|
+
//#region src/deploy/state.ts
|
|
4567
|
+
/**
|
|
4568
|
+
* Create a new empty state for a stage
|
|
4569
|
+
*/
|
|
4570
|
+
function createEmptyState(stage, projectId, environmentId) {
|
|
6088
4571
|
return {
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
4572
|
+
provider: "dokploy",
|
|
4573
|
+
stage,
|
|
4574
|
+
projectId,
|
|
4575
|
+
environmentId,
|
|
4576
|
+
applications: {},
|
|
4577
|
+
services: {},
|
|
4578
|
+
lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6092
4579
|
};
|
|
6093
4580
|
}
|
|
6094
4581
|
/**
|
|
6095
|
-
*
|
|
6096
|
-
* Only modifies the list when `markOptional` is true and there are optional vars.
|
|
4582
|
+
* Set application ID in state (mutates state)
|
|
6097
4583
|
*/
|
|
6098
|
-
function
|
|
6099
|
-
|
|
6100
|
-
const optionalSet = new Set(optionalEnvVars);
|
|
6101
|
-
return envVars.map((v) => optionalSet.has(v) ? `${v}?` : v);
|
|
4584
|
+
function setApplicationId(state, appName, applicationId) {
|
|
4585
|
+
state.applications[appName] = applicationId;
|
|
6102
4586
|
}
|
|
6103
4587
|
/**
|
|
6104
|
-
*
|
|
6105
|
-
*
|
|
6106
|
-
* Entry apps call `config.parse()` at module load time. To capture which
|
|
6107
|
-
* env vars are accessed, we:
|
|
6108
|
-
* 1. Spawn a subprocess with a module loader hook
|
|
6109
|
-
* 2. The loader intercepts `@geekmidas/envkit` and replaces EnvironmentParser
|
|
6110
|
-
* with SnifferEnvironmentParser
|
|
6111
|
-
* 3. Import the entry file (triggers config.parse())
|
|
6112
|
-
* 4. Capture and return the accessed env var names
|
|
6113
|
-
*
|
|
6114
|
-
* This approach provides process isolation - each app is sniffed in its own
|
|
6115
|
-
* subprocess, preventing module cache pollution.
|
|
6116
|
-
*
|
|
6117
|
-
* @param entryPath - Relative path to the entry file (e.g., './src/index.ts')
|
|
6118
|
-
* @param appPath - The app's path relative to workspace (e.g., 'apps/auth')
|
|
6119
|
-
* @param workspacePath - Absolute path to workspace root
|
|
6120
|
-
* @returns EntrySniffResult with env vars and optional error
|
|
4588
|
+
* Record the image an app was deployed with (mutates state)
|
|
6121
4589
|
*/
|
|
6122
|
-
|
|
6123
|
-
|
|
6124
|
-
|
|
6125
|
-
|
|
6126
|
-
const ran = await runSniffer(run, workspacePath, resolve(workspacePath, appPath), nodeWithTsx(workerPath, [fullEntryPath], [loaderPath]));
|
|
6127
|
-
if ("error" in ran) return {
|
|
6128
|
-
envVars: [],
|
|
6129
|
-
optionalEnvVars: [],
|
|
6130
|
-
error: ran.error
|
|
6131
|
-
};
|
|
6132
|
-
const answer = snifferAnswer(ran.stdout);
|
|
6133
|
-
if (answer) return {
|
|
6134
|
-
envVars: answer.envVars || [],
|
|
6135
|
-
optionalEnvVars: answer.optionalEnvVars || [],
|
|
6136
|
-
error: answer.error ? new Error(answer.error) : void 0
|
|
6137
|
-
};
|
|
6138
|
-
return {
|
|
6139
|
-
envVars: [],
|
|
6140
|
-
optionalEnvVars: [],
|
|
6141
|
-
error: /* @__PURE__ */ new Error(`Failed to sniff entry file (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
|
|
4590
|
+
function setDeployedImage(state, appName, image) {
|
|
4591
|
+
state.images = {
|
|
4592
|
+
...state.images,
|
|
4593
|
+
[appName]: image
|
|
6142
4594
|
};
|
|
6143
4595
|
}
|
|
6144
4596
|
/**
|
|
6145
|
-
*
|
|
6146
|
-
*
|
|
6147
|
-
* Route-based apps have endpoints, functions, crons, and subscribers that
|
|
6148
|
-
* use services. Each service's register() method accesses environment variables.
|
|
6149
|
-
*
|
|
6150
|
-
* This runs in a subprocess with tsx loader to properly handle TypeScript
|
|
6151
|
-
* compilation and path alias resolution (e.g., `src/...` imports).
|
|
6152
|
-
*
|
|
6153
|
-
* @param routes - Glob pattern(s) for route files
|
|
6154
|
-
* @param appPath - The app's path relative to workspace (e.g., 'apps/api')
|
|
6155
|
-
* @param workspacePath - Absolute path to workspace root
|
|
6156
|
-
* @returns EntrySniffResult with env vars and optional error
|
|
4597
|
+
* Get a generated secret for an app
|
|
6157
4598
|
*/
|
|
6158
|
-
|
|
6159
|
-
|
|
6160
|
-
const workerPath = resolveSnifferFile("sniffer-routes-worker");
|
|
6161
|
-
const pattern = (Array.isArray(routes) ? routes : [routes])[0];
|
|
6162
|
-
if (!pattern) return {
|
|
6163
|
-
envVars: [],
|
|
6164
|
-
optionalEnvVars: [],
|
|
6165
|
-
error: /* @__PURE__ */ new Error("No route patterns provided")
|
|
6166
|
-
};
|
|
6167
|
-
const ran = await runSniffer(run, workspacePath, fullAppPath, nodeWithTsx(workerPath, [fullAppPath, pattern]));
|
|
6168
|
-
if ("error" in ran) return {
|
|
6169
|
-
envVars: [],
|
|
6170
|
-
optionalEnvVars: [],
|
|
6171
|
-
error: ran.error
|
|
6172
|
-
};
|
|
6173
|
-
if (ran.stderr) ran.stderr.split("\n").filter((line) => line.trim()).forEach((line) => output.warn(line));
|
|
6174
|
-
const answer = snifferAnswer(ran.stdout);
|
|
6175
|
-
if (answer) return {
|
|
6176
|
-
envVars: answer.envVars || [],
|
|
6177
|
-
optionalEnvVars: answer.optionalEnvVars || [],
|
|
6178
|
-
error: answer.error ? new Error(answer.error) : void 0
|
|
6179
|
-
};
|
|
6180
|
-
return {
|
|
6181
|
-
envVars: [],
|
|
6182
|
-
optionalEnvVars: [],
|
|
6183
|
-
error: /* @__PURE__ */ new Error(`Failed to sniff route files (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
|
|
6184
|
-
};
|
|
4599
|
+
function getGeneratedSecret(state, appName, secretName) {
|
|
4600
|
+
return state?.generatedSecrets?.[appName]?.[secretName];
|
|
6185
4601
|
}
|
|
6186
4602
|
/**
|
|
6187
|
-
*
|
|
6188
|
-
* which environment variables it accesses.
|
|
6189
|
-
*
|
|
6190
|
-
* In a subprocess, like the entry and route sniffers: the module is the
|
|
6191
|
-
* project's code, and it was imported into the deploy itself before — with
|
|
6192
|
-
* every credential the deploy held in reach. Fire-and-forget rejections are
|
|
6193
|
-
* collected there with the shared `sniffWithFireAndForget`.
|
|
6194
|
-
*
|
|
6195
|
-
* @param envParserPath - The envParser config (e.g., './src/config/env#envParser')
|
|
6196
|
-
* @param appPath - The app's path relative to workspace
|
|
6197
|
-
* @param workspacePath - Absolute path to workspace root
|
|
6198
|
-
* @returns SniffResult with env vars and any errors encountered
|
|
4603
|
+
* Set a generated secret for an app (mutates state)
|
|
6199
4604
|
*/
|
|
6200
|
-
|
|
6201
|
-
|
|
6202
|
-
if (!
|
|
6203
|
-
|
|
6204
|
-
|
|
6205
|
-
|
|
6206
|
-
|
|
6207
|
-
|
|
6208
|
-
|
|
6209
|
-
|
|
6210
|
-
|
|
6211
|
-
|
|
6212
|
-
|
|
6213
|
-
optionalEnvVars: [],
|
|
6214
|
-
unhandledRejections: [],
|
|
6215
|
-
error: ran.error
|
|
6216
|
-
};
|
|
6217
|
-
const answer = snifferAnswer(ran.stdout);
|
|
6218
|
-
if (!answer) return {
|
|
6219
|
-
envVars: [],
|
|
6220
|
-
optionalEnvVars: [],
|
|
6221
|
-
unhandledRejections: [],
|
|
6222
|
-
error: /* @__PURE__ */ new Error(`Failed to sniff envParser (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
|
|
4605
|
+
function setGeneratedSecret(state, appName, secretName, value) {
|
|
4606
|
+
if (!state.generatedSecrets) state.generatedSecrets = {};
|
|
4607
|
+
if (!state.generatedSecrets[appName]) state.generatedSecrets[appName] = {};
|
|
4608
|
+
state.generatedSecrets[appName][secretName] = value;
|
|
4609
|
+
}
|
|
4610
|
+
/**
|
|
4611
|
+
* Set DNS verification record for a hostname (mutates state)
|
|
4612
|
+
*/
|
|
4613
|
+
function setDnsVerification(state, hostname, serverIp) {
|
|
4614
|
+
if (!state.dnsVerified) state.dnsVerified = {};
|
|
4615
|
+
state.dnsVerified[hostname] = {
|
|
4616
|
+
serverIp,
|
|
4617
|
+
verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6223
4618
|
};
|
|
6224
|
-
|
|
6225
|
-
|
|
6226
|
-
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
4619
|
+
}
|
|
4620
|
+
/**
|
|
4621
|
+
* Check if a hostname is already verified with the given IP
|
|
4622
|
+
*/
|
|
4623
|
+
function isDnsVerified(state, hostname, serverIp) {
|
|
4624
|
+
return (state?.dnsVerified?.[hostname])?.serverIp === serverIp;
|
|
4625
|
+
}
|
|
4626
|
+
/**
|
|
4627
|
+
* Get the key for a DNS record in state
|
|
4628
|
+
*/
|
|
4629
|
+
function getDnsRecordKey(name, type) {
|
|
4630
|
+
return `${name}:${type}`;
|
|
4631
|
+
}
|
|
4632
|
+
/**
|
|
4633
|
+
* Set a created DNS record in state (mutates state)
|
|
4634
|
+
*/
|
|
4635
|
+
function setDnsRecord(state, record) {
|
|
4636
|
+
if (!state.dnsRecords) state.dnsRecords = {};
|
|
4637
|
+
const key = getDnsRecordKey(record.name, record.type);
|
|
4638
|
+
state.dnsRecords[key] = {
|
|
4639
|
+
...record,
|
|
4640
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6230
4641
|
};
|
|
6231
4642
|
}
|
|
6232
4643
|
/**
|
|
6233
|
-
*
|
|
6234
|
-
*
|
|
6235
|
-
* @param apps - Map of app name to app config
|
|
6236
|
-
* @param workspacePath - Absolute path to workspace root
|
|
6237
|
-
* @param options - Optional configuration for sniffing behavior
|
|
6238
|
-
* @returns Map of app name to sniffed environment
|
|
4644
|
+
* Get backup state from state
|
|
6239
4645
|
*/
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
|
|
6243
|
-
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
4646
|
+
function getBackupState(state) {
|
|
4647
|
+
return state?.backups;
|
|
4648
|
+
}
|
|
4649
|
+
/**
|
|
4650
|
+
* Set backup state (mutates state)
|
|
4651
|
+
*/
|
|
4652
|
+
function setBackupState(state, backupState) {
|
|
4653
|
+
state.backups = backupState;
|
|
4654
|
+
}
|
|
4655
|
+
/**
|
|
4656
|
+
* Set postgres backup ID in state (mutates state)
|
|
4657
|
+
*/
|
|
4658
|
+
function setPostgresBackupId(state, backupId) {
|
|
4659
|
+
if (state.backups) state.backups.postgresBackupId = backupId;
|
|
6247
4660
|
}
|
|
6248
4661
|
//#endregion
|
|
6249
|
-
export {
|
|
4662
|
+
export { portKeys as $, workspace_exports as A, networkEnv as B, isMainFrontendApp as C, constructGlobs as D, backendsOf as E, postgresStatements as F, hostFor as G, localRolePassword as H, quoteIdentifier as I, providerOf as J, cacheBackendFor as K, composeFor as L, forgetState as M, applyPostgres as N, derivedContainers as O, postgresDatabaseNames as P, fakeKey as Q, pgClient as R, validateImageRef as S, FAKE_ENV as T, planFor as U, envFor as V, resourceName as W, DEFAULT_IMAGES as X, storageBackendFor as Y, describeServices as Z, dockerCommand as _, setApplicationId as a, loadEnvFiles as at, generateDockerignore as b, setDnsRecord as c, setPostgresBackupId as d, primaryPortKey as et, DeployJournal as f, appPackageName as g, DockerPushFailed as h, isDnsVerified as i, isPortAvailable as it, LOCAL_CA_PATH as j, reconcileWorkspace as k, setDnsVerification as l, DockerBuildFailed as m, getBackupState as n, createEntryWrapper as nt, setBackupState as o, loadSecretsForApp as ot, withGeneratedSecrets as p, eventsBackendFor as q, getGeneratedSecret as r, findAvailablePort as rt, setDeployedImage as s, prepareEntryCredentials as st, createEmptyState as t, createCredentialsPreload as tt, setGeneratedSecret as u, siteDockerfile as v, resolveHost as w, generateSlimDockerfile as x, detectPackageManager as y, appEnvKeys as z };
|
|
6250
4663
|
|
|
6251
|
-
//# sourceMappingURL=
|
|
4664
|
+
//# sourceMappingURL=state-B8YwmUZU.mjs.map
|