@argos-ci/cli 6.9.6 → 6.11.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 +587 -106
  2. package/package.json +13 -8
package/dist/index.mjs CHANGED
@@ -1,11 +1,15 @@
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 { 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";
9
13
  import { homedir } from "node:os";
10
14
  import { createHash, randomBytes } from "node:crypto";
11
15
  import { createServer } from "node:http";
@@ -41,13 +45,18 @@ const jsonOption = new Option("--json", "Output machine-readable JSON instead of
41
45
  const projectPathOption = new Option("--project <owner/project>", "Project path in owner/project format. Required for build-number references on review and comment commands");
42
46
  const changeProjectPathOption = new Option("--project <owner/project>", "Project the change belongs to, in owner/project format. Also ARGOS_PROJECT");
43
47
  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");
48
+ const buildProjectPathOption = new Option("--project <owner/project>", "Project the builds belong to, in owner/project format. Also ARGOS_PROJECT. Optional with a project token, which already identifies its project");
44
49
  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");
45
50
  const managedProjectPathOption = new Option("--project <owner/project>", "Project to act on, in owner/project format. Also ARGOS_PROJECT");
46
51
  const limitOption = new Option("--limit <number>", "Maximum number of items to fetch, following pagination as needed").default(String(100));
47
- /** Parse a `--limit` value into a positive integer, or abort. */
48
- function toLimit(value) {
52
+ /**
53
+ * Parse a `--limit` value into a positive integer, or abort. Pass `max` when
54
+ * the source caps how many items it can return.
55
+ */
56
+ function toLimit(value, { max = Infinity } = {}) {
49
57
  const limit = Number(value);
50
58
  if (!Number.isInteger(limit) || limit < 1) fail(`--limit must be a positive integer, received "${value}".`);
59
+ if (limit > max) fail(`--limit must be at most ${max}, received "${value}".`);
51
60
  return limit;
52
61
  }
53
62
  /** Parse a `--pr` value into a pull request number, or abort. */
@@ -248,6 +257,254 @@ function unwrapEmpty(result) {
248
257
  if (!result.response.ok) throwAPIError(result.error, result.response);
249
258
  }
250
259
  //#endregion
260
+ //#region src/lib/build.ts
261
+ const PER_PAGE$1 = 100;
262
+ /** Whether Argos is still processing the build, so its diffs are not final. */
263
+ function isBuildPending(build) {
264
+ return build.status === "pending" || build.status === "progress";
265
+ }
266
+ async function fetchBuild(target) {
267
+ const { client, owner, project, buildNumber } = target;
268
+ return unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}", { params: { path: {
269
+ owner,
270
+ project,
271
+ buildNumber
272
+ } } }));
273
+ }
274
+ /** Fetch every diff of a build, following pagination. */
275
+ async function fetchAllDiffs(target, options = {}) {
276
+ const { client, owner, project, buildNumber } = target;
277
+ const results = [];
278
+ for (let page = 1;; page++) {
279
+ const data = unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}/diffs", { params: {
280
+ path: {
281
+ owner,
282
+ project,
283
+ buildNumber
284
+ },
285
+ query: {
286
+ page: String(page),
287
+ perPage: String(PER_PAGE$1),
288
+ ...options.metricsPeriod ? { metricsPeriod: options.metricsPeriod } : {},
289
+ ...options.needsReview ? { needsReview: "true" } : {}
290
+ }
291
+ } }));
292
+ results.push(...data.results);
293
+ if (results.length >= data.pageInfo.total || data.results.length === 0) break;
294
+ }
295
+ return results;
296
+ }
297
+ //#endregion
298
+ //#region src/lib/download.ts
299
+ /** Files downloaded at the same time. */
300
+ const CONCURRENCY = 8;
301
+ /** Attempts per file before giving up, for failures that may not last. */
302
+ const MAX_ATTEMPTS = 3;
303
+ const RETRY_DELAY_MS = 1e3;
304
+ /** Extension given to a file of each content type when its name has none. */
305
+ const EXTENSION_BY_CONTENT_TYPE = {
306
+ "image/png": ".png",
307
+ "image/jpeg": ".jpg",
308
+ "image/webp": ".webp"
309
+ };
310
+ const IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
311
+ ".png",
312
+ ".jpg",
313
+ ".jpeg",
314
+ ".webp"
315
+ ]);
316
+ const WINDOWS_RESERVED_CHARACTERS = /[<>:"|?*\u0000-\u001f]/g;
317
+ /**
318
+ * Get the path, relative to the download directory, a snapshot is written to.
319
+ *
320
+ * A snapshot is named after the path it was uploaded from
321
+ * (`chromium/home.png`), so the directory mirrors the original layout. Names
322
+ * are whatever the uploader sent, so the `.` and `..` segments and leading
323
+ * slashes are dropped: every file stays inside the directory.
324
+ */
325
+ function getSnapshotPath(file, platform = process.platform) {
326
+ const segments = file.name.split(/[\\/]/).filter((segment) => segment !== "" && segment !== "." && segment !== "..").map((segment) => platform === "win32" ? segment.replace(WINDOWS_RESERVED_CHARACTERS, "_") : segment);
327
+ const basename = segments.pop() ?? "snapshot";
328
+ const extension = EXTENSION_BY_CONTENT_TYPE[file.contentType];
329
+ const suffix = extension && !IMAGE_EXTENSIONS.has(extname(basename).toLowerCase()) ? extension : "";
330
+ return [...segments, `${basename}${suffix}`].join("/");
331
+ }
332
+ /**
333
+ * Get a distinct path for each snapshot. Two names can map to the same file:
334
+ * `home` and `home.png` once the extension is added, or `Home.png` and
335
+ * `home.png`, which macOS and Windows store as one. The later ones get a
336
+ * ` (2)`, ` (3)`… before their extension instead of overwriting the first, on
337
+ * every platform, so a directory copied elsewhere keeps all its files.
338
+ */
339
+ function getSnapshotPaths(files, platform = process.platform) {
340
+ const used = /* @__PURE__ */ new Set();
341
+ return files.map((file) => {
342
+ const path = getSnapshotPath(file, platform);
343
+ const extension = extname(path);
344
+ const stem = path.slice(0, path.length - extension.length);
345
+ let candidate = path;
346
+ for (let index = 2; used.has(candidate.toLowerCase()); index++) candidate = `${stem} (${index})${extension}`;
347
+ used.add(candidate.toLowerCase());
348
+ return candidate;
349
+ });
350
+ }
351
+ function isErrnoException(error) {
352
+ return error instanceof Error && "code" in error;
353
+ }
354
+ /**
355
+ * Abort unless `directory` is missing or empty. Downloading into a directory
356
+ * that already holds files would overwrite some of them and leave others
357
+ * around, so the result would no longer match the build.
358
+ */
359
+ async function assertEmptyDirectory(directory) {
360
+ let entries;
361
+ try {
362
+ entries = await readdir(directory);
363
+ } catch (error) {
364
+ if (isErrnoException(error) && error.code === "ENOENT") return;
365
+ if (isErrnoException(error) && error.code === "ENOTDIR") fail(`${directory} is not a directory.`);
366
+ throw error;
367
+ }
368
+ if (entries.length > 0) fail(`${directory} is not empty. Pick a new directory with --output, or empty it first.`);
369
+ }
370
+ /** A failed response, and whether trying again may succeed. */
371
+ var HTTPStatusError = class extends Error {
372
+ retryable;
373
+ constructor(status) {
374
+ super(`HTTP ${status}`);
375
+ this.retryable = status === 429 || status >= 500;
376
+ }
377
+ };
378
+ async function downloadFile(file, path, signal) {
379
+ for (let attempt = 1;; attempt++) {
380
+ signal.throwIfAborted();
381
+ try {
382
+ const response = await fetch(file.url, { signal });
383
+ if (!response.ok || !response.body) {
384
+ await response.body?.cancel();
385
+ throw new HTTPStatusError(response.status);
386
+ }
387
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(path), { signal });
388
+ return;
389
+ } catch (error) {
390
+ if (signal.aborted) throw error;
391
+ if (!(!(error instanceof HTTPStatusError) || error.retryable) || attempt >= MAX_ATTEMPTS) {
392
+ const reason = error instanceof Error ? error.message : String(error);
393
+ fail(`Could not download "${file.name}" (${reason}): ${file.url}`);
394
+ }
395
+ await setTimeout$1(RETRY_DELAY_MS * attempt, void 0, { signal });
396
+ }
397
+ }
398
+ }
399
+ /**
400
+ * Download snapshot files into `directory`, a few at a time, each to the path
401
+ * {@link getSnapshotPaths} gives it. The first file that cannot be downloaded
402
+ * cancels the others, and its error is thrown once they have all stopped.
403
+ */
404
+ async function downloadSnapshots(files, directory, options = {}) {
405
+ const paths = getSnapshotPaths(files);
406
+ const entries = files.map((file, index) => ({
407
+ ...file,
408
+ path: join(directory, paths[index])
409
+ }));
410
+ const controller = new AbortController();
411
+ let failure = null;
412
+ let next = 0;
413
+ let done = 0;
414
+ const work = async () => {
415
+ try {
416
+ while (!controller.signal.aborted && next < entries.length) {
417
+ const entry = entries[next++];
418
+ await mkdir(dirname(entry.path), { recursive: true });
419
+ await downloadFile(entry, entry.path, controller.signal);
420
+ options.onProgress?.(++done, entries.length);
421
+ }
422
+ } catch (error) {
423
+ if (!failure) {
424
+ failure = { error };
425
+ controller.abort();
426
+ }
427
+ }
428
+ };
429
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, entries.length) }, work));
430
+ if (failure) throw failure.error;
431
+ return entries;
432
+ }
433
+ /**
434
+ * Download the snapshot each diff captured (its head; a removed diff has none)
435
+ * into `directory`, showing progress unless the output is JSON.
436
+ */
437
+ async function downloadBuildSnapshots(args) {
438
+ const snapshots = args.diffs.flatMap((diff) => diff.head ? [{
439
+ name: diff.head.name,
440
+ url: diff.head.url,
441
+ contentType: diff.head.contentType,
442
+ status: diff.status
443
+ }] : []);
444
+ const spinner = args.json || snapshots.length === 0 ? null : ora(`Downloading ${snapshots.length} snapshots`).start();
445
+ try {
446
+ const files = await downloadSnapshots(snapshots, args.directory, { onProgress: (done, total) => {
447
+ if (spinner) spinner.text = `Downloading snapshots (${done}/${total})`;
448
+ } });
449
+ return {
450
+ build: args.build,
451
+ directory: args.directory,
452
+ files
453
+ };
454
+ } finally {
455
+ spinner?.stop();
456
+ }
457
+ }
458
+ //#endregion
459
+ //#region src/lib/terminal.ts
460
+ /**
461
+ * Printing text the CLI did not author — an OAuth error description chosen by
462
+ * the authorization server, for instance.
463
+ *
464
+ * A terminal acts on what it is given: an ANSI escape sequence moves the
465
+ * cursor, erases a line or repaints it, and a carriage return overwrites the
466
+ * line just printed. Remote text reaching it unfiltered therefore doesn't just
467
+ * read badly, it can forge CLI output — a fake "run this command to continue"
468
+ * instruction under the CLI's own name (GHSA-q9j4-4h4j-mv5m).
469
+ */
470
+ /**
471
+ * Longest remote string we print. A description is a sentence; a wall of text
472
+ * is itself a way to scroll the real message off the screen.
473
+ */
474
+ const MAX_LENGTH = 200;
475
+ /**
476
+ * Escape sequences, matched together with the bytes that belong to them so no
477
+ * parameter remnant (`[2K`) is left behind as text: CSI (`ESC [`), OSC
478
+ * (`ESC ]`, up to its terminator) and, last, the plain escape sequences —
479
+ * optional intermediate bytes and a final one, which covers `ESC c` (reset the
480
+ * terminal) as much as `ESC 7`.
481
+ */
482
+ const ESCAPE_SEQUENCE_REGEX = /[\u001B\u009B](?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\)?|[ -/]*[0-~])/g;
483
+ /** Anything else a terminal acts on rather than displays: C0, DEL and C1. */
484
+ const CONTROL_CHARACTER_REGEX = /[\u0000-\u001F\u007F-\u009F]/g;
485
+ /**
486
+ * Explicit directional formatting: the other way to make a line read as
487
+ * something other than what it says, by reordering the characters around it
488
+ * rather than by driving the terminal. Bidirectional text itself is untouched —
489
+ * only the overrides, embeddings, isolates and marks are dropped.
490
+ */
491
+ const DIRECTIONAL_FORMATTING_REGEX = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
492
+ /**
493
+ * Reduce remote text to characters a terminal can only display, on a single
494
+ * line and bounded in length.
495
+ *
496
+ * Returns an empty string when nothing printable is left, so callers can fall
497
+ * back to a message of their own rather than print a blank error.
498
+ *
499
+ * @param text The remote value. Typed `unknown` because it comes from parsed
500
+ * JSON or a URL parameter and is not necessarily a string at runtime.
501
+ */
502
+ function sanitizeTerminalText(text) {
503
+ if (text === null || text === void 0) return "";
504
+ const sanitized = String(text).replace(ESCAPE_SEQUENCE_REGEX, "").replace(DIRECTIONAL_FORMATTING_REGEX, "").replace(CONTROL_CHARACTER_REGEX, " ").replace(/\s+/g, " ").trim();
505
+ return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}…` : sanitized;
506
+ }
507
+ //#endregion
251
508
  //#region src/lib/format.ts
252
509
  /** Render a scalar, using `-` for empty values. */
253
510
  function formatValue(value) {
@@ -376,6 +633,35 @@ function formatSnapshots(diffs, build) {
376
633
  ...diffs.flatMap((diff) => [...formatSnapshotDiff(diff, build), ""])
377
634
  ].slice(0, -1).join("\n");
378
635
  }
636
+ function formatBuilds(builds) {
637
+ if (builds.length === 0) return "No builds found.";
638
+ return [
639
+ `Builds (${builds.length})`,
640
+ "",
641
+ ...builds.flatMap((build) => [
642
+ `#${build.number} [${build.status}]`,
643
+ ` Branch: ${formatValue(build.head.branch)}`,
644
+ ` Commit: ${formatValue(build.head.sha)}`,
645
+ ` Snapshots: ${formatStats(build.stats)}`,
646
+ ` URL: ${build.url}`,
647
+ ""
648
+ ])
649
+ ].slice(0, -1).join("\n");
650
+ }
651
+ /**
652
+ * Format the result of a download. `kind` names what was downloaded, e.g.
653
+ * `baseline snapshot`, and is pluralized as needed.
654
+ */
655
+ function formatSnapshotDownload(download, kind = "snapshot") {
656
+ const { build, directory, files } = download;
657
+ if (files.length === 0) return `Build #${build.number} has no ${kind}s to download.`;
658
+ return [
659
+ `Downloaded ${files.length} ${kind}${files.length === 1 ? "" : "s"} of build #${build.number} to ${directory}`,
660
+ `Branch: ${formatValue(build.head.branch)}`,
661
+ `Commit: ${formatValue(build.head.sha)}`,
662
+ `URL: ${build.url}`
663
+ ].join("\n");
664
+ }
379
665
  /** When and where a change was captured, on one line. */
