@argos-ci/cli 6.10.0 → 6.12.0

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 (2) hide show
  1. package/dist/index.mjs +757 -333
  2. package/package.json +6 -6
package/dist/index.mjs CHANGED
@@ -1,16 +1,20 @@
1
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
1
+ import { mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
2
2
  import { fileURLToPath } from "node:url";
3
- import { resolve } from "node:path";
3
+ import { dirname, extname, join, resolve } from "node:path";
4
4
  import { Option, program } from "commander";
5
5
  import { deploy, finalize, skip, upload, uploadMedia } from "@argos-ci/core";
6
6
  import ora from "ora";
7
7
  import { APIError, createClient, throwAPIError } from "@argos-ci/api-client";
8
8
  import { determineAgent } from "@vercel/detect-agent";
9
- import { homedir } from "node:os";
9
+ import { createWriteStream } from "node:fs";
10
+ import { Readable } from "node:stream";
11
+ import { pipeline } from "node:stream/promises";
12
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
13
  import { createHash, randomBytes } from "node:crypto";
14
+ import { homedir } from "node:os";
11
15
  import { createServer } from "node:http";
12
16
  import open from "open";
13
- //#region src/lib/cli-error.ts
17
+ // src/lib/cli-error.ts
14
18
  /**
15
19
  * Error whose message is meant to be shown to the user verbatim (prefixed with
16
20
  * `Error: `) before the CLI exits with a non-zero code. Throw it — via
@@ -29,36 +33,46 @@ var CliError = class extends Error {
29
33
  function fail(message) {
30
34
  throw new CliError(message);
31
35
  }
32
- //#endregion
33
- //#region src/options.ts
36
+ // src/options.ts
34
37
  const parallelNonceOption = new Option("--parallel-nonce <string>", "A unique ID for this parallel build");
35
38
  const tokenOption = new Option("--token <token>", "Repository token");
36
- const projectOption = new Option("--project <slug>", "Argos project slug (account/project), used to disambiguate tokenless authentication when multiple projects are linked to the same repository");
39
+ const projectOption = new Option("--project <slug>", "Project in owner/project format. Also ARGOS_PROJECT. Required when the token is linked to several projects; also disambiguates tokenless authentication when several projects are linked to the same repository");
37
40
  const buildNameOption = new Option("--build-name <string>", "Name of the build, in case you want to run multiple Argos builds in a single CI job");
38
41
  const accountOption = new Option("--account <slug>", "Slug of the account (personal or team) that will own the project");
39
42
  const accountSlugOption = new Option("--account <slug>", "Slug of the account (personal or team) to act on. Also ARGOS_ACCOUNT");
40
43
  const jsonOption = new Option("--json", "Output machine-readable JSON instead of human-readable text");
41
44
  const projectPathOption = new Option("--project <owner/project>", "Project path in owner/project format. Required for build-number references on review and comment commands");
42
45
  const changeProjectPathOption = new Option("--project <owner/project>", "Project the change belongs to, in owner/project format. Also ARGOS_PROJECT");
43
- const testProjectPathOption = new Option("--project <owner/project>", "Project the test belongs to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token, which already identifies its project");
44
- const mediaProjectPathOption = new Option("--project <owner/project>", "Project the media belongs to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token, which already identifies its project");
46
+ const testProjectPathOption = new Option("--project <owner/project>", "Project the test belongs to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token linked to a single project, which already identifies it");
47
+ const buildProjectPathOption = new Option("--project <owner/project>", "Project the builds belong to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token linked to a single project, which already identifies it");
48
+ const mediaProjectPathOption = new Option("--project <owner/project>", "Project the media belongs to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token linked to a single project, which already identifies it");
45
49
  const managedProjectPathOption = new Option("--project <owner/project>", "Project to act on, in owner/project format. Also ARGOS_PROJECT");
46
50
  const limitOption = new Option("--limit <number>", "Maximum number of items to fetch, following pagination as needed").default(String(100));
51
+ const DAY_MS = 864e5;
52
+ /** Parse the value of `--<option>` into a positive integer, or abort. */
53
+ function toPositiveInteger(value, option) {
54
+ const number = Number(value);
55
+ if (!Number.isInteger(number) || number < 1) fail(`--${option} must be a positive integer, received "${value}".`);
56
+ return number;
57
+ }
58
+ /** Coerce the value of `--<option>` into an ISO 8601 datetime, or abort. */
59
+ function toIsoOrFail(value, option) {
60
+ const date = new Date(value);
61
+ if (Number.isNaN(date.getTime())) fail(`Invalid --${option} value: "${value}". Use an ISO 8601 datetime.`);
62
+ return date.toISOString();
63
+ }
47
64
  /**
48
65
  * Parse a `--limit` value into a positive integer, or abort. Pass `max` when
49
66
  * the source caps how many items it can return.
50
67
  */
51
- function toLimit(value, options) {
52
- const limit = Number(value);
53
- if (!Number.isInteger(limit) || limit < 1) fail(`--limit must be a positive integer, received "${value}".`);
54
- if (options?.max !== void 0 && limit > options.max) fail(`--limit must be at most ${options.max}, received "${value}".`);
68
+ function toLimit(value, { max = 1e400 } = {}) {
69
+ const limit = toPositiveInteger(value, "limit");
70
+ if (limit > max) fail(`--limit must be at most ${max}, received "${value}".`);
55
71
  return limit;
56
72
  }
57
73
  /** Parse a `--pr` value into a pull request number, or abort. */
58
74
  function toPrNumber(value) {
59
- const prNumber = Number(value);
60
- if (!Number.isInteger(prNumber) || prNumber < 1) fail(`--pr must be a positive integer, received "${value}".`);
61
- return prNumber;
75
+ return toPositiveInteger(value, "pr");
62
76
  }
63
77
  const METRICS_PERIOD_BY_CHOICE = {
64
78
  "24h": "LAST_24_HOURS",
@@ -72,8 +86,7 @@ const metricsPeriodOption = new Option("--metrics-period <period>", "Window over
72
86
  function toMetricsPeriod(choice) {
73
87
  return METRICS_PERIOD_BY_CHOICE[choice] ?? "LAST_7_DAYS";
74
88
  }
75
- //#endregion
76
- //#region src/commands/upload.ts
89
+ // src/commands/upload.ts
77
90
  function uploadCommand(program) {
78
91
  program.command("upload").argument("<directory>", "Directory to upload").description("Upload screenshots to Argos").option("-f, --files <patterns...>", "One or more globs matching image file paths to upload", "**/*.{png,jpg,jpeg}").option("-i, --ignore <patterns...>", "One or more globs matching image file paths to ignore (ex: \"**/*.png **/diff.jpg\")").addOption(tokenOption).addOption(projectOption).addOption(buildNameOption).addOption(new Option("--mode <string>", "Mode of comparison applied. CI for visual regression testing, monitoring for visual monitoring.").default("ci").choices(["ci", "monitoring"])).addOption(new Option("--parallel", "Enable parallel mode. Run multiple Argos builds and combine them at the end.\nCan also be set via the ARGOS_PARALLEL environment variable.")).addOption(new Option("--parallel-total <number>", "The number of parallel nodes being ran")).addOption(parallelNonceOption).addOption(new Option("--parallel-index <number>", "The index of the parallel node being ran (must be at least 1)")).addOption(new Option("--reference-branch <string>", "Branch used as baseline for screenshot comparison")).addOption(new Option("--reference-commit <string>", "Commit used as baseline for screenshot comparison")).addOption(new Option("--threshold <number>", "Sensitivity threshold between 0 and 1. The higher the threshold, the less sensitive the diff will be. Default to 0.5")).addOption(new Option("--subset", "Whether this build contains only a subset of screenshots.\nThis is useful when a build is created from an incomplete test suite where some tests are skipped.\nCan also be set via the ARGOS_SUBSET environment variable.")).action(async (directory, options) => {
79
92
  const spinner = ora("Uploading screenshots").start();
@@ -118,15 +131,15 @@ function uploadCommand(program) {
118
131
  }
119
132
  });
120
133
  }
121
- //#endregion
122
- //#region src/commands/finalize.ts
134
+ // src/commands/finalize.ts
123
135
  const skipIfEmptyOption = new Option("--skip-if-empty", "Create a skipped build when no parallel build matches the nonce.\nUseful when uploads are conditional (e.g. skipped by a CI cache) and Argos is a required status check: the skipped build reports a success status even though nothing was uploaded.");
124
136
  function finalizeCommand(program) {
125
- program.command("finalize").description("Finalize pending parallel builds").addOption(parallelNonceOption).addOption(tokenOption).addOption(skipIfEmptyOption).addOption(buildNameOption).action(async (options) => {
137
+ program.command("finalize").description("Finalize pending parallel builds").addOption(parallelNonceOption).addOption(tokenOption).addOption(projectOption).addOption(skipIfEmptyOption).addOption(buildNameOption).action(async (options) => {
126
138
  const spinner = ora("Finalizing builds").start();
127
139
  try {
128
140
  const result = await finalize({
129
141
  token: options.token,
142
+ project: options.project,
130
143
  parallel: options.parallelNonce ? { nonce: options.parallelNonce } : void 0,
131
144
  skipIfEmpty: options.skipIfEmpty,
132
145
  buildName: options.buildName
@@ -141,14 +154,14 @@ function finalizeCommand(program) {
141
154
  }
142
155
  });
143
156
  }
144
- //#endregion
145
- //#region src/commands/skip.ts
157
+ // src/commands/skip.ts
146
158
  function skipCommand(program) {
147
- program.command("skip").description("Mark a build as skipped").addOption(tokenOption).addOption(buildNameOption).action(async (options) => {
159
+ program.command("skip").description("Mark a build as skipped").addOption(tokenOption).addOption(projectOption).addOption(buildNameOption).action(async (options) => {
148
160
  const spinner = ora("Creating skipped build").start();
149
161
  try {
150
162
  const result = await skip({
151
163
  token: options.token,
164
+ project: options.project,
152
165
  buildName: options.buildName
153
166
  });
154
167
  spinner.succeed(`Build created: ${result.build.url}`);
@@ -161,8 +174,7 @@ function skipCommand(program) {
161
174
  }
162
175
  });
163
176
  }
164
- //#endregion
165
- //#region src/lib/user-agent.ts
177
+ // src/lib/user-agent.ts
166
178
  /**
167
179
  * The `User-Agent` the CLI sends on every API request.
168
180
  *
@@ -221,8 +233,7 @@ async function initUserAgent(version) {
221
233
  function getUserAgent() {
222
234
  return userAgent;
223
235
  }
224
- //#endregion
225
- //#region src/lib/api.ts
236
+ // src/lib/api.ts
226
237
  /** Optional override for the API base URL (used in tests and dev). */
227
238
  function getApiBaseUrl() {
228
239
  return process.env["ARGOS_API_BASE_URL"];
@@ -251,8 +262,204 @@ function unwrap(result) {
251
262
  function unwrapEmpty(result) {
252
263
  if (!result.response.ok) throwAPIError(result.error, result.response);
253
264
  }
254
- //#endregion
255
- //#region src/lib/terminal.ts
265
+ // src/lib/build.ts
266
+ const PER_PAGE$1 = 100;
267
+ /** Whether Argos is still processing the build, so its diffs are not final. */
268
+ function isBuildPending(build) {
269
+ return build.status === "pending" || build.status === "progress";
270
+ }
271
+ async function fetchBuild(target) {
272
+ const { client, owner, project, buildNumber } = target;
273
+ return unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}", { params: { path: {
274
+ owner,
275
+ project,
276
+ buildNumber
277
+ } } }));
278
+ }
279
+ /** Fetch every diff of a build, following pagination. */
280
+ async function fetchAllDiffs(target, options = {}) {
281
+ const { client, owner, project, buildNumber } = target;
282
+ const results = [];
283
+ for (let page = 1;; page++) {
284
+ const data = unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}/diffs", { params: {
285
+ path: {
286
+ owner,
287
+ project,
288
+ buildNumber
289
+ },
290
+ query: {
291
+ page: String(page),
292
+ perPage: String(PER_PAGE$1),
293
+ ...options.metricsPeriod ? { metricsPeriod: options.metricsPeriod } : {},
294
+ ...options.needsReview ? { needsReview: "true" } : {}
295
+ }
296
+ } }));
297
+ results.push(...data.results);
298
+ if (results.length >= data.pageInfo.total || data.results.length === 0) break;
299
+ }
300
+ return results;
301
+ }
302
+ // src/lib/download.ts
303
+ /** Files downloaded at the same time. */
304
+ const CONCURRENCY = 8;
305
+ /** Attempts per file before giving up, for failures that may not last. */
306
+ const MAX_ATTEMPTS = 3;
307
+ const RETRY_DELAY_MS = 1e3;
308
+ /** Extension given to a file of each content type when its name has none. */
309
+ const EXTENSION_BY_CONTENT_TYPE = {
310
+ "image/png": ".png",
311
+ "image/jpeg": ".jpg",
312
+ "image/webp": ".webp"
313
+ };
314
+ const IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
315
+ ".png",
316
+ ".jpg",
317
+ ".jpeg",
318
+ ".webp"
319
+ ]);
320
+ const WINDOWS_RESERVED_CHARACTERS = /[<>:"|?*\u0000-\u001f]/g;
321
+ /**
322
+ * Get the path, relative to the download directory, a snapshot is written to.
323
+ *
324
+ * A snapshot is named after the path it was uploaded from
325
+ * (`chromium/home.png`), so the directory mirrors the original layout. Names
326
+ * are whatever the uploader sent, so the `.` and `..` segments and leading
327
+ * slashes are dropped: every file stays inside the directory.
328
+ */
329
+ function getSnapshotPath(file, platform = process.platform) {
330
+ const segments = file.name.split(/[\\/]/).filter((segment) => segment !== "" && segment !== "." && segment !== "..").map((segment) => platform === "win32" ? segment.replace(WINDOWS_RESERVED_CHARACTERS, "_") : segment);
331
+ const basename = segments.pop() ?? "snapshot";
332
+ const extension = EXTENSION_BY_CONTENT_TYPE[file.contentType];
333
+ const suffix = extension && !IMAGE_EXTENSIONS.has(extname(basename).toLowerCase()) ? extension : "";
334
+ return [...segments, `${basename}${suffix}`].join("/");
335
+ }
336
+ /**
337
+ * Get a distinct path for each snapshot. Two names can map to the same file:
338
+ * `home` and `home.png` once the extension is added, or `Home.png` and
339
+ * `home.png`, which macOS and Windows store as one. The later ones get a
340
+ * ` (2)`, ` (3)`… before their extension instead of overwriting the first, on
341
+ * every platform, so a directory copied elsewhere keeps all its files.
342
+ */
343
+ function getSnapshotPaths(files, platform = process.platform) {
344
+ const used = /* @__PURE__ */ new Set();
345
+ return files.map((file) => {
346
+ const path = getSnapshotPath(file, platform);
347
+ const extension = extname(path);
348
+ const stem = path.slice(0, path.length - extension.length);
349
+ let candidate = path;
350
+ for (let index = 2; used.has(candidate.toLowerCase()); index++) candidate = `${stem} (${index})${extension}`;
351
+ used.add(candidate.toLowerCase());
352
+ return candidate;
353
+ });
354
+ }
355
+ function isErrnoException(error) {
356
+ return error instanceof Error && "code" in error;
357
+ }
358
+ /**
359
+ * Abort unless `directory` is missing or empty. Downloading into a directory
360
+ * that already holds files would overwrite some of them and leave others
361
+ * around, so the result would no longer match the build.
362
+ */
363
+ async function assertEmptyDirectory(directory) {
364
+ let entries;
365
+ try {
366
+ entries = await readdir(directory);
367
+ } catch (error) {
368
+ if (isErrnoException(error) && error.code === "ENOENT") return;
369
+ if (isErrnoException(error) && error.code === "ENOTDIR") fail(`${directory} is not a directory.`);
370
+ throw error;
371
+ }
372
+ if (entries.length > 0) fail(`${directory} is not empty. Pick a new directory with --output, or empty it first.`);
373
+ }
374
+ /** A failed response, and whether trying again may succeed. */
375
+ var HTTPStatusError = class extends Error {
376
+ retryable;
377
+ constructor(status) {
378
+ super(`HTTP ${status}`);
379
+ this.retryable = status === 429 || status >= 500;
380
+ }
381
+ };
382
+ async function downloadFile(file, path, signal) {
383
+ for (let attempt = 1;; attempt++) {
384
+ signal.throwIfAborted();
385
+ try {
386
+ const response = await fetch(file.url, { signal });
387
+ if (!response.ok || !response.body) {
388
+ await response.body?.cancel();
389
+ throw new HTTPStatusError(response.status);
390
+ }
391
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(path), { signal });
392
+ return;
393
+ } catch (error) {
394
+ if (signal.aborted) throw error;
395
+ if (!(!(error instanceof HTTPStatusError) || error.retryable) || attempt >= MAX_ATTEMPTS) {
396
+ const reason = error instanceof Error ? error.message : String(error);
397
+ fail(`Could not download "${file.name}" (${reason}): ${file.url}`);
398
+ }
399
+ await setTimeout$1(RETRY_DELAY_MS * attempt, void 0, { signal });
400
+ }
401
+ }
402
+ }
403
+ /**
404
+ * Download snapshot files into `directory`, a few at a time, each to the path
405
+ * {@link getSnapshotPaths} gives it. The first file that cannot be downloaded
406
+ * cancels the others, and its error is thrown once they have all stopped.
407
+ */
408
+ async function downloadSnapshots(files, directory, options = {}) {
409
+ const paths = getSnapshotPaths(files);
410
+ const entries = files.map((file, index) => ({
411
+ ...file,
412
+ path: join(directory, paths[index])
413
+ }));
414
+ const controller = new AbortController();
415
+ let failure = null;
416
+ let next = 0;
417
+ let done = 0;
418
+ const work = async () => {
419
+ try {
420
+ while (!controller.signal.aborted && next < entries.length) {
421
+ const entry = entries[next++];
422
+ await mkdir(dirname(entry.path), { recursive: true });
423
+ await downloadFile(entry, entry.path, controller.signal);
424
+ options.onProgress?.(++done, entries.length);
425
+ }
426
+ } catch (error) {
427
+ if (!failure) {
428
+ failure = { error };
429
+ controller.abort();
430
+ }
431
+ }
432
+ };
433
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, entries.length) }, work));
434
+ if (failure) throw failure.error;
435
+ return entries;
436
+ }
437
+ /**
438
+ * Download the snapshot each diff captured (its head; a removed diff has none)
439
+ * into `directory`, showing progress unless the output is JSON.
440
+ */
441
+ async function downloadBuildSnapshots(args) {
442
+ const snapshots = args.diffs.flatMap((diff) => diff.head ? [{
443
+ name: diff.head.name,
444
+ url: diff.head.url,
445
+ contentType: diff.head.contentType,
446
+ status: diff.status
447
+ }] : []);
448
+ const spinner = args.json || snapshots.length === 0 ? null : ora(`Downloading ${snapshots.length} snapshots`).start();
449
+ try {
450
+ const files = await downloadSnapshots(snapshots, args.directory, { onProgress: (done, total) => {
451
+ if (spinner) spinner.text = `Downloading snapshots (${done}/${total})`;
452
+ } });
453
+ return {
454
+ build: args.build,
455
+ directory: args.directory,
456
+ files
457
+ };
458
+ } finally {
459
+ spinner?.stop();
460
+ }
461
+ }
462
+ // src/lib/terminal.ts
256
463
  /**
257
464
  * Printing text the CLI did not author — an OAuth error description chosen by
258
465
  * the authorization server, for instance.
@@ -300,8 +507,7 @@ function sanitizeTerminalText(text) {
300
507
  const sanitized = String(text).replace(ESCAPE_SEQUENCE_REGEX, "").replace(DIRECTIONAL_FORMATTING_REGEX, "").replace(CONTROL_CHARACTER_REGEX, " ").replace(/\s+/g, " ").trim();
301
508
  return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}…` : sanitized;
302
509
  }
303
- //#endregion
304
- //#region src/lib/format.ts
510
+ // src/lib/format.ts
305
511
  /** Render a scalar, using `-` for empty values. */
