react-doctor 0.2.15 → 0.2.16-dev.114893e

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.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="32a62a68-f2f8-5b33-8780-72a601ba4ed1")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="005f503a-c838-5177-8bea-002799f23989")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as Path from "node:path";
@@ -41,11 +41,11 @@ import * as Exit from "effect/Exit";
41
41
  import { stripVTControlCharacters } from "node:util";
42
42
  import tty from "node:tty";
43
43
  import { codeFrameColumns } from "@babel/code-frame";
44
+ import Conf from "conf";
44
45
  import { createHash, randomUUID } from "node:crypto";
45
46
  import basePrompts from "prompts";
46
47
  import { SKILL_MANIFEST_FILE, detectInstalledSkillAgents, getSkillAgentConfig, getSkillAgentTypes, installSkillsFromSource } from "agent-install";
47
48
  import { fileURLToPath } from "node:url";
48
- import Conf from "conf";
49
49
  import { generateCode, loadFile, writeFile } from "magicast";
50
50
  import { getConfigFromVariableDeclaration, getDefaultExportOptions } from "magicast/helpers";
51
51
  //#region \0rolldown/runtime.js
@@ -7338,27 +7338,30 @@ var OxlintSpawnTimeoutMs = class extends Context.Reference("react-doctor/OxlintS
7338
7338
  var OxlintOutputMaxBytes = class extends Context.Reference("react-doctor/OxlintOutputMaxBytes", { defaultValue: () => OXLINT_OUTPUT_MAX_BYTES }) {};
7339
7339
  /**
7340
7340
  * Number of oxlint subprocesses the lint pass runs in parallel. Defaults
7341
- * to `1` (serial — the historical behavior) so resource usage is opt-in.
7342
- * The CLI's `--experimental-parallel` flag overrides this via `Layer.succeed`; the
7343
- * `REACT_DOCTOR_PARALLEL` env var seeds the default for programmatic /
7344
- * CI callers that never touch the flag:
7341
+ * to auto-detected CPU cores (parallel) so large repos scan fast out of
7342
+ * the box; `spawnLintBatches` transparently falls back to a single worker
7343
+ * if a parallel run exhausts system resources. The CLI's `--no-parallel`
7344
+ * flag forces serial via `Layer.succeed`; the `REACT_DOCTOR_PARALLEL` env
7345
+ * var seeds the default for programmatic / CI callers that never touch the
7346
+ * flag — parallelism is opt-OUT, so only the explicit serial values pin
7347
+ * one worker:
7345
7348
  *
7346
- * - unset / `0` / `false` / `off` → `1` (serial)
7347
- * - `auto` / `true` / `on` → available CPU cores (clamped)
7348
- * - a positive integer → that many workers (clamped)
7349
+ * - unset / `auto` / `true` / `on` → available CPU cores (clamped)
7350
+ * - `0` / `false` / `off` → `1` (serial)
7351
+ * - a positive integer → that many workers (clamped)
7352
+ * - any other value → available CPU cores (clamped)
7349
7353
  *
7350
7354
  * The resolved value is always within
7351
7355
  * `[MIN_SCAN_CONCURRENCY, MAX_SCAN_CONCURRENCY]`.
7352
7356
  */
7353
7357
  var OxlintConcurrency = class extends Context.Reference("react-doctor/OxlintConcurrency", { defaultValue: () => {
7354
7358
  const raw = process.env["REACT_DOCTOR_PARALLEL"];
7355
- if (raw === void 0) return 1;
7359
+ if (raw === void 0) return resolveScanConcurrency("auto");
7356
7360
  const normalized = raw.trim().toLowerCase();
7357
- if (normalized === "" || normalized === "0" || normalized === "false" || normalized === "off") return 1;
7358
- if (normalized === "auto" || normalized === "true" || normalized === "on") return resolveScanConcurrency("auto");
7361
+ if (normalized === "0" || normalized === "false" || normalized === "off") return 1;
7359
7362
  const parsed = Number.parseInt(normalized, 10);
7360
- if (!Number.isInteger(parsed) || parsed <= 0) return 1;
7361
- return resolveScanConcurrency(parsed);
7363
+ if (Number.isInteger(parsed) && parsed > 0) return resolveScanConcurrency(parsed);
7364
+ return resolveScanConcurrency("auto");
7362
7365
  } }) {};
7363
7366
  const DIAGNOSTIC_SURFACES = [
7364
7367
  "cli",
@@ -8359,6 +8362,100 @@ const checkReducedMotion = (rootDirectory) => {
8359
8362
  if (result.status === 0) return [];
8360
8363
  return [MISSING_REDUCED_MOTION_DIAGNOSTIC];
8361
8364
  };
8365
+ var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
8366
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
8367
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
8368
+ let formatter = (open, close, replace = open) => (input) => {
8369
+ let string = "" + input, index = string.indexOf(close, open.length);
8370
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
8371
+ };
8372
+ let replaceClose = (string, close, replace, index) => {
8373
+ let result = "", cursor = 0;
8374
+ do {
8375
+ result += string.substring(cursor, index) + replace;
8376
+ cursor = index + close.length;
8377
+ index = string.indexOf(close, cursor);
8378
+ } while (~index);
8379
+ return result + string.substring(cursor);
8380
+ };
8381
+ let createColors = (enabled = isColorSupported) => {
8382
+ let f = enabled ? formatter : () => String;
8383
+ return {
8384
+ isColorSupported: enabled,
8385
+ reset: f("\x1B[0m", "\x1B[0m"),
8386
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
8387
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
8388
+ italic: f("\x1B[3m", "\x1B[23m"),
8389
+ underline: f("\x1B[4m", "\x1B[24m"),
8390
+ inverse: f("\x1B[7m", "\x1B[27m"),
8391
+ hidden: f("\x1B[8m", "\x1B[28m"),
8392
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
8393
+ black: f("\x1B[30m", "\x1B[39m"),
8394
+ red: f("\x1B[31m", "\x1B[39m"),
8395
+ green: f("\x1B[32m", "\x1B[39m"),
8396
+ yellow: f("\x1B[33m", "\x1B[39m"),
8397
+ blue: f("\x1B[34m", "\x1B[39m"),
8398
+ magenta: f("\x1B[35m", "\x1B[39m"),
8399
+ cyan: f("\x1B[36m", "\x1B[39m"),
8400
+ white: f("\x1B[37m", "\x1B[39m"),
8401
+ gray: f("\x1B[90m", "\x1B[39m"),
8402
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
8403
+ bgRed: f("\x1B[41m", "\x1B[49m"),
8404
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
8405
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
8406
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
8407
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
8408
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
8409
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
8410
+ blackBright: f("\x1B[90m", "\x1B[39m"),
8411
+ redBright: f("\x1B[91m", "\x1B[39m"),
8412
+ greenBright: f("\x1B[92m", "\x1B[39m"),
8413
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
8414
+ blueBright: f("\x1B[94m", "\x1B[39m"),
8415
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
8416
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
8417
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
8418
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
8419
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
8420
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
8421
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
8422
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
8423
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
8424
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
8425
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
8426
+ };
8427
+ };
8428
+ module.exports = createColors();
8429
+ module.exports.createColors = createColors;
8430
+ })))(), 1);
8431
+ const highlighter = {
8432
+ error: import_picocolors.default.red,
8433
+ warn: import_picocolors.default.yellow,
8434
+ info: import_picocolors.default.cyan,
8435
+ success: import_picocolors.default.green,
8436
+ dim: import_picocolors.default.dim,
8437
+ gray: import_picocolors.default.gray,
8438
+ bold: import_picocolors.default.bold
8439
+ };
8440
+ /**
8441
+ * Override picocolors' automatic color detection. picocolors decides
8442
+ * once, at import time, from `NO_COLOR` / `FORCE_COLOR` / `TERM` / TTY.
8443
+ * This lets the CLI honor an explicit `--color` / `--no-color` flag
8444
+ * (clig.dev, Output: "Disable color … if the user requested it") by
8445
+ * swapping in a fresh set of formatters. Call it before any colored
8446
+ * output is produced. Every call site reads `highlighter.<method>` at
8447
+ * call time, so reassigning the properties propagates everywhere.
8448
+ */
8449
+ const setColorEnabled = (enabled) => {
8450
+ const colors = import_picocolors.default.createColors(enabled);
8451
+ highlighter.error = colors.red;
8452
+ highlighter.warn = colors.yellow;
8453
+ highlighter.info = colors.cyan;
8454
+ highlighter.success = colors.green;
8455
+ highlighter.dim = colors.dim;
8456
+ highlighter.gray = colors.gray;
8457
+ highlighter.bold = colors.bold;
8458
+ };
8362
8459
  const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
8363
8460
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
8364
8461
  const FALSY_VALUES = new Set([
@@ -8975,6 +9072,11 @@ const trimOrNull = (value) => {
8975
9072
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
8976
9073
  */
8977
9074
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
9075
+ /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
9076
+ const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
9077
+ /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
9078
+ const DIFF_RANGE_OPERATOR = "..";
9079
+ const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
8978
9080
  const isSafeGitRevision = (candidate) => {
8979
9081
  if (candidate.length === 0) return false;
8980
9082
  if (candidate.startsWith("-")) return false;
@@ -8982,6 +9084,31 @@ const isSafeGitRevision = (candidate) => {
8982
9084
  if (candidate.includes("..") || candidate.includes("@{")) return false;
8983
9085
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
8984
9086
  };
9087
+ /**
9088
+ * Splits a git revision range into its endpoints: three-dot `A...B`
9089
+ * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
9090
+ * when `value` carries no range operator so the caller falls back to
9091
+ * single-base resolution.
9092
+ *
9093
+ * Only the first operator is split on; any leftover `..` stays inside an
9094
+ * endpoint so `isSafeGitRevision` rejects malformed input like
9095
+ * `A..B..C` instead of silently guessing which pair the user meant.
9096
+ */
9097
+ const parseGitDiffRange = (value) => {
9098
+ const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
9099
+ if (symmetricIndex !== -1) return {
9100
+ base: value.slice(0, symmetricIndex),
9101
+ head: value.slice(symmetricIndex + 3),
9102
+ symmetric: true
9103
+ };
9104
+ const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
9105
+ if (rangeIndex !== -1) return {
9106
+ base: value.slice(0, rangeIndex),
9107
+ head: value.slice(rangeIndex + 2),
9108
+ symmetric: false
9109
+ };
9110
+ return null;
9111
+ };
8985
9112
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
8986
9113
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
8987
9114
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -9133,6 +9260,49 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9133
9260
  if (result.status !== 0) return null;
9134
9261
  return parseGithubViewerPermission(result.stdout);
9135
9262
  }).pipe(Effect.catch(() => Effect.succeed(null)));
9263
+ /**
9264
+ * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
9265
+ * selection. Each endpoint is validated with `isSafeGitRevision`
9266
+ * BEFORE it reaches `git` (so the range syntax can't smuggle a
9267
+ * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
9268
+ * verified to exist, then the diff runs between the two commits with
9269
+ * the same `--diff-filter=ACMR` shape the single-base path uses.
9270
+ */
9271
+ const resolveDiffRange = (input) => Effect.gen(function* () {
9272
+ if (input.range.base.length === 0 && input.range.head.length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" must name at least one commit (e.g. "main..feature").` }) }));
9273
+ const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
9274
+ const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
9275
+ for (const endpoint of [baseRef, headRef]) if (!isSafeGitRevision(endpoint)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" has an invalid endpoint "${endpoint}" (${GIT_REF_NAME_RULE}).` }) }));
9276
+ for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
9277
+ let diffBaseRef = baseRef;
9278
+ if (input.range.symmetric) {
9279
+ const mergeBase = yield* runGit(input.directory, [
9280
+ "merge-base",
9281
+ baseRef,
9282
+ headRef
9283
+ ]);
9284
+ if (mergeBase.status !== 0) return null;
9285
+ const mergeBaseRef = trimOrNull(mergeBase.stdout);
9286
+ if (mergeBaseRef === null) return null;
9287
+ diffBaseRef = mergeBaseRef;
9288
+ }
9289
+ const diff = yield* runGit(input.directory, [
9290
+ "diff",
9291
+ "-z",
9292
+ "--name-only",
9293
+ "--diff-filter=ACMR",
9294
+ "--relative",
9295
+ diffBaseRef,
9296
+ headRef
9297
+ ]);
9298
+ if (diff.status !== 0) return null;
9299
+ return {
9300
+ currentBranch: yield* currentBranch(input.directory),
9301
+ baseBranch: baseRef,
9302
+ changedFiles: splitNullSeparated(diff.stdout),
9303
+ isCurrentChanges: false
9304
+ };
9305
+ });
9136
9306
  return Git.of({
9137
9307
  currentBranch,
9138
9308
  defaultBranch,
@@ -9142,7 +9312,15 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9142
9312
  branchExists,
9143
9313
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
9144
9314
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
9145
- if (explicitBaseBranch !== void 0 && !isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (must match [A-Za-z0-9_./-] without leading '-', '..', or '@{').` }) }));
9315
+ if (explicitBaseBranch !== void 0) {
9316
+ const range = parseGitDiffRange(explicitBaseBranch);
9317
+ if (range !== null) return yield* resolveDiffRange({
9318
+ directory,
9319
+ range,
9320
+ raw: explicitBaseBranch
9321
+ });
9322
+ if (!isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (${GIT_REF_NAME_RULE}).` }) }));
9323
+ }
9146
9324
  const resolvedCurrentBranch = yield* currentBranch(directory);
9147
9325
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
9148
9326
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -10451,6 +10629,21 @@ const spawnOxlint = (args, rootDirectory, nodeBinaryPath, spawnTimeoutMs = OXLIN
10451
10629
  resolve(output);
10452
10630
  });
10453
10631
  });
