react-doctor 0.2.15-dev.66f9d64 → 0.2.15-dev.bf4c21e

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]="d012dbb2-27e9-5092-9eab-c7fa4573f0b2")}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]="6e59d54f-a063-5355-9b76-f82556f70c89")}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";
@@ -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",
@@ -8975,6 +8978,11 @@ const trimOrNull = (value) => {
8975
8978
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
8976
8979
  */
8977
8980
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
8981
+ /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
8982
+ const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
8983
+ /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
8984
+ const DIFF_RANGE_OPERATOR = "..";
8985
+ const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
8978
8986
  const isSafeGitRevision = (candidate) => {
8979
8987
  if (candidate.length === 0) return false;
8980
8988
  if (candidate.startsWith("-")) return false;
@@ -8982,6 +8990,31 @@ const isSafeGitRevision = (candidate) => {
8982
8990
  if (candidate.includes("..") || candidate.includes("@{")) return false;
8983
8991
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
8984
8992
  };
8993
+ /**
8994
+ * Splits a git revision range into its endpoints: three-dot `A...B`
8995
+ * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
8996
+ * when `value` carries no range operator so the caller falls back to
8997
+ * single-base resolution.
8998
+ *
8999
+ * Only the first operator is split on; any leftover `..` stays inside an
9000
+ * endpoint so `isSafeGitRevision` rejects malformed input like
9001
+ * `A..B..C` instead of silently guessing which pair the user meant.
9002
+ */
9003
+ const parseGitDiffRange = (value) => {
9004
+ const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
9005
+ if (symmetricIndex !== -1) return {
9006
+ base: value.slice(0, symmetricIndex),
9007
+ head: value.slice(symmetricIndex + 3),
9008
+ symmetric: true
9009
+ };
9010
+ const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
9011
+ if (rangeIndex !== -1) return {
9012
+ base: value.slice(0, rangeIndex),
9013
+ head: value.slice(rangeIndex + 2),
9014
+ symmetric: false
9015
+ };
9016
+ return null;
9017
+ };
8985
9018
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
8986
9019
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
8987
9020
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -9133,6 +9166,49 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9133
9166
  if (result.status !== 0) return null;
9134
9167
  return parseGithubViewerPermission(result.stdout);
9135
9168
  }).pipe(Effect.catch(() => Effect.succeed(null)));
9169
+ /**
9170
+ * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
9171
+ * selection. Each endpoint is validated with `isSafeGitRevision`
9172
+ * BEFORE it reaches `git` (so the range syntax can't smuggle a
9173
+ * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
9174
+ * verified to exist, then the diff runs between the two commits with
9175
+ * the same `--diff-filter=ACMR` shape the single-base path uses.
9176
+ */
9177
+ const resolveDiffRange = (input) => Effect.gen(function* () {
9178
+ 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").` }) }));
9179
+ const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
9180
+ const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
9181
+ 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}).` }) }));
9182
+ for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
9183
+ let diffBaseRef = baseRef;
9184
+ if (input.range.symmetric) {
9185
+ const mergeBase = yield* runGit(input.directory, [
9186
+ "merge-base",
9187
+ baseRef,
9188
+ headRef
9189
+ ]);
9190
+ if (mergeBase.status !== 0) return null;
9191
+ const mergeBaseRef = trimOrNull(mergeBase.stdout);
9192
+ if (mergeBaseRef === null) return null;
9193
+ diffBaseRef = mergeBaseRef;
9194
+ }
9195
+ const diff = yield* runGit(input.directory, [
9196
+ "diff",
9197
+ "-z",
9198
+ "--name-only",
9199
+ "--diff-filter=ACMR",
9200
+ "--relative",
9201
+ diffBaseRef,
9202
+ headRef
9203
+ ]);
9204
+ if (diff.status !== 0) return null;
9205
+ return {
9206
+ currentBranch: yield* currentBranch(input.directory),
9207
+ baseBranch: baseRef,
9208
+ changedFiles: splitNullSeparated(diff.stdout),
9209
+ isCurrentChanges: false
9210
+ };
9211
+ });
9136
9212
  return Git.of({
9137
9213
  currentBranch,
9138
9214
  defaultBranch,
@@ -9142,7 +9218,15 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9142
9218
  branchExists,
9143
9219
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
9144
9220
  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 '@{').` }) }));