306
512
  function formatValue(value) {
307
513
  if (value === null || value === void 0 || value === "") return "-";
@@ -337,7 +543,7 @@ function formatProject(project) {
337
543
  `ID: ${project.id}`,
338
544
  `Visibility: ${project.private ? "private" : "public"}`,
339
545
  `Default base branch: ${formatValue(project.defaultBaseBranch)}`,
340
- `Auto-approved branches: ${formatValue(project.autoApprovedBranchGlob)}`,
546
+ `Auto-approved branches: ${project.autoApprovalEnabled ? formatValue(project.autoApprovedBranchGlob) : "none"}`,
341
547
  `Summary check: ${project.summaryCheck}`,
342
548
  `PR comment: ${formatBoolean(project.prCommentEnabled)}`,
343
549
  `Default user level: ${formatValue(project.defaultUserLevel)}`,
@@ -429,6 +635,35 @@ function formatSnapshots(diffs, build) {
429
635
  ...diffs.flatMap((diff) => [...formatSnapshotDiff(diff, build), ""])
430
636
  ].slice(0, -1).join("\n");
431
637
  }
638
+ function formatBuilds(builds) {
639
+ if (builds.length === 0) return "No builds found.";
640
+ return [
641
+ `Builds (${builds.length})`,
642
+ "",
643
+ ...builds.flatMap((build) => [
644
+ `#${build.number} [${build.status}]`,
645
+ ` Branch: ${formatValue(build.head.branch)}`,
646
+ ` Commit: ${formatValue(build.head.sha)}`,
647
+ ` Snapshots: ${formatStats(build.stats)}`,
648
+ ` URL: ${build.url}`,
649
+ ""
650
+ ])
651
+ ].slice(0, -1).join("\n");
652
+ }
653
+ /**
654
+ * Format the result of a download. `kind` names what was downloaded, e.g.
655
+ * `baseline snapshot`, and is pluralized as needed.
656
+ */
657
+ function formatSnapshotDownload(download, kind = "snapshot") {
658
+ const { build, directory, files } = download;
659
+ if (files.length === 0) return `Build #${build.number} has no ${kind}s to download.`;
660
+ return [
661
+ `Downloaded ${files.length} ${kind}${files.length === 1 ? "" : "s"} of build #${build.number} to ${directory}`,
662
+ `Branch: ${formatValue(build.head.branch)}`,
663
+ `Commit: ${formatValue(build.head.sha)}`,
664
+ `URL: ${build.url}`
665
+ ].join("\n");
666
+ }
432
667
  /** When and where a change was captured, on one line. */
433
668
  function formatOccurrence(occurrence) {
434
669
  return `${occurrence.date} in build #${occurrence.buildNumber}`;
@@ -662,6 +897,42 @@ function formatDeployments(deployments) {
662
897
  function formatProjectDomain(domain) {
663
898
  return `Deployment domain: ${formatValue(domain.domain)}`;
664
899
  }
900
+ function formatTokenExpiration(expireAt) {
901
+ if (!expireAt) return "never";
902
+ return Date.parse(expireAt) <= Date.now() ? `${expireAt} (expired)` : expireAt;
903
+ }
904
+ /** The details of a project token, under its title line. */
905
+ function formatProjectTokenDetails(token) {
906
+ return [
907
+ ` Projects: ${formatValue(token.projects.join(", "))}`,
908
+ ` Permissions: ${token.permissions.join(", ")}`,
909
+ ` Created: ${token.createdAt}`,
910
+ ` Expires: ${formatTokenExpiration(token.expireAt)}`,
911
+ ` Last used: ${token.lastUsedAt ?? "never"}`
912
+ ];
913
+ }
914
+ function formatProjectTokens(tokens) {
915
+ if (tokens.length === 0) return "No tokens found.";
916
+ return [
917
+ `Tokens (${tokens.length})`,
918
+ "",
919
+ ...tokens.flatMap((token) => [
920
+ `${sanitizeTerminalText(token.name)} · ${token.id}`,
921
+ ...formatProjectTokenDetails(token),
922
+ ""
923
+ ])
924
+ ].slice(0, -1).join("\n");
925
+ }
926
+ function formatCreatedProjectToken(token) {
927
+ return [
928
+ `Created token ${sanitizeTerminalText(token.name)} · ${token.id}`,
929
+ ...formatProjectTokenDetails(token),
930
+ "",
931
+ token.token,
932
+ "",
933
+ "Save this token now: Argos does not store it and will not show it again."
934
+ ].join("\n");
935
+ }
665
936
  function formatIgnoredChanges(changes) {
666
937
  if (changes.length === 0) return "No ignored changes found.";
667
938
  return [
@@ -812,20 +1083,20 @@ function formatMediaVersions(versions) {
812
1083
  }
813
1084
  /**
814
1085
  * Format documentation search results, best match first. Titles and excerpts
815
- * come from the docs host, so they are sanitized before reaching the terminal;
816
- * the excerpt is also cut down to a single line.
1086
+ * come from the docs host, so they are sanitized before reaching the terminal,
1087
+ * which also cuts the excerpt down to a single line. URLs were normalized when
1088
+ * the results were parsed.
817
1089
  */
818
1090
  function formatDocsSearchResults(results, query) {
819
1091
  if (results.length === 0) return `No documentation found for "${sanitizeTerminalText(query)}".`;
820
1092
  return results.flatMap((result, index) => [
821
1093
  `${index + 1}. ${sanitizeTerminalText(result.title)}`,
822
- indent(sanitizeTerminalText(result.url)),
823
- result.excerpt ? indent(sanitizeTerminalText(result.excerpt)) : null,
1094
+ ` ${result.url}`,
1095
+ result.excerpt ? ` ${sanitizeTerminalText(result.excerpt)}` : null,
824
1096
  ""
825
1097
  ]).filter((line) => line !== null).slice(0, -1).join("\n");
826
1098
  }
827
- //#endregion
828
- //#region src/lib/oauth.ts
1099
+ // src/lib/oauth.ts
829
1100
  /**
830
1101
  * OAuth 2.1 client configuration and helpers for the `argos login` flow
831
1102
  * (Authorization Code + PKCE with a loopback redirect, RFC 8252).
@@ -837,7 +1108,8 @@ function formatDocsSearchResults(results, query) {
837
1108
  const OAUTH_CLIENT_ID = "argos-cli";
838
1109
  /**
839
1110
  * Scopes requested by `argos login`, covering the CLI's user actions (identity,
840
- * projects, reviews, comments, media). Build upload keeps using a project token.
1111
+ * projects, reviews, comments, media, team administration). Build upload keeps
1112
+ * using a project token.
841
1113
  *
842
1114
  * Every scope a CLI command needs has to be listed here: the consent screen
843
1115
  * only offers what the client asks for, so a missing entry is not something the
@@ -851,8 +1123,19 @@ const OAUTH_SCOPES = [
851
1123
  "comments:read",
852
1124
  "comments:write",
853
1125
  "media:read",
854
- "media:write"
1126
+ "media:write",
1127
+ "account:admin"
855
1128
  ];
1129
+ /**
1130
+ * Requested scopes that the consent screen grants only with "Admin" access
1131
+ * (`level: "admin"` in the Argos backend's `apps/backend/src/oauth/scopes.ts`).
1132
+ * The default, "Read and write", leaves them out, so a session can lack them
1133
+ * even when it was granted after the CLI started asking for them.
1134
+ */
1135
+ const OAUTH_ADMIN_SCOPES = /* @__PURE__ */ new Set(["projects:write", "account:admin"]);
1136
+ function isRequestedOAuthScope(value) {
1137
+ return OAUTH_SCOPES.includes(value);
1138
+ }
856
1139
  /** Refresh a bit early so a token never expires mid-request. */
857
1140
  const EXPIRY_SKEW_MS = 6e4;
858
1141
  function getAppBaseUrl() {
@@ -942,8 +1225,7 @@ async function revokeToken(token) {
942
1225
  }).toString()
943
1226
  }).catch(() => {});
944
1227
  }
945
- //#endregion
946
- //#region src/auth.ts
1228
+ // src/auth.ts
947
1229
  function getConfigPaths() {
948
1230
  const configDir = resolve(homedir(), ".config", "argos-ci");
949
1231
  return {
@@ -1044,8 +1326,7 @@ async function getStoredCredentials() {
1044
1326
  async function clearStoredCredentials() {
1045
1327
  await writeConfig({});
1046
1328
  }
1047
- //#endregion
1048
- //#region src/lib/build-reference.ts
1329
+ // src/lib/build-reference.ts
1049
1330
  const BUILD_URL_REGEXP = /^https:\/\/app\.argos-ci\.(?:com|dev(?::\d+)?)\/(?<owner>[^/?#]+)\/(?<project>[^/?#]+)\/builds\/(?<buildNumber>\d+)(?:[/?#]|$)/;
1050
1331
  /**
1051
1332
  * Parse a build reference, accepting either a bare build number (`"1234"`) or a
@@ -1071,8 +1352,7 @@ function parseBuildReferenceOrFail(reference) {
1071
1352
  if (!parsed) fail(`Build reference must be a valid build number or Argos build URL (https://app.argos-ci.com/.../builds/<number>), got "${reference}".`);
1072
1353
  return parsed;
1073
1354
  }
1074
- //#endregion
1075
- //#region src/lib/project.ts
1355
+ // src/lib/project.ts
1076
1356
  /**
1077
1357
  * Parse a `owner/project` slug. Returns `null` when it is not exactly two
1078
1358
  * non-empty segments.
@@ -1093,8 +1373,7 @@ function parseProjectPathOrFail(slug) {
1093
1373
  if (!parsed) fail("--project must be in the format 'owner/project'.");
1094
1374
  return parsed;
1095
1375
  }
1096
- //#endregion
1097
- //#region src/lib/target.ts
1376
+ // src/lib/target.ts
1098
1377
  /**
1099
1378
  * Resolve the API token if there is one, preferring an explicit token
1100
1379
  * (`--token` / `ARGOS_TOKEN`) over the one stored by `argos login`.
@@ -1115,14 +1394,20 @@ async function resolveToken(options) {
1115
1394
  if (!token) fail("No Argos token found. Use --token, set ARGOS_TOKEN, or run `argos login`.");
1116
1395
  return token;
1117
1396
  }
1397
+ /**
1398
+ * The project named by `--project` or the `ARGOS_PROJECT` environment variable,
1399
+ * or `null` when neither is set. Aborts on a value that is not `owner/project`.
1400
+ */
1401
+ function resolveProjectPath(options) {
1402
+ const slug = options.project || process.env["ARGOS_PROJECT"];
1403
+ return slug ? parseProjectPathOrFail(slug) : null;
1404
+ }
1118
1405
  function explicitProjectPath(reference, options) {
1119
1406
  if (reference.owner && reference.project) return {
1120
1407
  owner: reference.owner,
1121
1408
  project: reference.project
1122
1409
  };
1123
- const project = options.project || process.env["ARGOS_PROJECT"];
1124
- if (project) return parseProjectPathOrFail(project);
1125
- return null;
1410
+ return resolveProjectPath(options);
1126
1411
  }
1127
1412
  /**
1128
1413
  * Resolve a build reference into a ready-to-use {@link BuildTarget}: an
@@ -1168,10 +1453,10 @@ async function resolveBuildTarget(reference, options, { auth }) {
1168
1453
  */
1169
1454
  async function resolveProjectTarget(options, { auth }) {
1170
1455
  const client = createApiClient(await resolveToken(options));
1171
- const projectPath = options.project || process.env["ARGOS_PROJECT"];
1456
+ const projectPath = resolveProjectPath(options);
1172
1457
  if (projectPath) return {
1173
1458
  client,
1174
- ...parseProjectPathOrFail(projectPath)
1459
+ ...projectPath
1175
1460
  };
1176
1461
  if (auth === "user") fail("--project <owner/project> is required. Pass it or set ARGOS_PROJECT.");
1177
1462
  const project = unwrap(await client.GET("/project"));
@@ -1195,10 +1480,8 @@ async function resolveAccountTarget(options) {
1195
1480
  accountSlug
1196
1481
  };
1197
1482
  }
1198
- //#endregion
1199
- //#region src/lib/run.ts
1483
+ // src/lib/run.ts
1200
1484
  const USER_AUTH_HINT = "Ensure your token is a personal access token with access to this project. Project tokens (ARGOS_TOKEN in CI) can read build data but cannot perform review or comment actions.";
1201
- const SCOPE_HINT = "Your `argos login` session was granted before the CLI asked for this permission. Run `argos login` again to grant it.";
1202
1485
  /**
1203
1486
  * A scope rejection, as opposed to any other 403: the token is valid and the
1204
1487
  * user is allowed, it was simply issued without the permission this endpoint
@@ -1209,6 +1492,34 @@ function isInsufficientScope(error) {
1209
1492
  return error.status === 403 && /insufficient scope/i.test(error.message);
1210
1493
  }
1211
1494
  /**
1495
+ * The scopes named by a scope rejection ("Insufficient scope. This endpoint
1496
+ * requires: account:admin."). Anything not shaped like a scope is dropped, so
1497
+ * the hint never echoes arbitrary server text.
1498
+ */
1499
+ function parseRequiredScopes(message) {
1500
+ const match = /requires:\s*([^.]*)/i.exec(message);
1501
+ if (!match?.[1]) return [];
1502
+ return match[1].split(",").map((scope) => scope.trim()).filter((scope) => /^[a-z]+(?::[a-z]+)?$/.test(scope));
1503
+ }
1504
+ function formatScopes(scopes) {
1505
+ return scopes.map((scope) => `\`${scope}\``).join(", ");
1506
+ }
1507
+ /**
1508
+ * How to get the scopes an `argos login` session is missing. A session lacks a
1509
+ * scope for one of three reasons, each with its own fix: the CLI never asks for
1510
+ * it (only a personal access token helps), it is an admin scope left out by the
1511
+ * consent screen's default access level, or the session was granted before the
1512
+ * CLI asked for it.
1513
+ */
1514
+ function getScopeHint(message) {
1515
+ const required = parseRequiredScopes(message);
1516
+ if (required.length === 0) return "Run `argos login` again to grant the permission this command needs.";
1517
+ const ungrantable = required.filter((scope) => !isRequestedOAuthScope(scope));
1518
+ if (ungrantable.length > 0) return `\`argos login\` cannot grant ${formatScopes(ungrantable)}. Use a personal access token instead (\`--token\` or \`ARGOS_TOKEN\`).`;
1519
+ if (required.some((scope) => isRequestedOAuthScope(scope) && OAUTH_ADMIN_SCOPES.has(scope))) return `Your \`argos login\` session does not include ${formatScopes(required)}. Run \`argos login\` again and choose "Admin" access on the consent screen to grant it.`;
1520
+ return `Your \`argos login\` session does not include ${formatScopes(required)}. Run \`argos login\` again to grant it.`;
1521
+ }
1522
+ /**
1212
1523
  * Print an error and exit. {@link CliError} and {@link APIError} messages are
1213
1524
  * shown as-is; permission failures get an extra hint — how to grant a missing
1214
1525
  * scope, or which token type the command needs.
@@ -1217,7 +1528,7 @@ function handleCliError(error, auth) {
1217
1528
  let message;
1218
1529
  if (error instanceof CliError || error instanceof APIError) {
1219
1530
  message = error.message;
1220
- if (error instanceof APIError && isInsufficientScope(error)) message += `\n${SCOPE_HINT}`;
1531
+ if (error instanceof APIError && isInsufficientScope(error)) message += `\n${getScopeHint(error.message)}`;
1221
1532
  else if (auth === "user" && error instanceof APIError && (error.status === 401 || error.status === 403)) message += `\n${USER_AUTH_HINT}`;
1222
1533
  } else if (error instanceof Error) message = error.message;
1223
1534
  else message = String(error);
@@ -1240,8 +1551,27 @@ async function runBuildAction(opts) {
1240
1551
  handleCliError(error, opts.auth);
1241
1552
  }
1242
1553
  }
1243
- //#endregion
1244
- //#region src/commands/build/get.ts
1554
+ // src/commands/build/download.ts
1555
+ function registerBuildDownload(build) {
1556
+ build.command("download").description("Download the screenshots of a build to a directory, laid out by snapshot name").argument("<buildReference>", "Build number or Argos build URL").option("-o, --output <directory>", "Directory to write the screenshots to. Must be empty or not exist yet. Defaults to ./argos-build-<number>").addOption(tokenOption).addOption(buildProjectPathOption).addOption(jsonOption).action(async (reference, options) => {
1557
+ try {
1558
+ const target = await resolveBuildTarget(reference, options, { auth: "project" });
1559
+ const directory = resolve(options.output ?? `argos-build-${target.buildNumber}`);
1560
+ await assertEmptyDirectory(directory);
1561
+ const build = await fetchBuild(target);
1562
+ if (isBuildPending(build)) fail(`Build #${build.number} is still processing (${build.status}). Try again in a moment.`);
1563
+ output(await downloadBuildSnapshots({
1564
+ build,
1565
+ diffs: await fetchAllDiffs(target),
1566
+ directory,
1567
+ json: options.json
1568
+ }), options, (data) => formatSnapshotDownload(data));
1569
+ } catch (error) {
1570
+ handleCliError(error, "project");
1571
+ }
1572
+ });
1573
+ }
1574
+ // src/commands/build/get.ts
1245
1575
  function registerBuildGet(build) {
1246
1576
  build.command("get").description("Fetch build metadata").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(jsonOption).action((reference, options) => runBuildAction({
1247
1577
  reference,
@@ -1255,43 +1585,52 @@ function registerBuildGet(build) {
1255
1585
  format: formatBuild
1256
1586
  }));
1257
1587
  }
1258
- //#endregion
1259
- //#region src/commands/build/snapshots.ts
1260
- const PER_PAGE$1 = 100;
1261
- function isBuildPending(build) {
1262
- return build.status === "pending" || build.status === "progress";
1263
- }
1264
- async function fetchBuild(target) {
1265
- const { client, owner, project, buildNumber } = target;
1266
- return unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}", { params: { path: {
1267
- owner,
1268
- project,
1269
- buildNumber
1270
- } } }));
1271
- }
1272
- /** Fetch every diff of a build, following pagination. */
1273
- async function fetchAllDiffs(target, options) {
1274
- const { client, owner, project, buildNumber } = target;
1588
+ // src/lib/pagination.ts
1589
+ /** Largest page the API serves. */
1590
+ const MAX_PER_PAGE = 100;
1591
+ /**
1592
+ * Walk a paginated endpoint until `limit` items have been collected, the server
1593
+ * runs out of results, or its reported total is reached.
1594
+ *
1595
+ * `fetchPage` receives the page number and the size to request, both already
1596
+ * stringified — every paginated Argos endpoint takes them as query strings.
1597
+ */
1598
+ async function fetchPages(limit, fetchPage) {
1599
+ const perPage = String(Math.min(MAX_PER_PAGE, limit));
1275
1600
  const results = [];
1276
1601
  for (let page = 1;; page++) {
1277
- const data = unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}/diffs", { params: {
1278
- path: {
1279
- owner,
1280
- project,
1281
- buildNumber
1282
- },
1283
- query: {
1284
- page: String(page),
1285
- perPage: String(PER_PAGE$1),
1286
- metricsPeriod: options.metricsPeriod,
1287
- ...options.needsReview ? { needsReview: "true" } : {}
1288
- }
1289
- } }));
1602
+ const data = await fetchPage({
1603
+ page: String(page),
1604
+ perPage
1605
+ });
1290
1606
  results.push(...data.results);
1291
- if (results.length >= data.pageInfo.total || data.results.length === 0) break;
1607
+ if (results.length >= limit || results.length >= data.pageInfo.total || data.results.length === 0) break;
1292
1608
  }
1293
- return results;
1609
+ return results.slice(0, limit);
1610
+ }
1611
+ // src/commands/build/list.ts
1612
+ function registerBuildList(build) {
1613
+ build.command("list").description("List a project's builds, most recent first").option("--branch <name>", "Only list the builds of this branch").option("--commit <sha>", "Only list the builds of this commit, given as a full 40-character SHA. Use --search to match a prefix").option("--search <query>", "Match builds on their name, branch (substring) or commit (prefix)").addOption(limitOption).addOption(tokenOption).addOption(buildProjectPathOption).addOption(jsonOption).action(async (options) => {
1614
+ try {
1615
+ const { client, owner, project } = await resolveProjectTarget(options, { auth: "project" });
1616
+ output(await fetchPages(toLimit(options.limit), async (pagination) => unwrap(await client.GET("/projects/{owner}/{project}/builds", { params: {
1617
+ path: {
1618
+ owner,
1619
+ project
1620
+ },
1621
+ query: {
1622
+ ...pagination,
1623
+ ...options.branch ? { head: options.branch } : {},
1624
+ ...options.commit ? { headSha: options.commit } : {},
1625
+ ...options.search ? { search: options.search } : {}
1626
+ }
1627
+ } }))), options, formatBuilds);
1628
+ } catch (error) {
1629
+ handleCliError(error, "project");
1630
+ }
1631
+ });
1294
1632
  }
1633
+ // src/commands/build/snapshots.ts
1295
1634
  function registerBuildSnapshots(build) {
1296
1635
  build.command("snapshots").description("Fetch snapshot diffs for a build").argument("<buildReference>", "Build number or Argos build URL").addOption(new Option("--needs-review", "Only include snapshot diffs that require review")).addOption(metricsPeriodOption).addOption(tokenOption).addOption(jsonOption).action(async (reference, options) => {
1297
1636
  try {
@@ -1315,8 +1654,7 @@ function registerBuildSnapshots(build) {
1315
1654
  }
1316
1655
  });
1317
1656
  }
1318
- //#endregion
1319
- //#region src/commands/build/subscription.ts
1657
+ // src/commands/build/subscription.ts
1320
1658
  /** Register `build subscribe` / `build unsubscribe`; both act as a user. */
1321
1659
  function defineBuildSubscription(opts) {
1322
1660
  return (build) => {
@@ -1347,17 +1685,105 @@ const registerBuildUnsubscribe = defineBuildSubscription({
1347
1685
  buildNumber
1348
1686
  } } }))
1349
1687
  });
1350
- //#endregion
1351
- //#region src/commands/build/index.ts
1688
+ // src/commands/build/index.ts
1352
1689
  function buildCommand(program) {
1353
- const build = program.command("build").description("Inspect Argos builds");
1690
+ const build = program.command("build").description("Inspect and download Argos builds");
1691
+ registerBuildList(build);
1354
1692
  registerBuildGet(build);
1355
1693
  registerBuildSnapshots(build);
1694
+ registerBuildDownload(build);
1356
1695
  registerBuildSubscribe(build);
1357
1696
  registerBuildUnsubscribe(build);
1358
1697
  }
1359
- //#endregion
1360
- //#region src/lib/body.ts
1698
+ /**
1699
+ * Find the most recent baseline among a branch's builds.
1700
+ *
1701
+ * Whether a build can be a baseline (complete, tests passed, not a subset,
1702
+ * approved and not rejected) is not part of the build the API returns, so this
1703
+ * leaves the decision to Argos: it walks the branch's builds newest first, a
1704
+ * page at a time, and asks `findBaseline` for the first of their commits that
1705
+ * has an eligible build. Gives up after `maxPages` pages.
1706
+ */
1707
+ async function findLatestBaseline(api, { maxPages = 10 } = {}) {
1708
+ const asked = /* @__PURE__ */ new Set();
1709
+ let listed = 0;
1710
+ for (let page = 1; page <= maxPages; page++) {
1711
+ const { results, pageInfo } = await api.listBuilds(page);
1712
+ listed += results.length;
1713
+ const commits = [...new Set(results.map((build) => build.head.sha))].filter((sha) => !asked.has(sha));
1714
+ if (commits.length > 0) {
1715
+ commits.forEach((sha) => asked.add(sha));
1716
+ const baseline = await api.findBaseline(commits);
1717
+ if (baseline) return baseline;
1718
+ }
1719
+ if (results.length === 0 || listed >= pageInfo.total) break;
1720
+ }
1721
+ return null;
1722
+ }
1723
+ // src/commands/baseline/download.ts
1724
+ const PROJECT_TOKEN_HINT = "Finding the baseline takes the project's token: pass it with --token or set ARGOS_TOKEN. The token stored by `argos login` cannot be used.";
1725
+ const FAILURE_STATUSES = /* @__PURE__ */ new Set(["failure", "retryFailure"]);
1726
+ async function fetchTokenProject(client, project) {
1727
+ try {
1728
+ return unwrap(await client.GET("/project", { params: { query: { project } } }));
1729
+ } catch (error) {
1730
+ if (error instanceof APIError && (error.status === 401 || error.status === 403)) fail(`${error.message}\n${PROJECT_TOKEN_HINT}`);
1731
+ throw error;
1732
+ }
1733
+ }
1734
+ function registerBaselineDownload(baseline) {
1735
+ baseline.command("download").description("Download a project's latest baseline: the screenshots of the newest build of its default branch that Argos can use as a baseline").option("-o, --output <directory>", "Directory to write the screenshots to, laid out by snapshot name. Must be empty or not exist yet. Defaults to ./argos-baseline").option("--branch <name>", "Branch to take the baseline from. Defaults to the project's default base branch").addOption(new Option("--build-name <name>", "Name of the build to take the baseline of, as given to `argos upload --build-name`").default("default")).addOption(new Option("--mode <mode>", "Mode of the build to take the baseline of: ci for visual regression testing, monitoring for visual monitoring").choices(["ci", "monitoring"]).default("ci")).addOption(buildProjectPathOption).addOption(tokenOption).addOption(jsonOption).action(async (options) => {
1736
+ try {
1737
+ const directory = resolve(options.output ?? "argos-baseline");
1738
+ await assertEmptyDirectory(directory);
1739
+ const token = await resolveOptionalToken(options);
1740
+ if (!token) fail("No Argos token found. Pass the project's token with --token or set ARGOS_TOKEN.");
1741
+ const client = createApiClient(token);
1742
+ const projectPath = resolveProjectPath(options);
1743
+ const projectSlug = projectPath ? `${projectPath.owner}/${projectPath.project}` : void 0;
1744
+ const project = await fetchTokenProject(client, projectSlug);
1745
+ const path = {
1746
+ owner: project.account.slug,
1747
+ project: project.name
1748
+ };
1749
+ const branch = options.branch ?? project.defaultBaseBranch;
1750
+ const build = await findLatestBaseline({
1751
+ listBuilds: async (page) => unwrap(await client.GET("/projects/{owner}/{project}/builds", { params: {
1752
+ path,
1753
+ query: {
1754
+ head: branch,
1755
+ page: String(page),
1756
+ perPage: String(100)
1757
+ }
1758
+ } })),
1759
+ findBaseline: async (commits) => unwrap(await client.POST("/baseline", { body: {
1760
+ project: projectSlug,
1761
+ commits,
1762
+ name: options.buildName,
1763
+ mode: options.mode
1764
+ } })).baseline
1765
+ });
1766
+ if (!build) fail(`No baseline found on branch "${branch}" for build name "${options.buildName}" (${options.mode} mode). Check --branch, --build-name and --mode; only the latest 1000 builds of the branch are searched.`);
1767
+ output(await downloadBuildSnapshots({
1768
+ build,
1769
+ diffs: (await fetchAllDiffs({
1770
+ client,
1771
+ ...path,
1772
+ buildNumber: String(build.number)
1773
+ })).filter((diff) => !FAILURE_STATUSES.has(diff.status)),
1774
+ directory,
1775
+ json: options.json
1776
+ }), options, (data) => formatSnapshotDownload(data, "baseline snapshot"));
1777
+ } catch (error) {
1778
+ handleCliError(error, "project");
1779
+ }
1780
+ });
1781
+ }
1782
+ // src/commands/baseline/index.ts
1783
+ function baselineCommand(program) {
1784
+ registerBaselineDownload(program.command("baseline").description("Export a project's baseline screenshots"));
1785
+ }
1786
+ // src/lib/body.ts
1361
1787
  /**
1362
1788
  * Resolve the Markdown body of a comment or review from the mutually-exclusive
1363
1789
  * `--body` (inline) and `--body-file` (path) options.
@@ -1377,8 +1803,7 @@ async function resolveBody(options, { required = false } = {}) {
1377
1803
  }
1378
1804
  if (required) fail("A comment body is required. Use --body <markdown> or --body-file <path>.");
1379
1805
  }
1380
- //#endregion
1381
- //#region src/commands/review/create.ts
1806
+ // src/commands/review/create.ts
1382
1807
  const events = {
1383
1808
  approve: "APPROVE",
1384
1809
  reject: "REJECT",
@@ -1406,8 +1831,7 @@ function registerReviewCreate(review) {
1406
1831
  format: formatReview
1407
1832
  }));
1408
1833
  }
1409
- //#endregion
1410
- //#region src/commands/review/dismiss.ts
1834
+ // src/commands/review/dismiss.ts
1411
1835
  function registerReviewDismiss(review) {
1412
1836
  review.command("dismiss").description("Dismiss a submitted review on a build").argument("<buildReference>", "Build number or Argos build URL").argument("<reviewId>", "ID of the review to dismiss").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, reviewId, options) => runBuildAction({
1413
1837
  reference,
@@ -1422,8 +1846,7 @@ function registerReviewDismiss(review) {
1422
1846
  format: formatReview
1423
1847
  }));
1424
1848
  }
1425
- //#endregion
1426
- //#region src/commands/review/list.ts
1849
+ // src/commands/review/list.ts
1427
1850
  function registerReviewList(review) {
1428
1851
  review.command("list").description("List the reviews submitted on a build").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, options) => runBuildAction({
1429
1852
  reference,
@@ -1437,8 +1860,7 @@ function registerReviewList(review) {
1437
1860
  format: formatReviews
1438
1861
  }));
1439
1862
  }
1440
- //#endregion
1441
- //#region src/commands/review/reviewer.ts
1863
+ // src/commands/review/reviewer.ts
1442
1864
  function registerReviewReviewer(review) {
1443
1865
  const reviewer = review.command("reviewer").description("List, request, and cancel review requests on a build");
1444
1866
  reviewer.command("list").description("List the users currently requested to review a build").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, options) => runBuildAction({
@@ -1481,8 +1903,7 @@ function registerReviewReviewer(review) {
1481
1903
  format: formatReviewers
1482
1904
  }));
1483
1905
  }
1484
- //#endregion
1485
- //#region src/commands/review/index.ts
1906
+ // src/commands/review/index.ts
1486
1907
  function reviewCommand(program) {
1487
1908
  const review = program.command("review").description("List, submit, and dismiss build reviews");
1488
1909
  registerReviewList(review);
@@ -1490,8 +1911,7 @@ function reviewCommand(program) {
1490
1911
  registerReviewDismiss(review);
1491
1912
  registerReviewReviewer(review);
1492
1913
  }
1493
- //#endregion
1494
- //#region src/lib/anchor.ts
1914
+ // src/lib/anchor.ts
1495
1915
  function parsePair(value) {
1496
1916
  const parts = value.split(",").map((part) => Number(part.trim()));
1497
1917
  if (parts.length !== 2 || parts.some((part) => Number.isNaN(part))) return null;
@@ -1527,8 +1947,7 @@ function parseAnchor(options) {
1527
1947
  };
1528
1948
  }
1529
1949
  }
1530
- //#endregion
1531
- //#region src/commands/comment/create.ts
1950
+ // src/commands/comment/create.ts
1532
1951
  function registerCommentCreate(comment) {
1533
1952
  comment.command("create").description("Post a comment (or reply) on a build").argument("<buildReference>", "Build number or Argos build URL").option("--body <markdown>", "Markdown body of the comment").option("--body-file <path>", "Read the comment body from a Markdown file").option("--reply-to <threadId>", "Reply to an existing thread (its root comment ID)").option("--diff <screenshotDiffId>", "Anchor the comment to a screenshot diff").option("--anchor-point <x,y>", "Point on the diff in normalized 0-1 coordinates (requires --diff)").option("--anchor-lines <from,to>", "1-based inclusive line range on the diff (requires --diff)").option("--draft", "Attach to your pending review instead of posting immediately").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, options) => runBuildAction({
1534
1953
  reference,
@@ -1556,8 +1975,7 @@ function registerCommentCreate(comment) {
1556
1975
  format: formatComment
1557
1976
  }));
1558
1977
  }
1559
- //#endregion
1560
- //#region src/commands/comment/_action.ts
1978
+ // src/commands/comment/_action.ts
1561
1979
  /**
1562
1980
  * Register a `comment <name> <buildReference> <commentId>` command that runs
1563
1981
  * `perform` and prints the returned comment. Used for the single-comment
@@ -1580,8 +1998,7 @@ function defineCommentAction(opts) {
1580
1998
  }));
1581
1999
  };
1582
2000
  }
1583
- //#endregion
1584
- //#region src/commands/comment/delete.ts
2001
+ // src/commands/comment/delete.ts
1585
2002
  const registerCommentDelete = defineCommentAction({
1586
2003
  name: "delete",
1587
2004
  description: "Delete a comment on a build (author only)",
@@ -1592,8 +2009,7 @@ const registerCommentDelete = defineCommentAction({
1592
2009
  commentId
1593
2010
  } } }))
1594
2011
  });
1595
- //#endregion
1596
- //#region src/commands/comment/edit.ts
2012
+ // src/commands/comment/edit.ts
1597
2013
  function registerCommentEdit(comment) {
1598
2014
  comment.command("edit").description("Update the body of a comment (author only)").argument("<buildReference>", "Build number or Argos build URL").argument("<commentId>", "ID of the comment").option("--body <markdown>", "New Markdown body of the comment").option("--body-file <path>", "Read the new body from a Markdown file").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, commentId, options) => runBuildAction({
1599
2015
  reference,
@@ -1614,8 +2030,7 @@ function registerCommentEdit(comment) {
1614
2030
  format: formatComment
1615
2031
  }));
1616
2032
  }
1617
- //#endregion
1618
- //#region src/commands/comment/get.ts
2033
+ // src/commands/comment/get.ts
1619
2034
  const registerCommentGet = defineCommentAction({
1620
2035
  name: "get",
1621
2036
  description: "Fetch a single comment on a build",
@@ -1626,8 +2041,7 @@ const registerCommentGet = defineCommentAction({
1626
2041
  commentId
1627
2042
  } } }))
1628
2043
  });
1629
- //#endregion
1630
- //#region src/commands/comment/list.ts
2044
+ // src/commands/comment/list.ts
1631
2045
  function registerCommentList(comment) {
1632
2046
  comment.command("list").description("List the comments on a build").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, options) => runBuildAction({
1633
2047
  reference,
@@ -1641,8 +2055,7 @@ function registerCommentList(comment) {
1641
2055
  format: formatComments
1642
2056
  }));
1643
2057
  }
1644
- //#endregion
1645
- //#region src/commands/comment/react.ts
2058
+ // src/commands/comment/react.ts
1646
2059
  function registerCommentReact(comment) {
1647
2060
  comment.command("react").description("Add an emoji reaction to a comment").argument("<buildReference>", "Build number or Argos build URL").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji to react with").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, commentId, emoji, options) => runBuildAction({
1648
2061
  reference,
@@ -1660,8 +2073,7 @@ function registerCommentReact(comment) {
1660
2073
  format: formatComment
1661
2074
  }));
1662
2075
  }
1663
- //#endregion
1664
- //#region src/commands/comment/resolve.ts
2076
+ // src/commands/comment/resolve.ts
1665
2077
  const registerCommentResolve = defineCommentAction({
1666
2078
  name: "resolve",
1667
2079
  description: "Mark a comment thread as resolved",
@@ -1672,8 +2084,7 @@ const registerCommentResolve = defineCommentAction({
1672
2084
  commentId
1673
2085
  } } }))
1674
2086
  });
1675
- //#endregion
1676
- //#region src/commands/comment/subscribe.ts
2087
+ // src/commands/comment/subscribe.ts
1677
2088
  const registerCommentSubscribe = defineCommentAction({
1678
2089
  name: "subscribe",
1679
2090
  description: "Subscribe to a comment thread's notifications",
@@ -1684,8 +2095,7 @@ const registerCommentSubscribe = defineCommentAction({
1684
2095
  commentId
1685
2096
  } } }))
1686
2097
  });
1687
- //#endregion
1688
- //#region src/commands/comment/unreact.ts
2098
+ // src/commands/comment/unreact.ts
1689
2099
  function registerCommentUnreact(comment) {
1690
2100
  comment.command("unreact").description("Remove one of your emoji reactions from a comment").argument("<buildReference>", "Build number or Argos build URL").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji reaction to remove").addOption(tokenOption).addOption(projectPathOption).addOption(jsonOption).action((reference, commentId, emoji, options) => runBuildAction({
1691
2101
  reference,
@@ -1703,8 +2113,7 @@ function registerCommentUnreact(comment) {
1703
2113
  format: formatComment
1704
2114
  }));
1705
2115
  }
1706
- //#endregion
1707
- //#region src/commands/comment/unresolve.ts
2116
+ // src/commands/comment/unresolve.ts
1708
2117
  const registerCommentUnresolve = defineCommentAction({
1709
2118
  name: "unresolve",
1710
2119
  description: "Reopen a resolved comment thread",
@@ -1715,8 +2124,7 @@ const registerCommentUnresolve = defineCommentAction({
1715
2124
  commentId
1716
2125
  } } }))
1717
2126
  });
1718
- //#endregion
1719
- //#region src/commands/comment/unsubscribe.ts
2127
+ // src/commands/comment/unsubscribe.ts
1720
2128
  const registerCommentUnsubscribe = defineCommentAction({
1721
2129
  name: "unsubscribe",
1722
2130
  description: "Unsubscribe from a comment thread's notifications",
@@ -1727,8 +2135,7 @@ const registerCommentUnsubscribe = defineCommentAction({
1727
2135
  commentId
1728
2136
  } } }))
1729
2137
  });
1730
- //#endregion
1731
- //#region src/commands/comment/index.ts
2138
+ // src/commands/comment/index.ts
1732
2139
  function commentCommand(program) {
1733
2140
  const comment = program.command("comment").description("List, post, and act on build comments");
1734
2141
  registerCommentList(comment);
@@ -1743,8 +2150,7 @@ function commentCommand(program) {
1743
2150
  registerCommentSubscribe(comment);
1744
2151
  registerCommentUnsubscribe(comment);
1745
2152
  }
1746
- //#endregion
1747
- //#region src/commands/login.ts
2153
+ // src/commands/login.ts
1748
2154
  const LOGIN_CLI_SUCCESS_ROUTE = `/auth/cli/success`;
1749
2155
  const LOGIN_TIMEOUT_MS = 3e5;
1750
2156
  const CALLBACK_ERROR_HTML = `<!DOCTYPE html><html lang="en">
@@ -1891,8 +2297,7 @@ function loginCommand(program) {
1891
2297
  console.log(successColor("Logged in to Argos successfully."));
1892
2298
  });
1893
2299
  }
1894
- //#endregion
1895
- //#region src/commands/logout.ts
2300
+ // src/commands/logout.ts
1896
2301
  function logoutCommand(program) {
1897
2302
  program.command("logout").description("Log out from Argos").action(async () => {
1898
2303
  const { legacyToken, oauth } = await getStoredCredentials();
@@ -1905,14 +2310,14 @@ function logoutCommand(program) {
1905
2310
  console.log("Logged out from Argos.");
1906
2311
  });
1907
2312
  }
1908
- //#endregion
1909
- //#region src/commands/deploy.ts
2313
+ // src/commands/deploy.ts
1910
2314
  function deployCommand(program) {
1911
- program.command("deploy").argument("<directory>", "Directory of the static build to deploy").description("Deploy a static build (Storybook or any static site) to Argos").addOption(tokenOption).addOption(new Option("--prod", "Deploy as a production deployment").default(false)).action(async (directory, options) => {
2315
+ program.command("deploy").argument("<directory>", "Directory of the static build to deploy").description("Deploy a static build (Storybook or any static site) to Argos").addOption(tokenOption).addOption(projectOption).addOption(new Option("--prod", "Deploy as a production deployment").default(false)).action(async (directory, options) => {
1912
2316
  const spinner = ora("Deploying").start();
1913
2317
  try {
1914
2318
  const result = await deploy({
1915
2319
  token: options.token,
2320
+ project: options.project,
1916
2321
  root: resolve(directory),
1917
2322
  environment: options.prod ? "production" : void 0
1918
2323
  });
@@ -1926,8 +2331,7 @@ function deployCommand(program) {
1926
2331
  }
1927
2332
  });
1928
2333
  }
1929
- //#endregion
1930
- //#region src/commands/whoami.ts
2334
+ // src/commands/whoami.ts
1931
2335
  function whoamiCommand(program) {
1932
2336
  program.command("whoami").description("Display the user authenticated with the current Argos token").addOption(tokenOption).addOption(jsonOption).action(async (options) => {
1933
2337
  try {
@@ -1937,8 +2341,7 @@ function whoamiCommand(program) {
1937
2341
  }
1938
2342
  });
1939
2343
  }
1940
- //#endregion
1941
- //#region src/commands/create-project.ts
2344
+ // src/commands/create-project.ts
1942
2345
  function createProjectCommand(program) {
1943
2346
  program.command("create-project").argument("<name>", "Name of the project to create").description("Create a new project in an account you administer").addOption(accountOption).addOption(tokenOption).addOption(jsonOption).action(async (name, options) => {
1944
2347
  try {
@@ -1953,16 +2356,8 @@ function createProjectCommand(program) {
1953
2356
  }
1954
2357
  });
1955
2358
  }
1956
- //#endregion
1957
- //#region src/commands/analytics.ts
2359
+ // src/commands/analytics.ts
1958
2360
  const DEFAULT_PERIOD_DAYS = 30;
1959
- const DAY_MS = 864e5;
1960
- /** Coerce a user-supplied date into an ISO 8601 datetime, or fail cleanly. */
1961
- function toIsoOrFail(value, option) {
1962
- const date = new Date(value);
1963
- if (Number.isNaN(date.getTime())) fail(`Invalid --${option} value: "${value}". Use an ISO 8601 datetime.`);
1964
- return date.toISOString();
1965
- }
1966
2361
  /** Collect a repeatable `--project` flag into an array of project names. */
1967
2362
  function collectProject(value, previous = []) {
1968
2363
  return [...previous, value];
@@ -1997,8 +2392,7 @@ function analyticsCommand(program) {
1997
2392
  }
1998
2393
  });