10632
+ const PARALLELISM_EXHAUSTION_ERROR_CODES = new Set([
10633
+ "EAGAIN",
10634
+ "EMFILE",
10635
+ "ENFILE",
10636
+ "ENOMEM"
10637
+ ]);
10638
+ const isParallelismRelatedSpawnError = (error) => {
10639
+ if (!(error instanceof ReactDoctorError)) return false;
10640
+ const { reason } = error;
10641
+ if (reason._tag !== "OxlintSpawnFailed") return false;
10642
+ const { cause } = reason;
10643
+ if (typeof cause !== "object" || cause === null || !("code" in cause)) return false;
10644
+ const { code } = cause;
10645
+ return typeof code === "string" && PARALLELISM_EXHAUSTION_ERROR_CODES.has(code);
10646
+ };
10454
10647
  /**
10455
10648
  * Runs every prebuilt file batch through oxlint, with binary-split
10456
10649
  * retry on the splittable error classes (timeout / output-too-large /
@@ -10459,66 +10652,83 @@ const spawnOxlint = (args, rootDirectory, nodeBinaryPath, spawnTimeoutMs = OXLIN
10459
10652
  * (surfaced via `onPartialFailure`) so JSON-mode consumers see WHICH
10460
10653
  * files were skipped instead of silently losing them.
10461
10654
  *
10462
- * Errors that aren't splittable (oxlint config crash, JS plugin
10463
- * resolution failure, etc.) propagate to the caller — the
10464
- * `runOxlint` retry-without-extends fallback re-spawns this loop
10465
- * with a slimmer config in that case.
10655
+ * Parallel runs (concurrency > 1) get one extra safety net: if the pass
10656
+ * fails with a resource-exhaustion error that's exclusive to running
10657
+ * many oxlint subprocesses at once (EAGAIN / EMFILE / ENFILE / ENOMEM —
10658
+ * see `isParallelismRelatedSpawnError`), the whole pass replays once
10659
+ * with a single worker. That's the only failure a serial replay can
10660
+ * clear, so every other error class is left to propagate.
10661
+ *
10662
+ * Errors that aren't splittable and aren't parallelism-related (oxlint
10663
+ * config crash, JS plugin resolution failure, etc.) propagate to the
10664
+ * caller — the `runOxlint` retry-without-extends fallback re-spawns this
10665
+ * loop with a slimmer config in that case.
10466
10666
  */
10467
10667
  const spawnLintBatches = async (input) => {
10468
10668
  const { baseArgs, fileBatches, rootDirectory, nodeBinaryPath, project, onPartialFailure, onFileProgress, spawnTimeoutMs, outputMaxBytes } = input;
10469
- const concurrency = resolveScanConcurrency(input.concurrency ?? 1);
10669
+ const requestedConcurrency = resolveScanConcurrency(input.concurrency ?? 1);
10470
10670
  const totalFileCount = fileBatches.reduce((sum, batch) => sum + batch.length, 0);
10471
- const allDiagnostics = [];
10472
- const droppedFiles = [];
10473
- let firstDropReason = null;
10474
- const spawnLintBatch = async (batch) => {
10475
- const batchArgs = [...baseArgs, ...batch];
10476
- try {
10477
- return parseOxlintOutput(await spawnOxlint(batchArgs, rootDirectory, nodeBinaryPath, spawnTimeoutMs, outputMaxBytes), project, rootDirectory);
10478
- } catch (error) {
10479
- if (!isSplittableReactDoctorError(error)) throw error;
10480
- if (batch.length <= 1) {
10481
- droppedFiles.push(...batch);
10482
- if (firstDropReason === null) firstDropReason = error.message;
10483
- return [];
10671
+ const runBatchPass = async (concurrency) => {
10672
+ const allDiagnostics = [];
10673
+ const droppedFiles = [];
10674
+ let firstDropReason = null;
10675
+ const spawnLintBatch = async (batch) => {
10676
+ const batchArgs = [...baseArgs, ...batch];
10677
+ try {
10678
+ return parseOxlintOutput(await spawnOxlint(batchArgs, rootDirectory, nodeBinaryPath, spawnTimeoutMs, outputMaxBytes), project, rootDirectory);
10679
+ } catch (error) {
10680
+ if (!isSplittableReactDoctorError(error)) throw error;
10681
+ if (batch.length <= 1) {
10682
+ droppedFiles.push(...batch);
10683
+ if (firstDropReason === null) firstDropReason = error.message;
10684
+ return [];
10685
+ }
10686
+ const splitIndex = Math.ceil(batch.length / 2);
10687
+ return [...await spawnLintBatch(batch.slice(0, splitIndex)), ...await spawnLintBatch(batch.slice(splitIndex))];
10688
+ }
10689
+ };
10690
+ let startedFileCount = 0;
10691
+ let scannedFileCount = 0;
10692
+ let displayedFileCount = 0;
10693
+ const progressTimer = onFileProgress && totalFileCount > 1 ? setInterval(() => {
10694
+ const ceiling = Math.min(startedFileCount, totalFileCount - 1);
10695
+ if (displayedFileCount < ceiling) {
10696
+ displayedFileCount += 1;
10697
+ onFileProgress(displayedFileCount, totalFileCount);
10484
10698
  }
10485
- const splitIndex = Math.ceil(batch.length / 2);
10486
- return [...await spawnLintBatch(batch.slice(0, splitIndex)), ...await spawnLintBatch(batch.slice(splitIndex))];
10699
+ }, 50) : null;
10700
+ progressTimer?.unref?.();
10701
+ try {
10702
+ const batchResults = await mapWithConcurrency(fileBatches, concurrency, async (batch) => {
10703
+ startedFileCount += batch.length;
10704
+ const batchDiagnostics = await spawnLintBatch(batch);
10705
+ scannedFileCount += batch.length;
10706
+ if (onFileProgress) {
10707
+ displayedFileCount = Math.min(Math.max(displayedFileCount, scannedFileCount), totalFileCount);
10708
+ onFileProgress(displayedFileCount, totalFileCount);
10709
+ }
10710
+ return batchDiagnostics;
10711
+ });
10712
+ for (const batchDiagnostics of batchResults) allDiagnostics.push(...batchDiagnostics);
10713
+ } finally {
10714
+ if (progressTimer !== null) clearInterval(progressTimer);
10715
+ }
10716
+ if (droppedFiles.length > 0 && onPartialFailure) {
10717
+ const previewFiles = droppedFiles.slice(0, 3).join(", ");
10718
+ const remainderHint = droppedFiles.length > 3 ? `, +${droppedFiles.length - 3} more` : "";
10719
+ const reasonHint = firstDropReason ? ` — first failure: ${firstDropReason}` : "";
10720
+ onPartialFailure(`${droppedFiles.length} file(s) failed to lint and were skipped (${previewFiles}${remainderHint})${reasonHint}`);
10487
10721
  }
10722
+ return allDiagnostics;
10488
10723
  };
10489
- let startedFileCount = 0;
10490
- let scannedFileCount = 0;
10491
- let displayedFileCount = 0;
10492
- const progressTimer = onFileProgress && totalFileCount > 1 ? setInterval(() => {
10493
- const ceiling = Math.min(startedFileCount, totalFileCount - 1);
10494
- if (displayedFileCount < ceiling) {
10495
- displayedFileCount += 1;
10496
- onFileProgress(displayedFileCount, totalFileCount);
10497
- }
10498
- }, 50) : null;
10499
- progressTimer?.unref?.();
10724
+ let diagnostics;
10500
10725
  try {
10501
- const batchResults = await mapWithConcurrency(fileBatches, concurrency, async (batch) => {
10502
- startedFileCount += batch.length;
10503
- const batchDiagnostics = await spawnLintBatch(batch);
10504
- scannedFileCount += batch.length;
10505
- if (onFileProgress) {
10506
- displayedFileCount = Math.min(Math.max(displayedFileCount, scannedFileCount), totalFileCount);
10507
- onFileProgress(displayedFileCount, totalFileCount);
10508
- }
10509
- return batchDiagnostics;
10510
- });
10511
- for (const batchDiagnostics of batchResults) allDiagnostics.push(...batchDiagnostics);
10512
- } finally {
10513
- if (progressTimer !== null) clearInterval(progressTimer);
10514
- }
10515
- if (droppedFiles.length > 0 && onPartialFailure) {
10516
- const previewFiles = droppedFiles.slice(0, 3).join(", ");
10517
- const remainderHint = droppedFiles.length > 3 ? `, +${droppedFiles.length - 3} more` : "";
10518
- const reasonHint = firstDropReason ? ` — first failure: ${firstDropReason}` : "";
10519
- onPartialFailure(`${droppedFiles.length} file(s) failed to lint and were skipped (${previewFiles}${remainderHint})${reasonHint}`);
10726
+ diagnostics = await runBatchPass(requestedConcurrency);
10727
+ } catch (error) {
10728
+ if (requestedConcurrency <= 1 || !isParallelismRelatedSpawnError(error)) throw error;
10729
+ diagnostics = await runBatchPass(1);
10520
10730
  }
10521
- return dedupeDiagnostics(allDiagnostics);
10731
+ return dedupeDiagnostics(diagnostics);
10522
10732
  };
10523
10733
  let didValidate = false;
10524
10734
  /**
@@ -11077,7 +11287,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
11077
11287
  reason: null
11078
11288
  });
11079
11289
  const scanConcurrency = yield* OxlintConcurrency;
11080
- const workerCountSuffix = scanConcurrency > 1 ? ` · ${scanConcurrency} workers` : "";
11290
+ const workerCountSuffix = scanConcurrency > 1 ? ` ${highlighter.dim(`[~${scanConcurrency} workers]`)}` : "";
11081
11291
  const scanProgress = yield* progressService.start("Scanning...");
11082
11292
  const scanStartTime = Date.now();
11083
11293
  let lastReportedTotalFileCount = 0;
@@ -11524,12 +11734,13 @@ const buildSkippedChecks = (input) => {
11524
11734
  * Git service runs through Effect's `ChildProcess` (true subprocess
11525
11735
  * spawn, not `spawnSync`).
11526
11736
  *
11527
- * Tagged-reason errors are dispatched via `Effect.catchReasons`
11528
- * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
11529
- * union without manual `instanceof` checks). The recovered branches
11530
- * raise plain `Error`s so existing thrown-class consumers continue
11531
- * to work — anything else (real `GitInvocationFailed`, etc.)
11532
- * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
11737
+ * Failures propagate as the tagged `ReactDoctorError` (rejected by
11738
+ * `Effect.runPromise`) rather than being flattened into a plain
11739
+ * `Error`. The message is unchanged — `ReactDoctorError.message`
11740
+ * defers to `reason.message` — so message-matching callers keep
11741
+ * working, while the CLI can now dispatch on `error.reason._tag` to
11742
+ * render diff-base mistakes (`GitBaseBranchInvalid` /
11743
+ * `GitBaseBranchMissing`) as clean user errors instead of crashes.
11533
11744
  */
11534
11745
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
11535
11746
  const selection = yield* (yield* Git).diffSelection({
@@ -11543,105 +11754,8 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
11543
11754
  changedFiles: [...selection.changedFiles],
11544
11755
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
11545
11756
  };
11546
- }).pipe(Effect.provide(Git.layerNode), Effect.catchReasons("ReactDoctorError", {
11547
- GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
11548
- GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
11549
- })));
11757
+ }).pipe(Effect.provide(Git.layerNode)));
11550
11758
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
11551
- var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
11552
- let p = process || {}, argv = p.argv || [], env = p.env || {};
11553
- let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
11554
- let formatter = (open, close, replace = open) => (input) => {
11555
- let string = "" + input, index = string.indexOf(close, open.length);
11556
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
11557
- };
11558
- let replaceClose = (string, close, replace, index) => {
11559
- let result = "", cursor = 0;
11560
- do {
11561
- result += string.substring(cursor, index) + replace;
11562
- cursor = index + close.length;
11563
- index = string.indexOf(close, cursor);
11564
- } while (~index);
11565
- return result + string.substring(cursor);
11566
- };
11567
- let createColors = (enabled = isColorSupported) => {
11568
- let f = enabled ? formatter : () => String;
11569
- return {
11570
- isColorSupported: enabled,
11571
- reset: f("\x1B[0m", "\x1B[0m"),
11572
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
11573
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
11574
- italic: f("\x1B[3m", "\x1B[23m"),
11575
- underline: f("\x1B[4m", "\x1B[24m"),
11576
- inverse: f("\x1B[7m", "\x1B[27m"),
11577
- hidden: f("\x1B[8m", "\x1B[28m"),
11578
- strikethrough: f("\x1B[9m", "\x1B[29m"),
11579
- black: f("\x1B[30m", "\x1B[39m"),
11580
- red: f("\x1B[31m", "\x1B[39m"),
11581
- green: f("\x1B[32m", "\x1B[39m"),
11582
- yellow: f("\x1B[33m", "\x1B[39m"),
11583
- blue: f("\x1B[34m", "\x1B[39m"),
11584
- magenta: f("\x1B[35m", "\x1B[39m"),
11585
- cyan: f("\x1B[36m", "\x1B[39m"),
11586
- white: f("\x1B[37m", "\x1B[39m"),
11587
- gray: f("\x1B[90m", "\x1B[39m"),
11588
- bgBlack: f("\x1B[40m", "\x1B[49m"),
11589
- bgRed: f("\x1B[41m", "\x1B[49m"),
11590
- bgGreen: f("\x1B[42m", "\x1B[49m"),
11591
- bgYellow: f("\x1B[43m", "\x1B[49m"),
11592
- bgBlue: f("\x1B[44m", "\x1B[49m"),
11593
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
11594
- bgCyan: f("\x1B[46m", "\x1B[49m"),
11595
- bgWhite: f("\x1B[47m", "\x1B[49m"),
11596
- blackBright: f("\x1B[90m", "\x1B[39m"),
11597
- redBright: f("\x1B[91m", "\x1B[39m"),
11598
- greenBright: f("\x1B[92m", "\x1B[39m"),
11599
- yellowBright: f("\x1B[93m", "\x1B[39m"),
11600
- blueBright: f("\x1B[94m", "\x1B[39m"),
11601
- magentaBright: f("\x1B[95m", "\x1B[39m"),
11602
- cyanBright: f("\x1B[96m", "\x1B[39m"),
11603
- whiteBright: f("\x1B[97m", "\x1B[39m"),
11604
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
11605
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
11606
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
11607
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
11608
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
11609
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
11610
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
11611
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
11612
- };
11613
- };
11614
- module.exports = createColors();
11615
- module.exports.createColors = createColors;
11616
- })))(), 1);
11617
- const highlighter = {
11618
- error: import_picocolors.default.red,
11619
- warn: import_picocolors.default.yellow,
11620
- info: import_picocolors.default.cyan,
11621
- success: import_picocolors.default.green,
11622
- dim: import_picocolors.default.dim,
11623
- gray: import_picocolors.default.gray,
11624
- bold: import_picocolors.default.bold
11625
- };
11626
- /**
11627
- * Override picocolors' automatic color detection. picocolors decides
11628
- * once, at import time, from `NO_COLOR` / `FORCE_COLOR` / `TERM` / TTY.
11629
- * This lets the CLI honor an explicit `--color` / `--no-color` flag
11630
- * (clig.dev, Output: "Disable color … if the user requested it") by
11631
- * swapping in a fresh set of formatters. Call it before any colored
11632
- * output is produced. Every call site reads `highlighter.<method>` at
11633
- * call time, so reassigning the properties propagates everywhere.
11634
- */
11635
- const setColorEnabled = (enabled) => {
11636
- const colors = import_picocolors.default.createColors(enabled);
11637
- highlighter.error = colors.red;
11638
- highlighter.warn = colors.yellow;
11639
- highlighter.info = colors.cyan;
11640
- highlighter.success = colors.green;
11641
- highlighter.dim = colors.dim;
11642
- highlighter.gray = colors.gray;
11643
- highlighter.bold = colors.bold;
11644
- };
11645
11759
  /**
11646
11760
  * Canonical URL for a rule's documentation page — its reviewer-tested fix
11647
11761
  * recipe rendered for humans — served at
@@ -11757,9 +11871,38 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
11757
11871
  //#endregion
11758
11872
  //#region src/cli/utils/constants.ts
11759
11873
  const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
11874
+ const WELCOME_EXPLANATION_HOLD_MS = 2e3;
11875
+ const WELCOME_HOLD_MS = 1e3;
11760
11876
  const INTERNAL_ERROR_JSON_FALLBACK = "{\"schemaVersion\":1,\"ok\":false,\"error\":{\"message\":\"Internal error\",\"name\":\"Error\",\"chain\":[]}}\n";
11761
11877
  const SENTRY_FLUSH_TIMEOUT_MS = 2e3;
11762
11878
  const NANOSECONDS_PER_SECOND = 1000000000n;
11879
+ const METRIC = {
11880
+ cliInvoked: "cli.invoked",
11881
+ cliError: "cli.error",
11882
+ projectDetected: "project.detected",
11883
+ scanCompleted: "scan.completed",
11884
+ scanDuration: "scan.duration",
11885
+ scanPhaseDuration: "scan.phase_duration",
11886
+ scanFiles: "scan.files",
11887
+ scanScore: "scan.score",
11888
+ scanClean: "scan.clean",
11889
+ scanCheckSkipped: "scan.check_skipped",
11890
+ ruleFired: "rule.fired",
11891
+ lintFailed: "lint.failed",
11892
+ deadCodeFailed: "deadcode.failed",
11893
+ scoreUnavailable: "score.unavailable",
11894
+ oxlintWorkers: "oxlint.workers",
11895
+ agentHandoff: "agent.handoff",
11896
+ agentInstallHintShown: "agent.install_hint_shown",
11897
+ installCompleted: "install.completed",
11898
+ installAgent: "install.agent",
11899
+ installGitHook: "install.git_hook",
11900
+ installWorkflow: "install.workflow",
11901
+ installAgentHooks: "install.agent_hooks",
11902
+ installDependency: "install.dependency",
11903
+ rulesChanged: "rules.changed",
11904
+ rulesQueried: "rules.queried"
11905
+ };
11763
11906
  //#endregion
11764
11907
  //#region src/cli/utils/noop-console.ts
11765
11908
  /**
@@ -11801,7 +11944,7 @@ const makeNoopConsole = () => ({
11801
11944
  });
11802
11945
  //#endregion
11803
11946
  //#region src/cli/utils/version.ts
11804
- const VERSION = "0.2.15";
11947
+ const VERSION = "0.2.16-dev.114893e";
11805
11948
  //#endregion
11806
11949
  //#region src/cli/utils/json-mode.ts
11807
11950
  let context = null;
@@ -12025,13 +12168,20 @@ const buildSentryScope = (runContext = buildRunContext()) => {
12025
12168
  };
12026
12169
  };
12027
12170
  //#endregion
12028
- //#region src/cli/utils/scrub-sentry-event.ts
12171
+ //#region src/cli/utils/anonymize-text.ts
12172
+ /**
12173
+ * Free-text fields can carry both a home-directory path (the OS username) and a
12174
+ * secret/email echoed from user code, so run both scrubbers: strip the username
12175
+ * from paths, then mask any known credential/PII shape. Shared by the Sentry
12176
+ * event scrubber ({@link scrubSentryEvent}) and metric scrubber
12177
+ * ({@link scrubSentryMetric}).
12178
+ */
12029
12179
  const anonymizeText = (text) => redactSensitiveText(scrubSensitivePaths(text));
