@argos-ci/cli 6.10.0 → 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 +412 -70
  2. package/package.json +2 -2
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,6 +45,7 @@ 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));
@@ -48,10 +53,10 @@ const limitOption = new Option("--limit <number>", "Maximum number of items to f
48
53
  * Parse a `--limit` value into a positive integer, or abort. Pass `max` when
49
54
  * the source caps how many items it can return.
50
55
  */
51
- function toLimit(value, options) {
56
+ function toLimit(value, { max = Infinity } = {}) {
52
57
  const limit = Number(value);
53
58
  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}".`);
59
+ if (limit > max) fail(`--limit must be at most ${max}, received "${value}".`);
55
60
  return limit;
56
61
  }
57
62
  /** Parse a `--pr` value into a pull request number, or abort. */
@@ -252,6 +257,205 @@ function unwrapEmpty(result) {
252
257
  if (!result.response.ok) throwAPIError(result.error, result.response);
253
258
  }
254
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
255
459
  //#region src/lib/terminal.ts
256
460
  /**
257
461
  * Printing text the CLI did not author — an OAuth error description chosen by
@@ -429,6 +633,35 @@ function formatSnapshots(diffs, build) {
429
633
  ...diffs.flatMap((diff) => [...formatSnapshotDiff(diff, build), ""])
430
634
  ].slice(0, -1).join("\n");
431
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
+ }
432
665
  /** When and where a change was captured, on one line. */
433
666
  function formatOccurrence(occurrence) {
434
667
  return `${occurrence.date} in build #${occurrence.buildNumber}`;
@@ -812,15 +1045,16 @@ function formatMediaVersions(versions) {
812
1045
  }
813
1046
  /**
814
1047
  * 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.
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.
817
1051
  */
818
1052
  function formatDocsSearchResults(results, query) {
819
1053
  if (results.length === 0) return `No documentation found for "${sanitizeTerminalText(query)}".`;
820
1054
  return results.flatMap((result, index) => [
821
1055
  `${index + 1}. ${sanitizeTerminalText(result.title)}`,
822
- indent(sanitizeTerminalText(result.url)),
823
- result.excerpt ? indent(sanitizeTerminalText(result.excerpt)) : null,
1056
+ ` ${result.url}`,
1057
+ result.excerpt ? ` ${sanitizeTerminalText(result.excerpt)}` : null,
824
1058
  ""
825
1059
  ]).filter((line) => line !== null).slice(0, -1).join("\n");
826
1060
  }
@@ -1241,6 +1475,27 @@ async function runBuildAction(opts) {
1241
1475
  }
1242
1476
  }
1243
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
1244
1499
  //#region src/commands/build/get.ts
1245
1500
  function registerBuildGet(build) {
1246
1501
  build.command("get").description("Fetch build metadata").argument("<buildReference>", "Build number or Argos build URL").addOption(tokenOption).addOption(jsonOption).action((reference, options) => runBuildAction({
@@ -1256,42 +1511,54 @@ function registerBuildGet(build) {
1256
1511
  }));
1257
1512
  }
1258
1513
  //#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;
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));
1275
1526
  const results = [];
1276
1527
  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
- } }));
1528
+ const data = await fetchPage({
1529
+ page: String(page),
1530
+ perPage
1531
+ });
1290
1532
  results.push(...data.results);
1291
- 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;
1292
1534
  }
