react-doctor 0.5.1-dev.486c68f → 0.5.1-dev.7c88165

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]="0551c9da-9fe1-599a-8bff-8c4ce0e4b2a1")}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]="ecc7e4af-d176-5569-bc51-c3fbe220a76b")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import * as NodeChildProcess from "node:child_process";
5
5
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
@@ -21009,7 +21009,7 @@ const recurDefaults = /* @__PURE__ */ memoize((ast) => {
21009
21009
  * @since 4.0.0
21010
21010
  */
21011
21011
  function makeEffect(schema) {
21012
- const parser = run$2(recurDefaults(toType(schema.ast)));
21012
+ const parser = run$1(recurDefaults(toType(schema.ast)));
21013
21013
  return (input, options) => {
21014
21014
  return parser(input, options?.disableChecks ? options?.parseOptions ? {
21015
21015
  ...options.parseOptions,
@@ -21054,7 +21054,7 @@ function make$25(schema) {
21054
21054
  }
21055
21055
  /** @internal */
21056
21056
  function _is(ast) {
21057
- const parser = asExit(run$2(toType(ast)));
21057
+ const parser = asExit(run$1(toType(ast)));
21058
21058
  return (input) => {
21059
21059
  return isSuccess(parser(input, defaultParseOptions));
21060
21060
  };
@@ -21073,7 +21073,7 @@ function _is(ast) {
21073
21073
  * @since 4.0.0
21074
21074
  */
21075
21075
  function decodeUnknownEffect(schema, options) {
21076
- const parser = run$2(schema.ast);
21076
+ const parser = run$1(schema.ast);
21077
21077
  return options === void 0 ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
21078
21078
  }
21079
21079
  /**
@@ -21104,7 +21104,7 @@ function decodeUnknownOption$1(schema, options) {
21104
21104
  * @since 4.0.0
21105
21105
  */
21106
21106
  function encodeUnknownEffect(schema, options) {
21107
- const parser = run$2(flip$1(schema.ast));
21107
+ const parser = run$1(flip$1(schema.ast));
21108
21108
  return options === void 0 ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
21109
21109
  }
21110
21110
  /**
@@ -21126,7 +21126,7 @@ const mergeParseOptions = (options, overrideOptions) => overrideOptions === void
21126
21126
  ...overrideOptions
21127
21127
  };
21128
21128
  /** @internal */
21129
- function run$2(ast) {
21129
+ function run$1(ast) {
21130
21130
  const parser = recur$1(ast);
21131
21131
  return (input, options) => flatMapEager(parser(some(input), options ?? defaultParseOptions), (oa) => {
21132
21132
  if (oa._tag === "None") return fail$4(new InvalidValue(oa));
@@ -28330,7 +28330,7 @@ const ensuring = /* @__PURE__ */ dual(2, (self, finalizer) => fromChannel(ensuri
28330
28330
  * @category destructors
28331
28331
  * @since 2.0.0
28332
28332
  */
28333
- const run$1 = /* @__PURE__ */ dual(2, (self, sink) => scopedWith((scope) => toPullScoped(self.channel, scope).pipe(flatMap$2((upstream) => sink.transform(upstream, scope)), map$3(([a]) => a))));
28333
+ const run = /* @__PURE__ */ dual(2, (self, sink) => scopedWith((scope) => toPullScoped(self.channel, scope).pipe(flatMap$2((upstream) => sink.transform(upstream, scope)), map$3(([a]) => a))));
28334
28334
  /**
28335
28335
  * Runs the stream and collects all elements into an array.
28336
28336
  *
@@ -35068,7 +35068,7 @@ const layer$3 = /* @__PURE__ */ effect(ChildProcessSpawner, /* @__PURE__ */ gen(
35068
35068
  evaluate: () => nodeStream,
35069
35069
  onError: (error) => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)
35070
35070
  });
35071
- if (config.stream) yield* forkScoped(run$1(config.stream, sink));
35071
+ if (config.stream) yield* forkScoped(run(config.stream, sink));
35072
35072
  inputSinks.set(fd, sink);
35073
35073
  break;
35074
35074
  }
@@ -35097,7 +35097,7 @@ const layer$3 = /* @__PURE__ */ effect(ChildProcessSpawner, /* @__PURE__ */ gen(
35097
35097
  endOnDone: config.endOnDone,
35098
35098
  encoding: config.encoding
35099
35099
  });
35100
- if (isStream(config.stream)) return as(forkScoped(run$1(config.stream, sink)), sink);
35100
+ if (isStream(config.stream)) return as(forkScoped(run(config.stream, sink)), sink);
35101
35101
  return succeed$2(sink);
35102
35102
  });
35103
35103
  const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {
@@ -40271,6 +40271,42 @@ var Files = class Files extends Service()("react-doctor/Files") {
40271
40271
  }));
40272
40272
  };
40273
40273
  };
40274
+ const HUNK_HEADER_PATTERN = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
40275
+ /**
40276
+ * Parses a `git diff --unified=0` patch into the inclusive 1-based line ranges
40277
+ * each file added or modified on the new side. Files are keyed by the path in
40278
+ * the `+++ b/<path>` header (with `--relative`, relative to the diff's cwd).
40279
+ * Added/renamed/modified files appear; pure deletions (`+++ /dev/null`) are
40280
+ * skipped because they have no new-side line to report on.
40281
+ */
40282
+ const parseChangedLineRanges = (patch) => {
40283
+ const rangesByFile = /* @__PURE__ */ new Map();
40284
+ let currentRanges = null;
40285
+ for (const line of patch.split("\n")) {
40286
+ if (line.startsWith("+++ ")) {
40287
+ const target = line.slice(4).trim();
40288
+ if (target === "/dev/null") {
40289
+ currentRanges = null;
40290
+ continue;
40291
+ }
40292
+ const file = target.startsWith("b/") ? target.slice(2) : target;
40293
+ currentRanges = rangesByFile.get(file) ?? [];
40294
+ rangesByFile.set(file, currentRanges);
40295
+ continue;
40296
+ }
40297
+ if (currentRanges === null) continue;
40298
+ const hunk = HUNK_HEADER_PATTERN.exec(line);
40299
+ if (hunk === null) continue;
40300
+ const start = Number(hunk[1]);
40301
+ const lineCount = hunk[2] === void 0 ? 1 : Number(hunk[2]);
40302
+ if (lineCount <= 0) continue;
40303
+ currentRanges.push([start, start + lineCount - 1]);
40304
+ }
40305
+ return [...rangesByFile].filter(([, ranges]) => ranges.length > 0).map(([file, ranges]) => ({
40306
+ file,
40307
+ ranges
40308
+ }));
40309
+ };
40274
40310
  const trimOrNull = (value) => {
40275
40311
  const trimmed = value.trim();
40276
40312
  return trimmed.length === 0 ? null : trimmed;
@@ -40636,6 +40672,22 @@ var Git = class Git extends Service()("react-doctor/Git") {
40636
40672
  status: result.status,
40637
40673
  stdout: result.stdout
40638
40674
  };
40675
+ }),
40676
+ changedLineRanges: ({ directory, baseRef, cached, files }) => gen(function* () {
40677
+ if (files.length === 0) return [];
40678
+ if (baseRef !== void 0 && !isSafeGitRevision(baseRef)) return null;
40679
+ const result = yield* runGit(directory, [
40680
+ "diff",
40681
+ "--unified=0",
40682
+ "--diff-filter=ACMR",
40683
+ "--relative",
40684
+ ...cached ? ["--cached"] : [],
40685
+ ...baseRef !== void 0 ? [baseRef] : [],
40686
+ "--",
40687
+ ...files
40688
+ ]);
40689
+ if (result.status !== 0) return null;
40690
+ return parseChangedLineRanges(result.stdout);
40639
40691
  })
40640
40692
  });
40641
40693
  })).pipe(provide$2(layer$3.pipe(provide$2(mergeAll$1(layer$2, layer$1)))));
@@ -40666,7 +40718,8 @@ var Git = class Git extends Service()("react-doctor/Git") {
40666
40718
  status: matches.length === 0 ? 1 : 0,
40667
40719
  stdout
40668
40720
  };
40669
- })
40721
+ }),
40722
+ changedLineRanges: () => succeed$2(snapshot.changedLineRanges ?? [])
40670
40723
  }));
40671
40724
  };
40672
40725
  const estimateArgsLength = (args) => args.reduce((total, argument) => total + argument.length + 1, 0);
@@ -41659,6 +41712,7 @@ const shouldSuppressLocalUseHookDiagnostic = (diagnostic, rootDirectory) => {
41659
41712
  };
41660
41713
  const FILEPATH_WITH_LOCATION_PATTERN = /\S+\.\w+:\d+:\d+[\s\S]*$/;
41661
41714
  const REACT_COMPILER_TITLE = "React Compiler can't optimize this";
41715
+ const REACT_COMPILER_TODO_TITLE = "React Compiler doesn't support this syntax";
41662
41716
  const REACT_COMPILER_MESSAGE = "This component misses React Compiler's automatic memoization & re-renders more than it should. Rewrite the flagged code so the compiler can optimize it.";