9221
+ if (explicitBaseBranch !== void 0) {
9222
+ const range = parseGitDiffRange(explicitBaseBranch);
9223
+ if (range !== null) return yield* resolveDiffRange({
9224
+ directory,
9225
+ range,
9226
+ raw: explicitBaseBranch
9227
+ });
9228
+ 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}).` }) }));
9229
+ }
9146
9230
  const resolvedCurrentBranch = yield* currentBranch(directory);
9147
9231
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
9148
9232
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -10451,6 +10535,21 @@ const spawnOxlint = (args, rootDirectory, nodeBinaryPath, spawnTimeoutMs = OXLIN
10451
10535
  resolve(output);
10452
10536
  });
10453
10537
  });
10538
+ const PARALLELISM_EXHAUSTION_ERROR_CODES = new Set([
10539
+ "EAGAIN",
10540
+ "EMFILE",
10541
+ "ENFILE",
10542
+ "ENOMEM"
10543
+ ]);
10544
+ const isParallelismRelatedSpawnError = (error) => {
10545
+ if (!(error instanceof ReactDoctorError)) return false;
10546
+ const { reason } = error;
10547
+ if (reason._tag !== "OxlintSpawnFailed") return false;
10548
+ const { cause } = reason;
10549
+ if (typeof cause !== "object" || cause === null || !("code" in cause)) return false;
10550
+ const { code } = cause;
10551
+ return typeof code === "string" && PARALLELISM_EXHAUSTION_ERROR_CODES.has(code);
10552
+ };
10454
10553
  /**
10455
10554
  * Runs every prebuilt file batch through oxlint, with binary-split
10456
10555
  * retry on the splittable error classes (timeout / output-too-large /
@@ -10459,66 +10558,83 @@ const spawnOxlint = (args, rootDirectory, nodeBinaryPath, spawnTimeoutMs = OXLIN
10459
10558
  * (surfaced via `onPartialFailure`) so JSON-mode consumers see WHICH
10460
10559
  * files were skipped instead of silently losing them.
10461
10560
  *
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.
10561
+ * Parallel runs (concurrency > 1) get one extra safety net: if the pass
10562
+ * fails with a resource-exhaustion error that's exclusive to running
10563
+ * many oxlint subprocesses at once (EAGAIN / EMFILE / ENFILE / ENOMEM —
10564
+ * see `isParallelismRelatedSpawnError`), the whole pass replays once
10565
+ * with a single worker. That's the only failure a serial replay can
10566
+ * clear, so every other error class is left to propagate.
10567
+ *
10568
+ * Errors that aren't splittable and aren't parallelism-related (oxlint
10569
+ * config crash, JS plugin resolution failure, etc.) propagate to the
10570
+ * caller — the `runOxlint` retry-without-extends fallback re-spawns this
10571
+ * loop with a slimmer config in that case.
10466
10572
  */
10467
10573
  const spawnLintBatches = async (input) => {
10468
10574
  const { baseArgs, fileBatches, rootDirectory, nodeBinaryPath, project, onPartialFailure, onFileProgress, spawnTimeoutMs, outputMaxBytes } = input;
10469
- const concurrency = resolveScanConcurrency(input.concurrency ?? 1);
10575
+ const requestedConcurrency = resolveScanConcurrency(input.concurrency ?? 1);
10470
10576
  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 [];
10577
+ const runBatchPass = async (concurrency) => {
10578
+ const allDiagnostics = [];
10579
+ const droppedFiles = [];
10580
+ let firstDropReason = null;
10581
+ const spawnLintBatch = async (batch) => {
10582
+ const batchArgs = [...baseArgs, ...batch];
10583
+ try {
10584
+ return parseOxlintOutput(await spawnOxlint(batchArgs, rootDirectory, nodeBinaryPath, spawnTimeoutMs, outputMaxBytes), project, rootDirectory);
10585
+ } catch (error) {
10586
+ if (!isSplittableReactDoctorError(error)) throw error;
10587
+ if (batch.length <= 1) {
10588
+ droppedFiles.push(...batch);
10589
+ if (firstDropReason === null) firstDropReason = error.message;
10590
+ return [];
10591
+ }
10592
+ const splitIndex = Math.ceil(batch.length / 2);
10593
+ return [...await spawnLintBatch(batch.slice(0, splitIndex)), ...await spawnLintBatch(batch.slice(splitIndex))];
10594
+ }
10595
+ };
10596
+ let startedFileCount = 0;
10597
+ let scannedFileCount = 0;
10598
+ let displayedFileCount = 0;
10599
+ const progressTimer = onFileProgress && totalFileCount > 1 ? setInterval(() => {
10600
+ const ceiling = Math.min(startedFileCount, totalFileCount - 1);
10601
+ if (displayedFileCount < ceiling) {
10602
+ displayedFileCount += 1;
10603
+ onFileProgress(displayedFileCount, totalFileCount);
10484
10604
  }
10485
- const splitIndex = Math.ceil(batch.length / 2);
10486
- return [...await spawnLintBatch(batch.slice(0, splitIndex)), ...await spawnLintBatch(batch.slice(splitIndex))];
10605
+ }, 50) : null;
10606
+ progressTimer?.unref?.();
10607
+ try {
10608
+ const batchResults = await mapWithConcurrency(fileBatches, concurrency, async (batch) => {
10609
+ startedFileCount += batch.length;
10610
+ const batchDiagnostics = await spawnLintBatch(batch);
10611
+ scannedFileCount += batch.length;
10612
+ if (onFileProgress) {
10613
+ displayedFileCount = Math.min(Math.max(displayedFileCount, scannedFileCount), totalFileCount);
10614
+ onFileProgress(displayedFileCount, totalFileCount);
10615
+ }
10616
+ return batchDiagnostics;
10617
+ });
10618
+ for (const batchDiagnostics of batchResults) allDiagnostics.push(...batchDiagnostics);
10619
+ } finally {
10620
+ if (progressTimer !== null) clearInterval(progressTimer);
10487
10621
  }
10622
+ if (droppedFiles.length > 0 && onPartialFailure) {
10623
+ const previewFiles = droppedFiles.slice(0, 3).join(", ");
10624
+ const remainderHint = droppedFiles.length > 3 ? `, +${droppedFiles.length - 3} more` : "";
10625
+ const reasonHint = firstDropReason ? ` — first failure: ${firstDropReason}` : "";
10626
+ onPartialFailure(`${droppedFiles.length} file(s) failed to lint and were skipped (${previewFiles}${remainderHint})${reasonHint}`);
10627
+ }
10628
+ return allDiagnostics;
10488
10629
  };
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?.();
10630
+ let diagnostics;
10500
10631
  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}`);
10632
+ diagnostics = await runBatchPass(requestedConcurrency);
10633
+ } catch (error) {
10634
+ if (requestedConcurrency <= 1 || !isParallelismRelatedSpawnError(error)) throw error;
10635
+ diagnostics = await runBatchPass(1);
10520
10636
  }
10521
- return dedupeDiagnostics(allDiagnostics);
10637
+ return dedupeDiagnostics(diagnostics);
10522
10638
  };