1293
- return results;
1535
+ return results.slice(0, limit);
1294
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
1295
1562
  function registerBuildSnapshots(build) {
1296
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) => {
1297
1564
  try {
@@ -1350,12 +1617,101 @@ const registerBuildUnsubscribe = defineBuildSubscription({
1350
1617
  //#endregion
1351
1618
  //#region src/commands/build/index.ts
1352
1619
  function buildCommand(program) {
1353
- const build = program.command("build").description("Inspect Argos builds");
1620
+ const build = program.command("build").description("Inspect and download Argos builds");
1621
+ registerBuildList(build);
1354
1622
  registerBuildGet(build);
1355
1623
  registerBuildSnapshots(build);
1624
+ registerBuildDownload(build);
1356
1625
  registerBuildSubscribe(build);
1357
1626
  registerBuildUnsubscribe(build);
1358
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
+ }
1359
1715
  //#endregion
1360
1716
  //#region src/lib/body.ts
1361
1717
  /**
@@ -2039,30 +2395,6 @@ const registerChangeIgnore = defineChangeAction({
2039
2395
  } }))
2040
2396
  });
2041
2397
  //#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
2398
  //#region src/commands/change/list.ts
2067
2399
  function registerChangeList(change) {
2068
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) => {
@@ -3355,7 +3687,6 @@ function automationCommand(program) {
3355
3687
  * The endpoint is stateless, so a single `tools/call` request is enough: no
3356
3688
  * `initialize` handshake or session to carry between calls.
3357
3689
  */
3358
- /** Root of the published Argos documentation. */
3359
3690
  const DOCS_URL = "https://argos-ci.com/docs";
3360
3691
  const MCP_ENDPOINT = `${DOCS_URL}/~gitbook/mcp`;
3361
3692
  /**
@@ -3375,6 +3706,16 @@ const TIMEOUT_MS = 3e4;
3375
3706
  * `Content` is left out when the page has no passage to show.
3376
3707
  */
3377
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
+ }
3378
3719
  /** Parse the tool's text blocks into results, skipping any it can't read. */
3379
3720
  function parseDocsSearchContent(content) {
3380
3721
  const results = /* @__PURE__ */ new Map();
@@ -3382,7 +3723,7 @@ function parseDocsSearchContent(content) {
3382
3723
  if (block.type !== "text" || !block.text) continue;
3383
3724
  const match = RESULT_REGEX.exec(block.text);
3384
3725
  const title = match?.[1]?.trim();
3385
- const url = match?.[2]?.trim();
3726
+ const url = toHttpsUrl(match?.[2]);
3386
3727
  if (!title || !url || results.has(url)) continue;
3387
3728
  results.set(url, {
3388
3729
  title,
@@ -3404,7 +3745,7 @@ function parseMcpResponse(body, contentType) {
3404
3745
  const message = JSON.parse(line.slice(5));
3405
3746
  if ("result" in message || "error" in message) return message;
3406
3747
  }
3407
- throw new CliError("The documentation search returned no response.");
3748
+ fail("The documentation search returned no response.");
3408
3749
  }
3409
3750
  /** Search the Argos documentation, best match first. */
3410
3751
  async function searchDocs(query, options) {
@@ -3428,12 +3769,12 @@ async function searchDocs(query, options) {
3428
3769
  signal: AbortSignal.timeout(TIMEOUT_MS)
3429
3770
  }).catch((error) => {
3430
3771
  const reason = error instanceof Error ? error.message : String(error);
3431
- throw new CliError(`Could not reach ${DOCS_URL}: ${reason}`);
3772
+ fail(`Could not reach ${DOCS_URL}: ${reason}`);
3432
3773
  });
3433
- if (!response.ok) throw new CliError(`The documentation search failed with HTTP ${response.status}.`);
3774
+ if (!response.ok) fail(`The documentation search failed with HTTP ${response.status}.`);
3434
3775
  const message = parseMcpResponse(await response.text(), response.headers.get("content-type"));
3435
3776
  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"}`);
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"}`);
3437
3778
  return parseDocsSearchContent(content).slice(0, options.limit);
3438
3779
  }
3439
3780
  //#endregion
@@ -3473,6 +3814,7 @@ uploadCommand(program);
3473
3814
  skipCommand(program);
3474
3815
  finalizeCommand(program);
3475
3816
  buildCommand(program);
3817
+ baselineCommand(program);
3476
3818
  reviewCommand(program);
3477
3819
  commentCommand(program);
3478
3820
  loginCommand(program);
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.10.0",
4
+ "version": "6.11.0",
5
5
  "bin": {
6
6
  "argos": "./bin/argos-cli.js"
7
7
  },
@@ -59,5 +59,5 @@
59
59
  "check-format": "prettier --check --ignore-unknown --ignore-path=../../.gitignore --ignore-path=../../.prettierignore .",
60
60
  "lint": "eslint ."
61
61
  },
62
- "gitHead": "810aab42c890851ea19ba96f49c4f167a5f2e3df"
62
+ "gitHead": "e6023fc9502dba025911c8e4fd5dab829b729125"
63
63
  }