1999
2394
  }
2000
- //#endregion
2001
- //#region src/commands/change/_action.ts
2395
+ // src/commands/change/_action.ts
2002
2396
  /**
2003
2397
  * Register a `change <name> <changeId>` command that runs `perform` and prints
2004
2398
  * the updated change. Both change actions (ignore, unignore) share the same
@@ -2024,8 +2418,7 @@ function defineChangeAction(opts) {
2024
2418
  });
2025
2419
  };
2026
2420
  }
2027
- //#endregion
2028
- //#region src/commands/change/ignore.ts
2421
+ // src/commands/change/ignore.ts
2029
2422
  const registerChangeIgnore = defineChangeAction({
2030
2423
  name: "ignore",
2031
2424
  description: "Ignore a flaky test change so its diffs stop requiring review and are auto-approved on future builds",
@@ -2038,32 +2431,7 @@ const registerChangeIgnore = defineChangeAction({
2038
2431
  query: { metricsPeriod }
2039
2432
  } }))
2040
2433
  });
2041
- //#endregion
2042
- //#region src/lib/pagination.ts
2043
- /** Largest page the API serves. */
2044
- const MAX_PER_PAGE = 100;
2045
- /**
2046
- * Walk a paginated endpoint until `limit` items have been collected, the server
2047
- * runs out of results, or its reported total is reached.
2048
- *
2049
- * `fetchPage` receives the page number and the size to request, both already
2050
- * stringified — every paginated Argos endpoint takes them as query strings.
2051
- */
2052
- async function fetchPages(limit, fetchPage) {
2053
- const perPage = String(Math.min(MAX_PER_PAGE, limit));
2054
- const results = [];
2055
- for (let page = 1;; page++) {
2056
- const data = await fetchPage({
2057
- page: String(page),
2058
- perPage
2059
- });
2060
- results.push(...data.results);
2061
- if (results.length >= limit || results.length >= data.pageInfo.total || data.results.length === 0) break;
2062
- }
2063
- return results.slice(0, limit);
2064
- }
2065
- //#endregion
2066
- //#region src/commands/change/list.ts
2434
+ // src/commands/change/list.ts
2067
2435
  function registerChangeList(change) {
2068
2436
  change.command("list").description("List the changes currently ignored in a project, most recently ignored first").addOption(limitOption).addOption(tokenOption).addOption(changeProjectPathOption).addOption(jsonOption).action(async (options) => {
2069
2437
  try {
@@ -2080,8 +2448,7 @@ function registerChangeList(change) {
2080
2448
  }
2081
2449
  });
2082
2450
  }
2083
- //#endregion
2084
- //#region src/commands/change/unignore.ts
2451
+ // src/commands/change/unignore.ts
2085
2452
  const registerChangeUnignore = defineChangeAction({
2086
2453
  name: "unignore",
2087
2454
  description: "Stop ignoring a test change so its diffs require review again on future builds",
@@ -2094,16 +2461,14 @@ const registerChangeUnignore = defineChangeAction({
2094
2461
  query: { metricsPeriod }
2095
2462
  } }))
2096
2463
  });