10523
10639
  let didValidate = false;
10524
10640
  /**
@@ -11524,12 +11640,13 @@ const buildSkippedChecks = (input) => {
11524
11640
  * Git service runs through Effect's `ChildProcess` (true subprocess
11525
11641
  * spawn, not `spawnSync`).
11526
11642
  *
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`.
11643
+ * Failures propagate as the tagged `ReactDoctorError` (rejected by
11644
+ * `Effect.runPromise`) rather than being flattened into a plain
11645
+ * `Error`. The message is unchanged — `ReactDoctorError.message`
11646
+ * defers to `reason.message` — so message-matching callers keep
11647
+ * working, while the CLI can now dispatch on `error.reason._tag` to
11648
+ * render diff-base mistakes (`GitBaseBranchInvalid` /
11649
+ * `GitBaseBranchMissing`) as clean user errors instead of crashes.
11533
11650
  */
11534
11651
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
11535
11652
  const selection = yield* (yield* Git).diffSelection({
@@ -11543,10 +11660,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
11543
11660
  changedFiles: [...selection.changedFiles],
11544
11661
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
11545
11662
  };
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
- })));
11663
+ }).pipe(Effect.provide(Git.layerNode)));
11550
11664
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
11551
11665
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
11552
11666
  let p = process || {}, argv = p.argv || [], env = p.env || {};
@@ -11760,6 +11874,33 @@ const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
11760
11874
  const INTERNAL_ERROR_JSON_FALLBACK = "{\"schemaVersion\":1,\"ok\":false,\"error\":{\"message\":\"Internal error\",\"name\":\"Error\",\"chain\":[]}}\n";
11761
11875
  const SENTRY_FLUSH_TIMEOUT_MS = 2e3;
11762
11876
  const NANOSECONDS_PER_SECOND = 1000000000n;
11877
+ const METRIC = {
11878
+ cliInvoked: "cli.invoked",
11879
+ cliError: "cli.error",
11880
+ projectDetected: "project.detected",
11881
+ scanCompleted: "scan.completed",
11882
+ scanDuration: "scan.duration",
11883
+ scanPhaseDuration: "scan.phase_duration",
11884
+ scanFiles: "scan.files",
11885
+ scanScore: "scan.score",
11886
+ scanClean: "scan.clean",
11887
+ scanCheckSkipped: "scan.check_skipped",
11888
+ ruleFired: "rule.fired",
11889
+ lintFailed: "lint.failed",
11890
+ deadCodeFailed: "deadcode.failed",
11891
+ scoreUnavailable: "score.unavailable",
11892
+ oxlintWorkers: "oxlint.workers",
11893
+ agentHandoff: "agent.handoff",
11894
+ agentInstallHintShown: "agent.install_hint_shown",
11895
+ installCompleted: "install.completed",
11896
+ installAgent: "install.agent",
11897
+ installGitHook: "install.git_hook",
11898
+ installWorkflow: "install.workflow",
11899
+ installAgentHooks: "install.agent_hooks",
11900
+ installDependency: "install.dependency",
11901
+ rulesChanged: "rules.changed",
11902
+ rulesQueried: "rules.queried"
11903
+ };
11763
11904
  //#endregion
11764
11905
  //#region src/cli/utils/noop-console.ts
11765
11906
  /**
@@ -11801,7 +11942,7 @@ const makeNoopConsole = () => ({
11801
11942
  });
11802
11943
  //#endregion
11803
11944
  //#region src/cli/utils/version.ts
11804
- const VERSION = "0.2.15-dev.66f9d64";
11945
+ const VERSION = "0.2.15-dev.bf4c21e";
11805
11946
  //#endregion
11806
11947
  //#region src/cli/utils/json-mode.ts
11807
11948
  let context = null;
@@ -12025,13 +12166,20 @@ const buildSentryScope = (runContext = buildRunContext()) => {
12025
12166
  };
12026
12167
  };
12027
12168
  //#endregion
12028
- //#region src/cli/utils/scrub-sentry-event.ts
12169
+ //#region src/cli/utils/anonymize-text.ts
12170
+ /**
12171
+ * Free-text fields can carry both a home-directory path (the OS username) and a
12172
+ * secret/email echoed from user code, so run both scrubbers: strip the username
12173
+ * from paths, then mask any known credential/PII shape. Shared by the Sentry
12174
+ * event scrubber ({@link scrubSentryEvent}) and metric scrubber
12175
+ * ({@link scrubSentryMetric}).
12176
+ */
12029
12177
  const anonymizeText = (text) => redactSensitiveText(scrubSensitivePaths(text));
12030
12178
  /**
12031
12179
  * Recursively rewrites every string within an arbitrary value (object / array /
12032
12180
  * 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.
12181
+ * unstructured corners of a Sentry payload (event contexts/extra/tags, breadcrumb
12182
+ * data, span attributes, metric attributes) where a path or secret could hide.
12035
12183
  */
