@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.
Files changed (175) hide show
  1. package/README.md +1 -1
  2. package/dist/{HostingerProvider-Bx2lHHvu.cjs → HostingerProvider-Dlmbfass.cjs} +3 -3
  3. package/dist/{HostingerProvider-Bx2lHHvu.cjs.map → HostingerProvider-Dlmbfass.cjs.map} +1 -1
  4. package/dist/{HostingerProvider-Cd4aS5Kj.mjs → HostingerProvider-x9gQTAGZ.mjs} +2 -2
  5. package/dist/{HostingerProvider-Cd4aS5Kj.mjs.map → HostingerProvider-x9gQTAGZ.mjs.map} +1 -1
  6. package/dist/{LegacyStateStore-C2abV49N.cjs → LegacyStateStore-BGoo__sO.cjs} +2 -2
  7. package/dist/{LegacyStateStore-C2abV49N.cjs.map → LegacyStateStore-BGoo__sO.cjs.map} +1 -1
  8. package/dist/{LegacyStateStore-DIgkGaUP.mjs → LegacyStateStore-BUu1nQ5u.mjs} +2 -2
  9. package/dist/{LegacyStateStore-DIgkGaUP.mjs.map → LegacyStateStore-BUu1nQ5u.mjs.map} +1 -1
  10. package/dist/{LocalStateStore-DiJqKyPy.cjs → LocalStateStore-93urXyQe.cjs} +2 -2
  11. package/dist/{LocalStateStore-DiJqKyPy.cjs.map → LocalStateStore-93urXyQe.cjs.map} +1 -1
  12. package/dist/{LocalStateStore-Cy1ZBW7U.mjs → LocalStateStore-BRhMQRuy.mjs} +2 -2
  13. package/dist/{LocalStateStore-Cy1ZBW7U.mjs.map → LocalStateStore-BRhMQRuy.mjs.map} +1 -1
  14. package/dist/{S3StateStore-Ds0V1Lgm.cjs → S3StateStore-F4dxw6kS.cjs} +2 -2
  15. package/dist/{S3StateStore-Ds0V1Lgm.cjs.map → S3StateStore-F4dxw6kS.cjs.map} +1 -1
  16. package/dist/{S3StateStore-D3x6ivBL.mjs → S3StateStore-pw1GhWwt.mjs} +2 -2
  17. package/dist/{S3StateStore-D3x6ivBL.mjs.map → S3StateStore-pw1GhWwt.mjs.map} +1 -1
  18. package/dist/{SSMStateStore-CLipvx47.cjs → SSMStateStore-Bt9acuAF.cjs} +2 -2
  19. package/dist/{SSMStateStore-CLipvx47.cjs.map → SSMStateStore-Bt9acuAF.cjs.map} +1 -1
  20. package/dist/{SSMStateStore-DfF174xQ.mjs → SSMStateStore-Dmj7zzFO.mjs} +2 -2
  21. package/dist/{SSMStateStore-DfF174xQ.mjs.map → SSMStateStore-Dmj7zzFO.mjs.map} +1 -1
  22. package/dist/{bundler-C8uJf324.cjs → bundler-D6MlIfBT.cjs} +3 -3
  23. package/dist/{bundler-C8uJf324.cjs.map → bundler-D6MlIfBT.cjs.map} +1 -1
  24. package/dist/{bundler-DYgm9xsd.mjs → bundler-D_14JLZF.mjs} +3 -3
  25. package/dist/{bundler-DYgm9xsd.mjs.map → bundler-D_14JLZF.mjs.map} +1 -1
  26. package/dist/{cli-D3jofJ6j.cjs → cli-BfH1deAT.cjs} +6 -6
  27. package/dist/{cli-D3jofJ6j.cjs.map → cli-BfH1deAT.cjs.map} +1 -1
  28. package/dist/{cli-Bogz-zEj.mjs → cli-P56vvrDQ.mjs} +5 -5
  29. package/dist/{cli-Bogz-zEj.mjs.map → cli-P56vvrDQ.mjs.map} +1 -1
  30. package/dist/compose-391oEKj1.cjs +1982 -0
  31. package/dist/compose-391oEKj1.cjs.map +1 -0
  32. package/dist/compose-DprE3ASm.mjs +1862 -0
  33. package/dist/compose-DprE3ASm.mjs.map +1 -0
  34. package/dist/{config-DqNRiQOp.d.mts → config-BonvTW8p.d.mts} +3 -3
  35. package/dist/{config-Be-4_I6H.d.cts.map → config-BonvTW8p.d.mts.map} +1 -1
  36. package/dist/{config-Be-4_I6H.d.cts → config-V_X_BMpm.d.cts} +3 -3
  37. package/dist/{config-DqNRiQOp.d.mts.map → config-V_X_BMpm.d.cts.map} +1 -1
  38. package/dist/config.cjs +1 -1
  39. package/dist/config.d.cts +3 -3
  40. package/dist/config.d.mts +3 -3
  41. package/dist/config.mjs +1 -1
  42. package/dist/{credentials-B70vmLcm.cjs → credentials-Bzbg23n8.cjs} +176 -3
  43. package/dist/credentials-Bzbg23n8.cjs.map +1 -0
  44. package/dist/{credentials-s0wMeZBU.mjs → credentials-Dq1MnWQf.mjs} +128 -3
  45. package/dist/credentials-Dq1MnWQf.mjs.map +1 -0
  46. package/dist/{define-CYs0PEfZ.mjs → define-DR8xGYfL.mjs} +5 -1
  47. package/dist/define-DR8xGYfL.mjs.map +1 -0
  48. package/dist/{define-zUsP72ym.cjs → define-DzRz8FgH.cjs} +5 -1
  49. package/dist/define-DzRz8FgH.cjs.map +1 -0
  50. package/dist/deploy/public.cjs +18 -18
  51. package/dist/deploy/public.cjs.map +1 -1
  52. package/dist/deploy/public.d.cts +7 -4
  53. package/dist/deploy/public.d.cts.map +1 -1
  54. package/dist/deploy/public.d.mts +7 -4
  55. package/dist/deploy/public.d.mts.map +1 -1
  56. package/dist/deploy/public.mjs +11 -11
  57. package/dist/{deploy-Dc2LBJaK.mjs → deploy-9MBG_QLd.mjs} +8 -7
  58. package/dist/deploy-9MBG_QLd.mjs.map +1 -0
  59. package/dist/{deploy-yUcR2OlW.cjs → deploy-B80idPUZ.cjs} +11 -10
  60. package/dist/deploy-B80idPUZ.cjs.map +1 -0
  61. package/dist/{deploy-ZRXIPp1c.mjs → deploy-CZ5nlpsu.mjs} +13 -119
  62. package/dist/deploy-CZ5nlpsu.mjs.map +1 -0
  63. package/dist/{deploy-55rJkdKz.cjs → deploy-Cy8igpQF.cjs} +39 -145
  64. package/dist/deploy-Cy8igpQF.cjs.map +1 -0
  65. package/dist/{dokploy-CepdXuMl.mjs → dokploy-BdtBePjp.mjs} +3 -3
  66. package/dist/{dokploy-CepdXuMl.mjs.map → dokploy-BdtBePjp.mjs.map} +1 -1
  67. package/dist/{dokploy-D1d37rvM.cjs → dokploy-iFY8MY-L.cjs} +3 -3
  68. package/dist/{dokploy-D1d37rvM.cjs.map → dokploy-iFY8MY-L.cjs.map} +1 -1
  69. package/dist/{encryption-C9X98u2F.cjs → encryption-B1wJwgae.cjs} +5 -5
  70. package/dist/{encryption-C9X98u2F.cjs.map → encryption-B1wJwgae.cjs.map} +1 -1
  71. package/dist/{encryption-CKHjMpCr.mjs → encryption-DF_hgIpl.mjs} +4 -4
  72. package/dist/{encryption-CKHjMpCr.mjs.map → encryption-DF_hgIpl.mjs.map} +1 -1
  73. package/dist/{github-D-byNI7T.mjs → github-B0YYE98x.mjs} +3 -3
  74. package/dist/{github-D-byNI7T.mjs.map → github-B0YYE98x.mjs.map} +1 -1
  75. package/dist/{github-Dd3tMa1u.cjs → github-CYcmTdFs.cjs} +3 -3
  76. package/dist/{github-Dd3tMa1u.cjs.map → github-CYcmTdFs.cjs.map} +1 -1
  77. package/dist/{index-CfE9Y885.d.cts → index-DPUAGJaK.d.cts} +16 -3
  78. package/dist/index-DPUAGJaK.d.cts.map +1 -0
  79. package/dist/{index-CJ2qsSpp.d.mts → index-DwKD_8lt.d.mts} +16 -3
  80. package/dist/index-DwKD_8lt.d.mts.map +1 -0
  81. package/dist/index.cjs +233 -1667
  82. package/dist/index.cjs.map +1 -1
  83. package/dist/index.mjs +196 -1614
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/{local-C7wnrcYK.cjs → local-BdH4XN0E.cjs} +1 -178
  86. package/dist/local-BdH4XN0E.cjs.map +1 -0
  87. package/dist/{local-Cd8ZYQG3.mjs → local-CWR4Y_kW.mjs} +3 -126
  88. package/dist/local-CWR4Y_kW.mjs.map +1 -0
  89. package/dist/{migrate-B4gngTLe.mjs → migrate-B2qL5wj4.mjs} +6 -5
  90. package/dist/{migrate-B4gngTLe.mjs.map → migrate-B2qL5wj4.mjs.map} +1 -1
  91. package/dist/{migrate-tx9-P9uz.cjs → migrate-q4pPAXtO.cjs} +19 -18
  92. package/dist/{migrate-tx9-P9uz.cjs.map → migrate-q4pPAXtO.cjs.map} +1 -1
  93. package/dist/openapi.d.cts +1 -1
  94. package/dist/openapi.d.mts +1 -1
  95. package/dist/provider-C9_-45d5.cjs +56 -0
  96. package/dist/provider-C9_-45d5.cjs.map +1 -0
  97. package/dist/provider-q4lsYzYG.mjs +45 -0
  98. package/dist/provider-q4lsYzYG.mjs.map +1 -0
  99. package/dist/reconcile/public.d.cts +1 -1
  100. package/dist/reconcile/public.d.mts +1 -1
  101. package/dist/resolve-DLkIXTct.mjs +262 -0
  102. package/dist/resolve-DLkIXTct.mjs.map +1 -0
  103. package/dist/resolve-N_i4XNd-.cjs +315 -0
  104. package/dist/resolve-N_i4XNd-.cjs.map +1 -0
  105. package/dist/{runtime-CJEYK4Gz.d.mts → runtime-BnD7Nn96.d.cts} +2 -2
  106. package/dist/{runtime-CJEYK4Gz.d.mts.map → runtime-BnD7Nn96.d.cts.map} +1 -1
  107. package/dist/{runtime-Cjq1jlVX.d.cts → runtime-j-tmFL65.d.mts} +2 -2
  108. package/dist/{runtime-Cjq1jlVX.d.cts.map → runtime-j-tmFL65.d.mts.map} +1 -1
  109. package/dist/sniffer-BSwaL-dX.cjs +2236 -0
  110. package/dist/sniffer-BSwaL-dX.cjs.map +1 -0
  111. package/dist/sniffer-BZ-OJO4Y.mjs +2068 -0
  112. package/dist/sniffer-BZ-OJO4Y.mjs.map +1 -0
  113. package/dist/{sst-Cper040I.mjs → sst-B2HbrDR3.mjs} +4 -4
  114. package/dist/{sst-Cper040I.mjs.map → sst-B2HbrDR3.mjs.map} +1 -1
  115. package/dist/{sst-BdALKEas.cjs → sst-DcfsVH6x.cjs} +4 -4
  116. package/dist/{sst-BdALKEas.cjs.map → sst-DcfsVH6x.cjs.map} +1 -1
  117. package/dist/{sniffer-49KPbDgq.mjs → state-B8YwmUZU.mjs} +878 -2465
  118. package/dist/state-B8YwmUZU.mjs.map +1 -0
  119. package/dist/{sniffer-ByhbEW5A.cjs → state-DF26e_lo.cjs} +811 -2525
  120. package/dist/state-DF26e_lo.cjs.map +1 -0
  121. package/dist/{store-D_2ByRtW.cjs → store-CJF1Tqkq.cjs} +2 -2
  122. package/dist/{store-D_2ByRtW.cjs.map → store-CJF1Tqkq.cjs.map} +1 -1
  123. package/dist/{store-BaaonhkJ.mjs → store-CLiHnqOY.mjs} +2 -2
  124. package/dist/{store-BaaonhkJ.mjs.map → store-CLiHnqOY.mjs.map} +1 -1
  125. package/dist/target/public.cjs +6 -6
  126. package/dist/target/public.d.cts +2 -2
  127. package/dist/target/public.d.mts +2 -2
  128. package/dist/target/public.mjs +3 -3
  129. package/dist/terminal-Bs5E1oxm.cjs +88 -0
  130. package/dist/terminal-Bs5E1oxm.cjs.map +1 -0
  131. package/dist/terminal-CfbiYUbZ.mjs +84 -0
  132. package/dist/terminal-CfbiYUbZ.mjs.map +1 -0
  133. package/dist/{types-B_bEQvb9.d.mts → types-BCzMWBb6.d.mts} +43 -11
  134. package/dist/types-BCzMWBb6.d.mts.map +1 -0
  135. package/dist/{types-DkrDOMxw.d.cts → types-ByMWkXKP.d.cts} +43 -11
  136. package/dist/types-ByMWkXKP.d.cts.map +1 -0
  137. package/dist/workspace/index.cjs +3 -1
  138. package/dist/workspace/index.d.cts +3 -3
  139. package/dist/workspace/index.d.mts +3 -3
  140. package/dist/workspace/index.mjs +2 -2
  141. package/dist/{workspace-BwgWJK7h.cjs → workspace-BewAHZIo.cjs} +38 -3
  142. package/dist/workspace-BewAHZIo.cjs.map +1 -0
  143. package/dist/{workspace-Bwit4q9O.mjs → workspace-C06_pW4g.mjs} +27 -4
  144. package/dist/workspace-C06_pW4g.mjs.map +1 -0
  145. package/package.json +13 -13
  146. package/dist/credentials-B70vmLcm.cjs.map +0 -1
  147. package/dist/credentials-s0wMeZBU.mjs.map +0 -1
  148. package/dist/define-CYs0PEfZ.mjs.map +0 -1
  149. package/dist/define-zUsP72ym.cjs.map +0 -1
  150. package/dist/deploy-55rJkdKz.cjs.map +0 -1
  151. package/dist/deploy-Dc2LBJaK.mjs.map +0 -1
  152. package/dist/deploy-ZRXIPp1c.mjs.map +0 -1
  153. package/dist/deploy-yUcR2OlW.cjs.map +0 -1
  154. package/dist/index-CJ2qsSpp.d.mts.map +0 -1
  155. package/dist/index-CfE9Y885.d.cts.map +0 -1
  156. package/dist/local-C7wnrcYK.cjs.map +0 -1
  157. package/dist/local-Cd8ZYQG3.mjs.map +0 -1
  158. package/dist/resolve-BXsNQjMR.cjs +0 -220
  159. package/dist/resolve-BXsNQjMR.cjs.map +0 -1
  160. package/dist/resolve-DZ2IJ0qY.mjs +0 -173
  161. package/dist/resolve-DZ2IJ0qY.mjs.map +0 -1
  162. package/dist/runtime-BGNDrHzh.cjs +0 -163
  163. package/dist/runtime-BGNDrHzh.cjs.map +0 -1
  164. package/dist/runtime-Cmn-FeYO.mjs +0 -134
  165. package/dist/runtime-Cmn-FeYO.mjs.map +0 -1
  166. package/dist/sniffer-49KPbDgq.mjs.map +0 -1
  167. package/dist/sniffer-ByhbEW5A.cjs.map +0 -1
  168. package/dist/terminal-Bdv--jhY.cjs +0 -481
  169. package/dist/terminal-Bdv--jhY.cjs.map +0 -1
  170. package/dist/terminal-D7Ntz6WE.mjs +0 -440
  171. package/dist/terminal-D7Ntz6WE.mjs.map +0 -1
  172. package/dist/types-B_bEQvb9.d.mts.map +0 -1
  173. package/dist/types-DkrDOMxw.d.cts.map +0 -1
  174. package/dist/workspace-BwgWJK7h.cjs.map +0 -1
  175. package/dist/workspace-Bwit4q9O.mjs.map +0 -1
