@camposcloud/cli 0.0.0-stage → 1.0.1

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 (43) hide show
  1. package/README.md +153 -2
  2. package/dist/commands/apps.js +197 -0
  3. package/dist/commands/auth.js +194 -0
  4. package/dist/commands/completion.js +94 -0
  5. package/dist/commands/create.js +220 -0
  6. package/dist/commands/dashboard.js +44 -0
  7. package/dist/commands/db.js +85 -0
  8. package/dist/commands/deploy.js +104 -0
  9. package/dist/commands/env.js +103 -0
  10. package/dist/commands/files.js +101 -0
  11. package/dist/commands/lang.js +34 -0
  12. package/dist/commands/manage.js +121 -0
  13. package/dist/commands/teams.js +127 -0
  14. package/dist/commands/utils.js +102 -0
  15. package/dist/core/api.js +157 -0
  16. package/dist/core/apiErrors.js +38 -0
  17. package/dist/core/apps.js +98 -0
  18. package/dist/core/config.js +34 -0
  19. package/dist/core/context.js +43 -0
  20. package/dist/core/credentials.js +90 -0
  21. package/dist/core/databases.js +53 -0
  22. package/dist/core/detect.js +75 -0
  23. package/dist/core/deviceLogin.js +49 -0
  24. package/dist/core/env.js +71 -0
  25. package/dist/core/files.js +51 -0
  26. package/dist/core/help.js +193 -0
  27. package/dist/core/i18n.js +581 -0
  28. package/dist/core/logs.js +87 -0
  29. package/dist/core/output.js +27 -0
  30. package/dist/core/project.js +119 -0
  31. package/dist/core/prompt.js +29 -0
  32. package/dist/core/session.js +21 -0
  33. package/dist/core/suggest.js +28 -0
  34. package/dist/core/teams.js +39 -0
  35. package/dist/core/update.js +48 -0
  36. package/dist/index.js +223 -0
  37. package/dist/tui/App.js +400 -0
  38. package/dist/tui/App.test.js +189 -0
  39. package/dist/tui/Picker.js +87 -0
  40. package/dist/tui/clickable.js +64 -0
  41. package/dist/tui/mouse.js +65 -0
  42. package/dist/tui/run.js +27 -0
  43. package/package.json +58 -4