12036
12184
  const anonymizeInPlace = (value) => {
12037
12185
  if (Array.isArray(value)) {
@@ -12049,6 +12197,8 @@ const anonymizeInPlace = (value) => {
12049
12197
  else anonymizeInPlace(inner);
12050
12198
  }
12051
12199
  };
12200
+ //#endregion
12201
+ //#region src/cli/utils/scrub-sentry-event.ts
12052
12202
  /**
12053
12203
  * Anonymizes a Sentry event (error or transaction) before it leaves the
12054
12204
  * machine. Strips identity the SDK attaches automatically — the IP-bearing
@@ -12096,6 +12246,27 @@ const scrubSentryEvent = (event) => {
12096
12246
  }
12097
12247
  };
12098
12248
  //#endregion
12249
+ //#region src/cli/utils/scrub-sentry-metric.ts
12250
+ /**
12251
+ * Anonymizes a Sentry metric before it leaves the machine, mirroring
12252
+ * {@link scrubSentryEvent}. Drops the `server.address` default attribute (the
12253
+ * hostname) and scrubs home-directory paths + known secrets/emails from every
12254
+ * remaining attribute value (metric names are our own constants, so they're
12255
+ * left intact to avoid splitting a series). Returns `null` on any failure so an
12256
+ * un-anonymized metric is never sent. Wired into `beforeSendMetric`.
12257
+ */
12258
+ const scrubSentryMetric = (metric) => {
12259
+ try {
12260
+ if (metric.attributes) {
12261
+ delete metric.attributes["server.address"];
12262
+ anonymizeInPlace(metric.attributes);
12263
+ }
12264
+ return metric;
12265
+ } catch {
12266
+ return null;
12267
+ }
12268
+ };
12269
+ //#endregion
12099
12270
  //#region src/instrument.ts
12100
12271
  let isInitialized = false;
12101
12272
  let resolvedTracesSampleRate = 0;
@@ -12117,13 +12288,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12117
12288
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12118
12289
  * standard `SENTRY_RELEASE` override.
12119
12290
  */
12120
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.66f9d64`;
12291
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.bf4c21e`;
12121
12292
  /**
12122
12293
  * Deployment environment shown in Sentry's environment filter. Defaults to
12123
12294
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12124
12295
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12125
12296
  */
12126
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.66f9d64") ? "development" : "production");
12297
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.bf4c21e") ? "development" : "production");
12127
12298
  /**
12128
12299
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12129
12300
  * (set to `0` to disable tracing) and falls back to
@@ -12191,7 +12362,8 @@ const initializeSentry = () => {
12191
12362
  contexts
12192
12363
  },
12193
12364
  beforeSend: (event) => scrubSentryEvent(event),
12194
- beforeSendTransaction: (event) => scrubSentryEvent(event)
12365
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
12366
+ beforeSendMetric: (metric) => scrubSentryMetric(metric)
12195
12367
  });
12196
12368
  };
12197
12369
  //#endregion
@@ -15463,6 +15635,122 @@ const recordSentryProjectContext = (projectInfo, rootSpan) => {
15463
15635
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
15464
15636
  };
15465
15637
  //#endregion
15638
+ //#region src/cli/utils/record-metric.ts
15639
+ const cleanAttributes = (attributes) => {
15640
+ const cleaned = {};
15641
+ if (!attributes) return cleaned;
15642
+ for (const [key, value] of Object.entries(attributes)) if (value !== null && value !== void 0) cleaned[key] = value;
15643
+ return cleaned;
15644
+ };
15645
+ const withRunAttributes = (attributes) => ({
15646
+ ...toSpanAttributes(buildSentryScope().tags),
15647
+ ...cleanAttributes(attributes)
15648
+ });
15649
+ /**
15650
+ * Emits a Sentry counter. A guarded, swallow-on-throw no-op unless the CLI's
15651
+ * Sentry SDK is live, so it's inert under `--no-score`, tests, and the
15652
+ * programmatic `@react-doctor/api` library (none of which initialize Sentry).
15653
+ * Metrics flow independently of performance tracing, so counters are still
15654
+ * recorded when `SENTRY_TRACES_SAMPLE_RATE=0`.
15655
+ */
15656
+ const recordCount = (name, value = 1, attributes) => {
15657
+ if (!Sentry.isInitialized()) return;
15658
+ try {
15659
+ Sentry.metrics.count(name, value, { attributes: withRunAttributes(attributes) });
15660
+ } catch {}
15661
+ };
15662
+ /**
15663
+ * Emits a Sentry distribution (value ranges — durations, sizes, scores). Same
15664
+ * gating and run-attribute handling as {@link recordCount}.
15665
+ */
15666
+ const recordDistribution = (name, value, options = {}) => {
15667
+ if (!Sentry.isInitialized()) return;
15668
+ try {
15669
+ Sentry.metrics.distribution(name, value, {
15670
+ unit: options.unit,
15671
+ attributes: withRunAttributes(options.attributes)
15672
+ });
15673
+ } catch {}
15674
+ };
15675
+ //#endregion
15676
+ //#region src/cli/utils/record-scan-metrics.ts
15677
+ /**
15678
+ * Aggregates diagnostics into per-`(rule, severity)` firing counts, reusing the
15679
+ * canonical `getDiagnosticRuleIdentity` so the `<plugin>/<rule>` key and
15680
+ * category match every other rule-keyed surface. Pure and exported so the
15681
+ * bucketing is unit-testable without an active Sentry client (the emit helpers
15682
+ * no-op under tests). Grouping the emitted `rule.fired` counter by `category`
15683
+ * or `severity` in Sentry reproduces a coarser breakdown.
15684
+ */
15685
+ const summarizeRuleFirings = (diagnostics) => {
15686
+ const firings = /* @__PURE__ */ new Map();
15687
+ for (const diagnostic of diagnostics) {
15688
+ const { ruleKey, category } = getDiagnosticRuleIdentity(diagnostic);
15689
+ const firingKey = `${ruleKey}\u0000${diagnostic.severity}`;
15690
+ const existing = firings.get(firingKey);
15691
+ firings.set(firingKey, existing ? {
15692
+ ...existing,
15693
+ count: existing.count + 1
15694
+ } : {
15695
+ rule: ruleKey,
15696
+ plugin: diagnostic.plugin,
15697
+ category,
15698
+ severity: diagnostic.severity,
15699
+ count: 1
15700
+ });
15701
+ }
15702
+ return [...firings.values()];
15703
+ };
15704
+ /**
15705
+ * Emits the per-scan engineering + product counters/distributions for one
15706
+ * `inspect()` run (fires once per project in a workspace scan). Every emission
15707
+ * is a no-op unless Sentry is live, and the shared run/project attributes ride
15708
+ * along from the global scope, so call sites only pass scan-specific dimensions.
15709
+ */
15710
+ const recordScanMetrics = (input) => {
15711
+ const { result } = input;
15712
+ const hasSkippedChecks = result.skippedChecks.length > 0;
15713
+ recordCount(METRIC.scanCompleted, 1, {
15714
+ mode: input.mode,
15715
+ lint: input.lint,
15716
+ deadCode: input.deadCode,
15717
+ parallel: input.parallel,
15718
+ scoreOnly: input.scoreOnly,
15719
+ didLintFail: input.didLintFail,
15720
+ didDeadCodeFail: input.didDeadCodeFail,
15721
+ hasSkippedChecks
15722
+ });
15723
+ recordDistribution(METRIC.scanDuration, result.elapsedMilliseconds, {
15724
+ unit: "millisecond",
15725
+ attributes: {
15726
+ mode: input.mode,
15727
+ parallel: input.parallel,
15728
+ scoreOnly: input.scoreOnly
15729
+ }
15730
+ });
15731
+ if (result.scanElapsedMilliseconds !== void 0) recordDistribution(METRIC.scanPhaseDuration, result.scanElapsedMilliseconds, {
15732
+ unit: "millisecond",
15733
+ attributes: { mode: input.mode }
15734
+ });
15735
+ if (result.scannedFileCount !== void 0) recordDistribution(METRIC.scanFiles, result.scannedFileCount, { attributes: { mode: input.mode } });
15736
+ if (input.workerCount !== void 0) recordDistribution(METRIC.oxlintWorkers, input.workerCount, { attributes: { mode: input.mode } });
15737
+ for (const firing of summarizeRuleFirings(result.diagnostics)) recordCount(METRIC.ruleFired, firing.count, {
15738
+ rule: firing.rule,
15739
+ plugin: firing.plugin,
15740
+ category: firing.category,
15741
+ severity: firing.severity
15742
+ });
15743
+ if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
15744
+ if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
15745
+ else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
15746
+ if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
15747
+ if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
15748
+ for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
15749
+ check,
15750
+ reason: result.skippedCheckReasons?.[check] ?? null
15751
+ });
15752
+ };
15753
+ //#endregion
15466
15754
  //#region src/cli/utils/build-no-score-message.ts
