@geekmidas/cli 10.0.0-alpha.59 → 10.0.0-alpha.60

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 (150) hide show
  1. package/README.md +18 -1
  2. package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-BTZd2u0f.cjs} +3 -3
  3. package/dist/{HostingerProvider-BZFGYYVA.cjs.map → HostingerProvider-BTZd2u0f.cjs.map} +1 -1
  4. package/dist/{HostingerProvider-YQY3rMpV.mjs → HostingerProvider-DgzKa_Tj.mjs} +2 -2
  5. package/dist/{HostingerProvider-YQY3rMpV.mjs.map → HostingerProvider-DgzKa_Tj.mjs.map} +1 -1
  6. package/dist/{LegacyStateStore-CB4ch3Dl.mjs → LegacyStateStore-CToa2hga.mjs} +2 -2
  7. package/dist/{LegacyStateStore-CB4ch3Dl.mjs.map → LegacyStateStore-CToa2hga.mjs.map} +1 -1
  8. package/dist/{LegacyStateStore-CQJqvmXw.cjs → LegacyStateStore-CidlPT0N.cjs} +7 -7
  9. package/dist/{LegacyStateStore-CQJqvmXw.cjs.map → LegacyStateStore-CidlPT0N.cjs.map} +1 -1
  10. package/dist/LocalStateStore-BFLiOocU.mjs +165 -0
  11. package/dist/LocalStateStore-BFLiOocU.mjs.map +1 -0
  12. package/dist/LocalStateStore-Dpuqka1N.cjs +176 -0
  13. package/dist/LocalStateStore-Dpuqka1N.cjs.map +1 -0
  14. package/dist/{OpenApiTsGenerator-BCWPRZwD.cjs → OpenApiTsGenerator-BTuUumsV.cjs} +3 -3
  15. package/dist/{OpenApiTsGenerator-BCWPRZwD.cjs.map → OpenApiTsGenerator-BTuUumsV.cjs.map} +1 -1
  16. package/dist/{OpenApiTsGenerator-BRWD1Wit.mjs → OpenApiTsGenerator-CvVr1Ilz.mjs} +3 -3
  17. package/dist/{OpenApiTsGenerator-BRWD1Wit.mjs.map → OpenApiTsGenerator-CvVr1Ilz.mjs.map} +1 -1
  18. package/dist/{S3StateStore-CXTenDTW.mjs → S3StateStore-aaGkjcxO.mjs} +2 -2
  19. package/dist/{S3StateStore-CXTenDTW.mjs.map → S3StateStore-aaGkjcxO.mjs.map} +1 -1
  20. package/dist/{S3StateStore-DLS4rEc0.cjs → S3StateStore-cnm813Xn.cjs} +5 -5
  21. package/dist/{S3StateStore-DLS4rEc0.cjs.map → S3StateStore-cnm813Xn.cjs.map} +1 -1
  22. package/dist/{SSMStateStore-hnP5deFJ.mjs → SSMStateStore-BllaJKGo.mjs} +2 -2
  23. package/dist/{SSMStateStore-hnP5deFJ.mjs.map → SSMStateStore-BllaJKGo.mjs.map} +1 -1
  24. package/dist/{SSMStateStore-EqsTBIOs.cjs → SSMStateStore-DwaGprVX.cjs} +9 -9
  25. package/dist/{SSMStateStore-EqsTBIOs.cjs.map → SSMStateStore-DwaGprVX.cjs.map} +1 -1
  26. package/dist/appPorts-C9z9Pzn9.mjs +223 -0
  27. package/dist/appPorts-C9z9Pzn9.mjs.map +1 -0
  28. package/dist/appPorts-Cu79hJF6.cjs +264 -0
  29. package/dist/appPorts-Cu79hJF6.cjs.map +1 -0
  30. package/dist/{bundler-By6_sXiL.cjs → bundler-CzXZPSBJ.cjs} +4 -4
  31. package/dist/{bundler-By6_sXiL.cjs.map → bundler-CzXZPSBJ.cjs.map} +1 -1
  32. package/dist/{bundler-ouDdNvk9.mjs → bundler-DJVR4QlW.mjs} +4 -4
  33. package/dist/{bundler-ouDdNvk9.mjs.map → bundler-DJVR4QlW.mjs.map} +1 -1
  34. package/dist/cli-D_qTl20Z.cjs +69 -0
  35. package/dist/cli-D_qTl20Z.cjs.map +1 -0
  36. package/dist/cli-DzR1hpum.mjs +69 -0
  37. package/dist/cli-DzR1hpum.mjs.map +1 -0
  38. package/dist/{config-EuzFEkcH.mjs → config-C5-EEdmr.mjs} +4 -4
  39. package/dist/config-C5-EEdmr.mjs.map +1 -0
  40. package/dist/{config-WMOB9bLL.cjs → config-DXnkCEq0.cjs} +4 -4
  41. package/dist/config-DXnkCEq0.cjs.map +1 -0
  42. package/dist/config.cjs +1 -1
  43. package/dist/config.d.cts +2 -2
  44. package/dist/config.d.cts.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.d.mts.map +1 -1
  47. package/dist/config.mjs +1 -1
  48. package/dist/deploy/public.cjs +22 -0
  49. package/dist/deploy/public.d.cts +459 -0
  50. package/dist/deploy/public.d.cts.map +1 -0
  51. package/dist/deploy/public.d.mts +459 -0
  52. package/dist/deploy/public.d.mts.map +1 -0
  53. package/dist/deploy/public.mjs +5 -0
  54. package/dist/deploy/sniffer-hooks.cjs +1 -1
  55. package/dist/deploy/sniffer-hooks.mjs +1 -1
  56. package/dist/deploy/sniffer-loader.cjs +1 -1
  57. package/dist/deploy/sniffer-loader.mjs +1 -1
  58. package/dist/deploy-0fBVeWO-.cjs +3518 -0
  59. package/dist/deploy-0fBVeWO-.cjs.map +1 -0
  60. package/dist/deploy-D6Q09OkA.mjs +3429 -0
  61. package/dist/deploy-D6Q09OkA.mjs.map +1 -0
  62. package/dist/{discover-DXNviAh-.cjs → discover-Bc-4eA_p.cjs} +55 -3
  63. package/dist/discover-Bc-4eA_p.cjs.map +1 -0
  64. package/dist/{discover-Cf2jAcgF.mjs → discover-FrYvzkeC.mjs} +44 -4
  65. package/dist/discover-FrYvzkeC.mjs.map +1 -0
  66. package/dist/{encryption-BP8zfxEJ.cjs → encryption-CML4UaPi.cjs} +5 -5
  67. package/dist/{encryption-BP8zfxEJ.cjs.map → encryption-CML4UaPi.cjs.map} +1 -1
  68. package/dist/{encryption-BW7Gh51G.mjs → encryption-aDA2AzVx.mjs} +4 -4
  69. package/dist/{encryption-BW7Gh51G.mjs.map → encryption-aDA2AzVx.mjs.map} +1 -1
  70. package/dist/fakes-C9RiT6XG.mjs +125 -0
  71. package/dist/fakes-C9RiT6XG.mjs.map +1 -0
  72. package/dist/fakes-zW-jNAbQ.cjs +148 -0
  73. package/dist/fakes-zW-jNAbQ.cjs.map +1 -0
  74. package/dist/{github-DHpDMBT7.cjs → github-Cq57poPj.cjs} +7 -7
  75. package/dist/github-Cq57poPj.cjs.map +1 -0
  76. package/dist/{github-T_6sK3Rz.mjs → github-DmCj2u95.mjs} +7 -7
  77. package/dist/github-DmCj2u95.mjs.map +1 -0
  78. package/dist/home-DOzBaWaL.cjs +33 -0
  79. package/dist/home-DOzBaWaL.cjs.map +1 -0
  80. package/dist/home-GI7pJl1M.mjs +22 -0
  81. package/dist/home-GI7pJl1M.mjs.map +1 -0
  82. package/dist/{index-DV6j4Ydq.d.cts → index-Da1-oa9W.d.mts} +2 -2
  83. package/dist/{index-B5TJ-mB6.d.mts.map → index-Da1-oa9W.d.mts.map} +1 -1
  84. package/dist/{index-B5TJ-mB6.d.mts → index-UiWCaGzU.d.cts} +2 -2
  85. package/dist/{index-DV6j4Ydq.d.cts.map → index-UiWCaGzU.d.cts.map} +1 -1
  86. package/dist/index.cjs +341 -6412
  87. package/dist/index.cjs.map +1 -1
  88. package/dist/index.mjs +289 -6335
  89. package/dist/index.mjs.map +1 -1
  90. package/dist/{migrate-CThJfVHR.cjs → migrate-BTqIflwc.cjs} +11 -11
  91. package/dist/{migrate-CThJfVHR.cjs.map → migrate-BTqIflwc.cjs.map} +1 -1
  92. package/dist/{migrate-BrFREmgQ.mjs → migrate-B_6KofUo.mjs} +6 -6
  93. package/dist/{migrate-BrFREmgQ.mjs.map → migrate-B_6KofUo.mjs.map} +1 -1
  94. package/dist/openapi.cjs +3 -3
  95. package/dist/openapi.d.cts +1 -1
  96. package/dist/openapi.d.mts +1 -1
  97. package/dist/openapi.mjs +3 -3
  98. package/dist/{ready-mR96orkJ.cjs → ready-CCLIAkwR.cjs} +7 -148
  99. package/dist/ready-CCLIAkwR.cjs.map +1 -0
  100. package/dist/{ready-DbDHneLR.mjs → ready-CIHpnUc5.mjs} +7 -124
  101. package/dist/ready-CIHpnUc5.mjs.map +1 -0
  102. package/dist/reconcile/public.cjs +1 -1
  103. package/dist/reconcile/public.d.cts +1 -1
  104. package/dist/reconcile/public.d.cts.map +1 -1
  105. package/dist/reconcile/public.d.mts +1 -1
  106. package/dist/reconcile/public.d.mts.map +1 -1
  107. package/dist/reconcile/public.mjs +1 -1
  108. package/dist/{workspace-BRZ14o-o.mjs → sniffer-BM8fpCas.mjs} +3317 -27
  109. package/dist/sniffer-BM8fpCas.mjs.map +1 -0
  110. package/dist/{workspace-Dbn07ILl.cjs → sniffer-DIv12ncU.cjs} +3616 -91
  111. package/dist/sniffer-DIv12ncU.cjs.map +1 -0
  112. package/dist/store-BS8A7NcA.mjs +415 -0
  113. package/dist/store-BS8A7NcA.mjs.map +1 -0
  114. package/dist/store-KvNQwYaB.cjs +510 -0
  115. package/dist/store-KvNQwYaB.cjs.map +1 -0
  116. package/dist/{types-CipIIm8f.d.mts → types-Bp1mVxG0.d.mts} +17 -4
  117. package/dist/types-Bp1mVxG0.d.mts.map +1 -0
  118. package/dist/{types-D9b-IYdW.d.cts → types-efNLu9xu.d.cts} +17 -4
  119. package/dist/types-efNLu9xu.d.cts.map +1 -0
  120. package/dist/vitest.cjs +2 -2
  121. package/dist/vitest.mjs +2 -2
  122. package/dist/workspace/index.d.cts +2 -2
  123. package/dist/workspace/index.d.mts +2 -2
  124. package/dist/workspace-B64Xk1Mb.cjs.map +1 -1
  125. package/dist/workspace-Bp1xVaOz.mjs.map +1 -1
  126. package/package.json +23 -13
  127. package/dist/StateStore-B4u0wx2t.cjs +0 -412
  128. package/dist/StateStore-B4u0wx2t.cjs.map +0 -1
  129. package/dist/StateStore-CYUfGYcx.mjs +0 -359
  130. package/dist/StateStore-CYUfGYcx.mjs.map +0 -1
  131. package/dist/backends-CjuCiE8h.mjs +0 -59
  132. package/dist/backends-CjuCiE8h.mjs.map +0 -1
  133. package/dist/backends-v3xDuhO0.cjs +0 -82
  134. package/dist/backends-v3xDuhO0.cjs.map +0 -1
  135. package/dist/config-EuzFEkcH.mjs.map +0 -1
  136. package/dist/config-WMOB9bLL.cjs.map +0 -1
  137. package/dist/discover-Cf2jAcgF.mjs.map +0 -1
  138. package/dist/discover-DXNviAh-.cjs.map +0 -1
  139. package/dist/github-DHpDMBT7.cjs.map +0 -1
  140. package/dist/github-T_6sK3Rz.mjs.map +0 -1
  141. package/dist/ready-DbDHneLR.mjs.map +0 -1
  142. package/dist/ready-mR96orkJ.cjs.map +0 -1
  143. package/dist/store-DQgxT_WR.cjs +0 -211
  144. package/dist/store-DQgxT_WR.cjs.map +0 -1
  145. package/dist/store-DeGATCS-.mjs +0 -182
  146. package/dist/store-DeGATCS-.mjs.map +0 -1
  147. package/dist/types-CipIIm8f.d.mts.map +0 -1
  148. package/dist/types-D9b-IYdW.d.cts.map +0 -1
  149. package/dist/workspace-BRZ14o-o.mjs.map +0 -1
  150. package/dist/workspace-Dbn07ILl.cjs.map +0 -1