41663
41717
  const PLUGIN_CATEGORY_MAP = {
41664
41718
  react: "Bugs",
@@ -41686,7 +41740,10 @@ const getRuleRecommendation = (ruleName, project) => {
41686
41740
  };
41687
41741
  const getRuleCategory = (ruleName) => reactDoctorPlugin.rules[ruleName]?.category;
41688
41742
  const getRuleTitle = (ruleName) => reactDoctorPlugin.rules[ruleName]?.title;
41689
- const resolveDiagnosticTitle = (plugin, rule) => plugin === "react-hooks-js" ? REACT_COMPILER_TITLE : getRuleTitle(rule);
41743
+ const resolveDiagnosticTitle = (plugin, rule) => {
41744
+ if (plugin !== "react-hooks-js") return getRuleTitle(rule);
41745
+ return rule === "todo" ? REACT_COMPILER_TODO_TITLE : REACT_COMPILER_TITLE;
41746
+ };
41690
41747
  const cleanDiagnosticMessage = (message, help, plugin, rule, project) => {
41691
41748
  const cleaned = resolveCleanedDiagnostic(typeof message === "string" ? message : "", typeof help === "string" ? help : "", plugin, rule, project);
41692
41749
  return {
@@ -42445,25 +42502,36 @@ const decodeArtifact = decodeUnknownOption(Struct({ score: optional(Struct({
42445
42502
  const SCORE_AXES = [
42446
42503
  {
42447
42504
  key: "supplyChain",
42448
- label: "supply chain"
42505
+ label: "supply chain",
42506
+ gates: true
42449
42507
  },
42450
42508
  {
42451
42509
  key: "vulnerability",
42452
- label: "vulnerability"
42510
+ label: "vulnerability",
42511
+ gates: true
42453
42512
  },
42454
42513
  {
42455
42514
  key: "maintenance",
42456
- label: "maintenance"
42515
+ label: "maintenance",
42516
+ gates: false
42457
42517
  },
42458
42518
  {
42459
42519
  key: "quality",
42460
- label: "quality"
42520
+ label: "quality",
42521
+ gates: false
42461
42522
  },
42462
42523
  {
42463
42524
  key: "license",
42464
- label: "license"
42525
+ label: "license",
42526
+ gates: false
42465
42527
  }
42466
42528
  ];
42529
+ const GATED_AXES = SCORE_AXES.filter((axis) => axis.gates);
42530
+ const worstGatedAxis = (score) => {
42531
+ let worst = GATED_AXES[0];
42532
+ for (const axis of GATED_AXES) if (score[axis.key] < score[worst.key]) worst = axis;
42533
+ return worst;
42534
+ };
42467
42535
  const clampScore = (value) => {
42468
42536
  if (!Number.isFinite(value)) return 50;
42469
42537
  return Math.min(Math.max(value, 0), 100);
@@ -42604,15 +42672,14 @@ const fetchSocketScore = (dependency) => tryPromise(async (signal) => {
42604
42672
  "socket.purl": toPurl(dependency)
42605
42673
  } }));
42606
42674
  const formatAxisScores = (score) => SCORE_AXES.map((axis) => `${axis.label} ${toHundred(score[axis.key])}`).join(", ");
42607
- const buildLowScoreDiagnostic = (dependency, score, options) => {
42608
- const overall = toHundred(score.overall);
42675
+ const buildLowScoreDiagnostic = (dependency, score, failingAxis, options) => {
42609
42676
  const packagePageUrl = `${SOCKET_PACKAGE_PAGE_BASE}/${dependency.name}/overview/${dependency.version}`;
42610
42677
  return {
42611
42678
  filePath: "package.json",
42612
42679
  plugin: SUPPLY_CHAIN_PLUGIN,
42613
42680
  rule: SUPPLY_CHAIN_RULE,
42614
42681
  severity: options.severity,
42615
- message: `\`${dependency.name}\` (declared in package.json as "${dependency.spec}", scored at ${dependency.version}) has a Socket supply-chain score of ${overall}/100 (below the minimum of ${options.minScore}). Axis scores — ${formatAxisScores(score)}.`,
42682
+ message: `\`${dependency.name}\` (declared in package.json as "${dependency.spec}", scored at ${dependency.version}) has a Socket ${failingAxis.label} score of ${toHundred(score[failingAxis.key])}/100 (below the minimum of ${options.minScore}). Axis scores — ${formatAxisScores(score)}.`,
42616
42683
  help: `Update or replace the \`"${dependency.name}": "${dependency.spec}"\` entry in package.json. Review ${dependency.name} on Socket: ${packagePageUrl}. Or raise \`supplyChain.minScore\` if you have vetted and accepted this package.`,
42617
42684
  url: packagePageUrl,
42618
42685
  line: dependency.line,
@@ -42647,7 +42714,9 @@ const collectSupplyChainScores = (input) => gen(function* () {
42647
42714
  * Scores every direct dependency in the project's `package.json` against
42648
42715
  * Socket.dev's free PURL endpoint (the same one Socket Firewall's free tier
42649
42716
  * uses — no API key) and returns a diagnostic for each dependency whose
42650
- * Socket `overall` score is below the configured `minScore`.
42717
+ * worst Socket *security* axis — supply chain or vulnerability — is below
42718
+ * the configured `minScore`. The quality / maintenance / license axes are
42719
+ * reported as context but never gate (see GATED_AXES).
42651
42720
  *
42652
42721
  * Lookups run with bounded concurrency via `Effect.forEach`. The check is
42653
42722
  * total/fail-open: each per-package lookup already recovers to `null`
@@ -42665,8 +42734,9 @@ const checkSupplyChain = (input) => gen(function* () {
42665
42734
  for (let index = 0; index < dependencies.length; index += 1) {
42666
42735
  const score = scores[index];
42667
42736
  if (!score) continue;
42668
- if (toHundred(score.overall) >= options.minScore) continue;
42669
- diagnostics.push(buildLowScoreDiagnostic(dependencies[index], score, options));
42737
+ const worstAxis = worstGatedAxis(score);
42738
+ if (toHundred(score[worstAxis.key]) >= options.minScore) continue;
42739
+ diagnostics.push(buildLowScoreDiagnostic(dependencies[index], score, worstAxis, options));
42670
42740
  }
42671
42741
  return diagnostics;
42672
42742
  });
@@ -42674,7 +42744,8 @@ const checkSupplyChain = (input) => gen(function* () {
42674
42744
  * `SupplyChain` scores the project's direct dependencies against Socket.dev's
42675
42745
  * free, keyless PURL endpoint — the same lookup Socket Firewall's free tier
42676
42746
  * (`sfw`) performs — and streams a diagnostic for each dependency whose
42677
- * Socket score falls below the configured `supplyChain.minScore`.
42747
+ * worst Socket security axis (supply chain or vulnerability) falls below
42748
+ * the configured `supplyChain.minScore`.
42678
42749
  *
42679
42750
  * Runs by default (one network request per dependency); the orchestrator
42680
42751
  * provides `layerOf([])` only when the user opts out via
@@ -43366,6 +43437,21 @@ const getDiffInfo = (directory, explicitBaseBranch) => runPromise(gen(function*
43366
43437
  }).pipe(provide(Git.layerNode)));
43367
43438
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
43368
43439
  /**
43440
+ * Programmatic façade over `Git.changedLineRanges` (the `lines` scope). Diffs
43441
+ * `files` with `--unified=0` against `baseRef` (or the index when `cached`),
43442
+ * returning per-file changed line ranges relative to `directory`. Returns
43443
+ * `null` when the ranges can't be computed (git unavailable / unsafe ref /
43444
+ * non-zero exit) so the caller degrades to file-level scope; an empty array
43445
+ * means git succeeded but the files added no lines.
43446
+ */
43447
+ const getChangedLineRanges = (input) => runPromise(gen(function* () {
43448
+ const ranges = yield* (yield* Git).changedLineRanges(input);
43449
+ return ranges === null ? null : ranges.map((entry) => ({
43450
+ file: entry.file,
43451
+ ranges: entry.ranges
43452
+ }));
43453
+ }).pipe(provide(Git.layerNode)));
43454
+ /**
43369
43455
  * Canonical URL for a rule's documentation page — its reviewer-tested fix
43370
43456
  * recipe rendered for humans — served at
43371
43457
  * `https://react.doctor/docs/rules/<plugin>/<rule>`. The CLI links here
@@ -43414,6 +43500,48 @@ const groupBy = (items, keyFn) => {
43414
43500
  * a 404. Gate the directive on this predicate.
43415
43501
  */
43416
43502
  const hasPublishedFixRecipe = (diagnostic) => diagnostic.plugin === "react-doctor" && Object.hasOwn(reactDoctorPlugin.rules, diagnostic.rule);
43503
+ const unionValues = (baseValues, overrideValues) => [...new Set([...baseValues, ...overrideValues])];
43504
+ const mergeIgnores = (baseIgnore, overrideIgnore) => {
43505
+ const mergedIgnore = {
43506
+ ...baseIgnore,
43507
+ ...overrideIgnore
43508
+ };
43509
+ if (baseIgnore.rules && overrideIgnore.rules) mergedIgnore.rules = unionValues(baseIgnore.rules, overrideIgnore.rules);
43510
+ if (baseIgnore.files && overrideIgnore.files) mergedIgnore.files = unionValues(baseIgnore.files, overrideIgnore.files);
43511
+ if (baseIgnore.tags && overrideIgnore.tags) mergedIgnore.tags = unionValues(baseIgnore.tags, overrideIgnore.tags);
43512
+ if (baseIgnore.overrides && overrideIgnore.overrides) mergedIgnore.overrides = [...baseIgnore.overrides, ...overrideIgnore.overrides];
43513
+ return mergedIgnore;
43514
+ };
43515
+ /**
43516
+ * Layer one `ReactDoctorConfig` on top of another, additively: `rules` /
43517
+ * `categories` / `supplyChain` merge per key, `ignore` lists union
43518
+ * (`ignore.overrides` concatenate), and every other field is a scalar the
43519
+ * override simply wins on when set. Returns the base unchanged when there
43520
+ * is no override, and vice versa — so callers can thread `null` /
43521
+ * `undefined` through without special-casing.
43522
+ */
43523
+ const mergeReactDoctorConfigs = (baseConfig, overrideConfig) => {
43524
+ if (overrideConfig === void 0) return baseConfig;
43525
+ if (baseConfig === null) return overrideConfig;
43526
+ const mergedConfig = {
43527
+ ...baseConfig,
43528
+ ...overrideConfig
43529
+ };
43530
+ if (baseConfig.rules && overrideConfig.rules) mergedConfig.rules = {
43531
+ ...baseConfig.rules,
43532
+ ...overrideConfig.rules
43533
+ };
43534
+ if (baseConfig.categories && overrideConfig.categories) mergedConfig.categories = {
43535
+ ...baseConfig.categories,
43536
+ ...overrideConfig.categories
43537
+ };
43538
+ if (baseConfig.supplyChain && overrideConfig.supplyChain) mergedConfig.supplyChain = {
43539
+ ...baseConfig.supplyChain,
43540
+ ...overrideConfig.supplyChain
43541
+ };
43542
+ if (baseConfig.ignore && overrideConfig.ignore) mergedConfig.ignore = mergeIgnores(baseConfig.ignore, overrideConfig.ignore);
43543
+ return mergedConfig;
43544
+ };
43417
43545
  //#endregion
43418
43546
  //#region src/cli/utils/is-ci-environment.ts
43419
43547
  const CI_ENVIRONMENT_VARIABLES = [
@@ -43511,6 +43639,7 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
43511
43639
  //#region src/cli/utils/constants.ts
43512
43640
  const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
43513
43641
  const BASELINE_FILES_TEMP_DIR_PREFIX = "react-doctor-baseline-";
43642
+ const GH_DEFAULT_BRANCH_PROBE_TIMEOUT_MS = 5e3;
43514
43643
  const CI_TRUST_COMPANIES = "PayPal, Rippling, and Alibaba";
43515
43644
  const WELCOME_EXPLANATION_HOLD_MS = 1e3;
43516
43645
  const CATEGORY_COUNTUP_SETTLE_HOLD_MS = 1e3;
@@ -43521,6 +43650,8 @@ const METRIC = {
43521
43650
  cliInvoked: "cli.invoked",
43522
43651
  cliError: "cli.error",
43523
43652
  projectDetected: "project.detected",
43653
+ projectPathSelected: "project.path_selected",
43654
+ projectConfigSelected: "project.config_selected",
43524
43655
  scanCompleted: "scan.completed",
43525
43656
  scanDuration: "scan.duration",
43526
43657
  scanPhaseDuration: "scan.phase_duration",
@@ -43590,7 +43721,7 @@ const makeNoopConsole = () => ({
43590
43721
  });
43591
43722
  //#endregion
43592
43723
  //#region src/cli/utils/version.ts
43593
- const VERSION = "0.5.1-dev.486c68f";
43724
+ const VERSION = "0.5.1-dev.7c88165";
43594
43725
  //#endregion
43595
43726
  //#region src/cli/utils/json-mode.ts
43596
43727
  let context = null;
@@ -43948,13 +44079,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
43948
44079
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
43949
44080
  * standard `SENTRY_RELEASE` override.
43950
44081
  */
43951
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.5.1-dev.486c68f`;
44082
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.5.1-dev.7c88165`;
43952
44083
  /**
43953
44084
  * Deployment environment shown in Sentry's environment filter. Defaults to
43954
44085
  * `production` for tagged releases and `development` for dev/unbuilt versions,
43955
44086
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
43956
44087
  */
43957
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.5.1-dev.486c68f") ? "development" : "production");
44088
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.5.1-dev.7c88165") ? "development" : "production");
43958
44089
  /**
43959
44090
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
43960
44091
  * (set to `0` to disable tracing) and falls back to
@@ -47252,12 +47383,13 @@ const toSpanAttributes = (tags) => {
47252
47383
  /**
47253
47384
  * Clears the module-level run-scoped Sentry state — the current scanned project
47254
47385
  * and the active run trace. `inspect()` calls this at the start of every run and
47255
- * again after a clean one (it's invoked once per project in a workspace scan),
47256
- * so a prior or just-finished scan can't attach its project tags / trace to a
47257
- * later run or to a non-scan error (e.g. inspectAction's post-loop
47258
- * finalize/handoff steps). A thrown scan error skips the post-run reset, leaving
47259
- * the state for the command catch to attribute and link the crash. Safe to call
47260
- * when Sentry is off (the refs are read only when an event is built).
47386
+ * again after a clean one, so a prior or just-finished scan can't attach its
47387
+ * project tags / trace to a later run or to a non-scan error (e.g.
47388
+ * inspectAction's post-loop finalize/handoff steps). A thrown scan error skips
47389
+ * the post-run reset, leaving the state for the command catch to attribute and
47390
+ * link the crash. Concurrent batch members (`concurrentScan`) never touch this
47391
+ * state — they neither write nor reset it. Safe to call when Sentry is off (the
47392
+ * refs are read only when an event is built).
47261
47393
  */
47262
47394
  const resetSentryRunState = () => {
47263
47395
  setSentryProjectInfo(null);
@@ -47280,8 +47412,13 @@ const resetSentryRunState = () => {
47280
47412
  * state right after a clean run and at the start of the next one, so the trace
47281
47413
  * is never attached to a non-scan error; on a thrown error the state is left in
47282
47414
  * place for the command catch, then the process exits.
47415
+ *
47416
+ * A `concurrentScan` (one member of the CLI's multi-project pool) still gets
47417
+ * its own root span, but skips recording the active run trace — the module-
47418
+ * level handle has single-scan semantics, and overlapping writers would link a
47419
+ * crash to an arbitrary sibling's trace.
47283
47420
  */
47284
- const withSentryRunSpan = (run) => {
47421
+ const withSentryRunSpan = (run, options = {}) => {
47285
47422
  if (!isSentryTracingEnabled()) return run(void 0);
47286
47423
  const { tags } = buildSentryScope();
47287
47424
  const command = typeof tags.command === "string" ? tags.command : "inspect";
@@ -47290,12 +47427,14 @@ const withSentryRunSpan = (run) => {
47290
47427
  op: "cli.inspect",
47291
47428
  attributes: toSpanAttributes(tags)
47292
47429
  }, (rootSpan) => {
47293
- const spanContext = rootSpan.spanContext();
47294
- setActiveRunTrace({
47295
- traceId: spanContext.traceId,
47296
- spanId: spanContext.spanId,
47297
- sampled: (spanContext.traceFlags & 1) === 1
47298
- });
47430
+ if (options.concurrentScan !== true) {
47431
+ const spanContext = rootSpan.spanContext();
47432
+ setActiveRunTrace({
47433
+ traceId: spanContext.traceId,
47434
+ spanId: spanContext.spanId,
47435
+ sampled: (spanContext.traceFlags & 1) === 1
47436
+ });
47437
+ }
47299
47438
  return run(rootSpan);
47300
47439
  });
47301
47440
  };
@@ -47306,9 +47445,15 @@ const withSentryRunSpan = (run) => {
47306
47445
  * run's root span so the transaction/trace carries the project shape too.
47307
47446
  * Always cheap — the span attribute set is skipped when `rootSpan` is absent
47308
47447
  * (tracing off), and storing the info is a plain assignment.
47448
+ *
47449
+ * A `concurrentScan` only sets the span attributes: the module-level project
47450
+ * ref has single-scan semantics, and overlapping writers would stamp events
47451
+ * and metrics with an arbitrary sibling's project. Wide events keep full
47452
+ * attribution (they ride the span); per-emit metrics simply omit the project
47453
+ * shape during a concurrent batch (absent, never wrong).
47309
47454
  */
47310
- const recordSentryProjectContext = (projectInfo, rootSpan) => {
47311
- setSentryProjectInfo(projectInfo);
47455
+ const recordSentryProjectContext = (projectInfo, rootSpan, options = {}) => {
47456
+ if (options.concurrentScan !== true) setSentryProjectInfo(projectInfo);
47312
47457
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
47313
47458
  };
47314
47459
  //#endregion
@@ -47593,6 +47738,7 @@ const buildConfigAttributes = (input) => {
47593
47738
  const ruleKeys = Object.keys(ruleOverrides);
47594
47739
  return {
47595
47740
  mode: input.mode,
47741
+ scope: input.scope,
47596
47742
  parallel: input.parallel,
47597
47743
  workerCount: input.workerCount ?? null,
47598
47744
  lint: input.lint,
@@ -47601,6 +47747,7 @@ const buildConfigAttributes = (input) => {
47601
47747
  noScore: input.noScore,
47602
47748
  respectInlineDisables: input.respectInlineDisables,
47603
47749
  showWarnings: input.showWarnings,
47750
+ usedOutputDir: input.usedOutputDir,
47604
47751
  ignoredTagCount: input.ignoredTagCount,
47605
47752
  hasCustomConfig: input.hasCustomConfig,
47606
47753
  rulesConfigured: ruleKeys.length,
@@ -47634,6 +47781,9 @@ const recordRunEvent = (rootSpan, input) => {
47634
47781
  } catch {}
47635
47782
  };
47636
47783
  //#endregion
47784
+ //#region src/cli/utils/path-format.ts
47785
+ const toForwardSlashes = (filePath) => filePath.replaceAll("\\", "/");
47786
+ //#endregion
47637
47787
  //#region src/cli/utils/materialize-baseline-files.ts
47638
47788
  /**
47639
47789
  * Materializes the `ref` version of `files` into `tempDirectory` (via
@@ -48415,15 +48565,22 @@ const printNoScoreHeader = (noScoreMessage) => gen(function* () {
48415
48565
  });
48416
48566
  //#endregion
48417
48567
  //#region src/cli/utils/write-diagnostics-directory.ts
48418
- const writeDiagnosticsDirectory = (diagnostics) => {
48419
- const outputDirectory = Path.join(tmpdir(), `react-doctor-${randomUUID()}`);
48420
- NFS.mkdirSync(outputDirectory, { recursive: true });
48421
- for (const [ruleKey, ruleDiagnostics] of buildSortedRuleGroups(diagnostics)) {
48422
- const fileName = ruleKey.replace(/\//g, "--") + ".txt";
48423
- NFS.writeFileSync(Path.join(outputDirectory, fileName), formatRuleSummary(ruleKey, ruleDiagnostics));
48568
+ const ruleDumpFileName = (ruleKey) => ruleKey.replace(/\//g, "--") + ".txt";
48569
+ const readPreviousRuleDumpFileNames = (directory) => {
48570
+ try {
48571
+ const previous = JSON.parse(NFS.readFileSync(Path.join(directory, "diagnostics.json"), "utf8"));
48572
+ return new Set(previous.filter((d) => typeof d?.plugin === "string" && typeof d?.rule === "string").map((d) => ruleDumpFileName(`${d.plugin}/${d.rule}`)));
48573
+ } catch {
48574
+ return /* @__PURE__ */ new Set();
48424
48575
  }
48425
- NFS.writeFileSync(Path.join(outputDirectory, "diagnostics.json"), JSON.stringify(diagnostics));
48426
- return outputDirectory;
48576
+ };
48577
+ const writeDiagnosticsDirectory = (diagnostics, outputDirectory) => {
48578
+ const directory = outputDirectory ? Path.resolve(outputDirectory) : Path.join(tmpdir(), `react-doctor-${randomUUID()}`);
48579
+ if (outputDirectory) for (const fileName of readPreviousRuleDumpFileNames(directory)) NFS.rmSync(Path.join(directory, fileName), { force: true });
48580
+ NFS.mkdirSync(directory, { recursive: true });
48581
+ for (const [ruleKey, ruleDiagnostics] of buildSortedRuleGroups(diagnostics)) NFS.writeFileSync(Path.join(directory, ruleDumpFileName(ruleKey)), formatRuleSummary(ruleKey, ruleDiagnostics));
48582
+ NFS.writeFileSync(Path.join(directory, "diagnostics.json"), JSON.stringify(diagnostics));
48583
+ return directory;
48427
48584
  };
48428
48585
  //#endregion
48429
48586
  //#region src/cli/utils/render-summary.ts
@@ -48460,6 +48617,16 @@ const printFooter = (input) => gen(function* () {
48460
48617
  yield* log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
48461
48618
  yield* printFooterDescription("Report issues and star the repository!");
48462
48619
  });
48620
+ const printDiagnosticsDump = (diagnostics, outputDirectory, verbose, stream = "stdout") => gen(function* () {
48621
+ const writtenDirectory = yield* try_({
48622
+ try: () => writeDiagnosticsDirectory(diagnostics, outputDirectory),
48623
+ catch: (cause) => cause
48624
+ }).pipe(orElseSucceed(() => null));
48625
+ if (writtenDirectory !== null && (verbose || outputDirectory)) {
48626
+ const pathLine = highlighter.gray(` Full diagnostics written to ${writtenDirectory}`);
48627
+ yield* stream === "stderr" || Boolean(outputDirectory) && isJsonModeActive() ? sync(() => process.stderr.write(`${pathLine}\n`)) : log(pathLine);
48628
+ }
48629
+ });
48463
48630
  const printSummary = (input) => gen(function* () {
48464
48631
  if (input.scoreResult) {
48465
48632
  const animateProjection = Boolean(input.animateProjection) && input.potentialScore != null && !input.verbose;
@@ -48470,11 +48637,7 @@ const printSummary = (input) => gen(function* () {
48470
48637
  if (animateProjection) yield* animateScoreProjection(input.scoreResult, input.potentialScore, 5);
48471
48638
  }
48472
48639
  } else yield* printNoScoreHeader(input.noScoreMessage);
48473
- const diagnosticsDirectory = yield* try_({
48474
- try: () => writeDiagnosticsDirectory(input.diagnostics),
48475
- catch: (cause) => cause
48476
- }).pipe(orElseSucceed(() => null));
48477
- if (diagnosticsDirectory !== null && input.verbose) yield* log(highlighter.gray(` Full diagnostics written to ${diagnosticsDirectory}`));
48640
+ yield* printDiagnosticsDump(input.diagnostics, input.outputDirectory, input.verbose);
48478
48641
  });
48479
48642
  //#endregion
48480
48643
  //#region src/cli/utils/should-auto-select-current-choice.ts
@@ -48796,6 +48959,7 @@ const buildScanResultCacheKey = (input) => {
48796
48959
  ignoredTags: [...input.options.ignoredTags].sort(),
48797
48960
  concurrency: input.options.concurrency,
48798
48961
  baselineRef: input.options.baseline?.ref,
48962
+ changedLineRanges: input.options.changedLineRanges ?? void 0,
48799
48963
  noScore: input.options.noScore,
48800
48964
  isCi: input.options.isCi,
48801
48965
  suppressRendering: input.options.suppressRendering,
@@ -48844,6 +49008,16 @@ const recordOnboardingCompletion = (options) => {
48844
49008
  })) markOnboardingComplete();
48845
49009
  };
48846
49010
  const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
49011
+ const buildChangedLineMatcher = (directory, changedLineRanges) => {
49012
+ const rangesByFile = /* @__PURE__ */ new Map();
49013
+ for (const entry of changedLineRanges) rangesByFile.set(toForwardSlashes(entry.file), entry.ranges);
49014
+ return (diagnostic) => {
49015
+ const relativePath = toForwardSlashes(path.isAbsolute(diagnostic.filePath) ? path.relative(directory, diagnostic.filePath) : diagnostic.filePath);
49016
+ const ranges = rangesByFile.get(relativePath);
49017
+ if (ranges === void 0) return false;
49018
+ return ranges.some(([start, end]) => diagnostic.line >= start && diagnostic.line <= end);
49019
+ };
49020
+ };
48847
49021
  const buildIgnoredTags = (userConfig) => {
48848
49022
  const tags = /* @__PURE__ */ new Set();
48849
49023
  if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
@@ -48853,6 +49027,7 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
48853
49027
  lint: inputOptions.lint ?? userConfig?.lint ?? true,
48854
49028
  deadCode: inputOptions.deadCode ?? userConfig?.deadCode ?? true,
48855
49029
  verbose: inputOptions.verbose ?? userConfig?.verbose ?? false,
49030
+ outputDirectory: inputOptions.outputDirectory || null,
48856
49031
  scoreOnly: inputOptions.scoreOnly ?? false,
48857
49032
  noScore: inputOptions.noScore ?? userConfig?.noScore ?? false,
48858
49033
  isCi: inputOptions.isCi ?? false,
@@ -48869,11 +49044,19 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
48869
49044
  ignoredTags: buildIgnoredTags(userConfig),
48870
49045
  outputSurface: inputOptions.outputSurface ?? "cli",
48871
49046
  suppressRendering: inputOptions.suppressRendering ?? false,
49047
+ concurrentScan: inputOptions.concurrentScan ?? false,
48872
49048
  concurrency: inputOptions.concurrency,
48873
49049
  baseline: inputOptions.baseline ?? null,
49050
+ changedLineRanges: inputOptions.changedLineRanges ?? null,
48874
49051
  supplyChainManifestChanged: inputOptions.supplyChainManifestChanged ?? false
48875
49052
  });
49053
+ const deriveScope = (options) => {
49054
+ if (options.baseline) return "changed";
49055
+ if (options.changedLineRanges !== null) return "lines";
49056
+ return options.includePaths.length > 0 ? "files" : "full";
49057
+ };
48876
49058
  const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
49059
+ scope: deriveScope(options),
48877
49060
  parallel: options.concurrency !== void 0,
48878
49061
  workerCount: options.concurrency,
48879
49062
  lint: options.lint,
@@ -48882,13 +49065,15 @@ const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
48882
49065
  noScore: options.noScore,
48883
49066
  respectInlineDisables: options.respectInlineDisables,
48884
49067
  showWarnings: options.warnings,
49068
+ usedOutputDir: options.outputDirectory !== null,
48885
49069
  ignoredTagCount: options.ignoredTags.size,
48886
49070
  hasCustomConfig,
48887
49071
  userConfig
48888
49072
  });
48889
49073
  const inspect = async (directory, inputOptions = {}) => {
48890
49074
  const startTime = performance$1.now();
48891
- resetSentryRunState();
49075
+ const isConcurrentScan = inputOptions.concurrentScan === true;
49076
+ if (!isConcurrentScan) resetSentryRunState();
48892
49077
  const hasConfigOverride = inputOptions.configOverride !== void 0;
48893
49078
  let scanDirectory;
48894
49079
  let userConfig;
@@ -48896,7 +49081,7 @@ const inspect = async (directory, inputOptions = {}) => {
48896
49081
  if (hasConfigOverride) {
48897
49082
  scanDirectory = directory;
48898
49083
  userConfig = inputOptions.configOverride ?? null;
48899
- configSourceDirectory = null;
49084
+ configSourceDirectory = inputOptions.configSourceDirectory ?? null;
48900
49085
  } else {
48901
49086
  const scanTarget = await resolveScanTarget(directory);
48902
49087
  scanDirectory = scanTarget.resolvedDirectory;
@@ -48904,8 +49089,9 @@ const inspect = async (directory, inputOptions = {}) => {
48904
49089
  configSourceDirectory = scanTarget.configSourceDirectory;
48905
49090
  }
48906
49091
  const options = mergeInspectOptions(inputOptions, userConfig);
49092
+ const ownsSpinnerSilence = options.silent && !isConcurrentScan;
48907
49093
  const wasSpinnerSilent = isSpinnerSilent();
48908
- if (options.silent) setSpinnerSilent(true);
49094
+ if (ownsSpinnerSilence) setSpinnerSilent(true);
48909
49095
  try {
48910
49096
  const result = await withSentryRunSpan(async (rootSentrySpan) => {
48911
49097
  try {
@@ -48918,11 +49104,11 @@ const inspect = async (directory, inputOptions = {}) => {
48918
49104
  });
48919
49105
  throw error;
48920
49106
  }
48921
- });
48922
- resetSentryRunState();
49107
+ }, { concurrentScan: isConcurrentScan });
49108
+ if (!isConcurrentScan) resetSentryRunState();
48923
49109
  return result;
48924
49110
  } finally {
48925
- if (options.silent) setSpinnerSilent(wasSpinnerSilent);
49111
+ if (ownsSpinnerSilence) setSpinnerSilent(wasSpinnerSilent);
48926
49112
  }
48927
49113
  };
48928
49114
  /**
@@ -49011,7 +49197,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49011
49197
  const scanResultCache = cacheKey === null ? null : createScanResultCache(directory);
49012
49198
  const cachedPayload = cacheKey === null ? null : scanResultCache?.lookup(cacheKey) ?? null;
49013
49199
  if (cachedPayload) {
49014
- recordSentryProjectContext(cachedPayload.project, rootSentrySpan);
49200
+ recordSentryProjectContext(cachedPayload.project, rootSentrySpan, { concurrentScan: options.concurrentScan });
49015
49201
  recordCount(METRIC.projectDetected, 1);
49016
49202
  await renderCachedProjectDetection({
49017
49203
  payload: cachedPayload,
@@ -49033,7 +49219,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49033
49219
  recordOnboardingCompletion(options);
49034
49220
  return result;
49035
49221
  }
49036
- const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && options.lint && Boolean(resolvedNodeBinaryPath);
49222
+ const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && !options.suppressRendering && options.lint && Boolean(resolvedNodeBinaryPath);
49037
49223
  const layers = buildRuntimeLayers({
49038
49224
  directory,
49039
49225
  hasConfigOverride,
@@ -49062,7 +49248,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49062
49248
  suppressScanSummary: options.suppressRendering,
49063
49249
  supplyChainManifestChanged: options.supplyChainManifestChanged
49064
49250
  }, { beforeLint: (projectInfo, lintIncludePaths) => gen(function* () {
49065
- recordSentryProjectContext(projectInfo, rootSentrySpan);
49251
+ recordSentryProjectContext(projectInfo, rootSentrySpan, { concurrentScan: options.concurrentScan });
49066
49252
  recordCount(METRIC.projectDetected, 1);
49067
49253
  if (options.scoreOnly || options.suppressRendering) return;
49068
49254
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
@@ -49095,6 +49281,9 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49095
49281
  inspectDiagnostics = comparison.displayDiagnostics;
49096
49282
  baselineDelta = comparison.baselineDelta;
49097
49283
  }
49284
+ } else if (options.changedLineRanges !== null && isDiffMode) {
49285
+ const isOnChangedLine = buildChangedLineMatcher(directory, options.changedLineRanges);
49286
+ inspectDiagnostics = output.diagnostics.filter(isOnChangedLine);
49098
49287
  }
49099
49288
  const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
49100
49289
  const score = didLintFail ? null : output.score;
@@ -49209,15 +49398,16 @@ const finalizeAndRender = (input) => gen(function* () {
49209
49398
  ...baselineDelta ? { baselineDelta } : {}
49210
49399
  });
49211
49400
  if (options.suppressRendering) return buildResult();
49401
+ const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
49402
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
49212
49403
  if (options.scoreOnly) {
49404
+ if (options.outputDirectory !== null) yield* printDiagnosticsDump(printedDiagnostics, options.outputDirectory, false, "stderr");
49213
49405
  if (score) yield* log(`${score.score}`);
49214
- else yield* log(highlighter.gray(noScoreMessage));
49406
+ else yield* error$1(highlighter.gray(noScoreMessage));
49215
49407
  return buildResult();
49216
49408
  }
49217
49409
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
49218
49410
  const pause = onboardingSectionPause(animateRender);
49219
- const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
49220
- const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
49221
49411
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
49222
49412
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
49223
49413
  if (printedDiagnostics.length === 0) {
@@ -49235,6 +49425,7 @@ const finalizeAndRender = (input) => gen(function* () {
49235
49425
  yield* log(highlighter.gray(" Score not shown — some checks could not complete."));
49236
49426
  } else if (score) yield* printScoreHeader(score);
49237
49427
  else yield* printNoScoreHeader(noScoreMessage);
49428
+ if (options.outputDirectory !== null) yield* printDiagnosticsDump(printedDiagnostics, options.outputDirectory);
49238
49429
  return buildResult();
49239
49430
  }
49240
49431
  yield* pause;
@@ -49259,6 +49450,7 @@ const finalizeAndRender = (input) => gen(function* () {
49259
49450
  totalSourceFileCount: lintSourceFileCount,
49260
49451
  noScoreMessage,
49261
49452
  verbose: options.verbose,
49453
+ outputDirectory: options.outputDirectory,
49262
49454
  animateProjection: animateRender
49263
49455
  });
49264
49456
  if (hasSkippedChecks) {
@@ -49430,9 +49622,9 @@ const isExpectedUserError = (error) => error instanceof CliInputError || isProje
49430
49622
  //#region src/cli/utils/build-handoff-payload.ts
49431
49623
  const buildHandoffPayload = (input) => {
49432
49624
  const topGroups = buildSortedRuleGroups(input.diagnostics).slice(0, 3);
49433
- let diagnosticsDirectory = null;
49625
+ let outputDirectory = null;
49434
49626
  try {
49435
- diagnosticsDirectory = writeDiagnosticsDirectory([...input.diagnostics]);
49627
+ outputDirectory = writeDiagnosticsDirectory([...input.diagnostics], input.outputDirectory);
49436
49628
  } catch {}
49437
49629
  const lines = [
49438
49630
  "Before fixing anything, first ask me whether I'd like to add React Doctor to CI so every pull request is scanned automatically. Explain that:",
@@ -49459,7 +49651,7 @@ const buildHandoffPayload = (input) => {
49459
49651
  if (remainingFiles > 0) lines.push(` - +${remainingFiles} more files`);
49460
49652
  });
49461
49653
  lines.push("");
49462
- if (diagnosticsDirectory) lines.push(`Full results for all ${input.diagnostics.length} issues (diagnostics.json + a .txt per rule): ${diagnosticsDirectory}`, "");
49654
+ if (outputDirectory) lines.push(`Full results for all ${input.diagnostics.length} issues (diagnostics.json + a .txt per rule): ${outputDirectory}`, "");
49463
49655
  lines.push("Read each file and fix the root cause — don't suppress or silence the rule.", "", "Verify against the real thing, don't assume: confirm each change matches the canonical fix recipe you fetched for that rule, then re-run `npx react-doctor@latest --verbose` and check the issue is actually gone against the real tool before moving on.", "", "Teach me as you go: for every issue you touch, explain it in plain language (no jargon) — what the problem is, why it's a problem, and how serious it is in human terms. Describe the real-world impact and severity concretely (e.g. \"this crashes the page for users on Safari\" vs. \"this is a minor cleanup with no user impact\") so I understand why it matters, not just what changed.", "", "Then work through the rest from the full results above.");
49464
49656
  return lines.join("\n");
49465
49657
  };
@@ -49691,7 +49883,7 @@ const installReactDoctorScriptStep = (projectRoot) => {
49691
49883
  };
49692
49884
  //#endregion
49693
49885
  //#region src/cli/utils/install-github-workflow.ts
49694
- const buildWorkflowContent = () => `# React Doctor — finds security, performance, correctness, accessibility,
49886
+ const buildWorkflowContent = (defaultBranch) => `# React Doctor — finds security, performance, correctness, accessibility,
49695
49887
  # bundle-size, and architecture issues in React codebases.
49696
49888
  #
49697
49889
  # Docs: https://www.react.doctor/ci
@@ -49703,9 +49895,9 @@ on:
49703
49895
  # Scans the PR's changed files and posts a sticky summary comment listing only the new issues introduced relative to the merge base of the target branch.
49704
49896
  pull_request:
49705
49897
  types: [opened, synchronize, reopened, ready_for_review]
49706
- # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
49898
+ # Scans \`${defaultBranch}\` on every push to track the health-score trend and catch regressions that slipped past PR review.
49707
49899
  push:
49708
- branches: [main]
49900
+ branches: ["${defaultBranch}"]
49709
49901
 
49710
49902
  permissions:
49711
49903
  contents: read
@@ -49765,7 +49957,7 @@ const upgradeWorkflowActionToV2 = (content) => {
49765
49957
  changed: upgraded !== content
49766
49958
  };
49767
49959
  };
49768
- const installReactDoctorWorkflow = (projectRoot) => {
49960
+ const installReactDoctorWorkflow = (projectRoot, defaultBranch = "main") => {
49769
49961
  const workflowPath = getReactDoctorWorkflowPath(projectRoot);
49770
49962
  if (NFS.existsSync(workflowPath)) return {
49771
49963
  status: "exists",
@@ -49773,7 +49965,7 @@ const installReactDoctorWorkflow = (projectRoot) => {
49773
49965
  };
49774
49966
  try {
49775
49967
  NFS.mkdirSync(Path.dirname(workflowPath), { recursive: true });
49776
- NFS.writeFileSync(workflowPath, buildWorkflowContent());
49968
+ NFS.writeFileSync(workflowPath, buildWorkflowContent(defaultBranch));
49777
49969
  return {
49778
49970
  status: "created",
49779
49971
  workflowPath
@@ -49949,19 +50141,14 @@ const askUpgradeActionVersion = async (prompt = prompts) => {
49949
50141
  return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
49950
50142
  };
49951
50143
  //#endregion
49952
- //#region src/cli/utils/open-workflow-pull-request.ts
49953
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
49954
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
49955
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
49956
- const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
49957
-
49958
- Docs: https://www.react.doctor/ci`;
50144
+ //#region src/cli/utils/run-command.ts
49959
50145
  const execFileAsync$1 = promisify(execFile);
49960
- const run = async (command, args, cwd) => {
50146
+ const runCommand = async (command, args, cwd, timeoutMs) => {
49961
50147
  try {
49962
50148
  const { stdout, stderr } = await execFileAsync$1(command, [...args], {
49963
50149
  cwd,
49964
- encoding: "utf8"
50150
+ encoding: "utf8",
50151
+ timeout: timeoutMs
49965
50152
  });
49966
50153
  return {
49967
50154
  success: true,
@@ -49977,7 +50164,18 @@ const run = async (command, args, cwd) => {
49977
50164
  };
49978
50165
  }
49979
50166
  };
49980
- const detectDefaultBranch = async (cwd) => {
50167
+ //#endregion
50168
+ //#region src/cli/utils/detect-default-branch.ts
50169
+ const detectDefaultBranch = async (cwd, run = runCommand) => {
50170
+ const repoView = await run("gh", [
50171
+ "repo",
50172
+ "view",
50173
+ "--json",
50174
+ "defaultBranchRef",
50175
+ "--jq",
50176
+ ".defaultBranchRef.name"
50177
+ ], cwd, GH_DEFAULT_BRANCH_PROBE_TIMEOUT_MS);
50178
+ if (repoView.success && repoView.stdout !== "" && repoView.stdout !== "null") return repoView.stdout;
49981
50179
  const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
49982
50180
  if (symRef.success) {
49983
50181
  const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
@@ -49995,8 +50193,16 @@ const detectDefaultBranch = async (cwd) => {
49995
50193
  ], cwd)).success) return "master";
49996
50194
  return null;
49997
50195
  };
50196
+ //#endregion
50197
+ //#region src/cli/utils/open-workflow-pull-request.ts
50198
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
50199
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
50200
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
50201
+ const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
50202
+
50203
+ Docs: https://www.react.doctor/ci`;
49998
50204
  const findUniqueBranchName = async (cwd) => {
49999
- if (!(await run("git", [
50205
+ if (!(await runCommand("git", [
50000
50206
  "rev-parse",
50001
50207
  "--verify",
50002
50208
  NEW_BRANCH_PREFIX
@@ -50008,7 +50214,7 @@ const openWorkflowPullRequest = async (params) => {
50008
50214
  const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
50009
50215
  const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
50010
50216
  const prBody = params.prBody ?? DEFAULT_PR_BODY;
50011
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50217
+ const repoRootProbe = await runCommand("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50012
50218
  if (!repoRootProbe.success) return {
50013
50219
  status: "not-attempted",
50014
50220
  reason: "not-a-git-repo"
@@ -50018,16 +50224,16 @@ const openWorkflowPullRequest = async (params) => {
50018
50224
  status: "not-attempted",
50019
50225
  reason: "gh-not-installed"
50020
50226
  };
50021
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
50227
+ if (!(await runCommand("gh", ["auth", "status"], cwd)).success) return {
50022
50228
  status: "not-attempted",
50023
50229
  reason: "gh-not-authenticated"
50024
50230
  };
50025
- const defaultBranch = await detectDefaultBranch(cwd);
50231
+ const defaultBranch = params.baseBranch ?? await detectDefaultBranch(cwd);
50026
50232
  if (!defaultBranch) return {
50027
50233
  status: "not-attempted",
50028
50234
  reason: "no-default-branch"
50029
50235
  };
50030
- const previousBranchProbe = await run("git", [
50236
+ const previousBranchProbe = await runCommand("git", [
50031
50237
  "rev-parse",
50032
50238
  "--abbrev-ref",
50033
50239
  "HEAD"
@@ -50037,13 +50243,13 @@ const openWorkflowPullRequest = async (params) => {
50037
50243
  reason: "detached-head"
50038
50244
  };
50039
50245
  const previousBranch = previousBranchProbe.stdout;
50040
- await run("git", [
50246
+ await runCommand("git", [
50041
50247
  "fetch",
50042
50248
  "origin",
50043
50249
  defaultBranch
50044
50250
  ], cwd);
50045
50251
  const newBranch = await findUniqueBranchName(cwd);
50046
- if (!(await run("git", [
50252
+ if (!(await runCommand("git", [
50047
50253
  "checkout",
50048
50254
  "-b",
50049
50255
  newBranch,
@@ -50053,14 +50259,14 @@ const openWorkflowPullRequest = async (params) => {
50053
50259
  reason: "checkout-failed"
50054
50260
  };
50055
50261
  const restoreToPreviousBranch = async (deleteNewBranch) => {
50056
- await run("git", ["checkout", previousBranch], cwd);
50057
- if (deleteNewBranch) await run("git", [
50262
+ await runCommand("git", ["checkout", previousBranch], cwd);
50263
+ if (deleteNewBranch) await runCommand("git", [
50058
50264
  "branch",
50059
50265
  "-D",
50060
50266
  newBranch
50061
50267
  ], cwd);
50062
50268
  };
50063
- if (!(await run("git", [
50269
+ if (!(await runCommand("git", [
50064
50270
  "add",
50065
50271
  "--",
50066
50272
  Path.relative(cwd, workflowPath)
@@ -50071,7 +50277,7 @@ const openWorkflowPullRequest = async (params) => {
50071
50277
  reason: "git-add-failed"
50072
50278
  };
50073
50279
  }
50074
- if (!(await run("git", [
50280
+ if (!(await runCommand("git", [
50075
50281
  "commit",
50076
50282
  "-m",
50077
50283
  commitMessage
@@ -50082,7 +50288,7 @@ const openWorkflowPullRequest = async (params) => {
50082
50288
  reason: "git-commit-failed"
50083
50289
  };
50084
50290
  }
50085
- if (!(await run("git", [
50291
+ if (!(await runCommand("git", [
50086
50292
  "push",
50087
50293
  "-u",
50088
50294
  "origin",
@@ -50094,7 +50300,7 @@ const openWorkflowPullRequest = async (params) => {
50094
50300
  reason: "git-push-failed"
50095
50301
  };
50096
50302
  }
50097
- const prCreate = await run("gh", [
50303
+ const prCreate = await runCommand("gh", [
50098
50304
  "pr",
50099
50305
  "create",
50100
50306
  "--title",
@@ -50118,9 +50324,9 @@ const openWorkflowPullRequest = async (params) => {
50118
50324
  };
50119
50325
  const stageWorkflowFile = async (params) => {
50120
50326
  const workflowPath = Path.resolve(params.workflowPath);
50121
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50327
+ const repoRootProbe = await runCommand("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50122
50328
  if (!repoRootProbe.success) return false;
50123
- return (await run("git", [
50329
+ return (await runCommand("git", [
50124
50330
  "add",
50125
50331
  "--",
50126
50332
  Path.relative(repoRootProbe.stdout, workflowPath)
@@ -50149,7 +50355,8 @@ const setUpGitHubActions = async (options) => {
50149
50355
  installReactDoctorScriptStep(projectRoot);
50150
50356
  } catch {}
50151
50357
  const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
50152
- const workflowResult = installReactDoctorWorkflow(projectRoot);
50358
+ const defaultBranch = await detectDefaultBranch(projectRoot) ?? "main";
50359
+ const workflowResult = installReactDoctorWorkflow(projectRoot, defaultBranch);
50153
50360
  const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
50154
50361
  cliLogger.break();
50155
50362
  if (workflowResult.status === "failed") {
@@ -50158,7 +50365,10 @@ const setUpGitHubActions = async (options) => {
50158
50365
  }
50159
50366
  if (workflowResult.status === "created") {
50160
50367
  const pullRequestSpinner = spinner("Opening a pull request for review...").start();
50161
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
50368
+ const pullRequestResult = await openWorkflowPullRequest({
50369
+ workflowPath: workflowResult.workflowPath,
50370
+ baseBranch: defaultBranch
50371
+ });
50162
50372
  if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
50163
50373
  else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
50164
50374
  else {
@@ -50999,8 +51209,8 @@ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
50999
51209
  throw error;
51000
51210
  }
51001
51211
  };
51002
- const installReactDoctorWorkflowStep = (projectRoot) => {
51003
- return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
51212
+ const installReactDoctorWorkflowStep = async (projectRoot) => {
51213
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot, await detectDefaultBranch(projectRoot) ?? void 0), projectRoot);
51004
51214
  };
51005
51215
  const upgradeReactDoctorWorkflowStep = (projectRoot) => {
51006
51216
  const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
@@ -51068,7 +51278,7 @@ const runInstallReactDoctor = async (options = {}) => {
51068
51278
  let didInstallWorkflow = false;
51069
51279
  if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
51070
51280
  cliLogger.break();
51071
- if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
51281
+ if (shouldInstallWorkflow) didInstallWorkflow = await installReactDoctorWorkflowStep(projectRoot);
51072
51282
  else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
51073
51283
  }
51074
51284
  const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
@@ -51340,7 +51550,8 @@ const handoffToAgent = async (input) => {
51340
51550
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
51341
51551
  const payload = buildHandoffPayload({
51342
51552
  diagnostics: input.diagnostics,
51343
- projectName: input.projectName
51553
+ projectName: input.projectName,
51554
+ outputDirectory: input.outputDirectory
51344
51555
  });
51345
51556
  if (handoffTarget === CLIPBOARD_CHOICE) {
51346
51557
  if (await copyToClipboard(payload)) cliLogger.log("Copied the prompt to your clipboard.");
@@ -51535,9 +51746,6 @@ const reportErrorToSentry = async (error) => {
51535
51746
  }
51536
51747
  };
51537
51748
  //#endregion
51538
- //#region src/cli/utils/path-format.ts
51539
- const toForwardSlashes = (filePath) => filePath.replaceAll("\\", "/");
51540
- //#endregion
51541
51749
  //#region src/cli/utils/read-changed-files-from.ts
51542
51750
  const isSafeRelativePath = (filePath) => {
51543
51751
  if (filePath.length === 0) return false;
@@ -51564,6 +51772,9 @@ const readChangedFilesFrom = (filePath) => {
51564
51772
  return [...uniqueFiles];
51565
51773
  };
51566
51774
  //#endregion
51775
+ //#region src/cli/utils/filter-scans-for-surface.ts
51776
+ const filterScansForSurface = (completedScans, surface) => completedScans.flatMap((scan) => filterDiagnosticsForSurface([...scan.result.diagnostics], surface, scan.config));
51777
+ //#endregion
51567
51778
  //#region src/cli/utils/render-multi-project-summary.ts
51568
51779
  const getScoreLabel = (score) => {
51569
51780
  if (score >= 75) return "Great";
@@ -51591,10 +51802,10 @@ const findLowestScoredScan = (completedScans) => {
51591
51802
  return scoredScans.reduce((worst, scan) => scan.result.score.score < worst.result.score.score ? scan : worst);
51592
51803
  };
51593
51804
  const printMultiProjectSummary = (input) => gen(function* () {
51594
- const { completedScans, userConfig, verbose, isOffline, projectName } = input;
51805
+ const { completedScans, verbose, isOffline, projectName, totalElapsedMilliseconds } = input;
51595
51806
  const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
51596
51807
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
51597
- const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
51808
+ const displayDiagnostics = filterDiagnosticsByCategories(filterScansForSurface(completedScans, "cli"), categoryFilters);
51598
51809
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
51599
51810
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
51600
51811
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -51606,8 +51817,7 @@ const printMultiProjectSummary = (input) => gen(function* () {
51606
51817
  else fileCountFromScansWithoutPaths += scan.result.scannedFileCount ?? scan.result.project.sourceFileCount;
51607
51818
  }
51608
51819
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
51609
- const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
51610
- yield* log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
51820
+ yield* log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalElapsedMilliseconds)}`);
51611
51821
  if (displayDiagnostics.length > 0) {
51612
51822
  yield* log("");
51613
51823
  yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
@@ -51617,16 +51827,17 @@ const printMultiProjectSummary = (input) => gen(function* () {
51617
51827
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
51618
51828
  yield* printSummary({
51619
51829
  diagnostics: displayDiagnostics,
51620
- elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
51830
+ elapsedMilliseconds: totalElapsedMilliseconds,
51621
51831
  scoreResult: aggregateScore,
51622
- potentialScore: lowestScoredScan ? yield* promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
51832
+ potentialScore: lowestScoredScan ? yield* promise(() => computeProjectedScore(displayDiagnostics, filterScansForSurface([lowestScoredScan], "cli"), lowestScoredScan.result.score)) : null,
51623
51833
  totalSourceFileCount,
51624
51834
  noScoreMessage: "Score unavailable.",
51625
51835
  verbose,
51836
+ outputDirectory: input.outputDirectory,
51626
51837
  animateProjection: animateRender
51627
51838
  });
51628
51839
  const entries = completedScans.map((scan) => {
51629
- const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
51840
+ const projectDiagnostics = filterDiagnosticsByCategories(filterScansForSurface([scan], "cli"), categoryFilters);
51630
51841
  const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
51631
51842
  return {
51632
51843
  projectName: scan.result.project.projectName,
@@ -51723,6 +51934,7 @@ const resolveCliInspectOptions = (flags, userConfig) => {
51723
51934
  lint: flags.lint,
51724
51935
  deadCode: flags.deadCode,
51725
51936
  verbose: flags.verbose,
51937
+ outputDirectory: flags.outputDir,
51726
51938
  respectInlineDisables: flags.respectInlineDisables === false ? false : void 0,
51727
51939
  warnings: wantsWarningGate ? true : flags.warnings,
51728
51940
  scoreOnly: flags.score === true,
@@ -51734,22 +51946,101 @@ const resolveCliInspectOptions = (flags, userConfig) => {
51734
51946
  };
51735
51947
  };
51736
51948
  //#endregion
51737
- //#region src/cli/utils/resolve-diff-mode.ts
51738
- const resolveDiffMode = async (diffInfo, effectiveDiff, shouldSkipPrompts, isQuiet) => {
51739
- if (effectiveDiff !== void 0 && effectiveDiff !== false) {
51740
- if (diffInfo) return true;
51741
- if (!isQuiet) {
51742
- if (typeof effectiveDiff === "string") cliLogger.warn(`Could not compute diff against "${effectiveDiff}" (merge-base failed or HEAD has no history). Running full scan.`);
51743
- else cliLogger.warn("No feature branch or uncommitted changes detected. Running full scan.");
51744
- cliLogger.break();
51745
- }
51746
- return false;
51949
+ //#region src/cli/utils/resolve-scope.ts
51950
+ const SCOPE_VALUES = new Set([
51951
+ "full",
51952
+ "files",
51953
+ "changed",
51954
+ "lines"
51955
+ ]);
51956
+ const isScopeValue = (value) => SCOPE_VALUES.has(value);
51957
+ const coerceDeprecatedDiff = (value) => {
51958
+ if (value === void 0) return void 0;
51959
+ if (value === false || value === "false") return { scope: "full" };
51960
+ if (value === true || value === "true") return { scope: "changed" };
51961
+ if (value === "") return void 0;
51962
+ return {
51963
+ scope: "changed",
51964
+ base: value
51965
+ };
51966
+ };
51967
+ /**
51968
+ * Resolves the *requested* scope from flags + config without touching git.
51969
+ * Precedence mirrors `pickBlockingLevel`: flags win over config, and the new
51970
+ * `--scope` wins over the deprecated `--diff` alias on each side
51971
+ * (`flags.scope` > `flags.diff` > `config.scope` > `config.diff`). Returns
51972
+ * `scope: undefined` when nothing is set so the caller can default to `full`
51973
+ * or offer the interactive prompt.
51974
+ */
51975
+ const resolveScope = (flags, userConfig) => {
51976
+ const base = flags.base ?? userConfig?.base;
51977
+ if (typeof flags.scope === "string" && flags.scope.length > 0) {
51978
+ if (isScopeValue(flags.scope)) return {
51979
+ scope: flags.scope,
51980
+ base,
51981
+ usedDeprecatedDiff: false
51982
+ };
51983
+ cliLogger.warn(`Invalid --scope "${flags.scope}". Expected one of: full, files, changed, lines. Ignoring.`);
51747
51984
  }
51748
- if (effectiveDiff === false || !diffInfo) return false;
51749
- const changedSourceFiles = filterSourceFiles(diffInfo.changedFiles);
51750
- if (changedSourceFiles.length === 0) return false;
51751
- if (shouldSkipPrompts) return false;
51752
- if (isQuiet) return false;
51985
+ const flagDiff = coerceDeprecatedDiff(flags.diff);
51986
+ if (flagDiff !== void 0) return {
51987
+ scope: flagDiff.scope,
51988
+ base: base ?? flagDiff.base,
51989
+ usedDeprecatedDiff: true
51990
+ };
51991
+ if (userConfig?.scope !== void 0) {
51992
+ if (isScopeValue(userConfig.scope)) return {
51993
+ scope: userConfig.scope,
51994
+ base,
51995
+ usedDeprecatedDiff: false
51996
+ };
51997
+ cliLogger.warn(`Invalid scope "${userConfig.scope}" in config. Expected one of: full, files, changed, lines. Ignoring.`);
51998
+ }
51999
+ const configDiff = coerceDeprecatedDiff(userConfig?.diff);
52000
+ if (configDiff !== void 0) return {
52001
+ scope: configDiff.scope,
52002
+ base: base ?? configDiff.base,
52003
+ usedDeprecatedDiff: true
52004
+ };
52005
+ return {
52006
+ scope: void 0,
52007
+ base,
52008
+ usedDeprecatedDiff: false
52009
+ };
52010
+ };
52011
+ const warnDeprecatedDiff = (flags, userConfig) => {
52012
+ const usedFlag = flags.diff !== void 0;
52013
+ if (!usedFlag && userConfig?.diff === void 0) return;
52014
+ const targetScope = coerceDeprecatedDiff(usedFlag ? flags.diff : userConfig?.diff)?.scope ?? "changed";
52015
+ if (usedFlag) {
52016
+ const baseHint = targetScope === "changed" ? " (add `--base <ref>` to pin the base)" : "";
52017
+ cliLogger.warn(`The \`--diff\` flag is deprecated; use \`--scope ${targetScope}\`${baseHint} instead.`);
52018
+ return;
52019
+ }
52020
+ cliLogger.warn(`The \`diff\` config option is deprecated; use \`scope: "${targetScope}"\` instead.`);
52021
+ };
52022
+ const warnDiffUnavailable = (requested, isQuiet) => {
52023
+ if (isQuiet) return;
52024
+ if (typeof requested.base === "string") cliLogger.warn(`Could not compute diff against "${requested.base}" (merge-base failed or HEAD has no history). Running full scan.`);
52025
+ else cliLogger.warn("No feature branch or uncommitted changes detected. Running full scan.");
52026
+ cliLogger.break();
52027
+ };
52028
+ /**
52029
+ * Resolves the requested scope against the detected diff into the final scope.
52030
+ * An explicit non-`full` scope needs a usable `diffInfo`; without one it warns
52031
+ * and falls back to `full`. When nothing was requested, an interactive run on a
52032
+ * branch with changed source files is offered the "full vs changed" prompt.
52033
+ */
52034
+ const finalizeScope = async ({ requested, diffInfo, skipPrompts, isQuiet }) => {
52035
+ if (requested.scope !== void 0) {
52036
+ if (requested.scope === "full") return "full";
52037
+ if (diffInfo !== null) return requested.scope;
52038
+ warnDiffUnavailable(requested, isQuiet);
52039
+ return "full";
52040
+ }
52041
+ if (diffInfo === null || skipPrompts || isQuiet) return "full";
52042
+ const changedSourceFiles = filterSourceFiles([...diffInfo.changedFiles]);
52043
+ if (changedSourceFiles.length === 0) return "full";
51753
52044
  const { scanScope } = await prompts({
51754
52045
  type: "select",
51755
52046
  name: "scanScope",
@@ -51761,29 +52052,13 @@ const resolveDiffMode = async (diffInfo, effectiveDiff, shouldSkipPrompts, isQui
51761
52052
  }, {
51762
52053
  title: diffInfo.isCurrentChanges ? `Uncommitted changes (${changedSourceFiles.length})` : `Changed files on ${diffInfo.currentBranch ?? "this branch"} (${changedSourceFiles.length})`,
51763
52054
  description: diffInfo.isCurrentChanges ? "Compare working tree changes against HEAD" : `Compare against ${diffInfo.baseBranch} from the branch merge-base`,
51764
- value: "branch"
52055
+ value: "changed"
51765
52056
  }],
51766
52057
  initial: diffInfo.isCurrentChanges ? 0 : 1
51767
52058
  });
51768
- return scanScope === "branch";
52059
+ return scanScope === "changed" ? "changed" : "full";
51769
52060
  };
51770
52061
  //#endregion
51771
- //#region src/cli/utils/coerce-diff-value.ts
51772
- const coerceDiffValue = (value) => {
51773
- if (value === void 0) return void 0;
51774
- if (typeof value === "boolean") return value;
51775
- if (typeof value === "string") {
51776
- if (value.length === 0) return void 0;
51777
- if (value === "false") return false;
51778
- if (value === "true") return true;
51779
- return value;
51780
- }
51781
- process.stderr.write(`[react-doctor] invalid diff value (expected boolean or string): ${typeof value}. Falling back to no diff.\n`);
51782
- };
51783
- //#endregion
51784
- //#region src/cli/utils/resolve-effective-diff.ts
51785
- const resolveEffectiveDiff = (flags, userConfig) => coerceDiffValue(flags.diff ?? userConfig?.diff);
51786
- //#endregion
51787
52062
  //#region src/cli/utils/resolve-project-relative-directory.ts
51788
52063
  /**
51789
52064
  * The scanned project's directory relative to the diff root, forward-slashed —
@@ -51814,6 +52089,30 @@ const resolveProjectDiffIncludePaths = (rootDirectory, projectDirectory, diffInf
51814
52089
  return projectRelativePath.length > 0 ? [projectRelativePath] : [];
51815
52090
  });
51816
52091
  };
52092
+ /**
52093
+ * Re-keys repo-relative changed line ranges (from `getChangedLineRanges`) to
52094
+ * the scanned project, mirroring `resolveProjectDiffIncludePaths`'s boundary
52095
+ * rule so the `lines` scope filter inside `inspect()` matches the project-
52096
+ * relative diagnostic paths. Files outside the project are dropped.
52097
+ */
52098
+ const resolveProjectChangedLineRanges = (rootDirectory, projectDirectory, ranges) => {
52099
+ const relativeProjectDirectory = resolveProjectRelativeDirectory(rootDirectory, projectDirectory);
52100
+ if (relativeProjectDirectory === null) return [];
52101
+ if (relativeProjectDirectory.length === 0) return ranges.map((entry) => ({
52102
+ file: toForwardSlashes(entry.file),
52103
+ ranges: entry.ranges
52104
+ }));
52105
+ const projectPrefix = `${relativeProjectDirectory}/`;
52106
+ return ranges.flatMap((entry) => {
52107
+ const normalizedFilePath = toForwardSlashes(entry.file);
52108
+ if (!normalizedFilePath.startsWith(projectPrefix)) return [];
52109
+ const projectRelativePath = normalizedFilePath.slice(projectPrefix.length);
52110
+ return projectRelativePath.length > 0 ? [{
52111
+ file: projectRelativePath,
52112
+ ranges: entry.ranges
52113
+ }] : [];
52114
+ });
52115
+ };
51817
52116
  //#endregion
51818
52117
  //#region src/cli/utils/build-diagnostic-issue-url.ts
51819
52118
  const formatRuleIdentifier = (diagnostic) => `${diagnostic.plugin}/${diagnostic.rule}`;
@@ -51885,16 +52184,22 @@ const parseFileLineArgument = (rawArgument) => {
51885
52184
  };
51886
52185
  //#endregion
51887
52186
  //#region src/cli/utils/select-projects.ts
51888
- const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
52187
+ const selectProjects = async (rootDirectory, projectFlag, skipPrompts, configProjects) => {
51889
52188
  const hasRootPackageJson = isFile(Path.join(rootDirectory, "package.json"));
51890
52189
  let packages = listWorkspacePackages(rootDirectory);
51891
52190
  if (packages.length === 0 && (!hasRootPackageJson || isMonorepoRoot(rootDirectory))) packages = discoverReactSubprojects(rootDirectory);
52191
+ if (projectFlag) return resolveProjectFlag(projectFlag, packages, rootDirectory);
52192
+ const configRequestedNames = (configProjects ?? []).map((requestedName) => requestedName.trim()).filter((requestedName) => requestedName.length > 0);
52193
+ if (configRequestedNames.length > 0) {
52194
+ const resolvedDirectories = resolveRequestedProjects(configRequestedNames, packages, rootDirectory, "config");
52195
+ recordCount(METRIC.projectConfigSelected, resolvedDirectories.length);
52196
+ return resolvedDirectories;
52197
+ }
51892
52198
  if (packages.length === 0) return [rootDirectory];
51893
52199
  if (packages.length === 1) {
51894
52200
  cliLogger.log(`${highlighter.success("✔")} Select projects ${highlighter.dim("›")} ${packages[0].name}`);
51895
52201
  return [packages[0].directory];
51896
52202
  }
51897
- if (projectFlag) return resolveProjectFlag(projectFlag, packages);
51898
52203
  if (skipPrompts) {
51899
52204
  printDiscoveredProjects(packages);
51900
52205
  return packages.map((workspacePackage) => workspacePackage.directory);
@@ -51902,17 +52207,25 @@ const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
51902
52207
  return promptProjectSelection(packages, rootDirectory);
51903
52208
  };
51904
52209
  const ALL_PROJECTS_SENTINEL = "*";
51905
- const resolveProjectFlag = (projectFlag, workspacePackages) => {
52210
+ const resolveProjectFlag = (projectFlag, workspacePackages, rootDirectory) => {
51906
52211
  const requestedNames = projectFlag.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
51907
52212
  if (requestedNames.length === 0) throw new CliInputError(`--project "${projectFlag}" did not name any project. Pass a project name, a comma-separated list, or "*" for all.`);
51908
- if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.map((workspacePackage) => workspacePackage.directory);
51909
- const resolvedDirectories = [];
51910
- for (const requestedName of requestedNames) {
52213
+ return resolveRequestedProjects(requestedNames, workspacePackages, rootDirectory, "flag");
52214
+ };
52215
+ const resolveRequestedProjects = (requestedNames, workspacePackages, rootDirectory, source) => {
52216
+ if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.length > 0 ? workspacePackages.map((workspacePackage) => workspacePackage.directory) : [rootDirectory];
52217
+ const sourceLabel = source === "flag" ? "Project" : "Config \"projects\" entry";
52218
+ return requestedNames.map((requestedName) => {
51911
52219
  const matched = workspacePackages.find((workspacePackage) => workspacePackage.name === requestedName || Path.basename(workspacePackage.directory) === requestedName);
51912
- if (!matched) throw new CliInputError(`Project "${requestedName}" not found. Available: ${workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ")}`);
51913
- resolvedDirectories.push(matched.directory);
51914
- }
51915
- return resolvedDirectories;
52220
+ if (matched) return matched.directory;
52221
+ const candidateDirectory = Path.resolve(rootDirectory, requestedName);
52222
+ if (isDirectory(candidateDirectory)) {
52223
+ recordCount(METRIC.projectPathSelected);
52224
+ return candidateDirectory;
52225
+ }
52226
+ const availableNames = workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ");
52227
+ throw new CliInputError(workspacePackages.length > 0 ? `${sourceLabel} "${requestedName}" is not a workspace project or a directory. Available projects: ${availableNames}` : `${sourceLabel} "${requestedName}" is not a directory under ${rootDirectory}.`);
52228
+ });
51916
52229
  };
51917
52230
  const printDiscoveredProjects = (packages) => {
51918
52231
  cliLogger.log(`${highlighter.success("✔")} Select projects ${highlighter.dim("›")} ${packages.map((workspacePackage) => workspacePackage.name).join(", ")}`);
@@ -52046,10 +52359,12 @@ const warnDeprecatedFailOn = (flags, userConfig) => {
52046
52359
  };
52047
52360
  //#endregion
52048
52361
  //#region src/cli/utils/validate-mode-flags.ts
52362
+ const usedDiffAlias = (flags) => flags.diff !== void 0 && flags.diff !== false && flags.diff !== "false" && flags.diff !== "";
52363
+ const usedScope = (flags) => typeof flags.scope === "string" && flags.scope.length > 0;
52049
52364
  const validateModeFlags = (flags) => {
52050
- const coercedDiff = coerceDiffValue(flags.diff);
52051
- const exclusiveModes = [flags.staged ? "--staged" : null, coercedDiff !== void 0 && coercedDiff !== false ? "--diff" : null].filter((modeName) => modeName !== null);
52052
- if (exclusiveModes.length > 1) throw new CliInputError(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
52365
+ if (usedScope(flags) && usedDiffAlias(flags)) throw new CliInputError("Cannot combine --scope and --diff; --diff is the deprecated alias.");
52366
+ if (flags.staged && usedDiffAlias(flags)) throw new CliInputError("Cannot combine --staged and --diff; pick one mode.");
52367
+ if (flags.staged && (flags.scope === "full" || flags.scope === "changed")) throw new CliInputError(`Cannot combine --staged with --scope ${flags.scope}; use --scope files or --scope lines, or drop --scope.`);
52053
52368
  if (flags.score && flags.json) throw new CliInputError("Cannot combine --score and --json; pick one output mode.");
52054
52369
  if (flags.score && flags.telemetry === false) throw new CliInputError("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
52055
52370
  if (flags.sfw) {
@@ -52057,7 +52372,8 @@ const validateModeFlags = (flags) => {
52057
52372
  flags.json ? "--json" : null,
52058
52373
  flags.score ? "--score" : null,
52059
52374
  flags.staged ? "--staged" : null,
52060
- coercedDiff !== void 0 && coercedDiff !== false ? "--diff" : null
52375
+ usedScope(flags) ? "--scope" : null,
52376
+ usedDiffAlias(flags) ? "--diff" : null
52061
52377
  ].find((name) => name !== null);
52062
52378
  if (conflictingFlag) throw new CliInputError(`Cannot combine --sfw with ${conflictingFlag}; --sfw is a standalone demo listing.`);
52063
52379
  }
@@ -52104,7 +52420,7 @@ const finalizeScans = (input) => {
52104
52420
  }));
52105
52421
  }
52106
52422
  if (input.isScoreOnly || baselineDegraded) return;
52107
- if (shouldBlockCi(filterDiagnosticsForSurface(input.diagnostics, "ciFailure", input.userConfig), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
52423
+ if (shouldBlockCi(filterScansForSurface(input.completedScans, "ciFailure"), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
52108
52424
  };
52109
52425
  const buildChangedFilesDiffInfo = (changedFiles) => ({
52110
52426
  currentBranch: process.env.GITHUB_HEAD_REF?.trim() || null,
@@ -52153,6 +52469,7 @@ const inspectAction = async (directory, flags) => {
52153
52469
  const resolvedDirectory = scanTarget.resolvedDirectory;
52154
52470
  setJsonReportDirectory(resolvedDirectory);
52155
52471
  warnDeprecatedFailOn(flags, userConfig);
52472
+ warnDeprecatedDiff(flags, userConfig);
52156
52473
  if (scanTarget.didRedirectViaRootDir && !isQuiet) {
52157
52474
  cliLogger.dim(`Redirected to ${highlighter.info(toRelativePath(resolvedDirectory, requestedDirectory))} via react-doctor config "rootDir".`);
52158
52475
  cliLogger.break();
@@ -52214,18 +52531,28 @@ const inspectAction = async (directory, flags) => {
52214
52531
  });
52215
52532
  throw error;
52216
52533
  });
52534
+ const stagedWantsLines = resolveScope(flags, userConfig).scope === "lines";
52535
+ const stagedLineRanges = stagedWantsLines ? await getChangedLineRanges({
52536
+ directory: resolvedDirectory,
52537
+ cached: true,
52538
+ files: snapshot.stagedFiles
52539
+ }) : null;
52540
+ if (stagedWantsLines && stagedLineRanges === null && !isQuiet) {
52541
+ cliLogger.warn("Could not determine staged changed lines; reporting all issues in staged files.");
52542
+ cliLogger.break();
52543
+ }
52217
52544
  try {
52218
52545
  const scanResult = await inspect(snapshot.tempDirectory, {
52219
52546
  ...scanOptions,
52220
52547
  includePaths: snapshot.stagedFiles,
52221
- configOverride: userConfig
52548
+ configOverride: userConfig,
52549
+ changedLineRanges: stagedLineRanges ?? void 0
52222
52550
  });
52223
52551
  const remappedDiagnostics = scanResult.diagnostics.map((diagnostic) => ({
52224
52552
  ...diagnostic,
52225
52553
  filePath: Path.isAbsolute(diagnostic.filePath) ? diagnostic.filePath.replaceAll(snapshot.tempDirectory, () => resolvedDirectory) : diagnostic.filePath
52226
52554
  }));
52227
52555
  finalizeScans({
52228
- diagnostics: remappedDiagnostics,
52229
52556
  completedScans: [{
52230
52557
  directory: resolvedDirectory,
52231
52558
  result: {
@@ -52235,7 +52562,8 @@ const inspectAction = async (directory, flags) => {
52235
52562
  ...scanResult.project,
52236
52563
  rootDirectory: resolvedDirectory
52237
52564
  }
52238
- }
52565
+ },
52566
+ config: userConfig
52239
52567
  }],
52240
52568
  mode: "staged",
52241
52569
  diff: null,
@@ -52253,12 +52581,35 @@ const inspectAction = async (directory, flags) => {
52253
52581
  }
52254
52582
  return;
52255
52583
  }
52256
- const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts);
52584
+ const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts, userConfig?.projects);
52257
52585
  const changedFilesDiffInfo = flags.changedFilesFrom ? buildChangedFilesDiffInfo(readChangedFilesFrom(Path.resolve(flags.changedFilesFrom))) : null;
52258
- const effectiveDiff = resolveEffectiveDiff(flags, userConfig);
52259
- const diffInfo = changedFilesDiffInfo ?? (changedFilesDiffInfo === null && (effectiveDiff !== void 0 && effectiveDiff !== false || !skipPrompts && !isQuiet) ? await getDiffInfo(resolvedDirectory, typeof effectiveDiff === "string" ? effectiveDiff : void 0) : null);
52260
- const isDiffMode = changedFilesDiffInfo !== null || await resolveDiffMode(diffInfo, effectiveDiff, skipPrompts, isQuiet);
52261
- const baselineRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
52586
+ const requestedScope = resolveScope(flags, userConfig);
52587
+ const scopeRequest = requestedScope.scope === void 0 && changedFilesDiffInfo !== null ? {
52588
+ ...requestedScope,
52589
+ scope: "changed"
52590
+ } : requestedScope;
52591
+ const wantsDiffMode = scopeRequest.scope !== void 0 && scopeRequest.scope !== "full";
52592
+ const shouldDetectDiff = changedFilesDiffInfo === null && (wantsDiffMode || scopeRequest.scope === void 0 && !skipPrompts && !isQuiet);
52593
+ const diffInfo = changedFilesDiffInfo ?? (shouldDetectDiff ? await getDiffInfo(resolvedDirectory, scopeRequest.base) : null);
52594
+ const scope = await finalizeScope({
52595
+ requested: scopeRequest,
52596
+ diffInfo,
52597
+ skipPrompts,
52598
+ isQuiet
52599
+ });
52600
+ const isDiffMode = scope !== "full";
52601
+ const comparisonBaseRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
52602
+ const baselineRef = scope === "changed" ? comparisonBaseRef : null;
52603
+ const linesBaseRef = diffInfo?.isCurrentChanges ? "HEAD" : comparisonBaseRef;
52604
+ const changedLineRanges = scope === "lines" && diffInfo !== null && (diffInfo.isCurrentChanges || linesBaseRef !== null) && diffInfo !== null ? await getChangedLineRanges({
52605
+ directory: resolvedDirectory,
52606
+ baseRef: linesBaseRef ?? void 0,
52607
+ files: [...diffInfo.changedFiles]
52608
+ }) : null;
52609
+ if (scope === "lines" && changedLineRanges === null && !isQuiet) {
52610
+ cliLogger.warn("Could not determine changed lines (no base ref or git diff failed); reporting all issues in changed files.");
52611
+ cliLogger.break();
52612
+ }
52262
52613
  setJsonReportMode(baselineRef ? "baseline" : isDiffMode ? "diff" : "full");
52263
52614
  if (isDiffMode && diffInfo && !isQuiet) {
52264
52615
  if (diffInfo.isCurrentChanges) cliLogger.log("Scanning uncommitted changes");
@@ -52268,59 +52619,91 @@ const inspectAction = async (directory, flags) => {
52268
52619
  }
52269
52620
  cliLogger.break();
52270
52621
  }
52271
- const allDiagnostics = [];
52272
52622
  const completedScans = [];
52273
52623
  const isMultiProject = projectDirectories.length > 1;
52274
- const supplyChainEnabled = userConfig?.supplyChain?.enabled !== false;
52275
- for (const projectDirectory of projectDirectories) {
52624
+ const scanProject = async (projectDirectory) => {
52625
+ const projectScanTarget = projectDirectory === resolvedDirectory ? scanTarget : await resolveScanTarget(projectDirectory, { allowAmbiguous: true });
52626
+ const scanDirectory = projectScanTarget.resolvedDirectory;
52627
+ const projectConfig = projectDirectory === resolvedDirectory ? userConfig : mergeReactDoctorConfigs(userConfig, projectScanTarget.userConfig ?? void 0);
52628
+ const projectConfigSourceDirectory = projectScanTarget.userConfig?.plugins === void 0 ? scanTarget.configSourceDirectory : projectScanTarget.configSourceDirectory;
52629
+ const supplyChainEnabled = projectConfig?.supplyChain?.enabled !== false;
52276
52630
  let includePaths;
52277
52631
  let supplyChainManifestChanged = false;
52278
52632
  if (isDiffMode) {
52279
- const changedSourceFiles = diffInfo === null ? [] : resolveProjectDiffIncludePaths(resolvedDirectory, projectDirectory, diffInfo);
52280
- supplyChainManifestChanged = supplyChainEnabled && diffInfo !== null && projectManifestChanged(resolvedDirectory, projectDirectory, diffInfo);
52633
+ const changedSourceFiles = diffInfo === null ? [] : resolveProjectDiffIncludePaths(resolvedDirectory, scanDirectory, diffInfo);
52634
+ supplyChainManifestChanged = supplyChainEnabled && diffInfo !== null && projectManifestChanged(resolvedDirectory, scanDirectory, diffInfo);
52281
52635
  if (changedSourceFiles.length === 0 && !supplyChainManifestChanged) {
52282
52636
  if (!isQuiet) {
52283
- cliLogger.dim(`No changed source files in ${projectDirectory}, skipping.`);
52637
+ cliLogger.dim(`No changed source files in ${scanDirectory}, skipping.`);
52284
52638
  cliLogger.break();
52285
52639
  }
52286
- continue;
52640
+ return null;
52287
52641
  }
52288
52642
  includePaths = [...changedSourceFiles];
52289
52643
  if (supplyChainManifestChanged) includePaths.push("package.json");
52290
52644
  }
52291
52645
  if (!isQuiet && !isMultiProject) cliLogger.dim(" ");
52292
- const scanResult = await inspect(projectDirectory, {
52646
+ const scanResult = await inspect(scanDirectory, {
52293
52647
  ...scanOptions,
52294
52648
  includePaths,
52295
- configOverride: userConfig,
52649
+ configOverride: projectConfig,
52650
+ configSourceDirectory: projectConfigSourceDirectory ?? void 0,
52296
52651
  suppressRendering: isMultiProject,
52652
+ concurrentScan: isMultiProject,
52297
52653
  baseline: baselineRef ? { ref: baselineRef } : void 0,
52654
+ changedLineRanges: scope === "lines" && changedLineRanges !== null ? resolveProjectChangedLineRanges(resolvedDirectory, scanDirectory, changedLineRanges) : void 0,
52298
52655
  supplyChainManifestChanged
52299
52656
  });
52300
- allDiagnostics.push(...scanResult.diagnostics);
52301
- completedScans.push({
52302
- directory: projectDirectory,
52303
- result: scanResult
52304
- });
52305
52657
  if (!isQuiet && !isMultiProject) cliLogger.break();
52658
+ return {
52659
+ directory: scanDirectory,
52660
+ result: scanResult,
52661
+ config: projectConfig
52662
+ };
52663
+ };
52664
+ const scanLoopStartTime = performance$1.now();
52665
+ const projectCount = projectDirectories.length;
52666
+ const batchSpinner = isMultiProject && !isQuiet ? spinner(`Scanning ${projectCount} projects…`).start() : null;
52667
+ const ownsBatchSpinnerSilence = isMultiProject && scanOptions.silent === true;
52668
+ const wasSpinnerSilent = isSpinnerSilent();
52669
+ if (ownsBatchSpinnerSilence) setSpinnerSilent(true);
52670
+ let finishedProjectCount = 0;
52671
+ let scanOutcomes;
52672
+ try {
52673
+ scanOutcomes = await mapWithConcurrency(projectDirectories, isMultiProject ? 4 : 1, async (projectDirectory) => {
52674
+ const scanOutcome = await scanProject(projectDirectory);
52675
+ finishedProjectCount += 1;
52676
+ batchSpinner?.update(`Scanning ${projectCount} projects… (${finishedProjectCount}/${projectCount})`);
52677
+ return scanOutcome;
52678
+ });
52679
+ } finally {
52680
+ if (ownsBatchSpinnerSilence) setSpinnerSilent(wasSpinnerSilent);
52681
+ batchSpinner?.stop();
52682
+ }
52683
+ for (const scanOutcome of scanOutcomes) {
52684
+ if (scanOutcome === null) continue;
52685
+ completedScans.push(scanOutcome);
52306
52686
  }
52307
52687
  if (!isQuiet && isMultiProject && completedScans.length > 0) {
52308
52688
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
52309
52689
  await runPromise(printMultiProjectSummary({
52310
52690
  completedScans,
52311
52691
  categoryFilters,
52312
- userConfig,
52313
52692
  verbose: Boolean(flags.verbose),
52693
+ outputDirectory: flags.outputDir,
52314
52694
  isOffline: !shouldShowShareLink,
52315
- projectName: Path.basename(resolvedDirectory)
52695
+ projectName: Path.basename(resolvedDirectory),
52696
+ totalElapsedMilliseconds: performance$1.now() - scanLoopStartTime
52316
52697
  }));
52317
52698
  }
52699
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterScansForSurface(completedScans, scanOptions.outputSurface ?? "cli"), categoryFilters);
52700
+ const didScansWriteDump = isMultiProject ? !isQuiet && completedScans.length > 0 : completedScans.length > 0;
52701
+ if (flags.outputDir && !didScansWriteDump) await runPromise(printDiagnosticsDump(selectedSurfaceDiagnostics, flags.outputDir, false, isQuiet ? "stderr" : "stdout"));
52318
52702
  finalizeScans({
52319
- diagnostics: allDiagnostics,
52320
52703
  completedScans,
52321
52704
  mode: baselineRef ? "baseline" : isDiffMode ? "diff" : "full",
52322
52705
  diff: isDiffMode ? diffInfo : null,
52323
- baselineIntended: isDiffMode && diffInfo !== null && !diffInfo.isCurrentChanges,
52706
+ baselineIntended: scope === "changed" && diffInfo !== null && !diffInfo.isCurrentChanges,
52324
52707
  isJsonMode,
52325
52708
  isScoreOnly,
52326
52709
  flags,
@@ -52329,13 +52712,13 @@ const inspectAction = async (directory, flags) => {
52329
52712
  resolvedDirectory,
52330
52713
  startTime
52331
52714
  });
52332
- const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
52333
52715
  if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
52334
52716
  await handoffToAgent({
52335
52717
  diagnostics: selectedSurfaceDiagnostics,
52336
52718
  projectName: Path.basename(resolvedDirectory),
52337
52719
  rootDirectory: resolvedDirectory,
52338
- interactive: true
52720
+ interactive: true,
52721
+ outputDirectory: flags.outputDir
52339
52722
  });
52340
52723
  return;
52341
52724
  }
@@ -53127,11 +53510,14 @@ const ROOT_FLAG_SPEC = {
53127
53510
  "--yes"
53128
53511
  ]),
53129
53512
  longOptionsWithRequiredValues: new Set([
53513
+ "--base",
53130
53514
  "--category",
53131
53515
  "--changed-files-from",
53132
53516
  "--blocking",
53517
+ "--output-dir",
53133
53518
  "--fail-on",
53134
- "--project"
53519
+ "--project",
53520
+ "--scope"
53135
53521
  ]),
53136
53522
  longOptionsWithOptionalValues: new Set(["--diff"]),
53137
53523
  shortOptionsWithoutValues: new Set([
@@ -53283,6 +53669,7 @@ ${formatExampleLines([
53283
53669
  ["react-doctor", "scan the current project"],
53284
53670
  ["react-doctor ./apps/web", "scan a specific directory"],
53285
53671
  ["react-doctor --diff main", "scan only files changed vs. main"],
53672
+ ["react-doctor --project modules/a,modules/b", "score each module separately (names or paths)"],
53286
53673
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
53287
53674
  ["react-doctor --category Security", "show only one diagnostic category"],
53288
53675
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
@@ -53314,9 +53701,9 @@ ${highlighter.dim("Learn more:")}
53314
53701
  ${highlighter.info(CANONICAL_GITHUB_URL)}
53315
53702
  `;
53316
53703
  const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
53317
- 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("--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 force a full scan, overriding config)").addOption(new Option("--changed-files-from <file>", "scan source files listed in a newline-delimited changed-files file").hideHelp()).option("--no-score", "skip the score API, the share URL, and crash reporting").addOption(new Option("--category <category>", "only show diagnostics in a category (repeatable; e.g. Security)").argParser(collectCategoryOption)).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("--blocking <level>", "severity that fails CI: error (default), warning, or none (advisory)").addOption(new Option("--fail-on <level>", "[deprecated] alias for --blocking <level>").hideHelp()).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("--sfw", "demo: print the Socket.dev supply-chain score of every direct dependency, then exit").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
53704
+ 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("--output-dir <dir>", "directory for the full diagnostics dump (default: a temp folder)").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("--no-parallel", "lint serially with one worker (default: parallel across CPU cores; set the worker count with REACT_DOCTOR_PARALLEL)").option("--project <name>", "select projects: workspace names or directory paths (comma-separated for multiple); overrides the `projects` config field").option("--scope <value>", "how much to scan/report: full (default), files, changed (only new issues vs base), or lines (only changed lines)").option("--base <ref>", "base git ref for files/changed/lines scope (auto-detected when omitted)").addOption(new Option("--diff [base]", "[deprecated] alias for --scope changed (pass `false` to force a full scan)").hideHelp()).addOption(new Option("--changed-files-from <file>", "scan source files listed in a newline-delimited changed-files file").hideHelp()).option("--no-score", "skip the score API, the share URL, and crash reporting").addOption(new Option("--category <category>", "only show diagnostics in a category (repeatable; e.g. Security)").argParser(collectCategoryOption)).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("--blocking <level>", "severity that fails CI: error (default), warning, or none (advisory)").addOption(new Option("--fail-on <level>", "[deprecated] alias for --blocking <level>").hideHelp()).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("--sfw", "demo: print the Socket.dev supply-chain score of every direct dependency, then exit").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
53318
53705
  program.action(inspectAction);
53319
- program.command("why <location>").description("Explain why a rule fired (or why a suppression didn't apply) at a file:line").option("--project <name>", "select workspace project (comma-separated for multiple)").option("-c, --cwd <cwd>", "working directory", process.cwd()).option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").action((location, options) => whyAction(location, options));
53706
+ program.command("why <location>").description("Explain why a rule fired (or why a suppression didn't apply) at a file:line").option("--project <name>", "select projects: workspace names or directory paths (comma-separated for multiple)").option("-c, --cwd <cwd>", "working directory", process.cwd()).option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").action((location, options) => whyAction(location, options));
53320
53707
  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);
53321
53708
  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);
53322
53709
  const rules = program.command("rules").description("List, explain, and configure which React Doctor rules run");
@@ -53357,4 +53744,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
53357
53744
  export {};
53358
53745
 
53359
53746
  //# sourceMappingURL=cli.js.map
53360
- //# debugId=0551c9da-9fe1-599a-8bff-8c4ce0e4b2a1
53747
+ //# debugId=ecc7e4af-d176-5569-bc51-c3fbe220a76b