15467
15755
  const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
15468
15756
  const buildNoScoreMessage = (isScoreDisabled) => {
@@ -16370,6 +16658,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16370
16658
  suppressScanSummary: options.suppressRendering
16371
16659
  }, { beforeLint: (projectInfo, lintIncludePaths) => Effect.gen(function* () {
16372
16660
  recordSentryProjectContext(projectInfo, rootSentrySpan);
16661
+ recordCount(METRIC.projectDetected, 1);
16373
16662
  if (options.scoreOnly || options.suppressRendering) return;
16374
16663
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
16375
16664
  yield* printProjectDetection({
@@ -16405,7 +16694,21 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16405
16694
  scannedFilePaths: output.scannedFilePaths,
16406
16695
  scanElapsedMilliseconds: output.scanElapsedMilliseconds
16407
16696
  };
16408
- return await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16697
+ const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16698
+ recordScanMetrics({
16699
+ result,
16700
+ mode: isDiffMode ? "diff" : "full",
16701
+ parallel: options.concurrency !== void 0,
16702
+ workerCount: options.concurrency,
16703
+ lint: options.lint,
16704
+ deadCode: options.deadCode,
16705
+ scoreOnly: options.scoreOnly,
16706
+ noScore: options.noScore,
16707
+ didLintFail,
16708
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
16709
+ didDeadCodeFail: output.didDeadCodeFail
16710
+ });
16711
+ return result;
16409
16712
  };
16410
16713
  const finalizeAndRender = (input) => Effect.gen(function* () {
16411
16714
  const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
@@ -16589,6 +16892,21 @@ const handleError = (error, options = {}) => {
16589
16892
  if (options.shouldExit !== false) process.exit(1);
16590
16893
  process.exitCode = 1;
16591
16894
  };
16895
+ /**
16896
+ * Renderer for expected, user-actionable failures — a bad `--diff` value or
16897
+ * a base branch that isn't fetched. Prints just the (already human-readable)
16898
+ * message — no "Something went wrong", prefilled issue, Discord link, or
16899
+ * Sentry reference — because there is no bug to report.
16900
+ */
16901
+ const handleUserError = (error, options = {}) => {
16902
+ Effect.runSync(Effect.gen(function* () {
16903
+ yield* Console.error("");
16904
+ yield* Console.error(highlighter.error(formatErrorForReport(error)));
16905
+ yield* Console.error("");
16906
+ }));
16907
+ if (options.shouldExit !== false) process.exit(1);
16908
+ process.exitCode = 1;
16909
+ };
16592
16910
  //#endregion
16593
16911
  //#region src/cli/utils/build-handoff-payload.ts
16594
16912
  const buildHandoffPayload = (input) => {
@@ -17597,11 +17915,17 @@ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) =>
17597
17915
  projectRoot,
17598
17916
  runner: dependencyRunner
17599
17917
  });
17918
+ recordCount(METRIC.installDependency, 1, {
17919
+ status: dependencyResult.dependencyStatus,
17920
+ reason: dependencyResult.dependencyReason ?? null,
17921
+ packageManager: detectPackageManager(projectRoot)
17922
+ });
17600
17923
  if (dependencyResult.dependencyStatus === "skipped") {
17601
17924
  dependencySpinner.fail(formatDependencyInstallMessage(dependencyResult));
17602
- return;
17925
+ return dependencyResult;
17603
17926
  }
17604
17927
  dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
17928
+ return dependencyResult;
17605
17929
  } catch (error) {
17606
17930
  dependencySpinner.fail("Failed to install React Doctor package.");
17607
17931
  throw error;
@@ -17769,7 +18093,7 @@ const runInstallReactDoctor = async (options = {}) => {
17769
18093
  } catch {
17770
18094
  cliLogger.dim(" Skipped bundled sibling skills (install error).");
17771
18095
  }
17772
- await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
18096
+ const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
17773
18097
  if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
17774
18098
  const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
17775
18099
  try {
@@ -17780,6 +18104,7 @@ const runInstallReactDoctor = async (options = {}) => {
17780
18104
  hooksPathConfig: gitHookTarget.hooksPathConfig
17781
18105
  });
17782
18106
  hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
18107
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
17783
18108
  } catch (error) {
17784
18109
  hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
17785
18110
  throw error;
@@ -17793,7 +18118,10 @@ const runInstallReactDoctor = async (options = {}) => {
17793
18118
  agents: selectedAgents
17794
18119
  });
17795
18120
  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(", ")}.`);
18121
+ else {
18122
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18123
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
18124
+ }
17797
18125
  } catch (error) {
17798
18126
  hookSpinner.fail("Failed to install React Doctor agent hooks.");
17799
18127
  throw error;
@@ -17805,11 +18133,21 @@ const runInstallReactDoctor = async (options = {}) => {
17805
18133
  try {
17806
18134
  writeFileSync(workflowTargetPath, buildWorkflowContent());
17807
18135
  workflowSpinner.succeed(`GitHub Actions workflow added at ${path.relative(projectRoot, workflowTargetPath)}.`);
18136
+ recordCount(METRIC.installWorkflow, 1);
17808
18137
  } catch (error) {
17809
18138
  workflowSpinner.fail("Failed to add GitHub Actions workflow.");
17810
18139
  throw error;
17811
18140
  }
17812
18141
  }
18142
+ recordCount(METRIC.installCompleted, 1, {
18143
+ agentsCount: selectedAgents.length,
18144
+ gitHook: shouldInstallGitHook,
18145
+ agentHooks: shouldInstallAgentHooks,
18146
+ workflow: shouldInstallWorkflow,
18147
+ dependencyStatus: dependencyResult.dependencyStatus,
18148
+ packageManager: detectPackageManager(projectRoot)
18149
+ });
18150
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
17813
18151
  };
17814
18152
  //#endregion
17815
18153
  //#region src/cli/utils/install-skill-for-agent.ts
@@ -17922,6 +18260,16 @@ const handoffToAgent = async (input) => {
17922
18260
  ],
17923
18261
  initial: 0
17924
18262
  }, { onCancel: () => true });
18263
+ let handoffOutcome = "launch";
18264
+ if (handoffTarget === void 0) handoffOutcome = "cancel";
18265
+ else if (handoffTarget === SKIP_CHOICE) handoffOutcome = "skip";
18266
+ else if (handoffTarget === PRINT_CHOICE) handoffOutcome = "print";
18267
+ else if (handoffTarget === CLIPBOARD_CHOICE) handoffOutcome = "clipboard";
18268
+ recordCount(METRIC.agentHandoff, 1, {
18269
+ outcome: handoffOutcome,
18270
+ agent: handoffOutcome === "launch" ? handoffTarget : void 0,
18271
+ diagnosticsCount: input.diagnostics.length
18272
+ });
17925
18273
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
17926
18274
  const payload = buildHandoffPayload({
17927
18275
  diagnostics: input.diagnostics,
@@ -18067,6 +18415,13 @@ const reportErrorToSentry = async (error) => {
18067
18415
  if (!Sentry.isInitialized()) return void 0;
18068
18416
  try {
18069
18417
  const { tags, contexts } = buildSentryScope();
18418
+ let reason = "unknown";
18419
+ if (isReactDoctorError(error)) reason = error.reason._tag;
18420
+ else if (error instanceof Error) reason = error.name;
18421
+ recordCount(METRIC.cliError, 1, {
18422
+ command: typeof tags.command === "string" ? tags.command : void 0,
18423
+ reason
18424
+ });
18070
18425
  const runTrace = getActiveRunTrace();
18071
18426
  const eventId = Sentry.withScope((scope) => {
18072
18427
  for (const [name, context] of Object.entries(contexts)) scope.setContext(name, context);
@@ -18233,31 +18588,13 @@ const printAgentInstallHint = (writeLine = defaultWriteLine) => {
18233
18588
  //#endregion
18234
18589
  //#region src/cli/utils/resolve-parallel-flag.ts
18235
18590
  /**
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.
18591
+ * Maps the `--no-parallel` flag to an `InspectOptions.concurrency` value.
18592
+ * `--no-parallel` (`parallel === false`) pins serial, overriding any
18593
+ * env-enabled default; otherwise `undefined` defers to the ambient
18594
+ * `OxlintConcurrency` default (parallel, unless `REACT_DOCTOR_PARALLEL`
18595
+ * sets a worker count — the flag itself no longer takes one).
18249
18596
  */
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
- };
18597
+ const resolveParallelFlag = (parallel) => parallel === false ? 1 : void 0;
18261
18598
  //#endregion
18262
18599
  //#region src/cli/utils/resolve-cli-inspect-options.ts
18263
18600
  /**
@@ -18285,7 +18622,7 @@ const resolveCliInspectOptions = (flags, userConfig) => {
18285
18622
  isCi: isCiEnvironment(),
18286
18623
  silent: Boolean(flags.json),
18287
18624
  outputSurface: flags.prComment ? "prComment" : "cli",
18288
- concurrency: resolveParallelFlag(flags.experimentalParallel)
18625
+ concurrency: resolveParallelFlag(flags.parallel)
18289
18626
  };
18290
18627
  };
18291
18628
  //#endregion
@@ -18612,6 +18949,7 @@ const inspectAction = async (directory, flags) => {
18612
18949
  compact: Boolean(flags.jsonCompact),
18613
18950
  directory: requestedDirectory
18614
18951
  });
18952
+ recordCount(METRIC.cliInvoked, 1, { command: "inspect" });
18615
18953
  try {
18616
18954
  validateModeFlags(flags);
18617
18955
  maybeMigrateLegacyConfig(requestedDirectory, {
@@ -18789,21 +19127,30 @@ const inspectAction = async (directory, flags) => {
18789
19127
  isJsonMode,
18790
19128
  isScoreOnly,
18791
19129
  isStaged: Boolean(flags.staged)
18792
- })) printAgentInstallHint();
19130
+ })) {
19131
+ printAgentInstallHint();
19132
+ recordCount(METRIC.agentInstallHintShown, 1);
19133
+ }
18793
19134
  }
18794
19135
  } catch (error) {
18795
- const sentryEventId = await reportErrorToSentry(error);
19136
+ const isUserError = isReactDoctorError(error) && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
19137
+ const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
18796
19138
  if (isJsonMode) {
18797
19139
  writeJsonErrorReport(error);
18798
19140
  process.exitCode = 1;
18799
19141
  return;
18800
19142
  }
19143
+ if (isUserError) {
19144
+ handleUserError(error);
19145
+ return;
19146
+ }
18801
19147
  handleError(error, { sentryEventId });
18802
19148
  }
18803
19149
  };
18804
19150
  //#endregion
18805
19151
  //#region src/cli/commands/install.ts
18806
19152
  const installAction = async (options, command) => {
19153
+ recordCount(METRIC.cliInvoked, 1, { command: "install" });
18807
19154
  Effect.runSync(printBrandedHeader);
18808
19155
  try {
18809
19156
  const parentOptions = command?.parent?.opts?.();
@@ -19124,6 +19471,7 @@ const SEVERITY_VALUES = [
19124
19471
  "warn",
19125
19472
  "error"
19126
19473
  ];
19474
+ const recordRulesInvocation = () => recordCount(METRIC.cliInvoked, 1, { command: "rules" });
19127
19475
  const resolveProjectRoot = (options) => {
19128
19476
  const requestedDirectory = path.resolve(options.cwd ?? process.cwd());
19129
19477
  return findNearestPackageDirectory(requestedDirectory) ?? requestedDirectory;
@@ -19166,6 +19514,11 @@ const reportManualEdit = (target, nextConfig) => {
19166
19514
  process.exitCode = 1;
19167
19515
  };
19168
19516
  const rulesListAction = async (options) => {
19517
+ recordRulesInvocation();
19518
+ recordCount(METRIC.rulesQueried, 1, {
19519
+ subcommand: "list",
19520
+ hadFilter: Boolean(options.category || options.tag || options.framework || options.configured)
19521
+ });
19169
19522
  const catalog = buildRuleCatalog();
19170
19523
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
19171
19524
  const categoryFilter = options.category?.toLowerCase();
@@ -19197,6 +19550,8 @@ const rulesListAction = async (options) => {
19197
19550
  cliLogger.log(renderRuleCatalog(rows));
19198
19551
  };
19199
19552
  const rulesExplainAction = async (ruleQuery, options) => {
19553
+ recordRulesInvocation();
19554
+ recordCount(METRIC.rulesQueried, 1, { subcommand: "explain" });
19200
19555
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19201
19556
  if (!entry) {
19202
19557
  reportRuleNotFound(ruleQuery);
@@ -19224,7 +19579,7 @@ const rulesExplainAction = async (ruleQuery, options) => {
19224
19579
  effective
19225
19580
  }));
19226
19581
  };
19227
- const setRuleSeverityAndReport = async (entry, severity, options) => {
19582
+ const setRuleSeverityAndReport = async (entry, severity, options, action) => {
19228
19583
  const { target, nextConfig, written } = await applyConfigChange(options, (config) => setRuleSeverity(config, entry.key, severity));
19229
19584
  if (!written) {
19230
19585
  reportManualEdit(target, nextConfig);
@@ -19232,8 +19587,14 @@ const setRuleSeverityAndReport = async (entry, severity, options) => {
19232
19587
  }
19233
19588
  cliLogger.success(`Set ${entry.key} → ${severity}`);
19234
19589
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19590
+ recordCount(METRIC.rulesChanged, 1, {
19591
+ action,
19592
+ severity,
19593
+ target: entry.key
19594
+ });
19235
19595
  };
19236
19596
  const rulesSetAction = async (ruleQuery, severityValue, options) => {
19597
+ recordRulesInvocation();
19237
19598
  const severity = parseSeverity(severityValue);
19238
19599
  if (!severity) {
19239
19600
  reportInvalidSeverity(severityValue);
@@ -19244,16 +19605,17 @@ const rulesSetAction = async (ruleQuery, severityValue, options) => {
19244
19605
  reportRuleNotFound(ruleQuery);
19245
19606
  return;
19246
19607
  }
19247
- await setRuleSeverityAndReport(entry, severity, options);
19608
+ await setRuleSeverityAndReport(entry, severity, options, "set");
19248
19609
  };
19249
19610
  const rulesEnableAction = async (ruleQuery, options) => {
19611
+ recordRulesInvocation();
19250
19612
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19251
19613
  if (!entry) {
19252
19614
  reportRuleNotFound(ruleQuery);
19253
19615
  return;
19254
19616
  }
19255
19617
  if (options.severity === void 0) {
19256
- await setRuleSeverityAndReport(entry, entry.defaultSeverity, options);
19618
+ await setRuleSeverityAndReport(entry, entry.defaultSeverity, options, "enable");
19257
19619
  return;
19258
19620
  }
19259
19621
  const severity = parseSeverity(options.severity);
@@ -19266,17 +19628,19 @@ const rulesEnableAction = async (ruleQuery, options) => {
19266
19628
  process.exitCode = 1;
19267
19629
  return;
19268
19630
  }
19269
- await setRuleSeverityAndReport(entry, severity, options);
19631
+ await setRuleSeverityAndReport(entry, severity, options, "enable");
19270
19632
  };
19271
19633
  const rulesDisableAction = async (ruleQuery, options) => {
19634
+ recordRulesInvocation();
19272
19635
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19273
19636
  if (!entry) {
19274
19637
  reportRuleNotFound(ruleQuery);
19275
19638
  return;
19276
19639
  }
19277
- await setRuleSeverityAndReport(entry, "off", options);
19640
+ await setRuleSeverityAndReport(entry, "off", options, "disable");
19278
19641
  };
19279
19642
  const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19643
+ recordRulesInvocation();
19280
19644
  const severity = parseSeverity(severityValue);
19281
19645
  if (!severity) {
19282
19646
  reportInvalidSeverity(severityValue);
@@ -19297,8 +19661,14 @@ const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19297
19661
  }
19298
19662
  cliLogger.success(`Set category "${matchedCategory}" → ${severity}`);
19299
19663
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19664
+ recordCount(METRIC.rulesChanged, 1, {
19665
+ action: "category",
19666
+ severity,
19667
+ target: matchedCategory
19668
+ });
19300
19669
  };
19301
19670
  const rulesIgnoreTagAction = async (tag, options) => {
19671
+ recordRulesInvocation();
19302
19672
  const knownTags = listRuleTags(buildRuleCatalog());
19303
19673
  if (!knownTags.includes(tag)) {
19304
19674
  cliLogger.error(`Unknown tag "${tag}".`);
@@ -19313,8 +19683,13 @@ const rulesIgnoreTagAction = async (tag, options) => {
19313
19683
  }
19314
19684
  cliLogger.success(`Ignoring tag "${tag}" (rules with this tag are skipped before linting)`);
19315
19685
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19686
+ recordCount(METRIC.rulesChanged, 1, {
19687
+ action: "ignoreTag",
19688
+ target: tag
19689
+ });
19316
19690
  };
19317
19691
  const rulesUnignoreTagAction = async (tag, options) => {
19692
+ recordRulesInvocation();
19318
19693
  const target = await resolveRuleConfigTarget(resolveProjectRoot(options));
19319
19694
  if (!(target.config.ignore?.tags ?? []).includes(tag)) {
19320
19695
  cliLogger.dim(`Tag "${tag}" was not being ignored; nothing to change.`);
@@ -19328,6 +19703,10 @@ const rulesUnignoreTagAction = async (tag, options) => {
19328
19703
  }
19329
19704
  cliLogger.success(`Tag "${tag}" is no longer ignored`);
19330
19705
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19706
+ recordCount(METRIC.rulesChanged, 1, {
19707
+ action: "unignoreTag",
19708
+ target: tag
19709
+ });
19331
19710
  };
19332
19711
  //#endregion
19333
19712
  //#region src/cli/commands/version.ts
@@ -19340,6 +19719,7 @@ const rulesUnignoreTagAction = async (tag, options) => {
19340
19719
  */
19341
19720
  const buildVersionString = () => `react-doctor/${VERSION} ${process.platform}-${process.arch} node-${process.version}`;
19342
19721
  const versionAction = () => {
19722
+ recordCount(METRIC.cliInvoked, 1, { command: "version" });
19343
19723
  process.stdout.write(`${buildVersionString()}\n`);
19344
19724
  };
19345
19725
  //#endregion
@@ -19434,6 +19814,7 @@ const ROOT_FLAG_SPEC = {
19434
19814
  "--no-color",
19435
19815
  "--no-dead-code",
19436
19816
  "--no-lint",
19817
+ "--no-parallel",
19437
19818
  "--no-respect-inline-disables",
19438
19819
  "--no-score",
19439
19820
  "--no-telemetry",
@@ -19454,7 +19835,7 @@ const ROOT_FLAG_SPEC = {
19454
19835
  "--project",
19455
19836
  "--why"
19456
19837
  ]),
19457
- longOptionsWithOptionalValues: new Set(["--diff", "--experimental-parallel"]),
19838
+ longOptionsWithOptionalValues: new Set(["--diff"]),
19458
19839
  shortOptionsWithoutValues: new Set([
19459
19840
  "-h",
19460
19841
  "-v",
@@ -19621,7 +20002,7 @@ ${formatExampleLines([
19621
20002
  ${highlighter.dim("Learn more:")}
19622
20003
  ${highlighter.info(CANONICAL_GITHUB_URL)}
19623
20004
  `;
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);
20005
+ 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
20006
  program.action(inspectAction);
19626
20007
  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
20008
  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 +20038,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
19657
20038
  export {};
19658
20039
 
19659
20040
  //# sourceMappingURL=cli.js.map
19660
- //# debugId=d012dbb2-27e9-5092-9eab-c7fa4573f0b2
20041
+ //# debugId=6e59d54f-a063-5355-9b76-f82556f70c89