2097
- //#endregion
2098
- //#region src/commands/change/index.ts
2464
+ // src/commands/change/index.ts
2099
2465
  function changeCommand(program) {
2100
2466
  const change = program.command("change").description("Ignore or unignore flaky test changes");
2101
2467
  registerChangeList(change);
2102
2468
  registerChangeIgnore(change);
2103
2469
  registerChangeUnignore(change);
2104
2470
  }
2105
- //#endregion
2106
- //#region src/commands/media/comment/create.ts
2471
+ // src/commands/media/comment/create.ts
2107
2472
  function registerMediaCommentCreate(comment) {
2108
2473
  comment.command("create").description("Post a comment (or reply) on a media").argument("<mediaId>", "ID of the media").option("--body <markdown>", "Markdown body of the comment").option("--body-file <path>", "Read the comment body from a Markdown file").option("--reply-to <threadId>", "Reply to an existing thread (its root comment ID)").option("--anchor-point <x,y>", "Pin the comment to a spot on the media, in normalized 0-1 coordinates").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, options) => {
2109
2474
  try {
@@ -2123,8 +2488,7 @@ function registerMediaCommentCreate(comment) {
2123
2488
  }
2124
2489
  });
2125
2490
  }
2126
- //#endregion
2127
- //#region src/commands/media/comment/_action.ts
2491
+ // src/commands/media/comment/_action.ts
2128
2492
  /**
2129
2493
  * Register a `media comment <name> <mediaId> <commentId>` command that runs
2130
2494
  * `perform` and prints the returned comment.
@@ -2149,8 +2513,7 @@ function defineMediaCommentAction(opts) {
2149
2513
  });
2150
2514
  };
2151
2515
  }
2152
- //#endregion
2153
- //#region src/commands/media/comment/delete.ts
2516
+ // src/commands/media/comment/delete.ts
2154
2517
  const registerMediaCommentDelete = defineMediaCommentAction({
2155
2518
  name: "delete",
2156
2519
  description: "Delete a comment on a media (author only)",
@@ -2159,8 +2522,7 @@ const registerMediaCommentDelete = defineMediaCommentAction({
2159
2522
  commentId
2160
2523
  } } }))
2161
2524
  });
2162
- //#endregion
2163
- //#region src/commands/media/comment/edit.ts
2525
+ // src/commands/media/comment/edit.ts
2164
2526
  function registerMediaCommentEdit(comment) {
2165
2527
  comment.command("edit").description("Update the body of a comment on a media (author only)").argument("<mediaId>", "ID of the media").argument("<commentId>", "ID of the comment").option("--body <markdown>", "New Markdown body of the comment").option("--body-file <path>", "Read the new body from a Markdown file").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, commentId, options) => {
2166
2528
  try {
@@ -2177,8 +2539,7 @@ function registerMediaCommentEdit(comment) {
2177
2539
  }
2178
2540
  });
2179
2541
  }
2180
- //#endregion
2181
- //#region src/commands/media/comment/get.ts
2542
+ // src/commands/media/comment/get.ts
2182
2543
  const registerMediaCommentGet = defineMediaCommentAction({
2183
2544
  name: "get",
2184
2545
  description: "Show a single comment on a media",
@@ -2187,8 +2548,7 @@ const registerMediaCommentGet = defineMediaCommentAction({
2187
2548
  commentId
2188
2549
  } } }))
2189
2550
  });
2190
- //#endregion
2191
- //#region src/commands/media/comment/list.ts
2551
+ // src/commands/media/comment/list.ts
2192
2552
  function registerMediaCommentList(comment) {
2193
2553
  comment.command("list").description("List the open comment threads on a media — the feedback still to act on").argument("<mediaId>", "ID of the media").addOption(new Option("--all", "Include threads that are already resolved (by default only open ones are listed)")).addOption(tokenOption).addOption(jsonOption).action(async (mediaId, options) => {
2194
2554
  try {
@@ -2210,8 +2570,7 @@ function selectOpenThreads(comments) {
2210
2570
  const resolved = new Set(comments.filter((comment) => comment.resolvedAt !== null).map((comment) => comment.id));
2211
2571
  return comments.filter((comment) => comment.resolvedAt === null && !(comment.threadId !== null && resolved.has(comment.threadId)));
2212
2572
  }
2213
- //#endregion
2214
- //#region src/commands/media/comment/react.ts
2573
+ // src/commands/media/comment/react.ts
2215
2574
  function registerMediaCommentReact(comment) {
2216
2575
  comment.command("react").description("Add an emoji reaction to a comment on a media").argument("<mediaId>", "ID of the media").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji to react with").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, commentId, emoji, options) => {
2217
2576
  try {
@@ -2227,8 +2586,7 @@ function registerMediaCommentReact(comment) {
2227
2586
  }
2228
2587
  });
2229
2588
  }
2230
- //#endregion
2231
- //#region src/commands/media/comment/resolve.ts
2589
+ // src/commands/media/comment/resolve.ts
2232
2590
  const registerMediaCommentResolve = defineMediaCommentAction({
2233
2591
  name: "resolve",
2234
2592
  description: "Mark a comment thread as resolved — what to call once you have acted on the feedback",
@@ -2237,8 +2595,7 @@ const registerMediaCommentResolve = defineMediaCommentAction({
2237
2595
  commentId
2238
2596
  } } }))
2239
2597
  });
2240
- //#endregion
2241
- //#region src/commands/media/comment/subscribe.ts
2598
+ // src/commands/media/comment/subscribe.ts
2242
2599
  const registerMediaCommentSubscribe = defineMediaCommentAction({
2243
2600
  name: "subscribe",
2244
2601
  description: "Subscribe to a comment thread's notifications",
@@ -2247,8 +2604,7 @@ const registerMediaCommentSubscribe = defineMediaCommentAction({
2247
2604
  commentId
2248
2605
  } } }))
2249
2606
  });
2250
- //#endregion
2251
- //#region src/commands/media/comment/unreact.ts
2607
+ // src/commands/media/comment/unreact.ts
2252
2608
  function registerMediaCommentUnreact(comment) {
2253
2609
  comment.command("unreact").description("Remove one of your emoji reactions from a comment on a media").argument("<mediaId>", "ID of the media").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji reaction to remove").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, commentId, emoji, options) => {
2254
2610
  try {
@@ -2264,8 +2620,7 @@ function registerMediaCommentUnreact(comment) {
2264
2620
  }
2265
2621
  });
2266
2622
  }
2267
- //#endregion
2268
- //#region src/commands/media/comment/unresolve.ts
2623
+ // src/commands/media/comment/unresolve.ts
2269
2624
  const registerMediaCommentUnresolve = defineMediaCommentAction({
2270
2625
  name: "unresolve",
2271
2626
  description: "Reopen a resolved comment thread",
@@ -2274,8 +2629,7 @@ const registerMediaCommentUnresolve = defineMediaCommentAction({
2274
2629
  commentId
2275
2630
  } } }))
2276
2631
  });
2277
- //#endregion
2278
- //#region src/commands/media/comment/unsubscribe.ts
2632
+ // src/commands/media/comment/unsubscribe.ts
2279
2633
  const registerMediaCommentUnsubscribe = defineMediaCommentAction({
2280
2634
  name: "unsubscribe",
2281
2635
  description: "Stop receiving notifications for a comment thread",
@@ -2284,8 +2638,7 @@ const registerMediaCommentUnsubscribe = defineMediaCommentAction({
2284
2638
  commentId
2285
2639
  } } }))
2286
2640
  });
2287
- //#endregion
2288
- //#region src/commands/media/comment/index.ts
2641
+ // src/commands/media/comment/index.ts
2289
2642
  function registerMediaComment(media) {
2290
2643
  const comment = media.command("comment").description("List, post, and act on the comments left on a media — the feedback a human pinned to a spot on your screenshot");
2291
2644
  registerMediaCommentList(comment);
@@ -2300,8 +2653,7 @@ function registerMediaComment(media) {
2300
2653
  registerMediaCommentSubscribe(comment);
2301
2654
  registerMediaCommentUnsubscribe(comment);
2302
2655
  }
2303
- //#endregion
2304
- //#region src/commands/media/delete.ts
2656
+ // src/commands/media/delete.ts
2305
2657
  function registerMediaDelete(media) {
2306
2658
  media.command("delete").argument("<mediaId>", "ID of the media").description("Delete a media. Any share link or pull request embed pointing at it stops working").addOption(tokenOption).action(async (mediaId, options) => {
2307
2659
  try {
@@ -2312,8 +2664,7 @@ function registerMediaDelete(media) {
2312
2664
  }
2313
2665
  });
2314
2666
  }
2315
- //#endregion
2316
- //#region src/commands/media/get.ts
2667
+ // src/commands/media/get.ts
2317
2668
  function registerMediaGet(media) {
2318
2669
  media.command("get").argument("<mediaId>", "ID of the media").description("Show a media's share URL, Markdown embed and details").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, options) => {
2319
2670
  try {
@@ -2323,8 +2674,7 @@ function registerMediaGet(media) {
2323
2674
  }
2324
2675
  });
2325
2676
  }
2326
- //#endregion
2327
- //#region src/commands/media/list.ts
2677
+ // src/commands/media/list.ts
2328
2678
  function registerMediaList(media) {
2329
2679
  media.command("list").description("List a project's uploaded media, most recent first. A project token lists its own project").addOption(new Option("--branch <branch>", "Only media uploaded for this branch, staged and published alike. The way to find everything uploaded for the work in hand")).addOption(new Option("--pr <number>", "Only media published to this pull request")).addOption(new Option("--stage <stage>", "Restrict to media with no pull request yet, or to media published to one").choices(["staged", "published"])).addOption(new Option("--search <query>", "Match media on their name")).addOption(new Option("--type <type>", "Restrict to images or videos").choices(["image", "video"])).addOption(limitOption).addOption(tokenOption).addOption(mediaProjectPathOption).addOption(jsonOption).action(async (options) => {
2330
2680
  try {
@@ -2349,8 +2699,7 @@ function registerMediaList(media) {
2349
2699
  }
2350
2700
  });
2351
2701
  }
2352
- //#endregion
2353
- //#region src/commands/media/update.ts
2702
+ // src/commands/media/update.ts
2354
2703
  function registerMediaUpdate(media) {
2355
2704
  media.command("update").argument("<mediaId>", "ID of the media").description("Change a staged media's name, description or branch. Fixed once the media is published to a pull request").addOption(new Option("--name <name>", "Rename the media")).addOption(new Option("--description <text>", "Prose shown under the media in the pull request comment")).addOption(new Option("--no-description", "Remove the description")).addOption(new Option("--branch <branch>", "Branch to publish the media from, once a pull request opens for it")).addOption(new Option("--no-branch", "Detach the media from its branch, so no pull request will publish it")).addOption(tokenOption).addOption(jsonOption).action(async (mediaId, options) => {
2356
2705
  try {
@@ -2369,8 +2718,7 @@ function registerMediaUpdate(media) {
2369
2718
  }
2370
2719
  });
2371
2720
  }
2372
- //#endregion
2373
- //#region src/commands/media/upload.ts
2721
+ // src/commands/media/upload.ts
2374
2722
  function registerMediaUpload(media) {
2375
2723
  media.command("upload").argument("<files...>", "Image or video files to upload").description("Upload images or videos and print their share URLs and Markdown embeds").addOption(tokenOption).addOption(mediaProjectPathOption).addOption(new Option("--branch <branch>", "Branch the media belongs to. Use this when the pull request does not exist yet: Argos publishes the media and comments on the pull request by itself once one opens for that branch")).addOption(new Option("--pr <number>", "Pull request to publish the media to. Argos keeps one comment on it listing every media uploaded, edited in place")).addOption(new Option("--state <state>", "Which half of a before/after pair these files are. Inferred from a file name ending in -before or -after").choices(["before", "after"])).addOption(new Option("--description <text>", "Prose shown under the media in the pull request comment")).addOption(new Option("--visibility <visibility>", "Who can open the share page. Defaults to your project's visibility in Argos: public for a public project, team for a private one").choices(["team", "public"])).addOption(new Option("--no-compress", "Upload images exactly as they are instead of converting them to WebP")).addOption(jsonOption).action(async (files, options) => {
2376
2724
  const spinner = options.json ? null : ora(files.length === 1 ? "Uploading media" : `Uploading ${files.length} files`).start();
@@ -2395,8 +2743,7 @@ function registerMediaUpload(media) {
2395
2743
  }
2396
2744
  });
2397
2745
  }
2398
- //#endregion
2399
- //#region src/commands/media/versions.ts
2746
+ // src/commands/media/versions.ts
2400
2747
  function registerMediaVersions(media) {
2401
2748
  media.command("versions").argument("<mediaId>", "ID of the media").description("List a media's uploaded versions, newest first. Use it to resolve the version a comment was written against").addOption(tokenOption).addOption(jsonOption).action(async (mediaId, options) => {
2402
2749
  try {
@@ -2406,8 +2753,7 @@ function registerMediaVersions(media) {
2406
2753
  }
2407
2754
  });
2408
2755
  }
2409
- //#endregion
2410
- //#region src/commands/media/index.ts
2756
+ // src/commands/media/index.ts
2411
2757
  function mediaCommand(program) {
2412
2758
  const media = program.command("media").description("Upload standalone images and videos to Argos and get shareable links to paste into pull requests");
2413
2759
  registerMediaUpload(media);
@@ -2418,8 +2764,7 @@ function mediaCommand(program) {
2418
2764
  registerMediaVersions(media);
2419
2765
  registerMediaComment(media);
2420
2766
  }
2421
- //#endregion
2422
- //#region src/commands/test/changes.ts
2767
+ // src/commands/test/changes.ts
2423
2768
  const PER_PAGE = 100;
2424
2769
  const ignoredOption = new Option("--ignored <boolean>", "Only the changes currently ignored (`true`) or only the ones still under review (`false`)").choices(["true", "false"]);
2425
2770
  /** Fetch every change of a test, following pagination. */