380
666
  function formatOccurrence(occurrence) {
381
667
  return `${occurrence.date} in build #${occurrence.buildNumber}`;
@@ -757,54 +1043,20 @@ function formatMediaVersions(versions) {
757
1043
  ])
758
1044
  ].filter((line) => line !== null).slice(0, -1).join("\n");
759
1045
  }
760
- //#endregion
761
- //#region src/lib/terminal.ts
762
1046
  /**
763
- * Printing text the CLI did not author — an OAuth error description chosen by
764
- * the authorization server, for instance.
765
- *
766
- * A terminal acts on what it is given: an ANSI escape sequence moves the
767
- * cursor, erases a line or repaints it, and a carriage return overwrites the
768
- * line just printed. Remote text reaching it unfiltered therefore doesn't just
769
- * read badly, it can forge CLI output — a fake "run this command to continue"
770
- * instruction under the CLI's own name (GHSA-q9j4-4h4j-mv5m).
1047
+ * Format documentation search results, best match first. Titles and excerpts
1048
+ * come from the docs host, so they are sanitized before reaching the terminal,
1049
+ * which also cuts the excerpt down to a single line. URLs were normalized when
1050
+ * the results were parsed.
771
1051
  */
772
- /**
773
- * Longest remote string we print. A description is a sentence; a wall of text
774
- * is itself a way to scroll the real message off the screen.
775
- */
776
- const MAX_LENGTH = 200;
777
- /**
778
- * Escape sequences, matched together with the bytes that belong to them so no
779
- * parameter remnant (`[2K`) is left behind as text: CSI (`ESC [`), OSC
780
- * (`ESC ]`, up to its terminator) and, last, the plain escape sequences —
781
- * optional intermediate bytes and a final one, which covers `ESC c` (reset the
782
- * terminal) as much as `ESC 7`.
783
- */
784
- const ESCAPE_SEQUENCE_REGEX = /[\u001B\u009B](?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\)?|[ -/]*[0-~])/g;
785
- /** Anything else a terminal acts on rather than displays: C0, DEL and C1. */
786
- const CONTROL_CHARACTER_REGEX = /[\u0000-\u001F\u007F-\u009F]/g;
787
- /**
788
- * Explicit directional formatting: the other way to make a line read as
789
- * something other than what it says, by reordering the characters around it
790
- * rather than by driving the terminal. Bidirectional text itself is untouched —
791
- * only the overrides, embeddings, isolates and marks are dropped.
792
- */
793
- const DIRECTIONAL_FORMATTING_REGEX = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
794
- /**
795
- * Reduce remote text to characters a terminal can only display, on a single
796
- * line and bounded in length.
797
- *
798
- * Returns an empty string when nothing printable is left, so callers can fall
799
- * back to a message of their own rather than print a blank error.
800
- *
801
- * @param text The remote value. Typed `unknown` because it comes from parsed
802
- * JSON or a URL parameter and is not necessarily a string at runtime.
803
- */
804
- function sanitizeTerminalText(text) {
805
- if (text === null || text === void 0) return "";
806
- const sanitized = String(text).replace(ESCAPE_SEQUENCE_REGEX, "").replace(DIRECTIONAL_FORMATTING_REGEX, "").replace(CONTROL_CHARACTER_REGEX, " ").replace(/\s+/g, " ").trim();
807
- return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}…` : sanitized;
1052
+ function formatDocsSearchResults(results, query) {
1053
+ if (results.length === 0) return `No documentation found for "${sanitizeTerminalText(query)}".`;
1054
+ return results.flatMap((result, index) => [
1055
+ `${index + 1}. ${sanitizeTerminalText(result.title)}`,
1056
+ ` ${result.url}`,
1057
+ result.excerpt ? ` ${sanitizeTerminalText(result.excerpt)}` : null,
1058
+ ""
1059
+ ]).filter((line) => line !== null).slice(0, -1).join("\n");
808
1060
  }
809
1061
  //#endregion
810
1062
  //#region src/lib/oauth.ts
@@ -1223,6 +1475,27 @@ async function runBuildAction(opts) {
1223
1475
  }
1224
1476
  }
1225
1477
  //#endregion
1478
+ //#region src/commands/build/download.ts
1479
+ function registerBuildDownload(build) {
1480
+ 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) => {
1481
+ try {
1482
+ const target = await resolveBuildTarget(reference, options, { auth: "project" });
1483
+ const directory = resolve(options.output ?? `argos-build-${target.buildNumber}`);
1484
+ await assertEmptyDirectory(directory);
1485
+ const build = await fetchBuild(target);
1486
+ if (isBuildPending(build)) fail(`Build #${build.number} is still processing (${build.status}). Try again in a moment.`);
1487
+ output(await downloadBuildSnapshots({
1488
+ build,
1489
+ diffs: await fetchAllDiffs(target),
1490
+ directory,
1491
+ json: options.json
1492
+ }), options, (data) => formatSnapshotDownload(data));
1493
+ } catch (error) {
1494
+ handleCliError(error, "project");
1495
+ }
1496
+ });
1497
+ }
1498
+ //#endregion
1226
1499
  //#region src/commands/build/get.ts