12030
12180
  /**
12031
12181
  * Recursively rewrites every string within an arbitrary value (object / array /
12032
12182
  * primitive) through {@link anonymizeText}, mutating in place. Used to sweep the
12033
- * unstructured corners of an event (contexts, extra, tags, breadcrumb data,
12034
- * span attributes) where a path or secret could hide.
12183
+ * unstructured corners of a Sentry payload (event contexts/extra/tags, breadcrumb
12184
+ * data, span attributes, metric attributes) where a path or secret could hide.
12035
12185
  */
12036
12186
  const anonymizeInPlace = (value) => {
12037
12187
  if (Array.isArray(value)) {
@@ -12049,6 +12199,8 @@ const anonymizeInPlace = (value) => {
12049
12199
  else anonymizeInPlace(inner);
12050
12200
  }
12051
12201
  };
12202
+ //#endregion
12203
+ //#region src/cli/utils/scrub-sentry-event.ts
12052
12204
  /**
12053
12205
  * Anonymizes a Sentry event (error or transaction) before it leaves the
12054
12206
  * machine. Strips identity the SDK attaches automatically — the IP-bearing
@@ -12096,6 +12248,27 @@ const scrubSentryEvent = (event) => {
12096
12248
  }
12097
12249
  };
12098
12250
  //#endregion
12251
+ //#region src/cli/utils/scrub-sentry-metric.ts
12252
+ /**
12253
+ * Anonymizes a Sentry metric before it leaves the machine, mirroring
12254
+ * {@link scrubSentryEvent}. Drops the `server.address` default attribute (the
12255
+ * hostname) and scrubs home-directory paths + known secrets/emails from every
12256
+ * remaining attribute value (metric names are our own constants, so they're
12257
+ * left intact to avoid splitting a series). Returns `null` on any failure so an
12258
+ * un-anonymized metric is never sent. Wired into `beforeSendMetric`.
12259
+ */
12260
+ const scrubSentryMetric = (metric) => {
12261
+ try {
12262
+ if (metric.attributes) {
12263
+ delete metric.attributes["server.address"];
12264
+ anonymizeInPlace(metric.attributes);
12265
+ }
12266
+ return metric;
12267
+ } catch {
12268
+ return null;
12269
+ }
12270
+ };
12271
+ //#endregion
12099
12272
  //#region src/instrument.ts
12100
12273
  let isInitialized = false;
12101
12274
  let resolvedTracesSampleRate = 0;
@@ -12117,13 +12290,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12117
12290
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12118
12291
  * standard `SENTRY_RELEASE` override.
12119
12292
  */
12120
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15`;
12293
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.16-dev.114893e`;
12121
12294
  /**
12122
12295
  * Deployment environment shown in Sentry's environment filter. Defaults to
12123
12296
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12124
12297
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12125
12298
  */
12126
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15") ? "development" : "production");
12299
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.16-dev.114893e") ? "development" : "production");
12127
12300
  /**
12128
12301
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12129
12302
  * (set to `0` to disable tracing) and falls back to
@@ -12191,7 +12364,8 @@ const initializeSentry = () => {
12191
12364
  contexts
12192
12365
  },
12193
12366
  beforeSend: (event) => scrubSentryEvent(event),
12194
- beforeSendTransaction: (event) => scrubSentryEvent(event)
12367
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
12368
+ beforeSendMetric: (metric) => scrubSentryMetric(metric)
12195
12369
  });
12196
12370
  };
12197
12371
  //#endregion
@@ -15463,6 +15637,122 @@ const recordSentryProjectContext = (projectInfo, rootSpan) => {
15463
15637
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
15464
15638
  };
15465
15639
  //#endregion
15640
+ //#region src/cli/utils/record-metric.ts
15641
+ const cleanAttributes = (attributes) => {
15642
+ const cleaned = {};
15643
+ if (!attributes) return cleaned;
15644
+ for (const [key, value] of Object.entries(attributes)) if (value !== null && value !== void 0) cleaned[key] = value;
15645
+ return cleaned;
15646
+ };
15647
+ const withRunAttributes = (attributes) => ({
15648
+ ...toSpanAttributes(buildSentryScope().tags),
15649
+ ...cleanAttributes(attributes)
15650
+ });
15651
+ /**
15652
+ * Emits a Sentry counter. A guarded, swallow-on-throw no-op unless the CLI's
15653
+ * Sentry SDK is live, so it's inert under `--no-score`, tests, and the
15654
+ * programmatic `@react-doctor/api` library (none of which initialize Sentry).
15655
+ * Metrics flow independently of performance tracing, so counters are still
15656
+ * recorded when `SENTRY_TRACES_SAMPLE_RATE=0`.
15657
+ */
15658
+ const recordCount = (name, value = 1, attributes) => {
15659
+ if (!Sentry.isInitialized()) return;
15660
+ try {
15661
+ Sentry.metrics.count(name, value, { attributes: withRunAttributes(attributes) });
15662
+ } catch {}
15663
+ };
15664
+ /**
15665
+ * Emits a Sentry distribution (value ranges — durations, sizes, scores). Same
15666
+ * gating and run-attribute handling as {@link recordCount}.
15667
+ */
15668
+ const recordDistribution = (name, value, options = {}) => {
15669
+ if (!Sentry.isInitialized()) return;
15670
+ try {
15671
+ Sentry.metrics.distribution(name, value, {
15672
+ unit: options.unit,
15673
+ attributes: withRunAttributes(options.attributes)
15674
+ });
15675
+ } catch {}
15676
+ };
15677
+ //#endregion
15678
+ //#region src/cli/utils/record-scan-metrics.ts
15679
+ /**
15680
+ * Aggregates diagnostics into per-`(rule, severity)` firing counts, reusing the
15681
+ * canonical `getDiagnosticRuleIdentity` so the `<plugin>/<rule>` key and
15682
+ * category match every other rule-keyed surface. Pure and exported so the
15683
+ * bucketing is unit-testable without an active Sentry client (the emit helpers
15684
+ * no-op under tests). Grouping the emitted `rule.fired` counter by `category`
15685
+ * or `severity` in Sentry reproduces a coarser breakdown.
15686
+ */
15687
+ const summarizeRuleFirings = (diagnostics) => {
15688
+ const firings = /* @__PURE__ */ new Map();
15689
+ for (const diagnostic of diagnostics) {
15690
+ const { ruleKey, category } = getDiagnosticRuleIdentity(diagnostic);
15691
+ const firingKey = `${ruleKey}\u0000${diagnostic.severity}`;
15692
+ const existing = firings.get(firingKey);
15693
+ firings.set(firingKey, existing ? {
15694
+ ...existing,
15695
+ count: existing.count + 1
15696
+ } : {
15697
+ rule: ruleKey,
15698
+ plugin: diagnostic.plugin,
15699
+ category,
15700
+ severity: diagnostic.severity,
15701
+ count: 1
15702
+ });
15703
+ }
15704
+ return [...firings.values()];
15705
+ };
15706
+ /**
15707
+ * Emits the per-scan engineering + product counters/distributions for one
15708
+ * `inspect()` run (fires once per project in a workspace scan). Every emission
15709
+ * is a no-op unless Sentry is live, and the shared run/project attributes ride
15710
+ * along from the global scope, so call sites only pass scan-specific dimensions.
15711
+ */
15712
+ const recordScanMetrics = (input) => {
15713
+ const { result } = input;
15714
+ const hasSkippedChecks = result.skippedChecks.length > 0;
15715
+ recordCount(METRIC.scanCompleted, 1, {
15716
+ mode: input.mode,
15717
+ lint: input.lint,
15718
+ deadCode: input.deadCode,
15719
+ parallel: input.parallel,
15720
+ scoreOnly: input.scoreOnly,
15721
+ didLintFail: input.didLintFail,
15722
+ didDeadCodeFail: input.didDeadCodeFail,
15723
+ hasSkippedChecks
15724
+ });
15725
+ recordDistribution(METRIC.scanDuration, result.elapsedMilliseconds, {
15726
+ unit: "millisecond",
15727
+ attributes: {
15728
+ mode: input.mode,
15729
+ parallel: input.parallel,
15730
+ scoreOnly: input.scoreOnly
15731
+ }
15732
+ });
15733
+ if (result.scanElapsedMilliseconds !== void 0) recordDistribution(METRIC.scanPhaseDuration, result.scanElapsedMilliseconds, {
15734
+ unit: "millisecond",
15735
+ attributes: { mode: input.mode }
15736
+ });
15737
+ if (result.scannedFileCount !== void 0) recordDistribution(METRIC.scanFiles, result.scannedFileCount, { attributes: { mode: input.mode } });
15738
+ if (input.workerCount !== void 0) recordDistribution(METRIC.oxlintWorkers, input.workerCount, { attributes: { mode: input.mode } });
15739
+ for (const firing of summarizeRuleFirings(result.diagnostics)) recordCount(METRIC.ruleFired, firing.count, {
15740
+ rule: firing.rule,
15741
+ plugin: firing.plugin,
15742
+ category: firing.category,
15743
+ severity: firing.severity
15744
+ });
15745
+ if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
15746
+ if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
15747
+ else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
15748
+ if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
15749
+ if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
15750
+ for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
15751
+ check,
15752
+ reason: result.skippedCheckReasons?.[check] ?? null
15753
+ });
15754
+ };
15755
+ //#endregion
15466
15756
  //#region src/cli/utils/build-no-score-message.ts