@@ -2457,8 +2802,7 @@ function registerTestChanges(test) {
2457
2802
  }
2458
2803
  });
2459
2804
  }
2460
- //#endregion
2461
- //#region src/commands/test/comment/create.ts
2805
+ // src/commands/test/comment/create.ts
2462
2806
  function registerTestCommentCreate(comment) {
2463
2807
  comment.command("create").description("Post a comment (or reply) on a test").argument("<testId>", "Test ID, taken from a diff's `test.id`").option("--body <markdown>", "Markdown body of the comment").option("--body-file <path>", "Read the comment body from a Markdown file").option("--reply-to <threadId>", "Reply to an existing thread (its root comment ID)").addOption(tokenOption).addOption(testProjectPathOption).addOption(jsonOption).action(async (testId, options) => {
2464
2808
  try {
@@ -2480,8 +2824,7 @@ function registerTestCommentCreate(comment) {
2480
2824
  }
2481
2825
  });
2482
2826
  }
2483
- //#endregion
2484
- //#region src/commands/test/comment/_action.ts
2827
+ // src/commands/test/comment/_action.ts
2485
2828
  /**
2486
2829
  * Register a `test comment <name> <testId> <commentId>` command that runs
2487
2830
  * `perform` and prints the returned comment. Used for the single-comment actions
@@ -2506,8 +2849,7 @@ function defineTestCommentAction(opts) {
2506
2849
  });
2507
2850
  };
2508
2851
  }
2509
- //#endregion
2510
- //#region src/commands/test/comment/delete.ts
2852
+ // src/commands/test/comment/delete.ts
2511
2853
  const registerTestCommentDelete = defineTestCommentAction({
2512
2854
  name: "delete",
2513
2855
  description: "Delete a comment on a test (author or project admin)",
@@ -2518,8 +2860,7 @@ const registerTestCommentDelete = defineTestCommentAction({
2518
2860
  commentId
2519
2861
  } } }))
2520
2862
  });
2521
- //#endregion
2522
- //#region src/commands/test/comment/edit.ts
2863
+ // src/commands/test/comment/edit.ts
2523
2864
  function registerTestCommentEdit(comment) {
2524
2865
  comment.command("edit").description("Update the body of a comment on a test (author only)").argument("<testId>", "Test ID, taken from a diff's `test.id`").argument("<commentId>", "ID of the comment").option("--body <markdown>", "New Markdown body of the comment").option("--body-file <path>", "Read the new body from a Markdown file").addOption(tokenOption).addOption(testProjectPathOption).addOption(jsonOption).action(async (testId, commentId, options) => {
2525
2866
  try {
@@ -2539,8 +2880,7 @@ function registerTestCommentEdit(comment) {
2539
2880
  }
2540
2881
  });
2541
2882
  }
2542
- //#endregion
2543
- //#region src/commands/test/comment/get.ts
2883
+ // src/commands/test/comment/get.ts
2544
2884
  const registerTestCommentGet = defineTestCommentAction({
2545
2885
  name: "get",
2546
2886
  description: "Fetch a single comment on a test",
@@ -2551,8 +2891,7 @@ const registerTestCommentGet = defineTestCommentAction({
2551
2891
  commentId
2552
2892
  } } }))
2553
2893
  });
2554
- //#endregion
2555
- //#region src/commands/test/comment/list.ts
2894
+ // src/commands/test/comment/list.ts
2556
2895
  function registerTestCommentList(comment) {
2557
2896
  comment.command("list").description("List the comments on a test").argument("<testId>", "Test ID, taken from a diff's `test.id`").addOption(tokenOption).addOption(testProjectPathOption).addOption(jsonOption).action(async (testId, options) => {
2558
2897
  try {
@@ -2567,8 +2906,7 @@ function registerTestCommentList(comment) {
2567
2906
  }
2568
2907
  });
2569
2908
  }
2570
- //#endregion
2571
- //#region src/commands/test/comment/react.ts
2909
+ // src/commands/test/comment/react.ts
2572
2910
  function registerTestCommentReact(comment) {
2573
2911
  comment.command("react").description("Add an emoji reaction to a comment on a test").argument("<testId>", "Test ID, taken from a diff's `test.id`").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji to react with").addOption(tokenOption).addOption(testProjectPathOption).addOption(jsonOption).action(async (testId, commentId, emoji, options) => {
2574
2912
  try {
@@ -2587,8 +2925,7 @@ function registerTestCommentReact(comment) {
2587
2925
  }
2588
2926
  });
2589
2927
  }
2590
- //#endregion
2591
- //#region src/commands/test/comment/resolve.ts
2928
+ // src/commands/test/comment/resolve.ts
2592
2929
  const registerTestCommentResolve = defineTestCommentAction({
2593
2930
  name: "resolve",
2594
2931
  description: "Mark a comment thread on a test as resolved",
@@ -2599,8 +2936,7 @@ const registerTestCommentResolve = defineTestCommentAction({
2599
2936
  commentId
2600
2937
  } } }))
2601
2938
  });
2602
- //#endregion
2603
- //#region src/commands/test/comment/subscribe.ts
2939
+ // src/commands/test/comment/subscribe.ts
2604
2940
  const registerTestCommentSubscribe = defineTestCommentAction({
2605
2941
  name: "subscribe",
2606
2942
  description: "Follow a comment thread on a test to get notified of replies",
@@ -2611,8 +2947,7 @@ const registerTestCommentSubscribe = defineTestCommentAction({
2611
2947
  commentId
2612
2948
  } } }))
2613
2949
  });
2614
- //#endregion
2615
- //#region src/commands/test/comment/unreact.ts
2950
+ // src/commands/test/comment/unreact.ts
2616
2951
  function registerTestCommentUnreact(comment) {
2617
2952
  comment.command("unreact").description("Remove your emoji reaction from a comment on a test").argument("<testId>", "Test ID, taken from a diff's `test.id`").argument("<commentId>", "ID of the comment").argument("<emoji>", "Emoji to react with").addOption(tokenOption).addOption(testProjectPathOption).addOption(jsonOption).action(async (testId, commentId, emoji, options) => {
2618
2953
  try {
@@ -2631,8 +2966,7 @@ function registerTestCommentUnreact(comment) {
2631
2966
  }
2632
2967
  });
2633
2968
  }
2634
- //#endregion
2635
- //#region src/commands/test/comment/unresolve.ts
2969
+ // src/commands/test/comment/unresolve.ts
2636
2970
  const registerTestCommentUnresolve = defineTestCommentAction({
2637
2971
  name: "unresolve",
2638
2972
  description: "Reopen a resolved comment thread on a test",
@@ -2643,8 +2977,7 @@ const registerTestCommentUnresolve = defineTestCommentAction({
2643
2977
  commentId
2644
2978
  } } }))
2645
2979
  });
2646
- //#endregion
2647
- //#region src/commands/test/comment/unsubscribe.ts
2980
+ // src/commands/test/comment/unsubscribe.ts
2648
2981
  const registerTestCommentUnsubscribe = defineTestCommentAction({
2649
2982
  name: "unsubscribe",
2650
2983
  description: "Stop following a comment thread on a test",
@@ -2655,8 +2988,7 @@ const registerTestCommentUnsubscribe = defineTestCommentAction({
2655
2988
  commentId
2656
2989
  } } }))
2657
2990
  });
2658
- //#endregion
2659
- //#region src/commands/test/comment/index.ts
2991
+ // src/commands/test/comment/index.ts
2660
2992
  function registerTestComment(test) {
2661
2993
  const comment = test.command("comment").description("List, post, and act on comments left on a test");
2662
2994
  registerTestCommentList(comment);
@@ -2671,8 +3003,7 @@ function registerTestComment(test) {
2671
3003
  registerTestCommentSubscribe(comment);
2672
3004
  registerTestCommentUnsubscribe(comment);
2673
3005
  }
2674
- //#endregion
2675
- //#region src/commands/test/get.ts
3006
+ // src/commands/test/get.ts
2676
3007
  function registerTestGet(test) {
2677
3008
  test.command("get").description("Fetch a test and its flakiness metrics").argument("<testId>", "Test ID, taken from a diff's `test.id` (see `argos build snapshots`)").addOption(tokenOption).addOption(testProjectPathOption).addOption(metricsPeriodOption).addOption(jsonOption).action(async (testId, options) => {
2678
3009
  try {
@@ -2690,8 +3021,7 @@ function registerTestGet(test) {
2690
3021
  }
2691
3022
  });
2692
3023
  }
2693
- //#endregion
2694
- //#region src/commands/test/list.ts
3024
+ // src/commands/test/list.ts
2695
3025
  function registerTestList(test) {
2696
3026
  test.command("list").description("List the tests currently running in a project, flakiest first — the project's flakiness backlog").option("--build-name <name>", "Restrict to the tests of a single build name").option("--search <query>", "Match tests on their name").addOption(limitOption).addOption(tokenOption).addOption(testProjectPathOption).addOption(metricsPeriodOption).addOption(jsonOption).action(async (options) => {
2697
3027
  try {
@@ -2713,8 +3043,7 @@ function registerTestList(test) {
2713
3043
  }
2714
3044
  });
2715
3045
  }
2716
- //#endregion
2717
- //#region src/commands/test/subscription.ts
3046
+ // src/commands/test/subscription.ts
2718
3047
  /**
2719
3048
  * Register `test subscribe` / `test unsubscribe`. Both act as a user, so they
2720
3049
  * need a personal access token, and the project comes from `--project` or
@@ -2755,8 +3084,7 @@ const registerTestUnsubscribe = defineTestSubscription({
2755
3084
  testId
2756
3085
  } } }))
2757
3086
  });
2758
- //#endregion
2759
- //#region src/commands/test/index.ts
3087
+ // src/commands/test/index.ts
2760
3088
  function testCommand(program) {
2761
3089
  const test = program.command("test").description("Inspect a test's flakiness and the changes that keep coming back");
2762
3090
  registerTestList(test);
@@ -2766,8 +3094,7 @@ function testCommand(program) {
2766
3094
  registerTestSubscribe(test);
2767
3095
  registerTestUnsubscribe(test);
2768
3096
  }
2769
- //#endregion
2770
- //#region src/commands/account/_run.ts
3097
+ // src/commands/account/_run.ts
2771
3098
  /**
2772
3099
  * Run an account-scoped command end to end: resolve the account target, run the
2773
3100
  * handler, print the result, and turn any failure into a clean CLI error.
@@ -2783,8 +3110,7 @@ async function runAccountAction(opts) {
2783
3110
  handleCliError(error, "user");
2784
3111
  }
2785
3112
  }
2786
- //#endregion
2787
- //#region src/commands/account/domain/index.ts
3113
+ // src/commands/account/domain/index.ts
2788
3114
  function registerAccountDomain(account) {
2789
3115
  const domain = account.command("domain").description("Manage the email domains a team is open to: anyone signing up with a verified address on one joins automatically");
2790
3116
  domain.command("list").description("List the email domains a team is open to").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
@@ -2815,8 +3141,7 @@ function registerAccountDomain(account) {
2815
3141
  format: ({ domain: removed }) => `Closed the team to ${removed}. Existing members keep their access.`
2816
3142
  }));
2817
3143
  }
2818
- //#endregion
2819
- //#region src/commands/account/get.ts
3144
+ // src/commands/account/get.ts
2820
3145
  function registerAccountGet(account) {
2821
3146
  account.command("get").description("Fetch an account with its plan and current-period usage").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
2822
3147
  options,
@@ -2824,8 +3149,7 @@ function registerAccountGet(account) {
2824
3149
  format: formatAccount
2825
3150
  }));
2826
3151
  }
2827
- //#endregion
2828
- //#region src/commands/account/invite/cancel.ts
3152
+ // src/commands/account/invite/cancel.ts
2829
3153
  function registerInviteCancel(invite) {
2830
3154
  invite.command("cancel").description("Cancel a pending invite, invalidating its link").argument("<inviteId>", "Invite ID, taken from `argos account invite list`").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((inviteId, options) => runAccountAction({
2831
3155
  options,
@@ -2842,8 +3166,7 @@ function registerInviteCancel(invite) {
2842
3166
  format: ({ inviteId }) => `Cancelled invite ${inviteId}.`
2843
3167
  }));
2844
3168
  }
2845
- //#endregion
2846
- //#region src/commands/account/invite/create.ts
3169
+ // src/commands/account/invite/create.ts
2847
3170
  const TEAM_USER_LEVELS$1 = [
2848
3171
  "owner",
2849
3172
  "member",
@@ -2862,8 +3185,7 @@ function registerInviteCreate(invite) {
2862
3185
  format: formatInvites
2863
3186
  }));
2864
3187
  }
2865
- //#endregion
2866
- //#region src/commands/account/invite/list.ts
3188
+ // src/commands/account/invite/list.ts
2867
3189
  function registerInviteList(invite) {
2868
3190
  invite.command("list").description("List a team's pending invites, most recent first").option("--search <query>", "Match invites on their email address").addOption(limitOption).addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
2869
3191
  options,
@@ -2877,8 +3199,7 @@ function registerInviteList(invite) {
2877
3199
  format: formatInvites
2878
3200
  }));
2879
3201
  }
2880
- //#endregion
2881
- //#region src/commands/account/invite/reset-link.ts
3202
+ // src/commands/account/invite/reset-link.ts
2882
3203
  function registerInviteResetLink(invite) {
2883
3204
  invite.command("reset-link").description("Rotate the team's shared invite link, invalidating the previous one").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
2884
3205
  options,
@@ -2886,8 +3207,7 @@ function registerInviteResetLink(invite) {
2886
3207
  format: formatInviteLink
2887
3208
  }));
2888
3209
  }
2889
- //#endregion
2890
- //#region src/commands/account/invite/index.ts
3210
+ // src/commands/account/invite/index.ts
2891
3211
  function registerAccountInvite(account) {
2892
3212
  const invite = account.command("invite").description("Invite people to a team and manage pending invitations");
2893
3213
  registerInviteList(invite);
@@ -2895,8 +3215,7 @@ function registerAccountInvite(account) {
2895
3215
  registerInviteCancel(invite);
2896
3216
  registerInviteResetLink(invite);
2897
3217
  }
2898
- //#endregion
2899
- //#region src/commands/account/member/list.ts
3218
+ // src/commands/account/member/list.ts
2900
3219
  const ORDER_BY_CHOICES = [
2901
3220
  "date",
2902
3221
  "name-asc",
@@ -2917,8 +3236,7 @@ function registerMemberList(member) {
2917
3236
  format: formatMembers
2918
3237
  }));
2919
3238
  }
2920
- //#endregion
2921
- //#region src/commands/account/member/remove.ts
3239
+ // src/commands/account/member/remove.ts
2922
3240
  function registerMemberRemove(member) {
2923
3241
  member.command("remove").description("Remove a member from a team. The last member cannot be removed; removing the second-to-last one promotes the survivor to owner").argument("<userId>", "User ID, taken from `argos account member list`").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((userId, options) => runAccountAction({
2924
3242
  options,
@@ -2935,8 +3253,7 @@ function registerMemberRemove(member) {
2935
3253
  format: ({ userId }) => `Removed user ${userId} from the team.`
2936
3254
  }));
2937
3255
  }
2938
- //#endregion
2939
- //#region src/commands/account/member/set-level.ts
3256
+ // src/commands/account/member/set-level.ts
2940
3257
  const TEAM_USER_LEVELS = [
2941
3258
  "owner",
2942
3259
  "member",
@@ -2955,16 +3272,85 @@ function registerMemberSetLevel(member) {
2955
3272
  format: formatMember
2956
3273
  }));
2957
3274
  }
2958
- //#endregion
2959
- //#region src/commands/account/member/index.ts
3275
+ // src/commands/account/member/index.ts
2960
3276
  function registerAccountMember(account) {
2961
3277
  const member = account.command("member").description("List a team's members, change their role, or remove them");
2962
3278
  registerMemberList(member);
2963
3279
  registerMemberSetLevel(member);
2964
3280
  registerMemberRemove(member);
2965
3281
  }
2966
- //#endregion
2967
- //#region src/commands/account/update.ts
3282
+ // src/lib/project-token.ts
3283
+ /** Every permission a project token can hold, in the order Argos lists them. */
3284
+ const PROJECT_TOKEN_PERMISSIONS = [
3285
+ "builds:write",
3286
+ "deployments:write",
3287
+ "projects:read",
3288
+ "media:read",
3289
+ "media:write"
3290
+ ];
3291
+ const tokenNameOption = new Option("--name <name>", "Name to recognize the token by, e.g. the CI it is set in").makeOptionMandatory();
3292
+ const tokenPermissionsOption = new Option("--permissions <permissions...>", "What the token can do. Defaults to every permission").choices(PROJECT_TOKEN_PERMISSIONS);
3293
+ const tokenExpireAtOption = new Option("--expire-at <date>", "When the token stops working, as an ISO 8601 date (e.g. 2027-01-31 or 2027-01-31T12:00:00Z). Never, by default").conflicts("expiresIn");
3294
+ const tokenExpiresInOption = new Option("--expires-in <days>", "Number of days the token works for, from now. Never expires, by default");
3295
+ /**
3296
+ * Resolve `--expire-at` or `--expires-in` into the UTC ISO date the API takes,
3297
+ * or `null` for a token that never expires.
3298
+ */
3299
+ function resolveExpireAt(options, now = /* @__PURE__ */ new Date()) {
3300
+ if (options.expiresIn !== void 0) {
3301
+ const days = toPositiveInteger(options.expiresIn, "expires-in");
3302
+ return new Date(now.getTime() + days * DAY_MS).toISOString();
3303
+ }
3304
+ if (options.expireAt !== void 0) {
3305
+ const expireAt = toIsoOrFail(options.expireAt, "expire-at");
3306
+ if (Date.parse(expireAt) <= now.getTime()) fail(`--expire-at must be in the future, received "${options.expireAt}".`);
3307
+ return expireAt;
3308
+ }
3309
+ return null;
3310
+ }
3311
+ /** Build the body shared by both token creation endpoints. */
3312
+ function buildCreateTokenBody(options) {
3313
+ return {
3314
+ name: options.name,
3315
+ permissions: options.permissions,
3316
+ expireAt: resolveExpireAt(options)
3317
+ };
3318
+ }
3319
+ // src/commands/account/project-token/index.ts
3320
+ function registerAccountProjectToken(account) {
3321
+ const projectToken = account.command("project-token").description("Manage every project token of an account, including the ones linked to several projects. Requires administrator access to the account");
3322
+ projectToken.command("list").description("List an account's project tokens, whatever projects they are linked to").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
3323
+ options,
3324
+ handler: async ({ client, accountSlug }) => unwrap(await client.GET("/accounts/{accountSlug}/project-tokens", { params: { path: { accountSlug } } })),
3325
+ format: formatProjectTokens
3326
+ }));
3327
+ projectToken.command("create").description("Create a project token linked to one or more projects of the account and print it. It is shown only once: store it right away. CI using a token linked to several projects must set ARGOS_PROJECT").addOption(new Option("--projects <names...>", "Names of the account's projects to link, e.g. web docs").makeOptionMandatory()).addOption(tokenNameOption).addOption(tokenPermissionsOption).addOption(tokenExpireAtOption).addOption(tokenExpiresInOption).addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
3328
+ options,
3329
+ handler: async ({ client, accountSlug }) => unwrap(await client.POST("/accounts/{accountSlug}/project-tokens", {
3330
+ params: { path: { accountSlug } },
3331
+ body: {
3332
+ ...buildCreateTokenBody(options),
3333
+ projects: options.projects
3334
+ }
3335
+ })),
3336
+ format: formatCreatedProjectToken
3337
+ }));
3338
+ projectToken.command("revoke").description("Revoke a project token of the account. CI using it is rejected from its next request").argument("<tokenId>", "Token ID, taken from `argos account project-token list`").addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((tokenId, options) => runAccountAction({
3339
+ options,
3340
+ handler: async ({ client, accountSlug }) => {
3341
+ unwrapEmpty(await client.DELETE("/accounts/{accountSlug}/project-tokens/{tokenId}", { params: { path: {
3342
+ accountSlug,
3343
+ tokenId
3344
+ } } }));
3345
+ return {
3346
+ revoked: true,
3347
+ tokenId
3348
+ };
3349
+ },
3350
+ format: ({ tokenId: revoked }) => `Revoked token ${revoked}.`
3351
+ }));
3352
+ }
3353
+ // src/commands/account/update.ts
2968
3354
  const DEFAULT_USER_LEVELS = ["member", "contributor"];