@@ -0,0 +1,2068 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { t as LocalSandbox } from "./local-CWR4Y_kW.mjs";
3
+ import { a as getDokployCredentials, d as storeHostingerToken, i as getCredentialsPath, l as removeDokployCredentials, u as storeDokployCredentials } from "./credentials-Dq1MnWQf.mjs";
4
+ import { d as output, r as discover, s as nodeWithTsx } from "./discover-LMrqsWSU.mjs";
5
+ import { i as activeSandbox } from "./sandbox-Dm247NGx.mjs";
6
+ import { n as derivedApps } from "./derive-B4vDpzgP.mjs";
7
+ import { o as builtinTarget } from "./define-DR8xGYfL.mjs";
8
+ import { h as getPublicEnvPrefix, k as assertDeployedStage, s as getAppBuildOrder } from "./workspace-C06_pW4g.mjs";
9
+ import { l as applicationName, n as secretsStoreFor, u as deployIdentity } from "./store-CLiHnqOY.mjs";
10
+ import { D as constructGlobs } from "./state-B8YwmUZU.mjs";
11
+ import { a as parseTargetOptions, o as resolveTarget } from "./resolve-DLkIXTct.mjs";
12
+ import { dirname, resolve } from "node:path";
13
+ import { stdin, stdout } from "node:process";
14
+ import * as readline from "node:readline/promises";
15
+ import { existsSync } from "node:fs";
16
+ import { hostname, userInfo } from "node:os";
17
+ import { fileURLToPath } from "node:url";
18
+ import { createCipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
19
+ //#region src/prompt.ts
20
+ /**
21
+ * Asking the person at the terminal.
22
+ *
23
+ * CLI layer only: a command's action may prompt, nothing it calls may. A
24
+ * library call (`deploy()`) that needs something it was not given raises a
25
+ * named error instead, and the command decides whether to ask.
26
+ */
27
+ /** A prompt was needed with no terminal to ask at. */
28
+ var PromptNeedsTerminal = class extends Error {
29
+ question;
30
+ instead;
31
+ constructor(question, instead) {
32
+ super(`Interactive input required. ${instead}`);
33
+ this.question = question;
34
+ this.instead = instead;
35
+ this.name = "PromptNeedsTerminal";
36
+ }
37
+ };
38
+ /** Whether there is a person at a terminal to ask. */
39
+ function canPrompt() {
40
+ return process.stdin.isTTY === true;
41
+ }
42
+ /**
43
+ * Ask `message` and resolve with the line typed — without echoing it when
44
+ * `hidden`. Ctrl+C at a hidden prompt exits, as it would anywhere else in a
45
+ * terminal program: raw mode has taken the signal away from the shell.
46
+ */
47
+ async function prompt(message, options) {
48
+ if (!canPrompt()) throw new PromptNeedsTerminal(message, options.instead);
49
+ if (options.hidden) {
50
+ process.stdout.write(message);
51
+ return new Promise((resolve, reject) => {
52
+ let value = "";
53
+ const cleanup = () => {
54
+ process.stdin.setRawMode(false);
55
+ process.stdin.pause();
56
+ process.stdin.removeListener("data", onData);
57
+ process.stdin.removeListener("error", onError);
58
+ };
59
+ const onError = (err) => {
60
+ cleanup();
61
+ reject(err);
62
+ };
63
+ const onData = (char) => {
64
+ const c = char.toString();
65
+ if (c === "\n" || c === "\r") {
66
+ cleanup();
67
+ process.stdout.write("\n");
68
+ resolve(value);
69
+ } else if (c === "") {
70
+ cleanup();
71
+ process.stdout.write("\n");
72
+ process.exit(1);
73
+ } else if (c === "" || c === "\b") {
74
+ if (value.length > 0) value = value.slice(0, -1);
75
+ } else value += c;
76
+ };
77
+ process.stdin.setRawMode(true);
78
+ process.stdin.resume();
79
+ process.stdin.on("data", onData);
80
+ process.stdin.on("error", onError);
81
+ });
82
+ }
83
+ const rl = readline.createInterface({
84
+ input: stdin,
85
+ output: stdout
86
+ });
87
+ try {
88
+ return await rl.question(message);
89
+ } finally {
90
+ rl.close();
91
+ }
92
+ }
93
+ //#endregion
94
+ //#region src/auth/index.ts
95
+ const logger = console;
96
+ /**
97
+ * Validate Dokploy token by making a test API call
98
+ */
99
+ async function validateDokployToken(endpoint, token) {
100
+ const { DokployApi } = await Promise.resolve().then(() => dokploy_api_exports);
101
+ return new DokployApi({
102
+ baseUrl: endpoint,
103
+ token
104
+ }).validateToken();
105
+ }
106
+ /** What answers a login prompt without a terminal. */
107
+ const LOGIN_INSTEAD = "Please provide --token option.";
108
+ /**
109
+ * Login to a service
110
+ */
111
+ async function loginCommand(options) {
112
+ const { provider, token: providedToken, endpoint: providedEndpoint } = options;
113
+ if (provider === "dokploy") {
114
+ logger.log("\n🔐 Logging in to Dokploy...\n");
115
+ let endpoint = providedEndpoint;
116
+ if (!endpoint) endpoint = await prompt("Dokploy URL (e.g., https://dokploy.example.com): ", { instead: LOGIN_INSTEAD });
117
+ endpoint = endpoint.replace(/\/$/, "");
118
+ try {
119
+ new URL(endpoint);
120
+ } catch {
121
+ logger.error("Invalid URL format");
122
+ process.exit(1);
123
+ }
124
+ let token = providedToken;
125
+ if (!token) {
126
+ logger.log(`\nGenerate a token at: ${endpoint}/settings/profile\n`);
127
+ token = await prompt("API Token: ", {
128
+ hidden: true,
129
+ instead: LOGIN_INSTEAD
130
+ });
131
+ }
132
+ if (!token) {
133
+ logger.error("Token is required");
134
+ process.exit(1);
135
+ }
136
+ logger.log("\nValidating credentials...");
137
+ if (!await validateDokployToken(endpoint, token)) {
138
+ logger.error("\n✗ Invalid credentials. Please check your token and try again.");
139
+ process.exit(1);
140
+ }
141
+ await storeDokployCredentials(token, endpoint);
142
+ logger.log("\n✓ Successfully logged in to Dokploy!");
143
+ logger.log(` Endpoint: ${endpoint}`);
144
+ logger.log(` Credentials stored in: ${getCredentialsPath()}`);
145
+ logger.log("\nYou can now use deploy commands without setting DOKPLOY_API_TOKEN.");
146
+ }
147
+ if (provider === "hostinger") {
148
+ logger.log("\n🔐 Logging in to Hostinger...\n");
149
+ let token = providedToken;
150
+ if (!token) {
151
+ logger.log("\nGenerate a token at: https://hpanel.hostinger.com/profile/api\n");
152
+ token = await prompt("API Token: ", {
153
+ hidden: true,
154
+ instead: LOGIN_INSTEAD
155
+ });
156
+ }
157
+ if (!token) {
158
+ logger.error("Token is required");
159
+ process.exit(1);
160
+ }
161
+ await storeHostingerToken(token);
162
+ logger.log("\n✓ Hostinger token stored.");
163
+ logger.log(` Credentials stored in: ${getCredentialsPath()}`);
164
+ logger.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.");
165
+ logger.log("\nYou can now use it as a DNS provider without setting HOSTINGER_API_TOKEN.");
166
+ }
167
+ }
168
+ /**
169
+ * Logout from a service
170
+ */
171
+ async function logoutCommand(options) {
172
+ const { provider = "dokploy" } = options;
173
+ if (provider === "all") {
174
+ if (await removeDokployCredentials()) logger.log("\n✓ Logged out from all services");
175
+ else logger.log("\nNo stored credentials found");
176
+ return;
177
+ }
178
+ if (provider === "dokploy") {
179
+ if (await removeDokployCredentials()) logger.log("\n✓ Logged out from Dokploy");
180
+ else logger.log("\nNo Dokploy credentials found");
181
+ }
182
+ }
183
+ /**
184
+ * Show current login status
185
+ */
186
+ async function whoamiCommand() {
187
+ logger.log("\n📋 Current credentials:\n");
188
+ const dokploy = await getDokployCredentials();
189
+ if (dokploy) {
190
+ logger.log(" Dokploy:");
191
+ logger.log(` Endpoint: ${dokploy.endpoint}`);
192
+ logger.log(` Token: ${maskToken(dokploy.token)}`);
193
+ } else logger.log(" Dokploy: Not logged in");
194
+ logger.log(`\n Credentials file: ${getCredentialsPath()}`);
195
+ }
196
+ /**
197
+ * Mask a token for display
198
+ */
199
+ function maskToken(token) {
200
+ if (token.length <= 8) return "****";
201
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
202
+ }
203
+ //#endregion
204
+ //#region src/workspace/client-generator.ts
205
+ /**
206
+ * Normalize routes to an array of patterns.
207
+ * Handles a glob or a list of them.
208
+ * @internal Exported for use in dev command
209
+ */
210
+ function normalizeRoutes(routes) {
211
+ if (!routes) return [];
212
+ return Array.isArray(routes) ? routes : [routes];
213
+ }
214
+ //#endregion
215
+ //#region src/secrets/encryption.ts
216
+ var encryption_exports = /* @__PURE__ */ __exportAll({
217
+ encryptSecrets: () => encryptSecrets,
218
+ generateDefineOptions: () => generateDefineOptions,
219
+ keyFingerprint: () => keyFingerprint
220
+ });
221
+ /** AES-256-GCM configuration */
222
+ const ALGORITHM = "aes-256-gcm";
223
+ const KEY_LENGTH = 32;
224
+ const IV_LENGTH = 12;
225
+ /**
226
+ * Encrypt secrets for embedding in a bundle.
227
+ * Uses AES-256-GCM with a randomly generated ephemeral key.
228
+ *
229
+ * @param secrets - Key-value pairs to encrypt
230
+ * @returns Encrypted payload with ephemeral master key
231
+ */
232
+ function encryptSecrets(secrets) {
233
+ const masterKey = randomBytes(KEY_LENGTH);
234
+ const iv = randomBytes(IV_LENGTH);
235
+ const plaintext = JSON.stringify(secrets);
236
+ const cipher = createCipheriv(ALGORITHM, masterKey, iv);
237
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
238
+ const authTag = cipher.getAuthTag();
239
+ return {
240
+ encrypted: Buffer.concat([ciphertext, authTag]).toString("base64"),
241
+ iv: iv.toString("hex"),
242
+ masterKey: masterKey.toString("hex")
243
+ };
244
+ }
245
+ /**
246
+ * Generate the define options for tsdown/esbuild.
247
+ * These will be injected at build time.
248
+ */
249
+ function generateDefineOptions(payload) {
250
+ return {
251
+ __GKM_ENCRYPTED_CREDENTIALS__: JSON.stringify(payload.encrypted),
252
+ __GKM_CREDENTIALS_IV__: JSON.stringify(payload.iv)
253
+ };
254
+ }
255
+ /**
256
+ * A short, one-way name for a master key: the first 8 hex characters of its
257
+ * SHA-256.
258
+ *
259
+ * Printed where the key itself used to be, so a person can tell which key a
260
+ * build used — and match it against the one they hold — without the output
261
+ * carrying a value that decrypts every secret of the stage.
262
+ */
263
+ function keyFingerprint(masterKey) {
264
+ return createHash("sha256").update(masterKey).digest("hex").slice(0, 8);
265
+ }
266
+ //#endregion
267
+ //#region src/target/secrets.ts
268
+ /**
269
+ * A stage's secrets as a target sees them: read and written through the
270
+ * stage's own store, and masked in everything the run prints once read.
271
+ */
272
+ /**
273
+ * Shorter values are left alone: what a progress line legitimately prints —
274
+ * a port, a stage, an app name — would otherwise come out as `***` wherever
275
+ * a secret happened to share it.
276
+ */
277
+ const SHORTEST_MASKED = 6;
278
+ /** The values a run must never print, and the rewrite that keeps it so. */
279
+ var Redactor = class {
280
+ values = /* @__PURE__ */ new Set();
281
+ add(value) {
282
+ if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
283
+ }
284
+ /** `text` with every masked value replaced by `***`, longest first. */
285
+ redact(text) {
286
+ if (this.values.size === 0) return text;
287
+ let out = text;
288
+ const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
289
+ for (const value of longestFirst) out = out.replaceAll(value, "***");
290
+ return out;
291
+ }
292
+ };
293
+ /** Every value in `secrets` that is a secret rather than a label. */
294
+ function secretValues(secrets) {
295
+ return [
296
+ secrets.seed,
297
+ ...Object.values(secrets.custom ?? {}),
298
+ ...Object.values(secrets.urls ?? {}),
299
+ ...Object.values(secrets.services ?? {}).map((service) => service?.password)
300
+ ].filter((value) => typeof value === "string");
301
+ }
302
+ /**
303
+ * The stage's secrets through the store `secrets.store` names for it. Opening
304
+ * one builds a client and makes no request, so a target that never reads them
305
+ * costs nothing.
306
+ */
307
+ async function deploySecrets(workspace, stage, redactor, options = {}) {
308
+ const store = await secretsStoreFor(workspace, stage, options);
309
+ const mask = (secrets) => {
310
+ for (const value of secretValues(secrets)) redactor.add(value);
311
+ };
312
+ return {
313
+ store: store.name,
314
+ async read() {
315
+ const secrets = await store.read(stage);
316
+ if (secrets) mask(secrets);
317
+ return secrets;
318
+ },
319
+ async write(secrets) {
320
+ mask(secrets);
321
+ await store.write(stage, secrets);
322
+ },
323
+ mask: (value) => redactor.add(value)
324
+ };
325
+ }
326
+ //#endregion
327
+ //#region src/deploy/events.ts
328
+ /** An error as an event carries it: its name and message, nothing else. */
329
+ function eventError(error) {
330
+ if (error instanceof Error) return {
331
+ name: error.name,
332
+ message: error.message
333
+ };
334
+ return {
335
+ name: "Error",
336
+ message: String(error)
337
+ };
338
+ }
339
+ //#endregion
340
+ //#region src/deploy/StateProvider.ts
341
+ /**
342
+ * Check if value is a StateProvider implementation.
343
+ */
344
+ function isStateProvider(value) {
345
+ return typeof value === "object" && value !== null && typeof value.read === "function" && typeof value.write === "function";
346
+ }
347
+ //#endregion
348
+ //#region src/deploy/StateStore.ts
349
+ /**
350
+ * Deploy state store.
351
+ *
352
+ * `StateProvider` reads and writes a whole stage at once, with nothing to stop
353
+ * two runs of the same stage from overwriting each other and nowhere to record
354
+ * a resource the moment it exists. A `StateStore` adds the three things a
355
+ * deploy needs to be safe against crashes and concurrent runs:
356
+ *
357
+ * - `lock(stage)`: one run per stage. A second gets `StateLocked`, naming the
358
+ * holder, instead of racing the first.
359
+ * - Versioned `read` and conditional `write`: a write names the version it was
360
+ * based on, and raises `StateVersionConflict` when the stored state moved on
361
+ * underneath it, so nothing is lost silently even without the lock.
362
+ * - Per-resource records: `putResource` journals one resource at a time, so a
363
+ * run that dies half way leaves behind the ids of everything it created.
364
+ *
365
+ * Built-in stores: `LocalStateStore`, `SSMStateStore`, `S3StateStore`. A
366
+ * custom `StateProvider` is wrapped by `LegacyStateStore`, which keeps it
367
+ * working but cannot lock.
368
+ */
369
+ var StateLocked = class extends Error {
370
+ stage;
371
+ holder;
372
+ location;
373
+ constructor(stage, holder, location) {
374
+ const by = holder ? `${holder.owner}@${holder.host} (pid ${holder.pid}) since ${holder.acquiredAt}${holder.operation ? ` for '${holder.operation}'` : ""}` : "a run that did not record who it was";
375
+ 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}\`.`);
376
+ this.stage = stage;
377
+ this.holder = holder;
378
+ this.location = location;
379
+ this.name = "StateLocked";
380
+ }
381
+ };
382
+ var StateVersionConflict = class extends Error {
383
+ stage;
384
+ expectedVersion;
385
+ actualVersion;
386
+ constructor(stage, expectedVersion, actualVersion) {
387
+ 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.`);
388
+ this.stage = stage;
389
+ this.expectedVersion = expectedVersion;
390
+ this.actualVersion = actualVersion;
391
+ this.name = "StateVersionConflict";
392
+ }
393
+ };
394
+ var StageStateMissing = class extends Error {
395
+ stage;
396
+ constructor(stage) {
397
+ super(`There is no deploy state for stage '${stage}' to record a resource in. Write the stage's state first (write with expectedVersion: null).`);
398
+ this.stage = stage;
399
+ this.name = "StageStateMissing";
400
+ }
401
+ };
402
+ var StateUnreadable = class extends Error {
403
+ stage;
404
+ location;
405
+ constructor(stage, location, cause) {
406
+ 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 });
407
+ this.stage = stage;
408
+ this.location = location;
409
+ this.name = "StateUnreadable";
410
+ }
411
+ };
412
+ var StateSchemaTooNew = class extends Error {
413
+ stage;
414
+ schemaVersion;
415
+ constructor(stage, schemaVersion) {
416
+ 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.`);
417
+ this.stage = stage;
418
+ this.schemaVersion = schemaVersion;
419
+ this.name = "StateSchemaTooNew";
420
+ }
421
+ };
422
+ /**
423
+ * Not thrown: emitted (once per store) when a custom `StateProvider` stands
424
+ * in for a store, so a deploy that cannot be protected from a concurrent one
425
+ * says so.
426
+ */
427
+ var StateStoreWithoutLocking = class extends Error {
428
+ provider;
429
+ constructor(provider) {
430
+ super(`The custom state provider '${provider}' has no lock and no versions, so two deploys of the same stage can still overwrite each other. Implement StateStore (lock, versioned read, conditional write) or use the 'local', 'ssm' or 's3' state provider.`);
431
+ this.provider = provider;
432
+ this.name = "StateStoreWithoutLocking";
433
+ }
434
+ };
435
+ var StateStoreNeedsWorkspaceName = class extends Error {
436
+ provider;
437
+ constructor(provider) {
438
+ super(`The '${provider}' state provider keys state by workspace name. Set "name" in gkm.config.ts.`);
439
+ this.provider = provider;
440
+ this.name = "StateStoreNeedsWorkspaceName";
441
+ }
442
+ };
443
+ var UnknownStateProvider = class extends Error {
444
+ config;
445
+ constructor(config) {
446
+ super(`Unknown state provider ${JSON.stringify(config)}. Use 'local', 'ssm', 's3', or an object implementing StateStore or StateProvider.`);
447
+ this.config = config;
448
+ this.name = "UnknownStateProvider";
449
+ }
450
+ };
451
+ /** A lock or write that could not get at the state backend in time. */
452
+ var StateStoreBusy = class extends Error {
453
+ stage;
454
+ location;
455
+ constructor(stage, location) {
456
+ super(`Timed out waiting to write deploy state for stage '${stage}' (${location}). If no other gkm process is running, remove ${location}.`);
457
+ this.stage = stage;
458
+ this.location = location;
459
+ this.name = "StateStoreBusy";
460
+ }
461
+ };
462
+ function decodeDocument(stage, body, location) {
463
+ let parsed;
464
+ try {
465
+ parsed = JSON.parse(body);
466
+ } catch (error) {
467
+ throw new StateUnreadable(stage, location, error);
468
+ }
469
+ if (typeof parsed !== "object" || parsed === null) throw new StateUnreadable(stage, location, parsed);
470
+ const schemaVersion = parsed.schemaVersion;
471
+ if (schemaVersion === void 0) return {
472
+ schemaVersion: 1,
473
+ state: parsed
474
+ };
475
+ if (schemaVersion === 2) return {
476
+ schemaVersion: 2,
477
+ document: parsed
478
+ };
479
+ throw new StateSchemaTooNew(stage, schemaVersion);
480
+ }
481
+ function encodeDocument(document) {
482
+ return JSON.stringify(document, null, 2);
483
+ }
484
+ /**
485
+ * v1 state as a v2 document. The ids v1 kept are seeded as `ready` records,
486
+ * so the first journaled deploy after an upgrade adopts them rather than
487
+ * treating them as unknown.
488
+ */
489
+ function migrateV1(stage, state) {
490
+ const now = (/* @__PURE__ */ new Date()).toISOString();
491
+ const resources = {};
492
+ const seed = (type, name, id) => {
493
+ if (!id) return;
494
+ const key = name ? `${type}:${name}` : type;
495
+ resources[key] = {
496
+ key,
497
+ type,
498
+ id,
499
+ status: "ready",
500
+ updatedAt: now
501
+ };
502
+ };
503
+ seed("project", null, state.projectId);
504
+ seed("environment", null, state.environmentId);
505
+ for (const [app, id] of Object.entries(state.applications ?? {})) seed("application", app, id);
506
+ seed("postgres", null, state.services?.postgresId);
507
+ seed("redis", null, state.services?.redisId);
508
+ seed("backup-destination", null, state.backups?.destinationId);
509
+ return {
510
+ schemaVersion: 2,
511
+ stage,
512
+ serial: 1,
513
+ state,
514
+ resources,
515
+ updatedAt: now
516
+ };
517
+ }
518
+ function newLockHolder(options) {
519
+ let owner = "unknown";
520
+ try {
521
+ owner = userInfo().username;
522
+ } catch {}
523
+ return {
524
+ id: randomUUID(),
525
+ owner,
526
+ host: hostname(),
527
+ pid: process.pid,
528
+ acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
529
+ operation: options?.operation
530
+ };
531
+ }
532
+ function contentVersion(body) {
533
+ return createHash("sha256").update(body).digest("hex").slice(0, 16);
534
+ }
535
+ /**
536
+ * A store over a backend that can read and conditionally write one blob per
537
+ * stage, and create a lock object only if it does not exist. Migration and
538
+ * resource records are the same for every such backend, so they live here.
539
+ */
540
+ var DocumentStateStore = class {
541
+ async lock(stage, options) {
542
+ const holder = newLockHolder(options);
543
+ await this.createLock(stage, holder);
544
+ let released = false;
545
+ return {
546
+ stage,
547
+ holder,
548
+ release: async () => {
549
+ if (released) return;
550
+ released = true;
551
+ await this.removeLock(stage, holder);
552
+ }
553
+ };
554
+ }
555
+ async forceUnlock(stage) {
556
+ const holder = await this.readLock(stage);
557
+ await this.removeLock(stage, null);
558
+ return holder;
559
+ }
560
+ async read(stage) {
561
+ const current = await this.readDocument(stage);
562
+ if (!current) return null;
563
+ return {
564
+ state: current.document.state,
565
+ resources: current.document.resources,
566
+ version: current.version
567
+ };
568
+ }
569
+ async write(stage, state, options) {
570
+ if (options.expectedVersion === null) {
571
+ const document = {
572
+ schemaVersion: 2,
573
+ stage,
574
+ serial: 1,
575
+ state,
576
+ resources: {},
577
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
578
+ };
579
+ return this.writeRaw(stage, encodeDocument(document), null);
580
+ }
581
+ return this.mutate(stage, options.expectedVersion, (document) => ({
582
+ ...document,
583
+ state
584
+ }));
585
+ }
586
+ async putResource(stage, record, options) {
587
+ return this.mutate(stage, options?.expectedVersion, (document) => ({
588
+ ...document,
589
+ resources: {
590
+ ...document.resources,
591
+ [record.key]: {
592
+ ...record,
593
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
594
+ }
595
+ }
596
+ }));
597
+ }
598
+ async deleteResource(stage, key, options) {
599
+ return this.mutate(stage, options?.expectedVersion, (document) => {
600
+ const { [key]: _removed, ...resources } = document.resources;
601
+ return {
602
+ ...document,
603
+ resources
604
+ };
605
+ });
606
+ }
607
+ async mutate(stage, expectedVersion, change) {
608
+ const current = await this.readDocument(stage);
609
+ if (!current) {
610
+ if (expectedVersion !== void 0) throw new StateVersionConflict(stage, expectedVersion, null);
611
+ throw new StageStateMissing(stage);
612
+ }
613
+ if (expectedVersion !== void 0 && current.version !== expectedVersion) throw new StateVersionConflict(stage, expectedVersion, current.version);
614
+ const next = change(current.document);
615
+ next.serial = current.document.serial + 1;
616
+ next.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
617
+ return this.writeRaw(stage, encodeDocument(next), current.version);
618
+ }
619
+ /**
620
+ * Reads the stage's document, migrating v1 in place on the way. The
621
+ * migration is itself a conditional write: if another run migrated (or
622
+ * wrote) first, its result is read instead.
623
+ */
624
+ async readDocument(stage, attempt = 0) {
625
+ const raw = await this.readRaw(stage);
626
+ if (!raw) return null;
627
+ const decoded = decodeDocument(stage, raw.body, this.location(stage));
628
+ if (decoded.schemaVersion === 2) return {
629
+ document: decoded.document,
630
+ version: raw.version
631
+ };
632
+ await this.writeV1Backup(stage, raw.body);
633
+ const document = migrateV1(stage, decoded.state);
634
+ try {
635
+ return {
636
+ document,
637
+ version: await this.writeRaw(stage, encodeDocument(document), raw.version)
638
+ };
639
+ } catch (error) {
640
+ if (error instanceof StateVersionConflict && attempt < 2) return this.readDocument(stage, attempt + 1);
641
+ throw error;
642
+ }
643
+ }
644
+ };
645
+ function isStateStore(value) {
646
+ return typeof value === "object" && value !== null && typeof value.lock === "function" && typeof value.read === "function" && typeof value.write === "function" && typeof value.putResource === "function";
647
+ }
648
+ /**
649
+ * The store for a workspace's `state` config:
650
+ *
651
+ * - none / `'local'`: `LocalStateStore` under `.gkm/`
652
+ * - `'ssm'`: `SSMStateStore`, with no local cache — SSM is read directly, so
653
+ * a stale local copy can never win over it
654
+ * - `'s3'`: `S3StateStore`
655
+ * - a `StateStore` object: used as is
656
+ * - a `StateProvider` object: wrapped by `LegacyStateStore`
657
+ */
658
+ async function createStateStore(options) {
659
+ const { config, workspaceRoot, workspaceName } = options;
660
+ if (!config || config.provider === "local") {
661
+ const { LocalStateStore } = await import("./LocalStateStore-BRhMQRuy.mjs").then((n) => n.n);
662
+ return new LocalStateStore(workspaceRoot);
663
+ }
664
+ if (isStateStore(config.provider)) return config.provider;
665
+ if (isStateProvider(config.provider)) {
666
+ const { LegacyStateStore } = await import("./LegacyStateStore-BUu1nQ5u.mjs");
667
+ return new LegacyStateStore(config.provider, { warn: options.warn });
668
+ }
669
+ if (config.provider === "ssm") {
670
+ if (!workspaceName) throw new StateStoreNeedsWorkspaceName("ssm");
671
+ const { SSMStateStore } = await import("./SSMStateStore-Dmj7zzFO.mjs");
672
+ const ssm = config;
673
+ return SSMStateStore.create({
674
+ workspaceName,
675
+ region: ssm.region,
676
+ profile: ssm.profile
677
+ });
678
+ }
679
+ if (config.provider === "s3") {
680
+ if (!workspaceName) throw new StateStoreNeedsWorkspaceName("s3");
681
+ const { S3StateStore } = await import("./S3StateStore-pw1GhWwt.mjs");
682
+ const s3 = config;
683
+ return S3StateStore.create({
684
+ workspaceName,
685
+ bucket: s3.bucket,
686
+ prefix: s3.prefix,
687
+ region: s3.region,
688
+ profile: s3.profile
689
+ });
690
+ }
691
+ throw new UnknownStateProvider(config);
692
+ }
693
+ //#endregion
694
+ //#region src/deploy/orchestrate.ts
695
+ /**
696
+ * The run around a target: what every deploy does whatever it deploys
697
+ * through.
698
+ *
699
+ * It loads the workspace, resolves the target, works out the apps and the
700
+ * identity, takes the stage's lock, and calls the target's phases in order,
701
+ * reporting each as it starts, finishes or fails. Everything that is about
702
+ * *where* the stage goes is the target's.
703
+ */
704
+ /** Apps were asked for by name that the workspace does not have. */
705
+ var UnknownDeployApps = class extends Error {
706
+ apps;
707
+ available;
708
+ constructor(apps, available) {
709
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
710
+ this.apps = apps;
711
+ this.available = available;
712
+ this.name = "UnknownDeployApps";
713
+ }
714
+ };
715
+ /** Every app asked for deploys through some other target. */
716
+ var NoDeployableApps = class extends Error {
717
+ stage;
718
+ target;
719
+ constructor(stage, target) {
720
+ super(`No apps to deploy through "${target}": every selected app deploys somewhere else. Pick the target with --target, or set each app's deploy in gkm.config.ts.`);
721
+ this.stage = stage;
722
+ this.target = target;
723
+ this.name = "NoDeployableApps";
724
+ }
725
+ };
726
+ /** A failed rollback, after the failure that called for it. */
727
+ var RollbackFailed = class extends Error {
728
+ target;
729
+ failure;
730
+ constructor(target, failure, cause) {
731
+ super(`Deploying through "${target}" failed, and so did rolling it back: ${cause instanceof Error ? cause.message : String(cause)}. The stage may be part-released; deploy again, or roll it back by hand. The first failure: ${failure instanceof Error ? failure.message : String(failure)}`, { cause });
732
+ this.target = target;
733
+ this.failure = failure;
734
+ this.name = "RollbackFailed";
735
+ }
736
+ };
737
+ /**
738
+ * Generate image tag from stage and timestamp
739
+ */
740
+ function generateTag(stage) {
741
+ return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
742
+ }
743
+ /** Why an app that deploys through another target is left out. */
744
+ function elsewhere(target, stage) {
745
+ const instead = builtinTarget(target)?.instead?.(stage);
746
+ if (instead) return `it deploys through "${target}" — ${instead}`;
747
+ return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
748
+ }
749
+ /**
750
+ * Deploy a workspace's stage through its target.
751
+ *
752
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
753
+ * exits: credentials come from `ctx.credentials`, progress goes to
754
+ * `ctx.emit` and to `output`, and every failure is thrown.
755
+ *
756
+ * @internal
757
+ */
758
+ async function runDeploy(source, request, ctx) {
759
+ const { stage } = request;
760
+ const redactor = ctx.redactor ?? new Redactor();
761
+ const emit = (event) => ctx.emit(event.type === "log" ? {
762
+ ...event,
763
+ message: redactor.redact(event.message)
764
+ } : event);
765
+ /** Run one phase between its events. */
766
+ const phase = async (name, body) => {
767
+ ctx.signal?.throwIfAborted();
768
+ emit({
769
+ type: "phase.started",
770
+ phase: name
771
+ });
772
+ try {
773
+ const value = await body();
774
+ emit({
775
+ type: "phase.finished",
776
+ phase: name
777
+ });
778
+ return value;
779
+ } catch (error) {
780
+ emit({
781
+ type: "phase.failed",
782
+ phase: name,
783
+ error: eventError(error)
784
+ });
785
+ throw error;
786
+ }
787
+ };
788
+ ctx.signal?.throwIfAborted();
789
+ emit({
790
+ type: "phase.started",
791
+ phase: "validate"
792
+ });
793
+ let prepared;
794
+ try {
795
+ prepared = await prepare(source, request, ctx, emit, redactor);
796
+ } catch (error) {
797
+ emit({
798
+ type: "phase.failed",
799
+ phase: "validate",
800
+ error: eventError(error)
801
+ });
802
+ throw error;
803
+ }
804
+ const { resolved, phaseCtx, store } = prepared;
805
+ const { target } = resolved;
806
+ if (ctx.dryRun) {
807
+ const run = await validate(target, phaseCtx, emit);
808
+ await phase("plan", () => target.plan(phaseCtx, run));
809
+ return target.result(phaseCtx, run);
810
+ }
811
+ let lock;
812
+ try {
813
+ lock = await store.lock(stage, { operation: "deploy" });
814
+ } catch (error) {
815
+ emit({
816
+ type: "phase.failed",
817
+ phase: "validate",
818
+ error: eventError(error)
819
+ });
820
+ throw error;
821
+ }
822
+ try {
823
+ const run = await validate(target, phaseCtx, emit);
824
+ if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
825
+ if (target.build) await phase("build", () => target.build(phaseCtx, run));
826
+ let releasing = "release";
827
+ try {
828
+ await phase("release", () => target.release(phaseCtx, run));
829
+ releasing = "verify";
830
+ if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
831
+ } catch (error) {
832
+ if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
833
+ if (!target.rollback) throw error;
834
+ try {
835
+ await phase("rollback", () => target.rollback(phaseCtx, run, {
836
+ phase: releasing,
837
+ error
838
+ }));
839
+ } catch (rollbackError) {
840
+ throw new RollbackFailed(resolved.name, error, rollbackError);
841
+ }
842
+ throw error;
843
+ }
844
+ return await target.result(phaseCtx, run);
845
+ } finally {
846
+ await lock.release();
847
+ }
848
+ }
849
+ /** `validate`, then the run's `deploy.started`, inside the validate phase. */
850
+ async function validate(target, phaseCtx, emit) {
851
+ try {
852
+ const run = await target.validate(phaseCtx);
853
+ const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
854
+ emit({
855
+ type: "deploy.started",
856
+ stage: phaseCtx.stage,
857
+ target: phaseCtx.target,
858
+ identity: phaseCtx.identity.key,
859
+ tag: phaseCtx.tag,
860
+ apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
861
+ dryRun: phaseCtx.dryRun
862
+ });
863
+ emit({
864
+ type: "phase.finished",
865
+ phase: "validate"
866
+ });
867
+ return run;
868
+ } catch (error) {
869
+ emit({
870
+ type: "phase.failed",
871
+ phase: "validate",
872
+ error: eventError(error)
873
+ });
874
+ throw error;
875
+ }
876
+ }
877
+ /** Everything the phases are handed, worked out before the first of them. */
878
+ async function prepare(source, request, ctx, emit, redactor) {
879
+ const { stage } = request;
880
+ const configured = typeof source === "function" ? await source() : source;
881
+ const local = stage === configured.stages.local;
882
+ if (!local) assertDeployedStage(configured.stages, stage);
883
+ const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
884
+ const resolved = await resolveTarget(targetName, {
885
+ workspace: configured,
886
+ stage,
887
+ ...ctx.targets ? { host: ctx.targets } : {}
888
+ });
889
+ if (local && !resolved.target.capabilities.localStage) assertDeployedStage(configured.stages, stage);
890
+ const options = await parseTargetOptions(resolved);
891
+ const manifest = await discover({
892
+ patterns: constructGlobs(configured),
893
+ cwd: configured.root
894
+ });
895
+ const units = derivedApps(manifest, configured);
896
+ const workspace = Object.keys(units).length > 0 ? {
897
+ ...configured,
898
+ apps: units
899
+ } : configured;
900
+ const identity = deployIdentity(workspace, stage);
901
+ const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
902
+ cwd: workspace.root,
903
+ stage
904
+ }) : generateTag(stage));
905
+ const buildOrder = getAppBuildOrder(workspace);
906
+ let selected = buildOrder;
907
+ if (request.apps && request.apps.length > 0) {
908
+ const unknown = request.apps.filter((name) => !workspace.apps[name]);
909
+ if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
910
+ selected = buildOrder.filter((name) => request.apps.includes(name));
911
+ }
912
+ const skipped = [];
913
+ const skip = (app, reason) => {
914
+ skipped.push({
915
+ app,
916
+ reason
917
+ });
918
+ emit({
919
+ type: "app.skipped",
920
+ app,
921
+ reason
922
+ });
923
+ };
924
+ const byDefault = configured.deploy?.default ?? "dokploy";
925
+ const apps = selected.filter((name) => {
926
+ const own = workspace.apps[name].resolvedDeployTarget;
927
+ const deploysThrough = own === byDefault ? targetName : own;
928
+ if (deploysThrough === targetName) return true;
929
+ skip(name, elsewhere(deploysThrough, stage));
930
+ return false;
931
+ });
932
+ if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
933
+ const store = await createStateStore({
934
+ config: workspace.state,
935
+ workspaceRoot: workspace.root,
936
+ workspaceName: workspace.name
937
+ });
938
+ const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
939
+ const line = (level) => (message) => emit({
940
+ type: "log",
941
+ level,
942
+ message
943
+ });
944
+ const logger = {
945
+ info: line("info"),
946
+ warn: line("warn"),
947
+ error: line("error")
948
+ };
949
+ return {
950
+ resolved,
951
+ phaseCtx: {
952
+ target: targetName,
953
+ cwd: workspace.root,
954
+ stage,
955
+ tag,
956
+ tagGiven: request.tag !== void 0,
957
+ apps,
958
+ skipped,
959
+ identity,
960
+ workspace,
961
+ manifest,
962
+ options,
963
+ dryRun: ctx.dryRun,
964
+ credentials: ctx.credentials,
965
+ state: store,
966
+ secrets,
967
+ logger,
968
+ signal: ctx.signal ?? new AbortController().signal,
969
+ childOutput: ctx.childOutput ?? "inherit",
970
+ emit,
971
+ skip,
972
+ name: (resource) => applicationName(identity, resource)
973
+ },
974
+ store
975
+ };
976
+ }
977
+ //#endregion
978
+ //#region src/deploy/dokploy-api.ts
979
+ var dokploy_api_exports = /* @__PURE__ */ __exportAll({
980
+ DEFAULT_DOKPLOY_TIMEOUT_MS: () => DEFAULT_DOKPLOY_TIMEOUT_MS,
981
+ DokployApi: () => DokployApi,
982
+ DokployApiError: () => DokployApiError,
983
+ DokployRequestTimedOut: () => DokployRequestTimedOut
984
+ });
985
+ /** Per request, so a stalled server fails the deploy, not the CI job. */
986
+ const DEFAULT_DOKPLOY_TIMEOUT_MS = 3e4;
987
+ /**
988
+ * Dokploy accepted the connection but did not answer in time.
989
+ *
990
+ * Not retried: a request that arrived and stalled may still be acted on, and
991
+ * sending it again could repeat a deploy or a create the server is already
992
+ * doing.
993
+ */
994
+ var DokployRequestTimedOut = class extends Error {
995
+ baseUrl;
996
+ endpoint;
997
+ timeoutMs;
998
+ constructor(baseUrl, endpoint, timeoutMs) {
999
+ 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.`);
1000
+ this.baseUrl = baseUrl;
1001
+ this.endpoint = endpoint;
1002
+ this.timeoutMs = timeoutMs;
1003
+ this.name = "DokployRequestTimedOut";
1004
+ }
1005
+ };
1006
+ /**
1007
+ * Waits `ms` between retries, or rejects with the signal's reason the moment
1008
+ * it aborts — a caller who gave up should not sit through the backoff.
1009
+ */
1010
+ function pause(ms, signal) {
1011
+ return new Promise((resolve, reject) => {
1012
+ if (signal?.aborted) {
1013
+ reject(signal.reason);
1014
+ return;
1015
+ }
1016
+ const onAbort = () => {
1017
+ clearTimeout(timer);
1018
+ reject(signal?.reason);
1019
+ };
1020
+ const timer = setTimeout(() => {
1021
+ signal?.removeEventListener("abort", onAbort);
1022
+ resolve();
1023
+ }, ms);
1024
+ signal?.addEventListener("abort", onAbort, { once: true });
1025
+ });
1026
+ }
1027
+ var DokployApiError = class extends Error {
1028
+ status;
1029
+ statusText;
1030
+ issues;
1031
+ constructor(message, status, statusText, issues) {
1032
+ super(message);
1033
+ this.status = status;
1034
+ this.statusText = statusText;
1035
+ this.issues = issues;
1036
+ this.name = "DokployApiError";
1037
+ }
1038
+ };
1039
+ /**
1040
+ * Dokploy API client
1041
+ */
1042
+ var DokployApi = class {
1043
+ baseUrl;
1044
+ token;
1045
+ timeoutMs;
1046
+ signal;
1047
+ constructor(options) {
1048
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
1049
+ this.token = options.token;
1050
+ this.timeoutMs = options.timeoutMs ?? 3e4;
1051
+ this.signal = options.signal;
1052
+ }
1053
+ /**
1054
+ * Make a GET request to the Dokploy API
1055
+ */
1056
+ async get(endpoint) {
1057
+ return this.request("GET", endpoint);
1058
+ }
1059
+ /**
1060
+ * Make a POST request to the Dokploy API
1061
+ */
1062
+ async post(endpoint, body) {
1063
+ return this.request("POST", endpoint, body);
1064
+ }
1065
+ /**
1066
+ * Make a request to the Dokploy API
1067
+ */
1068
+ async request(method, endpoint, body) {
1069
+ const url = `${this.baseUrl}/api/${endpoint}`;
1070
+ let response;
1071
+ let timeout;
1072
+ let lastError;
1073
+ for (let attempt = 1; attempt <= 3; attempt++) {
1074
+ this.signal?.throwIfAborted();
1075
+ timeout = AbortSignal.timeout(this.timeoutMs);
1076
+ try {
1077
+ response = await fetch(url, {
1078
+ method,
1079
+ headers: {
1080
+ "Content-Type": "application/json",
1081
+ "x-api-key": this.token
1082
+ },
1083
+ body: body ? JSON.stringify(body) : void 0,
1084
+ signal: this.signal ? AbortSignal.any([this.signal, timeout]) : timeout
1085
+ });
1086
+ break;
1087
+ } catch (error) {
1088
+ const stopped = this.stopped(timeout, endpoint);
1089
+ if (stopped) throw stopped;
1090
+ lastError = error;
1091
+ if (attempt === 3) break;
1092
+ await pause(attempt * 750, this.signal);
1093
+ }
1094
+ }
1095
+ if (!response || !timeout) {
1096
+ const detail = lastError instanceof Error ? lastError.message : String(lastError);
1097
+ throw new DokployApiError(`Could not reach Dokploy at ${this.baseUrl} (${endpoint}): ${detail}`, 0, "Network error");
1098
+ }
1099
+ try {
1100
+ return await this.read(response);
1101
+ } catch (error) {
1102
+ throw this.stopped(timeout, endpoint) ?? error;
1103
+ }
1104
+ }
1105
+ /**
1106
+ * What a request cut short should reject with: the caller's own reason
1107
+ * when they aborted, `DokployRequestTimedOut` when the deadline passed,
1108
+ * nothing when it was neither.
1109
+ */
1110
+ stopped(timeout, endpoint) {
1111
+ if (this.signal?.aborted) return this.signal.reason;
1112
+ if (timeout.aborted) return new DokployRequestTimedOut(this.baseUrl, endpoint, this.timeoutMs);
1113
+ }
1114
+ /** Turns a response into its JSON body, or a `DokployApiError`. */
1115
+ async read(response) {
1116
+ if (!response.ok) {
1117
+ let errorMessage = `Dokploy API error: ${response.status} ${response.statusText}`;
1118
+ let issues;
1119
+ try {
1120
+ const errorBody = await response.json();
1121
+ if (errorBody.message) errorMessage = `Dokploy API error: ${errorBody.message}`;
1122
+ if (errorBody.issues?.length) {
1123
+ issues = errorBody.issues;
1124
+ errorMessage += `\n Issues: ${errorBody.issues.map((i) => i.message).join(", ")}`;
1125
+ }
1126
+ } catch {}
1127
+ throw new DokployApiError(errorMessage, response.status, response.statusText, issues);
1128
+ }
1129
+ const text = await response.text();
1130
+ if (!text || text.trim() === "") return;
1131
+ return JSON.parse(text);
1132
+ }
1133
+ /**
1134
+ * Every external port published on this server, across every project.
1135
+ *
1136
+ * Dokploy knows what it has bound; guessing does not. A port that looks free
1137
+ * from here can be held by a service in a project this deploy has never
1138
+ * heard of — which surfaces as `Port 5432 is already in use by container
1139
+ * "…"`, naming something the caller cannot see.
1140
+ *
1141
+ * `project.all` is a summary, so each project is fetched: the per-service
1142
+ * `externalPort` only appears on `project.one`.
1143
+ */
1144
+ async publishedPorts() {
1145
+ const ports = /* @__PURE__ */ new Set();
1146
+ const projects = await this.listProjects();
1147
+ for (const project of projects) {
1148
+ const details = await this.getProject(project.projectId);
1149
+ for (const environment of details.environments ?? []) {
1150
+ const resources = [
1151
+ ...environment.postgres ?? [],
1152
+ ...environment.redis ?? [],
1153
+ ...environment.applications ?? []
1154
+ ];
1155
+ for (const resource of resources) if (typeof resource.externalPort === "number") ports.add(resource.externalPort);
1156
+ }
1157
+ }
1158
+ return ports;
1159
+ }
1160
+ /**
1161
+ * Validate the API token by making a test request
1162
+ */
1163
+ async validateToken() {
1164
+ try {
1165
+ await this.get("project.all");
1166
+ return true;
1167
+ } catch {
1168
+ return false;
1169
+ }
1170
+ }
1171
+ /**
1172
+ * List all projects
1173
+ */
1174
+ async listProjects() {
1175
+ return this.get("project.all");
1176
+ }
1177
+ /**
1178
+ * Get a single project by ID
1179
+ */
1180
+ async getProject(projectId) {
1181
+ return this.get(`project.one?projectId=${projectId}`);
1182
+ }
1183
+ /**
1184
+ * Create a new project
1185
+ */
1186
+ async createProject(name, description) {
1187
+ return this.post("project.create", {
1188
+ name,
1189
+ description: description ?? `Created by gkm CLI`
1190
+ });
1191
+ }
1192
+ /**
1193
+ * Change a project's name or description.
1194
+ *
1195
+ * The name is sent with the description because `project.update` validates
1196
+ * the whole project on some Dokploy versions, and a missing name fails it.
1197
+ */
1198
+ async updateProject(projectId, updates) {
1199
+ await this.post("project.update", {
1200
+ projectId,
1201
+ ...updates
1202
+ });
1203
+ }
1204
+ /**
1205
+ * Delete a project and all its resources
1206
+ */
1207
+ async deleteProject(projectId) {
1208
+ await this.post("project.remove", { projectId });
1209
+ }
1210
+ /**
1211
+ * Create an environment in a project
1212
+ */
1213
+ async createEnvironment(projectId, name, description) {
1214
+ return this.post("environment.create", {
1215
+ projectId,
1216
+ name,
1217
+ description: description ?? `${name} environment`
1218
+ });
1219
+ }
1220
+ /**
1221
+ * List all applications in a project
1222
+ */
1223
+ async listApplications(projectId) {
1224
+ return this.listInProject(projectId, (env) => env.applications);
1225
+ }
1226
+ /**
1227
+ * Everything of one kind in a project, across its environments.
1228
+ *
1229
+ * From `project.one`, because the per-kind `*.all?projectId=` endpoints
1230
+ * return **404** on current Dokploy: resources live under environments now.
1231
+ * Those calls used to be wrapped in `catch { return [] }`, which turned "I
1232
+ * could not ask" into "there are none" — and for a find-or-create that is
1233
+ * the worst available answer. Every deploy created a second application, a
1234
+ * second Postgres and a second Redis, silently, for as long as the project
1235
+ * existed.
1236
+ *
1237
+ * A failure here is not swallowed: creating a duplicate is worse than
1238
+ * stopping.
1239
+ */
1240
+ async listInProject(projectId, pick) {
1241
+ return ((await this.getProject(projectId)).environments ?? []).flatMap((environment) => (pick(environment) ?? []).map((resource) => ({
1242
+ ...resource,
1243
+ environmentId: environment.environmentId
1244
+ })));
1245
+ }
1246
+ /**
1247
+ * Find an application by name in a project
1248
+ */
1249
+ async findApplicationByName(projectId, name, environmentId) {
1250
+ const applications = await this.listApplications(projectId);
1251
+ const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
1252
+ return applications.find((app) => (!environmentId || app.environmentId === environmentId) && (app.name === name || app.appName === normalizedName));
1253
+ }
1254
+ /**
1255
+ * Create a new application
1256
+ */
1257
+ async createApplication(name, projectId, environmentId) {
1258
+ return this.post("application.create", {
1259
+ name,
1260
+ projectId,
1261
+ environmentId,
1262
+ appName: name.toLowerCase().replace(/[^a-z0-9-]/g, "-")
1263
+ });
1264
+ }
1265
+ /**
1266
+ * Find or create an application by name
1267
+ */
1268
+ async findOrCreateApplication(name, projectId, environmentId) {
1269
+ const existing = await this.findApplicationByName(projectId, name, environmentId);
1270
+ if (existing) return {
1271
+ application: existing,
1272
+ created: false
1273
+ };
1274
+ return {
1275
+ application: await this.createApplication(name, projectId, environmentId),
1276
+ created: true
1277
+ };
1278
+ }
1279
+ /**
1280
+ * Get an application by ID
1281
+ */
1282
+ async getApplication(applicationId) {
1283
+ try {
1284
+ return await this.get(`application.one?applicationId=${applicationId}`);
1285
+ } catch {
1286
+ return null;
1287
+ }
1288
+ }
1289
+ /**
1290
+ * Update an application
1291
+ */
1292
+ async updateApplication(applicationId, updates) {
1293
+ await this.post("application.update", {
1294
+ applicationId,
1295
+ ...updates
1296
+ });
1297
+ }
1298
+ /**
1299
+ * Save environment variables for an application
1300
+ */
1301
+ async saveApplicationEnv(applicationId, env, options) {
1302
+ await this.post("application.saveEnvironment", {
1303
+ applicationId,
1304
+ env,
1305
+ buildArgs: options?.buildArgs ?? null,
1306
+ buildSecrets: options?.buildSecrets ?? null,
1307
+ createEnvFile: false
1308
+ });
1309
+ }
1310
+ /**
1311
+ * Configure application to use Docker provider (pull from registry)
1312
+ *
1313
+ * For private registries, either:
1314
+ * - Use `registryId` if the registry is configured in Dokploy
1315
+ * - Or provide `username`, `password`, and `registryUrl` directly
1316
+ */
1317
+ async saveDockerProvider(applicationId, dockerImage, options) {
1318
+ await this.post("application.saveDockerProvider", {
1319
+ applicationId,
1320
+ dockerImage,
1321
+ ...options,
1322
+ username: options?.username ?? null,
1323
+ password: options?.password ?? null,
1324
+ registryUrl: options?.registryUrl ?? null
1325
+ });
1326
+ }
1327
+ /**
1328
+ * Deploy an application
1329
+ */
1330
+ async deployApplication(applicationId) {
1331
+ await this.post("application.deploy", { applicationId });
1332
+ }
1333
+ /**
1334
+ * Delete an application
1335
+ */
1336
+ async deleteApplication(applicationId) {
1337
+ await this.post("application.remove", { applicationId });
1338
+ }
1339
+ /**
1340
+ * List all registries
1341
+ */
1342
+ async listRegistries() {
1343
+ return this.get("registry.all");
1344
+ }
1345
+ /**
1346
+ * Create a new registry
1347
+ */
1348
+ async createRegistry(registryName, registryUrl, username, password, options) {
1349
+ return this.post("registry.create", {
1350
+ registryName,
1351
+ registryUrl,
1352
+ username,
1353
+ password,
1354
+ imagePrefix: options?.imagePrefix
1355
+ });
1356
+ }
1357
+ /**
1358
+ * Get a registry by ID
1359
+ */
1360
+ async getRegistry(registryId) {
1361
+ return this.get(`registry.one?registryId=${registryId}`);
1362
+ }
1363
+ /**
1364
+ * Update a registry
1365
+ */
1366
+ async updateRegistry(registryId, updates) {
1367
+ await this.post("registry.update", {
1368
+ registryId,
1369
+ ...updates
1370
+ });
1371
+ }
1372
+ /**
1373
+ * Delete a registry
1374
+ */
1375
+ async deleteRegistry(registryId) {
1376
+ await this.post("registry.remove", { registryId });
1377
+ }
1378
+ /**
1379
+ * List all Postgres databases in a project
1380
+ */
1381
+ async listPostgres(projectId) {
1382
+ return this.listInProject(projectId, (env) => env.postgres);
1383
+ }
1384
+ /**
1385
+ * Find a Postgres database by name in a project
1386
+ */
1387
+ async findPostgresByName(projectId, name) {
1388
+ const databases = await this.listPostgres(projectId);
1389
+ const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
1390
+ const match = databases.find((db) => db.name === name || db.appName === normalizedName);
1391
+ if (!match) return void 0;
1392
+ return this.getPostgres(match.postgresId);
1393
+ }
1394
+ /**
1395
+ * Create a new Postgres database
1396
+ */
1397
+ async createPostgres(name, projectId, environmentId, options) {
1398
+ return this.post("postgres.create", {
1399
+ name,
1400
+ projectId,
1401
+ environmentId,
1402
+ appName: options?.appName ?? name.toLowerCase().replace(/[^a-z0-9-]/g, "-"),
1403
+ databaseName: options?.databaseName,
1404
+ databaseUser: options?.databaseUser ?? "postgres",
1405
+ databasePassword: options?.databasePassword,
1406
+ dockerImage: options?.dockerImage ?? "postgres:18",
1407
+ description: options?.description ?? `Postgres database for ${name}`
1408
+ });
1409
+ }
1410
+ /**
1411
+ * Find or create a Postgres database by name
1412
+ */
1413
+ async findOrCreatePostgres(name, projectId, environmentId, options) {
1414
+ const existing = await this.findPostgresByName(projectId, name);
1415
+ if (existing) return {
1416
+ postgres: existing,
1417
+ created: false
1418
+ };
1419
+ return {
1420
+ postgres: await this.createPostgres(name, projectId, environmentId, options),
1421
+ created: true
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Get a Postgres database by ID
1426
+ */
1427
+ async getPostgres(postgresId) {
1428
+ return this.get(`postgres.one?postgresId=${postgresId}`);
1429
+ }
1430
+ /**
1431
+ * Deploy a Postgres database
1432
+ */
1433
+ async deployPostgres(postgresId) {
1434
+ await this.post("postgres.deploy", { postgresId });
1435
+ }
1436
+ /**
1437
+ * Save environment variables for Postgres
1438
+ */
1439
+ async savePostgresEnv(postgresId, env) {
1440
+ await this.post("postgres.saveEnvironment", {
1441
+ postgresId,
1442
+ env
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Set external port for Postgres (for external access)
1447
+ */
1448
+ async savePostgresExternalPort(postgresId, externalPort) {
1449
+ await this.post("postgres.saveExternalPort", {
1450
+ postgresId,
1451
+ externalPort
1452
+ });
1453
+ }
1454
+ /**
1455
+ * Update Postgres configuration
1456
+ */
1457
+ async updatePostgres(postgresId, updates) {
1458
+ await this.post("postgres.update", {
1459
+ postgresId,
1460
+ ...updates
1461
+ });
1462
+ }
1463
+ /**
1464
+ * Delete a Postgres database
1465
+ */
1466
+ async deletePostgres(postgresId) {
1467
+ await this.post("postgres.remove", { postgresId });
1468
+ }
1469
+ /**
1470
+ * The compose stacks in a project.
1471
+ *
1472
+ * Dokploy has first-class primitives for Postgres and Redis and none for
1473
+ * MinIO, so an object store is a compose stack — the one kind whose contents
1474
+ * this target writes rather than configures.
1475
+ */
1476
+ async listCompose(projectId) {
1477
+ return this.listInProject(projectId, (env) => env.compose);
1478
+ }
1479
+ /** A compose stack by name, hydrated — `project.one` returns summaries. */
1480
+ async findComposeByName(projectId, name) {
1481
+ const summary = (await this.listCompose(projectId)).find((compose) => compose.name === name);
1482
+ return summary ? this.getCompose(summary.composeId) : void 0;
1483
+ }
1484
+ async getCompose(composeId) {
1485
+ return this.get(`compose.one?composeId=${composeId}`);
1486
+ }
1487
+ /**
1488
+ * A compose stack carrying the file this target wrote.
1489
+ *
1490
+ * Created empty and then updated, because `compose.create` takes no file:
1491
+ * it defaults to `sourceType: 'github'` and expects a repository. `raw` is
1492
+ * what makes the file ours.
1493
+ */
1494
+ async findOrCreateCompose(name, projectId, environmentId, composeFile) {
1495
+ const existing = await this.findComposeByName(projectId, name);
1496
+ const compose = existing ?? await this.post("compose.create", {
1497
+ name,
1498
+ environmentId,
1499
+ composeType: "docker-compose"
1500
+ });
1501
+ await this.post("compose.update", {
1502
+ composeId: compose.composeId,
1503
+ sourceType: "raw",
1504
+ composeFile
1505
+ });
1506
+ return {
1507
+ compose,
1508
+ created: !existing
1509
+ };
1510
+ }
1511
+ async deployCompose(composeId) {
1512
+ await this.post("compose.deploy", { composeId });
1513
+ }
1514
+ async deleteCompose(composeId) {
1515
+ await this.post("compose.delete", {
1516
+ composeId,
1517
+ deleteVolumes: false
1518
+ });
1519
+ }
1520
+ /**
1521
+ * List all Redis instances in a project
1522
+ */
1523
+ async listRedis(projectId) {
1524
+ return this.listInProject(projectId, (env) => env.redis);
1525
+ }
1526
+ /**
1527
+ * Find a Redis instance by name in a project
1528
+ */
1529
+ async findRedisByName(projectId, name) {
1530
+ const instances = await this.listRedis(projectId);
1531
+ const normalizedName = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
1532
+ const match = instances.find((redis) => redis.name === name || redis.appName === normalizedName);
1533
+ return match ? this.getRedis(match.redisId) : void 0;
1534
+ }
1535
+ /**
1536
+ * Create a new Redis instance
1537
+ */
1538
+ async createRedis(name, projectId, environmentId, options) {
1539
+ return this.post("redis.create", {
1540
+ name,
1541
+ projectId,
1542
+ environmentId,
1543
+ appName: options?.appName ?? name.toLowerCase().replace(/[^a-z0-9-]/g, "-"),
1544
+ databasePassword: options?.databasePassword,
1545
+ dockerImage: options?.dockerImage ?? "redis:8",
1546
+ description: options?.description ?? `Redis instance for ${name}`
1547
+ });
1548
+ }
1549
+ /**
1550
+ * Find or create a Redis instance by name
1551
+ */
1552
+ async findOrCreateRedis(name, projectId, environmentId, options) {
1553
+ const existing = await this.findRedisByName(projectId, name);
1554
+ if (existing) return {
1555
+ redis: existing,
1556
+ created: false
1557
+ };
1558
+ return {
1559
+ redis: await this.createRedis(name, projectId, environmentId, options),
1560
+ created: true
1561
+ };
1562
+ }
1563
+ /**
1564
+ * Get a Redis instance by ID
1565
+ */
1566
+ async getRedis(redisId) {
1567
+ return this.get(`redis.one?redisId=${redisId}`);
1568
+ }
1569
+ /**
1570
+ * Deploy a Redis instance
1571
+ */
1572
+ async deployRedis(redisId) {
1573
+ await this.post("redis.deploy", { redisId });
1574
+ }
1575
+ /**
1576
+ * Save environment variables for Redis
1577
+ */
1578
+ async saveRedisEnv(redisId, env) {
1579
+ await this.post("redis.saveEnvironment", {
1580
+ redisId,
1581
+ env
1582
+ });
1583
+ }
1584
+ /**
1585
+ * Set external port for Redis (for external access)
1586
+ */
1587
+ async saveRedisExternalPort(redisId, externalPort) {
1588
+ await this.post("redis.saveExternalPort", {
1589
+ redisId,
1590
+ externalPort
1591
+ });
1592
+ }
1593
+ /**
1594
+ * Update Redis configuration
1595
+ */
1596
+ async updateRedis(redisId, updates) {
1597
+ await this.post("redis.update", {
1598
+ redisId,
1599
+ ...updates
1600
+ });
1601
+ }
1602
+ /**
1603
+ * Delete a Redis instance
1604
+ */
1605
+ async deleteRedis(redisId) {
1606
+ await this.post("redis.remove", { redisId });
1607
+ }
1608
+ /**
1609
+ * Create a new domain for an application
1610
+ */
1611
+ async createDomain(options) {
1612
+ return this.post("domain.create", options);
1613
+ }
1614
+ /**
1615
+ * Update an existing domain
1616
+ */
1617
+ async updateDomain(domainId, updates) {
1618
+ await this.post("domain.update", {
1619
+ domainId,
1620
+ ...updates
1621
+ });
1622
+ }
1623
+ /**
1624
+ * Delete a domain
1625
+ */
1626
+ async deleteDomain(domainId) {
1627
+ await this.post("domain.delete", { domainId });
1628
+ }
1629
+ /**
1630
+ * Get a domain by ID
1631
+ */
1632
+ async getDomain(domainId) {
1633
+ return this.get(`domain.one?domainId=${domainId}`);
1634
+ }
1635
+ /**
1636
+ * Get all domains for an application
1637
+ */
1638
+ async getDomainsByApplicationId(applicationId) {
1639
+ return this.get(`domain.byApplicationId?applicationId=${applicationId}`);
1640
+ }
1641
+ /**
1642
+ * Validate a domain and trigger SSL certificate generation
1643
+ *
1644
+ * This should be called after DNS records are created and propagated.
1645
+ * It triggers Let's Encrypt certificate generation for HTTPS domains.
1646
+ *
1647
+ * @param domain - The domain hostname to validate (e.g., 'api.example.com')
1648
+ */
1649
+ async validateDomain(domain) {
1650
+ return this.post("domain.validateDomain", { domain });
1651
+ }
1652
+ /**
1653
+ * Auto-generate a domain name for an application
1654
+ */
1655
+ async generateDomain(appName, serverId) {
1656
+ return this.post("domain.generateDomain", {
1657
+ appName,
1658
+ serverId
1659
+ });
1660
+ }
1661
+ /**
1662
+ * List all backup destinations
1663
+ */
1664
+ async listDestinations() {
1665
+ return this.get("destination.all");
1666
+ }
1667
+ /**
1668
+ * Get a destination by ID
1669
+ */
1670
+ async getDestination(destinationId) {
1671
+ return this.get(`destination.one?destinationId=${destinationId}`);
1672
+ }
1673
+ /**
1674
+ * Create a new S3 backup destination
1675
+ */
1676
+ async createDestination(options) {
1677
+ return this.post("destination.create", { ...options });
1678
+ }
1679
+ /**
1680
+ * Find a destination by name
1681
+ */
1682
+ async findDestinationByName(name) {
1683
+ return (await this.listDestinations()).find((d) => d.name === name);
1684
+ }
1685
+ /**
1686
+ * Find or create a destination by name
1687
+ */
1688
+ async findOrCreateDestination(name, options) {
1689
+ const existing = await this.findDestinationByName(name);
1690
+ if (existing) return {
1691
+ destination: existing,
1692
+ created: false
1693
+ };
1694
+ return {
1695
+ destination: await this.createDestination({
1696
+ name,
1697
+ ...options
1698
+ }),
1699
+ created: true
1700
+ };
1701
+ }
1702
+ /**
1703
+ * Update a destination
1704
+ */
1705
+ async updateDestination(destinationId, updates) {
1706
+ await this.post("destination.update", {
1707
+ destinationId,
1708
+ ...updates
1709
+ });
1710
+ }
1711
+ /**
1712
+ * Delete a destination
1713
+ */
1714
+ async deleteDestination(destinationId) {
1715
+ await this.post("destination.remove", { destinationId });
1716
+ }
1717
+ /**
1718
+ * Test connection to a destination
1719
+ */
1720
+ async testDestinationConnection(destinationId) {
1721
+ return this.post("destination.testConnection", { destinationId });
1722
+ }
1723
+ /**
1724
+ * Create a backup schedule for postgres
1725
+ */
1726
+ async createPostgresBackup(options) {
1727
+ return this.post("backup.create", {
1728
+ ...options,
1729
+ databaseType: "postgres"
1730
+ });
1731
+ }
1732
+ /**
1733
+ * List backups for a postgres database
1734
+ */
1735
+ async listPostgresBackups(postgresId) {
1736
+ return this.get(`backup.all?postgresId=${postgresId}&databaseType=postgres`);
1737
+ }
1738
+ /**
1739
+ * Get a backup by ID
1740
+ */
1741
+ async getBackup(backupId) {
1742
+ return this.get(`backup.one?backupId=${backupId}`);
1743
+ }
1744
+ /**
1745
+ * Update a backup schedule
1746
+ */
1747
+ async updateBackup(backupId, updates) {
1748
+ await this.post("backup.update", {
1749
+ backupId,
1750
+ ...updates
1751
+ });
1752
+ }
1753
+ /**
1754
+ * Delete a backup schedule
1755
+ */
1756
+ async deleteBackup(backupId) {
1757
+ await this.post("backup.remove", { backupId });
1758
+ }
1759
+ /**
1760
+ * Trigger a manual backup run
1761
+ */
1762
+ async runBackupManually(backupId) {
1763
+ await this.post("backup.manualBackup", { backupId });
1764
+ }
1765
+ };
1766
+ //#endregion
1767
+ //#region src/deploy/sniffer.ts
1768
+ const __filename = fileURLToPath(import.meta.url);
1769
+ const __dirname = dirname(__filename);
1770
+ /**
1771
+ * Resolve the path to a sniffer helper file.
1772
+ * Handles both dev (.ts with tsx) and production (.mjs from dist).
1773
+ *
1774
+ * In production: sniffer.ts is bundled into dist/index.mjs, but sniffer helper
1775
+ * files are output to dist/deploy/ as standalone modules for subprocess loading.
1776
+ *
1777
+ * In development: All files are in src/deploy/ and loaded via tsx.
1778
+ */
1779
+ function resolveSnifferFile(baseName) {
1780
+ const deployMjsPath = resolve(__dirname, "deploy", `${baseName}.mjs`);
1781
+ if (existsSync(deployMjsPath)) return deployMjsPath;
1782
+ const mjsPath = resolve(__dirname, `${baseName}.mjs`);
1783
+ if (existsSync(mjsPath)) return mjsPath;
1784
+ const tsPath = resolve(__dirname, `${baseName}.ts`);
1785
+ if (existsSync(tsPath)) return tsPath;
1786
+ return tsPath;
1787
+ }
1788
+ /**
1789
+ * Run a sniffer worker in the sandbox, with the sandbox's environment and
1790
+ * nothing of the deploy's: the deploy's Dokploy token, registry login and AWS
1791
+ * keys stay where they are. A worker that outlives the timeout is killed, and
1792
+ * comes back as the error the caller reports.
1793
+ */
1794
+ async function runSniffer(run, workspacePath, cwd, nodeArgs) {
1795
+ const sandbox = run.sandbox ?? activeSandbox() ?? new LocalSandbox({ root: resolve(workspacePath) });
1796
+ try {
1797
+ const result = await sandbox.exec("node", nodeArgs, {
1798
+ cwd,
1799
+ env: { ...sandbox.env },
1800
+ timeoutMs: run.timeoutMs ?? 3e4,
1801
+ output: "capture"
1802
+ });
1803
+ return {
1804
+ stdout: result.stdout,
1805
+ stderr: result.stderr,
1806
+ code: result.exitCode
1807
+ };
1808
+ } catch (error) {
1809
+ return { error: error instanceof Error ? error : new Error(String(error)) };
1810
+ }
1811
+ }
1812
+ /** The worker's JSON answer: the last object on stdout naming `envVars`. */
1813
+ function snifferAnswer(stdout) {
1814
+ try {
1815
+ const jsonMatch = stdout.match(/\{[^{}]*"envVars"[^{}]*\}[^{]*$/);
1816
+ return jsonMatch ? JSON.parse(jsonMatch[0]) : void 0;
1817
+ } catch {
1818
+ return;
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Get required environment variables for an app.
1823
+ *
1824
+ * Detection strategy (in order):
1825
+ * 1. Frontend apps: Returns empty (no server secrets)
1826
+ * 2. Apps with `requiredEnv`: Uses explicit list from config
1827
+ * 3. Entry apps: Imports entry file in subprocess to capture config.parse() calls
1828
+ * 4. Route-based apps: Loads route files and calls getEnvironment() on each construct
1829
+ * 5. Apps with `envParser` (no routes): Runs SnifferEnvironmentParser to detect usage
1830
+ * 6. Apps with neither: Returns empty
1831
+ *
1832
+ * This function handles "fire and forget" async operations gracefully,
1833
+ * capturing errors and unhandled rejections without failing the build.
1834
+ *
1835
+ * @param app - The normalized app configuration
1836
+ * @param appName - The name of the app
1837
+ * @param workspacePath - Absolute path to the workspace root
1838
+ * @param options - Optional configuration for sniffing behavior
1839
+ * @returns The sniffed environment with required variables
1840
+ */
1841
+ async function sniffAppEnvironment(app, appName, workspacePath, options = {}) {
1842
+ const { logWarnings = true, markOptional = false } = options;
1843
+ const run = {
1844
+ ...options.sandbox ? { sandbox: options.sandbox } : {},
1845
+ ...options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}
1846
+ };
1847
+ if (app.type === "web" || app.type === "mobile") {
1848
+ const publicPrefix = getPublicEnvPrefix(app.framework);
1849
+ const depVars = publicPrefix ? (app.dependencies ?? []).map((dep) => `${publicPrefix}${dep.toUpperCase()}_URL`) : [];
1850
+ if (app.config) {
1851
+ const sniffedVars = [];
1852
+ const sniffedOptional = [];
1853
+ const configPaths = [];
1854
+ if (app.config.client) configPaths.push(app.config.client);
1855
+ if (app.config.server) configPaths.push(app.config.server);
1856
+ for (const configPath of configPaths) {
1857
+ const result = await sniffEntryFile(configPath, app.path, workspacePath, run);
1858
+ if (logWarnings && result.error) output.warn(`[sniffer] ${appName}: Config file "${configPath}" threw error during sniffing (env vars still captured): ${result.error.message}`);
1859
+ sniffedVars.push(...result.envVars);
1860
+ sniffedOptional.push(...result.optionalEnvVars);
1861
+ }
1862
+ const optionalEnvVars = [...new Set(sniffedOptional)];
1863
+ return {
1864
+ appName,
1865
+ requiredEnvVars: applyMarkOptional([.../* @__PURE__ */ new Set([...depVars, ...sniffedVars])], optionalEnvVars, markOptional),
1866
+ optionalEnvVars
1867
+ };
1868
+ }
1869
+ return {
1870
+ appName,
1871
+ requiredEnvVars: depVars,
1872
+ optionalEnvVars: []
1873
+ };
1874
+ }
1875
+ if (app.entry) {
1876
+ const result = await sniffEntryFile(app.entry, app.path, workspacePath, run);
1877
+ if (logWarnings && result.error) output.warn(`[sniffer] ${appName}: Entry file threw error during sniffing (env vars still captured): ${result.error.message}`);
1878
+ return {
1879
+ appName,
1880
+ requiredEnvVars: applyMarkOptional(result.envVars, result.optionalEnvVars, markOptional),
1881
+ optionalEnvVars: result.optionalEnvVars
1882
+ };
1883
+ }
1884
+ if (app.routes) {
1885
+ const result = await sniffRouteFiles(normalizeRoutes(app.routes), app.path, workspacePath, run);
1886
+ if (logWarnings && result.error) output.warn(`[sniffer] ${appName}: Route sniffing threw error (env vars still captured): ${result.error.message}`);
1887
+ return {
1888
+ appName,
1889
+ requiredEnvVars: applyMarkOptional(result.envVars, result.optionalEnvVars, markOptional),
1890
+ optionalEnvVars: result.optionalEnvVars
1891
+ };
1892
+ }
1893
+ if (app.envParser) {
1894
+ const result = await sniffEnvParser(app.envParser, app.path, workspacePath, run);
1895
+ if (logWarnings) {
1896
+ if (result.error) output.warn(`[sniffer] ${appName}: envParser threw error during sniffing (env vars still captured): ${result.error.message}`);
1897
+ if (result.unhandledRejections.length > 0) output.warn(`[sniffer] ${appName}: Fire-and-forget rejections during sniffing (suppressed): ${result.unhandledRejections.map((e) => e.message).join(", ")}`);
1898
+ }
1899
+ return {
1900
+ appName,
1901
+ requiredEnvVars: applyMarkOptional(result.envVars, result.optionalEnvVars, markOptional),
1902
+ optionalEnvVars: result.optionalEnvVars
1903
+ };
1904
+ }
1905
+ return {
1906
+ appName,
1907
+ requiredEnvVars: [],
1908
+ optionalEnvVars: []
1909
+ };
1910
+ }
1911
+ /**
1912
+ * Apply the `?` suffix to optional variables in an env var list.
1913
+ * Only modifies the list when `markOptional` is true and there are optional vars.
1914
+ */
1915
+ function applyMarkOptional(envVars, optionalEnvVars, markOptional) {
1916
+ if (!markOptional || optionalEnvVars.length === 0) return envVars;
1917
+ const optionalSet = new Set(optionalEnvVars);
1918
+ return envVars.map((v) => optionalSet.has(v) ? `${v}?` : v);
1919
+ }
1920
+ /**
1921
+ * Sniff an entry file by importing it in a subprocess.
1922
+ *
1923
+ * Entry apps call `config.parse()` at module load time. To capture which
1924
+ * env vars are accessed, we:
1925
+ * 1. Spawn a subprocess with a module loader hook
1926
+ * 2. The loader intercepts `@geekmidas/envkit` and replaces EnvironmentParser
1927
+ * with SnifferEnvironmentParser
1928
+ * 3. Import the entry file (triggers config.parse())
1929
+ * 4. Capture and return the accessed env var names
1930
+ *
1931
+ * This approach provides process isolation - each app is sniffed in its own
1932
+ * subprocess, preventing module cache pollution.
1933
+ *
1934
+ * @param entryPath - Relative path to the entry file (e.g., './src/index.ts')
1935
+ * @param appPath - The app's path relative to workspace (e.g., 'apps/auth')
1936
+ * @param workspacePath - Absolute path to workspace root
1937
+ * @returns EntrySniffResult with env vars and optional error
1938
+ */
1939
+ async function sniffEntryFile(entryPath, appPath, workspacePath, run = {}) {
1940
+ const fullEntryPath = resolve(workspacePath, appPath, entryPath);
1941
+ const loaderPath = resolveSnifferFile("sniffer-loader");
1942
+ const workerPath = resolveSnifferFile("sniffer-worker");
1943
+ const ran = await runSniffer(run, workspacePath, resolve(workspacePath, appPath), nodeWithTsx(workerPath, [fullEntryPath], [loaderPath]));
1944
+ if ("error" in ran) return {
1945
+ envVars: [],
1946
+ optionalEnvVars: [],
1947
+ error: ran.error
1948
+ };
1949
+ const answer = snifferAnswer(ran.stdout);
1950
+ if (answer) return {
1951
+ envVars: answer.envVars || [],
1952
+ optionalEnvVars: answer.optionalEnvVars || [],
1953
+ error: answer.error ? new Error(answer.error) : void 0
1954
+ };
1955
+ return {
1956
+ envVars: [],
1957
+ optionalEnvVars: [],
1958
+ error: /* @__PURE__ */ new Error(`Failed to sniff entry file (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
1959
+ };
1960
+ }
1961
+ /**
1962
+ * Sniff route files by loading constructs and calling getEnvironment().
1963
+ *
1964
+ * Route-based apps have endpoints, functions, crons, and subscribers that
1965
+ * use services. Each service's register() method accesses environment variables.
1966
+ *
1967
+ * This runs in a subprocess with tsx loader to properly handle TypeScript
1968
+ * compilation and path alias resolution (e.g., `src/...` imports).
1969
+ *
1970
+ * @param routes - Glob pattern(s) for route files
1971
+ * @param appPath - The app's path relative to workspace (e.g., 'apps/api')
1972
+ * @param workspacePath - Absolute path to workspace root
1973
+ * @returns EntrySniffResult with env vars and optional error
1974
+ */
1975
+ async function sniffRouteFiles(routes, appPath, workspacePath, run = {}) {
1976
+ const fullAppPath = resolve(workspacePath, appPath);
1977
+ const workerPath = resolveSnifferFile("sniffer-routes-worker");
1978
+ const pattern = (Array.isArray(routes) ? routes : [routes])[0];
1979
+ if (!pattern) return {
1980
+ envVars: [],
1981
+ optionalEnvVars: [],
1982
+ error: /* @__PURE__ */ new Error("No route patterns provided")
1983
+ };
1984
+ const ran = await runSniffer(run, workspacePath, fullAppPath, nodeWithTsx(workerPath, [fullAppPath, pattern]));
1985
+ if ("error" in ran) return {
1986
+ envVars: [],
1987
+ optionalEnvVars: [],
1988
+ error: ran.error
1989
+ };
1990
+ if (ran.stderr) ran.stderr.split("\n").filter((line) => line.trim()).forEach((line) => output.warn(line));
1991
+ const answer = snifferAnswer(ran.stdout);
1992
+ if (answer) return {
1993
+ envVars: answer.envVars || [],
1994
+ optionalEnvVars: answer.optionalEnvVars || [],
1995
+ error: answer.error ? new Error(answer.error) : void 0
1996
+ };
1997
+ return {
1998
+ envVars: [],
1999
+ optionalEnvVars: [],
2000
+ error: /* @__PURE__ */ new Error(`Failed to sniff route files (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
2001
+ };
2002
+ }
2003
+ /**
2004
+ * Run the SnifferEnvironmentParser on an envParser module to detect
2005
+ * which environment variables it accesses.
2006
+ *
2007
+ * In a subprocess, like the entry and route sniffers: the module is the
2008
+ * project's code, and it was imported into the deploy itself before — with
2009
+ * every credential the deploy held in reach. Fire-and-forget rejections are
2010
+ * collected there with the shared `sniffWithFireAndForget`.
2011
+ *
2012
+ * @param envParserPath - The envParser config (e.g., './src/config/env#envParser')
2013
+ * @param appPath - The app's path relative to workspace
2014
+ * @param workspacePath - Absolute path to workspace root
2015
+ * @returns SniffResult with env vars and any errors encountered
2016
+ */
2017
+ async function sniffEnvParser(envParserPath, appPath, workspacePath, run = {}) {
2018
+ const [modulePath, exportName = "default"] = envParserPath.split("#");
2019
+ if (!modulePath) return {
2020
+ envVars: [],
2021
+ optionalEnvVars: [],
2022
+ unhandledRejections: []
2023
+ };
2024
+ const appRoot = resolve(workspacePath, appPath);
2025
+ const fullPath = resolve(appRoot, modulePath);
2026
+ const workerPath = resolveSnifferFile("sniffer-envparser-worker");
2027
+ const ran = await runSniffer(run, workspacePath, appRoot, nodeWithTsx(workerPath, [fullPath, exportName]));
2028
+ if ("error" in ran) return {
2029
+ envVars: [],
2030
+ optionalEnvVars: [],
2031
+ unhandledRejections: [],
2032
+ error: ran.error
2033
+ };
2034
+ const answer = snifferAnswer(ran.stdout);
2035
+ if (!answer) return {
2036
+ envVars: [],
2037
+ optionalEnvVars: [],
2038
+ unhandledRejections: [],
2039
+ error: /* @__PURE__ */ new Error(`Failed to sniff envParser (exit code ${ran.code}): ${ran.stderr || ran.stdout || "No output"}`)
2040
+ };
2041
+ for (const warning of answer.warnings ?? []) output.warn(warning);
2042
+ return {
2043
+ envVars: answer.envVars ?? [],
2044
+ optionalEnvVars: answer.optionalEnvVars ?? [],
2045
+ unhandledRejections: (answer.unhandledRejections ?? []).map((message) => new Error(message)),
2046
+ ...answer.error ? { error: new Error(answer.error) } : {}
2047
+ };
2048
+ }
2049
+ /**
2050
+ * Sniff environment requirements for multiple apps.
2051
+ *
2052
+ * @param apps - Map of app name to app config
2053
+ * @param workspacePath - Absolute path to workspace root
2054
+ * @param options - Optional configuration for sniffing behavior
2055
+ * @returns Map of app name to sniffed environment
2056
+ */
2057
+ async function sniffAllApps(apps, workspacePath, options = {}) {
2058
+ const results = /* @__PURE__ */ new Map();
2059
+ for (const [appName, app] of Object.entries(apps)) {
2060
+ const sniffed = await sniffAppEnvironment(app, appName, workspacePath, options);
2061
+ results.set(appName, sniffed);
2062
+ }
2063
+ return results;
2064
+ }
2065
+ //#endregion
2066
+ export { loginCommand as C, canPrompt as D, whoamiCommand as E, prompt as O, keyFingerprint as S, validateDokployToken as T, newLockHolder as _, NoDeployableApps as a, encryptSecrets as b, runDeploy as c, StateLocked as d, StateStoreBusy as f, createStateStore as g, contentVersion as h, DokployApiError as i, DocumentStateStore as l, StateVersionConflict as m, sniffAppEnvironment as n, RollbackFailed as o, StateStoreWithoutLocking as p, DokployApi as r, UnknownDeployApps as s, sniffAllApps as t, StageStateMissing as u, eventError as v, logoutCommand as w, encryption_exports as x, Redactor as y };
2067
+
2068
+ //# sourceMappingURL=sniffer-BZ-OJO4Y.mjs.map