15467
15757
  const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
15468
15758
  const buildNoScoreMessage = (isScoreDisabled) => {
@@ -15586,6 +15876,12 @@ const buildCodeFrame = (input) => {
15586
15876
  });
15587
15877
  };
15588
15878
  //#endregion
15879
+ //#region src/cli/utils/build-section-divider.ts
15880
+ const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
15881
+ //#endregion
15882
+ //#region src/cli/utils/ease-out-cubic.ts
15883
+ const easeOutCubic = (progress) => 1 - (1 - progress) ** 3;
15884
+ //#endregion
15589
15885
  //#region src/cli/utils/indent-multiline-text.ts
15590
15886
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
15591
15887
  //#endregion
@@ -15625,6 +15921,11 @@ const wrapTextToWidth = (text, width, options = {}) => {
15625
15921
  return text.split("\n").flatMap((lineText) => wrapLine(lineText, width, breakLongWords));
15626
15922
  };
15627
15923
  //#endregion
15924
+ //#region src/cli/utils/write-stdout.ts
15925
+ const writeStdout = (text) => Effect.sync(() => {
15926
+ process.stdout.write(text);
15927
+ });
15928
+ //#endregion
15628
15929
  //#region src/cli/utils/render-diagnostics.ts
15629
15930
  const POINTER = isUnicodeSupported() ? "›" : ">";
15630
15931
  const colorizeBySeverity = (text, severity) => severity === "error" ? highlighter.error(text) : highlighter.warn(text);
@@ -15658,17 +15959,28 @@ const buildCategoryDiagnosticGroups = (diagnostics, rulePriority) => {
15658
15959
  return categoryGroupA.category.localeCompare(categoryGroupB.category);
15659
15960
  });
15660
15961
  };
15661
- const buildCompactCategoryLine = (categoryGroup) => {
15662
- const errorCount = categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
15663
- const warningCount = categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
15962
+ const formatCategoryTallyLine = (tally, errorShown, warningShown) => {
15664
15963
  const parts = [];
15665
- if (errorCount > 0) parts.push(highlighter.error(`${errorCount} ${errorCount === 1 ? "error" : "errors"}`));
15666
- if (warningCount > 0) parts.push(highlighter.warn(highlighter.dim(`${warningCount} ${warningCount === 1 ? "warning" : "warnings"}`)));
15667
- return ` ${highlighter.bold(categoryGroup.category)} ${highlighter.dim(POINTER)} ${parts.join(highlighter.dim(", "))}`;
15668
- };
15964
+ if (tally.errorCount > 0) parts.push(highlighter.error(`${errorShown} ${errorShown === 1 ? "error" : "errors"}`));
15965
+ if (tally.warningCount > 0) parts.push(highlighter.warn(highlighter.dim(`${warningShown} ${warningShown === 1 ? "warning" : "warnings"}`)));
15966
+ return ` ${highlighter.bold(tally.category)} ${highlighter.dim(POINTER)} ${parts.join(highlighter.dim(", "))}`;
15967
+ };
15968
+ const buildCategoryTally = (categoryGroup) => ({
15969
+ category: categoryGroup.category,
15970
+ errorCount: categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length,
15971
+ warningCount: categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length
15972
+ });
15973
+ const buildCategoryTallyLines = (tallies) => tallies.map((tally) => formatCategoryTallyLine(tally, tally.errorCount, tally.warningCount));
15974
+ const printCategoryCountUp = (tallies) => Effect.gen(function* () {
15975
+ for (let frame = 0; frame <= 16; frame += 1) {
15976
+ const fraction = easeOutCubic(frame / 16);
15977
+ const lines = tallies.map((tally) => formatCategoryTallyLine(tally, Math.round(tally.errorCount * fraction), Math.round(tally.warningCount * fraction)));
15978
+ yield* writeStdout(`${frame === 0 ? "" : `\x1b[${tallies.length}A`}\r${lines.join("\n\r")}\n`);
15979
+ if (frame < 16) yield* Effect.sleep(45);
15980
+ }
15981
+ });
15669
15982
  const TOP_ERROR_DETAIL_INDENT = " ";
15670
15983
  const pickRepresentativeDiagnostic = (ruleDiagnostics) => ruleDiagnostics.find((diagnostic) => diagnostic.line > 0) ?? ruleDiagnostics[0];
15671
- const isErrorRuleGroup = (ruleDiagnostics) => pickRepresentativeDiagnostic(ruleDiagnostics).severity === "error";
15672
15984
  const FRAME_CONTEXT_REACH_LINES = 3;
15673
15985
  const clusterNearbyDiagnostics = (diagnostics) => {
15674
15986
  const byFile = groupBy(diagnostics, (diagnostic) => diagnostic.filePath);
@@ -15719,101 +16031,87 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
15719
16031
  }
15720
16032
  return lines;
15721
16033
  };