@@ -0,0 +1,3518 @@
1
+ const require_sniffer = require("./sniffer-DIv12ncU.cjs");
2
+ const require_home = require("./home-DOzBaWaL.cjs");
3
+ const require_discover = require("./discover-Bc-4eA_p.cjs");
4
+ const require_config = require("./config-DXnkCEq0.cjs");
5
+ const require_workspace = require("./workspace-B64Xk1Mb.cjs");
6
+ const require_storage = require("./storage-CSGoC3bK.cjs");
7
+ const require_store = require("./store-KvNQwYaB.cjs");
8
+ let node_path = require("node:path");
9
+ let node_fs_promises = require("node:fs/promises");
10
+ let node_os = require("node:os");
11
+ let _geekmidas_manifest = require("@geekmidas/manifest");
12
+ let node_crypto = require("node:crypto");
13
+ let _geekmidas_constructs_encryption = require("@geekmidas/constructs/encryption");
14
+ let _geekmidas_db_pg_roles = require("@geekmidas/db/pg/roles");
15
+ let pg = require("pg");
16
+ let _geekmidas_cache_postgres = require("@geekmidas/cache/postgres");
17
+ let node_dns_promises = require("node:dns/promises");
18
+ //#region src/deploy/credentials.ts
19
+ /**
20
+ * How a deploy gets the credentials it acts with.
21
+ *
22
+ * `deploy()` never prompts and never reads a terminal: it asks a
23
+ * `CredentialProvider` and, when the provider has nothing, stops with
24
+ * `MissingCredential` naming what it needed and how to supply it. Whether to
25
+ * ask a person, read a vault or fail is the caller's decision — `gkm deploy`
26
+ * prompts at a terminal and stores what was typed; a CI job sets the
27
+ * environment; a host passes its own provider.
28
+ */
29
+ /** How to supply each kind, for the error that says it is missing. */
30
+ const HOW_TO_PROVIDE = {
31
+ dokploy: "Set DOKPLOY_API_TOKEN (and DOKPLOY_ENDPOINT, or deploy.dokploy.endpoint in gkm.config.ts), run `gkm login --provider dokploy`, or pass them through the deploy's CredentialProvider.",
32
+ registry: "Add the registry in Dokploy (Settings → Docker Registry) and set deploy.dokploy.registryId, set DOCKER_REGISTRY_USERNAME and DOCKER_REGISTRY_PASSWORD, or run `gkm deploy` at a terminal to be asked for them."
33
+ };
34
+ /** A deploy needed a credential, and its provider had none. */
35
+ var MissingCredential = class extends Error {
36
+ kind;
37
+ target;
38
+ howToProvide;
39
+ constructor(kind, target, howToProvide = HOW_TO_PROVIDE[kind]) {
40
+ const what = kind === "dokploy" ? `No Dokploy credentials${target ? ` for ${target}` : ""}.` : `Dokploy has no registry for ${target ?? "the configured registry"}, and there are no credentials to create one with.`;
41
+ super(`${what} ${howToProvide}`);
42
+ this.kind = kind;
43
+ this.target = target;
44
+ this.howToProvide = howToProvide;
45
+ this.name = "MissingCredential";
46
+ }
47
+ };
48
+ /** Whatever was asked for, from the first provider that has it. */
49
+ function chainCredentials(...providers) {
50
+ return { async get(request, options) {
51
+ for (const provider of providers) {
52
+ const found = await provider.get(request, options);
53
+ if (found) return found;
54
+ }
55
+ } };
56
+ }
57
+ /**
58
+ * Credentials from the environment, then from what `gkm login` stored. What
59
+ * `deploy()` uses when it is handed no provider.
60
+ *
61
+ * - Dokploy: `DOKPLOY_API_TOKEN` / `DOKPLOY_ENDPOINT`, each falling back to
62
+ * the stored login, and the endpoint finally to `deploy.dokploy.endpoint`.
63
+ * Each half is read on its own: a token is a secret and belongs in the
64
+ * environment, an endpoint is configuration and belongs in the config.
65
+ * - Registry: `DOCKER_REGISTRY_USERNAME` / `DOCKER_REGISTRY_PASSWORD`.
66
+ */
67
+ function storedCredentials(options = {}) {
68
+ const env = options.env ?? process.env;
69
+ return { async get(asked) {
70
+ const request = asked;
71
+ switch (request.kind) {
72
+ case "dokploy": {
73
+ const stored = (await require_sniffer.readCredentials(options.home ? { home: options.home } : void 0)).dokploy;
74
+ const token = env.DOKPLOY_API_TOKEN ?? stored?.token;
75
+ const endpoint = env.DOKPLOY_ENDPOINT ?? stored?.endpoint ?? request.endpoint;
76
+ if (!token || !endpoint) return void 0;
77
+ return {
78
+ endpoint: endpoint.replace(/\/$/, ""),
79
+ token
80
+ };
81
+ }
82
+ case "registry": {
83
+ const username = env.DOCKER_REGISTRY_USERNAME;
84
+ const password = env.DOCKER_REGISTRY_PASSWORD;
85
+ if (!username || !password) return void 0;
86
+ return {
87
+ username,
88
+ password
89
+ };
90
+ }
91
+ }
92
+ } };
93
+ }
94
+ //#endregion
95
+ //#region src/deploy/events.ts
96
+ /** An error as an event carries it: its name and message, nothing else. */
97
+ function eventError(error) {
98
+ if (error instanceof Error) return {
99
+ name: error.name,
100
+ message: error.message
101
+ };
102
+ return {
103
+ name: "Error",
104
+ message: String(error)
105
+ };
106
+ }
107
+ //#endregion
108
+ //#region src/deploy/fromManifest.ts
109
+ /**
110
+ * The Dokploy target, read off the construct manifest.
111
+ *
112
+ * The AWS target has done this since `fromManifest` landed: a table keyed by
113
+ * declaration kind, each entry turning one declaration into infrastructure and
114
+ * the env keys it resolves. Dokploy had no such thing — it resolved environment
115
+ * from the *sniffer*, which walks application code for `get('X')` calls, and a
116
+ * construct reads its own key inside `@geekmidas/constructs` where there is
117
+ * nothing to find. So a declared app deployed here got none of the model, and
118
+ * nothing reported the absence: the deploy succeeded and the first request that
119
+ * needed a URL failed at runtime.
120
+ *
121
+ * This is the same table, over the REST wrapper instead of over Pulumi.
122
+ *
123
+ * **Two phases, and the split is not incidental.** Creating a Postgres and
124
+ * creating a role inside it are different kinds of act: the first is an API
125
+ * call, the second needs a connection to a database that does not exist yet
126
+ * when the call is made. So provisioners *accumulate* DDL rather than running
127
+ * it, and it is applied once against a cluster that is up — which is exactly
128
+ * what `DatabaseBootstrap` does on AWS, for exactly the same reason.
129
+ *
130
+ * **The DDL itself is shared.** `roleStatements` and `cacheTableStatements` are
131
+ * the same generators the local target and the AWS target use. Dokploy used to
132
+ * write its own `DO $$` block, which meant three targets applying three
133
+ * different definitions of "the role split" and no way to notice they had
134
+ * drifted.
135
+ *
136
+ * Entries are deliberately small and free of I/O ordering: each takes what it
137
+ * needs and returns what it resolved. That is what would let a Pulumi dynamic
138
+ * provider wrap one later without the table itself changing — see §6b.
139
+ */
140
+ /**
141
+ * The internal hostname a Dokploy Postgres answers on.
142
+ *
143
+ * Its own service name on the Docker network — not the server's public address.
144
+ * An app reaching its database over the public internet would be a credential
145
+ * crossing a network that did not need to see it.
146
+ */
147
+ function clusterHost(postgres) {
148
+ return postgres.appName;
149
+ }
150
+ /**
151
+ * What a resource is called in the provider.
152
+ *
153
+ * `cloudName` and nothing else — the same scoped kebab rule the AWS target
154
+ * uses, so a name reads identically on both: `production-shop-orders`.
155
+ *
156
+ * It briefly carried a `-postgres` suffix on the theory that a Dokploy project
157
+ * is one flat list where an application and its database would collide. It is
158
+ * not: `project.one` returns typed collections — `applications`, `postgres`,
159
+ * `redis`, `compose`, `mariadb`, `mongo`, `mysql` — so the kind is already in
160
+ * the shape of the response and an application and a Postgres of the same name
161
+ * are different objects with different ids. The suffix was answering a question
162
+ * nobody had asked.
163
+ */
164
+ function serviceName(scope, id) {
165
+ return (0, _geekmidas_manifest.cloudName)(scope, id);
166
+ }
167
+ const PROVISIONERS = {
168
+ /**
169
+ * A Postgres service, plus the roles that reach it.
170
+ *
171
+ * The service is `findOrCreate`, because a deploy that recreated the
172
+ * database would be a deploy that lost the data. The roles are deferred:
173
+ * they need a connection to a cluster this call has only just asked for.
174
+ */
175
+ database: async (declaration, context) => {
176
+ if (declaration.kind !== "database") throw new WrongKind(declaration.kind);
177
+ const name = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
178
+ const { postgres } = await context.api.findOrCreatePostgres(serviceName({
179
+ stage: context.stage,
180
+ app: context.scope ?? context.project
181
+ }, declaration.id), context.projectId, context.environmentId, {
182
+ databaseName: name,
183
+ databasePassword: derivedPassword(context, `${name}:master`)
184
+ });
185
+ const host = clusterHost(postgres);
186
+ context.clusters[postgres.databaseName] = postgres;
187
+ const schema = declaration.schema ?? "app";
188
+ const runtime = name;
189
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
190
+ const reads = readsFrom(context.manifest, declaration.id);
191
+ context.deferred.push(...statementsFor({
192
+ id: declaration.id,
193
+ database: postgres.databaseName,
194
+ ownsDatabase: true,
195
+ runtime,
196
+ owner,
197
+ ...reads ? { reader: (0, _geekmidas_db_pg_roles.readerRole)(runtime) } : {},
198
+ schema,
199
+ context
200
+ }));
201
+ return { provides: {
202
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(runtime, derivedPassword(context, runtime), host, postgres.databaseName),
203
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "ownerUrl")]: postgresUrl(owner, derivedPassword(context, owner), host, postgres.databaseName)
204
+ } };
205
+ },
206
+ /**
207
+ * A schema in the parent's database, with its own role and its own URL — so
208
+ * the parent's role holds no grant on these tables at all.
209
+ */
210
+ "database-schema": async (declaration, context) => {
211
+ if (declaration.kind !== "database-schema") throw new WrongKind(declaration.kind);
212
+ const parent = context.provisioned[declaration.of];
213
+ if (!parent) throw new UnresolvedParent(declaration.id, declaration.of);
214
+ const runtime = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
215
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
216
+ const reads = readsFrom(context.manifest, declaration.id);
217
+ const parentUrl = new URL(parent.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")] ?? "");
218
+ context.deferred.push(...statementsFor({
219
+ id: declaration.id,
220
+ database: parentUrl.pathname.slice(1),
221
+ runtime,
222
+ owner,
223
+ ...reads ? { reader: (0, _geekmidas_db_pg_roles.readerRole)(runtime) } : {},
224
+ schema: declaration.schema,
225
+ context
226
+ }));
227
+ return { provides: {
228
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(runtime, derivedPassword(context, runtime), parentUrl.hostname, parentUrl.pathname.slice(1)),
229
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "ownerUrl")]: postgresUrl(owner, derivedPassword(context, owner), parentUrl.hostname, parentUrl.pathname.slice(1))
230
+ } };
231
+ },
232
+ /**
233
+ * A read-only endpoint on the same cluster.
234
+ *
235
+ * Nothing is provisioned: a Dokploy Postgres has one endpoint, so this
236
+ * resolves to the writer's address — and that is safe rather than a
237
+ * loophole, because read-only is enforced by the reader role's grants and
238
+ * not by which host the URL names. The role itself was created with its
239
+ * parent.
240
+ */
241
+ "database-reader": async (declaration, context) => {
242
+ if (declaration.kind !== "database-reader") throw new WrongKind(declaration.kind);
243
+ const parent = context.provisioned[declaration.of];
244
+ if (!parent) throw new UnresolvedParent(declaration.id, declaration.of);
245
+ const parentUrl = new URL(parent.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")] ?? "");
246
+ const reader = (0, _geekmidas_db_pg_roles.readerRole)(parentUrl.username);
247
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: postgresUrl(reader, derivedPassword(context, reader), parentUrl.hostname, parentUrl.pathname.slice(1)) } };
248
+ },
249
+ /**
250
+ * A cache, wherever the project said it lives.
251
+ *
252
+ * `db` is a table in a database the manifest already declares, so it
253
+ * provisions no service and costs nothing to run — the same relationship
254
+ * pg-boss has. The table's DDL is deferred with the roles, and the table
255
+ * name travels in the URL because two caches in one database resolve the
256
+ * same connection string.
257
+ */
258
+ cache: async (declaration, context) => {
259
+ if (declaration.kind !== "cache") throw new WrongKind(declaration.kind);
260
+ const parentId = declaration.of ?? (context.cache === "db" ? soleDatabase(context) : void 0);
261
+ if (!parentId) throw new CacheNeedsAHome(declaration.id, context.cache);
262
+ const parent = context.provisioned[parentId];
263
+ if (!parent) throw new UnresolvedParent(declaration.id, parentId);
264
+ const parentUrl = parent.provides[(0, _geekmidas_manifest.provideKey)(parentId, "url")];
265
+ if (!parentUrl) throw new UnresolvedParent(declaration.id, parentId);
266
+ const table = declaration.table ?? (0, _geekmidas_manifest.cacheTable)(declaration.id);
267
+ const schema = schemaOf(context.manifest, parentId);
268
+ const qualified = schema ? `${schema}.${table}` : table;
269
+ context.deferred.push(...(0, _geekmidas_cache_postgres.cacheTableStatements)({ table: qualified }).map((statement) => ({
270
+ id: declaration.id,
271
+ database: new URL(parentUrl).pathname.slice(1),
272
+ describe: statement.describe,
273
+ sql: statement.sql,
274
+ ...statement.exists ? { exists: statement.exists } : {}
275
+ })), {
276
+ id: declaration.id,
277
+ database: new URL(parentUrl).pathname.slice(1),
278
+ describe: `${qualified} is owned by its schema's owner`,
279
+ sql: `ALTER TABLE ${quoted(qualified)} OWNER TO ${quoted((0, _geekmidas_db_pg_roles.ownerRole)(new URL(parentUrl).username))}`
280
+ }, {
281
+ id: declaration.id,
282
+ database: new URL(parentUrl).pathname.slice(1),
283
+ describe: `${new URL(parentUrl).username} may read and write ${qualified}`,
284
+ sql: `GRANT SELECT, INSERT, UPDATE, DELETE ON ${quoted(qualified)} TO ${quoted(new URL(parentUrl).username)}`
285
+ });
286
+ const url = new URL(parentUrl);
287
+ url.searchParams.set("table", table);
288
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: url.toString() } };
289
+ },
290
+ /**
291
+ * A bucket, as a MinIO stack on the box.
292
+ *
293
+ * Dokploy has first-class primitives for Postgres and Redis and none for
294
+ * object storage, so this is the one kind whose infrastructure this target
295
+ * *writes* rather than configures — a compose file with one service in it.
296
+ *
297
+ * The service is named `cloudName(...)` like everything else, which is not
298
+ * cosmetic here: containers on `dokploy-network` resolve each other by
299
+ * service name, so the name is the address. Calling it `minio` would work
300
+ * for exactly one project on the box and then collide.
301
+ *
302
+ * `s3://` carries no credentials, deliberately — deployed on AWS the SDK
303
+ * reads them from an execution role, so a URL that embedded a key would be
304
+ * one more thing to rotate and leak. There is no role here, so the same
305
+ * chain reads `AWS_ACCESS_KEY_ID` beside the URL, exactly as it does
306
+ * locally.
307
+ */
308
+ objects: async (declaration, context) => {
309
+ if (declaration.kind !== "objects") throw new WrongKind(declaration.kind);
310
+ const backend = context.storage ?? "minio";
311
+ if (backend !== "minio") throw new UnprovisionableBucket(declaration.id, backend);
312
+ const service = serviceName({
313
+ stage: context.stage,
314
+ app: context.scope ?? context.project
315
+ }, declaration.id);
316
+ const bucket = require_sniffer.resourceName(declaration.id, declaration.kind, context.stage);
317
+ const user = `${bucket}-root`;
318
+ const password = derivedPassword(context, `objects:${declaration.id}`);
319
+ const { compose } = await context.api.findOrCreateCompose(service, context.projectId, context.environmentId, minioCompose({
320
+ service,
321
+ bucket,
322
+ user,
323
+ password
324
+ }));
325
+ await context.api.deployCompose(compose.composeId);
326
+ return { provides: {
327
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: s3Url(service, bucket),
328
+ AWS_ACCESS_KEY_ID: user,
329
+ AWS_SECRET_ACCESS_KEY: password,
330
+ AWS_REGION: MINIO_REGION
331
+ } };
332
+ },
333
+ /**
334
+ * The address a bucket's objects are served on.
335
+ *
336
+ * Nothing is provisioned: Dokploy runs Traefik, so a second reverse proxy
337
+ * behind the first would terminate TLS twice — which is why the local
338
+ * target's Caddy has no equivalent here. What this resolves is the address,
339
+ * and the `open` prefixes are applied to the bucket rather than to an edge,
340
+ * so a policy is what makes them public wherever the bucket lives.
341
+ *
342
+ * Until a Traefik rule exists it answers on MinIO directly, path-style,
343
+ * which is honest about the shape it has today: the bucket is in the path
344
+ * rather than fronted by a host of its own.
345
+ */
346
+ "file-server": async (declaration, context) => {
347
+ if (declaration.kind !== "file-server") throw new WrongKind(declaration.kind);
348
+ const parentUrl = context.provisioned[declaration.of]?.provides[(0, _geekmidas_manifest.provideKey)(declaration.of, "url")];
349
+ if (!parentUrl) throw new UnresolvedParent(declaration.id, declaration.of);
350
+ const endpoint = new URL(parentUrl).searchParams.get("endpoint");
351
+ const bucket = new URL(parentUrl).hostname;
352
+ if (!endpoint) throw new UnresolvedParent(declaration.id, declaration.of);
353
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: `${endpoint}/${bucket}` } };
354
+ },
355
+ /**
356
+ * A topic, and below it a queue — the same broker either way.
357
+ *
358
+ * Under pg-boss there is nothing to create in Dokploy: the broker is a
359
+ * schema tenant of the database the app already declared, exactly as it is
360
+ * locally, so what this resolves is an address rather than a service. Which
361
+ * is the point of putting the backend in config — the same handlers drain
362
+ * pg-boss here and SQS on AWS because the string they were handed said so.
363
+ *
364
+ * The tenant gets its own role rather than the cluster master, for the
365
+ * reason every other tenant does: pg-boss creates and owns its tables, and
366
+ * a broker that could also read the application's is a broker with a grant
367
+ * nothing asked for.
368
+ */
369
+ topic: async (declaration, context) => {
370
+ if (declaration.kind !== "topic") throw new WrongKind(declaration.kind);
371
+ return broker(declaration.id, context);
372
+ },
373
+ queue: async (declaration, context) => {
374
+ if (declaration.kind !== "queue") throw new WrongKind(declaration.kind);
375
+ return broker(declaration.id, context);
376
+ },
377
+ /**
378
+ * A signing key, generated once and remembered in the stage's store.
379
+ *
380
+ * Random, never derived: a key computed from the project and stage names
381
+ * signs sessions anyone reading the repo could forge. The deploy generates
382
+ * it before provisioning (`withGeneratedSecrets`) and every later deploy
383
+ * reads the same one, so live sessions survive a redeploy. Nothing is
384
+ * created in Dokploy: a secret has no address.
385
+ */
386
+ secret: async (declaration, context) => {
387
+ if (declaration.kind !== "secret") throw new WrongKind(declaration.kind);
388
+ const key = declaration.provides?.[0];
389
+ if (!key) return { provides: {} };
390
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
391
+ },
392
+ /**
393
+ * The keyring the stage keeps in its secrets.
394
+ *
395
+ * Generated on the first deploy (`withGeneratedSecrets`) and rotated only
396
+ * by `gkm encryption:rotate`, so a redeploy never changes a key and nothing
397
+ * written becomes unreadable. Nothing is created in Dokploy: the process
398
+ * holds the keyring.
399
+ */
400
+ encryption: async (declaration, context) => {
401
+ if (declaration.kind !== "encryption") throw new WrongKind(declaration.kind);
402
+ const key = (0, _geekmidas_manifest.provideKey)(declaration.id, "url");
403
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
404
+ },
405
+ /**
406
+ * A third party's credentials, as the stage was given them.
407
+ *
408
+ * Nothing is created and nothing derived: the value was issued by somebody
409
+ * else. A stage that was never given one fails the deploy here, naming the
410
+ * command that sets it — not the first request that needs it.
411
+ */
412
+ credential: async (declaration, context) => {
413
+ if (declaration.kind !== "credential") throw new WrongKind(declaration.kind);
414
+ const key = (0, _geekmidas_manifest.provideKey)(declaration.id, "credentials");
415
+ return { provides: { [key]: supplied(declaration.id, key, context) } };
416
+ },
417
+ /**
418
+ * An API somebody else runs: the URL this stage calls it at, and the
419
+ * credentials it was issued for this stage.
420
+ */
421
+ "external-api": async (declaration, context) => {
422
+ if (declaration.kind !== "external-api") throw new WrongKind(declaration.kind);
423
+ const credentials = (0, _geekmidas_manifest.provideKey)(declaration.id, "credentials");
424
+ return { provides: {
425
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: (0, _geekmidas_manifest.externalApiUrl)(declaration, context.stage),
426
+ [credentials]: supplied(declaration.id, credentials, context)
427
+ } };
428
+ },
429
+ /**
430
+ * A surface, at the address whatever created its domain assigned.
431
+ *
432
+ * Nothing is provisioned here: the application and its domain are the
433
+ * existing engine's, and Dokploy's own Traefik terminates TLS with a Let's
434
+ * Encrypt certificate. What this adds is the *derivation* — who may call it,
435
+ * and where a cookie it sets is readable — from the graph rather than from a
436
+ * hand-maintained list.
437
+ */
438
+ "rest-api": async (declaration, context) => {
439
+ if (declaration.kind !== "rest-api") throw new WrongKind(declaration.kind);
440
+ const url = context.addresses?.[declaration.id];
441
+ if (!url) throw new SurfaceHasNoAddress(declaration.id);
442
+ const origins = [...new Set((0, _geekmidas_manifest.dependentsOf)(context.manifest, declaration.id).map((caller) => context.addresses?.[caller]).filter((address) => Boolean(address)))].sort();
443
+ const domain = (0, _geekmidas_manifest.cookieDomain)([url, ...origins]);
444
+ const schemes = (0, _geekmidas_manifest.dependentsOf)(context.manifest, declaration.id).flatMap((caller) => {
445
+ const app = context.manifest[caller];
446
+ return app?.kind === "mobile-app" ? (0, _geekmidas_manifest.mobileOrigins)((0, _geekmidas_manifest.schemeBase)(context.project, app.scheme)) : [];
447
+ });
448
+ return { provides: {
449
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "url")]: url,
450
+ [(0, _geekmidas_manifest.provideKey)(declaration.id, "trustedOrigins")]: [...origins, ...schemes].join(","),
451
+ ...domain ? { [(0, _geekmidas_manifest.provideKey)(declaration.id, "cookieDomain")]: domain } : {}
452
+ } };
453
+ }
454
+ };
455
+ /** The provisioner for a kind, or nothing where this target has none yet. */
456
+ function provisionerFor(kind) {
457
+ return PROVISIONERS[kind];
458
+ }
459
+ /**
460
+ * The role DDL for one database or tenant, from the shared generator.
461
+ *
462
+ * The same statements the local target applies and the same ones the AWS
463
+ * bootstrap runs. Dokploy used to write its own, which is how three targets
464
+ * came to hold three definitions of the same split.
465
+ */
466
+ function statementsFor(options) {
467
+ const { id, database, runtime, owner, reader, schema, context } = options;
468
+ return (0, _geekmidas_db_pg_roles.roleStatements)({
469
+ runtime,
470
+ owner,
471
+ ...reader ? { reader } : {},
472
+ schema,
473
+ ...options.ownsDatabase ? { database } : {},
474
+ passwords: {
475
+ runtime: derivedPassword(context, runtime),
476
+ owner: derivedPassword(context, owner),
477
+ ...reader ? { reader: derivedPassword(context, reader) } : {}
478
+ }
479
+ }).map((statement) => ({
480
+ ...statement,
481
+ id,
482
+ database
483
+ }));
484
+ }
485
+ /**
486
+ * The connection string a declared queue or topic publishes on.
487
+ *
488
+ * One broker for the whole project, which is what the local target does and
489
+ * what the runtime expects: the generated pollers open a single connection and
490
+ * subscribe each worker by name on it. So every carrier resolves to the same
491
+ * address, and the DDL that backs it is pushed once however many are declared.
492
+ *
493
+ * Only pg-boss is answered here. SNS needs a topic ARN that has to exist
494
+ * first, and RabbitMQ needs a broker Dokploy has no primitive for — both are
495
+ * the §4.3 question, and composing a plausible URL for either would fail at the
496
+ * first publish instead of here.
497
+ */
498
+ function broker(id, context) {
499
+ const backend = context.events ?? "pgboss";
500
+ if (backend !== "pgboss") throw new UnprovisionableCarrier(id, backend);
501
+ const parentId = soleDatabase(context);
502
+ if (!parentId) throw new BrokerNeedsADatabase(id);
503
+ const parentUrl = context.provisioned[parentId]?.provides[(0, _geekmidas_manifest.provideKey)(parentId, "url")];
504
+ if (!parentUrl) throw new UnresolvedParent(id, parentId);
505
+ const url = new URL(parentUrl);
506
+ const database = url.pathname.slice(1);
507
+ const runtime = `${database}_${PGBOSS_SCHEMA}`;
508
+ const owner = (0, _geekmidas_db_pg_roles.ownerRole)(runtime);
509
+ if (!context.provisioned[BROKER_ID]) {
510
+ context.deferred.push(...statementsFor({
511
+ id: BROKER_ID,
512
+ database,
513
+ runtime,
514
+ owner,
515
+ schema: PGBOSS_SCHEMA,
516
+ context
517
+ }));
518
+ context.provisioned[BROKER_ID] = { provides: {} };
519
+ }
520
+ const connection = pgbossUrl(runtime, derivedPassword(context, runtime), url.host, database);
521
+ return { provides: { [(0, _geekmidas_manifest.provideKey)(id, "publisherConnectionString")]: connection } };
522
+ }
523
+ /** The schema pg-boss creates its tables in, here as locally. */
524
+ const PGBOSS_SCHEMA = "pgboss";
525
+ /**
526
+ * The id the broker's DDL is pushed under.
527
+ *
528
+ * Not a construct — no declaration names it — but the deferred statements need
529
+ * an id, and every carrier in the project shares this one.
530
+ */
531
+ const BROKER_ID = "PgBoss";
532
+ /**
533
+ * A pg-boss address: a Postgres URL under a scheme that picks the transport.
534
+ *
535
+ * The protocol is what a producer branches on, so it never branches — the same
536
+ * `.publish()` reaches pg-boss here and SQS on AWS.
537
+ */
538
+ function pgbossUrl(role, password, host, database) {
539
+ return `pgboss://${role}:${encodeURIComponent(password)}@${host}/${database}?schema=${PGBOSS_SCHEMA}`;
540
+ }
541
+ /** The region MinIO is addressed with. It has no regions; the SDK wants one. */
542
+ const MINIO_REGION = "us-east-1";
543
+ /** An `s3://` URL pointing the same S3 client at MinIO on the internal network. */
544
+ function s3Url(service, bucket) {
545
+ return `s3://${bucket}?region=${MINIO_REGION}&endpoint=http://${service}:9000&forcePathStyle=true`;
546
+ }
547
+ /**
548
+ * A one-service compose file for a bucket.
549
+ *
550
+ * `dokploy-network` is external and already exists — it is what every Dokploy
551
+ * service is attached to, and joining it is what makes the app able to resolve
552
+ * this one by name. The bucket itself is created by MinIO's entrypoint rather
553
+ * than by a second call, so there is nothing to reconcile afterwards.
554
+ */
555
+ function minioCompose(options) {
556
+ const { service, bucket, user, password } = options;
557
+ return [
558
+ "services:",
559
+ ` ${service}:`,
560
+ " image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z",
561
+ ` command: server /data --console-address ":9001"`,
562
+ " environment:",
563
+ ` MINIO_ROOT_USER: ${user}`,
564
+ ` MINIO_ROOT_PASSWORD: ${password}`,
565
+ " volumes:",
566
+ ` - ${service}-data:/data`,
567
+ " networks:",
568
+ " - dokploy-network",
569
+ " healthcheck:",
570
+ " test: [\"CMD\", \"mc\", \"ready\", \"local\"]",
571
+ " interval: 10s",
572
+ " retries: 5",
573
+ ` ${service}-bucket:`,
574
+ " image: minio/mc:latest",
575
+ " depends_on:",
576
+ ` ${service}:`,
577
+ " condition: service_healthy",
578
+ " entrypoint: >",
579
+ ` /bin/sh -c "mc alias set s3 http://${service}:9000 ${user} ${password} &&`,
580
+ ` mc mb --ignore-existing s3/${bucket}"`,
581
+ " networks:",
582
+ " - dokploy-network",
583
+ "volumes:",
584
+ ` ${service}-data:`,
585
+ "networks:",
586
+ " dokploy-network:",
587
+ " external: true",
588
+ ""
589
+ ].join("\n");
590
+ }
591
+ /** Whether anything reads through a reader on this construct. */
592
+ function readsFrom(manifest, id) {
593
+ return Object.values(manifest).some((declaration) => declaration.kind === "database-reader" && declaration.of === id);
594
+ }
595
+ /** The schema a database or tenant pins on its roles. */
596
+ function schemaOf(manifest, id) {
597
+ const declaration = manifest[id];
598
+ if (declaration?.kind === "database") return declaration.schema ?? "app";
599
+ if (declaration?.kind === "database-schema") return declaration.schema;
600
+ }
601
+ /**
602
+ * The one declared database, where `cache: 'db'` has to pick.
603
+ *
604
+ * Unambiguous with one and arbitrary with two, so two is an error rather than a
605
+ * coin toss — a cache landing in a database nobody chose surfaces as entries
606
+ * that are never found, long after the deploy reported success.
607
+ */
608
+ function soleDatabase(context) {
609
+ const databases = Object.entries(context.manifest).filter(([, declaration]) => declaration.kind === "database").map(([id]) => id);
610
+ if (databases.length > 1) throw new CacheIsAmbiguous(databases);
611
+ return databases[0];
612
+ }
613
+ /**
614
+ * A password derived from the stage's seed, the project, the stage and the role.
615
+ *
616
+ * Derived rather than stored per role so a redeploy hands the running
617
+ * application the password it already has, and two projects never share one.
618
+ * The seed is what makes it secret: random, generated once and kept in the
619
+ * stage's store. Without it the inputs are all in the repo, and so was every
620
+ * production password.
621
+ */
622
+ function derivedPassword(context, role) {
623
+ return (0, node_crypto.createHash)("sha256").update(`${context.seed}:${context.project}:${context.stage}:role:${role}`).digest("base64url").slice(0, 32);
624
+ }
625
+ /** A connection string for a role on a cluster. */
626
+ function postgresUrl(role, password, host, database) {
627
+ return `postgres://${role}:${encodeURIComponent(password)}@${host}:5432/${database}`;
628
+ }
629
+ /** Quote an identifier, per segment, for DDL that cannot be parameterised. */
630
+ function quoted(name) {
631
+ return name.split(".").map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(".");
632
+ }
633
+ /** A provisioner was handed a declaration of the wrong kind. */
634
+ /**
635
+ * A value only the stage's own secrets can hold.
636
+ *
637
+ * @throws {MissingSuppliedSecret} when the stage was never given it.
638
+ */
639
+ function supplied(id, key, context) {
640
+ const value = context.supplied?.[key];
641
+ if (value === void 0) throw new MissingSuppliedSecret(id, key, context.stage);
642
+ return value;
643
+ }
644
+ /** A construct needs a value the stage was never given. */
645
+ var MissingSuppliedSecret = class extends Error {
646
+ id;
647
+ key;
648
+ stage;
649
+ constructor(id, key, stage) {
650
+ super(`'${id}' needs ${key}, and the stage '${stage}' has none. Nothing can derive it; set it in the stage's secrets: gkm secrets:set ${key} '…' --stage ${stage}`);
651
+ this.id = id;
652
+ this.key = key;
653
+ this.stage = stage;
654
+ this.name = "MissingSuppliedSecret";
655
+ }
656
+ };
657
+ var WrongKind = class extends Error {
658
+ kind;
659
+ constructor(kind) {
660
+ super(`No Dokploy provisioner handles '${kind}'`);
661
+ this.kind = kind;
662
+ this.name = "WrongKind";
663
+ }
664
+ };
665
+ /** A derived construct whose parent has not been provisioned. */
666
+ var UnresolvedParent = class extends Error {
667
+ id;
668
+ parent;
669
+ constructor(id, parent) {
670
+ super(`'${id}' derives from '${parent}', which has not been provisioned. Provision in \`provisionOrder\`, which puts parents first.`);
671
+ this.id = id;
672
+ this.parent = parent;
673
+ this.name = "UnresolvedParent";
674
+ }
675
+ };
676
+ /** A cache with nowhere to live. */
677
+ var CacheNeedsAHome = class extends Error {
678
+ id;
679
+ backend;
680
+ constructor(id, backend) {
681
+ super(`'${id}' is a cache and nothing says where it lives. Declare it from its database — \`orders.cache('${id}')\`.` + (backend ? ` The deploy target's backend is '${backend}'.` : ""));
682
+ this.id = id;
683
+ this.backend = backend;
684
+ this.name = "CacheNeedsAHome";
685
+ }
686
+ };
687
+ /** A `'db'` cache (a server target's default) with more than one database. */
688
+ var CacheIsAmbiguous = class extends Error {
689
+ databases;
690
+ constructor(databases) {
691
+ super(`A cache backed by the database needs to know which one, and this app declares ${databases.length}: ${databases.join(", ")}. Declare the cache from its database rather than as a bare new Cache().`);
692
+ this.databases = databases;
693
+ this.name = "CacheIsAmbiguous";
694
+ }
695
+ };
696
+ /** A surface reached provisioning before its domain existed. */
697
+ var SurfaceHasNoAddress = class extends Error {
698
+ id;
699
+ constructor(id) {
700
+ super(`'${id}' is a surface and no address was supplied for it. The domain is created before the manifest is provisioned, so this means the two ran out of order.`);
701
+ this.id = id;
702
+ this.name = "SurfaceHasNoAddress";
703
+ }
704
+ };
705
+ /** A queue or topic on a backend this target has no primitive for. */
706
+ var UnprovisionableCarrier = class extends Error {
707
+ id;
708
+ backend;
709
+ constructor(id, backend) {
710
+ super(`'${id}' is carried by '${backend}', which this target cannot provision. SNS needs a topic ARN that has to exist first and RabbitMQ needs a broker Dokploy has no primitive for; pg-boss is a schema tenant of a database this app already declares, which is why it is the one that works here. Deploy this app to a target that has the backend.`);
711
+ this.id = id;
712
+ this.backend = backend;
713
+ this.name = "UnprovisionableCarrier";
714
+ }
715
+ };
716
+ /** A pg-boss carrier in an app that declares no database to host it. */
717
+ var BrokerNeedsADatabase = class extends Error {
718
+ id;
719
+ constructor(id) {
720
+ super(`'${id}' is carried by pg-boss, which lives in the database the app declares — and this app declares none. Declare a database, or deploy to a target whose broker is its own.`);
721
+ this.id = id;
722
+ this.name = "BrokerNeedsADatabase";
723
+ }
724
+ };
725
+ /** A bucket on a backend this target has no primitive for. */
726
+ var UnprovisionableBucket = class extends Error {
727
+ id;
728
+ backend;
729
+ constructor(id, backend) {
730
+ super(`'${id}' is stored on '${backend}', which this target cannot provision: an S3 or R2 bucket belongs to an account this deploy does not hold, the way an API key does. Supply the bucket's URL.`);
731
+ this.id = id;
732
+ this.backend = backend;
733
+ this.name = "UnprovisionableBucket";
734
+ }
735
+ };
736
+ //#endregion
737
+ //#region src/deploy/declared.ts
738
+ /**
739
+ * The declared half of a Dokploy deploy.
740
+ *
741
+ * `fromManifest.ts` decides what each construct resolves to; this runs it —
742
+ * discovers the manifest, walks it parents-first, and applies the DDL the
743
+ * provisioners deferred.
744
+ *
745
+ * It is deliberately separate from the engine in `index.ts`. That file deploys
746
+ * *applications*: images, registries, domains, the things a project has whether
747
+ * or not it declares anything. This is the part that exists because the app
748
+ * declared it, and keeping the two apart is what lets a project adopt the model
749
+ * without rewriting its deploy — and lets this one be tested without one.
750
+ */
751
+ /**
752
+ * Provision everything the workspace declares, and return what it resolved.
753
+ */
754
+ async function provisionDeclared(options) {
755
+ const { workspace } = options;
756
+ const empty = {
757
+ env: {},
758
+ statements: [],
759
+ provisioned: {},
760
+ clusters: {}
761
+ };
762
+ const manifest = options.manifest ?? await require_discover.discover({
763
+ patterns: require_sniffer.constructGlobs(workspace),
764
+ cwd: workspace.root
765
+ });
766
+ if (Object.keys(manifest).length === 0) return empty;
767
+ const context = {
768
+ manifest,
769
+ provisioned: {},
770
+ api: options.api,
771
+ projectId: options.projectId,
772
+ environmentId: options.environmentId,
773
+ stage: options.stage,
774
+ project: workspace.name,
775
+ scope: options.scope ?? workspace.name,
776
+ cache: require_sniffer.cacheBackendFor(require_sniffer.providerOf(workspace)),
777
+ events: require_sniffer.eventsBackendFor(require_sniffer.providerOf(workspace)),
778
+ storage: require_sniffer.storageBackendFor(require_sniffer.providerOf(workspace)),
779
+ addresses: surfaceAddresses(manifest, options.appUrls),
780
+ seed: options.seed,
781
+ ...options.supplied ? { supplied: options.supplied } : {},
782
+ deferred: [],
783
+ clusters: {}
784
+ };
785
+ const env = {};
786
+ for (const id of carriersLast((0, _geekmidas_manifest.provisionOrder)(manifest), manifest)) {
787
+ const declaration = manifest[id];
788
+ if (!declaration) continue;
789
+ const provisioner = provisionerFor(declaration.kind);
790
+ if (!provisioner) continue;
791
+ const result = await provisioner(declaration, context);
792
+ context.provisioned[id] = result;
793
+ Object.assign(env, result.provides);
794
+ }
795
+ return {
796
+ env,
797
+ statements: context.deferred.map((statement) => ({
798
+ id: statement.id,
799
+ describe: statement.describe,
800
+ ...statement.database ? { database: statement.database } : {},
801
+ ...statement.exists ? { exists: statement.exists } : {},
802
+ create: statement.sql
803
+ })),
804
+ provisioned: context.provisioned,
805
+ clusters: context.clusters
806
+ };
807
+ }
808
+ /**
809
+ * Run the deferred DDL against a cluster that is now reachable.
810
+ *
811
+ * The same applier the local target uses: every statement asks whether it is
812
+ * needed first, so a redeploy is free and a half-applied run recovers by being
813
+ * run again.
814
+ */
815
+ async function applyDeclared(client, statements) {
816
+ return (await require_sniffer.applyPostgres(client, statements)).filter((entry) => entry.created).length;
817
+ }
818
+ /**
819
+ * The provisioning order, with queues and topics moved to the end.
820
+ *
821
+ * `provisionOrder` walks `of` edges, and a carrier has none: a topic is not
822
+ * *derived from* a database, because under SNS it does not live in one. Where
823
+ * it lives is a fact about the backend, which is config — so the dependency is
824
+ * real under pg-boss and absent under SNS, and writing it into the declaration
825
+ * would state it in the one place that cannot know.
826
+ *
827
+ * Here it can. This runs where the backend is known, and the rule needs no
828
+ * branch on it: nothing depends on a carrier. A queue's worker and a topic's
829
+ * subscribers are *bound* to it rather than dependent on it, which is why
830
+ * neither holds a key of its own — so a carrier can always go last, and under
831
+ * pg-boss that is exactly late enough for the database it reads to be there.
832
+ */
833
+ function carriersLast(ordered, manifest) {
834
+ const carries = (id) => {
835
+ const kind = manifest[id]?.kind;
836
+ return kind === "queue" || kind === "topic";
837
+ };
838
+ return [...ordered.filter((id) => !carries(id)), ...ordered.filter(carries)];
839
+ }
840
+ /**
841
+ * Where each declared surface answers: its own app's address.
842
+ *
843
+ * Every surface is an app of its own, keyed by its id the way the derivation
844
+ * keyed it — `Api` is `api`, `Webhooks` is `webhooks` — and answers on that
845
+ * app's host, `{subdomain}.{domain}`. It used to be handed the first backend's
846
+ * address, so a workspace with two APIs pointed both at the same one.
847
+ */
848
+ function surfaceAddresses(manifest, appUrls) {
849
+ const addresses = {};
850
+ for (const [id, declaration] of Object.entries(manifest)) {
851
+ if (declaration.kind !== "rest-api") continue;
852
+ const url = appUrls[require_config.appKey(id)];
853
+ if (url) addresses[id] = url;
854
+ }
855
+ return addresses;
856
+ }
857
+ //#endregion
858
+ //#region src/deploy/state.ts
859
+ /**
860
+ * Deploy state management for Dokploy deployments
861
+ *
862
+ * Stores resource IDs (applications, services) per stage to avoid
863
+ * re-creating resources on subsequent deploys.
864
+ */
865
+ /**
866
+ * Create a new empty state for a stage
867
+ */
868
+ function createEmptyState(stage, projectId, environmentId) {
869
+ return {
870
+ provider: "dokploy",
871
+ stage,
872
+ projectId,
873
+ environmentId,
874
+ applications: {},
875
+ services: {},
876
+ lastDeployedAt: (/* @__PURE__ */ new Date()).toISOString()
877
+ };
878
+ }
879
+ /**
880
+ * Set application ID in state (mutates state)
881
+ */
882
+ function setApplicationId(state, appName, applicationId) {
883
+ state.applications[appName] = applicationId;
884
+ }
885
+ /**
886
+ * Record the image an app was deployed with (mutates state)
887
+ */
888
+ function setDeployedImage(state, appName, image) {
889
+ state.images = {
890
+ ...state.images,
891
+ [appName]: image
892
+ };
893
+ }
894
+ /**
895
+ * Get a generated secret for an app
896
+ */
897
+ function getGeneratedSecret(state, appName, secretName) {
898
+ return state?.generatedSecrets?.[appName]?.[secretName];
899
+ }
900
+ /**
901
+ * Set a generated secret for an app (mutates state)
902
+ */
903
+ function setGeneratedSecret(state, appName, secretName, value) {
904
+ if (!state.generatedSecrets) state.generatedSecrets = {};
905
+ if (!state.generatedSecrets[appName]) state.generatedSecrets[appName] = {};
906
+ state.generatedSecrets[appName][secretName] = value;
907
+ }
908
+ /**
909
+ * Set DNS verification record for a hostname (mutates state)
910
+ */
911
+ function setDnsVerification(state, hostname, serverIp) {
912
+ if (!state.dnsVerified) state.dnsVerified = {};
913
+ state.dnsVerified[hostname] = {
914
+ serverIp,
915
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
916
+ };
917
+ }
918
+ /**
919
+ * Check if a hostname is already verified with the given IP
920
+ */
921
+ function isDnsVerified(state, hostname, serverIp) {
922
+ return (state?.dnsVerified?.[hostname])?.serverIp === serverIp;
923
+ }
924
+ /**
925
+ * Get the key for a DNS record in state
926
+ */
927
+ function getDnsRecordKey(name, type) {
928
+ return `${name}:${type}`;
929
+ }
930
+ /**
931
+ * Set a created DNS record in state (mutates state)
932
+ */
933
+ function setDnsRecord(state, record) {
934
+ if (!state.dnsRecords) state.dnsRecords = {};
935
+ const key = getDnsRecordKey(record.name, record.type);
936
+ state.dnsRecords[key] = {
937
+ ...record,
938
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
939
+ };
940
+ }
941
+ /**
942
+ * Get backup state from state
943
+ */
944
+ function getBackupState(state) {
945
+ return state?.backups;
946
+ }
947
+ /**
948
+ * Set backup state (mutates state)
949
+ */
950
+ function setBackupState(state, backupState) {
951
+ state.backups = backupState;
952
+ }
953
+ /**
954
+ * Set postgres backup ID in state (mutates state)
955
+ */
956
+ function setPostgresBackupId(state, backupId) {
957
+ if (state.backups) state.backups.postgresBackupId = backupId;
958
+ }
959
+ //#endregion
960
+ //#region src/deploy/dns/DnsProvider.ts
961
+ /**
962
+ * Check if value is a DnsProvider implementation.
963
+ */
964
+ function isDnsProvider(value) {
965
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.getRecords === "function" && typeof value.upsertRecords === "function" && typeof value.deleteRecords === "function";
966
+ }
967
+ /**
968
+ * Create a DNS provider based on configuration.
969
+ *
970
+ * - 'hostinger': HostingerProvider
971
+ * - 'route53': Route53Provider
972
+ * - 'manual': Returns null (user handles DNS)
973
+ * - Custom: Use provided DnsProvider implementation
974
+ */
975
+ async function createDnsProvider(options) {
976
+ const { config } = options;
977
+ if (config.provider === "manual") return null;
978
+ if (isDnsProvider(config.provider)) return config.provider;
979
+ const provider = config.provider;
980
+ if (provider === "hostinger") {
981
+ const { HostingerProvider } = await Promise.resolve().then(() => require("./HostingerProvider-BTZd2u0f.cjs"));
982
+ return new HostingerProvider();
983
+ }
984
+ if (provider === "route53") {
985
+ const { Route53Provider } = await Promise.resolve().then(() => require("./Route53Provider-DVILBsvV.cjs"));
986
+ const route53Config = config;
987
+ return new Route53Provider({
988
+ region: route53Config.region,
989
+ profile: route53Config.profile,
990
+ hostedZoneId: route53Config.hostedZoneId
991
+ });
992
+ }
993
+ if (provider === "cloudflare") throw new Error("Cloudflare DNS provider not yet implemented");
994
+ throw new Error(`Unknown DNS provider: ${JSON.stringify(config)}`);
995
+ }
996
+ //#endregion
997
+ //#region src/deploy/dns/index.ts
998
+ /**
999
+ * DNS orchestration for deployments
1000
+ *
1001
+ * Handles automatic DNS record creation for deployed applications.
1002
+ */
1003
+ const logger$3 = require_discover.output;
1004
+ /**
1005
+ * Check if DNS config is legacy format (single domain with `domain` property)
1006
+ */
1007
+ function isLegacyDnsConfig(config) {
1008
+ return typeof config === "object" && config !== null && "provider" in config && "domain" in config;
1009
+ }
1010
+ /**
1011
+ * Normalize DNS config to new multi-domain format
1012
+ */
1013
+ function normalizeDnsConfig(config) {
1014
+ if (isLegacyDnsConfig(config)) {
1015
+ const { domain, ...providerConfig } = config;
1016
+ return { [domain]: providerConfig };
1017
+ }
1018
+ return config;
1019
+ }
1020
+ /**
1021
+ * Find the root domain for a hostname from available DNS configs
1022
+ *
1023
+ * @example
1024
+ * findRootDomain('api.geekmidas.com', { 'geekmidas.com': {...}, 'geekmidas.dev': {...} })
1025
+ * // Returns 'geekmidas.com'
1026
+ */
1027
+ function findRootDomain(hostname, dnsConfig) {
1028
+ const domains = Object.keys(dnsConfig).sort((a, b) => b.length - a.length);
1029
+ for (const domain of domains) if (hostname === domain || hostname.endsWith(`.${domain}`)) return domain;
1030
+ return null;
1031
+ }
1032
+ /**
1033
+ * Group hostnames by their root domain
1034
+ */
1035
+ function groupHostnamesByDomain(appHostnames, dnsConfig) {
1036
+ const grouped = /* @__PURE__ */ new Map();
1037
+ for (const [appName, hostname] of appHostnames) {
1038
+ const rootDomain = findRootDomain(hostname, dnsConfig);
1039
+ if (!rootDomain) {
1040
+ logger$3.log(` ⚠ No DNS config found for hostname: ${hostname}`);
1041
+ continue;
1042
+ }
1043
+ if (!grouped.has(rootDomain)) grouped.set(rootDomain, /* @__PURE__ */ new Map());
1044
+ grouped.get(rootDomain).set(appName, hostname);
1045
+ }
1046
+ return grouped;
1047
+ }
1048
+ /**
1049
+ * Resolve IP address from a hostname
1050
+ */
1051
+ async function resolveHostnameToIp(hostname) {
1052
+ try {
1053
+ return (await (0, node_dns_promises.lookup)(hostname, { family: 4 })).address;
1054
+ } catch (error) {
1055
+ throw new Error(`Failed to resolve IP for ${hostname}: ${error instanceof Error ? error.message : "Unknown error"}`);
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Extract subdomain from full hostname relative to root domain
1060
+ *
1061
+ * @example
1062
+ * extractSubdomain('api.joemoer.traflabs.io', 'traflabs.io') => 'api.joemoer'
1063
+ * extractSubdomain('joemoer.traflabs.io', 'traflabs.io') => 'joemoer'
1064
+ */
1065
+ function extractSubdomain(hostname, rootDomain) {
1066
+ if (!hostname.endsWith(rootDomain)) throw new Error(`Hostname ${hostname} is not under root domain ${rootDomain}`);
1067
+ return hostname.slice(0, -(rootDomain.length + 1)) || "@";
1068
+ }
1069
+ /**
1070
+ * Generate required DNS records for a deployment
1071
+ */
1072
+ function generateRequiredRecords(appHostnames, rootDomain, serverIp) {
1073
+ const records = [];
1074
+ for (const [appName, hostname] of appHostnames) {
1075
+ const subdomain = extractSubdomain(hostname, rootDomain);
1076
+ records.push({
1077
+ hostname,
1078
+ subdomain,
1079
+ type: "A",
1080
+ value: serverIp,
1081
+ appName
1082
+ });
1083
+ }
1084
+ return records;
1085
+ }
1086
+ /**
1087
+ * Print DNS records table
1088
+ */
1089
+ function printDnsRecordsTable(records, rootDomain) {
1090
+ logger$3.log(`\n 📋 DNS Records for ${rootDomain}:`);
1091
+ logger$3.log(" ┌─────────────────────────────────────┬──────┬─────────────────┬────────┐");
1092
+ logger$3.log(" │ Subdomain │ Type │ Value │ Status │");
1093
+ logger$3.log(" ├─────────────────────────────────────┼──────┼─────────────────┼────────┤");
1094
+ for (const record of records) {
1095
+ const subdomain = record.subdomain.padEnd(35);
1096
+ const type = record.type.padEnd(4);
1097
+ const value = record.value.padEnd(15);
1098
+ let status;
1099
+ if (record.error) status = "✗";
1100
+ else if (record.created) status = "✓ new";
1101
+ else if (record.existed) status = "✓";
1102
+ else status = "?";
1103
+ logger$3.log(` │ ${subdomain} │ ${type} │ ${value} │ ${status.padEnd(6)} │`);
1104
+ }
1105
+ logger$3.log(" └─────────────────────────────────────┴──────┴─────────────────┴────────┘");
1106
+ }
1107
+ /**
1108
+ * Print DNS records in a simple format for manual setup
1109
+ */
1110
+ function printDnsRecordsSimple(records, rootDomain) {
1111
+ logger$3.log("\n 📋 Required DNS Records:");
1112
+ logger$3.log(` Add these A records to your DNS provider (${rootDomain}):\n`);
1113
+ for (const record of records) logger$3.log(` ${record.subdomain} → ${record.value} (A record)`);
1114
+ logger$3.log("");
1115
+ }
1116
+ /**
1117
+ * Create DNS records for a single domain using its configured provider
1118
+ */
1119
+ async function createDnsRecordsForDomain(records, rootDomain, providerConfig) {
1120
+ const ttl = "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300;
1121
+ let provider;
1122
+ try {
1123
+ provider = await createDnsProvider({ config: providerConfig });
1124
+ } catch (error) {
1125
+ const message = error instanceof Error ? error.message : "Unknown error";
1126
+ logger$3.log(` ⚠ Failed to create DNS provider for ${rootDomain}: ${message}`);
1127
+ return records.map((r) => ({
1128
+ ...r,
1129
+ error: message
1130
+ }));
1131
+ }
1132
+ if (!provider) return records.map((r) => ({
1133
+ ...r,
1134
+ created: false,
1135
+ existed: false
1136
+ }));
1137
+ const results = [];
1138
+ const upsertRecords = records.map((r) => ({
1139
+ name: r.subdomain,
1140
+ type: r.type,
1141
+ ttl,
1142
+ value: r.value
1143
+ }));
1144
+ try {
1145
+ const upsertResults = await provider.upsertRecords(rootDomain, upsertRecords);
1146
+ for (const [i, record] of records.entries()) {
1147
+ const result = upsertResults[i];
1148
+ if (!result) {
1149
+ results.push({
1150
+ hostname: record.hostname,
1151
+ subdomain: record.subdomain,
1152
+ type: record.type,
1153
+ value: record.value,
1154
+ appName: record.appName,
1155
+ error: "No result returned from provider"
1156
+ });
1157
+ continue;
1158
+ }
1159
+ if (result.unchanged) results.push({
1160
+ hostname: record.hostname,
1161
+ subdomain: record.subdomain,
1162
+ type: record.type,
1163
+ value: record.value,
1164
+ appName: record.appName,
1165
+ existed: true,
1166
+ created: false
1167
+ });
1168
+ else results.push({
1169
+ hostname: record.hostname,
1170
+ subdomain: record.subdomain,
1171
+ type: record.type,
1172
+ value: record.value,
1173
+ appName: record.appName,
1174
+ created: result.created,
1175
+ existed: !result.created
1176
+ });
1177
+ }
1178
+ } catch (error) {
1179
+ const message = error instanceof Error ? error.message : "Unknown error";
1180
+ logger$3.log(` ⚠ Failed to create DNS records for ${rootDomain}: ${message}`);
1181
+ return records.map((r) => ({
1182
+ hostname: r.hostname,
1183
+ subdomain: r.subdomain,
1184
+ type: r.type,
1185
+ value: r.value,
1186
+ appName: r.appName,
1187
+ error: message
1188
+ }));
1189
+ }
1190
+ return results;
1191
+ }
1192
+ /**
1193
+ * Main DNS orchestration function for deployments
1194
+ *
1195
+ * Supports both legacy single-domain format and new multi-domain format:
1196
+ * - Legacy: { provider: 'hostinger', domain: 'example.com' }
1197
+ * - Multi: { 'example.com': { provider: 'hostinger' }, 'example.dev': { provider: 'route53' } }
1198
+ *
1199
+ * @param appHostnames - Map of app names to hostnames
1200
+ * @param dnsConfig - DNS configuration (legacy or multi-domain)
1201
+ * @param dokployEndpoint - Dokploy server endpoint to resolve IP from
1202
+ * @param state - Optional state to save created records for later deletion
1203
+ */
1204
+ async function orchestrateDns(appHostnames, dnsConfig, dokployEndpoint, state) {
1205
+ if (!dnsConfig) return null;
1206
+ const normalizedConfig = normalizeDnsConfig(dnsConfig);
1207
+ logger$3.log("\n🌐 Setting up DNS records...");
1208
+ let serverIp;
1209
+ try {
1210
+ const endpointUrl = new URL(dokployEndpoint);
1211
+ serverIp = await resolveHostnameToIp(endpointUrl.hostname);
1212
+ logger$3.log(` Server IP: ${serverIp} (from ${endpointUrl.hostname})`);
1213
+ } catch (error) {
1214
+ const message = error instanceof Error ? error.message : "Unknown error";
1215
+ logger$3.log(` ⚠ Failed to resolve server IP: ${message}`);
1216
+ return null;
1217
+ }
1218
+ const groupedHostnames = groupHostnamesByDomain(appHostnames, normalizedConfig);
1219
+ if (groupedHostnames.size === 0) {
1220
+ logger$3.log(" No DNS records needed (no hostnames match configured domains)");
1221
+ return {
1222
+ records: [],
1223
+ success: true,
1224
+ serverIp
1225
+ };
1226
+ }
1227
+ const allRecords = [];
1228
+ let hasFailures = false;
1229
+ for (const [rootDomain, domainHostnames] of groupedHostnames) {
1230
+ const providerConfig = normalizedConfig[rootDomain];
1231
+ if (!providerConfig) {
1232
+ logger$3.log(` ⚠ No provider config for ${rootDomain}`);
1233
+ continue;
1234
+ }
1235
+ const providerName = typeof providerConfig.provider === "string" ? providerConfig.provider : "custom";
1236
+ const requiredRecords = generateRequiredRecords(domainHostnames, rootDomain, serverIp);
1237
+ if (requiredRecords.length === 0) continue;
1238
+ logger$3.log(` Creating DNS records for ${rootDomain} (${providerName})...`);
1239
+ const domainRecords = await createDnsRecordsForDomain(requiredRecords, rootDomain, providerConfig);
1240
+ allRecords.push(...domainRecords);
1241
+ const created = domainRecords.filter((r) => r.created).length;
1242
+ const existed = domainRecords.filter((r) => r.existed).length;
1243
+ const failed = domainRecords.filter((r) => r.error).length;
1244
+ if (created > 0) logger$3.log(` ✓ Created ${created} DNS record(s) for ${rootDomain}`);
1245
+ if (existed > 0) logger$3.log(` ✓ ${existed} record(s) already exist for ${rootDomain}`);
1246
+ if (failed > 0) {
1247
+ logger$3.log(` ⚠ ${failed} record(s) failed for ${rootDomain}`);
1248
+ hasFailures = true;
1249
+ }
1250
+ if (state) {
1251
+ for (const record of domainRecords) if (record.created || record.existed) setDnsRecord(state, {
1252
+ domain: rootDomain,
1253
+ name: record.subdomain,
1254
+ type: record.type,
1255
+ value: record.value,
1256
+ ttl: "ttl" in providerConfig && providerConfig.ttl ? providerConfig.ttl : 300
1257
+ });
1258
+ }
1259
+ printDnsRecordsTable(domainRecords, rootDomain);
1260
+ if (providerConfig.provider === "manual" || failed > 0) printDnsRecordsSimple(domainRecords.filter((r) => !r.created && !r.existed), rootDomain);
1261
+ }
1262
+ return {
1263
+ records: allRecords,
1264
+ success: !hasFailures,
1265
+ serverIp
1266
+ };
1267
+ }
1268
+ /**
1269
+ * Verify DNS records resolve correctly after deployment.
1270
+ *
1271
+ * This function:
1272
+ * 1. Checks state for previously verified hostnames (skips if already verified with same IP)
1273
+ * 2. Attempts to resolve each hostname to an IP
1274
+ * 3. Compares resolved IP with expected server IP
1275
+ * 4. Updates state with verification results
1276
+ *
1277
+ * @param appHostnames - Map of app names to hostnames
1278
+ * @param serverIp - Expected IP address the hostnames should resolve to
1279
+ * @param state - Deploy state for caching verification results
1280
+ * @returns Array of verification results
1281
+ */
1282
+ async function verifyDnsRecords(appHostnames, serverIp, state) {
1283
+ const results = [];
1284
+ logger$3.log("\n🔍 Verifying DNS records...");
1285
+ for (const [appName, hostname] of appHostnames) {
1286
+ if (isDnsVerified(state, hostname, serverIp)) {
1287
+ logger$3.log(` ✓ ${hostname} (previously verified)`);
1288
+ results.push({
1289
+ hostname,
1290
+ appName,
1291
+ verified: true,
1292
+ expectedIp: serverIp,
1293
+ skipped: true
1294
+ });
1295
+ continue;
1296
+ }
1297
+ try {
1298
+ const resolvedIp = await resolveHostnameToIp(hostname);
1299
+ if (resolvedIp === serverIp) {
1300
+ setDnsVerification(state, hostname, serverIp);
1301
+ logger$3.log(` ✓ ${hostname} → ${resolvedIp}`);
1302
+ results.push({
1303
+ hostname,
1304
+ appName,
1305
+ verified: true,
1306
+ resolvedIp,
1307
+ expectedIp: serverIp
1308
+ });
1309
+ } else {
1310
+ logger$3.log(` ⚠ ${hostname} resolves to ${resolvedIp}, expected ${serverIp}`);
1311
+ results.push({
1312
+ hostname,
1313
+ appName,
1314
+ verified: false,
1315
+ resolvedIp,
1316
+ expectedIp: serverIp
1317
+ });
1318
+ }
1319
+ } catch (error) {
1320
+ const message = error instanceof Error ? error.message : "Unknown error";
1321
+ logger$3.log(` ⚠ ${hostname} DNS not propagated (${message})`);
1322
+ results.push({
1323
+ hostname,
1324
+ appName,
1325
+ verified: false,
1326
+ expectedIp: serverIp,
1327
+ error: message
1328
+ });
1329
+ }
1330
+ }
1331
+ const verified = results.filter((r) => r.verified).length;
1332
+ const skipped = results.filter((r) => r.skipped).length;
1333
+ const pending = results.filter((r) => !r.verified).length;
1334
+ if (pending > 0) {
1335
+ logger$3.log(`\n ${verified} verified, ${pending} pending propagation`);
1336
+ logger$3.log(" DNS changes may take 5-30 minutes to propagate");
1337
+ } else if (skipped > 0) logger$3.log(` ${verified} verified (${skipped} from cache)`);
1338
+ return results;
1339
+ }
1340
+ //#endregion
1341
+ //#region src/deploy/docker.ts
1342
+ const logger$2 = require_discover.output;
1343
+ /**
1344
+ * The id the Dockerfile templates mount the encrypted credentials under:
1345
+ * `RUN --mount=type=secret,id=gkm_credentials`.
1346
+ */
1347
+ const CREDENTIALS_SECRET_ID = "gkm_credentials";
1348
+ /**
1349
+ * Get the full image reference
1350
+ */
1351
+ function getImageRef(registry, imageName, tag) {
1352
+ if (registry) return `${registry}/${imageName}:${tag}`;
1353
+ return `${imageName}:${tag}`;
1354
+ }
1355
+ /**
1356
+ * The `docker build` argv for an image.
1357
+ *
1358
+ * One element per value, so nothing in a ref or a build arg is read by a
1359
+ * shell, and `--opt=value` rather than `--opt value`, so a value that starts
1360
+ * with `-` cannot be taken for one of docker's own flags.
1361
+ *
1362
+ * @internal Exported for testing
1363
+ */
1364
+ function dockerBuildArgs(options) {
1365
+ const { dockerfilePath, imageRef, buildArgs = [], credentialsFile } = options;
1366
+ return [
1367
+ "build",
1368
+ "--platform=linux/amd64",
1369
+ `--file=${dockerfilePath}`,
1370
+ `--tag=${imageRef}`,
1371
+ ...buildArgs.map((arg) => `--build-arg=${arg}`),
1372
+ ...credentialsFile ? [`--secret=id=${CREDENTIALS_SECRET_ID},src=${credentialsFile}`] : [],
1373
+ "."
1374
+ ];
1375
+ }
1376
+ /**
1377
+ * Write the encrypted credentials where `docker build --secret` reads them.
1378
+ *
1379
+ * Two lines — ciphertext, then IV — so a template can split them with `sed`
1380
+ * in any base image. Owner-only, in a directory of its own, and the returned
1381
+ * cleanup removes both whatever the build did.
1382
+ *
1383
+ * @internal Exported for testing
1384
+ */
1385
+ async function writeCredentialsFile(credentials) {
1386
+ const dir = await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "gkm-credentials-"));
1387
+ const path = (0, node_path.join)(dir, CREDENTIALS_SECRET_ID);
1388
+ await (0, node_fs_promises.writeFile)(path, `${credentials.encrypted}\n${credentials.iv}\n`, { mode: 384 });
1389
+ await (0, node_fs_promises.chmod)(path, 384);
1390
+ return {
1391
+ path,
1392
+ cleanup: () => (0, node_fs_promises.rm)(dir, {
1393
+ recursive: true,
1394
+ force: true
1395
+ })
1396
+ };
1397
+ }
1398
+ /**
1399
+ * Build Docker image
1400
+ * @param imageRef - Full image reference (registry/name:tag)
1401
+ * @param buildArgs - Build arguments to pass to docker build
1402
+ * @param credentials - Encrypted credentials, passed as a build secret
1403
+ */
1404
+ async function buildImage(imageRef, buildArgs, credentials, { cwd, signal, stdio }) {
1405
+ logger$2.log(`\n🔨 Building Docker image: ${imageRef}`);
1406
+ logger$2.log(" Generating Dockerfile for the pre-built bundle...");
1407
+ await require_sniffer.dockerCommand({
1408
+ slim: true,
1409
+ cwd
1410
+ });
1411
+ const dockerfilePath = (0, node_path.join)(cwd, ".gkm", "docker", "Dockerfile");
1412
+ const secret = credentials ? await writeCredentialsFile(credentials) : void 0;
1413
+ try {
1414
+ await require_sniffer.run("docker", dockerBuildArgs({
1415
+ dockerfilePath,
1416
+ imageRef,
1417
+ buildArgs,
1418
+ credentialsFile: secret?.path
1419
+ }), {
1420
+ cwd,
1421
+ env: {
1422
+ ...process.env,
1423
+ DOCKER_BUILDKIT: "1"
1424
+ },
1425
+ ...signal ? { signal } : {},
1426
+ ...stdio ? { stdio } : {}
1427
+ });
1428
+ logger$2.log(`✅ Image built: ${imageRef}`);
1429
+ } catch (error) {
1430
+ throw new require_sniffer.DockerBuildFailed(imageRef, error);
1431
+ } finally {
1432
+ await secret?.cleanup();
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Push Docker image to registry
1437
+ */
1438
+ async function pushImage(imageRef, { cwd, signal, stdio }) {
1439
+ logger$2.log(`\n☁️ Pushing image: ${imageRef}`);
1440
+ try {
1441
+ await require_sniffer.run("docker", ["push", imageRef], {
1442
+ cwd,
1443
+ ...signal ? { signal } : {},
1444
+ ...stdio ? { stdio } : {}
1445
+ });
1446
+ logger$2.log(`✅ Image pushed: ${imageRef}`);
1447
+ } catch (error) {
1448
+ throw new require_sniffer.DockerPushFailed(imageRef, error);
1449
+ }
1450
+ }
1451
+ /**
1452
+ * The digest the registry gave a pushed image, `sha256:…`.
1453
+ *
1454
+ * A tag can be pushed over — by the next deploy, or by anything else that
1455
+ * shares the repository — and the digest is what says which image a stage
1456
+ * actually ran. `RepoDigests` has one entry per repository the image was
1457
+ * pushed to, so the one for this ref's repository is picked by name.
1458
+ *
1459
+ * @internal Exported for testing
1460
+ */
1461
+ async function pushedDigest(imageRef, { cwd, signal } = { cwd: process.cwd() }) {
1462
+ const repository = imageRef.split("@")[0].replace(/:[\w][\w.-]*$/, "");
1463
+ const output = await require_sniffer.runOutput("docker", [
1464
+ "image",
1465
+ "inspect",
1466
+ "--format={{json .RepoDigests}}",
1467
+ imageRef
1468
+ ], {
1469
+ cwd,
1470
+ ...signal ? { signal } : {}
1471
+ });
1472
+ let digests;
1473
+ try {
1474
+ digests = JSON.parse(output.trim() || "[]");
1475
+ } catch {
1476
+ return;
1477
+ }
1478
+ if (!Array.isArray(digests)) return void 0;
1479
+ return digests.find((entry) => typeof entry === "string" && entry.startsWith(`${repository}@`))?.slice(repository.length + 1);
1480
+ }
1481
+ /**
1482
+ * Deploy using Docker (build and optionally push image)
1483
+ */
1484
+ async function deployDocker(options) {
1485
+ const { stage, tag, skipPush, masterKey, config, buildArgs, credentials } = options;
1486
+ const imageName = config.imageName;
1487
+ const imageRef = require_sniffer.validateImageRef(getImageRef(config.registry, imageName, tag));
1488
+ const docker = {
1489
+ cwd: options.cwd ?? process.cwd(),
1490
+ ...options.signal ? { signal: options.signal } : {},
1491
+ ...options.stdio ? { stdio: options.stdio } : {}
1492
+ };
1493
+ await buildImage(imageRef, buildArgs, credentials, docker);
1494
+ let digest;
1495
+ if (!skipPush) {
1496
+ if (!config.registry) logger$2.warn("\n⚠️ No registry configured. Use --skip-push or configure docker.registry in gkm.config.ts");
1497
+ else {
1498
+ await pushImage(imageRef, docker);
1499
+ digest = await pushedDigest(imageRef, docker);
1500
+ }
1501
+ }
1502
+ logger$2.log("\n✅ Docker deployment ready!");
1503
+ logger$2.log(`\n📋 Deployment details:`);
1504
+ logger$2.log(` Image: ${imageRef}`);
1505
+ logger$2.log(` Stage: ${stage}`);
1506
+ if (masterKey) logger$2.log(`\n🔐 Run the container with GKM_MASTER_KEY set to the key with fingerprint ${require_sniffer.keyFingerprint(masterKey)}.`);
1507
+ return {
1508
+ imageRef,
1509
+ ...digest ? { digest } : {},
1510
+ masterKey
1511
+ };
1512
+ }
1513
+ //#endregion
1514
+ //#region src/deploy/env-resolver.ts
1515
+ /**
1516
+ * Environment Variable Resolution for Dokploy Deployments
1517
+ *
1518
+ * Resolves sniffed environment variables to actual values during deployment.
1519
+ * Auto-supports common variables like DATABASE_URL, REDIS_URL, BETTER_AUTH_*,
1520
+ * and falls back to user-provided secrets.
1521
+ */
1522
+ /**
1523
+ * Generate a secure random secret (64 hex characters = 32 bytes)
1524
+ */
1525
+ function generateSecret() {
1526
+ return (0, node_crypto.randomBytes)(32).toString("hex");
1527
+ }
1528
+ /**
1529
+ * Get or generate a secret for an app.
1530
+ * If the secret already exists in state, returns it.
1531
+ * Otherwise generates a new one and stores it.
1532
+ */
1533
+ function getOrGenerateSecret(state, appName, secretName) {
1534
+ const existing = getGeneratedSecret(state, appName, secretName);
1535
+ if (existing) return existing;
1536
+ const generated = generateSecret();
1537
+ setGeneratedSecret(state, appName, secretName, generated);
1538
+ return generated;
1539
+ }
1540
+ /**
1541
+ * Resolve a single environment variable
1542
+ */
1543
+ function resolveEnvVar(varName, context) {
1544
+ switch (varName) {
1545
+ case "PORT": return String(context.app.port);
1546
+ case "NODE_ENV": return "production";
1547
+ case "STAGE": return context.stage;
1548
+ case "BETTER_AUTH_URL": return `https://${context.appHostname}`;
1549
+ case "BETTER_AUTH_SECRET": return getOrGenerateSecret(context.state, context.appName, "BETTER_AUTH_SECRET");
1550
+ case "BETTER_AUTH_TRUSTED_ORIGINS":
1551
+ if (context.frontendUrls.length > 0) return context.frontendUrls.join(",");
1552
+ break;
1553
+ case "GKM_MASTER_KEY": if (context.masterKey) return context.masterKey;
1554
+ }
1555
+ if (context.dependencyUrls && varName.endsWith("_URL")) {
1556
+ const depName = (require_workspace.stripPublicPrefix(varName) ?? varName).slice(0, -4).toLowerCase();
1557
+ if (context.dependencyUrls[depName]) return context.dependencyUrls[depName];
1558
+ }
1559
+ if (context.userSecrets) {
1560
+ if (context.userSecrets.custom[varName]) return context.userSecrets.custom[varName];
1561
+ if (varName in context.userSecrets.urls) return context.userSecrets.urls[varName];
1562
+ if (varName === "POSTGRES_PASSWORD" && context.userSecrets.services.postgres) return context.userSecrets.services.postgres.password;
1563
+ if (varName === "REDIS_PASSWORD" && context.userSecrets.services.redis) return context.userSecrets.services.redis.password;
1564
+ }
1565
+ }
1566
+ /**
1567
+ * Resolve all environment variables for an app
1568
+ */
1569
+ function resolveEnvVars(requiredVars, context) {
1570
+ const resolved = {};
1571
+ const missing = [];
1572
+ for (const varName of requiredVars) {
1573
+ const value = resolveEnvVar(varName, context);
1574
+ if (value !== void 0) resolved[varName] = value;
1575
+ else missing.push(varName);
1576
+ }
1577
+ return {
1578
+ resolved,
1579
+ missing
1580
+ };
1581
+ }
1582
+ /**
1583
+ * Format missing variables error message
1584
+ */
1585
+ function formatMissingVarsError(appName, missing, stage) {
1586
+ return `Deployment failed: ${appName} is missing required environment variables:\n${missing.map((v) => ` - ${v}`).join("\n")}\n\nAdd them with:\n gkm secrets:set <VAR_NAME> <value> --stage ${stage}\n\nOr add them to the app's requiredEnv in gkm.config.ts to have them auto-resolved.`;
1587
+ }
1588
+ /**
1589
+ * Validate that all required environment variables can be resolved
1590
+ */
1591
+ function validateEnvVars(requiredVars, context) {
1592
+ const { resolved, missing } = resolveEnvVars(requiredVars, context);
1593
+ return {
1594
+ valid: missing.length === 0,
1595
+ missing,
1596
+ resolved
1597
+ };
1598
+ }
1599
+ //#endregion
1600
+ //#region src/deploy/generated.ts
1601
+ /**
1602
+ * The values a deployed stage generates once and keeps: what nothing can
1603
+ * provision and nobody else issues.
1604
+ *
1605
+ * - **A seed**, which salts every password a deploy derives — a database's
1606
+ * master and roles, a bucket's root user. Derived from repo facts alone
1607
+ * (project, stage, construct id), those passwords were computable by anyone
1608
+ * who could read the repo.
1609
+ * - **Each `secret` construct's value** — an auth server's signing secret —
1610
+ * random, rather than derived.
1611
+ * - **Each `encryption` construct's keyring** — one random key and an index
1612
+ * key. Later keys are added by `gkm encryption:rotate`, never by a deploy.
1613
+ *
1614
+ * Both are generated on the first deploy that needs them and written to the
1615
+ * stage's store, so every later deploy reads the same values: sessions survive
1616
+ * a redeploy, and a role's password does not move. A value set by hand with
1617
+ * `gkm secrets:set` is kept, never replaced.
1618
+ */
1619
+ /**
1620
+ * The stage's secrets with its seed and every declared `secret`'s value
1621
+ * present, generating what is missing. Pure: the caller writes the result
1622
+ * back to the stage's store when `generated` is not empty.
1623
+ */
1624
+ function withGeneratedSecrets(secrets, manifest) {
1625
+ const generated = [];
1626
+ const custom = { ...secrets.custom };
1627
+ for (const declaration of Object.values(manifest)) {
1628
+ if (declaration?.kind !== "secret" && declaration?.kind !== "encryption") continue;
1629
+ const key = declaration.provides?.[0];
1630
+ if (!key || custom[key]) continue;
1631
+ custom[key] = declaration.kind === "encryption" ? (0, _geekmidas_constructs_encryption.generateKeyring)() : random();
1632
+ generated.push(key);
1633
+ }
1634
+ const seed = secrets.seed ?? random();
1635
+ if (!secrets.seed) generated.push("seed");
1636
+ return {
1637
+ secrets: generated.length ? {
1638
+ ...secrets,
1639
+ seed,
1640
+ custom,
1641
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1642
+ } : secrets,
1643
+ generated
1644
+ };
1645
+ }
1646
+ /** 256 bits, URL-safe. */
1647
+ function random() {
1648
+ return (0, node_crypto.randomBytes)(32).toString("base64url");
1649
+ }
1650
+ //#endregion
1651
+ //#region src/deploy/journal.ts
1652
+ var DeployJournal = class DeployJournal {
1653
+ store;
1654
+ stage;
1655
+ state;
1656
+ resources;
1657
+ version;
1658
+ existed;
1659
+ constructor(store, stage, state, resources, version, existed) {
1660
+ this.store = store;
1661
+ this.stage = stage;
1662
+ this.state = state;
1663
+ this.resources = resources;
1664
+ this.version = version;
1665
+ this.existed = existed;
1666
+ }
1667
+ /**
1668
+ * The stage's journal — its stored state, or `initial` written as the
1669
+ * stage's first state, so there is somewhere to record the very first
1670
+ * resource before it is created.
1671
+ */
1672
+ static async open(store, stage, initial) {
1673
+ const stored = await store.read(stage);
1674
+ if (stored) return new DeployJournal(store, stage, stored.state, stored.resources, stored.version, true);
1675
+ const state = initial();
1676
+ const version = await store.write(stage, state, { expectedVersion: null });
1677
+ return new DeployJournal(store, stage, state, {}, version, false);
1678
+ }
1679
+ record(key) {
1680
+ return this.resources[key];
1681
+ }
1682
+ /** The keys a previous run marked `pending` and never saw created. */
1683
+ unfinished() {
1684
+ return Object.values(this.resources).filter((record) => record.status === "pending").map((record) => record.key);
1685
+ }
1686
+ /** Records that `entry` is about to be created. */
1687
+ async pending(entry) {
1688
+ await this.put({
1689
+ ...entry,
1690
+ status: "pending"
1691
+ });
1692
+ }
1693
+ /** Records `entry` as existing with `id`; a no-op if it already is. */
1694
+ async ready(entry, id) {
1695
+ const current = this.resources[entry.key];
1696
+ if (current?.status === "ready" && current.id === id) return;
1697
+ await this.put({
1698
+ ...entry,
1699
+ status: "ready",
1700
+ id
1701
+ });
1702
+ }
1703
+ /**
1704
+ * The resource `entry` names: by its recorded id, else by looking it up,
1705
+ * else created — with `pending` written before the create and `ready`
1706
+ * after, so a run that dies in between leaves a record the next run
1707
+ * resolves by looking the resource up rather than creating another.
1708
+ */
1709
+ async ensure(entry, steps) {
1710
+ const record = this.resources[entry.key];
1711
+ let staleId;
1712
+ if (record?.status === "ready" && record.id && steps.get) {
1713
+ const known = await steps.get(record.id);
1714
+ if (known) {
1715
+ await this.ready(entry, steps.id(known));
1716
+ return {
1717
+ resource: known,
1718
+ via: "recorded"
1719
+ };
1720
+ }
1721
+ staleId = record.id;
1722
+ }
1723
+ const existing = await steps.find();
1724
+ if (existing) {
1725
+ await this.ready(entry, steps.id(existing));
1726
+ return {
1727
+ resource: existing,
1728
+ via: record?.status === "pending" ? "resumed" : "found",
1729
+ ...staleId ? { staleId } : {}
1730
+ };
1731
+ }
1732
+ await this.pending(entry);
1733
+ const created = await steps.create();
1734
+ await this.ready(entry, steps.id(created));
1735
+ return {
1736
+ resource: created,
1737
+ via: "created",
1738
+ ...staleId ? { staleId } : {}
1739
+ };
1740
+ }
1741
+ /** Writes the stage's state, keeping its resource records. */
1742
+ async save() {
1743
+ this.state.lastDeployedAt = (/* @__PURE__ */ new Date()).toISOString();
1744
+ this.version = await this.store.write(this.stage, this.state, { expectedVersion: this.version });
1745
+ }
1746
+ async put(record) {
1747
+ this.version = await this.store.putResource(this.stage, record, { expectedVersion: this.version });
1748
+ this.resources = {
1749
+ ...this.resources,
1750
+ [record.key]: {
1751
+ ...record,
1752
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1753
+ }
1754
+ };
1755
+ }
1756
+ };
1757
+ //#endregion
1758
+ //#region src/deploy/ownership.ts
1759
+ /**
1760
+ * Which Dokploy project a deploy is allowed to deploy into.
1761
+ *
1762
+ * Deploy used to take any project whose name matched the workspace's, in any
1763
+ * case — so a second workspace called `shop` (or `Shop`) on the same server
1764
+ * deployed into the first one's project, over its images and applications. A
1765
+ * project is now claimed by an ownership marker in its description, and a
1766
+ * project with the right name and no marker is somebody else's.
1767
+ */
1768
+ /**
1769
+ * A Dokploy project with the name this deploy would use exists, and nothing
1770
+ * says this workspace created it.
1771
+ */
1772
+ var ProjectNotOwned = class extends Error {
1773
+ projectName;
1774
+ projectId;
1775
+ identity;
1776
+ ownedBy;
1777
+ constructor(projectName, projectId, identity, ownedBy) {
1778
+ super(`The Dokploy project '${projectName}' (${projectId}) was not created by this workspace (${identity})${ownedBy ? ` — it is marked '${ownedBy}'` : ""}, so deploy will not use it. Set deploy.namespace in gkm.config.ts to deploy under a name of your own, or, if this project really is this workspace's, add 'gkm:${identity}' to its description in Dokploy.`);
1779
+ this.projectName = projectName;
1780
+ this.projectId = projectId;
1781
+ this.identity = identity;
1782
+ this.ownedBy = ownedBy;
1783
+ this.name = "ProjectNotOwned";
1784
+ }
1785
+ };
1786
+ /** A description with the marker added, keeping what was there. */
1787
+ function withMarker(description, marker) {
1788
+ const existing = (description ?? "").trim();
1789
+ return existing ? `${existing}\n${marker}` : marker;
1790
+ }
1791
+ /** `project.one`, or `null` when Dokploy no longer has the project. */
1792
+ async function projectById(api, projectId) {
1793
+ try {
1794
+ return await api.getProject(projectId) ?? null;
1795
+ } catch (error) {
1796
+ if (error instanceof require_sniffer.DokployApiError) return null;
1797
+ throw error;
1798
+ }
1799
+ }
1800
+ /**
1801
+ * The project this identity owns, if there is one — read only, so a dry run
1802
+ * asks the same question a deploy does:
1803
+ *
1804
+ * 1. The one the stage's state names, if Dokploy still has it. State written
1805
+ * before markers existed is trusted — it holds an id this workspace was
1806
+ * given when it created the project.
1807
+ * 2. One with this name *and* this identity's marker.
1808
+ *
1809
+ * A project that matches by name (in any case) but carries no marker, or
1810
+ * another identity's, raises `ProjectNotOwned` — it is never adopted.
1811
+ */
1812
+ async function findProject(api, identity, stateProjectId) {
1813
+ const name = require_store.projectName(identity);
1814
+ const marker = require_store.ownershipMarker(identity);
1815
+ if (stateProjectId) {
1816
+ const known = await projectById(api, stateProjectId);
1817
+ if (known) {
1818
+ const claimed = require_store.markerOf(known.description);
1819
+ if (claimed && claimed !== marker) throw new ProjectNotOwned(known.name, known.projectId, identity.key, claimed);
1820
+ return {
1821
+ projectId: known.projectId,
1822
+ name: known.name,
1823
+ description: known.description ?? null,
1824
+ environments: known.environments ?? [],
1825
+ via: "state",
1826
+ needsClaim: !claimed
1827
+ };
1828
+ }
1829
+ }
1830
+ const projects = await api.listProjects();
1831
+ const owned = projects.find((p) => p.name.toLowerCase() === name.toLowerCase() && require_store.isOwnedBy(p.description, identity));
1832
+ if (owned) {
1833
+ const details = await api.getProject(owned.projectId);
1834
+ return {
1835
+ projectId: owned.projectId,
1836
+ name: owned.name,
1837
+ description: owned.description ?? null,
1838
+ environments: details.environments ?? [],
1839
+ via: "marker",
1840
+ needsClaim: false
1841
+ };
1842
+ }
1843
+ const clash = projects.find((p) => p.name.toLowerCase() === name.toLowerCase());
1844
+ if (clash) throw new ProjectNotOwned(clash.name, clash.projectId, identity.key, require_store.markerOf(clash.description));
1845
+ return null;
1846
+ }
1847
+ /**
1848
+ * The project this deploy deploys into: the one {@link findProject} finds —
1849
+ * claimed with this identity's marker if it carries none yet, so the next
1850
+ * deploy without state still finds it — or a new one, marked.
1851
+ */
1852
+ async function resolveProject(api, identity, stateProjectId, log = () => {}, hooks = {}) {
1853
+ const marker = require_store.ownershipMarker(identity);
1854
+ const found = await findProject(api, identity, stateProjectId);
1855
+ if (found) {
1856
+ if (found.needsClaim) {
1857
+ await api.updateProject(found.projectId, {
1858
+ name: found.name,
1859
+ description: withMarker(found.description, marker)
1860
+ });
1861
+ log(` Claimed project ${found.name} for ${identity.key}`);
1862
+ }
1863
+ return {
1864
+ projectId: found.projectId,
1865
+ name: found.name,
1866
+ environments: found.environments,
1867
+ via: found.via
1868
+ };
1869
+ }
1870
+ await hooks.beforeCreate?.();
1871
+ const created = await api.createProject(require_store.projectName(identity), withMarker("Deployed by gkm.", marker));
1872
+ return {
1873
+ projectId: created.project.projectId,
1874
+ name: created.project.name,
1875
+ environments: [created.environment],
1876
+ via: "created"
1877
+ };
1878
+ }
1879
+ //#endregion
1880
+ //#region src/deploy/registry.ts
1881
+ /**
1882
+ * Which Dokploy registry a stage's images are pulled through.
1883
+ *
1884
+ * It used to be one id stored per machine (`~/.gkm/credentials.json`), and
1885
+ * when that was empty, the first registry Dokploy listed — so an image could be
1886
+ * deployed with credentials for a registry nobody chose, and two workspaces
1887
+ * deployed from one machine shared whichever was stored last. The id is now
1888
+ * kept in the stage's state, and found only from what the workspace
1889
+ * configured.
1890
+ */
1891
+ /** There is nowhere to push images to, so Dokploy has nothing to pull. */
1892
+ var RegistryNotConfigured = class extends Error {
1893
+ stage;
1894
+ constructor(stage) {
1895
+ super(`Deploying '${stage}' needs a container registry: Dokploy pulls each app's image from one. Set deploy.dokploy.registry in gkm.config.ts (e.g. 'ghcr.io/acme'), and deploy.dokploy.registryId if Dokploy already holds that registry's credentials.`);
1896
+ this.stage = stage;
1897
+ this.name = "RegistryNotConfigured";
1898
+ }
1899
+ };
1900
+ /** `deploy.dokploy.registryId` names a registry Dokploy does not have. */
1901
+ var RegistryNotFound = class extends Error {
1902
+ registryId;
1903
+ constructor(registryId) {
1904
+ super(`deploy.dokploy.registryId '${registryId}' is not a registry on this Dokploy server. Find the right id under Settings → Docker Registry in Dokploy and set it in gkm.config.ts, or remove it to have deploy find the registry by its URL.`);
1905
+ this.registryId = registryId;
1906
+ this.name = "RegistryNotFound";
1907
+ }
1908
+ };
1909
+ /** More than one Dokploy registry serves the configured registry. */
1910
+ var RegistryAmbiguous = class extends Error {
1911
+ registry;
1912
+ registryIds;
1913
+ constructor(registry, registryIds) {
1914
+ super(`Dokploy has ${registryIds.length} registries for '${registry}' (${registryIds.join(", ")}). Set deploy.dokploy.registryId in gkm.config.ts to the one this workspace pushes with.`);
1915
+ this.registry = registry;
1916
+ this.registryIds = registryIds;
1917
+ this.name = "RegistryAmbiguous";
1918
+ }
1919
+ };
1920
+ /** `https://ghcr.io/acme/` → `{ host: 'ghcr.io', path: 'acme' }`. */
1921
+ function parts(url) {
1922
+ const [host = "", ...path] = url.replace(/^[a-z]+:\/\//i, "").replace(/\/+$/, "").toLowerCase().split("/");
1923
+ return {
1924
+ host,
1925
+ path: path.join("/")
1926
+ };
1927
+ }
1928
+ /**
1929
+ * The Dokploy registries that serve `registry`: the same host, and — where
1930
+ * Dokploy's own entry names one — the same path.
1931
+ */
1932
+ function serving(registries, registry) {
1933
+ const wanted = parts(registry);
1934
+ const sameHost = registries.filter((r) => parts(r.registryUrl ?? "").host === wanted.host);
1935
+ if (sameHost.length <= 1) return sameHost;
1936
+ return sameHost.filter((r) => {
1937
+ return (parts(r.registryUrl ?? "").path || (r.imagePrefix ?? "").toLowerCase()) === wanted.path;
1938
+ });
1939
+ }
1940
+ /** `registry.one`, or `null` when Dokploy says it has no such registry. */
1941
+ async function registryById(api, registryId) {
1942
+ try {
1943
+ return await api.getRegistry(registryId) ?? null;
1944
+ } catch (error) {
1945
+ if (error instanceof require_sniffer.DokployApiError) return null;
1946
+ throw error;
1947
+ }
1948
+ }
1949
+ /**
1950
+ * The registry id for a stage, in order: the configured id, the one in the
1951
+ * stage's state, the one Dokploy has for the configured registry URL, and
1952
+ * otherwise a new one. Never a registry the workspace did not point at.
1953
+ */
1954
+ async function resolveRegistry(api, options) {
1955
+ const { stage, registry, configuredId, stateId, log = () => {} } = options;
1956
+ if (!registry) throw new RegistryNotConfigured(stage);
1957
+ if (configuredId) {
1958
+ const configured = await registryById(api, configuredId);
1959
+ if (!configured) throw new RegistryNotFound(configuredId);
1960
+ return configured;
1961
+ }
1962
+ if (stateId) {
1963
+ const known = await registryById(api, stateId);
1964
+ if (known) return known;
1965
+ log(` ⚠ The stage's registry ${stateId} no longer exists in Dokploy`);
1966
+ }
1967
+ const matches = serving(await api.listRegistries(), registry);
1968
+ if (matches.length > 1) throw new RegistryAmbiguous(registry, matches.map((r) => r.registryId));
1969
+ if (matches[0]) return matches[0];
1970
+ return options.create(registry);
1971
+ }
1972
+ //#endregion
1973
+ //#region src/deploy/secrets.ts
1974
+ /**
1975
+ * Filter secrets to only include the env vars that an app requires.
1976
+ *
1977
+ * @param stageSecrets - All secrets for the stage
1978
+ * @param sniffedEnv - The sniffed environment requirements for the app
1979
+ * @returns Filtered secrets with found/missing tracking
1980
+ */
1981
+ function filterSecretsForApp(stageSecrets, sniffedEnv) {
1982
+ const allSecrets = require_storage.toEmbeddableSecrets(stageSecrets);
1983
+ const filtered = {};
1984
+ const found = [];
1985
+ const missing = [];
1986
+ for (const key of sniffedEnv.requiredEnvVars) if (key in allSecrets) {
1987
+ filtered[key] = allSecrets[key];
1988
+ found.push(key);
1989
+ } else missing.push(key);
1990
+ return {
1991
+ appName: sniffedEnv.appName,
1992
+ secrets: filtered,
1993
+ found: found.sort(),
1994
+ missing: missing.sort()
1995
+ };
1996
+ }
1997
+ /**
1998
+ * Encrypt filtered secrets for an app.
1999
+ * Generates an ephemeral master key that should be injected into Dokploy.
2000
+ *
2001
+ * @param filteredSecrets - The filtered secrets for the app
2002
+ * @returns Encrypted payload with master key
2003
+ */
2004
+ function encryptSecretsForApp(filteredSecrets) {
2005
+ const payload = require_sniffer.encryptSecrets(filteredSecrets.secrets);
2006
+ return {
2007
+ appName: filteredSecrets.appName,
2008
+ payload,
2009
+ masterKey: payload.masterKey,
2010
+ secretCount: Object.keys(filteredSecrets.secrets).length,
2011
+ missingSecrets: filteredSecrets.missing
2012
+ };
2013
+ }
2014
+ /**
2015
+ * Filter and encrypt secrets for an app in one step.
2016
+ *
2017
+ * @param stageSecrets - All secrets for the stage
2018
+ * @param sniffedEnv - The sniffed environment requirements for the app
2019
+ * @returns Encrypted secrets with master key
2020
+ */
2021
+ function prepareSecretsForApp(stageSecrets, sniffedEnv) {
2022
+ return encryptSecretsForApp(filterSecretsForApp(stageSecrets, sniffedEnv));
2023
+ }
2024
+ /**
2025
+ * Prepare secrets for multiple apps.
2026
+ *
2027
+ * @param stageSecrets - All secrets for the stage
2028
+ * @param sniffedApps - Map of app name to sniffed environment
2029
+ * @returns Map of app name to encrypted secrets
2030
+ */
2031
+ function prepareSecretsForAllApps(stageSecrets, sniffedApps) {
2032
+ const results = /* @__PURE__ */ new Map();
2033
+ for (const [appName, sniffedEnv] of sniffedApps) if (sniffedEnv.requiredEnvVars.length > 0) {
2034
+ const encrypted = prepareSecretsForApp(stageSecrets, sniffedEnv);
2035
+ results.set(appName, encrypted);
2036
+ }
2037
+ return results;
2038
+ }
2039
+ /**
2040
+ * Generate a report on secrets preparation.
2041
+ */
2042
+ function generateSecretsReport(encryptedApps, sniffedApps) {
2043
+ const appsWithSecrets = [];
2044
+ const appsWithoutSecrets = [];
2045
+ const appsWithMissingSecrets = [];
2046
+ for (const [appName, sniffedEnv] of sniffedApps) {
2047
+ if (sniffedEnv.requiredEnvVars.length === 0) {
2048
+ appsWithoutSecrets.push(appName);
2049
+ continue;
2050
+ }
2051
+ const encrypted = encryptedApps.get(appName);
2052
+ if (encrypted) {
2053
+ appsWithSecrets.push(appName);
2054
+ if (encrypted.missingSecrets.length > 0) appsWithMissingSecrets.push({
2055
+ appName,
2056
+ missing: encrypted.missingSecrets
2057
+ });
2058
+ }
2059
+ }
2060
+ return {
2061
+ totalApps: sniffedApps.size,
2062
+ appsWithSecrets: appsWithSecrets.sort(),
2063
+ appsWithoutSecrets: appsWithoutSecrets.sort(),
2064
+ appsWithMissingSecrets
2065
+ };
2066
+ }
2067
+ //#endregion
2068
+ //#region src/deploy/terminal.ts
2069
+ /**
2070
+ * The credentials `gkm deploy` can ask a person for. CLI layer only.
2071
+ *
2072
+ * `deploy()` asks its `CredentialProvider` and stops with `MissingCredential`
2073
+ * when the answer is nothing. At a terminal, `gkm deploy` would rather ask:
2074
+ * this provider reads the environment and the stored login first, and only
2075
+ * when both are empty prompts — and stores a Dokploy login it validated, so
2076
+ * the next deploy does not ask again. With no terminal it answers nothing, and
2077
+ * the deploy says what was missing instead of waiting on a prompt nobody sees.
2078
+ */
2079
+ const logger$1 = require_discover.output;
2080
+ /** What answers a deploy prompt without a terminal. */
2081
+ const INSTEAD = "Please configure manually.";
2082
+ /** The Dokploy URL typed at the prompt is not a URL. */
2083
+ var DokployEndpointInvalid = class extends Error {
2084
+ endpoint;
2085
+ constructor(endpoint) {
2086
+ super("Invalid URL format");
2087
+ this.endpoint = endpoint;
2088
+ this.name = "DokployEndpointInvalid";
2089
+ }
2090
+ };
2091
+ /** Dokploy refused the token typed at the prompt; nothing was stored. */
2092
+ var DokployTokenRejected = class extends Error {
2093
+ endpoint;
2094
+ constructor(endpoint) {
2095
+ super("Invalid credentials. Please check your token.");
2096
+ this.endpoint = endpoint;
2097
+ this.name = "DokployTokenRejected";
2098
+ }
2099
+ };
2100
+ /** Asks the person at the terminal for what nothing else supplied. */
2101
+ function asking() {
2102
+ return { async get(asked) {
2103
+ if (!require_sniffer.canPrompt()) return void 0;
2104
+ const request = asked;
2105
+ if (request.kind === "dokploy") {
2106
+ logger$1.log("\n📋 Dokploy credentials not found. Let's set them up.");
2107
+ const endpoint = (await require_sniffer.prompt("Dokploy URL (e.g., https://dokploy.example.com): ", { instead: INSTEAD })).replace(/\/$/, "");
2108
+ try {
2109
+ new URL(endpoint);
2110
+ } catch {
2111
+ throw new DokployEndpointInvalid(endpoint);
2112
+ }
2113
+ logger$1.log(`\nGenerate a token at: ${endpoint}/settings/profile\n`);
2114
+ const token = await require_sniffer.prompt("API Token: ", {
2115
+ hidden: true,
2116
+ instead: INSTEAD
2117
+ });
2118
+ logger$1.log("\nValidating credentials...");
2119
+ if (!await require_sniffer.validateDokployToken(endpoint, token)) throw new DokployTokenRejected(endpoint);
2120
+ await require_sniffer.storeDokployCredentials(token, endpoint);
2121
+ logger$1.log("✓ Credentials saved");
2122
+ return {
2123
+ endpoint,
2124
+ token
2125
+ };
2126
+ }
2127
+ logger$1.log(` Dokploy has no registry for ${request.url}. Let's create one.`);
2128
+ return {
2129
+ username: await require_sniffer.prompt("Registry username: ", { instead: INSTEAD }),
2130
+ password: await require_sniffer.prompt("Registry password/token: ", {
2131
+ hidden: true,
2132
+ instead: INSTEAD
2133
+ })
2134
+ };
2135
+ } };
2136
+ }
2137
+ /**
2138
+ * The environment, then the stored login, then — at a terminal — the person
2139
+ * running the command.
2140
+ */
2141
+ function terminalCredentials(base = storedCredentials()) {
2142
+ return chainCredentials(base, asking());
2143
+ }
2144
+ //#endregion
2145
+ //#region src/deploy/index.ts
2146
+ /**
2147
+ * Deploy Module
2148
+ *
2149
+ * Handles deployment of GKM workspaces to various providers (Docker, Dokploy).
2150
+ *
2151
+ * ## Per-App Database Credentials
2152
+ *
2153
+ * When deploying to Dokploy with Postgres, this module creates per-app database
2154
+ * users with isolated schemas. This follows the same pattern as local dev mode
2155
+ * (docker/postgres/init.sh).
2156
+ *
2157
+ * ### How It Works
2158
+ *
2159
+ * 1. **Provisioning**: Creates Postgres service with master credentials
2160
+ * 2. **User Creation**: For each backend app that needs DATABASE_URL:
2161
+ * - Generates a unique password (stored in deploy state)
2162
+ * - Creates a database user with that password
2163
+ * - Assigns schema permissions based on app name
2164
+ * 3. **Schema Assignment**:
2165
+ * - `api` app: Uses `public` schema (shared tables)
2166
+ * - Other apps (e.g., `auth`): Get their own schema with `search_path` set
2167
+ * 4. **Environment Injection**: Each app receives its own DATABASE_URL
2168
+ *
2169
+ * ### Security
2170
+ *
2171
+ * - External Postgres port is enabled only during user creation, then disabled
2172
+ * - Each app can only access its own schema
2173
+ * - Credentials are stored in `.gkm/deploy-{stage}.json` (gitignored)
2174
+ * - Subsequent deploys reuse existing credentials from state
2175
+ *
2176
+ * ### Example Flow
2177
+ *
2178
+ * ```
2179
+ * gkm deploy --stage production
2180
+ * ├─ Create Postgres (user: postgres, db: myproject)
2181
+ * ├─ Enable external port temporarily
2182
+ * ├─ Create user "api" → public schema
2183
+ * ├─ Create user "auth" → auth schema (search_path=auth)
2184
+ * ├─ Disable external port
2185
+ * ├─ Deploy "api" with DATABASE_URL=postgresql://api:xxx@postgres:5432/myproject
2186
+ * └─ Deploy "auth" with DATABASE_URL=postgresql://auth:yyy@postgres:5432/myproject
2187
+ * ```
2188
+ *
2189
+ * @module deploy
2190
+ */
2191
+ const logger = require_discover.output;
2192
+ /**
2193
+ * Wait for Postgres to be ready to accept connections.
2194
+ *
2195
+ * Polls the Postgres server until it accepts a connection or max retries reached.
2196
+ * Used after enabling the external port to ensure the database is accessible
2197
+ * before creating users.
2198
+ *
2199
+ * @param host - The Postgres server hostname
2200
+ * @param port - The external port (typically 5432)
2201
+ * @param user - Master database user (postgres)
2202
+ * @param password - Master database password
2203
+ * @param database - Database name to connect to
2204
+ * @param maxRetries - Maximum number of connection attempts (default: 30)
2205
+ * @param retryIntervalMs - Milliseconds between retries (default: 2000)
2206
+ * @throws Error if Postgres is not ready after maxRetries
2207
+ */
2208
+ async function waitForPostgres(host, port, user, password, database, maxRetries = 30, retryIntervalMs = 2e3) {
2209
+ for (let i = 0; i < maxRetries; i++) try {
2210
+ const client = new pg.Client({
2211
+ host,
2212
+ port,
2213
+ user,
2214
+ password,
2215
+ database,
2216
+ connectionTimeoutMillis: 5e3
2217
+ });
2218
+ client.on("error", () => {});
2219
+ await client.connect();
2220
+ await client.end();
2221
+ return;
2222
+ } catch {
2223
+ if (i < maxRetries - 1) {
2224
+ logger.log(` Waiting for Postgres... (${i + 1}/${maxRetries})`);
2225
+ await new Promise((r) => setTimeout(r, retryIntervalMs));
2226
+ }
2227
+ }
2228
+ throw new PostgresNotReady(host, port, maxRetries);
2229
+ }
2230
+ /** A Postgres published for the role DDL never accepted a connection. */
2231
+ var PostgresNotReady = class extends Error {
2232
+ host;
2233
+ port;
2234
+ attempts;
2235
+ constructor(host, port, attempts) {
2236
+ super(`Postgres not ready after ${attempts} retries (${host}:${port}). Check that the port is reachable from here — a firewall in front of the server drops it silently — and deploy again.`);
2237
+ this.host = host;
2238
+ this.port = port;
2239
+ this.attempts = attempts;
2240
+ this.name = "PostgresNotReady";
2241
+ }
2242
+ };
2243
+ /** No port could be published for a cluster, so its DDL cannot reach it. */
2244
+ var PostgresPortUnavailable = class extends Error {
2245
+ appName;
2246
+ taken;
2247
+ constructor(appName, taken) {
2248
+ super(`Could not publish a port for ${appName}. In use on this server: ${[...taken].sort((a, b) => a - b).join(", ") || "none reported"}. The role DDL needs to reach the cluster from here.`);
2249
+ this.appName = appName;
2250
+ this.taken = taken;
2251
+ this.name = "PostgresPortUnavailable";
2252
+ }
2253
+ };
2254
+ /**
2255
+ * Run the manifest's DDL against a Dokploy Postgres.
2256
+ *
2257
+ * The cluster is only reachable from outside while an external port is
2258
+ * published, so this opens one, applies, and leaves it as it found it. The
2259
+ * alternative — running DDL from inside the network — needs a container to run
2260
+ * it in, which is what `DatabaseBootstrap` is on AWS and what a Dokploy target
2261
+ * has no equivalent for yet.
2262
+ *
2263
+ * The applier is the local target's, so every statement asks whether it is
2264
+ * needed first: a redeploy is free, and a half-applied run recovers by being
2265
+ * run again.
2266
+ */
2267
+ /**
2268
+ * A high port for one service, the same one every time.
2269
+ *
2270
+ * Derived from the service name rather than random so two deploys of the same
2271
+ * database agree and two different databases do not collide — and in the
2272
+ * ephemeral range, above anything a server is likely to have bound
2273
+ * deliberately.
2274
+ */
2275
+ function derivedPort(appName) {
2276
+ const digest = (0, node_crypto.createHash)("sha256").update(appName).digest();
2277
+ return 49152 + (digest[0] << 8 | digest[1]) % 16e3;
2278
+ }
2279
+ async function applyDeclaredStatements(api, postgres, serverHostname, statements) {
2280
+ let externalPort = await api.getPostgres(postgres.postgresId).then((current) => current.externalPort).catch(() => null) ?? void 0;
2281
+ const opened = externalPort === void 0;
2282
+ if (externalPort === void 0) {
2283
+ const taken = await api.publishedPorts().catch(() => /* @__PURE__ */ new Set());
2284
+ const candidates = [5432, derivedPort(postgres.appName)].filter((port) => !taken.has(port));
2285
+ for (const candidate of candidates) try {
2286
+ await api.savePostgresExternalPort(postgres.postgresId, candidate);
2287
+ externalPort = candidate;
2288
+ break;
2289
+ } catch (error) {
2290
+ if (!(error instanceof Error ? error.message : String(error)).includes("already in use")) throw error;
2291
+ logger.log(` Port ${candidate} is taken; trying another...`);
2292
+ }
2293
+ if (externalPort === void 0) throw new PostgresPortUnavailable(postgres.appName, [...taken]);
2294
+ logger.log(` Publishing ${postgres.appName} on ${externalPort}...`);
2295
+ }
2296
+ await api.deployPostgres(postgres.postgresId);
2297
+ await waitForPostgres(serverHostname, externalPort, postgres.databaseUser, postgres.databasePassword, postgres.databaseName);
2298
+ const client = { async query(database, sql, values) {
2299
+ const connection = new pg.Client({
2300
+ host: serverHostname,
2301
+ port: externalPort,
2302
+ user: postgres.databaseUser,
2303
+ password: postgres.databasePassword,
2304
+ database: database ?? postgres.databaseName,
2305
+ connectionTimeoutMillis: 15e3
2306
+ });
2307
+ connection.on("error", () => {});
2308
+ await connection.connect();
2309
+ try {
2310
+ return (await connection.query(sql, values)).rows;
2311
+ } finally {
2312
+ await connection.end();
2313
+ }
2314
+ } };
2315
+ const unpublish = async () => {
2316
+ if (!opened) return;
2317
+ await api.savePostgresExternalPort(postgres.postgresId, null).then(() => api.deployPostgres(postgres.postgresId)).catch(() => {
2318
+ logger.log(` ⚠ Could not close external port ${externalPort} on ${postgres.appName} — close it in Dokploy.`);
2319
+ });
2320
+ };
2321
+ let lastError;
2322
+ try {
2323
+ for (let attempt = 1; attempt <= 3; attempt++) try {
2324
+ return await applyDeclared(client, statements);
2325
+ } catch (error) {
2326
+ lastError = error;
2327
+ if (attempt === 3) break;
2328
+ const message = error instanceof Error ? error.message : String(error);
2329
+ logger.log(` ⏳ Cluster still settling (${message}); retrying (${attempt}/2)...`);
2330
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
2331
+ await waitForPostgres(serverHostname, externalPort, postgres.databaseUser, postgres.databasePassword, postgres.databaseName).catch(() => {});
2332
+ }
2333
+ throw lastError;
2334
+ } finally {
2335
+ await unpublish();
2336
+ }
2337
+ }
2338
+ /**
2339
+ * Get the server hostname from the Dokploy endpoint URL
2340
+ */
2341
+ function getServerHostname(endpoint) {
2342
+ return new URL(endpoint).hostname;
2343
+ }
2344
+ /**
2345
+ * Generate image tag from stage and timestamp
2346
+ */
2347
+ function generateTag(stage) {
2348
+ return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
2349
+ }
2350
+ /**
2351
+ * The things this deploy creates a container for.
2352
+ *
2353
+ * A deploy unit is a *declaration*, not a config entry — and since that is now
2354
+ * true of every app, not just the ones being deployed, this is the workspace's
2355
+ * own derivation under the name the deploy phases call it by.
2356
+ */
2357
+ function deployUnits(manifest, workspace) {
2358
+ return require_config.derivedApps(manifest, workspace);
2359
+ }
2360
+ /**
2361
+ * The variables an app cannot start without.
2362
+ *
2363
+ * The sniffer reports every key it saw in `requiredEnvVars` and says which of
2364
+ * them were read through `.optional()` or `.default()` in `optionalEnvVars`.
2365
+ * Reading only the first treats a key that is *absent by design* as a missing
2366
+ * secret — `AUTH_COOKIE_DOMAIN` is published only when a surface has a domain
2367
+ * to widen a cookie to, and one host has nothing to share it with.
2368
+ *
2369
+ * The same distinction `bundleServer` draws. It is drawn twice because the
2370
+ * bundle and the deploy each validate, and the deploy was the half still
2371
+ * failing on an answer that was correct.
2372
+ */
2373
+ function requiredOf(requirements) {
2374
+ if (!requirements) return [];
2375
+ const optional = new Set(requirements.optionalEnvVars);
2376
+ return requirements.requiredEnvVars.map((name) => name.endsWith("?") ? name.slice(0, -1) : name).filter((name) => !optional.has(name));
2377
+ }
2378
+ /** Apps were asked for by name that the workspace does not have. */
2379
+ var UnknownDeployApps = class extends Error {
2380
+ apps;
2381
+ available;
2382
+ constructor(apps, available) {
2383
+ super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
2384
+ this.apps = apps;
2385
+ this.available = available;
2386
+ this.name = "UnknownDeployApps";
2387
+ }
2388
+ };
2389
+ /** Every app asked for deploys somewhere other than Dokploy. */
2390
+ var NoDeployableApps = class extends Error {
2391
+ stage;
2392
+ constructor(stage) {
2393
+ super("No apps to deploy. All selected apps have unsupported deploy targets.");
2394
+ this.stage = stage;
2395
+ this.name = "NoDeployableApps";
2396
+ }
2397
+ };
2398
+ /** A backend failed, so the run stopped before deploying anything after it. */
2399
+ var BackendDeployFailed = class extends Error {
2400
+ app;
2401
+ constructor(app, cause) {
2402
+ super(`Backend deployment failed for ${app}. Aborting to prevent partial deployment.`, { cause });
2403
+ this.app = app;
2404
+ this.name = "BackendDeployFailed";
2405
+ }
2406
+ };
2407
+ /** An app's environment needs values the stage does not have. */
2408
+ var MissingEnvVars = class extends Error {
2409
+ app;
2410
+ missing;
2411
+ stage;
2412
+ constructor(app, missing, stage) {
2413
+ super(formatMissingVarsError(app, [...missing], stage));
2414
+ this.app = app;
2415
+ this.missing = missing;
2416
+ this.stage = stage;
2417
+ this.name = "MissingEnvVars";
2418
+ }
2419
+ };
2420
+ /** Workspace deploys go to Dokploy; another provider was asked for. */
2421
+ var DeployProviderUnsupported = class extends Error {
2422
+ provider;
2423
+ constructor(provider) {
2424
+ super(`Workspace deployment only supports Dokploy. Got: ${provider}`);
2425
+ this.provider = provider;
2426
+ this.name = "DeployProviderUnsupported";
2427
+ }
2428
+ };
2429
+ /** How `resolveProject` found a project, in the journal's words. */
2430
+ const PROJECT_VIA = {
2431
+ state: "recorded",
2432
+ marker: "found",
2433
+ created: "created"
2434
+ };
2435
+ /**
2436
+ * Deploy every app in a workspace to Dokploy.
2437
+ *
2438
+ * Two-phase orchestration:
2439
+ * - PHASE 1: Deploy backend apps (with encrypted secrets)
2440
+ * - PHASE 2: Deploy frontend apps (with public URLs from backends)
2441
+ *
2442
+ * Security model:
2443
+ * - Backend apps get encrypted secrets embedded at build time
2444
+ * - Only GKM_MASTER_KEY is injected as Dokploy env var
2445
+ * - Frontend apps get public URLs baked in at build time (no secrets)
2446
+ *
2447
+ * The engine under `deploy()` and `gkm deploy`. It never prompts and never
2448
+ * exits: credentials come from `ctx.credentials`, progress goes to
2449
+ * `ctx.emit` and to `output`, and every failure is thrown.
2450
+ *
2451
+ * @internal
2452
+ */
2453
+ async function runDeploy(source, request, ctx) {
2454
+ const { stage, tag, apps: selectedApps } = request;
2455
+ ctx.emit({
2456
+ type: "phase.started",
2457
+ phase: "validate"
2458
+ });
2459
+ const configured = typeof source === "function" ? await source() : source;
2460
+ const manifest = await require_discover.discover({
2461
+ patterns: require_sniffer.constructGlobs(configured),
2462
+ cwd: configured.root
2463
+ });
2464
+ const units = deployUnits(manifest, configured);
2465
+ const workspace = Object.keys(units).length > 0 ? {
2466
+ ...configured,
2467
+ apps: units
2468
+ } : configured;
2469
+ const identity = require_store.deployIdentity(workspace, stage);
2470
+ logger.log(`\n🚀 Deploying workspace "${workspace.name}" to Dokploy...`);
2471
+ logger.log(` Stage: ${stage}`);
2472
+ const imageTag = tag ?? generateTag(stage);
2473
+ logger.log(` Tag: ${imageTag}`);
2474
+ const buildOrder = require_workspace.getAppBuildOrder(workspace);
2475
+ let appsToDeployNames = buildOrder;
2476
+ if (selectedApps && selectedApps.length > 0) {
2477
+ const invalidApps = selectedApps.filter((name) => !workspace.apps[name]);
2478
+ if (invalidApps.length > 0) throw new UnknownDeployApps(invalidApps, Object.keys(workspace.apps));
2479
+ appsToDeployNames = buildOrder.filter((name) => selectedApps.includes(name));
2480
+ logger.log(` Deploying apps: ${appsToDeployNames.join(", ")}`);
2481
+ } else logger.log(` Deploying all apps: ${appsToDeployNames.join(", ")}`);
2482
+ const skipped = [];
2483
+ const skip = (app, reason) => {
2484
+ skipped.push({
2485
+ app,
2486
+ reason
2487
+ });
2488
+ ctx.emit({
2489
+ type: "app.skipped",
2490
+ app,
2491
+ reason
2492
+ });
2493
+ };
2494
+ const dokployApps = appsToDeployNames.filter((name) => {
2495
+ const target = workspace.apps[name].resolvedDeployTarget;
2496
+ if (target === "sst") {
2497
+ const reason = `it deploys with SST — run \`gkm build && sst deploy --stage ${stage}\``;
2498
+ logger.log(` ⚠️ Skipping ${name}: ${reason}`);
2499
+ skip(name, reason);
2500
+ return false;
2501
+ }
2502
+ if (!require_workspace.isDeployTargetSupported(target)) {
2503
+ const reason = require_workspace.getDeployTargetError(target, name);
2504
+ logger.log(` ⚠️ Skipping ${name}: ${reason}`);
2505
+ skip(name, reason);
2506
+ return false;
2507
+ }
2508
+ return true;
2509
+ });
2510
+ if (dokployApps.length === 0) throw new NoDeployableApps(stage);
2511
+ appsToDeployNames = dokployApps;
2512
+ for (const name of appsToDeployNames) if (workspace.apps[name].type === "mobile") skip(name, MOBILE_SKIP_REASON);
2513
+ ctx.emit({
2514
+ type: "deploy.started",
2515
+ stage,
2516
+ identity: identity.key,
2517
+ tag: imageTag,
2518
+ apps: appsToDeployNames.filter((name) => workspace.apps[name].type !== "mobile"),
2519
+ dryRun: ctx.dryRun
2520
+ });
2521
+ const store = await require_sniffer.createStateStore({
2522
+ config: workspace.state,
2523
+ workspaceRoot: workspace.root,
2524
+ workspaceName: workspace.name
2525
+ });
2526
+ const run = {
2527
+ workspace,
2528
+ manifest,
2529
+ stage,
2530
+ imageTag,
2531
+ appsToDeployNames,
2532
+ identity,
2533
+ store,
2534
+ skipped,
2535
+ ctx
2536
+ };
2537
+ if (ctx.dryRun) return planDeploy(run);
2538
+ const lock = await store.lock(stage, { operation: "deploy" });
2539
+ try {
2540
+ return await deployLocked(run);
2541
+ } finally {
2542
+ await lock.release();
2543
+ }
2544
+ }
2545
+ /**
2546
+ * The stage's secrets and every app's environment requirements. A dry run
2547
+ * reads the secrets and generates nothing into the store.
2548
+ */
2549
+ async function preflight({ workspace, manifest, stage, ctx }) {
2550
+ logger.log("\n🔐 Loading secrets and analyzing environment requirements...");
2551
+ const secretsStore = await require_store.secretsStoreFor(workspace, stage, { ...ctx.home ? { home: ctx.home } : {} });
2552
+ const stored = await secretsStore.read(stage);
2553
+ if (!stored) logger.log(` ⚠️ No secrets found for stage "${stage}"; starting them`);
2554
+ const { secrets: stageSecrets, generated } = withGeneratedSecrets(stored ?? require_storage.initStageSecrets(stage), manifest);
2555
+ if (generated.length > 0) {
2556
+ if (ctx.dryRun) logger.log(` 🔑 Would generate for "${stage}" (${secretsStore.name}): ${generated.join(", ")}`);
2557
+ else {
2558
+ await secretsStore.write(stage, stageSecrets);
2559
+ logger.log(` 🔑 Generated for "${stage}" (${secretsStore.name}): ${generated.join(", ")}`);
2560
+ }
2561
+ }
2562
+ const sniffedApps = await require_sniffer.sniffAllApps(workspace.apps, workspace.root);
2563
+ const encryptedSecrets = stageSecrets ? prepareSecretsForAllApps(stageSecrets, sniffedApps) : /* @__PURE__ */ new Map();
2564
+ if (stageSecrets) {
2565
+ const report = generateSecretsReport(encryptedSecrets, sniffedApps);
2566
+ if (report.appsWithSecrets.length > 0) logger.log(` ✓ Encrypted secrets for: ${report.appsWithSecrets.join(", ")}`);
2567
+ if (report.appsWithMissingSecrets.length > 0) for (const { appName, missing } of report.appsWithMissingSecrets) logger.log(` ⚠️ ${appName}: Missing secrets: ${missing.join(", ")}`);
2568
+ }
2569
+ return {
2570
+ stageSecrets,
2571
+ sniffedApps,
2572
+ encryptedSecrets
2573
+ };
2574
+ }
2575
+ /** Everything a deploy does while it holds the stage's lock. */
2576
+ async function deployLocked(run) {
2577
+ const { workspace, manifest, stage, imageTag, appsToDeployNames, identity, store, ctx } = run;
2578
+ const { stageSecrets, sniffedApps, encryptedSecrets } = await preflight(run);
2579
+ ctx.emit({
2580
+ type: "phase.finished",
2581
+ phase: "validate"
2582
+ });
2583
+ const changes = [];
2584
+ const applied = (change, via) => {
2585
+ changes.push(change);
2586
+ ctx.emit({
2587
+ type: "resource.applied",
2588
+ ...change,
2589
+ via
2590
+ });
2591
+ };
2592
+ ctx.signal?.throwIfAborted();
2593
+ ctx.emit({
2594
+ type: "phase.started",
2595
+ phase: "provision"
2596
+ });
2597
+ const { api, endpoint } = await dokployApi(workspace, ctx);
2598
+ logger.log("\n📋 Loading deploy state...");
2599
+ const journal = await DeployJournal.open(store, stage, () => createEmptyState(stage, "", ""));
2600
+ const state = journal.state;
2601
+ if (journal.existed) logger.log(` Found existing state for stage "${stage}"`);
2602
+ else logger.log(` Creating new state for stage "${stage}"`);
2603
+ const unfinished = journal.unfinished();
2604
+ if (unfinished.length > 0) logger.log(` ⚠ A previous run stopped while creating: ${unfinished.join(", ")} — looking for them before creating anything`);
2605
+ logger.log("\n📁 Setting up Dokploy project...");
2606
+ logger.log(` Identity: ${identity.key}`);
2607
+ const projectEntry = {
2608
+ key: "project",
2609
+ type: "project",
2610
+ data: {
2611
+ name: require_store.projectName(identity),
2612
+ identity: identity.key
2613
+ }
2614
+ };
2615
+ const project = await resolveProject(api, identity, state.projectId || void 0, (message) => logger.log(message), { beforeCreate: () => journal.pending(projectEntry) });
2616
+ await journal.ready(projectEntry, project.projectId);
2617
+ applied({
2618
+ key: "project",
2619
+ resourceType: "project",
2620
+ action: project.via === "created" ? "create" : "reuse",
2621
+ id: project.projectId
2622
+ }, PROJECT_VIA[project.via]);
2623
+ if (project.via === "created") logger.log(` ✓ Created project: ${project.projectId}`);
2624
+ else logger.log(` Found existing project: ${project.name}`);
2625
+ const environmentEntry = {
2626
+ key: "environment",
2627
+ type: "environment",
2628
+ data: { name: stage }
2629
+ };
2630
+ const environment = await journal.ensure(environmentEntry, {
2631
+ find: async () => project.environments.find((e) => e.name.toLowerCase() === stage.toLowerCase()),
2632
+ create: () => {
2633
+ logger.log(` Creating "${stage}" environment...`);
2634
+ return api.createEnvironment(project.projectId, stage);
2635
+ },
2636
+ id: (e) => e.environmentId
2637
+ });
2638
+ const environmentId = environment.resource.environmentId;
2639
+ applied({
2640
+ key: "environment",
2641
+ resourceType: "environment",
2642
+ action: environment.via === "created" ? "create" : "reuse",
2643
+ id: environmentId
2644
+ }, environment.via);
2645
+ if (environment.via === "created") logger.log(` ✓ Created environment: ${stage}`);
2646
+ else logger.log(` Using environment: ${environment.resource.name}`);
2647
+ if (journal.existed) {
2648
+ if (state.projectId && state.projectId !== project.projectId) logger.log(` ⚠ Project ID changed, updating state`);
2649
+ if (state.environmentId && state.environmentId !== environmentId) logger.log(` ⚠ Environment ID changed, updating state`);
2650
+ }
2651
+ state.projectId = project.projectId;
2652
+ state.environmentId = environmentId;
2653
+ state.identity = identity.key;
2654
+ logger.log("\n🐳 Checking registry...");
2655
+ const registry = workspace.deploy.dokploy?.registry;
2656
+ let registryCreated = false;
2657
+ const dokployRegistry = await resolveRegistry(api, {
2658
+ stage,
2659
+ registry,
2660
+ configuredId: workspace.deploy.dokploy?.registryId,
2661
+ stateId: state.registryId,
2662
+ log: (message) => logger.log(message),
2663
+ create: async (url) => {
2664
+ const login = await ctx.credentials.get({
2665
+ kind: "registry",
2666
+ url
2667
+ }, { signal: ctx.signal });
2668
+ if (!login) throw new MissingCredential("registry", url);
2669
+ const created = await api.createRegistry("Default Registry", url, login.username, login.password);
2670
+ registryCreated = true;
2671
+ logger.log(` ✓ Registry created: ${created.registryId}`);
2672
+ return created;
2673
+ }
2674
+ });
2675
+ const registryId = dokployRegistry.registryId;
2676
+ state.registryId = registryId;
2677
+ applied({
2678
+ key: "registry",
2679
+ resourceType: "registry",
2680
+ action: registryCreated ? "create" : "reuse",
2681
+ id: registryId
2682
+ }, registryCreated ? "created" : "found");
2683
+ logger.log(` Using registry: ${dokployRegistry.registryName}`);
2684
+ await journal.save();
2685
+ const skippedMobileApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "mobile");
2686
+ if (skippedMobileApps.length > 0) logger.log(`\n📱 Skipping ${skippedMobileApps.length} mobile app(s) — deploy via framework toolchain: ${skippedMobileApps.join(", ")}`);
2687
+ let declaredEnv = {};
2688
+ let declaredClusters = {};
2689
+ {
2690
+ logger.log("\n📦 Provisioning declared constructs...");
2691
+ const appUrls = {};
2692
+ for (const appName of appsToDeployNames) {
2693
+ if (workspace.apps[appName]?.type !== "backend") continue;
2694
+ appUrls[appName] = `https://${hostOf(workspace, appName, stage)}`;
2695
+ }
2696
+ const declared = await provisionDeclared({
2697
+ api,
2698
+ workspace,
2699
+ projectId: project.projectId,
2700
+ environmentId,
2701
+ stage,
2702
+ scope: identity.scope,
2703
+ appUrls,
2704
+ supplied: stageSecrets.custom,
2705
+ seed: stageSecrets.seed,
2706
+ manifest
2707
+ });
2708
+ declaredEnv = declared.env;
2709
+ declaredClusters = declared.clusters;
2710
+ if (Object.keys(declaredEnv).length > 0) logger.log(` 🔌 Resolved ${Object.keys(declaredEnv).length} declared URL(s)`);
2711
+ if (declared.statements.length > 0) {
2712
+ const serverHostname = getServerHostname(endpoint);
2713
+ for (const [databaseName, cluster] of Object.entries(declared.clusters)) {
2714
+ const statements = declared.statements.filter((statement) => statement.database === databaseName);
2715
+ if (statements.length === 0) continue;
2716
+ const created = await applyDeclaredStatements(api, cluster, serverHostname, statements);
2717
+ logger.log(` 🗄️ ${databaseName}: applied ${statements.length} statement(s), ${created} new`);
2718
+ }
2719
+ }
2720
+ }
2721
+ const backupCluster = Object.values(declaredClusters)[0];
2722
+ if (workspace.deploy?.backups && backupCluster) {
2723
+ logger.log("\n💾 Provisioning backup destination...");
2724
+ const { provisionBackupDestination } = await Promise.resolve().then(() => require("./backup-provisioner-BmhIO_Yr.cjs"));
2725
+ const backupState = await provisionBackupDestination({
2726
+ api,
2727
+ projectId: project.projectId,
2728
+ projectName: identity.scope,
2729
+ stage,
2730
+ config: workspace.deploy.backups,
2731
+ existingState: getBackupState(state),
2732
+ logger
2733
+ });
2734
+ setBackupState(state, backupState);
2735
+ if (!backupState.postgresBackupId) {
2736
+ const backupSchedule = workspace.deploy.backups.schedule ?? "0 2 * * *";
2737
+ const backupRetention = workspace.deploy.backups.retention ?? 30;
2738
+ logger.log(" Creating postgres backup schedule...");
2739
+ setPostgresBackupId(state, (await api.createPostgresBackup({
2740
+ schedule: backupSchedule,
2741
+ prefix: `${stage}/postgres`,
2742
+ destinationId: backupState.destinationId,
2743
+ database: backupCluster.databaseName,
2744
+ postgresId: backupCluster.postgresId,
2745
+ enabled: true,
2746
+ keepLatestCount: backupRetention
2747
+ })).backupId);
2748
+ logger.log(` ✓ Postgres backup schedule created (${backupSchedule})`);
2749
+ } else logger.log(" ✓ Using existing postgres backup schedule");
2750
+ }
2751
+ ctx.emit({
2752
+ type: "phase.finished",
2753
+ phase: "provision"
2754
+ });
2755
+ const backendApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "backend");
2756
+ const frontendApps = appsToDeployNames.filter((name) => workspace.apps[name].type === "web");
2757
+ const publicUrls = {};
2758
+ const results = [];
2759
+ const appHostnames = /* @__PURE__ */ new Map();
2760
+ const appDomainIds = /* @__PURE__ */ new Map();
2761
+ /** An app is up: say so, and remember where. */
2762
+ const deployed = (appName, result, host) => {
2763
+ const url = `https://${host}`;
2764
+ results.push({
2765
+ ...result,
2766
+ success: true,
2767
+ url
2768
+ });
2769
+ ctx.emit({
2770
+ type: "app.deployed",
2771
+ app: appName,
2772
+ applicationId: result.applicationId,
2773
+ imageRef: result.imageRef,
2774
+ url
2775
+ });
2776
+ };
2777
+ /** An app failed: say so, and record it in the result. */
2778
+ const failed = (appName, app, error) => {
2779
+ const message = error instanceof Error ? error.message : "Unknown error";
2780
+ logger.log(` ✗ Failed to deploy ${appName}: ${message}`);
2781
+ results.push({
2782
+ appName,
2783
+ type: app.type,
2784
+ success: false,
2785
+ error: message
2786
+ });
2787
+ ctx.emit({
2788
+ type: "app.failed",
2789
+ app: appName,
2790
+ error: eventError(error)
2791
+ });
2792
+ };
2793
+ /** An image is pushed: worth keeping even if what follows fails. */
2794
+ const built = async (appName, image, ref) => {
2795
+ setDeployedImage(state, appName, {
2796
+ ref: image.imageRef ?? ref,
2797
+ ...image.digest ? { digest: image.digest } : {}
2798
+ });
2799
+ await journal.save();
2800
+ ctx.emit({
2801
+ type: "artifact.built",
2802
+ app: appName,
2803
+ imageRef: image.imageRef ?? ref,
2804
+ ...image.digest ? { digest: image.digest } : {}
2805
+ });
2806
+ changes.push({
2807
+ key: `image:${appName}`,
2808
+ resourceType: "image",
2809
+ action: "build",
2810
+ id: image.digest ?? image.imageRef ?? ref
2811
+ });
2812
+ };
2813
+ const frontendUrls = [];
2814
+ for (const appName of frontendApps) frontendUrls.push(`https://${hostOf(workspace, appName, stage)}`);
2815
+ ctx.signal?.throwIfAborted();
2816
+ ctx.emit({
2817
+ type: "phase.started",
2818
+ phase: "release"
2819
+ });
2820
+ if (backendApps.length > 0) {
2821
+ logger.log("\n📦 PHASE 1: Deploying backend applications...");
2822
+ for (const appName of backendApps) {
2823
+ ctx.signal?.throwIfAborted();
2824
+ const app = workspace.apps[appName];
2825
+ logger.log(`\n ⚙️ Deploying ${appName}...`);
2826
+ try {
2827
+ const application = await ensureApplication(api, journal, appName, require_store.applicationName(identity, appName), project.projectId, environmentId, applied);
2828
+ const appSecrets = encryptedSecrets.get(appName);
2829
+ const credentials = appSecrets && appSecrets.secretCount > 0 ? {
2830
+ encrypted: appSecrets.payload.encrypted,
2831
+ iv: appSecrets.payload.iv
2832
+ } : void 0;
2833
+ if (appSecrets && credentials) logger.log(` Encrypted ${appSecrets.secretCount} secrets`);
2834
+ const imageRef$1 = require_store.imageRef(identity, appName, registry, imageTag);
2835
+ logger.log(` Building Docker image: ${imageRef$1}`);
2836
+ const image = await deployDocker({
2837
+ stage,
2838
+ tag: imageTag,
2839
+ skipPush: false,
2840
+ config: {
2841
+ registry,
2842
+ imageName: require_store.imageName(identity, appName),
2843
+ appName
2844
+ },
2845
+ credentials,
2846
+ ...dockerRun(workspace, app, ctx)
2847
+ });
2848
+ await built(appName, image, imageRef$1);
2849
+ const backendHost = hostOf(workspace, appName, stage);
2850
+ const dependencyUrls = {};
2851
+ if (app.dependencies) {
2852
+ for (const dep of app.dependencies) if (publicUrls[dep]) dependencyUrls[dep] = publicUrls[dep];
2853
+ }
2854
+ const envContext = {
2855
+ app,
2856
+ appName,
2857
+ stage,
2858
+ state,
2859
+ appHostname: backendHost,
2860
+ frontendUrls,
2861
+ userSecrets: stageSecrets ?? void 0,
2862
+ masterKey: appSecrets?.masterKey,
2863
+ dependencyUrls
2864
+ };
2865
+ const sniffedVars = requiredOf(sniffedApps.get(appName));
2866
+ const { valid, missing, resolved } = validateEnvVars([.../* @__PURE__ */ new Set([
2867
+ "PORT",
2868
+ "NODE_ENV",
2869
+ "STAGE",
2870
+ ...sniffedVars
2871
+ ])], envContext);
2872
+ if (!valid) throw new MissingEnvVars(appName, missing, stage);
2873
+ const withDeclared = {
2874
+ ...resolved,
2875
+ ...declaredEnv
2876
+ };
2877
+ const envVars = Object.entries(withDeclared).map(([key, value]) => `${key}=${value}`);
2878
+ if (Object.keys(withDeclared).length > 0) logger.log(` Resolved ${Object.keys(withDeclared).length} env vars: ${Object.keys(withDeclared).sort().join(", ")}`);
2879
+ await api.saveDockerProvider(application.applicationId, imageRef$1, { registryId });
2880
+ await api.saveApplicationEnv(application.applicationId, envVars.join("\n"));
2881
+ logger.log(` Deploying to Dokploy...`);
2882
+ await api.deployApplication(application.applicationId);
2883
+ const domainId = await ensureDomain(api, journal, backendHost, app.port, application.applicationId, applied);
2884
+ appHostnames.set(appName, backendHost);
2885
+ if (domainId) appDomainIds.set(appName, domainId);
2886
+ publicUrls[appName] = `https://${backendHost}`;
2887
+ deployed(appName, {
2888
+ appName,
2889
+ type: app.type,
2890
+ applicationId: application.applicationId,
2891
+ imageRef: imageRef$1,
2892
+ ...image.digest ? { digest: image.digest } : {}
2893
+ }, backendHost);
2894
+ logger.log(` ✓ ${appName} deployed successfully`);
2895
+ } catch (error) {
2896
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
2897
+ failed(appName, app, error);
2898
+ throw new BackendDeployFailed(appName, error);
2899
+ }
2900
+ }
2901
+ }
2902
+ if (frontendApps.length > 0) {
2903
+ logger.log("\n🌐 PHASE 2: Deploying frontend applications...");
2904
+ for (const appName of frontendApps) {
2905
+ ctx.signal?.throwIfAborted();
2906
+ const app = workspace.apps[appName];
2907
+ logger.log(`\n 🌐 Deploying ${appName}...`);
2908
+ try {
2909
+ const application = await ensureApplication(api, journal, appName, require_store.applicationName(identity, appName), project.projectId, environmentId, applied);
2910
+ const dependencyUrls = {};
2911
+ if (app.dependencies) {
2912
+ for (const dep of app.dependencies) if (publicUrls[dep]) dependencyUrls[dep] = publicUrls[dep];
2913
+ }
2914
+ const frontendHost = hostOf(workspace, appName, stage);
2915
+ const envContext = {
2916
+ app,
2917
+ appName,
2918
+ stage,
2919
+ state,
2920
+ appHostname: frontendHost,
2921
+ frontendUrls: [],
2922
+ userSecrets: stageSecrets ?? void 0,
2923
+ dependencyUrls
2924
+ };
2925
+ const { valid, missing, resolved } = validateEnvVars(requiredOf(sniffedApps.get(appName)), envContext);
2926
+ if (!valid) throw new MissingEnvVars(appName, missing, stage);
2927
+ if (Object.keys(resolved).length > 0) logger.log(` Resolved ${Object.keys(resolved).length} env vars: ${Object.keys(resolved).join(", ")}`);
2928
+ const publicPrefix = require_workspace.getPublicEnvPrefix(app.framework);
2929
+ const buildArgs = [];
2930
+ const publicUrlArgNames = [];
2931
+ if (publicPrefix) {
2932
+ for (const [key, value] of Object.entries(resolved)) if (key.startsWith(publicPrefix)) {
2933
+ buildArgs.push(`${key}=${value}`);
2934
+ publicUrlArgNames.push(key);
2935
+ }
2936
+ }
2937
+ if (buildArgs.length > 0) logger.log(` Build args: ${publicUrlArgNames.join(", ")}`);
2938
+ const imageRef$2 = require_store.imageRef(identity, appName, registry, imageTag);
2939
+ logger.log(` Building Docker image: ${imageRef$2}`);
2940
+ const image = await deployDocker({
2941
+ stage,
2942
+ tag: imageTag,
2943
+ skipPush: false,
2944
+ config: {
2945
+ registry,
2946
+ imageName: require_store.imageName(identity, appName),
2947
+ appName
2948
+ },
2949
+ buildArgs,
2950
+ publicUrlArgs: publicUrlArgNames,
2951
+ ...dockerRun(workspace, app, ctx)
2952
+ });
2953
+ await built(appName, image, imageRef$2);
2954
+ const envVars = [
2955
+ `NODE_ENV=production`,
2956
+ `PORT=${app.port}`,
2957
+ `STAGE=${stage}`
2958
+ ];
2959
+ for (const [key, value] of Object.entries(resolved)) envVars.push(`${key}=${value}`);
2960
+ await api.saveDockerProvider(application.applicationId, imageRef$2, { registryId });
2961
+ await api.saveApplicationEnv(application.applicationId, envVars.join("\n"));
2962
+ logger.log(` Deploying to Dokploy...`);
2963
+ await api.deployApplication(application.applicationId);
2964
+ const domainId = await ensureDomain(api, journal, frontendHost, app.port, application.applicationId, applied);
2965
+ appHostnames.set(appName, frontendHost);
2966
+ if (domainId) appDomainIds.set(appName, domainId);
2967
+ publicUrls[appName] = `https://${frontendHost}`;
2968
+ deployed(appName, {
2969
+ appName,
2970
+ type: app.type,
2971
+ applicationId: application.applicationId,
2972
+ imageRef: imageRef$2,
2973
+ ...image.digest ? { digest: image.digest } : {}
2974
+ }, frontendHost);
2975
+ logger.log(` ✓ ${appName} deployed successfully`);
2976
+ } catch (error) {
2977
+ if (ctx.signal?.aborted) throw ctx.signal.reason;
2978
+ failed(appName, app, error);
2979
+ }
2980
+ }
2981
+ }
2982
+ logger.log("\n📋 Saving deploy state...");
2983
+ await journal.save();
2984
+ logger.log(" ✓ State saved");
2985
+ ctx.emit({
2986
+ type: "phase.finished",
2987
+ phase: "release"
2988
+ });
2989
+ ctx.signal?.throwIfAborted();
2990
+ ctx.emit({
2991
+ type: "phase.started",
2992
+ phase: "verify"
2993
+ });
2994
+ const dnsConfig = workspace.deploy.dns;
2995
+ if (dnsConfig && appHostnames.size > 0) {
2996
+ const dnsResult = await orchestrateDns(appHostnames, dnsConfig, endpoint);
2997
+ if (dnsResult?.serverIp && appHostnames.size > 0) {
2998
+ await verifyDnsRecords(appHostnames, dnsResult.serverIp, state);
2999
+ await journal.save();
3000
+ }
3001
+ if (dnsResult?.success && appHostnames.size > 0) {
3002
+ logger.log("\n🔒 Validating domains for SSL certificates...");
3003
+ for (const [appName, hostname] of appHostnames) try {
3004
+ const result = await api.validateDomain(hostname);
3005
+ if (result.isValid) logger.log(` ✓ ${appName}: ${hostname} → ${result.resolvedIp}`);
3006
+ else logger.log(` ⚠ ${appName}: ${hostname} not valid`);
3007
+ } catch (validationError) {
3008
+ const message = validationError instanceof Error ? validationError.message : "Unknown error";
3009
+ logger.log(` ⚠ ${appName}: validation failed - ${message}`);
3010
+ }
3011
+ }
3012
+ }
3013
+ ctx.emit({
3014
+ type: "phase.finished",
3015
+ phase: "verify"
3016
+ });
3017
+ const successCount = results.filter((r) => r.success).length;
3018
+ const failedCount = results.filter((r) => !r.success).length;
3019
+ logger.log(`\n${"─".repeat(50)}`);
3020
+ logger.log(`\n✅ Workspace deployment complete!`);
3021
+ logger.log(` Project: ${project.projectId}`);
3022
+ logger.log(` Successful: ${successCount}`);
3023
+ if (failedCount > 0) logger.log(` Failed: ${failedCount}`);
3024
+ if (Object.keys(publicUrls).length > 0) {
3025
+ logger.log("\n 📡 Deployed URLs:");
3026
+ for (const [name, url] of Object.entries(publicUrls)) logger.log(` ${name}: ${url}`);
3027
+ }
3028
+ return {
3029
+ apps: results,
3030
+ projectId: project.projectId,
3031
+ environmentId,
3032
+ successCount,
3033
+ failedCount,
3034
+ stage,
3035
+ identity: identity.key,
3036
+ tag: imageTag,
3037
+ dryRun: false,
3038
+ skipped: run.skipped,
3039
+ urls: publicUrls,
3040
+ changes
3041
+ };
3042
+ }
3043
+ /**
3044
+ * An app's Dokploy application, through the journal: by the id recorded for
3045
+ * it, else by its name in the stage's environment, else created. Its id goes
3046
+ * into `state.applications` too, which the env resolver and `state:show` read.
3047
+ */
3048
+ async function ensureApplication(api, journal, appName, dokployAppName, projectId, environmentId, applied) {
3049
+ const recorded = journal.record(`application:${appName}`);
3050
+ if (recorded?.status === "ready" && recorded.id) logger.log(` Using cached ID: ${recorded.id}`);
3051
+ const { resource, via, staleId } = await journal.ensure({
3052
+ key: `application:${appName}`,
3053
+ type: "application",
3054
+ data: { name: dokployAppName }
3055
+ }, {
3056
+ get: (id) => api.getApplication(id),
3057
+ find: () => api.findApplicationByName(projectId, dokployAppName, environmentId),
3058
+ create: () => api.createApplication(dokployAppName, projectId, environmentId),
3059
+ id: (application) => application.applicationId
3060
+ });
3061
+ if (staleId) logger.log(` ⚠ Cached ID invalid, will create new`);
3062
+ logger.log(` ${{
3063
+ recorded: "✓ Application found",
3064
+ resumed: "Resumed application a stopped run created",
3065
+ found: "Found existing application",
3066
+ created: "Created application"
3067
+ }[via]}: ${resource.applicationId}`);
3068
+ applied({
3069
+ key: `application:${appName}`,
3070
+ resourceType: "application",
3071
+ action: via === "created" ? "create" : "reuse",
3072
+ id: resource.applicationId
3073
+ }, via);
3074
+ setApplicationId(journal.state, appName, resource.applicationId);
3075
+ return resource;
3076
+ }
3077
+ /**
3078
+ * The domain `host` routes to an application, through the journal — found on
3079
+ * the application before it is created, so a re-run never adds a second.
3080
+ *
3081
+ * A domain that cannot be created is reported and skipped rather than
3082
+ * failing the app: the application is deployed and reachable on Dokploy's
3083
+ * own address, and DNS is fixed by hand more easily than a half deploy.
3084
+ */
3085
+ async function ensureDomain(api, journal, host, port, applicationId, applied) {
3086
+ try {
3087
+ const { resource, via } = await journal.ensure({
3088
+ key: `domain:${host}`,
3089
+ type: "domain",
3090
+ data: {
3091
+ host,
3092
+ applicationId
3093
+ }
3094
+ }, {
3095
+ find: async () => (await api.getDomainsByApplicationId(applicationId)).find((d) => d.host === host),
3096
+ create: () => api.createDomain({
3097
+ host,
3098
+ port,
3099
+ https: true,
3100
+ certificateType: "letsencrypt",
3101
+ applicationId
3102
+ }),
3103
+ id: (domain) => domain.domainId
3104
+ });
3105
+ logger.log(` ✓ Domain: https://${host} (${via === "created" ? "created" : "existing"})`);
3106
+ applied({
3107
+ key: `domain:${host}`,
3108
+ resourceType: "domain",
3109
+ action: via === "created" ? "create" : "reuse",
3110
+ id: resource.domainId
3111
+ }, via);
3112
+ return resource.domainId;
3113
+ } catch (domainError) {
3114
+ if (domainError instanceof require_sniffer.StateVersionConflict || domainError instanceof require_sniffer.StateStoreBusy || isAbort(domainError)) throw domainError;
3115
+ const message = domainError instanceof Error ? domainError.message : "Unknown error";
3116
+ logger.log(` ⚠ Domain creation failed: ${message}`);
3117
+ return;
3118
+ }
3119
+ }
3120
+ /** Whether `error` is a run being stopped rather than something failing. */
3121
+ function isAbort(error) {
3122
+ return error instanceof Error && error.name === "AbortError";
3123
+ }
3124
+ /** Where docker runs for one app: in the app's own directory. */
3125
+ function dockerRun(workspace, app, ctx) {
3126
+ return {
3127
+ cwd: (0, node_path.resolve)(workspace.root, app.path),
3128
+ ...ctx.signal ? { signal: ctx.signal } : {},
3129
+ ...ctx.stdio ? { stdio: ctx.stdio } : {}
3130
+ };
3131
+ }
3132
+ /** The Dokploy login, from the run's provider, or `MissingCredential`. */
3133
+ async function dokployApi(workspace, ctx) {
3134
+ const configured = workspace.deploy.dokploy?.endpoint;
3135
+ const creds = await ctx.credentials.get({
3136
+ kind: "dokploy",
3137
+ ...configured ? { endpoint: configured } : {}
3138
+ }, { signal: ctx.signal });
3139
+ if (!creds) throw new MissingCredential("dokploy", configured);
3140
+ return {
3141
+ api: new require_sniffer.DokployApi({
3142
+ baseUrl: creds.endpoint,
3143
+ token: creds.token,
3144
+ ...ctx.signal ? { signal: ctx.signal } : {}
3145
+ }),
3146
+ endpoint: creds.endpoint
3147
+ };
3148
+ }
3149
+ /** Each app's public host, the same way the deploy resolves it. */
3150
+ function hostOf(workspace, appName, stage) {
3151
+ const app = workspace.apps[appName];
3152
+ return require_sniffer.resolveHost(appName, app, stage, workspace.deploy?.domains, app.type === "web" && require_sniffer.isMainFrontendApp(appName, app, workspace.apps));
3153
+ }
3154
+ /**
3155
+ * What a deploy would do, from the same lookups it starts with — and nothing
3156
+ * else: no lock, no state written, no secret generated, no Dokploy resource
3157
+ * created or changed, no image built or pushed.
3158
+ */
3159
+ async function planDeploy(run) {
3160
+ const { workspace, manifest, stage, imageTag, appsToDeployNames, identity } = run;
3161
+ const { ctx } = run;
3162
+ await preflight(run);
3163
+ ctx.emit({
3164
+ type: "phase.finished",
3165
+ phase: "validate"
3166
+ });
3167
+ ctx.signal?.throwIfAborted();
3168
+ ctx.emit({
3169
+ type: "phase.started",
3170
+ phase: "plan"
3171
+ });
3172
+ logger.log("\n🔎 Dry run: nothing will be created, changed, built or pushed.");
3173
+ const changes = [];
3174
+ const plan = (change, detail) => {
3175
+ changes.push(change);
3176
+ ctx.emit({
3177
+ type: "resource.planned",
3178
+ ...change
3179
+ });
3180
+ const sign = change.action === "reuse" ? "=" : "+";
3181
+ logger.log(` ${sign} ${change.action} ${change.key} (${detail})`);
3182
+ };
3183
+ const { api } = await dokployApi(workspace, ctx);
3184
+ const state = (await run.store.read(stage))?.state;
3185
+ const project = await findProject(api, identity, state?.projectId);
3186
+ if (project) plan({
3187
+ key: "project",
3188
+ resourceType: "project",
3189
+ action: "reuse",
3190
+ id: project.projectId
3191
+ }, project.needsClaim ? `${project.name}, would be claimed for ${identity.key}` : project.name);
3192
+ else plan({
3193
+ key: "project",
3194
+ resourceType: "project",
3195
+ action: "create"
3196
+ }, require_store.projectName(identity));
3197
+ const environment = project?.environments.find((e) => e.name.toLowerCase() === stage.toLowerCase());
3198
+ plan(environment ? {
3199
+ key: "environment",
3200
+ resourceType: "environment",
3201
+ action: "reuse",
3202
+ id: environment.environmentId
3203
+ } : {
3204
+ key: "environment",
3205
+ resourceType: "environment",
3206
+ action: "create"
3207
+ }, stage);
3208
+ let registryPlanned;
3209
+ const registry = await resolveRegistry(api, {
3210
+ stage,
3211
+ registry: workspace.deploy.dokploy?.registry,
3212
+ configuredId: workspace.deploy.dokploy?.registryId,
3213
+ stateId: state?.registryId,
3214
+ log: (message) => logger.log(message),
3215
+ create: async (url) => {
3216
+ registryPlanned = {
3217
+ key: "registry",
3218
+ resourceType: "registry",
3219
+ action: "create"
3220
+ };
3221
+ return {
3222
+ registryId: "",
3223
+ registryName: url
3224
+ };
3225
+ }
3226
+ });
3227
+ plan(registryPlanned ?? {
3228
+ key: "registry",
3229
+ resourceType: "registry",
3230
+ action: "reuse",
3231
+ id: registry.registryId
3232
+ }, registry.registryName);
3233
+ for (const [id, declaration] of Object.entries(manifest)) plan({
3234
+ key: `construct:${id}`,
3235
+ resourceType: declaration.kind,
3236
+ action: "ensure"
3237
+ }, declaration.kind);
3238
+ const apps = [];
3239
+ const urls = {};
3240
+ for (const appName of appsToDeployNames) {
3241
+ const app = workspace.apps[appName];
3242
+ if (app.type === "mobile") continue;
3243
+ const dokployAppName = require_store.applicationName(identity, appName);
3244
+ const recordedId = state?.applications?.[appName];
3245
+ const existing = project && environment ? (recordedId ? await api.getApplication(recordedId).catch(() => null) : null) ?? await api.findApplicationByName(project.projectId, dokployAppName, environment.environmentId) : null;
3246
+ plan(existing ? {
3247
+ key: `application:${appName}`,
3248
+ resourceType: "application",
3249
+ action: "reuse",
3250
+ id: existing.applicationId
3251
+ } : {
3252
+ key: `application:${appName}`,
3253
+ resourceType: "application",
3254
+ action: "create"
3255
+ }, dokployAppName);
3256
+ const ref = require_store.imageRef(identity, appName, workspace.deploy.dokploy?.registry, imageTag);
3257
+ plan({
3258
+ key: `image:${appName}`,
3259
+ resourceType: "image",
3260
+ action: "build"
3261
+ }, ref);
3262
+ const host = hostOf(workspace, appName, stage);
3263
+ const domain = existing ? (await api.getDomainsByApplicationId(existing.applicationId)).find((d) => d.host === host) : void 0;
3264
+ plan(domain ? {
3265
+ key: `domain:${host}`,
3266
+ resourceType: "domain",
3267
+ action: "reuse",
3268
+ id: domain.domainId
3269
+ } : {
3270
+ key: `domain:${host}`,
3271
+ resourceType: "domain",
3272
+ action: "create"
3273
+ }, `https://${host}`);
3274
+ urls[appName] = `https://${host}`;
3275
+ apps.push({
3276
+ appName,
3277
+ type: app.type,
3278
+ success: true,
3279
+ imageRef: ref,
3280
+ url: urls[appName],
3281
+ ...existing ? { applicationId: existing.applicationId } : {}
3282
+ });
3283
+ }
3284
+ const creates = changes.filter((c) => c.action !== "reuse").length;
3285
+ logger.log(`\n✅ Dry run complete: ${creates} to create or build, ${changes.length - creates} to reuse.`);
3286
+ ctx.emit({
3287
+ type: "phase.finished",
3288
+ phase: "plan"
3289
+ });
3290
+ return {
3291
+ apps,
3292
+ projectId: project?.projectId ?? "",
3293
+ environmentId: environment?.environmentId ?? "",
3294
+ successCount: apps.length,
3295
+ failedCount: 0,
3296
+ stage,
3297
+ identity: identity.key,
3298
+ tag: imageTag,
3299
+ dryRun: true,
3300
+ skipped: run.skipped,
3301
+ urls,
3302
+ changes
3303
+ };
3304
+ }
3305
+ /** Why a mobile app is left out of a Dokploy deploy. */
3306
+ const MOBILE_SKIP_REASON = "deploys via its framework toolchain";
3307
+ //#endregion
3308
+ //#region src/deploy/deploy.ts
3309
+ /**
3310
+ * `deploy()`: a deploy as a library call.
3311
+ *
3312
+ * `gkm deploy` could only be driven from an interactive terminal: it prompted
3313
+ * for what it lacked and exited the process on failure, worked out of
3314
+ * `process.cwd()`, and reported progress by printing. Here the caller says
3315
+ * where the project is, hands over the credentials and a signal, and gets back
3316
+ * a run — events to iterate while it goes, and a structured result at the end.
3317
+ * Nothing below this asks a person anything or ends the process; `gkm deploy`
3318
+ * is a thin wrapper that does both.
3319
+ */
3320
+ /**
3321
+ * Every event a run emits, kept so that each iteration — however late it
3322
+ * starts — sees the run from its first event to its last.
3323
+ */
3324
+ var EventLog = class {
3325
+ events = [];
3326
+ closed = false;
3327
+ waiting = [];
3328
+ push(event) {
3329
+ this.events.push(event);
3330
+ this.wake();
3331
+ }
3332
+ close() {
3333
+ this.closed = true;
3334
+ this.wake();
3335
+ }
3336
+ wake() {
3337
+ const waiting = this.waiting;
3338
+ this.waiting = [];
3339
+ for (const resume of waiting) resume();
3340
+ }
3341
+ async *iterate() {
3342
+ let next = 0;
3343
+ while (true) if (next < this.events.length) yield this.events[next++];
3344
+ else if (this.closed) return;
3345
+ else await new Promise((resume) => this.waiting.push(resume));
3346
+ }
3347
+ };
3348
+ /** `childOutput` as `spawn` reads it, where it is not the default. */
3349
+ const CHILD_STDIO = {
3350
+ stderr: [
3351
+ "ignore",
3352
+ 2,
3353
+ 2
3354
+ ],
3355
+ ignore: "ignore"
3356
+ };
3357
+ function forward(logger, level, message) {
3358
+ if (!logger) return;
3359
+ if (level === "info") logger.info(message);
3360
+ else if (level === "error" && logger.error) logger.error(message);
3361
+ else logger.warn(message);
3362
+ }
3363
+ /**
3364
+ * Deploy a project's stage.
3365
+ *
3366
+ * ```ts
3367
+ * import { deploy } from '@geekmidas/cli/deploy';
3368
+ *
3369
+ * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
3370
+ * for await (const event of run) {
3371
+ * if (event.type === 'app.deployed') console.log(event.app, event.url);
3372
+ * }
3373
+ * const result = await run.result;
3374
+ * ```
3375
+ *
3376
+ * The run starts at once; iterating it is optional, and an iteration started
3377
+ * late still sees every event from the first.
3378
+ */
3379
+ function deploy(input) {
3380
+ const log = new EventLog();
3381
+ const emit = (event) => {
3382
+ log.push(event);
3383
+ if (event.type === "log") forward(input.logger, event.level, event.message);
3384
+ };
3385
+ const ctx = {
3386
+ emit,
3387
+ credentials: input.credentials ?? storedCredentials({ home: input.home ?? require_home.gkmHome() }),
3388
+ dryRun: input.dryRun ?? false,
3389
+ home: input.home ?? require_home.gkmHome(),
3390
+ ...input.signal ? { signal: input.signal } : {},
3391
+ ...input.childOutput && input.childOutput !== "inherit" ? { stdio: CHILD_STDIO[input.childOutput] } : {}
3392
+ };
3393
+ const result = require_discover.withOutput((level, message) => emit({
3394
+ type: "log",
3395
+ level,
3396
+ message
3397
+ }), async () => {
3398
+ try {
3399
+ input.signal?.throwIfAborted();
3400
+ const deployed = await runDeploy(() => load(input), {
3401
+ stage: input.stage,
3402
+ ...input.tag ? { tag: input.tag } : {},
3403
+ ...input.apps ? { apps: input.apps } : {}
3404
+ }, ctx);
3405
+ emit({
3406
+ type: "deploy.finished",
3407
+ result: deployed
3408
+ });
3409
+ return deployed;
3410
+ } catch (error) {
3411
+ emit({
3412
+ type: "deploy.failed",
3413
+ error: eventError(error)
3414
+ });
3415
+ throw error;
3416
+ } finally {
3417
+ log.close();
3418
+ }
3419
+ });
3420
+ result.catch(() => {});
3421
+ return {
3422
+ result,
3423
+ [Symbol.asyncIterator]: () => log.iterate()
3424
+ };
3425
+ }
3426
+ /** The workspace at `input.cwd`, refusing a stage it does not deploy. */
3427
+ async function load(input) {
3428
+ const { workspace } = await require_config.loadWorkspaceConfig((0, node_path.resolve)(input.cwd));
3429
+ require_workspace.assertDeployedStage(workspace.stages, input.stage);
3430
+ return workspace;
3431
+ }
3432
+ //#endregion
3433
+ Object.defineProperty(exports, "BackendDeployFailed", {
3434
+ enumerable: true,
3435
+ get: function() {
3436
+ return BackendDeployFailed;
3437
+ }
3438
+ });
3439
+ Object.defineProperty(exports, "DeployProviderUnsupported", {
3440
+ enumerable: true,
3441
+ get: function() {
3442
+ return DeployProviderUnsupported;
3443
+ }
3444
+ });
3445
+ Object.defineProperty(exports, "MissingCredential", {
3446
+ enumerable: true,
3447
+ get: function() {
3448
+ return MissingCredential;
3449
+ }
3450
+ });
3451
+ Object.defineProperty(exports, "MissingEnvVars", {
3452
+ enumerable: true,
3453
+ get: function() {
3454
+ return MissingEnvVars;
3455
+ }
3456
+ });
3457
+ Object.defineProperty(exports, "NoDeployableApps", {
3458
+ enumerable: true,
3459
+ get: function() {
3460
+ return NoDeployableApps;
3461
+ }
3462
+ });
3463
+ Object.defineProperty(exports, "ProjectNotOwned", {
3464
+ enumerable: true,
3465
+ get: function() {
3466
+ return ProjectNotOwned;
3467
+ }
3468
+ });
3469
+ Object.defineProperty(exports, "RegistryAmbiguous", {
3470
+ enumerable: true,
3471
+ get: function() {
3472
+ return RegistryAmbiguous;
3473
+ }
3474
+ });
3475
+ Object.defineProperty(exports, "RegistryNotConfigured", {
3476
+ enumerable: true,
3477
+ get: function() {
3478
+ return RegistryNotConfigured;
3479
+ }
3480
+ });
3481
+ Object.defineProperty(exports, "RegistryNotFound", {
3482
+ enumerable: true,
3483
+ get: function() {
3484
+ return RegistryNotFound;
3485
+ }
3486
+ });
3487
+ Object.defineProperty(exports, "UnknownDeployApps", {
3488
+ enumerable: true,
3489
+ get: function() {
3490
+ return UnknownDeployApps;
3491
+ }
3492
+ });
3493
+ Object.defineProperty(exports, "chainCredentials", {
3494
+ enumerable: true,
3495
+ get: function() {
3496
+ return chainCredentials;
3497
+ }
3498
+ });
3499
+ Object.defineProperty(exports, "deploy", {
3500
+ enumerable: true,
3501
+ get: function() {
3502
+ return deploy;
3503
+ }
3504
+ });
3505
+ Object.defineProperty(exports, "storedCredentials", {
3506
+ enumerable: true,
3507
+ get: function() {
3508
+ return storedCredentials;
3509
+ }
3510
+ });
3511
+ Object.defineProperty(exports, "terminalCredentials", {
3512
+ enumerable: true,
3513
+ get: function() {
3514
+ return terminalCredentials;
3515
+ }
3516
+ });
3517
+
3518
+ //# sourceMappingURL=deploy-0fBVeWO-.cjs.map