2969
3355
  function registerAccountUpdate(account) {
2970
3356
  account.command("update").description("Change the role given to users joining a team through its invite link or a verified email domain").addOption(new Option("--default-user-level <level>", "Role given to users that join the team automatically").choices(DEFAULT_USER_LEVELS).makeOptionMandatory()).addOption(accountSlugOption).addOption(tokenOption).addOption(jsonOption).action((options) => runAccountAction({
@@ -2976,18 +3362,17 @@ function registerAccountUpdate(account) {
2976
3362
  format: formatAccount
2977
3363
  }));
2978
3364
  }
2979
- //#endregion
2980
- //#region src/commands/account/index.ts
3365
+ // src/commands/account/index.ts
2981
3366
  function accountCommand(program) {
2982
- const account = program.command("account").description("Inspect an account's plan and usage, and manage a team's members, invites, and email domains");
3367
+ const account = program.command("account").description("Inspect an account's plan and usage, manage its project tokens, and a team's members, invites, and email domains");
2983
3368
  registerAccountGet(account);
2984
3369
  registerAccountUpdate(account);
2985
3370
  registerAccountMember(account);
2986
3371
  registerAccountInvite(account);
2987
3372
  registerAccountDomain(account);
3373
+ registerAccountProjectToken(account);
2988
3374
  }
2989
- //#endregion
2990
- //#region src/commands/project/_run.ts
3375
+ // src/commands/project/_run.ts
2991
3376
  /**
2992
3377
  * Run a project-scoped command end to end: resolve the project target, run the
2993
3378
  * handler, print the result, and turn any failure into a clean CLI error.
@@ -3003,8 +3388,7 @@ async function runProjectAction(opts) {
3003
3388
  handleCliError(error, opts.auth);
3004
3389
  }
3005
3390
  }
3006
- //#endregion
3007
- //#region src/commands/project/contributor.ts
3391
+ // src/commands/project/contributor.ts
3008
3392
  const PROJECT_USER_LEVELS$1 = [
3009
3393
  "admin",
3010
3394
  "reviewer",
@@ -3054,8 +3438,7 @@ function registerProjectContributor(project) {
3054
3438
  format: ({ userId: removed }) => `Revoked access for user ${removed}.`
3055
3439
  }));
3056
3440
  }
3057
- //#endregion
3058
- //#region src/commands/project/deployments.ts
3441
+ // src/commands/project/deployments.ts
3059
3442
  const ENVIRONMENTS = ["preview", "production"];
3060
3443
  function registerProjectDeployments(project) {
3061
3444
  project.command("deployments").description("List a project's deployments, most recent first").addOption(new Option("--environment <environment>", "Restrict to one environment. Use production to see what is live right now").choices(ENVIRONMENTS)).addOption(limitOption).addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
@@ -3074,8 +3457,7 @@ function registerProjectDeployments(project) {
3074
3457
  format: formatDeployments
3075
3458
  }));
3076
3459
  }
3077
- //#endregion
3078
- //#region src/commands/project/domain.ts
3460
+ // src/commands/project/domain.ts
3079
3461
  function registerProjectDomain(project) {
3080
3462
  const domain = project.command("domain").description("Read or set the domain a project's production deployments are served on");
3081
3463
  domain.command("get").description("Get a project's production deployment domain").addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
@@ -3100,8 +3482,7 @@ function registerProjectDomain(project) {
3100
3482
  format: formatProjectDomain
3101
3483
  }));
3102
3484
  }
3103
- //#endregion
3104
- //#region src/commands/project/get.ts
3485
+ // src/commands/project/get.ts
3105
3486
  function registerProjectGet(project) {
3106
3487
  project.command("get").description("Fetch a project and its settings").addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3107
3488
  options,
@@ -3113,8 +3494,48 @@ function registerProjectGet(project) {
3113
3494
  format: formatProject
3114
3495
  }));
3115
3496
  }
3116
- //#endregion
3117
- //#region src/commands/project/transfer.ts
3497
+ // src/commands/project/token.ts
3498
+ function registerProjectToken(project) {
3499
+ const token = project.command("token").description("Manage the tokens CI authenticates with (ARGOS_TOKEN). To rotate one without downtime: create its replacement, update the CI secret, then revoke the old token");
3500
+ token.command("list").description("List a project's tokens, including the ones linked to other projects too").addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3501
+ options,
3502
+ auth: "user",
3503
+ handler: async ({ client, owner, project: name }) => unwrap(await client.GET("/projects/{owner}/{project}/tokens", { params: { path: {
3504
+ owner,
3505
+ project: name
3506
+ } } })),
3507
+ format: formatProjectTokens
3508
+ }));
3509
+ token.command("create").description("Create a token for a project and print it. It is shown only once: store it right away, e.g. as the ARGOS_TOKEN secret of your CI").addOption(tokenNameOption).addOption(tokenPermissionsOption).addOption(tokenExpireAtOption).addOption(tokenExpiresInOption).addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3510
+ options,
3511
+ auth: "user",
3512
+ handler: async ({ client, owner, project: name }) => unwrap(await client.POST("/projects/{owner}/{project}/tokens", {
3513
+ params: { path: {
3514
+ owner,
3515
+ project: name
3516
+ } },
3517
+ body: buildCreateTokenBody(options)
3518
+ })),
3519
+ format: formatCreatedProjectToken
3520
+ }));
3521
+ token.command("revoke").description("Revoke a project token. CI using it is rejected from its next request").argument("<tokenId>", "Token ID, taken from `argos project token list`").addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((tokenId, options) => runProjectAction({
3522
+ options,
3523
+ auth: "user",
3524
+ handler: async ({ client, owner, project: name }) => {
3525
+ unwrapEmpty(await client.DELETE("/projects/{owner}/{project}/tokens/{tokenId}", { params: { path: {
3526
+ owner,
3527
+ project: name,
3528
+ tokenId
3529
+ } } }));
3530
+ return {
3531
+ revoked: true,
3532
+ tokenId
3533
+ };
3534
+ },
3535
+ format: ({ tokenId: revoked }) => `Revoked token ${revoked}.`
3536
+ }));
3537
+ }
3538
+ // src/commands/project/transfer.ts
3118
3539
  function registerProjectTransfer(project) {
3119
3540
  project.command("transfer").description("Move a project to another account. You must administer the project and the account receiving it").addOption(new Option("--to <slug>", "Slug of the account that will own the project").makeOptionMandatory()).option("--name <name>", "Name to give the project on the target account. Defaults to its current name, which must be free there").addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3120
3541
  options,
@@ -3132,8 +3553,7 @@ function registerProjectTransfer(project) {
3132
3553
  format: formatProject
3133
3554
  }));
3134
3555
  }
3135
- //#endregion
3136
- //#region src/commands/project/update.ts
3556
+ // src/commands/project/update.ts
3137
3557
  const BOOLEAN_CHOICES = ["true", "false"];
3138
3558
  const SUMMARY_CHECKS = [
3139
3559
  "always",
@@ -3187,6 +3607,7 @@ async function buildBody(options, load) {
3187
3607
  if (options.name !== void 0) body.name = options.name;
3188
3608
  if (options.defaultBaseBranch !== void 0) body.defaultBaseBranch = toNullable(options.defaultBaseBranch);
3189
3609
  if (options.autoApprovedBranchGlob !== void 0) body.autoApprovedBranchGlob = toNullable(options.autoApprovedBranchGlob);
3610
+ if (options.autoApproval !== void 0) body.autoApprovalEnabled = toBoolean(options.autoApproval);
3190
3611
  if (options.deploymentProductionBranchGlob !== void 0) body.deploymentProductionBranchGlob = toNullable(options.deploymentProductionBranchGlob);
3191
3612
  if (options.private !== void 0) body.private = options.private === "inherit" ? null : toBoolean(options.private);
3192
3613
  if (options.summaryCheck !== void 0) body.summaryCheck = options.summaryCheck;
@@ -3207,7 +3628,7 @@ async function loadIgnoreConfig(client, owner, project) {
3207
3628
  } } })).ignoreConfig;
3208
3629
  }
3209
3630
  function registerProjectUpdate(project) {
3210
- project.command("update").description("Update a project's settings. Only the settings you pass are changed").option("--name <name>", "Rename the project").option("--default-base-branch <branch>", "Branch used as the baseline when no better one applies. Pass an empty string to fall back to the repository default").option("--auto-approved-branch-glob <glob>", "Glob matching the branches whose builds are approved automatically. Pass an empty string to fall back to the default base branch").option("--deployment-production-branch-glob <glob>", "Glob matching the branches whose deployments count as production. Pass an empty string to fall back to the repository default").addOption(new Option("--private <value>", "Force the project's privacy, or inherit it from the linked repository").choices([...BOOLEAN_CHOICES, "inherit"])).addOption(new Option("--summary-check <mode>", "When to post the summary check on a pull request").choices(SUMMARY_CHECKS)).addOption(new Option("--default-user-level <level>", "Access given to team members that are not contributors on this project").choices([...PROJECT_USER_LEVELS, "none"])).addOption(new Option("--ignore-changes <value>", "Whether changes can be ignored on this project").choices(BOOLEAN_CHOICES)).option("--auto-ignore-after <changes>", "Ignore a change automatically once it has reappeared this many times, or \"off\"").addOption(new Option("--deployments <value>", "Whether deployments are served for this project").choices(BOOLEAN_CHOICES)).addOption(new Option("--deployment-auth <mode>", "Who can reach the project's deployments").choices(DEPLOYMENT_AUTHS)).addOption(new Option("--github-actions-oidc <value>", "Whether builds can authenticate with a GitHub Actions OIDC token").choices(BOOLEAN_CHOICES)).addOption(new Option("--tokenless-auth <value>", "Whether builds from forked pull requests can be uploaded without a token").choices(BOOLEAN_CHOICES)).addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3631
+ project.command("update").description("Update a project's settings. Only the settings you pass are changed").option("--name <name>", "Rename the project").option("--default-base-branch <branch>", "Branch used as the baseline when no better one applies. Pass an empty string to fall back to the repository default").option("--auto-approved-branch-glob <glob>", "Glob matching the branches whose builds are approved automatically. Pass an empty string to fall back to the default base branch").addOption(new Option("--auto-approval <value>", "Whether builds on branches matching the auto-approved glob are approved automatically. Pass false to review every build, base branch included; the glob is kept").choices(BOOLEAN_CHOICES)).option("--deployment-production-branch-glob <glob>", "Glob matching the branches whose deployments count as production. Pass an empty string to fall back to the repository default").addOption(new Option("--private <value>", "Force the project's privacy, or inherit it from the linked repository").choices([...BOOLEAN_CHOICES, "inherit"])).addOption(new Option("--summary-check <mode>", "When to post the summary check on a pull request").choices(SUMMARY_CHECKS)).addOption(new Option("--default-user-level <level>", "Access given to team members that are not contributors on this project").choices([...PROJECT_USER_LEVELS, "none"])).addOption(new Option("--ignore-changes <value>", "Whether changes can be ignored on this project").choices(BOOLEAN_CHOICES)).option("--auto-ignore-after <changes>", "Ignore a change automatically once it has reappeared this many times, or \"off\"").addOption(new Option("--deployments <value>", "Whether deployments are served for this project").choices(BOOLEAN_CHOICES)).addOption(new Option("--deployment-auth <mode>", "Who can reach the project's deployments").choices(DEPLOYMENT_AUTHS)).addOption(new Option("--github-actions-oidc <value>", "Whether builds can authenticate with a GitHub Actions OIDC token").choices(BOOLEAN_CHOICES)).addOption(new Option("--tokenless-auth <value>", "Whether builds from forked pull requests can be uploaded without a token").choices(BOOLEAN_CHOICES)).addOption(managedProjectPathOption).addOption(tokenOption).addOption(jsonOption).action((options) => runProjectAction({
3211
3632
  options,
3212
3633
  auth: "user",
3213
3634
  handler: async ({ client, owner, project: name }) => {
@@ -3224,19 +3645,18 @@ function registerProjectUpdate(project) {
3224
3645
  format: formatProject
3225
3646
  }));
3226
3647
  }
3227
- //#endregion
3228
- //#region src/commands/project/index.ts
3648
+ // src/commands/project/index.ts
3229
3649
  function projectCommand(program) {
3230
- const project = program.command("project").description("Inspect and configure a project: settings, contributors, deployments, and its deployment domain");
3650
+ const project = program.command("project").description("Inspect and configure a project: settings, contributors, tokens, deployments, and its deployment domain");
3231
3651
  registerProjectGet(project);
3232
3652
  registerProjectUpdate(project);
3233
3653
  registerProjectTransfer(project);
3234
3654
  registerProjectContributor(project);
3655
+ registerProjectToken(project);
3235
3656
  registerProjectDeployments(project);
3236
3657
  registerProjectDomain(project);
3237
3658
  }
3238
- //#endregion
3239
- //#region src/commands/automation/_definition.ts
3659
+ // src/commands/automation/_definition.ts
3240
3660
  /**
3241
3661
  * Resolve an automation rule definition from the mutually-exclusive
3242
3662
  * `--definition` (inline JSON) and `--definition-file` (path) options.
@@ -3261,8 +3681,7 @@ async function resolveDefinition(options) {
3261
3681
  fail(`Invalid rule definition JSON: ${error instanceof Error ? error.message : String(error)}`);
3262
3682
  }
3263
3683
  }
3264
- //#endregion
3265
- //#region src/commands/automation/index.ts
3684
+ // src/commands/automation/index.ts
3266
3685
  const ACTIVE_CHOICES = ["true", "false"];
3267
3686
  const definitionOption = new Option("--definition <json>", "Rule definition as JSON: name, events, conditions, actions");
3268
3687
  const definitionFileOption = new Option("--definition-file <path>", "Read the rule definition from a JSON file");
@@ -3342,8 +3761,7 @@ function automationCommand(program) {
3342
3761
  format: formatAutomationRule
3343
3762
  }));
3344
3763
  }
3345
- //#endregion
3346
- //#region src/lib/docs.ts
3764
+ // src/lib/docs.ts
3347
3765
  /**
3348
3766
  * Searching the Argos documentation.
3349
3767
  *
@@ -3355,7 +3773,6 @@ function automationCommand(program) {
3355
3773
  * The endpoint is stateless, so a single `tools/call` request is enough: no
3356
3774
  * `initialize` handshake or session to carry between calls.
3357
3775
  */
3358
- /** Root of the published Argos documentation. */
3359
3776
  const DOCS_URL = "https://argos-ci.com/docs";
3360
3777
  const MCP_ENDPOINT = `${DOCS_URL}/~gitbook/mcp`;
3361
3778
  /**
@@ -3375,6 +3792,16 @@ const TIMEOUT_MS = 3e4;
3375
3792
  * `Content` is left out when the page has no passage to show.
3376
3793
  */
3377
3794
  const RESULT_REGEX = /^Title: ([^\n]*)\nLink: ([^\n]*)(?:\nContent: ([\s\S]*))?/;
3795
+ /**
3796
+ * The link as a normalized `https:` URL, or `null` when it is not one. The URL
3797
+ * serializer percent-encodes control and non-ASCII characters, so the result
3798
+ * is safe to print as-is and to hand to `curl`.
3799
+ */
3800
+ function toHttpsUrl(link) {
3801
+ if (!link || !URL.canParse(link)) return null;
3802
+ const url = new URL(link);
3803
+ return url.protocol === "https:" ? url.href : null;
3804
+ }
3378
3805
  /** Parse the tool's text blocks into results, skipping any it can't read. */
3379
3806
  function parseDocsSearchContent(content) {
3380
3807
  const results = /* @__PURE__ */ new Map();
@@ -3382,7 +3809,7 @@ function parseDocsSearchContent(content) {
3382
3809
  if (block.type !== "text" || !block.text) continue;
3383
3810
  const match = RESULT_REGEX.exec(block.text);
3384
3811
  const title = match?.[1]?.trim();
3385
- const url = match?.[2]?.trim();
3812
+ const url = toHttpsUrl(match?.[2]);
3386
3813
  if (!title || !url || results.has(url)) continue;
3387
3814
  results.set(url, {
3388
3815
  title,
@@ -3404,7 +3831,7 @@ function parseMcpResponse(body, contentType) {
3404
3831
  const message = JSON.parse(line.slice(5));
3405
3832
  if ("result" in message || "error" in message) return message;
3406
3833
  }
3407
- throw new CliError("The documentation search returned no response.");
3834
+ fail("The documentation search returned no response.");
3408
3835
  }
3409
3836
  /** Search the Argos documentation, best match first. */
3410
3837
  async function searchDocs(query, options) {
@@ -3428,16 +3855,15 @@ async function searchDocs(query, options) {
3428
3855
  signal: AbortSignal.timeout(TIMEOUT_MS)
3429
3856
  }).catch((error) => {
3430
3857
  const reason = error instanceof Error ? error.message : String(error);
3431
- throw new CliError(`Could not reach ${DOCS_URL}: ${reason}`);
3858
+ fail(`Could not reach ${DOCS_URL}: ${reason}`);
3432
3859
  });
3433
- if (!response.ok) throw new CliError(`The documentation search failed with HTTP ${response.status}.`);
3860
+ if (!response.ok) fail(`The documentation search failed with HTTP ${response.status}.`);
3434
3861
  const message = parseMcpResponse(await response.text(), response.headers.get("content-type"));
3435
3862
  const content = message.result?.content ?? [];
3436
- if (message.error || message.result?.isError) throw new CliError(`The documentation search failed: ${sanitizeTerminalText(message.error ? message.error.message : content.map((block) => block.text ?? "").join(" ")) || "unknown error"}`);
3863
+ if (message.error || message.result?.isError) fail(`The documentation search failed: ${sanitizeTerminalText(message.error ? message.error.message : content.map((block) => block.text ?? "").join(" ")) || "unknown error"}`);
3437
3864
  return parseDocsSearchContent(content).slice(0, options.limit);
3438
3865
  }
3439
- //#endregion
3440
- //#region src/commands/docs/search.ts
3866
+ // src/commands/docs/search.ts
3441
3867
  const DEFAULT_DOCS_LIMIT = 5;
3442
3868
  function registerDocsSearch(docs) {
3443
3869
  docs.command("search").description(`Search the Argos documentation (${DOCS_URL})`).argument("<query...>", "What to look for, e.g. \"parallel builds\"").addOption(new Option("--limit <number>", `Maximum number of results, up to 10`).default(String(DEFAULT_DOCS_LIMIT))).addOption(jsonOption).addHelpText("after", [
@@ -3457,13 +3883,11 @@ function registerDocsSearch(docs) {
3457
3883
  }
3458
3884
  });
3459
3885
  }
3460
- //#endregion
3461
- //#region src/commands/docs/index.ts
3886
+ // src/commands/docs/index.ts
3462
3887
  function docsCommand(program) {
3463
3888
  registerDocsSearch(program.command("docs").description("Search the Argos documentation from the terminal"));
3464
3889
  }
3465
- //#endregion
3466
- //#region src/index.ts
3890
+ // src/index.ts
3467
3891
  const __dirname = fileURLToPath(new URL(".", import.meta.url));
3468
3892
  const rawPkg = await readFile(resolve(__dirname, "..", "package.json"), "utf8");
3469
3893
  const pkg = JSON.parse(rawPkg);
@@ -3473,6 +3897,7 @@ uploadCommand(program);
3473
3897
  skipCommand(program);
3474
3898
  finalizeCommand(program);
3475
3899
  buildCommand(program);
3900
+ baselineCommand(program);
3476
3901
  reviewCommand(program);
3477
3902
  commentCommand(program);
3478
3903
  loginCommand(program);
@@ -3490,5 +3915,4 @@ automationCommand(program);
3490
3915
  docsCommand(program);
3491
3916
  if (!process.argv.slice(2).length) program.outputHelp();
3492
3917
  else program.parse(process.argv);
3493
- //#endregion
3494
3918
  export {};