Repository navigation
Expand file tree
/
Copy pathdeploy.js
More file actions
executable file
·2715 lines (2376 loc) · 88.3 KB
/
Copy pathdeploy.js
File metadata and controls
executable file
·2715 lines (2376 loc) · 88.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* DollarDeploy CLI (ddc)
*/
const fs = require("fs");
const path = require("path");
const readline = require("readline");
const { execFileSync } = require("child_process");
const packageJson = require("./package.json");
const DEFAULT_PROVIDER = "hetzner";
const DEFAULT_BASE_URL = "https://dollardeploy.com";
const DEFAULT_TIMEOUT = 600000; // 10 minutes
const AUTH_DIR = path.join(require("os").homedir(), ".dollardeploy");
const AUTH_FILE = path.join(AUTH_DIR, "auth");
const PROVIDER_DEFAULTS = {
hetzner: {
type: "cax11",
region: "fsn1",
image: "ubuntu-24.04"
},
datacrunch: {
type: "CPU.4V.16G",
region: "FIN-01",
image: "ubuntu-24.04"
},
do: {
type: "s-2vcpu-4gb",
region: "fra1",
image: "ubuntu-24-04"
}
};
// User-facing provider aliases mapped to the identifier the API expects.
// "verda" is the current brand for the provider the API still calls "datacrunch".
const PROVIDER_ALIASES = {
verda: "datacrunch"
};
const normalizeProvider = provider =>
provider ? (PROVIDER_ALIASES[provider] ?? provider) : provider;
/** @type {typeof console & { verbose: (...args: any[]) => void }} */
const logger = {
...console,
/* eslint-disable-next-line no-console */
info: (...args) => console.error(...args),
/* eslint-disable-next-line no-console */
warn: (...args) => console.error(...args),
/* eslint-disable-next-line no-console */
error: (...args) => console.error(...args),
verbose: (...args) => {
if (process.env.NEXT_PUBLIC_LOG_VERBOSE === "1") {
/* eslint-disable-next-line no-console */
console.error(...args);
}
}
};
// ─── Output helpers (AI agent friendly) ──────────────────────────────────────
let jsonOutput = false;
const output = data => {
if (jsonOutput) {
logger.log(JSON.stringify(data, null, 2));
} else if (Array.isArray(data)) {
if (data.length === 0) {
logger.info("No results.");
return;
}
const keys = Object.keys(data[0]);
const widths = keys.map(k =>
Math.max(k.length, ...data.map(row => String(row[k] ?? "").length))
);
const header = keys.map((k, i) => k.padEnd(widths[i])).join(" ");
const separator = widths.map(w => "-".repeat(w)).join(" ");
logger.log(header);
logger.log(separator);
for (const row of data) {
logger.log(keys.map((k, i) => String(row[k] ?? "").padEnd(widths[i])).join(" "));
}
logger.log("total: " + data.length);
} else {
for (const [key, value] of Object.entries(data)) {
logger.log(`${key}: ${value}`);
}
}
};
// Render a value for plain-text (non-JSON) output. Arrays are comma-joined and
// objects (e.g. env, provision) become a compact `key=value` string instead of
// the useless `[object Object]`.
const formatFieldValue = value => {
if (value === null || value === undefined) {
return "";
}
if (Array.isArray(value)) {
return value
.map(item => (item && typeof item === "object" ? JSON.stringify(item) : String(item)))
.join(", ");
}
if (typeof value === "object") {
return Object.entries(value)
.map(([k, v]) => `${k}=${v && typeof v === "object" ? JSON.stringify(v) : v}`)
.join(", ");
}
return String(value);
};
// ─── Auth helpers ────────────────────────────────────────────────────────────
const findAuth = baseUrl => {
// 1. Environment variable takes priority
if (process.env.DOLLARDEPLOY_API_KEY) {
let parsedBaseUrl = undefined;
if (fs.existsSync(AUTH_FILE)) {
const content = fs.readFileSync(AUTH_FILE, "utf-8").trim();
const parsed = JSON.parse(content);
parsedBaseUrl = parsed.baseUrl;
}
return {
apiKey: process.env.DOLLARDEPLOY_API_KEY,
baseUrl:
baseUrl ?? parsedBaseUrl ?? process.env.DOLLARDEPLOY_BASE_URL ?? DEFAULT_BASE_URL
};
}
// 2. Stored auth file
try {
if (fs.existsSync(AUTH_FILE)) {
const content = fs.readFileSync(AUTH_FILE, "utf-8").trim();
const parsed = JSON.parse(content);
return {
apiKey: parsed.apiKey,
baseUrl:
baseUrl ?? parsed.baseUrl ?? process.env.DOLLARDEPLOY_BASE_URL ?? DEFAULT_BASE_URL
};
} else {
return {};
}
} catch {
throw new Error(
"Failed to read auth file. Run `ddc auth` to set it, use --api-key argument or DOLLARDEPLOY_API_KEY env var."
);
}
};
const updateAuth = (apiKey, baseUrl) => {
let existing = {};
if (fs.existsSync(AUTH_FILE)) {
existing = JSON.parse(fs.readFileSync(AUTH_FILE, "utf-8").trim());
}
fs.mkdirSync(AUTH_DIR, { recursive: true });
fs.writeFileSync(
AUTH_FILE,
JSON.stringify({ ...existing, apiKey, baseUrl }, null, 2) + "\n",
{
mode: 0o600
}
);
};
// ─── Prompt helper ───────────────────────────────────────────────────────────
const prompt = question =>
new Promise(resolve => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stderr
});
rl.question(question, answer => {
rl.close();
resolve(answer.trim());
});
});
const confirm = async question => {
if (process.stdin.isTTY) {
const answer = await prompt(`${question} [y/N] `);
return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
} else {
throw new Error("Not interactive mode. Use --yes to skip confirmation.");
}
};
// ─── API client ──────────────────────────────────────────────────────────────
/**
* @param {Object} auth
* @returns {Object} API client
*/
const createApiClient = auth => {
if (!auth.apiKey) {
throw new Error(
"API key is required. Run `ddc auth` to set it, or use --api-key or DOLLARDEPLOY_API_KEY."
);
}
const apiKey = auth.apiKey;
const baseUrl = auth.baseUrl ?? DEFAULT_BASE_URL;
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
"User-Agent": "DollarDeploy-CLI/" + packageJson.version
};
const apiError = (response, message) =>
Object.assign(
new Error(
`API Error (${response.url}: ${response.status}): ${message || response.statusText}`
),
{
url: response.url,
status: response.status,
statusText: response.statusText
}
);
const handleResponse = async response => {
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw apiError(response, body?.message);
}
if (response.status === 204) {
return {};
}
try {
return await response.json();
} catch (error) {
throw apiError(response, error.message);
}
};
const post = (url, body) => {
logger.verbose(`POST ${url}...`);
const startTime = Date.now();
return fetch(new URL(url, baseUrl).toString(), {
method: "POST",
headers,
body: JSON.stringify(body)
}).then(res => {
logger.verbose(`POST ${url} (status: ${res.status}) Δ ${Date.now() - startTime}ms`);
return handleResponse(res);
});
};
const patch = (url, body) => {
logger.verbose(`PATCH ${url}...`);
const startTime = Date.now();
return fetch(new URL(url, baseUrl).toString(), {
method: "PATCH",
headers,
body: JSON.stringify(body)
}).then(res => {
logger.verbose(`PATCH ${url} (status: ${res.status}) Δ ${Date.now() - startTime}ms`);
return handleResponse(res);
});
};
const del = url => {
logger.verbose(`DELETE ${url}...`);
const startTime = Date.now();
return fetch(new URL(url, baseUrl).toString(), {
method: "DELETE",
headers
}).then(res => {
logger.verbose(`DELETE ${url} (status: ${res.status}) Δ ${Date.now() - startTime}ms`);
return handleResponse(res);
});
};
const get = url => {
logger.verbose(`GET ${url}...`);
const startTime = Date.now();
return fetch(new URL(url, baseUrl).toString(), {
method: "GET",
headers
}).then(res => {
logger.verbose(`GET ${url} (status: ${res.status}) Δ ${Date.now() - startTime}ms`);
return handleResponse(res);
});
};
return {
baseUrl,
createHost: name => post("/api/host/create", { name }),
getHost: id => get(`/api/host/${id}`),
listHosts: status => get(`/api/host${status ? `?status=${status}` : ""}`),
updateHost: (id, data) => patch(`/api/host/${id}`, data),
deleteHost: id => del(`/api/host/${id}`),
getProvision: hostId =>
get(`/api/host/${hostId}/provision`).catch(err => {
if (err.status === 404) {
return undefined;
}
throw err;
}),
saveProvision: (hostId, data) => patch(`/api/host/${hostId}/provision`, data),
provisionHost: hostId => post(`/api/host/${hostId}/provision`),
getProviderConfig: (provider, filters = {}) =>
get(
`/api/provider/${provider}?` +
Object.entries(filters)
.filter(([, v]) => v !== undefined && v !== null && v !== "")
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
.join("&")
),
testConnection: hostId => post(`/api/host/${hostId}/test`),
prepareHost: hostId => post(`/api/host/${hostId}/prepare`),
createService: (hostId, type) => post(`/api/host/${hostId}/service/create`, { type }),
listServices: hostId => get(`/api/host/${hostId}/service`),
getService: (hostId, serviceId) => get(`/api/host/${hostId}/service/${serviceId}`),
deleteService: (hostId, serviceId) => del(`/api/host/${hostId}/service/${serviceId}`),
startProvision: hostId => post(`/api/host/${hostId}/provision`),
deprovisionHost: (hostId, deleteHost = true) =>
post(`/api/host/${hostId}/deprovision`, { deleteHost }),
getTask: id => get(`/api/task/${id}`),
listTasks: status => get(`/api/task${status ? `?status=${status}` : ""}`),
cancelTask: id => post(`/api/task/${id}/cancel`),
getTaskJournal: id => get(`/api/journal/latest?taskId=${id}`),
getLogs: params =>
get(
"/api/journal/latest?" +
Object.entries(params)
.filter(([, v]) => v !== undefined && v !== null && v !== "")
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
.join("&")
),
getTemplates: () => get("/api/template"),
getTemplate: id => get(`/api/template/${id}`),
launchTemplate: args => post("/api/task/launch", args),
getApp: id => get(`/api/app/${id}`),
getUser: () => get("/api/user"),
listApps: () => get("/api/app"),
createApp: args => post("/api/app/create", args),
suggestApp: app => post("/api/app/suggest", app),
updateApp: (id, data) => patch(`/api/app/${id}`, data),
buildApp: (id, options = {}) => post(`/api/app/${id}/build`, options),
deployApp: (id, options = {}) => post(`/api/app/${id}/deploy`, options),
deleteApp: id => del(`/api/app/${id}`),
removeApp: (id, options = { deleteApp: false }) => post(`/api/app/${id}/remove`, options),
listSshKeys: () => get("/api/settings/privateKey"),
createSshKey: data => post("/api/settings/privateKey/create", data),
deleteSshKey: id => del(`/api/settings/privateKey/${id}`),
listCrons: query => get(`/api/cron${query ? "?" + query : ""}`),
getCron: id => get(`/api/cron/${id}`),
createCron: data => post("/api/cron", data),
updateCron: (id, data) => patch(`/api/cron/${id}`, data),
deleteCron: id => del(`/api/cron/${id}`),
runCron: id => post(`/api/cron/${id}/run`, {}),
listCronRuns: (cronId, limit = 10) =>
get(`/api/cron/${encodeURIComponent(cronId)}/runs?limit=${limit}`)
};
};
// ─── Utility functions ───────────────────────────────────────────────────────
const shorten = (text, maxLength = 90) => {
if (!text) {
return "";
}
if (text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength - 3) + "...";
};
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const waitForTask = async (api, taskId, timeout = DEFAULT_TIMEOUT) => {
const startTime = Date.now();
const pollInterval = 2000;
logger.verbose(`Waiting for task ${taskId}...`);
while (Date.now() - startTime < timeout) {
const task = await api.getTask(taskId);
const journal = await api.getTaskJournal(taskId);
const message = shorten(journal.logs[0]?.message?.trim());
if (message) {
logger.info(`Task (${task.type}) ${task.status}: ${message}`);
} else {
logger.info(`Task (${task.type}) ${task.status}`);
}
if (task.status === "completed") {
if (task.nextTaskId) {
return await waitForTask(api, task.nextTaskId, timeout);
}
return task;
}
if (task.status === "error" || task.status === "cancelled") {
throw new Error(
`Task ${taskId} failed: ${task.status} (${shorten(journal.logs[0]?.message?.trim() ?? "No message")})`
);
}
await sleep(pollInterval);
}
throw new Error(`Task ${taskId} timed out after ${timeout}ms`);
};
const RETRY_HTTP_ERRORS = [502, 503, 504];
const checkUrl = async (url, maxRetries = 20, retryDelay = 2000) => {
logger.verbose(`Checking ${url}...`);
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, {
method: "GET",
headers: { "User-Agent": "DollarDeploy-CLI/" + packageJson.version },
signal: AbortSignal.timeout(10000)
});
if (!RETRY_HTTP_ERRORS.includes(response.status)) {
logger.verbose(`URL responding (status: ${response.status})`);
return response.status;
}
logger.verbose(`URL ${url} status ${response.status}, retrying...`);
} catch (error) {
logger.verbose(`Attempt ${i + 1}/${maxRetries}: ${error.message}`);
}
if (i < maxRetries - 1) {
await sleep(retryDelay);
}
}
throw new Error(`URL ${url} not accessible after ${maxRetries} attempts`);
};
// Verify the deployed URL is responding, but never fail the deploy over it —
// the app is already deployed, so a slow first boot shouldn't report an error.
const verifyDeployedUrl = async appUrl => {
logger.info(`Checking ${appUrl}...`);
try {
await checkUrl(appUrl);
logger.info(`Deployed: ${appUrl}`);
} catch (error) {
logger.warn(`Deployed, but ${appUrl} is not responding yet: ${error.message}`);
}
};
// ─── Local folder detection (git + env files) ────────────────────────────────
// Run a git command in `dir` and return trimmed stdout, or "" on any failure
// (not a repo, git missing, no remote). git errors are swallowed on purpose so
// detection degrades gracefully into a clear CLI message.
const runGit = (dir, args) => {
try {
return execFileSync("git", args, {
cwd: dir,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"]
}).trim();
} catch {
return "";
}
};
// Normalize any git remote URL to a plain https GitHub-style URL:
// git@github.com:org/repo.git -> https://github.com/org/repo
// ssh://git@github.com/org/repo.git -> https://github.com/org/repo
// https://user:token@github.com/... -> https://github.com/...
const normalizeRepoUrl = raw => {
if (!raw) {
return undefined;
}
let url = raw.trim();
const scpMatch = url.match(/^git@([^:]+):(.+)$/);
if (scpMatch) {
url = `https://${scpMatch[1]}/${scpMatch[2]}`;
}
url = url.replace(/^ssh:\/\/git@/, "https://").replace(/^git\+https:\/\//, "https://");
url = url.replace(/^(https?:\/\/)[^@/]+@/, "$1");
url = url.replace(/\/+$/, "").replace(/\.git$/, "");
return url;
};
// True when both URLs point to the same repository, ignoring the differences
// normalizeRepoUrl removes (trailing slash, .git, ssh form) and letter case.
const isSameRepo = (a, b) =>
!!a && !!b && normalizeRepoUrl(a).toLowerCase() === normalizeRepoUrl(b).toLowerCase();
// Pick an app name not used by any existing app: name, name2, name3, ...
const findAvailableAppName = (name, apps) => {
const taken = new Set(apps.map(app => app.name));
let candidate = name;
let index = 1;
while (taken.has(candidate)) {
index++;
candidate = name + index;
}
return candidate;
};
// Detect the git repository in `dir`: normalized remote URL, current branch,
// list of uncommitted changes, and count of commits not pushed upstream.
// Returns null when `dir` is not inside a git work tree.
const getGitInfo = dir => {
if (runGit(dir, ["rev-parse", "--is-inside-work-tree"]) !== "true") {
return null;
}
const branch = runGit(dir, ["rev-parse", "--abbrev-ref", "HEAD"]) || undefined;
let rawUrl = runGit(dir, ["remote", "get-url", "origin"]);
if (!rawUrl) {
const firstRemote = runGit(dir, ["remote"]).split("\n").filter(Boolean)[0];
if (firstRemote) {
rawUrl = runGit(dir, ["remote", "get-url", firstRemote]);
}
}
const status = runGit(dir, ["status", "--porcelain"]);
const dirty = status ? status.split("\n").filter(Boolean) : [];
const aheadRaw = runGit(dir, ["rev-list", "--count", "@{u}..HEAD"]);
const ahead = /^\d+$/.test(aheadRaw) ? parseInt(aheadRaw, 10) : 0;
return { repoUrl: normalizeRepoUrl(rawUrl), branch, dirty, ahead };
};
// Parse KEY=VALUE lines from a .env file body. Ignores blanks and comments,
// tolerates a leading `export `, and strips matching surrounding quotes.
const parseEnvFile = content => {
const env = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) {
continue;
}
const body = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed;
const eqIndex = body.indexOf("=");
if (eqIndex === -1) {
continue;
}
const key = body.slice(0, eqIndex).trim();
if (!key) {
continue;
}
let value = body.slice(eqIndex + 1).trim();
if (
value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")))
) {
value = value.slice(1, -1);
}
env[key] = value;
}
return env;
};
// Real env files are read in priority order (first match wins per key). Keys
// present only in .env.example (or empty everywhere) become placeholders the
// user must fill at dollardeploy.com.
const LOCAL_ENV_FILES = [
".env.production",
".env.prod",
".env.production.local",
".env.local"
];
const readLocalEnv = dir => {
const values = {};
const sources = {};
for (const file of LOCAL_ENV_FILES) {
const full = path.join(dir, file);
if (!fs.existsSync(full)) {
continue;
}
const parsed = parseEnvFile(fs.readFileSync(full, "utf8"));
for (const [key, value] of Object.entries(parsed)) {
if (value === "" || values[key] !== undefined) {
continue;
}
values[key] = value;
sources[key] = file;
}
}
const placeholders = [];
const examplePath = path.join(dir, ".env.example");
if (fs.existsSync(examplePath)) {
const example = parseEnvFile(fs.readFileSync(examplePath, "utf8"));
for (const key of Object.keys(example)) {
if (values[key] === undefined) {
placeholders.push(key);
}
}
}
return { values, sources, placeholders };
};
// Max number of env var names to list in the overview before summarizing the
// rest as "+ N more". Values are never printed (they may be secrets).
const MAX_ENV_PREVIEW = 5;
// Render a compact, capped list of names, e.g. "A, B, C, D, E + 3 more".
const formatNameList = names => {
if (names.length <= MAX_ENV_PREVIEW) {
return names.join(", ");
}
const shown = names.slice(0, MAX_ENV_PREVIEW).join(", ");
return `${shown} + ${names.length - MAX_ENV_PREVIEW} more`;
};
// Read-only preview of which host a local deploy will target, for the overview.
const resolveHostLabel = async (api, hostId, flags) => {
if (hostId) {
const host = await api.getHost(hostId).catch(() => null);
return host ? host.name || host.id : hostId;
}
if (flags["create-host"]) {
const provider = normalizeProvider(flags.provider) || DEFAULT_PROVIDER;
return `new ${provider} host (will be provisioned)`;
}
const activeHosts = (await api.listHosts("active")).filter(h => h.status === "active");
if (activeHosts.length === 1) {
return `${activeHosts[0].name || activeHosts[0].id} (only active host)`;
}
if (activeHosts.length > 1) {
return "multiple active hosts - pick one with --hostId <id>";
}
return "none - an app entry will be created, select a server at dollardeploy.com";
};
// Print the "what will be deployed" summary shown before a local-folder deploy.
const printDeployOverview = ({
repoUrl,
branch,
dirty,
ahead,
hostLabel,
values,
cliEnv,
placeholders,
appExisted,
canRedeploy
}) => {
logger.info("");
logger.info("Deploy overview");
logger.info(` Repository: ${repoUrl}`);
if (branch) {
logger.info(` Branch: ${branch}`);
}
logger.info(` Target host: ${hostLabel}`);
if (dirty.length > 0) {
logger.warn(
` Warning: ${dirty.length} uncommitted change(s) - the deploy builds from the remote, so uncommitted edits will not ship until committed and pushed.`
);
}
if (ahead > 0) {
logger.warn(
` Warning: ${ahead} commit(s) not pushed to the remote - they will not be included in this deploy.`
);
}
// When the app already exists, its configuration is left untouched - a local
// deploy only triggers a new build+deploy, so do not list env we won't apply.
if (appExisted) {
logger.info(" App already exists - its settings and env will not be changed.");
if (canRedeploy) {
logger.info(" This will trigger a redeploy of the existing app.");
}
logger.info("");
return;
}
const envKeys = Array.from(new Set([...Object.keys(values), ...Object.keys(cliEnv)])).sort();
if (envKeys.length > 0) {
logger.info(
` Environment variables (${envKeys.length}, values hidden): ${formatNameList(envKeys)}`
);
}
if (placeholders.length > 0) {
logger.info(
` Needs a value at dollardeploy.com (from .env.example): ${formatNameList(placeholders)}`
);
}
logger.info("");
};
// ─── Argument parser ─────────────────────────────────────────────────────────
const parseArgs = argv => {
const positional = [];
const flags = {};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--") {
positional.push(...argv.slice(i + 1));
break;
}
if (arg.startsWith("--")) {
const key = arg.slice(2);
const next = argv[i + 1];
if (next && !next.startsWith("--")) {
if (flags[key] !== undefined && key === "env") {
// Only allow multiple env values if the key is "env"
if (!Array.isArray(flags[key])) {
flags[key] = [flags[key]];
}
flags[key].push(next);
} else {
flags[key] = next;
}
i++;
} else {
flags[key] = true;
}
} else if (arg.startsWith("-") && arg.length === 2) {
const shortMap = { v: "verbose", j: "json", h: "help", V: "version", f: "follow" };
const mapped = shortMap[arg[1]];
if (mapped) {
flags[mapped] = true;
}
} else {
positional.push(arg);
}
}
return { positional, flags };
};
// ─── Commands ────────────────────────────────────────────────────────────────
const cmdAuth = async (_api, _positional, flags) => {
const apiKey = flags["api-key"] || flags.apiKey;
const baseUrl = flags["base-url"] || flags.baseUrl;
if (apiKey) {
updateAuth(apiKey, baseUrl);
logger.info("API key saved to ~/.dollardeploy/auth");
return;
}
// Interactive mode
const key = await prompt("Enter your DollarDeploy API key: ");
if (!key) {
logger.error("No API key provided. Aborting.");
process.exit(1);
}
updateAuth(key, baseUrl);
logger.info("API key saved to ~/.dollardeploy/auth");
};
const cmdHostList = async (api, _positional, flags) => {
const status = flags.status || undefined;
const hosts = await api.listHosts(status);
if (jsonOutput || flags.all) {
output(hosts);
return;
}
const rows = hosts.map(h => ({
id: h.id,
name: h.name || "",
status: h.status ?? "draft",
ip: h.ipAddress || "",
apps: h.apps?.length ?? 0,
createdAt: h.createdAt
}));
output(rows);
};
const cmdHostGet = async (api, positional, flags) => {
const hostId = positional[0] || flags.hostId;
const help = flags.help;
if (!hostId || help) {
logger.info("ddc host get <host-id> [--all]");
process.exit(hostId ? 0 : 1);
}
const host = await api.getHost(hostId);
const provision = await api.getProvision(hostId);
if (jsonOutput || flags.all) {
output({ ...host, provision });
return;
}
// Plain text: show all host fields except noisy objects, plus formatted provision.
const excluded = new Set(["health", "apps", "project"]);
const row = {};
for (const [key, value] of Object.entries(host)) {
if (excluded.has(key)) {
continue;
}
row[key] = formatFieldValue(value);
}
row.provision = provision ? formatFieldValue(provision) : "";
output(row);
};
const cmdAppList = async (api, _positional, flags) => {
const help = flags.help;
if (help) {
logger.info("ddc app list [--fields <fields>|--all]");
process.exit(0);
}
const apps = await api.listApps();
if (jsonOutput || flags.all) {
output(apps);
return;
}
const fields = flags.fields?.split(",") || [
"id",
"name",
"status",
"repositoryUrl",
"hostname"
];
const rows = apps.map(a =>
Object.fromEntries(
fields.map(f => [f, f === "hostname" && a[f] ? "https://" + a[f] : a[f]])
)
);
output(rows);
};
const cmdAppGet = async (api, positional, flags) => {
const appId = positional[0] || flags.appId;
const help = flags.help;
if (!appId || help) {
logger.info("ddc app get <app-id> [--fields <fields>|--all]");
process.exit(appId ? 0 : 1);
}
const app = await api.getApp(appId);
if (jsonOutput || flags.all) {
output(app);
return;
}
if (flags.fields) {
const fields = flags.fields.split(",");
output(
Object.fromEntries(
fields.map(f => [f, f === "hostname" && app[f] ? "https://" + app[f] : (app[f] ?? "")])
)
);
return;
}
// Plain text: show all app fields except noisy objects (host, project).
const excluded = new Set(["host", "project"]);
const row = {};
for (const [key, value] of Object.entries(app)) {
if (excluded.has(key)) {
continue;
}
row[key] = key === "hostname" && value ? "https://" + value : formatFieldValue(value);
}
output(row);
};
const cmdSshList = async (api, _positional, flags) => {
const sshKeys = await api.listSshKeys();
const name = flags.name;
const help = flags.help;
if (help) {
logger.info("ddc ssh list [--name <name>]");
process.exit(1);
}
const rows = sshKeys
.filter(k => (name ? k.name === name : true))
.map(k => ({
id: k.id,
name: k.name || "",
createdAt: k.createdAt,
fingerprint: k.fingerprint
}));
output(rows);
};
const cmdHostCreate = async (api, _positional, flags) => {
const name = flags.name || undefined;
const provider = normalizeProvider(flags.provider);
const providerType = flags.type || PROVIDER_DEFAULTS[provider]?.type;
const providerRegion = flags.region || PROVIDER_DEFAULTS[provider]?.region;
const image = flags.image || PROVIDER_DEFAULTS[provider]?.image;
const timeout = parseInt(flags.timeout) || DEFAULT_TIMEOUT;
const services = flags.services?.split(",") || ["docker"];
const skipPrepare = flags["skip-prepare"] === true;
logger.info("Creating host...");
const host = await api.createHost(name);
logger.info(`Host created: ${host.id} (${host.name})`);
if (provider) {
if (!providerType || !providerRegion || !image) {
throw new Error(
`Incomplete config for ${provider}: type=${providerType}, region=${providerRegion}, image=${image}`
);
}
logger.info(`Provisioning ${provider} (${providerType} in ${providerRegion})...`);
await api.saveProvision(host.id, {
provider,
providerType,
providerRegion,
image
});
const provisionTask = await api.startProvision(host.id);
await waitForTask(api, provisionTask.id, timeout);
logger.info("Instance provisioned.");
const updatedHost = await api.getHost(host.id);
if (updatedHost.status !== "active") {
throw new Error(`Host is not active. Status: ${updatedHost.status}`);
}
if (!skipPrepare) {
await api.updateHost(host.id, { swap: 4096 });
logger.info("Testing connection...");
await api.testConnection(host.id).then(task => waitForTask(api, task.id, timeout));
for (const type of services) {
const existingServices = await api.listServices(host.id);
if (!existingServices?.find(s => s.type === type)) {
logger.info(`Installing ${type}...`);
await api.createService(host.id, type);
}
}
logger.info("Preparing host...");
await api.prepareHost(host.id).then(task => waitForTask(api, task.id, timeout));
}
}
logger.info("Host ready.");
const finalHost = await api.getHost(host.id);
const provision = await api.getProvision(host.id);
output({
id: finalHost.id,
name: finalHost.name,
status: finalHost.status ?? "draft",
ip: finalHost.ipAddress || "<not assigned>",
provision: provision?.provider
});
};
const cmdHostDestroy = async (api, positional, flags) => {
const hostId = positional[0] || flags.hostId;
if (!hostId) {
logger.error("ddc host destroy <host-id>");
process.exit(1);
}
const timeout = parseInt(flags.timeout) || DEFAULT_TIMEOUT;
const host = await api.getHost(hostId);
if (!flags.yes && !flags.force) {
const ok = await confirm(
`This will deprovision and permanently delete host "${host.name || host.id}" (${host.ipAddress || "no IP"}).\nContinue?`
);
if (!ok) {
logger.info("Aborted.");
return;
}
}
// Remove all apps on the host first
if (host.apps?.length > 0) {
for (const app of host.apps) {