1227
1500
  function registerBuildGet(build) {
1228
1501
  build.command("get").description("Fetch build metadata").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(jsonOption).action((reference, options) => runBuildAction({
@@ -1238,42 +1511,54 @@ function registerBuildGet(build) {
1238
1511
  }));
1239
1512
  }
1240
1513
  //#endregion
1241
- //#region src/commands/build/snapshots.ts
1242
- const PER_PAGE$1 = 100;
1243
- function isBuildPending(build) {
1244
- return build.status === "pending" || build.status === "progress";
1245
- }
1246
- async function fetchBuild(target) {
1247
- const { client, owner, project, buildNumber } = target;
1248
- return unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}", { params: { path: {
1249
- owner,
1250
- project,
1251
- buildNumber
1252
- } } }));
1253
- }
1254
- /** Fetch every diff of a build, following pagination. */
1255
- async function fetchAllDiffs(target, options) {
1256
- const { client, owner, project, buildNumber } = target;
1514
+ //#region src/lib/pagination.ts
1515
+ /** Largest page the API serves. */
1516
+ const MAX_PER_PAGE = 100;
1517
+ /**
1518
+ * Walk a paginated endpoint until `limit` items have been collected, the server
1519
+ * runs out of results, or its reported total is reached.
1520
+ *
1521
+ * `fetchPage` receives the page number and the size to request, both already
1522
+ * stringified — every paginated Argos endpoint takes them as query strings.
1523
+ */
1524
+ async function fetchPages(limit, fetchPage) {
1525
+ const perPage = String(Math.min(MAX_PER_PAGE, limit));
1257
1526
  const results = [];
1258
1527
  for (let page = 1;; page++) {
1259
- const data = unwrap(await client.GET("/projects/{owner}/{project}/builds/{buildNumber}/diffs", { params: {
1260
- path: {
1261
- owner,
1262
- project,
1263
- buildNumber
1264
- },
1265
- query: {
1266
- page: String(page),
1267
- perPage: String(PER_PAGE$1),
1268
- metricsPeriod: options.metricsPeriod,
1269
- ...options.needsReview ? { needsReview: "true" } : {}
1270
- }
1271
- } }));
1528
+ const data = await fetchPage({
1529
+ page: String(page),
1530
+ perPage
1531
+ });
1272
1532
  results.push(...data.results);
1273
- if (results.length >= data.pageInfo.total || data.results.length === 0) break;
1533
+ if (results.length >= limit || results.length >= data.pageInfo.total || data.results.length === 0) break;
1274
1534
  }
1275
- return results;
1535
+ return results.slice(0, limit);
1276
1536
  }
1537
+ //#endregion
1538
+ //#region src/commands/build/list.ts
1539
+ function registerBuildList(build) {
1540
+ 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) => {
1541
+ try {
1542
+ const { client, owner, project } = await resolveProjectTarget(options, { auth: "project" });
1543
+ output(await fetchPages(toLimit(options.limit), async (pagination) => unwrap(await client.GET("/projects/{owner}/{project}/builds", { params: {
1544
+ path: {
1545
+ owner,
1546
+ project
1547
+ },
1548
+ query: {
1549
+ ...pagination,
1550
+ ...options.branch ? { head: options.branch } : {},
1551
+ ...options.commit ? { headSha: options.commit } : {},
1552
+ ...options.search ? { search: options.search } : {}
1553
+ }
1554
+ } }))), options, formatBuilds);
1555
+ } catch (error) {
1556
+ handleCliError(error, "project");
1557
+ }
1558
+ });
1559
+ }
1560
+ //#endregion
1561
+ //#region src/commands/build/snapshots.ts
1277
1562
  function registerBuildSnapshots(build) {
1278
1563
  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) => {
1279
1564
  try {
@@ -1332,12 +1617,101 @@ const registerBuildUnsubscribe = defineBuildSubscription({
1332
1617
  //#endregion
1333
1618
  //#region src/commands/build/index.ts
1334
1619
  function buildCommand(program) {
1335
- const build = program.command("build").description("Inspect Argos builds");
1620
+ const build = program.command("build").description("Inspect and download Argos builds");
1621
+ registerBuildList(build);
1336
1622
  registerBuildGet(build);
1337
1623
  registerBuildSnapshots(build);
1624
+ registerBuildDownload(build);
1338
1625
  registerBuildSubscribe(build);
1339
1626
  registerBuildUnsubscribe(build);
1340
1627
  }
1628
+ /**
1629
+ * Find the most recent baseline among a branch's builds.
1630
+ *
1631
+ * Whether a build can be a baseline (complete, tests passed, not a subset,
1632
+ * approved and not rejected) is not part of the build the API returns, so this
1633
+ * leaves the decision to Argos: it walks the branch's builds newest first, a
1634
+ * page at a time, and asks `findBaseline` for the first of their commits that
1635
+ * has an eligible build. Gives up after `maxPages` pages.
1636
+ */
1637
+ async function findLatestBaseline(api, { maxPages = 10 } = {}) {
1638
+ const asked = /* @__PURE__ */ new Set();
1639
+ let listed = 0;
1640
+ for (let page = 1; page <= maxPages; page++) {
1641
+ const { results, pageInfo } = await api.listBuilds(page);
1642
+ listed += results.length;
1643
+ const commits = [...new Set(results.map((build) => build.head.sha))].filter((sha) => !asked.has(sha));
1644
+ if (commits.length > 0) {
1645
+ commits.forEach((sha) => asked.add(sha));
1646
+ const baseline = await api.findBaseline(commits);
1647
+ if (baseline) return baseline;
1648
+ }
1649
+ if (results.length === 0 || listed >= pageInfo.total) break;
1650
+ }
1651
+ return null;
1652
+ }
1653
+ //#endregion
1654
+ //#region src/commands/baseline/download.ts
1655
+ 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.";
1656
+ const FAILURE_STATUSES = /* @__PURE__ */ new Set(["failure", "retryFailure"]);
1657
+ async function fetchTokenProject(client) {
1658
+ try {
1659
+ return unwrap(await client.GET("/project"));
1660
+ } catch (error) {
1661
+ if (error instanceof APIError && (error.status === 401 || error.status === 403)) fail(`${error.message}\n${PROJECT_TOKEN_HINT}`);
1662
+ throw error;
1663
+ }
1664
+ }
1665
+ function registerBaselineDownload(baseline) {
1666
+ 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(tokenOption).addOption(jsonOption).action(async (options) => {
1667
+ try {
1668
+ const directory = resolve(options.output ?? "argos-baseline");
1669
+ await assertEmptyDirectory(directory);
1670
+ const token = await resolveOptionalToken(options);
1671
+ if (!token) fail("No Argos token found. Pass the project's token with --token or set ARGOS_TOKEN.");
1672
+ const client = createApiClient(token);
1673
+ const project = await fetchTokenProject(client);
1674
+ const path = {
1675
+ owner: project.account.slug,
1676
+ project: project.name
1677
+ };
1678
+ const branch = options.branch ?? project.defaultBaseBranch;
1679
+ const build = await findLatestBaseline({
1680
+ listBuilds: async (page) => unwrap(await client.GET("/projects/{owner}/{project}/builds", { params: {
1681
+ path,
1682
+ query: {
1683
+ head: branch,
1684
+ page: String(page),
1685
+ perPage: String(100)
1686
+ }
1687
+ } })),
1688
+ findBaseline: async (commits) => unwrap(await client.POST("/baseline", { body: {
1689
+ commits,
1690
+ name: options.buildName,
1691
+ mode: options.mode
1692
+ } })).baseline
1693
+ });
1694
+ 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.`);
1695
+ output(await downloadBuildSnapshots({
1696
+ build,
1697
+ diffs: (await fetchAllDiffs({
1698
+ client,
1699
+ ...path,
1700
+ buildNumber: String(build.number)
1701
+ })).filter((diff) => !FAILURE_STATUSES.has(diff.status)),
1702
+ directory,
1703
+ json: options.json
1704
+ }), options, (data) => formatSnapshotDownload(data, "baseline snapshot"));
1705
+ } catch (error) {
1706
+ handleCliError(error, "project");
1707
+ }
1708
+ });
1709
+ }
1710
+ //#endregion
1711
+ //#region src/commands/baseline/index.ts
1712
+ function baselineCommand(program) {
1713
+ registerBaselineDownload(program.command("baseline").description("Export a project's baseline screenshots"));
1714
+ }
1341
1715
  //#endregion
1342
1716
  //#region src/lib/body.ts
1343
1717
  /**
@@ -2021,30 +2395,6 @@ const registerChangeIgnore = defineChangeAction({
2021
2395
  } }))
2022
2396
  });
2023
2397
  //#endregion
2024
- //#region src/lib/pagination.ts
2025
- /** Largest page the API serves. */
2026
- const MAX_PER_PAGE = 100;
2027
- /**
2028
- * Walk a paginated endpoint until `limit` items have been collected, the server
2029
- * runs out of results, or its reported total is reached.
2030
- *
2031
- * `fetchPage` receives the page number and the size to request, both already
2032
- * stringified — every paginated Argos endpoint takes them as query strings.
2033
- */
2034
- async function fetchPages(limit, fetchPage) {
2035
- const perPage = String(Math.min(MAX_PER_PAGE, limit));
2036
- const results = [];
2037
- for (let page = 1;; page++) {
2038
- const data = await fetchPage({
2039
- page: String(page),
2040
- perPage
2041
- });
2042
- results.push(...data.results);
2043
- if (results.length >= limit || results.length >= data.pageInfo.total || data.results.length === 0) break;
2044
- }
2045
- return results.slice(0, limit);
2046
- }
2047
- //#endregion
2048
2398
  //#region src/commands/change/list.ts
2049
2399
  function registerChangeList(change) {
2050
2400
  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) => {
@@ -3325,6 +3675,135 @@ function automationCommand(program) {
3325
3675
  }));
3326
3676
  }
3327
3677
  //#endregion
3678
+ //#region src/lib/docs.ts
3679
+ /**
3680
+ * Searching the Argos documentation.
3681
+ *
3682
+ * The docs are published on GitBook, which serves every public site with a
3683
+ * Model Context Protocol endpoint at `<site>/~gitbook/mcp`. Its
3684
+ * `searchDocumentation` tool needs no token — unlike GitBook's REST search,
3685
+ * which wants an API token that a published CLI could not keep secret.
3686
+ *
3687
+ * The endpoint is stateless, so a single `tools/call` request is enough: no
3688
+ * `initialize` handshake or session to carry between calls.
3689
+ */
3690
+ const DOCS_URL = "https://argos-ci.com/docs";
3691
+ const MCP_ENDPOINT = `${DOCS_URL}/~gitbook/mcp`;
3692
+ /**
3693
+ * A cold search can take well over ten seconds; past this, the request is
3694
+ * abandoned rather than left hanging.
3695
+ */
3696
+ const TIMEOUT_MS = 3e4;
3697
+ /**
3698
+ * One search hit, as the tool renders it:
3699
+ *
3700
+ * ```
3701
+ * Title: <page title>
3702
+ * Link: <page URL>
3703
+ * Content: <matching passage, possibly several paragraphs>
3704
+ * ```
3705
+ *
3706
+ * `Content` is left out when the page has no passage to show.
3707
+ */
3708
+ const RESULT_REGEX = /^Title: ([^\n]*)\nLink: ([^\n]*)(?:\nContent: ([\s\S]*))?/;
3709
+ /**
3710
+ * The link as a normalized `https:` URL, or `null` when it is not one. The URL
3711
+ * serializer percent-encodes control and non-ASCII characters, so the result
3712
+ * is safe to print as-is and to hand to `curl`.
3713
+ */
3714
+ function toHttpsUrl(link) {
3715
+ if (!link || !URL.canParse(link)) return null;
3716
+ const url = new URL(link);
3717
+ return url.protocol === "https:" ? url.href : null;
3718
+ }
3719
+ /** Parse the tool's text blocks into results, skipping any it can't read. */
3720
+ function parseDocsSearchContent(content) {
3721
+ const results = /* @__PURE__ */ new Map();
3722
+ for (const block of content) {
3723
+ if (block.type !== "text" || !block.text) continue;
3724
+ const match = RESULT_REGEX.exec(block.text);
3725
+ const title = match?.[1]?.trim();
3726
+ const url = toHttpsUrl(match?.[2]);
3727
+ if (!title || !url || results.has(url)) continue;
3728
+ results.set(url, {
3729
+ title,
3730
+ url,
3731
+ excerpt: match?.[3]?.trim() || null
3732
+ });
3733
+ }
3734
+ return [...results.values()];
3735
+ }
3736
+ /**
3737
+ * Read the JSON-RPC response out of the body. The endpoint answers with a
3738
+ * server-sent event stream, each JSON-RPC message on one `data:` line, but may
3739
+ * answer with plain JSON, which the protocol allows too.
3740
+ */
3741
+ function parseMcpResponse(body, contentType) {
3742
+ if (!contentType?.includes("text/event-stream")) return JSON.parse(body);
3743
+ for (const line of body.split("\n")) {
3744
+ if (!line.startsWith("data:")) continue;
3745
+ const message = JSON.parse(line.slice(5));
3746
+ if ("result" in message || "error" in message) return message;
3747
+ }
3748
+ fail("The documentation search returned no response.");
3749
+ }
3750
+ /** Search the Argos documentation, best match first. */
3751
+ async function searchDocs(query, options) {
3752
+ const userAgent = getUserAgent();
3753
+ const response = await fetch(MCP_ENDPOINT, {
3754
+ method: "POST",
3755
+ headers: {
3756
+ "Content-Type": "application/json",
3757
+ Accept: "application/json, text/event-stream",
3758
+ ...userAgent ? { "User-Agent": userAgent } : {}
3759
+ },
3760
+ body: JSON.stringify({
3761
+ jsonrpc: "2.0",
3762
+ id: 1,
3763
+ method: "tools/call",
3764
+ params: {
3765
+ name: "searchDocumentation",
3766
+ arguments: { query }
3767
+ }
3768
+ }),
3769
+ signal: AbortSignal.timeout(TIMEOUT_MS)
3770
+ }).catch((error) => {
3771
+ const reason = error instanceof Error ? error.message : String(error);
3772
+ fail(`Could not reach ${DOCS_URL}: ${reason}`);
3773
+ });
3774
+ if (!response.ok) fail(`The documentation search failed with HTTP ${response.status}.`);
3775
+ const message = parseMcpResponse(await response.text(), response.headers.get("content-type"));
3776
+ const content = message.result?.content ?? [];
3777
+ 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"}`);
3778
+ return parseDocsSearchContent(content).slice(0, options.limit);
3779
+ }
3780
+ //#endregion
3781
+ //#region src/commands/docs/search.ts
3782
+ const DEFAULT_DOCS_LIMIT = 5;
3783
+ function registerDocsSearch(docs) {
3784
+ 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", [
3785
+ "",
3786
+ "No token needed. Read a result in full as Markdown by appending .md to",
3787
+ "its URL, or by requesting it with an `Accept: text/markdown` header:",
3788
+ "",
3789
+ " url=$(argos docs search \"parallel builds\" --json | jq -r \".[0].url\")",
3790
+ " curl -H \"Accept: text/markdown\" \"$url\""
3791
+ ].join("\n")).action(async (words, options) => {
3792
+ try {
3793
+ const query = words.join(" ").trim();
3794
+ if (!query) fail("A search query is required.");
3795
+ output(await searchDocs(query, { limit: toLimit(options.limit, { max: 10 }) }), options, (data) => formatDocsSearchResults(data, query));
3796
+ } catch (error) {
3797
+ handleCliError(error);
3798
+ }
3799
+ });
3800
+ }
3801
+ //#endregion
3802
+ //#region src/commands/docs/index.ts
3803
+ function docsCommand(program) {
3804
+ registerDocsSearch(program.command("docs").description("Search the Argos documentation from the terminal"));
3805
+ }
3806
+ //#endregion
3328
3807
  //#region src/index.ts
3329
3808
  const __dirname = fileURLToPath(new URL(".", import.meta.url));
3330
3809
  const rawPkg = await readFile(resolve(__dirname, "..", "package.json"), "utf8");
@@ -3335,6 +3814,7 @@ uploadCommand(program);
3335
3814
  skipCommand(program);
3336
3815
  finalizeCommand(program);
3337
3816
  buildCommand(program);
3817
+ baselineCommand(program);
3338
3818
  reviewCommand(program);
3339
3819
  commentCommand(program);
3340
3820
  loginCommand(program);
@@ -3349,6 +3829,7 @@ testCommand(program);
3349
3829
  accountCommand(program);
3350
3830
  projectCommand(program);
3351
3831
  automationCommand(program);
3832
+ docsCommand(program);
3352
3833
  if (!process.argv.slice(2).length) program.outputHelp();
3353
3834
  else program.parse(process.argv);
3354
3835
  //#endregion
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@argos-ci/cli",
3
3
  "description": "Command-line (CLI) for visual testing with Argos.",
4
- "version": "6.9.6",
4
+ "version": "6.11.0",
5
5
  "bin": {
6
6
  "argos": "./bin/argos-cli.js"
7
7
  },
@@ -23,19 +23,24 @@
23
23
  },
24
24
  "license": "MIT",
25
25
  "keywords": [
26
- "cli",
27
26
  "argos",
27
+ "argos-ci",
28
+ "cli",
28
29
  "testing",
29
- "visual testing",
30
- "regression",
31
- "visual regression"
30
+ "visual-testing",
31
+ "visual-regression",
32
+ "visual-regression-testing",
33
+ "screenshot-testing",
34
+ "snapshot-testing",
35
+ "continuous-integration",
36
+ "ci"
32
37
  ],
33
38
  "publishConfig": {
34
39
  "access": "public"
35
40
  },
36
41
  "dependencies": {
37
- "@argos-ci/api-client": "0.31.2",
38
- "@argos-ci/core": "6.8.7",
42
+ "@argos-ci/api-client": "0.31.3",
43
+ "@argos-ci/core": "6.8.8",
39
44
  "@vercel/detect-agent": "^1.2.5",
40
45
  "commander": "^15.0.0",
41
46
  "open": "^11.0.4",
@@ -54,5 +59,5 @@
54
59
  "check-format": "prettier --check --ignore-unknown --ignore-path=../../.gitignore --ignore-path=../../.prettierignore .",
55
60
  "lint": "eslint ."
56
61
  },
57
- "gitHead": "e9d0b2fb39001683230eff86f9c39e0016b5cf27"
62
+ "gitHead": "e6023fc9502dba025911c8e4fd5dab829b729125"
58
63
  }