@@ -0,0 +1,87 @@
1
+ /** Splits a stream of SSE text into events; keeps a partial event until the rest arrives. */
2
+ export class SseParser {
3
+ buffer = "";
4
+ push(chunk) {
5
+ this.buffer += chunk.replace(/\r\n/g, "\n");
6
+ const events = [];
7
+ let boundary;
8
+ while ((boundary = this.buffer.indexOf("\n\n")) !== -1) {
9
+ const block = this.buffer.slice(0, boundary);
10
+ this.buffer = this.buffer.slice(boundary + 2);
11
+ const event = parseBlock(block);
12
+ if (event)
13
+ events.push(event);
14
+ }
15
+ return events;
16
+ }
17
+ }
18
+ function parseBlock(block) {
19
+ let name = "message";
20
+ const data = [];
21
+ for (const line of block.split("\n")) {
22
+ if (!line || line.startsWith(":"))
23
+ continue; // comment (": ping")
24
+ const separator = line.indexOf(":");
25
+ const field = separator === -1 ? line : line.slice(0, separator);
26
+ let value = separator === -1 ? "" : line.slice(separator + 1);
27
+ if (value.startsWith(" "))
28
+ value = value.slice(1);
29
+ if (field === "event")
30
+ name = value;
31
+ else if (field === "data")
32
+ data.push(value);
33
+ }
34
+ const text = data.join("\n");
35
+ const json = () => { try {
36
+ return JSON.parse(text);
37
+ }
38
+ catch {
39
+ return {};
40
+ } };
41
+ switch (name) {
42
+ case "ready": {
43
+ const value = json();
44
+ return { type: "ready", name: String(value.name ?? ""), online: value.online === true };
45
+ }
46
+ case "clear": return { type: "clear" };
47
+ case "log": return { type: "log", text };
48
+ case "status": return { type: "status", action: String(json().action ?? "") };
49
+ case "end": {
50
+ const value = json();
51
+ return { type: "end", reason: String(value.reason ?? ""), message: value.message };
52
+ }
53
+ default: return null;
54
+ }
55
+ }
56
+ /**
57
+ * Follows the console until `signal` aborts or the server ends it. `onEvent` gets every event in order.
58
+ * Resolves with the reason the stream stopped.
59
+ */
60
+ export async function streamLogs(client, appId, options) {
61
+ const tail = Math.max(0, Math.min(500, options.tail ?? 100));
62
+ const response = await client.stream(`/v1/apps/${encodeURIComponent(appId)}/logs?tail=${tail}`, options.signal);
63
+ if (!response.body)
64
+ return "no-body";
65
+ const parser = new SseParser();
66
+ const decoder = new TextDecoder();
67
+ const reader = response.body.getReader();
68
+ let reason = "closed";
69
+ try {
70
+ while (true) {
71
+ const { value, done } = await reader.read();
72
+ if (done)
73
+ break;
74
+ for (const event of parser.push(decoder.decode(value, { stream: true }))) {
75
+ if (event.type === "end")
76
+ reason = event.reason || "end";
77
+ options.onEvent(event);
78
+ }
79
+ }
80
+ }
81
+ catch (error) {
82
+ if (!options.signal.aborted)
83
+ throw error;
84
+ reason = "aborted";
85
+ }
86
+ return reason;
87
+ }
@@ -0,0 +1,27 @@
1
+ import pc from "picocolors";
2
+ export const ui = {
3
+ ok: (text) => console.log(`${pc.green("✓")} ${text}`),
4
+ fail: (text) => console.error(`${pc.red("✗")} ${text}`),
5
+ info: (text) => console.log(text),
6
+ dim: (text) => console.log(pc.dim(text)),
7
+ blank: () => console.log(""),
8
+ };
9
+ /** A one-line spinner; on a pipe or in CI it prints the text once and stays quiet. */
10
+ export function spinner(text) {
11
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
12
+ if (!process.stdout.isTTY) {
13
+ console.log(`${text}…`);
14
+ return { stop: () => undefined };
15
+ }
16
+ let index = 0;
17
+ const draw = () => process.stdout.write(`\r${pc.cyan(frames[index++ % frames.length])} ${text}`);
18
+ draw();
19
+ const timer = setInterval(draw, 80);
20
+ return {
21
+ stop: () => {
22
+ clearInterval(timer);
23
+ process.stdout.write("\r\x1b[2K");
24
+ },
25
+ };
26
+ }
27
+ export { pc };
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { zip } from "fflate";
4
+ import { t } from "./i18n.js";
5
+ /**
6
+ * A folder linked to an application (`campos link`): `.campos/project.json` at the project's root says which
7
+ * application `campos deploy` sends the folder to. Commands look for it from the current folder upwards,
8
+ * like git does with `.git`.
9
+ */
10
+ export const PROJECT_DIR = ".campos";
11
+ const PROJECT_FILE = "project.json";
12
+ export function findProject(from = process.cwd()) {
13
+ let dir = path.resolve(from);
14
+ while (true) {
15
+ const file = path.join(dir, PROJECT_DIR, PROJECT_FILE);
16
+ try {
17
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
18
+ if (typeof data?.appId === "string")
19
+ return { root: dir, appId: data.appId, name: String(data.name ?? ""), apiUrl: String(data.apiUrl ?? "") };
20
+ }
21
+ catch {
22
+ // not here
23
+ }
24
+ const parent = path.dirname(dir);
25
+ if (parent === dir)
26
+ return null;
27
+ dir = parent;
28
+ }
29
+ }
30
+ /** Writes the link, and keeps `.campos/` out of git when the folder has a `.gitignore`. */
31
+ export function writeProject(root, project) {
32
+ fs.mkdirSync(path.join(root, PROJECT_DIR), { recursive: true });
33
+ fs.writeFileSync(path.join(root, PROJECT_DIR, PROJECT_FILE), `${JSON.stringify(project, null, 2)}\n`);
34
+ const gitignore = path.join(root, ".gitignore");
35
+ if (fs.existsSync(gitignore)) {
36
+ const content = fs.readFileSync(gitignore, "utf8");
37
+ if (!content.split(/\r?\n/).some((line) => line.trim().replace(/\/$/, "") === PROJECT_DIR)) {
38
+ fs.appendFileSync(gitignore, `${content.endsWith("\n") || content === "" ? "" : "\n"}${PROJECT_DIR}/\n`);
39
+ }
40
+ }
41
+ }
42
+ export function removeProject(root) {
43
+ fs.rmSync(path.join(root, PROJECT_DIR, PROJECT_FILE), { force: true });
44
+ try {
45
+ fs.rmdirSync(path.join(root, PROJECT_DIR));
46
+ }
47
+ catch { /* not empty, or gone */ }
48
+ }
49
+ /**
50
+ * What never goes up: dependencies are installed on the server, and these are tools' own folders.
51
+ * Same list as the VS Code extension. `.env` files do go: the application may need them.
52
+ */
53
+ export const DEFAULT_IGNORE = ["node_modules", ".git", PROJECT_DIR, "__pycache__", ".venv", "venv", ".DS_Store"];
54
+ /** `.camposignore`: one pattern per line, `#` comments; a name (`dist`, `*.log`) or a path (`src/tmp`). */
55
+ export function readIgnoreFile(root) {
56
+ try {
57
+ return fs.readFileSync(path.join(root, ".camposignore"), "utf8")
58
+ .split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ }
64
+ function globToRegExp(glob) {
65
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]");
66
+ return new RegExp(`^${escaped}$`, process.platform === "win32" ? "i" : "");
67
+ }
68
+ /** Whether a relative, forward-slash path is left out: a pattern without "/" matches any segment's name. */
69
+ export function createExcluder(patterns) {
70
+ const byName = [];
71
+ const byPath = [];
72
+ for (const raw of patterns) {
73
+ const pattern = raw.trim().replace(/\\/g, "/").replace(/^\.?\/+/, "").replace(/\/+$/, "");
74
+ if (!pattern)
75
+ continue;
76
+ (pattern.includes("/") ? byPath : byName).push(globToRegExp(pattern));
77
+ }
78
+ return (relativePath) => {
79
+ const segments = relativePath.split("/");
80
+ if (segments.some((segment) => byName.some((re) => re.test(segment))))
81
+ return true;
82
+ for (let i = 1; i <= segments.length; i++) {
83
+ if (byPath.some((re) => re.test(segments.slice(0, i).join("/"))))
84
+ return true;
85
+ }
86
+ return false;
87
+ };
88
+ }
89
+ export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024; // what the control accepts per upload
90
+ const MAX_FILES = 50_000;
91
+ /** Zips the folder, leaving out what `exclude` says. Symbolic links and special files are skipped. */
92
+ export async function zipProject(root, exclude) {
93
+ const files = {};
94
+ const names = [];
95
+ let totalBytes = 0;
96
+ const walk = async (dir, base) => {
97
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
98
+ entries.sort((a, b) => a.name.localeCompare(b.name));
99
+ for (const entry of entries) {
100
+ const rel = base ? `${base}/${entry.name}` : entry.name;
101
+ if (exclude(rel))
102
+ continue;
103
+ const full = path.join(dir, entry.name);
104
+ if (entry.isDirectory())
105
+ await walk(full, rel);
106
+ else if (entry.isFile()) {
107
+ if (names.length >= MAX_FILES)
108
+ throw new Error(t("error.tooManyFiles", { max: String(MAX_FILES) }));
109
+ const data = await fs.promises.readFile(full);
110
+ totalBytes += data.length;
111
+ files[rel] = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
112
+ names.push(rel);
113
+ }
114
+ }
115
+ };
116
+ await walk(root, "");
117
+ const zipped = await new Promise((resolve, reject) => zip(files, { level: 6 }, (error, data) => (error ? reject(error) : resolve(data))));
118
+ return { zip: Buffer.from(zipped.buffer, zipped.byteOffset, zipped.byteLength), files: names, totalBytes };
119
+ }
@@ -0,0 +1,29 @@
1
+ import { t } from "./i18n.js";
2
+ /**
3
+ * Questions in the terminal. They use the same keyboard reading as the lists (Ink): mixing Node's readline
4
+ * with Ink left the next Enter arriving as a cancel on Windows.
5
+ */
6
+ export const isInteractive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
7
+ /** Thrown when the person presses Esc in a question. */
8
+ export class PromptCancelled extends Error {
9
+ }
10
+ /** A line of text, with a default (Enter keeps it). Esc throws PromptCancelled. */
11
+ export async function ask(question, fallback = "") {
12
+ const { askText } = await import("../tui/Picker.js");
13
+ const answer = await askText(question, fallback);
14
+ if (answer === null)
15
+ throw new PromptCancelled();
16
+ return answer;
17
+ }
18
+ /** Yes or no, chosen with the arrow keys; the default comes first. Outside a terminal, the answer is no. */
19
+ export async function confirm(question, fallback = false) {
20
+ if (!isInteractive())
21
+ return false;
22
+ const { pick } = await import("../tui/Picker.js");
23
+ const yes = { label: t("prompt.yes"), value: true };
24
+ const no = { label: t("prompt.no"), value: false };
25
+ const answer = await pick(question, fallback ? [yes, no] : [no, yes], { filter: false });
26
+ if (answer === null)
27
+ throw new PromptCancelled();
28
+ return answer;
29
+ }
@@ -0,0 +1,21 @@
1
+ import { ApiClient } from "./api.js";
2
+ import { readToken } from "./credentials.js";
3
+ /** No credential for this API address: the command needs `campos login` first. */
4
+ export class NotSignedInError extends Error {
5
+ constructor() {
6
+ super("Not signed in");
7
+ }
8
+ }
9
+ /** A client carrying the stored credential, for commands that need an account. */
10
+ export async function signedInClient(apiUrl) {
11
+ const stored = await readToken(apiUrl);
12
+ if (!stored)
13
+ throw new NotSignedInError();
14
+ return new ApiClient(apiUrl, stored.token);
15
+ }
16
+ /** The signed-in client and the team the command works in (null: the personal account). */
17
+ export async function signedInContext(apiUrl) {
18
+ const client = await signedInClient(apiUrl);
19
+ const { activeTeam } = await import("./teams.js");
20
+ return { client, team: await activeTeam(client, apiUrl) };
21
+ }
@@ -0,0 +1,28 @@
1
+ /** How many single-letter edits turn `a` into `b` (insert, delete, replace). */
2
+ export function editDistance(a, b) {
3
+ const previous = Array.from({ length: b.length + 1 }, (_, index) => index);
4
+ for (let i = 1; i <= a.length; i++) {
5
+ let diagonal = previous[0];
6
+ previous[0] = i;
7
+ for (let j = 1; j <= b.length; j++) {
8
+ const above = previous[j];
9
+ previous[j] = Math.min(previous[j] + 1, previous[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
10
+ diagonal = above;
11
+ }
12
+ }
13
+ return previous[b.length];
14
+ }
15
+ /** The candidate closest to `word`, when it is close enough to be a typo (or `word` starts it). */
16
+ export function closest(word, candidates) {
17
+ const wanted = word.toLowerCase();
18
+ const prefix = candidates.find((candidate) => candidate.startsWith(wanted) && wanted.length >= 2);
19
+ if (prefix)
20
+ return prefix;
21
+ let best = null;
22
+ for (const candidate of candidates) {
23
+ const distance = editDistance(wanted, candidate);
24
+ if (!best || distance < best.distance)
25
+ best = { candidate, distance };
26
+ }
27
+ return best && best.distance <= Math.max(1, Math.floor(best.candidate.length / 3)) ? best.candidate : null;
28
+ }
@@ -0,0 +1,39 @@
1
+ import { AppLookupError } from "./apps.js";
2
+ import { storedTeam, teamOverride } from "./context.js";
3
+ export const listTeams = (client) => client.get("/v1/teams");
4
+ export const getTeam = (client, id) => client.get(`/v1/teams/${encodeURIComponent(id)}`);
5
+ export const createTeam = (client, name) => client.post(`/v1/teams/create/${encodeURIComponent(name)}`);
6
+ export const inviteToTeam = (client, id, email, roleId) => client.post(`/v1/teams/${encodeURIComponent(id)}/invite`, { email, ...(roleId ? { roleId } : {}) });
7
+ export const personOf = (value) => (value && typeof value === "object" ? value : null);
8
+ export const isOwner = (team, userId) => (personOf(team.owner)?._id ?? team.owner) === userId;
9
+ /** Words that mean "my own account, no team". */
10
+ const PERSONAL = new Set(["pessoal", "personal", "eu", "me", "-", "nenhum", "none"]);
11
+ export const meansPersonal = (query) => PERSONAL.has(query.trim().toLowerCase());
12
+ /** A team by id, exact name (ignoring case) or a unique start of a name. */
13
+ export function resolveTeam(teams, query) {
14
+ const wanted = query.trim().toLowerCase();
15
+ const byId = teams.find((team) => team._id === query.trim());
16
+ if (byId)
17
+ return byId;
18
+ const exact = teams.filter((team) => team.name.toLowerCase() === wanted);
19
+ if (exact.length === 1)
20
+ return exact[0];
21
+ const prefix = teams.filter((team) => team.name.toLowerCase().startsWith(wanted));
22
+ if (prefix.length === 1)
23
+ return prefix[0];
24
+ throw new AppLookupError(query, (exact.length > 1 ? exact : prefix).map((team) => `${team.name} (${team._id})`));
25
+ }
26
+ /**
27
+ * The team this command works in: `--team`/`CAMPOS_TEAM` when given (resolved against the person's teams),
28
+ * otherwise the one chosen with `campos team use`, otherwise the personal account (null).
29
+ */
30
+ export async function activeTeam(client, apiUrl) {
31
+ const wanted = teamOverride();
32
+ if (wanted) {
33
+ if (meansPersonal(wanted))
34
+ return null;
35
+ const team = resolveTeam(await listTeams(client), wanted);
36
+ return { id: team._id, name: team.name };
37
+ }
38
+ return storedTeam(apiUrl);
39
+ }
@@ -0,0 +1,48 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import semver from "semver";
4
+ import { configDir } from "./config.js";
5
+ const latestUrl = "https://registry.npmjs.org/@camposcloud%2fcli/latest";
6
+ const hour = 60 * 60 * 1000;
7
+ async function cachedCheck(file) {
8
+ try {
9
+ const cached = JSON.parse(await readFile(file, "utf8"));
10
+ const latest = typeof cached.latest === "string" ? semver.valid(cached.latest) : null;
11
+ const age = Date.now() - cached.checkedAt;
12
+ if (age >= 0 && age < (latest ? 24 * hour : hour)) {
13
+ return { checkedAt: cached.checkedAt, latest };
14
+ }
15
+ }
16
+ catch {
17
+ // A missing or unreadable cache is treated as a fresh start.
18
+ }
19
+ }
20
+ async function registryVersion(fetchLatest) {
21
+ try {
22
+ const response = await fetchLatest(latestUrl, { signal: AbortSignal.timeout(750) });
23
+ if (!response.ok)
24
+ return null;
25
+ const data = await response.json();
26
+ return typeof data?.version === "string" ? semver.valid(data.version) : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ export async function availableUpdate(current, directory = configDir(), fetchLatest = fetch) {
33
+ if (!semver.valid(current))
34
+ return null;
35
+ const file = path.join(directory, "update-check.json");
36
+ const cached = await cachedCheck(file);
37
+ const latest = cached ? cached.latest : await registryVersion(fetchLatest);
38
+ if (!cached) {
39
+ try {
40
+ await mkdir(directory, { recursive: true });
41
+ await writeFile(file, JSON.stringify({ checkedAt: Date.now(), latest }));
42
+ }
43
+ catch {
44
+ // A read-only config directory should not block the CLI.
45
+ }
46
+ }
47
+ return latest && semver.gt(latest, current) ? latest : null;
48
+ }
package/dist/index.js ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ import { Command, Help } from "commander";
3
+ import { ApiError, CLI_VERSION, NetworkError } from "./core/api.js";
4
+ import { AppLookupError } from "./core/apps.js";
5
+ import { resolveApiUrl } from "./core/config.js";
6
+ import { setTeamOverride } from "./core/context.js";
7
+ import { h, translateCommanderError } from "./core/help.js";
8
+ import { currentLanguage, t } from "./core/i18n.js";
9
+ import { pc, ui } from "./core/output.js";
10
+ import { NotSignedInError } from "./core/session.js";
11
+ import { isInteractive, PromptCancelled } from "./core/prompt.js";
12
+ import { availableUpdate } from "./core/update.js";
13
+ import { login, logout, whoami } from "./commands/auth.js";
14
+ import { appsInfo, appsList, appsPower, CancelledError, findAppByWord, logs, NoAppNamedError, status } from "./commands/apps.js";
15
+ import { closest } from "./core/suggest.js";
16
+ import { create, deleteApp } from "./commands/create.js";
17
+ import { dashboard } from "./commands/dashboard.js";
18
+ import { dbInfo, dbList, dbPower, dbUrl } from "./commands/db.js";
19
+ import { deploy, link, unlink } from "./commands/deploy.js";
20
+ import { envList, envPull, envPush, envSet, envUnset } from "./commands/env.js";
21
+ import { filesCat, filesList, filesPull, filesPush, filesRemove } from "./commands/files.js";
22
+ import { teamCreate, teamCurrent, teamInvite, teamMembers, teamsList, teamUse } from "./commands/teams.js";
23
+ import { appUrl, doctor, openDashboard } from "./commands/utils.js";
24
+ import { autorestart, dbPassword, dbUpdate, rename, scale } from "./commands/manage.js";
25
+ import { complete, completionScript } from "./commands/completion.js";
26
+ import { lang } from "./commands/lang.js";
27
+ import { localizeServerMessage } from "./core/apiErrors.js";
28
+ /** The help, laid out like commander's but with its headings in the CLI's language. */
29
+ class LocalizedHelp extends Help {
30
+ formatHelp(cmd, helper) {
31
+ const width = helper.padWidth(cmd, helper);
32
+ const item = (term, description) => (description ? ` ${term.padEnd(width + 2)}${description}` : ` ${term}`);
33
+ const usage = currentLanguage() === "pt" ? helper.commandUsage(cmd).replace("[options]", "[opções]").replace("[command]", "[comando]") : helper.commandUsage(cmd);
34
+ const out = [`${h("usage")}: ${usage}`, ""];
35
+ const description = helper.commandDescription(cmd);
36
+ if (description)
37
+ out.push(description, "");
38
+ const args = helper.visibleArguments(cmd).map((arg) => item(helper.argumentTerm(arg), helper.argumentDescription(arg)));
39
+ if (args.length)
40
+ out.push(`${h("arguments")}:`, ...args, "");
41
+ const optionText = (text) => (currentLanguage() === "pt" ? text.replace("(default: ", "(padrão: ") : text);
42
+ const options = helper.visibleOptions(cmd).map((option) => item(helper.optionTerm(option), optionText(helper.optionDescription(option))));
43
+ if (options.length)
44
+ out.push(`${h("options")}:`, ...options, "");
45
+ const subTerm = (sub) => (currentLanguage() === "pt" ? helper.subcommandTerm(sub).replace("[options]", "[opções]") : helper.subcommandTerm(sub));
46
+ const commands = helper.visibleCommands(cmd).map((sub) => item(subTerm(sub), helper.subcommandDescription(sub)));
47
+ if (commands.length)
48
+ out.push(`${h("commands")}:`, ...commands, "");
49
+ return out.join("\n");
50
+ }
51
+ }
52
+ const program = new Command()
53
+ .name("campos")
54
+ .description(h("program"))
55
+ .version(CLI_VERSION, "-v, --version", h("version"))
56
+ .helpOption("-h, --help", h("help"))
57
+ .helpCommand(false)
58
+ .option("--api-url <url>", h("apiUrl"))
59
+ .option("--team <team>", h("team"))
60
+ .configureOutput({ outputError: (text, write) => write(`${pc.red(`✗ ${translateCommanderError(text).replace(/^error: /, "").trim()}`)}\n`) });
61
+ // The --team option is global: it applies to whichever command runs.
62
+ program.hook("preAction", (_root, action) => setTeamOverride(action.optsWithGlobals().team));
63
+ const apiUrl = () => resolveApiUrl(program.opts().apiUrl);
64
+ /** Runs a command and turns what can go wrong into a short message and an exit code. */
65
+ const run = (action) => async (...args) => {
66
+ try {
67
+ process.exitCode = await action(...args);
68
+ }
69
+ catch (error) {
70
+ if (error instanceof CancelledError || error instanceof PromptCancelled)
71
+ ui.info(t("error.cancelled"));
72
+ else if (error instanceof NoAppNamedError)
73
+ ui.fail(t("error.noAppNamed"));
74
+ else if (error instanceof NotSignedInError)
75
+ ui.fail(t("error.notSignedIn"));
76
+ else if (error instanceof NetworkError)
77
+ ui.fail(t("error.network", { url: error.url }));
78
+ else if (error instanceof ApiError && error.status === 401)
79
+ ui.fail(t("error.session"));
80
+ else if (error instanceof ApiError)
81
+ ui.fail(localizeServerMessage(error.message));
82
+ else if (error instanceof AppLookupError)
83
+ ui.fail(error.candidates.length ? t("error.appAmbiguous", { query: error.query, list: error.candidates.join(", ") }) : t("error.appNotFound", { query: error.query }));
84
+ else
85
+ ui.fail(localizeServerMessage(error?.message ?? String(error)));
86
+ process.exitCode = 1;
87
+ }
88
+ };
89
+ // Account
90
+ program.command("login").description(h("login"))
91
+ .option("--token <token>", h("loginToken"))
92
+ .option("--no-browser", h("loginNoBrowser"))
93
+ .action(run((options) => login(apiUrl(), options)));
94
+ program.command("logout").description(h("logout")).action(run(() => logout(apiUrl())));
95
+ program.command("whoami").description(h("whoami")).option("--json", h("json")).action(run((options) => whoami(apiUrl(), options)));
96
+ // Applications, everyday
97
+ program.command("status [app]").description(h("status")).option("--json", h("json")).action(run((query, options) => status(apiUrl(), query, options)));
98
+ program.command("start [app]").description(h("start")).action(run((query) => appsPower(apiUrl(), query, "start")));
99
+ program.command("stop [app]").description(h("stop")).action(run((query) => appsPower(apiUrl(), query, "stop")));
100
+ program.command("restart [app]").description(h("restartCmd")).action(run((query) => appsPower(apiUrl(), query, "restart")));
101
+ program.command("info [app]").description(h("info")).option("--json", h("json")).action(run((query, options) => appsInfo(apiUrl(), query, options)));
102
+ program.command("logs [app]").description(h("logs"))
103
+ .option("-f, --follow", h("logsFollow"))
104
+ .option("-n, --tail <lines>", h("logsTail"), "100")
105
+ .action(run((query, options) => logs(apiUrl(), query, options)));
106
+ const apps = program.command("apps").description(h("apps")).option("--json", h("json")).action(run((options) => appsList(apiUrl(), options)));
107
+ apps.command("list").description(h("appsList")).option("--json", h("json")).action(run((options) => appsList(apiUrl(), options)));
108
+ apps.command("info [app]").description(h("info")).option("--json", h("json")).action(run((query, options) => appsInfo(apiUrl(), query, options)));
109
+ apps.command("start [app]").description(h("start")).action(run((query) => appsPower(apiUrl(), query, "start")));
110
+ apps.command("stop [app]").description(h("stop")).action(run((query) => appsPower(apiUrl(), query, "stop")));
111
+ apps.command("restart [app]").description(h("restartCmd")).action(run((query) => appsPower(apiUrl(), query, "restart")));
112
+ apps.command("delete [app]").description(h("delete")).option("-y, --yes", h("yes")).action(run((query, options) => deleteApp(apiUrl(), query, options)));
113
+ // Project folder
114
+ program.command("create").alias("init").description(h("create"))
115
+ .option("--name <name>", h("createName"))
116
+ .option("--runtime <runtime>", h("createRuntime"))
117
+ .option("--main <file>", h("createMain"))
118
+ .option("--memory <mb>", h("createMemory"))
119
+ .option("--web", h("createWeb"))
120
+ .option("--port <port>", h("createPort"))
121
+ .option("--subdomain <name>", h("createSubdomain"))
122
+ .option("--start <command>", h("createStart"))
123
+ .option("--no-env", h("createNoEnv"))
124
+ .option("-y, --yes", h("yes"))
125
+ .action(run((options) => create(apiUrl(), options)));
126
+ program.command("delete [app]").description(h("delete")).option("-y, --yes", h("yes")).action(run((query, options) => deleteApp(apiUrl(), query, options)));
127
+ program.command("scale <memory>").description(h("scale")).option("-a, --app <app>", h("app")).action(run((memory, options) => scale(apiUrl(), memory, options)));
128
+ program.command("rename <name>").description(h("rename")).option("-a, --app <app>", h("app")).action(run((name, options) => rename(apiUrl(), name, options)));
129
+ program.command("autorestart <on|off>").description(h("autorestart")).option("-a, --app <app>", h("app")).action(run((value, options) => autorestart(apiUrl(), value, options)));
130
+ program.command("link [app]").description(h("link")).action(run((query) => link(apiUrl(), query)));
131
+ program.command("unlink").description(h("unlink")).action(run(() => unlink()));
132
+ program.command("deploy").description(h("deploy"))
133
+ .option("-a, --app <app>", h("deployApp"))
134
+ .option("--no-restart", h("deployNoRestart"))
135
+ .option("--dry-run", h("deployDryRun"))
136
+ .action(run((options) => deploy(apiUrl(), options)));
137
+ // Environment variables
138
+ const env = program.command("env [app]").description(h("env"))
139
+ .option("--show", h("envShow"))
140
+ .option("--json", h("json"))
141
+ .action(run((query, options) => envList(apiUrl(), query, options)));
142
+ env.command("set <assignments...>").description(h("envSet")).option("-a, --app <app>", h("app")).option("--restart", h("restart"))
143
+ .action(run((assignments, options) => envSet(apiUrl(), assignments, options)));
144
+ env.command("unset <keys...>").description(h("envUnset")).option("-a, --app <app>", h("app")).option("--restart", h("restart"))
145
+ .action(run((keys, options) => envUnset(apiUrl(), keys, options)));
146
+ env.command("pull [file]").description(h("envPull")).option("-a, --app <app>", h("app")).option("--force", h("envPullForce"))
147
+ .action(run((file, options) => envPull(apiUrl(), file, options)));
148
+ env.command("push [file]").description(h("envPush")).option("-a, --app <app>", h("app")).option("--replace", h("envPushReplace")).option("--restart", h("restart"))
149
+ .action(run((file, options) => envPush(apiUrl(), file, options)));
150
+ // Files
151
+ const files = program.command("files [path]").description(h("files")).option("-a, --app <app>", h("app")).option("--json", h("json"))
152
+ .action(run((dir, options) => filesList(apiUrl(), dir, options)));
153
+ files.command("cat <path>").description(h("filesCat")).option("-a, --app <app>", h("app")).action(run((file, options) => filesCat(apiUrl(), file, options)));
154
+ files.command("pull <path> [destination]").description(h("filesPull")).option("-a, --app <app>", h("app"))
155
+ .action(run((source, destination, options) => filesPull(apiUrl(), source, destination, options)));
156
+ files.command("push <local> [folder]").description(h("filesPush")).option("-a, --app <app>", h("app")).option("--restart", h("restart"))
157
+ .action(run((source, destination, options) => filesPush(apiUrl(), source, destination, options)));
158
+ files.command("rm <paths...>").description(h("filesRm")).option("-a, --app <app>", h("app")).option("-y, --yes", h("yes"))
159
+ .action(run((targets, options) => filesRemove(apiUrl(), targets, options)));
160
+ // Databases
161
+ const db = program.command("db").description(h("db")).option("--json", h("json")).action(run((options) => dbList(apiUrl(), options)));
162
+ db.command("list").description(h("dbList")).option("--json", h("json")).action(run((options) => dbList(apiUrl(), options)));
163
+ db.command("info <database>").description(h("dbInfo")).option("--json", h("json")).action(run((query, options) => dbInfo(apiUrl(), query, options)));
164
+ db.command("url <database>").description(h("dbUrl")).action(run((query) => dbUrl(apiUrl(), query)));
165
+ db.command("password <database>").description(h("dbPassword")).option("--password <password>", h("dbPasswordValue")).action(run((query, options) => dbPassword(apiUrl(), query, options)));
166
+ db.command("scale <database> <memory>").description(h("dbScale")).action(run((query, memory) => dbUpdate(apiUrl(), query, { memory })));
167
+ db.command("rename <database> <name>").description(h("dbRename")).action(run((query, name) => dbUpdate(apiUrl(), query, { name })));
168
+ db.command("start <database>").description(h("dbStart")).action(run((query) => dbPower(apiUrl(), query, "start")));
169
+ db.command("stop <database>").description(h("dbStop")).action(run((query) => dbPower(apiUrl(), query, "stop")));
170
+ db.command("restart <database>").description(h("dbRestart")).action(run((query) => dbPower(apiUrl(), query, "restart")));
171
+ // Teams
172
+ program.command("teams").description(h("teams")).option("--json", h("json")).action(run((options) => teamsList(apiUrl(), options)));
173
+ const team = program.command("team").description(h("teamCmd")).action(run(() => teamCurrent(apiUrl())));
174
+ team.command("use [team]").alias("switch").description(h("teamUse")).action(run((query) => teamUse(apiUrl(), query)));
175
+ team.command("list").description(h("teams")).option("--json", h("json")).action(run((options) => teamsList(apiUrl(), options)));
176
+ team.command("members [team]").description(h("teamMembers")).option("--json", h("json")).action(run((query, options) => teamMembers(apiUrl(), query, options)));
177
+ team.command("invite <email>").description(h("teamInvite")).option("--role <role>", h("teamInviteRole")).action(run((email, options) => teamInvite(apiUrl(), email, { ...options, team: program.opts().team })));
178
+ team.command("create <name>").description(h("teamCreate")).option("--no-use", h("teamCreateNoUse")).action(run((name, options) => teamCreate(apiUrl(), name, options)));
179
+ // Utilities
180
+ program.command("open [app]").description(h("open")).action(run((query) => openDashboard(apiUrl(), query)));
181
+ program.command("url [app]").description(h("url")).option("-o, --open", h("urlOpen")).action(run((query, options) => appUrl(apiUrl(), query, options)));
182
+ program.command("doctor").description(h("doctor")).action(run(() => doctor(apiUrl())));
183
+ program.command("lang [language]").description(h("lang")).action(run((value) => lang(value)));
184
+ program.command("completion [shell]").description(h("completion")).action(run(async (shell) => completionScript(shell)));
185
+ // Called by the completion scripts; not listed in the help.
186
+ program.command("__complete", { hidden: true }).argument("[words...]").allowUnknownOption(true).helpOption(false)
187
+ .action(run((words = []) => complete(program, apiUrl, words)));
188
+ // Anything after "campos" that is not a command: say so plainly.
189
+ program.allowExcessArguments(true);
190
+ program.action(run(async () => {
191
+ const [word] = program.args;
192
+ if (!word)
193
+ return dashboard(apiUrl(), program.helpInformation());
194
+ // `campos <application>`: its page in the dashboard (or its status, outside a terminal).
195
+ const app = await findAppByWord(apiUrl(), program.args.join(" "));
196
+ if (app) {
197
+ if (process.stdin.isTTY && process.stdout.isTTY)
198
+ return dashboard(apiUrl(), program.helpInformation(), app._id);
199
+ return status(apiUrl(), app._id, {});
200
+ }
201
+ const commands = program.commands.filter((command) => !command.name().startsWith("__")).map((command) => command.name());
202
+ const guess = closest(word, commands);
203
+ ui.fail(guess ? t("error.unknownCommandGuess", { command: word, guess }) : t("error.unknownCommand", { command: word }));
204
+ return 1;
205
+ }));
206
+ // Every command, and every subcommand, uses the localized help.
207
+ const localizeAll = (command) => {
208
+ command.createHelp = () => Object.assign(new LocalizedHelp(), command.configureHelp());
209
+ command.commands.forEach(localizeAll);
210
+ };
211
+ localizeAll(program);
212
+ const args = process.argv.slice(2);
213
+ if (isInteractive() && process.stderr.isTTY && !process.env.CI && !args.includes("--json") && !args.includes("__complete")) {
214
+ const latest = await availableUpdate(CLI_VERSION);
215
+ if (latest) {
216
+ console.error(pc.yellow(t("update.available", {
217
+ current: CLI_VERSION,
218
+ latest,
219
+ command: "npm install -g @camposcloud/cli@latest",
220
+ })));
221
+ }
222
+ }
223
+ await program.parseAsync(process.argv);