@argos-ci/cli 6.2.0 → 6.4.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 +396 -52
  2. package/package.json +4 -4
package/dist/index.mjs CHANGED
@@ -6,8 +6,8 @@ import { deploy, finalize, skip, upload } from "@argos-ci/core";
6
6
  import ora from "ora";
7
7
  import { APIError, createClient, throwAPIError } from "@argos-ci/api-client";
8
8
  import { homedir } from "node:os";
9
- import { createServer } from "node:http";
10
9
  import { createHash, randomBytes } from "node:crypto";
10
+ import { createServer } from "node:http";
11
11
  import open from "open";
12
12
  //#region src/options.ts
13
13
  const parallelNonceOption = new Option("--parallel-nonce <string>", "A unique ID for this parallel build");
@@ -17,6 +17,19 @@ const buildNameOption = new Option("--build-name <string>", "Name of the build,
17
17
  const accountOption = new Option("--account <slug>", "Slug of the account (personal or team) that will own the project");
18
18
  const jsonOption = new Option("--json", "Output machine-readable JSON instead of human-readable text");
19
19
  const projectPathOption = new Option("--project <owner/project>", "Project path in owner/project format. Required for build-number references on review and comment commands");
20
+ const changeProjectPathOption = new Option("--project <owner/project>", "Project the change belongs to, in owner/project format. Also ARGOS_PROJECT");
21
+ const METRICS_PERIOD_BY_CHOICE = {
22
+ "24h": "LAST_24_HOURS",
23
+ "3d": "LAST_3_DAYS",
24
+ "7d": "LAST_7_DAYS",
25
+ "30d": "LAST_30_DAYS",
26
+ "90d": "LAST_90_DAYS"
27
+ };
28
+ const metricsPeriodOption = new Option("--metrics-period <period>", "Window over which test flakiness metrics are computed").choices(Object.keys(METRICS_PERIOD_BY_CHOICE)).default("7d");
29
+ /** Map a `--metrics-period` choice to the value the API expects. */
30
+ function toMetricsPeriod(choice) {
31
+ return METRICS_PERIOD_BY_CHOICE[choice] ?? "LAST_7_DAYS";
32
+ }
20
33
  //#endregion
21
34
  //#region src/commands/upload.ts
22
35
  function uploadCommand(program) {
@@ -196,6 +209,32 @@ function formatBuild(build) {
196
209
  `URL: ${build.url}`
197
210
  ].join("\n");
198
211
  }
212
+ /** Render a 0–1 metric to two decimals, or `-` when absent. */
213
+ function formatRatio(value) {
214
+ return value === null || value === void 0 ? "-" : value.toFixed(2);
215
+ }
216
+ /** Compact one-line summary of a test's flakiness metrics. */
217
+ function formatFlakiness(metrics) {
218
+ return `${formatRatio(metrics.flakiness)} (stability ${formatRatio(metrics.stability)}, consistency ${formatRatio(metrics.consistency)})`;
219
+ }
220
+ /** Human-readable lines for a single snapshot diff. */
221
+ function formatSnapshotDiff(diff, build) {
222
+ const lines = [
223
+ `${diff.name} [${diff.status}]`,
224
+ ` Review: ${build.url}/${diff.id}`,
225
+ ` Mask: ${formatValue(diff.url)}`,
226
+ ` Base file: ${formatValue(diff.base?.url)}`,
227
+ ` Head file: ${formatValue(diff.head?.url)}`,
228
+ ` Score: ${formatValue(diff.score)}`,
229
+ ` Group: ${formatValue(diff.group)}`
230
+ ];
231
+ if (diff.test) lines.push(` Flakiness: ${formatFlakiness(diff.test.metrics)}`);
232
+ if (diff.change) {
233
+ const ignored = diff.change.ignored ? " [ignored]" : "";
234
+ lines.push(` Change: ${diff.change.id}${ignored} · ${diff.change.occurrences} occurrences`);
235
+ }
236
+ return lines;
237
+ }
199
238
  function formatSnapshots(diffs, build) {
200
239
  if (diffs.length === 0) return "No snapshots found.";
201
240
  return [
@@ -203,18 +242,16 @@ function formatSnapshots(diffs, build) {
203
242
  `Count: ${diffs.length}`,
204
243
  `Summary: ${formatSnapshotSummary(diffs)}`,
205
244
  "",
206
- ...diffs.flatMap((diff) => [
207
- `${diff.name} [${diff.status}]`,
208
- ` Review: ${build.url}/${diff.id}`,
209
- ` Mask: ${formatValue(diff.url)}`,
210
- ` Base file: ${formatValue(diff.base?.url)}`,
211
- ` Head file: ${formatValue(diff.head?.url)}`,
212
- ` Score: ${formatValue(diff.score)}`,
213
- ` Group: ${formatValue(diff.group)}`,
214
- ""
215
- ])
245
+ ...diffs.flatMap((diff) => [...formatSnapshotDiff(diff, build), ""])
216
246
  ].slice(0, -1).join("\n");
217
247
  }
248
+ function formatChange(change) {
249
+ return [
250
+ `Change ${change.id}`,
251
+ `Ignored: ${change.ignored ? "yes" : "no"}`,
252
+ `Occurrences: ${change.occurrences}`
253
+ ].join("\n");
254
+ }
218
255
  function formatReview(review) {
219
256
  const lines = [
220
257
  `Review #${review.id}`,
@@ -238,6 +275,33 @@ function formatReviews(reviews) {
238
275
  ])
239
276
  ].slice(0, -1).join("\n");
240
277
  }
278
+ function formatAnalytics(analytics, context) {
279
+ const { screenshots, builds } = analytics;
280
+ const lines = [
281
+ `Analytics for ${context.account}`,
282
+ `Period: ${context.from} → ${context.to ?? "now"} (grouped by ${context.groupBy})`,
283
+ "",
284
+ `Builds: ${builds.all.total}`,
285
+ ` Changes detected: ${builds.all.changesDetected}`,
286
+ ` No changes: ${builds.all.noChanges}`,
287
+ ` Accepted: ${builds.all.accepted}`,
288
+ ` Rejected: ${builds.all.rejected}`,
289
+ `Screenshots: ${screenshots.all.total}`
290
+ ];
291
+ const names = /* @__PURE__ */ new Map();
292
+ for (const project of [...builds.projects, ...screenshots.projects]) names.set(project.id, project.name);
293
+ const ids = /* @__PURE__ */ new Set([...Object.keys(builds.all.projects), ...Object.keys(screenshots.all.projects)]);
294
+ if (ids.size > 0) {
295
+ const rows = [...ids].map((id) => ({
296
+ name: names.get(id) ?? id,
297
+ builds: builds.all.projects[id] ?? 0,
298
+ screenshots: screenshots.all.projects[id] ?? 0
299
+ })).sort((a, b) => b.builds - a.builds || b.screenshots - a.screenshots);
300
+ lines.push("", `Projects (${rows.length}):`);
301
+ for (const row of rows) lines.push(` ${row.name}: ${row.builds} builds, ${row.screenshots} screenshots`);
302
+ }
303
+ return lines.join("\n");
304
+ }
241
305
  function indent(text) {
242
306
  return text.split("\n").map((line) => ` ${line}`).join("\n");
243
307
  }
@@ -304,6 +368,118 @@ function fail(message) {
304
368
  throw new CliError(message);
305
369
  }
306
370
  //#endregion
371
+ //#region src/lib/oauth.ts
372
+ /**
373
+ * OAuth 2.1 client configuration and helpers for the `argos login` flow
374
+ * (Authorization Code + PKCE with a loopback redirect, RFC 8252).
375
+ *
376
+ * The authorization server is the Argos app origin; endpoints and token
377
+ * validation are implemented in the main Argos repo (`apps/backend/src/oauth`).
378
+ */
379
+ /** First-party public client id, seeded in the Argos database. */
380
+ const OAUTH_CLIENT_ID = "argos-cli";
381
+ /**
382
+ * Scopes requested by `argos login`, covering the CLI's user actions (identity,
383
+ * projects, reviews, comments). Build upload keeps using a project token.
384
+ */
385
+ const OAUTH_SCOPES = [
386
+ "profile",
387
+ "projects:read",
388
+ "projects:write",
389
+ "reviews:write",
390
+ "comments:read",
391
+ "comments:write"
392
+ ];
393
+ /** Refresh a bit early so a token never expires mid-request. */
394
+ const EXPIRY_SKEW_MS = 60 * 1e3;
395
+ function getAppBaseUrl() {
396
+ return process.env["ARGOS_APP_BASE_URL"] ?? "https://app.argos-ci.com/";
397
+ }
398
+ /**
399
+ * A token endpoint request that reached the server and was rejected by it
400
+ * (non-2xx / OAuth error), as opposed to a transient network failure. Lets
401
+ * callers tell "your session is gone, log in again" from "the network is down".
402
+ */
403
+ var OAuthTokenError = class extends Error {
404
+ code;
405
+ constructor(message, code) {
406
+ super(message);
407
+ this.code = code;
408
+ this.name = "OAuthTokenError";
409
+ }
410
+ };
411
+ function toTokenSet(data) {
412
+ return {
413
+ accessToken: data.access_token,
414
+ refreshToken: data.refresh_token,
415
+ expiresAt: Date.now() + data.expires_in * 1e3 - EXPIRY_SKEW_MS,
416
+ scope: data.scope ?? ""
417
+ };
418
+ }
419
+ /** Generate a PKCE `code_verifier` and its S256 `code_challenge`. */
420
+ function generatePkce() {
421
+ const codeVerifier = randomBytes(32).toString("base64url");
422
+ return {
423
+ codeVerifier,
424
+ codeChallenge: createHash("sha256").update(codeVerifier).digest("base64url")
425
+ };
426
+ }
427
+ /** Build the `/oauth/authorize` URL to open in the browser. */
428
+ function buildAuthorizeUrl(params) {
429
+ const url = new URL("/oauth/authorize", getAppBaseUrl());
430
+ url.searchParams.set("response_type", "code");
431
+ url.searchParams.set("client_id", OAUTH_CLIENT_ID);
432
+ url.searchParams.set("redirect_uri", params.redirectUri);
433
+ url.searchParams.set("scope", OAUTH_SCOPES.join(" "));
434
+ url.searchParams.set("state", params.state);
435
+ url.searchParams.set("code_challenge", params.codeChallenge);
436
+ url.searchParams.set("code_challenge_method", "S256");
437
+ return url.href;
438
+ }
439
+ async function postToken(body) {
440
+ const url = new URL("/oauth/token", getAppBaseUrl());
441
+ const response = await fetch(url, {
442
+ method: "POST",
443
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
444
+ body: new URLSearchParams(body).toString()
445
+ });
446
+ const data = await response.json().catch(() => null);
447
+ if (!response.ok || !data?.access_token) throw new OAuthTokenError(data?.error_description ?? data?.error ?? `HTTP ${response.status}`, data?.error);
448
+ if (typeof data.refresh_token !== "string" || data.refresh_token === "") throw new Error("Token endpoint response is missing a refresh token.");
449
+ if (typeof data.expires_in !== "number" || !Number.isFinite(data.expires_in)) throw new Error("Token endpoint response is missing a valid expiry.");
450
+ return data;
451
+ }
452
+ /** Exchange an authorization code for a token set (`grant_type=authorization_code`). */
453
+ async function exchangeAuthorizationCode(params) {
454
+ return toTokenSet(await postToken({
455
+ grant_type: "authorization_code",
456
+ code: params.code,
457
+ redirect_uri: params.redirectUri,
458
+ client_id: OAUTH_CLIENT_ID,
459
+ code_verifier: params.codeVerifier
460
+ }));
461
+ }
462
+ /** Rotate a refresh token for a new token set (`grant_type=refresh_token`). */
463
+ async function refreshTokenSet(refreshToken) {
464
+ return toTokenSet(await postToken({
465
+ grant_type: "refresh_token",
466
+ refresh_token: refreshToken,
467
+ client_id: OAUTH_CLIENT_ID
468
+ }));
469
+ }
470
+ /** Best-effort token revocation (RFC 7009); never throws. */
471
+ async function revokeToken(token) {
472
+ const url = new URL("/oauth/revoke", getAppBaseUrl());
473
+ await fetch(url, {
474
+ method: "POST",
475
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
476
+ body: new URLSearchParams({
477
+ token,
478
+ client_id: OAUTH_CLIENT_ID
479
+ }).toString()
480
+ }).catch(() => {});
481
+ }
482
+ //#endregion
307
483
  //#region src/auth.ts
308
484
  function getConfigPaths() {
309
485
  const configDir = resolve(homedir(), ".config", "argos-ci");
@@ -312,6 +488,16 @@ function getConfigPaths() {
312
488
  configPath: resolve(configDir, "config.json")
313
489
  };
314
490
  }
491
+ function parseOAuthTokenSet(value) {
492
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
493
+ const record = value;
494
+ if (typeof record.accessToken === "string" && typeof record.refreshToken === "string" && typeof record.expiresAt === "number") return {
495
+ accessToken: record.accessToken,
496
+ refreshToken: record.refreshToken,
497
+ expiresAt: record.expiresAt,
498
+ scope: typeof record.scope === "string" ? record.scope : ""
499
+ };
500
+ }
315
501
  function parseConfig(raw) {
316
502
  let parsed;
317
503
  try {
@@ -321,9 +507,12 @@ function parseConfig(raw) {
321
507
  }
322
508
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
323
509
  const record = parsed;
324
- if (!("token" in record) || record.token === void 0) return {};
325
- if (typeof record.token !== "string") return null;
326
- return { token: record.token };
510
+ if ("token" in record && record.token !== void 0 && typeof record.token !== "string") return null;
511
+ const config = {};
512
+ if (typeof record.token === "string") config.token = record.token;
513
+ const oauth = parseOAuthTokenSet(record.oauth);
514
+ if (oauth) config.oauth = oauth;
515
+ return config;
327
516
  }
328
517
  async function clearConfig() {
329
518
  const { configPath } = getConfigPaths();
@@ -353,16 +542,43 @@ async function writeConfig(config) {
353
542
  await writeFile(tmpPath, JSON.stringify(config, null, 2), { mode: 384 });
354
543
  await rename(tmpPath, configPath);
355
544
  }
356
- async function getStoredToken() {
357
- return (await readConfig())?.token;
545
+ /** Persist the OAuth token set from a successful login or refresh. */
546
+ async function saveOAuthTokens(tokens) {
547
+ await writeConfig({ oauth: tokens });
358
548
  }
359
- async function saveToken(token) {
360
- await writeConfig({
361
- ...await readConfig() ?? {},
362
- token
363
- });
549
+ /**
550
+ * Return a valid access token for API calls, or `undefined` when not logged in.
551
+ * Transparently refreshes (and persists) an expired OAuth access token, and
552
+ * falls back to a legacy personal access token when present.
553
+ */
554
+ async function getAccessToken() {
555
+ const config = await readConfig();
556
+ if (!config) return;
557
+ if (config.oauth) {
558
+ if (Date.now() < config.oauth.expiresAt) return config.oauth.accessToken;
559
+ try {
560
+ const tokens = await refreshTokenSet(config.oauth.refreshToken);
561
+ await saveOAuthTokens(tokens);
562
+ return tokens.accessToken;
563
+ } catch (err) {
564
+ if (config.token) return config.token;
565
+ if (err instanceof OAuthTokenError) console.warn("Warning: Your Argos session has expired. Run `argos login` again.");
566
+ else console.warn("Warning: Could not reach Argos to refresh your session. Check your connection and try again.");
567
+ return;
568
+ }
569
+ }
570
+ return config.token;
364
571
  }
365
- async function removeToken() {
572
+ /** Read the stored credentials without refreshing (used by `logout`). */
573
+ async function getStoredCredentials() {
574
+ const config = await readConfig();
575
+ return {
576
+ legacyToken: config?.token,
577
+ oauth: config?.oauth
578
+ };
579
+ }
580
+ /** Remove all stored credentials. */
581
+ async function clearStoredCredentials() {
366
582
  await writeConfig({});
367
583
  }
368
584
  //#endregion
@@ -421,7 +637,7 @@ function parseProjectPathOrFail(slug) {
421
637
  * `ARGOS_TOKEN`) over the one stored by `argos login`.
422
638
  */
423
639
  async function resolveToken(options) {
424
- const token = options.token || process.env["ARGOS_TOKEN"] || await getStoredToken();
640
+ const token = options.token || process.env["ARGOS_TOKEN"] || await getAccessToken();
425
641
  if (!token) fail("No Argos token found. Use --token, set ARGOS_TOKEN, or run `argos login`.");
426
642
  return token;
427
643
  }
@@ -466,6 +682,20 @@ async function resolveBuildTarget(reference, options, { auth }) {
466
682
  buildNumber
467
683
  };
468
684
  }
685
+ /**
686
+ * Resolve a project-scoped command target: an authenticated client and the
687
+ * `owner`/`project` pair every project endpoint needs. The project path comes
688
+ * from `--project owner/project` or the `ARGOS_PROJECT` environment variable.
689
+ */
690
+ async function resolveProjectTarget(options) {
691
+ const client = createApiClient(await resolveToken(options));
692
+ const projectPath = options.project || process.env["ARGOS_PROJECT"];
693
+ if (!projectPath) fail("--project <owner/project> is required. Pass it or set ARGOS_PROJECT.");
694
+ return {
695
+ client,
696
+ ...parseProjectPathOrFail(projectPath)
697
+ };
698
+ }
469
699
  //#endregion
470
700
  //#region src/lib/run.ts
471
701
  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.";
@@ -543,6 +773,7 @@ async function fetchAllDiffs(target, options) {
543
773
  query: {
544
774
  page: String(page),
545
775
  perPage: String(PER_PAGE),
776
+ metricsPeriod: options.metricsPeriod,
546
777
  ...options.needsReview ? { needsReview: "true" } : {}
547
778
  }
548
779
  } }));
@@ -552,7 +783,7 @@ async function fetchAllDiffs(target, options) {
552
783
  return results;
553
784
  }
554
785
  function registerBuildSnapshots(build) {
555
- 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(tokenOption).addOption(jsonOption).action(async (reference, options) => {
786
+ 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) => {
556
787
  try {
557
788
  const target = await resolveBuildTarget(reference, options, { auth: "project" });
558
789
  const build = await fetchBuild(target);
@@ -565,7 +796,10 @@ function registerBuildSnapshots(build) {
565
796
  console.log(message);
566
797
  return;
567
798
  }
568
- output(await fetchAllDiffs(target, { needsReview: Boolean(options.needsReview) }), options, (data) => formatSnapshots(data, build));
799
+ output(await fetchAllDiffs(target, {
800
+ needsReview: Boolean(options.needsReview),
801
+ metricsPeriod: toMetricsPeriod(options.metricsPeriod)
802
+ }), options, (data) => formatSnapshots(data, build));
569
803
  } catch (error) {
570
804
  handleCliError(error, "project");
571
805
  }
@@ -922,8 +1156,6 @@ function commentCommand(program) {
922
1156
  }
923
1157
  //#endregion
924
1158
  //#region src/commands/login.ts
925
- const APP_BASE_URL = process.env["ARGOS_APP_BASE_URL"] ?? "https://app.argos-ci.com/";
926
- const API_BASE_URL = process.env["ARGOS_API_BASE_URL"] ?? "https://api.argos-ci.com/v2/";
927
1159
  const LOGIN_CLI_SUCCESS_ROUTE = `/auth/cli/success`;
928
1160
  const LOGIN_TIMEOUT_MS = 300 * 1e3;
929
1161
  const CALLBACK_ERROR_HTML = `<!DOCTYPE html><html lang="en">
@@ -935,13 +1167,13 @@ const CALLBACK_ERROR_HTML = `<!DOCTYPE html><html lang="en">
935
1167
  <p>Authorization failed. Please run <code>argos login</code> again.</p>
936
1168
  </body>
937
1169
  </html>`;
938
- function color(text, code) {
939
- if (!process.stderr.isTTY || process.env["NO_COLOR"]) return text;
940
- return `\u001B[${code}m${text}\u001B[0m`;
1170
+ function color(text, code, isTTY) {
1171
+ if (!isTTY || process.env["NO_COLOR"]) return text;
1172
+ return `\x1b[${code}m${text}\x1b[0m`;
941
1173
  }
942
- const successColor = (text) => color(text, 32);
943
- const warningColor = (text) => color(text, 33);
944
- const errorColor = (text) => color(text, 31);
1174
+ const successColor = (text) => color(text, 32, process.stdout.isTTY);
1175
+ const warningColor = (text) => color(text, 33, process.stderr.isTTY);
1176
+ const errorColor = (text) => color(text, 31, process.stderr.isTTY);
945
1177
  function startCallbackServer() {
946
1178
  return new Promise((resolve, reject) => {
947
1179
  let resolveCallback = () => {};
@@ -957,7 +1189,7 @@ function startCallbackServer() {
957
1189
  server.closeAllConnections();
958
1190
  };
959
1191
  const server = createServer((req, res) => {
960
- const url = new URL(req.url ?? "/", "http://localhost");
1192
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
961
1193
  if (url.pathname !== "/callback") {
962
1194
  res.writeHead(404, { Connection: "close" });
963
1195
  res.end();
@@ -991,7 +1223,7 @@ function startCallbackServer() {
991
1223
  return;
992
1224
  }
993
1225
  res.writeHead(302, {
994
- Location: new URL(LOGIN_CLI_SUCCESS_ROUTE, APP_BASE_URL).href,
1226
+ Location: new URL(LOGIN_CLI_SUCCESS_ROUTE, getAppBaseUrl()).href,
995
1227
  Connection: "close"
996
1228
  });
997
1229
  res.end(() => {
@@ -1020,8 +1252,7 @@ function startCallbackServer() {
1020
1252
  function loginCommand(program) {
1021
1253
  program.command("login").description("Log in to Argos by opening your browser").action(async () => {
1022
1254
  const state = randomBytes(16).toString("hex");
1023
- const codeVerifier = randomBytes(32).toString("base64url");
1024
- const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
1255
+ const { codeVerifier, codeChallenge } = generatePkce();
1025
1256
  let port;
1026
1257
  let waitForCallback;
1027
1258
  try {
@@ -1031,13 +1262,15 @@ function loginCommand(program) {
1031
1262
  console.error(err);
1032
1263
  process.exit(1);
1033
1264
  }
1034
- const loginUrl = new URL("/auth/cli", APP_BASE_URL);
1035
- loginUrl.searchParams.set("port", port.toString());
1036
- loginUrl.searchParams.set("state", state);
1037
- loginUrl.searchParams.set("pkce", codeChallenge);
1265
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
1266
+ const authorizeUrl = buildAuthorizeUrl({
1267
+ redirectUri,
1268
+ state,
1269
+ codeChallenge
1270
+ });
1038
1271
  console.log("\nOpening browser for authentication…");
1039
- console.log(`If the browser doesn't open, visit:\n ${loginUrl.href}\n`);
1040
- if (process.env["ARGOS_CLI_DISABLE_BROWSER"] !== "1") await open(loginUrl.href).catch((err) => {
1272
+ console.log(`If the browser doesn't open, visit:\n ${authorizeUrl}\n`);
1273
+ if (process.env["ARGOS_CLI_DISABLE_BROWSER"] !== "1") await open(authorizeUrl).catch((err) => {
1041
1274
  console.warn(warningColor(`Warning: Failed to open browser — ${err instanceof Error ? err.message : String(err)}`));
1042
1275
  console.log("Hint: Open the URL above manually to continue authentication.");
1043
1276
  });
@@ -1052,15 +1285,16 @@ function loginCommand(program) {
1052
1285
  console.error(errorColor("Error: State mismatch. Try logging in again."));
1053
1286
  process.exit(1);
1054
1287
  }
1055
- const { data, error } = await createClient({ baseUrl: API_BASE_URL }).POST("/auth/cli/token", { body: {
1056
- code: result.code,
1057
- code_verifier: codeVerifier
1058
- } });
1059
- if (error || !data?.token) {
1060
- console.error(errorColor("Error: Authentication failed. Please run `argos login` again."));
1288
+ try {
1289
+ await saveOAuthTokens(await exchangeAuthorizationCode({
1290
+ code: result.code,
1291
+ codeVerifier,
1292
+ redirectUri
1293
+ }));
1294
+ } catch (err) {
1295
+ console.error(errorColor(`Error: Authentication failed${err instanceof Error ? ` — ${err.message}` : ""}. Please run \`argos login\` again.`));
1061
1296
  process.exit(1);
1062
1297
  }
1063
- await saveToken(data.token);
1064
1298
  console.log(successColor("Logged in to Argos successfully."));
1065
1299
  });
1066
1300
  }
@@ -1068,11 +1302,13 @@ function loginCommand(program) {
1068
1302
  //#region src/commands/logout.ts
1069
1303
  function logoutCommand(program) {
1070
1304
  program.command("logout").description("Log out from Argos").action(async () => {
1071
- if (!await getStoredToken()) {
1305
+ const { legacyToken, oauth } = await getStoredCredentials();
1306
+ if (!legacyToken && !oauth) {
1072
1307
  console.log("No token found. You are already logged out.");
1073
1308
  return;
1074
1309
  }
1075
- await removeToken();
1310
+ if (oauth) await revokeToken(oauth.refreshToken);
1311
+ await clearStoredCredentials();
1076
1312
  console.log("Logged out from Argos.");
1077
1313
  });
1078
1314
  }
@@ -1125,6 +1361,112 @@ function createProjectCommand(program) {
1125
1361
  });
1126
1362
  }
1127
1363
  //#endregion
1364
+ //#region src/commands/analytics.ts
1365
+ const DEFAULT_PERIOD_DAYS = 30;
1366
+ const DAY_MS = 1440 * 60 * 1e3;
1367
+ /** Coerce a user-supplied date into an ISO 8601 datetime, or fail cleanly. */
1368
+ function toIsoOrFail(value, option) {
1369
+ const date = new Date(value);
1370
+ if (Number.isNaN(date.getTime())) fail(`Invalid --${option} value: "${value}". Use an ISO 8601 datetime.`);
1371
+ return date.toISOString();
1372
+ }
1373
+ /** Collect a repeatable `--project` flag into an array of project names. */
1374
+ function collectProject(value, previous = []) {
1375
+ return [...previous, value];
1376
+ }
1377
+ function analyticsCommand(program) {
1378
+ program.command("analytics").description("Fetch build and screenshot analytics for an account").option("--account <slug>", "Slug of the account (personal or team) to fetch analytics for").option("--from <datetime>", `Start of the analytics period (ISO 8601). Defaults to ${DEFAULT_PERIOD_DAYS} days ago.`).option("--to <datetime>", "End of the analytics period (ISO 8601). Defaults to now.").addOption(new Option("--group-by <period>", "Time period used to group each series data point").choices([
1379
+ "day",
1380
+ "week",
1381
+ "month"
1382
+ ]).default("day")).option("--project <name>", "Filter by project name. Repeat the flag to include multiple projects.", collectProject).addOption(tokenOption).addOption(jsonOption).action(async (options) => {
1383
+ try {
1384
+ const accountSlug = options.account || process.env["ARGOS_ACCOUNT"];
1385
+ if (!accountSlug) fail("An account is required. Use --account <slug> or set ARGOS_ACCOUNT.");
1386
+ const from = options.from ? toIsoOrFail(options.from, "from") : (/* @__PURE__ */ new Date(Date.now() - DEFAULT_PERIOD_DAYS * DAY_MS)).toISOString();
1387
+ const to = options.to ? toIsoOrFail(options.to, "to") : void 0;
1388
+ output(unwrap(await createApiClient(await resolveToken({ token: options.token })).GET("/accounts/{accountSlug}/analytics", { params: {
1389
+ path: { accountSlug },
1390
+ query: {
1391
+ from,
1392
+ to,
1393
+ groupBy: options.groupBy,
1394
+ projectNames: options.project
1395
+ }
1396
+ } })), options, (data) => formatAnalytics(data, {
1397
+ account: accountSlug,
1398
+ from,
1399
+ to,
1400
+ groupBy: options.groupBy
1401
+ }));
1402
+ } catch (error) {
1403
+ handleCliError(error, "user");
1404
+ }
1405
+ });
1406
+ }
1407
+ //#endregion
1408
+ //#region src/commands/change/_action.ts
1409
+ /**
1410
+ * Register a `change <name> <changeId>` command that runs `perform` and prints
1411
+ * the updated change. Both change actions (ignore, unignore) share the same
1412
+ * shape and differ only by the endpoint they hit. They act as a user, so they
1413
+ * need a personal access token, and the project comes from `--project` or
1414
+ * `ARGOS_PROJECT` since a change id does not carry the account slug.
1415
+ */
1416
+ function defineChangeAction(opts) {
1417
+ return (change) => {
1418
+ change.command(opts.name).description(opts.description).argument("<changeId>", "Change ID, taken from a diff's `change.id` (see `argos build snapshots`)").addOption(tokenOption).addOption(changeProjectPathOption).addOption(metricsPeriodOption).addOption(jsonOption).action(async (changeId, options) => {
1419
+ try {
1420
+ const { client, owner, project } = await resolveProjectTarget(options);
1421
+ output(await opts.perform({
1422
+ client,
1423
+ owner,
1424
+ project,
1425
+ changeId,
1426
+ metricsPeriod: toMetricsPeriod(options.metricsPeriod)
1427
+ }), options, formatChange);
1428
+ } catch (error) {
1429
+ handleCliError(error, "user");
1430
+ }
1431
+ });
1432
+ };
1433
+ }
1434
+ //#endregion
1435
+ //#region src/commands/change/ignore.ts
1436
+ const registerChangeIgnore = defineChangeAction({
1437
+ name: "ignore",
1438
+ description: "Ignore a flaky test change so its diffs stop requiring review and are auto-approved on future builds",
1439
+ perform: async ({ client, owner, project, changeId, metricsPeriod }) => unwrap(await client.POST("/projects/{owner}/{project}/changes/{changeId}/ignore", { params: {
1440
+ path: {
1441
+ owner,
1442
+ project,
1443
+ changeId
1444
+ },
1445
+ query: { metricsPeriod }
1446
+ } }))
1447
+ });
1448
+ //#endregion
1449
+ //#region src/commands/change/unignore.ts
1450
+ const registerChangeUnignore = defineChangeAction({
1451
+ name: "unignore",
1452
+ description: "Stop ignoring a test change so its diffs require review again on future builds",
1453
+ perform: async ({ client, owner, project, changeId, metricsPeriod }) => unwrap(await client.POST("/projects/{owner}/{project}/changes/{changeId}/unignore", { params: {
1454
+ path: {
1455
+ owner,
1456
+ project,
1457
+ changeId
1458
+ },
1459
+ query: { metricsPeriod }
1460
+ } }))
1461
+ });
1462
+ //#endregion
1463
+ //#region src/commands/change/index.ts
1464
+ function changeCommand(program) {
1465
+ const change = program.command("change").description("Ignore or unignore flaky test changes");
1466
+ registerChangeIgnore(change);
1467
+ registerChangeUnignore(change);
1468
+ }
1469
+ //#endregion
1128
1470
  //#region src/index.ts
1129
1471
  const rawPkg = await readFile(resolve(fileURLToPath(new URL(".", import.meta.url)), "..", "package.json"), "utf8");
1130
1472
  const pkg = JSON.parse(rawPkg);
@@ -1140,6 +1482,8 @@ logoutCommand(program);
1140
1482
  deployCommand(program);
1141
1483
  whoamiCommand(program);
1142
1484
  createProjectCommand(program);
1485
+ analyticsCommand(program);
1486
+ changeCommand(program);
1143
1487
  if (!process.argv.slice(2).length) program.outputHelp();
1144
1488
  else program.parse(process.argv);
1145
1489
  //#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.2.0",
4
+ "version": "6.4.0",
5
5
  "bin": {
6
6
  "argos": "./bin/argos-cli.js"
7
7
  },
@@ -34,8 +34,8 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "@argos-ci/api-client": "0.25.0",
38
- "@argos-ci/core": "6.6.0",
37
+ "@argos-ci/api-client": "0.26.0",
38
+ "@argos-ci/core": "6.6.1",
39
39
  "commander": "^15.0.0",
40
40
  "open": "^11.0.0",
41
41
  "ora": "^9.4.0",
@@ -54,5 +54,5 @@
54
54
  "check-format": "prettier --check --ignore-unknown --ignore-path=../../.gitignore --ignore-path=../../.prettierignore .",
55
55
  "lint": "eslint ."
56
56
  },
57
- "gitHead": "686b6fa8385ed77598ec86f66b073e9897cef176"
57
+ "gitHead": "2fda63bc0d4ac0f1a2ef6a181361e8b0c4de8349"
58
58
  }