15722
- const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, renderEverySite) => {
16034
+ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, renderEverySite, isAgentEnvironment) => {
15723
16035
  const representative = pickRepresentativeDiagnostic(ruleDiagnostics);
15724
16036
  const { severity } = representative;
15725
16037
  const trailingBadge = formatTrailingSiteBadge(ruleDiagnostics.length);
15726
16038
  const headline = colorizeBySeverity(`${representative.category}: ${representative.title ?? ruleKey}`, severity);
15727
- const lines = [` ${colorizeBySeverity(severity === "error" ? "✗" : "⚠", severity)} ${headline}${trailingBadge}`];
15728
- if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
15729
- if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
15730
- const renderCodeFrame = severity === "error";
15731
- const sites = renderEverySite ? ruleDiagnostics : [representative];
15732
- for (const cluster of clusterNearbyDiagnostics(sites)) lines.push(...buildDiagnosticClusterLines(cluster, resolveSourceRoot, renderCodeFrame));
15733
- return lines;
15734
- };
15735
- const WARNING_DETAIL_INDENT = " ";
15736
- const computeRuleNameColumnWidth = (ruleKeys) => ruleKeys.reduce((widest, ruleKey) => Math.max(widest, ruleKey.length), 36);
15737
- const padRuleNameToColumn = (ruleName, columnWidth) => ruleName.length >= columnWidth ? ruleName : ruleName + " ".repeat(columnWidth - ruleName.length);
15738
- const buildWarningHeaderLine = (ruleKey, siteCount, ruleNameColumnWidth) => {
15739
- const ruleName = formatSiteCountBadge(siteCount).length > 0 ? padRuleNameToColumn(ruleKey, ruleNameColumnWidth) : ruleKey;
15740
- return ` ${highlighter.warn("⚠")} ${ruleName}${formatTrailingSiteBadge(siteCount)}`;
15741
- };
15742
- const buildWarningRuleBlock = (ruleKey, ruleDiagnostics, ruleNameColumnWidth, isAgentEnvironment) => {
15743
- const representative = pickRepresentativeDiagnostic(ruleDiagnostics);
15744
- const lines = [buildWarningHeaderLine(ruleKey, ruleDiagnostics.length, ruleNameColumnWidth)];
15745
- if (!isAgentEnvironment) {
16039
+ const lines = [` ${colorizeBySeverity(severity === "error" ? "✖" : "⚠", severity)} ${headline}${trailingBadge}`];
16040
+ if (renderEverySite && !isAgentEnvironment) {
15746
16041
  const learnMoreLine = formatLearnMoreLine(representative);
15747
- if (learnMoreLine) lines.push(`${WARNING_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16042
+ if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
15748
16043
  }
15749
- lines.push(highlighter.gray(indentMultilineText(representative.message, WARNING_DETAIL_INDENT)));
15750
- if (representative.help) lines.push(highlighter.gray(indentMultilineText(`→ ${representative.help}`, WARNING_DETAIL_INDENT)));
15751
- if (isAgentEnvironment) {
16044
+ if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16045
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16046
+ if (renderEverySite && isAgentEnvironment) {
15752
16047
  const fixRecipeLine = formatFixRecipeLine(representative);
15753
- if (fixRecipeLine) lines.push(highlighter.gray(`${WARNING_DETAIL_INDENT}${fixRecipeLine}`));
15754
- }
15755
- for (const [filePath, sites] of buildVerboseSiteMap(ruleDiagnostics)) {
15756
- if (sites.length === 0) {
15757
- lines.push(highlighter.gray(`${WARNING_DETAIL_INDENT}${filePath}`));
15758
- continue;
15759
- }
15760
- for (const site of sites) {
15761
- lines.push(highlighter.gray(`${WARNING_DETAIL_INDENT}${filePath}:${site.line}`));
15762
- if (site.suppressionHint) lines.push(highlighter.gray(`${WARNING_DETAIL_INDENT} ↳ ${site.suppressionHint}`));
15763
- }
16048
+ if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
15764
16049
  }
16050
+ const renderCodeFrame = severity === "error" || renderEverySite;
16051
+ const sites = renderEverySite ? ruleDiagnostics : [representative];
16052
+ for (const cluster of clusterNearbyDiagnostics(sites)) lines.push(...buildDiagnosticClusterLines(cluster, resolveSourceRoot, renderCodeFrame));
15765
16053
  return lines;
15766
16054
  };
15767
16055
  const selectErrorRuleGroups = (diagnostics, rulePriority) => buildSortedRuleGroups(diagnostics.filter((diagnostic) => diagnostic.severity === "error"), rulePriority);
15768
16056
  const selectTopErrorRuleGroups = (diagnostics, limit, rulePriority) => selectErrorRuleGroups(diagnostics, rulePriority).slice(0, limit);
15769
- const buildMoreRulesLine = (hiddenRuleCount, severityNoun, accent) => {
15770
- const ruleNoun = hiddenRuleCount === 1 ? "rule" : "rules";
15771
- return ` ${highlighter.bold(accent(`+${hiddenRuleCount} more ${ruleNoun}`))} ${highlighter.dim("— run")} ${highlighter.bold(highlighter.info("--verbose"))} ${highlighter.dim(`to view the rest of the ${severityNoun} and details about each`)}`;
16057
+ const buildOverflowSummaryLine = (diagnostics, rulePriority) => {
16058
+ const errorRuleGroups = selectErrorRuleGroups(diagnostics, rulePriority);
16059
+ const shownErrorRuleCount = Math.min(3, errorRuleGroups.length);
16060
+ if (diagnostics.length <= shownErrorRuleCount) return void 0;
16061
+ const hiddenErrorRuleCount = errorRuleGroups.length - shownErrorRuleCount;
16062
+ const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
16063
+ const parts = [];
16064
+ if (hiddenErrorRuleCount > 0) {
16065
+ const ruleNoun = hiddenErrorRuleCount === 1 ? "rule" : "rules";
16066
+ parts.push(highlighter.bold(highlighter.error(`+${hiddenErrorRuleCount} more ${ruleNoun}`)));
16067
+ }
16068
+ if (warningCount > 0) {
16069
+ const warningNoun = warningCount === 1 ? "warning" : "warnings";
16070
+ parts.push(highlighter.bold(highlighter.warn(`+${warningCount} optional ${warningNoun}`)));
16071
+ }
16072
+ const command = highlighter.bold(highlighter.info("npx react-doctor@latest --verbose"));
16073
+ return ` ${parts.length > 0 ? `${parts.join(highlighter.dim(" and "))} ${highlighter.dim("- run")}` : highlighter.dim("Run")} ${command} ${highlighter.dim("for details")}`;
15772
16074
  };
15773
16075
  const getTopErrorRuleKeys = (diagnostics, limit, rulePriority) => new Set(selectTopErrorRuleGroups(diagnostics, limit, rulePriority).map(([ruleKey]) => ruleKey));
15774
- const buildTopErrorsLines = (diagnostics, resolveSourceRoot, rulePriority) => {
15775
- const errorRuleGroups = selectErrorRuleGroups(diagnostics, rulePriority);
15776
- const topRuleGroups = errorRuleGroups.slice(0, 3);
15777
- if (topRuleGroups.length === 0) return [];
15778
- const hiddenRuleCount = errorRuleGroups.length - topRuleGroups.length;
16076
+ const buildTopErrorsSection = (diagnostics, resolveSourceRoot, rulePriority) => {
16077
+ const topRuleGroups = selectErrorRuleGroups(diagnostics, rulePriority).slice(0, 3);
16078
+ if (topRuleGroups.length === 0) return {
16079
+ lines: [],
16080
+ blockOffsets: []
16081
+ };
15779
16082
  const lines = [
15780
- highlighter.dim(` ${"─".repeat(60)}`),
16083
+ buildSectionDivider(),
15781
16084
  ` ${highlighter.bold(`Top ${topRuleGroups.length} ${topRuleGroups.length === 1 ? "error" : "errors"} you should fix`)}`,
15782
16085
  ""
15783
16086
  ];
16087
+ const blockOffsets = [];
15784
16088
  for (const [ruleKey, ruleDiagnostics] of topRuleGroups) {
15785
- lines.push(...buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, false));
16089
+ blockOffsets.push(lines.length);
16090
+ lines.push(...buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, false, false));
15786
16091
  lines.push("");
15787
16092
  }
15788
- if (hiddenRuleCount > 0) lines.push(buildMoreRulesLine(hiddenRuleCount, "errors", highlighter.error));
15789
- return lines;
15790
- };
15791
- const buildWarningsListLines = (diagnostics, rulePriority) => {
15792
- const warningDiagnostics = diagnostics.filter((diagnostic) => diagnostic.severity === "warning");
15793
- if (warningDiagnostics.length === 0) return [];
15794
- const sortedRuleGroups = buildSortedRuleGroups(warningDiagnostics, rulePriority);
15795
- const shownRuleGroups = sortedRuleGroups.slice(0, 10);
15796
- const hiddenRuleCount = sortedRuleGroups.length - shownRuleGroups.length;
15797
- const ruleNameColumnWidth = computeRuleNameColumnWidth(shownRuleGroups.map(([ruleKey]) => ruleKey));
15798
- const lines = [
15799
- highlighter.dim(` ${"─".repeat(60)}`),
15800
- ` ${highlighter.bold(`${warningDiagnostics.length} ${warningDiagnostics.length === 1 ? "warning" : "warnings"}`)}`,
15801
- ""
15802
- ];
15803
- for (const [ruleKey, ruleDiagnostics] of shownRuleGroups) lines.push(buildWarningHeaderLine(ruleKey, ruleDiagnostics.length, ruleNameColumnWidth));
15804
- if (hiddenRuleCount > 0) lines.push(buildMoreRulesLine(hiddenRuleCount, "warnings", highlighter.warn));
15805
- return lines;
16093
+ return {
16094
+ lines,
16095
+ blockOffsets
16096
+ };
15806
16097
  };
15807
- const buildCategoryBreakdownLines = (diagnostics, rulePriority) => buildCategoryDiagnosticGroups(diagnostics, rulePriority).map(buildCompactCategoryLine);
15808
16098
  const joinSections = (...sections) => {
15809
16099
  const lines = [];
16100
+ const sectionStarts = [];
15810
16101
  for (const section of sections) {
15811
- if (section.length === 0) continue;
16102
+ if (section.length === 0) {
16103
+ sectionStarts.push(null);
16104
+ continue;
16105
+ }
15812
16106
  if (lines.length > 0) lines.push("");
16107
+ sectionStarts.push(lines.length);
15813
16108
  lines.push(...section);
15814
16109
  }
15815
16110
  if (lines.length > 0 && lines[lines.length - 1] !== "") lines.push("");
15816
- return lines;
16111
+ return {
16112
+ lines,
16113
+ sectionStarts
16114
+ };
15817
16115
  };
15818
16116
  const buildCountsSummaryLines = (diagnostics) => {
15819
16117
  const totalIssueCount = diagnostics.length;
@@ -15828,19 +16126,36 @@ const buildCountsSummaryLines = (diagnostics) => {
15828
16126
  * single Effect.forEach over Console.log so failures or fiber
15829
16127
  * interruption produce predictable partial output.
15830
16128
  */
15831
- const printDiagnostics = (diagnostics, isVerbose, sourceRoot, rulePriority, isAgentEnvironment = false) => Effect.gen(function* () {
16129
+ const printDiagnostics = (diagnostics, isVerbose, sourceRoot, rulePriority, isAgentEnvironment = false, onboarding = {}) => Effect.gen(function* () {
16130
+ const sectionPause = onboarding.sectionPause ?? Effect.void;
16131
+ const animateCountUp = onboarding.animateCountUp ?? false;
15832
16132
  const resolveSourceRoot = typeof sourceRoot === "function" ? sourceRoot : () => sourceRoot;
15833
16133
  let detailLines;
15834
- if (!isVerbose) detailLines = buildTopErrorsLines(diagnostics, resolveSourceRoot, rulePriority);
15835
- else {
15836
- const sortedRuleGroups = buildSortedRuleGroups(diagnostics, rulePriority);
15837
- const warningRuleNameColumnWidth = computeRuleNameColumnWidth(sortedRuleGroups.filter(([, ruleDiagnostics]) => !isErrorRuleGroup(ruleDiagnostics)).map(([ruleKey]) => ruleKey));
15838
- detailLines = sortedRuleGroups.flatMap(([ruleKey, ruleDiagnostics]) => {
15839
- return [...isErrorRuleGroup(ruleDiagnostics) ? buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, true) : buildWarningRuleBlock(ruleKey, ruleDiagnostics, warningRuleNameColumnWidth, isAgentEnvironment), ""];
15840
- });
16134
+ let topErrorBlockOffsets = [];
16135
+ if (!isVerbose) {
16136
+ const topErrors = buildTopErrorsSection(diagnostics, resolveSourceRoot, rulePriority);
16137
+ detailLines = topErrors.lines;
16138
+ topErrorBlockOffsets = topErrors.blockOffsets;
16139
+ } else detailLines = buildSortedRuleGroups(diagnostics, rulePriority).flatMap(([ruleKey, ruleDiagnostics]) => {
16140
+ return [...buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, true, isAgentEnvironment), ""];
16141
+ });
16142
+ const overflowLine = isVerbose ? void 0 : buildOverflowSummaryLine(diagnostics, rulePriority);
16143
+ const categoryTallies = buildCategoryDiagnosticGroups(diagnostics, rulePriority).map(buildCategoryTally);
16144
+ const categoryLines = buildCategoryTallyLines(categoryTallies);
16145
+ const { lines, sectionStarts } = joinSections(categoryLines, buildCountsSummaryLines(diagnostics), detailLines, overflowLine ? [overflowLine] : []);
16146
+ const [categoryStart, , detailStart] = sectionStarts;
16147
+ const pauseBeforeLineIndices = detailStart == null ? /* @__PURE__ */ new Set() : new Set(topErrorBlockOffsets.map((offset) => detailStart + offset));
16148
+ let lineIndex = 0;
16149
+ while (lineIndex < lines.length) {
16150
+ if (animateCountUp && lineIndex === categoryStart && categoryLines.length > 0) {
16151
+ yield* printCategoryCountUp(categoryTallies);
16152
+ lineIndex += categoryLines.length;
16153
+ continue;
16154
+ }
16155
+ if (pauseBeforeLineIndices.has(lineIndex)) yield* sectionPause;
16156
+ yield* Console.log(lines[lineIndex]);
16157
+ lineIndex += 1;
15841
16158
  }
15842
- const lines = joinSections(buildCategoryBreakdownLines(diagnostics, rulePriority), buildCountsSummaryLines(diagnostics), detailLines, isVerbose ? [] : buildWarningsListLines(diagnostics, rulePriority));
15843
- for (const line of lines) yield* Console.log(line);
15844
16159
  });
15845
16160
  const formatElapsedTime = (elapsedMilliseconds) => {
15846
16161
  if (elapsedMilliseconds < 1e3) return `${Math.round(elapsedMilliseconds)}ms`;
@@ -15878,6 +16193,44 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
15878
16193
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
15879
16194
  return potentialScore.score;
15880
16195
  };
16196
+ const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16197
+ const FALSY_FLAG_VALUES = new Set([
16198
+ "",
16199
+ "0",
16200
+ "false"
16201
+ ]);
16202
+ const isOnboardingForced = (environment = process.env) => {
16203
+ const value = environment[FORCE_ONBOARDING_ENV_VAR];
16204
+ return value !== void 0 && !FALSY_FLAG_VALUES.has(value.toLowerCase());
16205
+ };
16206
+ const onboardingSectionPause = (shouldPace) => shouldPace ? Effect.sleep(850) : Effect.void;
16207
+ const shouldRecordOnboarding = (input) => input.paceOnboardingSections && !input.forceOnboarding && !input.verbose && !input.isNonInteractiveEnvironment;
16208
+ const canAnimateOnboarding = (stream = process.stdout) => {
16209
+ if (!(stream.isTTY === true && (stream.columns ?? 0) > 0 && process.env.TERM !== "dumb")) return false;
16210
+ return isOnboardingForced() || !isCiEnvironment();
16211
+ };
16212
+ //#endregion
16213
+ //#region src/cli/utils/onboarding-state.ts
16214
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
16215
+ const ONBOARDED_AT_KEY = "onboardedAt";
16216
+ const getOnboardingStore = (options = {}) => new Conf({
16217
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
16218
+ cwd: options.cwd
16219
+ });
16220
+ const hasCompletedOnboarding = (options = {}) => {
16221
+ try {
16222
+ return typeof getOnboardingStore(options).get(ONBOARDED_AT_KEY) === "string";
16223
+ } catch {
16224
+ return true;
16225
+ }
16226
+ };
16227
+ const markOnboardingComplete = (options = {}) => {
16228
+ try {
16229
+ const store = getOnboardingStore(options);
16230
+ if (typeof store.get(ONBOARDED_AT_KEY) === "string") return;
16231
+ store.set(ONBOARDED_AT_KEY, (/* @__PURE__ */ new Date()).toISOString());
16232
+ } catch {}
16233
+ };
15881
16234
  //#endregion
15882
16235
  //#region src/cli/utils/render-project-detection.ts
15883
16236
  const printProjectDetection = (_input) => Effect.void;
@@ -15894,8 +16247,6 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
15894
16247
  const RAINBOW_GRADIENT_WIDTH = 80;
15895
16248
  const RAINBOW_OKLCH_LIGHTNESS = .638;
15896
16249
  const RAINBOW_OKLCH_CHROMA = .129;
15897
- const easeOutCubic = (progress) => 1 - (1 - progress) ** 3;
15898
- const sleep = (milliseconds) => Effect.promise(() => new Promise((resolve) => setTimeout(resolve, milliseconds)));
15899
16250
  const buildScoreBarSegments = (filledCount) => {
15900
16251
  const emptyCount = 50 - filledCount;
15901
16252
  return {
@@ -15965,9 +16316,6 @@ const buildFaceRenderedLines = (score) => {
15965
16316
  const colorize = (text) => colorizeByScore(text, score);
15966
16317
  return buildRawFaceLines(score).map(colorize);
15967
16318
  };
15968
- const writeScoreHeaderLine = (line) => Effect.sync(() => {
15969
- process.stdout.write(line);
15970
- });
15971
16319
  const buildScoreLine = (displayScore, finalScore, label) => {
15972
16320
  const scoreNumber = colorizeByScore(`${displayScore}`, finalScore);
15973
16321
  const scoreLabel = colorizeByScore(label, finalScore);
@@ -16006,37 +16354,37 @@ const printAnimatedScore = (scoreFaceLine, barFaceLine, score, label, potentialS
16006
16354
  const progress = easeOutCubic(frame / 40);
16007
16355
  const animatedScore = Math.round(score * progress);
16008
16356
  if (isPerfectScore) {
16009
- yield* writeScoreHeaderLine(`${frame === 0 ? "" : "\x1B[4A"}\r${buildRainbowScoreHeaderFrame({
16357
+ yield* writeStdout(`${frame === 0 ? "" : "\x1B[4A"}\r${buildRainbowScoreHeaderFrame({
16010
16358
  score,
16011
16359
  displayScore: animatedScore,
16012
16360
  label,
16013
16361
  frame
16014
16362
  })}`);
16015
- if (frame < 40) yield* sleep(50);
16363
+ if (frame < 40) yield* Effect.sleep(50);
16016
16364
  continue;
16017
16365
  }
16018
16366
  const animatedScoreLine = buildScoreLine(animatedScore, score, label);
16019
16367
  const animatedBarLine = frame === 40 && potentialScore !== void 0 ? buildProjectedScoreBar(score, potentialScore) : buildScoreBar(animatedScore, score);
16020
- yield* writeScoreHeaderLine(`${frame === 0 ? "" : "\x1B[2A"}\r${buildScoreHeaderLine(scoreFaceLine, animatedScoreLine)}\n\r${buildScoreHeaderLine(barFaceLine, animatedBarLine)}\n`);
16021
- if (frame < 40) yield* sleep(50);
16368
+ yield* writeStdout(`${frame === 0 ? "" : "\x1B[2A"}\r${buildScoreHeaderLine(scoreFaceLine, animatedScoreLine)}\n\r${buildScoreHeaderLine(barFaceLine, animatedBarLine)}\n`);
16369
+ if (frame < 40) yield* Effect.sleep(50);
16022
16370
  }
16023
16371
  if (!isPerfectScore) return;
16024
16372
  for (let frame = 0; frame < 16; frame += 1) {
16025
- yield* writeScoreHeaderLine(`\x1b[4A\r${buildRainbowScoreHeaderFrame({
16373
+ yield* writeStdout(`\x1b[4A\r${buildRainbowScoreHeaderFrame({
16026
16374
  score,
16027
16375
  displayScore: score,
16028
16376
  label,
16029
16377
  frame
16030
16378
  })}`);
16031
- yield* sleep(50);
16379
+ yield* Effect.sleep(50);
16032
16380
  }
16033
- yield* writeScoreHeaderLine(`\x1b[4A\r${buildFinalPerfectScoreHeaderFrame(score, label, 16)}\x1b[2A`);
16381
+ yield* writeStdout(`\x1b[4A\r${buildFinalPerfectScoreHeaderFrame(score, label, 16)}\x1b[2A`);
16034
16382
  });
16035
16383
  const printScoreHeader = (scoreResult, potentialScore) => Effect.gen(function* () {
16036
16384
  const isPerfectScore = scoreResult.score === 100;
16037
16385
  const renderedFaceLines = buildFaceRenderedLines(scoreResult.score);
16038
16386
  const rawFaceLines = buildRawFaceLines(scoreResult.score);
16039
- const shouldAnimate = !isSpinnerSilent() && isSpinnerInteractive(process.stdout);
16387
+ const shouldAnimate = !isSpinnerSilent() && canAnimateOnboarding(process.stdout);
16040
16388
  const displayScore = shouldAnimate ? 0 : scoreResult.score;
16041
16389
  const rightColumnLines = [
16042
16390
  buildScoreLine(displayScore, scoreResult.score, scoreResult.label),
@@ -16062,9 +16410,19 @@ const printScoreHeader = (scoreResult, potentialScore) => Effect.gen(function* (
16062
16410
  }));
16063
16411
  yield* Console.log("");
16064
16412
  if (shouldAnimate) {
16065
- yield* writeScoreHeaderLine("\x1B[5A");
16413
+ yield* writeStdout("\x1B[5A");
16066
16414
  yield* printAnimatedScore(renderedFaceLines[0], renderedFaceLines[1], scoreResult.score, scoreResult.label, potentialScore);
16067
- yield* writeScoreHeaderLine("\x1B[3B");
16415
+ yield* writeStdout("\x1B[3B");
16416
+ }
16417
+ });
16418
+ const animateScoreProjection = (scoreResult, potentialScore, linesBelowBar) => Effect.gen(function* () {
16419
+ if (scoreResult.score === 100 || potentialScore <= scoreResult.score) return;
16420
+ const barFaceLine = buildFaceRenderedLines(scoreResult.score)[1] ?? "";
16421
+ for (let frame = 1; frame <= 16; frame += 1) {
16422
+ const progress = easeOutCubic(frame / 16);
16423
+ const displayedPotential = scoreResult.score + (potentialScore - scoreResult.score) * progress;
16424
+ yield* writeStdout(`\x1b[${linesBelowBar}A\r${buildScoreHeaderLine(barFaceLine, buildProjectedScoreBar(scoreResult.score, displayedPotential))}\x1b[${linesBelowBar}B\r`);
16425
+ if (frame < 16) yield* Effect.sleep(35);
16068
16426
  }
16069
16427
  });
16070
16428
  const printBrandingOnlyHeader = Effect.gen(function* () {
@@ -16099,23 +16457,30 @@ const buildShareUrl = (diagnostics, scoreResult, projectName) => {
16099
16457
  if (affectedFileCount > 0) params.set("f", String(affectedFileCount));
16100
16458
  return `${SHARE_BASE_URL}?${params.toString()}`;
16101
16459
  };
16102
- const printVerboseTip = (diagnostics, isVerbose) => Effect.gen(function* () {
16103
- if (isVerbose || diagnostics.length === 0) return;
16104
- const command = highlighter.info("npx react-doctor@latest --verbose");
16105
- const message = diagnostics.some((diagnostic) => diagnostic.severity === "warning") ? `Run ${command} to see each warning explained with its fix` : `Run ${command} to see each issue explained with its fix`;
16106
- yield* Console.log(highlighter.dim(` Tip: ${message}`));
16107
- });
16108
- const printDocsNote = () => Effect.gen(function* () {
16460
+ const printFooter = (input) => Effect.gen(function* () {
16109
16461
  yield* Console.log("");
16462
+ yield* Console.log(buildSectionDivider());
16463
+ yield* Console.log("");
16464
+ if (!input.isOffline) {
16465
+ const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
16466
+ yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
16467
+ yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
16468
+ yield* Console.log("");
16469
+ }
16110
16470
  yield* Console.log(` ${highlighter.bold("Docs:")} ${highlighter.info(DOCS_URL)}`);
16111
- yield* Console.log(highlighter.dim(" Set up CI/CD, suppress rules with a config file, and scan diffs or PRs."));
16471
+ yield* Console.log(highlighter.dim(" Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file"));
16472
+ yield* Console.log("");
16473
+ yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
16474
+ yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
16112
16475
  });
16113
16476
  const printSummary = (input) => Effect.gen(function* () {
16114
16477
  if (input.scoreResult) {
16115
- yield* printScoreHeader(input.scoreResult, input.potentialScore ?? void 0);
16478
+ const animateProjection = Boolean(input.animateProjection) && input.potentialScore != null && !input.verbose;
16479
+ yield* printScoreHeader(input.scoreResult, animateProjection ? void 0 : input.potentialScore ?? void 0);
16116
16480
  if (input.potentialScore != null) {
16117
16481
  const improvement = input.potentialScore - input.scoreResult.score;
16118
16482
  yield* Console.log(highlighter.gray(" You could improve ") + colorizeByScore(`+${improvement}%`, input.potentialScore) + highlighter.gray(` by fixing the top 3 issues`));
16483
+ if (animateProjection) yield* animateScoreProjection(input.scoreResult, input.potentialScore, 5);
16119
16484
  }
16120
16485
  } else yield* printNoScoreHeader(input.noScoreMessage);
16121
16486
  const diagnosticsDirectory = yield* Effect.try({
@@ -16123,12 +16488,6 @@ const printSummary = (input) => Effect.gen(function* () {
16123
16488
  catch: (cause) => cause
16124
16489
  }).pipe(Effect.orElseSucceed(() => null));
16125
16490
  if (diagnosticsDirectory !== null && input.verbose) yield* Console.log(highlighter.gray(` Full diagnostics written to ${diagnosticsDirectory}`));
16126
- if (!input.isOffline) {
16127
- yield* Console.log("");
16128
- const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
16129
- yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
16130
- yield* Console.log("");
16131
- }
16132
16491
  });
16133
16492
  //#endregion
16134
16493
  //#region src/cli/utils/cli-logger.ts
@@ -16370,6 +16729,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16370
16729
  suppressScanSummary: options.suppressRendering
16371
16730
  }, { beforeLint: (projectInfo, lintIncludePaths) => Effect.gen(function* () {
16372
16731
  recordSentryProjectContext(projectInfo, rootSentrySpan);
16732
+ recordCount(METRIC.projectDetected, 1);
16373
16733
  if (options.scoreOnly || options.suppressRendering) return;
16374
16734
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
16375
16735
  yield* printProjectDetection({
@@ -16388,9 +16748,12 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16388
16748
  else runConsole(Console.error(highlighter.error(lintFailureReason)));
16389
16749
  const inspectDiagnostics = output.diagnostics;
16390
16750
  const score = didLintFail ? null : output.score;
16751
+ const elapsedMilliseconds = performance.now() - startTime;
16752
+ const forceOnboarding = isOnboardingForced();
16753
+ const paceOnboardingSections = !options.silent && !options.scoreOnly && !options.suppressRendering && !options.verbose && canAnimateOnboarding(process.stdout) && (forceOnboarding || !hasCompletedOnboarding());
16391
16754
  const finalizeInput = {
16392
16755
  options,
16393
- elapsedMilliseconds: performance.now() - startTime,
16756
+ elapsedMilliseconds,
16394
16757
  diagnostics: inspectDiagnostics,
16395
16758
  score,
16396
16759
  project: output.project,
@@ -16405,7 +16768,27 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16405
16768
  scannedFilePaths: output.scannedFilePaths,
16406
16769
  scanElapsedMilliseconds: output.scanElapsedMilliseconds
16407
16770
  };
16408
- return await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16771
+ const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16772
+ if (shouldRecordOnboarding({
16773
+ paceOnboardingSections,
16774
+ forceOnboarding,
16775
+ verbose: options.verbose,
16776
+ isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
16777
+ })) markOnboardingComplete();
16778
+ recordScanMetrics({
16779
+ result,
16780
+ mode: isDiffMode ? "diff" : "full",
16781
+ parallel: options.concurrency !== void 0,
16782
+ workerCount: options.concurrency,
16783
+ lint: options.lint,
16784
+ deadCode: options.deadCode,
16785
+ scoreOnly: options.scoreOnly,
16786
+ noScore: options.noScore,
16787
+ didLintFail,
16788
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
16789
+ didDeadCodeFail: output.didDeadCodeFail
16790
+ });
16791
+ return result;
16409
16792
  };
16410
16793
  const finalizeAndRender = (input) => Effect.gen(function* () {
16411
16794
  const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
@@ -16435,16 +16818,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16435
16818
  else yield* Console.log(highlighter.gray(noScoreMessage));
16436
16819
  return buildResult();
16437
16820
  }
16821
+ const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
16822
+ const pause = onboardingSectionPause(animateRender);
16438
16823
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
16439
16824
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
16440
16825
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
16441
16826
  if (surfaceDiagnostics.length === 0) {
16827
+ yield* pause;
16442
16828
  if (hasSkippedChecks) {
16443
16829
  const skippedLabel = skippedChecks.join(" and ");
16444
16830
  yield* Console.warn(highlighter.warn(`No issues detected, but ${skippedLabel} checks failed — results are incomplete.`));
16445
16831
  } else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
16446
16832
  else yield* Console.log(highlighter.success("No issues found!"));
16447
16833
  yield* Console.log("");
16834
+ yield* pause;
16448
16835
  if (hasSkippedChecks) {
16449
16836
  yield* printBrandingOnlyHeader;
16450
16837
  yield* Console.log(highlighter.gray(" Score not shown — some checks could not complete."));
@@ -16452,8 +16839,12 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16452
16839
  else yield* printNoScoreHeader(noScoreMessage);
16453
16840
  return buildResult();
16454
16841
  }
16842
+ yield* pause;
16455
16843
  yield* Console.log("");
16456
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment());
16844
+ yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
16845
+ sectionPause: pause,
16846
+ animateCountUp: animateRender
16847
+ });
16457
16848
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
16458
16849
  if (demotedDiagnosticCount > 0) {
16459
16850
  yield* Console.log(highlighter.gray(` ${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface (e.g. design cleanup) — run \`npx react-doctor@latest .\` locally for the full list.`));
@@ -16461,24 +16852,29 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16461
16852
  }
16462
16853
  const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
16463
16854
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
16855
+ yield* pause;
16464
16856
  yield* printSummary({
16465
16857
  diagnostics: [...surfaceDiagnostics],
16466
16858
  elapsedMilliseconds,
16467
16859
  scoreResult: score,
16468
16860
  potentialScore,
16469
- projectName: project.projectName,
16470
16861
  totalSourceFileCount: lintSourceFileCount,
16471
16862
  noScoreMessage,
16472
- isOffline: !shouldShowShareLink,
16473
- verbose: options.verbose
16863
+ verbose: options.verbose,
16864
+ animateProjection: animateRender
16474
16865
  });
16475
16866
  if (hasSkippedChecks) {
16476
16867
  const skippedLabel = skippedChecks.join(" and ");
16477
16868
  yield* Console.log("");
16478
16869
  yield* Console.warn(highlighter.warn(` Note: ${skippedLabel} checks failed — score may be incomplete.`));
16479
16870
  }
16480
- yield* printVerboseTip([...surfaceDiagnostics], options.verbose);
16481
- yield* printDocsNote();
16871
+ yield* pause;
16872
+ yield* printFooter({
16873
+ diagnostics: [...surfaceDiagnostics],
16874
+ scoreResult: score,
16875
+ projectName: project.projectName,
16876
+ isOffline: !shouldShowShareLink
16877
+ });
16482
16878
  return buildResult();
16483
16879
  });
16484
16880
  //#endregion
@@ -16589,6 +16985,21 @@ const handleError = (error, options = {}) => {
16589
16985
  if (options.shouldExit !== false) process.exit(1);
16590
16986
  process.exitCode = 1;
16591
16987
  };
16988
+ /**
16989
+ * Renderer for expected, user-actionable failures — a bad `--diff` value or
16990
+ * a base branch that isn't fetched. Prints just the (already human-readable)
16991
+ * message — no "Something went wrong", prefilled issue, Discord link, or
16992
+ * Sentry reference — because there is no bug to report.
16993
+ */
16994
+ const handleUserError = (error, options = {}) => {
16995
+ Effect.runSync(Effect.gen(function* () {
16996
+ yield* Console.error("");
16997
+ yield* Console.error(highlighter.error(formatErrorForReport(error)));
16998
+ yield* Console.error("");
16999
+ }));
17000
+ if (options.shouldExit !== false) process.exit(1);
17001
+ process.exitCode = 1;
17002
+ };
16592
17003
  //#endregion
16593
17004
  //#region src/cli/utils/build-handoff-payload.ts
16594
17005
  const buildHandoffPayload = (input) => {
@@ -17597,11 +18008,17 @@ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) =>
17597
18008
  projectRoot,
17598
18009
  runner: dependencyRunner
17599
18010
  });
18011
+ recordCount(METRIC.installDependency, 1, {
18012
+ status: dependencyResult.dependencyStatus,
18013
+ reason: dependencyResult.dependencyReason ?? null,
18014
+ packageManager: detectPackageManager(projectRoot)
18015
+ });
17600
18016
  if (dependencyResult.dependencyStatus === "skipped") {
17601
18017
  dependencySpinner.fail(formatDependencyInstallMessage(dependencyResult));
17602
- return;
18018
+ return dependencyResult;
17603
18019
  }
17604
18020
  dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
18021
+ return dependencyResult;
17605
18022
  } catch (error) {
17606
18023
  dependencySpinner.fail("Failed to install React Doctor package.");
17607
18024
  throw error;
@@ -17769,7 +18186,7 @@ const runInstallReactDoctor = async (options = {}) => {
17769
18186
  } catch {
17770
18187
  cliLogger.dim(" Skipped bundled sibling skills (install error).");
17771
18188
  }
17772
- await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
18189
+ const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
17773
18190
  if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
17774
18191
  const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
17775
18192
  try {
@@ -17780,6 +18197,7 @@ const runInstallReactDoctor = async (options = {}) => {
17780
18197
  hooksPathConfig: gitHookTarget.hooksPathConfig
17781
18198
  });
17782
18199
  hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
18200
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
17783
18201
  } catch (error) {
17784
18202
  hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
17785
18203
  throw error;
@@ -17793,7 +18211,10 @@ const runInstallReactDoctor = async (options = {}) => {
17793
18211
  agents: selectedAgents
17794
18212
  });
17795
18213
  if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
17796
- else hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18214
+ else {
18215
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18216
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
18217
+ }
17797
18218
  } catch (error) {
17798
18219
  hookSpinner.fail("Failed to install React Doctor agent hooks.");
17799
18220
  throw error;
@@ -17805,11 +18226,21 @@ const runInstallReactDoctor = async (options = {}) => {
17805
18226
  try {
17806
18227
  writeFileSync(workflowTargetPath, buildWorkflowContent());
17807
18228
  workflowSpinner.succeed(`GitHub Actions workflow added at ${path.relative(projectRoot, workflowTargetPath)}.`);
18229
+ recordCount(METRIC.installWorkflow, 1);
17808
18230
  } catch (error) {
17809
18231
  workflowSpinner.fail("Failed to add GitHub Actions workflow.");
17810
18232
  throw error;
17811
18233
  }
17812
18234
  }
18235
+ recordCount(METRIC.installCompleted, 1, {
18236
+ agentsCount: selectedAgents.length,
18237
+ gitHook: shouldInstallGitHook,
18238
+ agentHooks: shouldInstallAgentHooks,
18239
+ workflow: shouldInstallWorkflow,
18240
+ dependencyStatus: dependencyResult.dependencyStatus,
18241
+ packageManager: detectPackageManager(projectRoot)
18242
+ });
18243
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
17813
18244
  };
17814
18245
  //#endregion
17815
18246
  //#region src/cli/utils/install-skill-for-agent.ts
@@ -17880,7 +18311,6 @@ const copyToClipboard = (text) => {
17880
18311
  //#endregion
17881
18312
  //#region src/cli/utils/handoff-to-agent.ts
17882
18313
  const CLIPBOARD_CHOICE = "clipboard";
17883
- const PRINT_CHOICE = "print";
17884
18314
  const SKIP_CHOICE = "skip";
17885
18315
  const printPayload = (payload) => {
17886
18316
  cliLogger.break();
@@ -17894,10 +18324,11 @@ const detectLaunchableAgents = async () => {
17894
18324
  };
17895
18325
  const handoffToAgent = async (input) => {
17896
18326
  if (!input.interactive || input.diagnostics.length === 0) return;
18327
+ cliLogger.break();
17897
18328
  const { handoffTarget } = await prompts({
17898
18329
  type: "select",
17899
18330
  name: "handoffTarget",
17900
- message: "Hand these issues to an agent?",
18331
+ message: "Would you like to spawn an agent to fix these issues?",
17901
18332
  choices: [
17902
18333
  ...(await detectLaunchableAgents()).map((agentId) => ({
17903
18334
  title: getSkillAgentConfig(agentId).displayName,
@@ -17909,11 +18340,6 @@ const handoffToAgent = async (input) => {
17909
18340
  description: "Paste into any agent or chat",
17910
18341
  value: CLIPBOARD_CHOICE
17911
18342
  },
17912
- {
17913
- title: "Print prompt",
17914
- description: "Show the prompt below",
17915
- value: PRINT_CHOICE
17916
- },
17917
18343
  {
17918
18344
  title: "Skip",
17919
18345
  description: "Don't hand off",
@@ -17922,15 +18348,20 @@ const handoffToAgent = async (input) => {
17922
18348
  ],
17923
18349
  initial: 0
17924
18350
  }, { onCancel: () => true });
18351
+ let handoffOutcome = "launch";
18352
+ if (handoffTarget === void 0) handoffOutcome = "cancel";
18353
+ else if (handoffTarget === SKIP_CHOICE) handoffOutcome = "skip";
18354
+ else if (handoffTarget === CLIPBOARD_CHOICE) handoffOutcome = "clipboard";
18355
+ recordCount(METRIC.agentHandoff, 1, {
18356
+ outcome: handoffOutcome,
18357
+ agent: handoffOutcome === "launch" ? handoffTarget : void 0,
18358
+ diagnosticsCount: input.diagnostics.length
18359
+ });
17925
18360
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
17926
18361
  const payload = buildHandoffPayload({
17927
18362
  diagnostics: input.diagnostics,
17928
18363
  projectName: input.projectName
17929
18364
  });
17930
- if (handoffTarget === PRINT_CHOICE) {
17931
- printPayload(payload);
17932
- return;
17933
- }
17934
18365
  if (handoffTarget === CLIPBOARD_CHOICE) {
17935
18366
  if (await copyToClipboard(payload)) cliLogger.log("Copied the prompt to your clipboard.");
17936
18367
  else printPayload(payload);
@@ -18047,6 +18478,35 @@ const printBrandedHeader = Effect.gen(function* () {
18047
18478
  yield* Console.log("");
18048
18479
  });
18049
18480
  //#endregion
18481
+ //#region src/cli/utils/render-welcome.ts
18482
+ const HAPPY_FACE_LINES = [
18483
+ "┌─────┐",
18484
+ "│ ◠ ◠ │",
18485
+ "│ ▽ │",
18486
+ "└─────┘"
18487
+ ];
18488
+ const typeLine = (linePrefix, text, style) => Effect.gen(function* () {
18489
+ const characters = [...text];
18490
+ for (let length = 1; length <= characters.length; length += 1) {
18491
+ yield* writeStdout(`\r${linePrefix}${style(characters.slice(0, length).join(""))}\x1b[K`);
18492
+ yield* Effect.sleep(32);
18493
+ }
18494
+ });
18495
+ const playWelcomeScene = () => Effect.gen(function* () {
18496
+ const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
18497
+ const mouthPrefix = ` ${face[2] ?? ""} `;
18498
+ yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
18499
+ yield* writeStdout("\x1B[3A");
18500
+ yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment));
18501
+ yield* Effect.sleep(500);
18502
+ yield* writeStdout("\x1B[1B");
18503
+ yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment));
18504
+ yield* Effect.sleep(WELCOME_EXPLANATION_HOLD_MS);
18505
+ yield* typeLine(mouthPrefix, "Let's scan your codebase...", (fragment) => highlighter.dim(fragment));
18506
+ yield* Effect.sleep(WELCOME_HOLD_MS);
18507
+ yield* writeStdout("\x1B[3A\r\x1B[0J");
18508
+ });
18509
+ //#endregion
18050
18510
  //#region src/cli/utils/report-error.ts
18051
18511
  /**
18052
18512
  * Sends an error to Sentry — enriched with a fresh snapshot of the current run
@@ -18067,6 +18527,13 @@ const reportErrorToSentry = async (error) => {
18067
18527
  if (!Sentry.isInitialized()) return void 0;
18068
18528
  try {
18069
18529
  const { tags, contexts } = buildSentryScope();
18530
+ let reason = "unknown";
18531
+ if (isReactDoctorError(error)) reason = error.reason._tag;
18532
+ else if (error instanceof Error) reason = error.name;
18533
+ recordCount(METRIC.cliError, 1, {
18534
+ command: typeof tags.command === "string" ? tags.command : void 0,
18535
+ reason
18536
+ });
18070
18537
  const runTrace = getActiveRunTrace();
18071
18538
  const eventId = Sentry.withScope((scope) => {
18072
18539
  for (const [name, context] of Object.entries(contexts)) scope.setContext(name, context);
@@ -18136,7 +18603,7 @@ const findLowestScoredScan = (completedScans) => {
18136
18603
  return scoredScans.reduce((worst, scan) => scan.result.score.score < worst.result.score.score ? scan : worst);
18137
18604
  };
18138
18605
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
18139
- const { completedScans, userConfig, verbose } = input;
18606
+ const { completedScans, userConfig, verbose, isOffline, projectName } = input;
18140
18607
  const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
18141
18608
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
18142
18609
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
@@ -18163,10 +18630,8 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
18163
18630
  elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
18164
18631
  scoreResult: aggregateScore,
18165
18632
  potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
18166
- projectName: completedScans.map((scan) => scan.result.project.projectName).join(", "),
18167
18633
  totalSourceFileCount,
18168
18634
  noScoreMessage: "Score unavailable.",
18169
- isOffline: true,
18170
18635
  verbose
18171
18636
  });
18172
18637
  const entries = completedScans.map((scan) => {
@@ -18181,9 +18646,12 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
18181
18646
  const longestProjectNameLength = Math.max(...entries.map((entry) => entry.projectName.length));
18182
18647
  yield* Console.log("");
18183
18648
  for (const entry of entries) yield* Console.log(buildSummaryLine(entry, longestProjectNameLength));
18184
- yield* Console.log("");
18185
- yield* printVerboseTip(surfaceDiagnostics, verbose);
18186
- yield* printDocsNote();
18649
+ yield* printFooter({
18650
+ diagnostics: surfaceDiagnostics,
18651
+ scoreResult: aggregateScore,
18652
+ projectName,
18653
+ isOffline
18654
+ });
18187
18655
  });
18188
18656
  //#endregion
18189
18657
  //#region src/cli/utils/prompt-install-setup.ts
@@ -18233,31 +18701,13 @@ const printAgentInstallHint = (writeLine = defaultWriteLine) => {
18233
18701
  //#endregion
18234
18702
  //#region src/cli/utils/resolve-parallel-flag.ts
18235
18703
  /**
18236
- * Translates the `--experimental-parallel [workers]` flag into a concrete
18237
- * worker count for `InspectOptions.concurrency`:
18238
- *
18239
- * - flag absent (`undefined`) → `undefined` (defer to the ambient
18240
- * default: serial unless `REACT_DOCTOR_PARALLEL` is set)
18241
- * - bare flag / `auto` → auto-detect CPU cores
18242
- * - `--experimental-parallel <n>` → `n` workers (clamped)
18243
- * - `false` / `off` / `0` → serial (an explicit opt-out, so
18244
- * it overrides an env-enabled default rather than deferring to it)
18245
- * - an unparseable value → auto-detect cores
18246
- *
18247
- * Commander yields `true` for a bare flag, the raw string for an explicit
18248
- * value, and `undefined` when the flag is omitted.
18704
+ * Maps the `--no-parallel` flag to an `InspectOptions.concurrency` value.
18705
+ * `--no-parallel` (`parallel === false`) pins serial, overriding any
18706
+ * env-enabled default; otherwise `undefined` defers to the ambient
18707
+ * `OxlintConcurrency` default (parallel, unless `REACT_DOCTOR_PARALLEL`
18708
+ * sets a worker count — the flag itself no longer takes one).
18249
18709
  */
18250
- const resolveParallelFlag = (parallel) => {
18251
- if (parallel === void 0) return void 0;
18252
- if (parallel === true) return resolveScanConcurrency("auto");
18253
- if (parallel === false) return 1;
18254
- const normalized = parallel.trim().toLowerCase();
18255
- if (normalized === "" || normalized === "auto" || normalized === "true") return resolveScanConcurrency("auto");
18256
- if (normalized === "false" || normalized === "off" || normalized === "0") return 1;
18257
- const parsed = Number.parseInt(normalized, 10);
18258
- if (!Number.isInteger(parsed) || parsed <= 0) return resolveScanConcurrency("auto");
18259
- return resolveScanConcurrency(parsed);
18260
- };
18710
+ const resolveParallelFlag = (parallel) => parallel === false ? 1 : void 0;
18261
18711
  //#endregion
18262
18712
  //#region src/cli/utils/resolve-cli-inspect-options.ts
18263
18713
  /**
@@ -18285,7 +18735,7 @@ const resolveCliInspectOptions = (flags, userConfig) => {
18285
18735
  isCi: isCiEnvironment(),
18286
18736
  silent: Boolean(flags.json),
18287
18737
  outputSurface: flags.prComment ? "prComment" : "cli",
18288
- concurrency: resolveParallelFlag(flags.experimentalParallel)
18738
+ concurrency: resolveParallelFlag(flags.parallel)
18289
18739
  };
18290
18740
  };
18291
18741
  //#endregion
@@ -18518,7 +18968,7 @@ const runExplain = async (fileLineArgument, context) => {
18518
18968
  }
18519
18969
  for (const diagnostic of matchingDiagnostics) {
18520
18970
  const ruleIdentifier = `${diagnostic.plugin}/${diagnostic.rule}`;
18521
- const severitySymbol = diagnostic.severity === "error" ? "✗" : "⚠";
18971
+ const severitySymbol = diagnostic.severity === "error" ? "✖" : "⚠";
18522
18972
  const colorizedRule = colorizeRuleByDiagnostic(ruleIdentifier, diagnostic.severity);
18523
18973
  const severityLabel = colorizeRuleByDiagnostic(diagnostic.severity, diagnostic.severity);
18524
18974
  cliLogger.log(`${severitySymbol} ${colorizedRule} ${highlighter.dim(`(${severityLabel})`)} — ${diagnostic.message}`);
@@ -18612,6 +19062,7 @@ const inspectAction = async (directory, flags) => {
18612
19062
  compact: Boolean(flags.jsonCompact),
18613
19063
  directory: requestedDirectory
18614
19064
  });
19065
+ recordCount(METRIC.cliInvoked, 1, { command: "inspect" });
18615
19066
  try {
18616
19067
  validateModeFlags(flags);
18617
19068
  maybeMigrateLegacyConfig(requestedDirectory, {
@@ -18636,7 +19087,8 @@ const inspectAction = async (directory, flags) => {
18636
19087
  });
18637
19088
  return;
18638
19089
  }
18639
- if (!isQuiet) Effect.runSync(printBrandedHeader);
19090
+ if (!isQuiet) if ((isOnboardingForced() || !hasCompletedOnboarding()) && canAnimateOnboarding(process.stdout)) await Effect.runPromise(playWelcomeScene());
19091
+ else Effect.runSync(printBrandedHeader);
18640
19092
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
18641
19093
  const skipPrompts = shouldSkipPrompts({
18642
19094
  yes: flags.yes,
@@ -18751,11 +19203,16 @@ const inspectAction = async (directory, flags) => {
18751
19203
  });
18752
19204
  if (!isQuiet && !isMultiProject) cliLogger.break();
18753
19205
  }
18754
- if (!isQuiet && isMultiProject && completedScans.length > 0) await Effect.runPromise(printMultiProjectSummary({
18755
- completedScans,
18756
- userConfig,
18757
- verbose: Boolean(flags.verbose)
18758
- }));
19206
+ if (!isQuiet && isMultiProject && completedScans.length > 0) {
19207
+ const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
19208
+ await Effect.runPromise(printMultiProjectSummary({
19209
+ completedScans,
19210
+ userConfig,
19211
+ verbose: Boolean(flags.verbose),
19212
+ isOffline: !shouldShowShareLink,
19213
+ projectName: path.basename(resolvedDirectory)
19214
+ }));
19215
+ }
18759
19216
  finalizeScans({
18760
19217
  diagnostics: allDiagnostics,
18761
19218
  completedScans,
@@ -18789,21 +19246,30 @@ const inspectAction = async (directory, flags) => {
18789
19246
  isJsonMode,
18790
19247
  isScoreOnly,
18791
19248
  isStaged: Boolean(flags.staged)
18792
- })) printAgentInstallHint();
19249
+ })) {
19250
+ printAgentInstallHint();
19251
+ recordCount(METRIC.agentInstallHintShown, 1);
19252
+ }
18793
19253
  }
18794
19254
  } catch (error) {
18795
- const sentryEventId = await reportErrorToSentry(error);
19255
+ const isUserError = isReactDoctorError(error) && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
19256
+ const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
18796
19257
  if (isJsonMode) {
18797
19258
  writeJsonErrorReport(error);
18798
19259
  process.exitCode = 1;
18799
19260
  return;
18800
19261
  }
19262
+ if (isUserError) {
19263
+ handleUserError(error);
19264
+ return;
19265
+ }
18801
19266
  handleError(error, { sentryEventId });
18802
19267
  }
18803
19268
  };
18804
19269
  //#endregion
18805
19270
  //#region src/cli/commands/install.ts
18806
19271
  const installAction = async (options, command) => {
19272
+ recordCount(METRIC.cliInvoked, 1, { command: "install" });
18807
19273
  Effect.runSync(printBrandedHeader);
18808
19274
  try {
18809
19275
  const parentOptions = command?.parent?.opts?.();
@@ -19124,6 +19590,7 @@ const SEVERITY_VALUES = [
19124
19590
  "warn",
19125
19591
  "error"
19126
19592
  ];
19593
+ const recordRulesInvocation = () => recordCount(METRIC.cliInvoked, 1, { command: "rules" });
19127
19594
  const resolveProjectRoot = (options) => {
19128
19595
  const requestedDirectory = path.resolve(options.cwd ?? process.cwd());
19129
19596
  return findNearestPackageDirectory(requestedDirectory) ?? requestedDirectory;
@@ -19166,6 +19633,11 @@ const reportManualEdit = (target, nextConfig) => {
19166
19633
  process.exitCode = 1;
19167
19634
  };
19168
19635
  const rulesListAction = async (options) => {
19636
+ recordRulesInvocation();
19637
+ recordCount(METRIC.rulesQueried, 1, {
19638
+ subcommand: "list",
19639
+ hadFilter: Boolean(options.category || options.tag || options.framework || options.configured)
19640
+ });
19169
19641
  const catalog = buildRuleCatalog();
19170
19642
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
19171
19643
  const categoryFilter = options.category?.toLowerCase();
@@ -19197,6 +19669,8 @@ const rulesListAction = async (options) => {
19197
19669
  cliLogger.log(renderRuleCatalog(rows));
19198
19670
  };
19199
19671
  const rulesExplainAction = async (ruleQuery, options) => {
19672
+ recordRulesInvocation();
19673
+ recordCount(METRIC.rulesQueried, 1, { subcommand: "explain" });
19200
19674
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19201
19675
  if (!entry) {
19202
19676
  reportRuleNotFound(ruleQuery);
@@ -19224,7 +19698,7 @@ const rulesExplainAction = async (ruleQuery, options) => {
19224
19698
  effective
19225
19699
  }));
19226
19700
  };
19227
- const setRuleSeverityAndReport = async (entry, severity, options) => {
19701
+ const setRuleSeverityAndReport = async (entry, severity, options, action) => {
19228
19702
  const { target, nextConfig, written } = await applyConfigChange(options, (config) => setRuleSeverity(config, entry.key, severity));
19229
19703
  if (!written) {
19230
19704
  reportManualEdit(target, nextConfig);
@@ -19232,8 +19706,14 @@ const setRuleSeverityAndReport = async (entry, severity, options) => {
19232
19706
  }
19233
19707
  cliLogger.success(`Set ${entry.key} → ${severity}`);
19234
19708
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19709
+ recordCount(METRIC.rulesChanged, 1, {
19710
+ action,
19711
+ severity,
19712
+ target: entry.key
19713
+ });
19235
19714
  };
19236
19715
  const rulesSetAction = async (ruleQuery, severityValue, options) => {
19716
+ recordRulesInvocation();
19237
19717
  const severity = parseSeverity(severityValue);
19238
19718
  if (!severity) {
19239
19719
  reportInvalidSeverity(severityValue);
@@ -19244,16 +19724,17 @@ const rulesSetAction = async (ruleQuery, severityValue, options) => {
19244
19724
  reportRuleNotFound(ruleQuery);
19245
19725
  return;
19246
19726
  }
19247
- await setRuleSeverityAndReport(entry, severity, options);
19727
+ await setRuleSeverityAndReport(entry, severity, options, "set");
19248
19728
  };
19249
19729
  const rulesEnableAction = async (ruleQuery, options) => {
19730
+ recordRulesInvocation();
19250
19731
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19251
19732
  if (!entry) {
19252
19733
  reportRuleNotFound(ruleQuery);
19253
19734
  return;
19254
19735
  }
19255
19736
  if (options.severity === void 0) {
19256
- await setRuleSeverityAndReport(entry, entry.defaultSeverity, options);
19737
+ await setRuleSeverityAndReport(entry, entry.defaultSeverity, options, "enable");
19257
19738
  return;
19258
19739
  }
19259
19740
  const severity = parseSeverity(options.severity);
@@ -19266,17 +19747,19 @@ const rulesEnableAction = async (ruleQuery, options) => {
19266
19747
  process.exitCode = 1;
19267
19748
  return;
19268
19749
  }
19269
- await setRuleSeverityAndReport(entry, severity, options);
19750
+ await setRuleSeverityAndReport(entry, severity, options, "enable");
19270
19751
  };
19271
19752
  const rulesDisableAction = async (ruleQuery, options) => {
19753
+ recordRulesInvocation();
19272
19754
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19273
19755
  if (!entry) {
19274
19756
  reportRuleNotFound(ruleQuery);
19275
19757
  return;
19276
19758
  }
19277
- await setRuleSeverityAndReport(entry, "off", options);
19759
+ await setRuleSeverityAndReport(entry, "off", options, "disable");
19278
19760
  };
19279
19761
  const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19762
+ recordRulesInvocation();
19280
19763
  const severity = parseSeverity(severityValue);
19281
19764
  if (!severity) {
19282
19765
  reportInvalidSeverity(severityValue);
@@ -19297,8 +19780,14 @@ const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19297
19780
  }
19298
19781
  cliLogger.success(`Set category "${matchedCategory}" → ${severity}`);
19299
19782
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19783
+ recordCount(METRIC.rulesChanged, 1, {
19784
+ action: "category",
19785
+ severity,
19786
+ target: matchedCategory
19787
+ });
19300
19788
  };
19301
19789
  const rulesIgnoreTagAction = async (tag, options) => {
19790
+ recordRulesInvocation();
19302
19791
  const knownTags = listRuleTags(buildRuleCatalog());
19303
19792
  if (!knownTags.includes(tag)) {
19304
19793
  cliLogger.error(`Unknown tag "${tag}".`);
@@ -19313,8 +19802,13 @@ const rulesIgnoreTagAction = async (tag, options) => {
19313
19802
  }
19314
19803
  cliLogger.success(`Ignoring tag "${tag}" (rules with this tag are skipped before linting)`);
19315
19804
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19805
+ recordCount(METRIC.rulesChanged, 1, {
19806
+ action: "ignoreTag",
19807
+ target: tag
19808
+ });
19316
19809
  };
19317
19810
  const rulesUnignoreTagAction = async (tag, options) => {
19811
+ recordRulesInvocation();
19318
19812
  const target = await resolveRuleConfigTarget(resolveProjectRoot(options));
19319
19813
  if (!(target.config.ignore?.tags ?? []).includes(tag)) {
19320
19814
  cliLogger.dim(`Tag "${tag}" was not being ignored; nothing to change.`);
@@ -19328,6 +19822,10 @@ const rulesUnignoreTagAction = async (tag, options) => {
19328
19822
  }
19329
19823
  cliLogger.success(`Tag "${tag}" is no longer ignored`);
19330
19824
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19825
+ recordCount(METRIC.rulesChanged, 1, {
19826
+ action: "unignoreTag",
19827
+ target: tag
19828
+ });
19331
19829
  };
19332
19830
  //#endregion
19333
19831
  //#region src/cli/commands/version.ts
@@ -19340,6 +19838,7 @@ const rulesUnignoreTagAction = async (tag, options) => {
19340
19838
  */
19341
19839
  const buildVersionString = () => `react-doctor/${VERSION} ${process.platform}-${process.arch} node-${process.version}`;
19342
19840
  const versionAction = () => {
19841
+ recordCount(METRIC.cliInvoked, 1, { command: "version" });
19343
19842
  process.stdout.write(`${buildVersionString()}\n`);
19344
19843
  };
19345
19844
  //#endregion
@@ -19434,6 +19933,7 @@ const ROOT_FLAG_SPEC = {
19434
19933
  "--no-color",
19435
19934
  "--no-dead-code",
19436
19935
  "--no-lint",
19936
+ "--no-parallel",
19437
19937
  "--no-respect-inline-disables",
19438
19938
  "--no-score",
19439
19939
  "--no-telemetry",
@@ -19454,7 +19954,7 @@ const ROOT_FLAG_SPEC = {
19454
19954
  "--project",
19455
19955
  "--why"
19456
19956
  ]),
19457
- longOptionsWithOptionalValues: new Set(["--diff", "--experimental-parallel"]),
19957
+ longOptionsWithOptionalValues: new Set(["--diff"]),
19458
19958
  shortOptionsWithoutValues: new Set([
19459
19959
  "-h",
19460
19960
  "-v",
@@ -19621,7 +20121,7 @@ ${formatExampleLines([
19621
20121
  ${highlighter.dim("Learn more:")}
19622
20122
  ${highlighter.info(CANONICAL_GITHUB_URL)}
19623
20123
  `;
19624
- const program = new Command().name("react-doctor").description("Diagnose React codebase health").version(VERSION, "-v, --version", "display the version number").argument("[directory]", "project directory to scan", ".").option("--lint", "enable linting").option("--no-lint", "skip linting").option("--dead-code", "enable dead-code analysis (default)").option("--no-dead-code", "skip dead-code analysis (unused files / exports / dependencies, circular imports)").option("--verbose", "show every rule and per-file details (default shows top 3 rules)").option("--score", "output only the score").option("--json", "output a single structured JSON report (suppresses other output)").option("--json-compact", "with --json, emit compact JSON (no indentation)").option("-y, --yes", "skip prompts, scan all workspace projects").option("--full", "force a full scan (overrides any `diff` value in config or `--diff`)").option("--experimental-parallel [workers]", "experimental: lint with N parallel workers (default: auto-detect CPU cores) — speeds up large repos").option("--project <name>", "select workspace project (comma-separated for multiple)").option("--diff [base]", "scan only files changed vs base branch (pass `false` to disable; overridden by --full)").option("--changed-files-from <file>", "internal: scan source files listed in a newline-delimited changed-files file").option("--no-score", "skip the score API, the share URL, and crash reporting").option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--fail-on <level>", "exit with error code on diagnostics: error, warning, none (default: none)").option("--annotations", "output diagnostics as GitHub Actions annotations").option("--pr-comment", "tune CLI output for sticky PR comments (drops weak-signal rule families like `design` from the printed list and the fail-on gate; configure via config.surfaces)").option("--explain <file:line>", "diagnose why a rule fired or why a suppression didn't apply at a specific location").option("--why <file:line>", "alias for --explain").option("--respect-inline-disables", "respect inline `// eslint-disable*` / `// oxlint-disable*` comments (default)").option("--no-respect-inline-disables", "audit mode: neutralize inline lint suppressions before scanning").option("--warnings", "show warning-severity diagnostics (default)").option("--no-warnings", "hide warning-severity diagnostics (errors only)").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
20124
+ const program = new Command().name("react-doctor").description("Diagnose React codebase health").version(VERSION, "-v, --version", "display the version number").argument("[directory]", "project directory to scan", ".").option("--lint", "enable linting").option("--no-lint", "skip linting").option("--dead-code", "enable dead-code analysis (default)").option("--no-dead-code", "skip dead-code analysis (unused files / exports / dependencies, circular imports)").option("--verbose", "show every rule and per-file details (default shows top 3 rules)").option("--score", "output only the score").option("--json", "output a single structured JSON report (suppresses other output)").option("--json-compact", "with --json, emit compact JSON (no indentation)").option("-y, --yes", "skip prompts, scan all workspace projects").option("--full", "force a full scan (overrides any `diff` value in config or `--diff`)").option("--no-parallel", "lint serially with one worker (default: parallel across CPU cores; set the worker count with REACT_DOCTOR_PARALLEL)").option("--project <name>", "select workspace project (comma-separated for multiple)").option("--diff [base]", "scan only files changed vs base branch (pass `false` to disable; overridden by --full)").option("--changed-files-from <file>", "internal: scan source files listed in a newline-delimited changed-files file").option("--no-score", "skip the score API, the share URL, and crash reporting").option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--fail-on <level>", "exit with error code on diagnostics: error, warning, none (default: none)").option("--annotations", "output diagnostics as GitHub Actions annotations").option("--pr-comment", "tune CLI output for sticky PR comments (drops weak-signal rule families like `design` from the printed list and the fail-on gate; configure via config.surfaces)").option("--explain <file:line>", "diagnose why a rule fired or why a suppression didn't apply at a specific location").option("--why <file:line>", "alias for --explain").option("--respect-inline-disables", "respect inline `// eslint-disable*` / `// oxlint-disable*` comments (default)").option("--no-respect-inline-disables", "audit mode: neutralize inline lint suppressions before scanning").option("--warnings", "show warning-severity diagnostics (default)").option("--no-warnings", "hide warning-severity diagnostics (errors only)").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
19625
20125
  program.action(inspectAction);
19626
20126
  program.command("install").alias("setup").description("Install the react-doctor skill into your coding agents and optional git hook").option("-y, --yes", "skip prompts, install for all detected agents").option("--dry-run", "show what would be installed without writing files").option("--agent-hooks", "install native non-blocking agent hooks for Claude Code and Cursor").option("-c, --cwd <cwd>", "working directory", process.cwd()).option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderInstallHelpEpilog).action(installAction);
19627
20127
  program.command("version").description("show the version with Node and platform info").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").action(versionAction);
@@ -19657,4 +20157,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
19657
20157
  export {};
19658
20158
 
19659
20159
  //# sourceMappingURL=cli.js.map
19660
- //# debugId=32a62a68-f2f8-5b33-8780-72a601ba4ed1
20160
+ //# debugId=005f503a-c838-5177-8bea-002799f23989