react-doctor 0.5.1-dev.94f9f4f → 0.5.1-dev.9cc6555

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]="f25bdf09-ff57-565e-b47b-46ef237158c2")}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]="5c7334de-5fd1-50a7-bb75-1a17b3b54e4e")}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));
@@ -22356,6 +22356,7 @@ var Diagnostic = class extends Class("Diagnostic")({
22356
22356
  endLine: optional(Number$1),
22357
22357
  endColumn: optional(Number$1),
22358
22358
  category: String$1,
22359
+ fileContext: optional(Literals(["test", "story"])),
22359
22360
  suppressionHint: optional(String$1),
22360
22361
  relatedLocations: optional(ArraySchema(DiagnosticRelatedLocation))
22361
22362
  }) {};
@@ -28330,7 +28331,7 @@ const ensuring = /* @__PURE__ */ dual(2, (self, finalizer) => fromChannel(ensuri
28330
28331
  * @category destructors
28331
28332
  * @since 2.0.0
28332
28333
  */
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))));
28334
+ 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
28335
  /**
28335
28336
  * Runs the stream and collects all elements into an array.
28336
28337
  *
@@ -35068,7 +35069,7 @@ const layer$3 = /* @__PURE__ */ effect(ChildProcessSpawner, /* @__PURE__ */ gen(
35068
35069
  evaluate: () => nodeStream,
35069
35070
  onError: (error) => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)
35070
35071
  });
35071
- if (config.stream) yield* forkScoped(run$1(config.stream, sink));
35072
+ if (config.stream) yield* forkScoped(run(config.stream, sink));
35072
35073
  inputSinks.set(fd, sink);
35073
35074
  break;
35074
35075
  }
@@ -35097,7 +35098,7 @@ const layer$3 = /* @__PURE__ */ effect(ChildProcessSpawner, /* @__PURE__ */ gen(
35097
35098
  endOnDone: config.endOnDone,
35098
35099
  encoding: config.encoding
35099
35100
  });
35100
- if (isStream(config.stream)) return as(forkScoped(run$1(config.stream, sink)), sink);
35101
+ if (isStream(config.stream)) return as(forkScoped(run(config.stream, sink)), sink);
35101
35102
  return succeed$2(sink);
35102
35103
  });
35103
35104
  const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {
@@ -37767,8 +37768,10 @@ const isFileIgnoredByPatterns = (filePath, rootDirectory, patterns) => {
37767
37768
  const relativePath = toRelativePath(filePath, rootDirectory);
37768
37769
  return patterns.some((pattern) => pattern.test(relativePath));
37769
37770
  };
37771
+ const SCRIPT_EXTENSION_FRAGMENT = "[cm]?[jt]sx?";
37772
+ const STORY_FILE_SUFFIX_PATTERN = new RegExp(`\\.(?:stories|story)\\.(?:${SCRIPT_EXTENSION_FRAGMENT})$`);
37773
+ const TEST_FILE_SUFFIX_PATTERN = new RegExp(`\\.(?:test|spec|fixture|fixtures)\\.(?:${SCRIPT_EXTENSION_FRAGMENT})$`);
37770
37774
  const TEST_FILE_DIRECTORY_PATTERN = /(?:^|\/)(?:__tests__|__test__|tests|test|__mocks__|cypress|e2e|playwright)\//;
37771
- const TEST_FILE_SUFFIX_PATTERN = /\.(?:test|spec|stories|story|fixture|fixtures)\.(?:[cm]?[jt]sx?)$/;
37772
37775
  const FIXTURE_PROJECT_PATTERN = /\/(?:fixtures|__fixtures__)\//;
37773
37776
  const SOURCE_ROOT_PATTERN = /\/(?:src|app|lib|components|pages|features|modules|packages|apps|frontend|client)\//g;
37774
37777
  const stripAboveSourceRoot = (relativePath) => {
@@ -37779,12 +37782,23 @@ const stripAboveSourceRoot = (relativePath) => {
37779
37782
  if (lastIdx >= 0) return relativePath.slice(lastIdx);
37780
37783
  return relativePath.slice(fixtureMatch.index + fixtureMatch[0].length - 1);
37781
37784
  };
37782
- const isTestFilePath = (relativePath) => {
37783
- if (relativePath.length === 0) return false;
37785
+ /**
37786
+ * Classifies where a file sits relative to shipped code. A finding in a
37787
+ * `.stories.tsx` or `.spec.ts` file never runs in front of users, so
37788
+ * renderers label those sites instead of framing them as production
37789
+ * impact (`rn-no-raw-text` in a spec doesn't say users crash).
37790
+ *
37791
+ * `"story"` is the `.stories.*` / `.story.*` suffix; `"test"` is the
37792
+ * test/spec/fixture suffixes and test directories; `"production"` is
37793
+ * the default.
37794
+ */
37795
+ const classifyFileContext = (relativePath) => {
37796
+ if (relativePath.length === 0) return "production";
37784
37797
  const forwardSlashed = relativePath.replaceAll("\\", "/");
37785
- if (TEST_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return true;
37798
+ if (STORY_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return "story";
37799
+ if (TEST_FILE_SUFFIX_PATTERN.test(forwardSlashed)) return "test";
37786
37800
  const scoped = stripAboveSourceRoot(forwardSlashed);
37787
- return TEST_FILE_DIRECTORY_PATTERN.test(scoped);
37801
+ return TEST_FILE_DIRECTORY_PATTERN.test(scoped) ? "test" : "production";
37788
37802
  };
37789
37803
  /**
37790
37804
  * Resolves the user-configured severity override for a rule.
@@ -38004,6 +38018,8 @@ const collectStringSet = (values) => {
38004
38018
  * 5. `rn-no-raw-text` suppression via configured `textComponents` and
38005
38019
  * `rawTextWrapperComponents` (config-driven JSX enclosure checks)
38006
38020
  * 6. inline suppressions (`// react-doctor-disable-next-line ...`)
38021
+ * 7. file-context stamping (`fileContext: "test" | "story"` on
38022
+ * survivors in non-production files, so renderers can label them)
38007
38023
  *
38008
38024
  * Returns `null` when the diagnostic is dropped, the (possibly
38009
38025
  * severity-restamped) diagnostic otherwise.
@@ -38023,7 +38039,7 @@ const buildDiagnosticPipeline = (input) => {
38023
38039
  const hasTextComponents = textComponentNames.size > 0;
38024
38040
  const hasRawTextWrappers = rawTextWrapperComponentNames.size > 0;
38025
38041
  const fileLinesCache = /* @__PURE__ */ new Map();
38026
- const testFileCache = /* @__PURE__ */ new Map();
38042
+ const fileContextCache = /* @__PURE__ */ new Map();
38027
38043
  const libraryFileCache = /* @__PURE__ */ new Map();
38028
38044
  const isLibraryFile = (filePath) => {
38029
38045
  let cached = libraryFileCache.get(filePath);
@@ -38040,11 +38056,11 @@ const buildDiagnosticPipeline = (input) => {
38040
38056
  fileLinesCache.set(filePath, lines);
38041
38057
  return lines;
38042
38058
  };
38043
- const isTest = (filePath) => {
38044
- let cached = testFileCache.get(filePath);
38059
+ const getFileContext = (filePath) => {
38060
+ let cached = fileContextCache.get(filePath);
38045
38061
  if (cached === void 0) {
38046
- cached = isTestFilePath(filePath);
38047
- testFileCache.set(filePath, cached);
38062
+ cached = classifyFileContext(filePath);
38063
+ fileContextCache.set(filePath, cached);
38048
38064
  }
38049
38065
  return cached;
38050
38066
  };
@@ -38053,7 +38069,7 @@ const buildDiagnosticPipeline = (input) => {
38053
38069
  const rule = reactDoctorPlugin.rules[diagnostic.rule];
38054
38070
  if (!rule?.tags?.includes("test-noise")) return false;
38055
38071
  if (rule.tags.includes("migration-hint")) return false;
38056
- return isTest(diagnostic.filePath);
38072
+ return getFileContext(diagnostic.filePath) !== "production";
38057
38073
  };
38058
38074
  const isRuleIgnored = (ruleIdentifier) => {
38059
38075
  for (const ignored of ignoredRules) if (isSameRuleKey(ignored, ruleIdentifier)) return true;
@@ -38110,6 +38126,11 @@ const buildDiagnosticPipeline = (input) => {
38110
38126
  };
38111
38127
  }
38112
38128
  }
38129
+ const fileContext = getFileContext(current.filePath);
38130
+ if (fileContext !== "production") current = {
38131
+ ...current,
38132
+ fileContext
38133
+ };
38113
38134
  return current;
38114
38135
  } };
38115
38136
  };
@@ -40271,6 +40292,42 @@ var Files = class Files extends Service()("react-doctor/Files") {
40271
40292
  }));
40272
40293
  };
40273
40294
  };
40295
+ const HUNK_HEADER_PATTERN = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
40296
+ /**
40297
+ * Parses a `git diff --unified=0` patch into the inclusive 1-based line ranges
40298
+ * each file added or modified on the new side. Files are keyed by the path in
40299
+ * the `+++ b/<path>` header (with `--relative`, relative to the diff's cwd).
40300
+ * Added/renamed/modified files appear; pure deletions (`+++ /dev/null`) are
40301
+ * skipped because they have no new-side line to report on.
40302
+ */
40303
+ const parseChangedLineRanges = (patch) => {
40304
+ const rangesByFile = /* @__PURE__ */ new Map();
40305
+ let currentRanges = null;
40306
+ for (const line of patch.split("\n")) {
40307
+ if (line.startsWith("+++ ")) {
40308
+ const target = line.slice(4).trim();
40309
+ if (target === "/dev/null") {
40310
+ currentRanges = null;
40311
+ continue;
40312
+ }
40313
+ const file = target.startsWith("b/") ? target.slice(2) : target;
40314
+ currentRanges = rangesByFile.get(file) ?? [];
40315
+ rangesByFile.set(file, currentRanges);
40316
+ continue;
40317
+ }
40318
+ if (currentRanges === null) continue;
40319
+ const hunk = HUNK_HEADER_PATTERN.exec(line);
40320
+ if (hunk === null) continue;
40321
+ const start = Number(hunk[1]);
40322
+ const lineCount = hunk[2] === void 0 ? 1 : Number(hunk[2]);
40323
+ if (lineCount <= 0) continue;
40324
+ currentRanges.push([start, start + lineCount - 1]);
40325
+ }
40326
+ return [...rangesByFile].filter(([, ranges]) => ranges.length > 0).map(([file, ranges]) => ({
40327
+ file,
40328
+ ranges
40329
+ }));
40330
+ };
40274
40331
  const trimOrNull = (value) => {
40275
40332
  const trimmed = value.trim();
40276
40333
  return trimmed.length === 0 ? null : trimmed;
@@ -40636,6 +40693,22 @@ var Git = class Git extends Service()("react-doctor/Git") {
40636
40693
  status: result.status,
40637
40694
  stdout: result.stdout
40638
40695
  };
40696
+ }),
40697
+ changedLineRanges: ({ directory, baseRef, cached, files }) => gen(function* () {
40698
+ if (files.length === 0) return [];
40699
+ if (baseRef !== void 0 && !isSafeGitRevision(baseRef)) return null;
40700
+ const result = yield* runGit(directory, [
40701
+ "diff",
40702
+ "--unified=0",
40703
+ "--diff-filter=ACMR",
40704
+ "--relative",
40705
+ ...cached ? ["--cached"] : [],
40706
+ ...baseRef !== void 0 ? [baseRef] : [],
40707
+ "--",
40708
+ ...files
40709
+ ]);
40710
+ if (result.status !== 0) return null;
40711
+ return parseChangedLineRanges(result.stdout);
40639
40712
  })
40640
40713
  });
40641
40714
  })).pipe(provide$2(layer$3.pipe(provide$2(mergeAll$1(layer$2, layer$1)))));
@@ -40666,7 +40739,8 @@ var Git = class Git extends Service()("react-doctor/Git") {
40666
40739
  status: matches.length === 0 ? 1 : 0,
40667
40740
  stdout
40668
40741
  };
40669
- })
40742
+ }),
40743
+ changedLineRanges: () => succeed$2(snapshot.changedLineRanges ?? [])
40670
40744
  }));
40671
40745
  };
40672
40746
  const estimateArgsLength = (args) => args.reduce((total, argument) => total + argument.length + 1, 0);
@@ -41658,8 +41732,18 @@ const shouldSuppressLocalUseHookDiagnostic = (diagnostic, rootDirectory) => {
41658
41732
  return bindingResolution !== null && !bindingResolution.isReactUseBinding;
41659
41733
  };
41660
41734
  const FILEPATH_WITH_LOCATION_PATTERN = /\S+\.\w+:\d+:\d+[\s\S]*$/;
41735
+ const LEADING_SEVERITY_LABEL_PATTERN = /^(?:Error|Warning):\s*/;
41736
+ const TRAILING_PERIOD_PATTERN = /\.$/;
41661
41737
  const REACT_COMPILER_TITLE = "React Compiler can't optimize this";
41662
- 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.";
41738
+ const REACT_COMPILER_TODO_TITLE = "React Compiler doesn't support this syntax";
41739
+ const REACT_COMPILER_IMPACT = "This component misses React Compiler's automatic memoization & re-renders more than it should";
41740
+ const REACT_COMPILER_ACTION = "Rewrite the flagged code so the compiler can optimize it.";
41741
+ const REACT_COMPILER_GENERIC_MESSAGE = `${REACT_COMPILER_IMPACT}. ${REACT_COMPILER_ACTION}`;
41742
+ const buildReactCompilerMessage = (reasonSummary) => {
41743
+ const normalizedSummary = reasonSummary.replace(TRAILING_PERIOD_PATTERN, "");
41744
+ if (!normalizedSummary) return REACT_COMPILER_GENERIC_MESSAGE;
41745
+ return `${REACT_COMPILER_IMPACT}: ${normalizedSummary}. ${REACT_COMPILER_ACTION}`;
41746
+ };
41663
41747
  const PLUGIN_CATEGORY_MAP = {
41664
41748
  react: "Bugs",
41665
41749
  "react-hooks": "Bugs",
@@ -41686,7 +41770,10 @@ const getRuleRecommendation = (ruleName, project) => {
41686
41770
  };
41687
41771
  const getRuleCategory = (ruleName) => reactDoctorPlugin.rules[ruleName]?.category;
41688
41772
  const getRuleTitle = (ruleName) => reactDoctorPlugin.rules[ruleName]?.title;
41689
- const resolveDiagnosticTitle = (plugin, rule) => plugin === "react-hooks-js" ? REACT_COMPILER_TITLE : getRuleTitle(rule);
41773
+ const resolveDiagnosticTitle = (plugin, rule) => {
41774
+ if (plugin !== "react-hooks-js") return getRuleTitle(rule);
41775
+ return rule === "todo" ? REACT_COMPILER_TODO_TITLE : REACT_COMPILER_TITLE;
41776
+ };
41690
41777
  const cleanDiagnosticMessage = (message, help, plugin, rule, project) => {
41691
41778
  const cleaned = resolveCleanedDiagnostic(typeof message === "string" ? message : "", typeof help === "string" ? help : "", plugin, rule, project);
41692
41779
  return {
@@ -41695,10 +41782,19 @@ const cleanDiagnosticMessage = (message, help, plugin, rule, project) => {
41695
41782
  };
41696
41783
  };
41697
41784
  const resolveCleanedDiagnostic = (message, help, plugin, rule, project) => {
41698
- if (plugin === "react-hooks-js") return {
41699
- message: REACT_COMPILER_MESSAGE,
41700
- help: appendReanimatedSharedValueHint(message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim() || help, rule, project)
41701
- };
41785
+ if (plugin === "react-hooks-js") {
41786
+ const bailoutReason = message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim().replace(LEADING_SEVERITY_LABEL_PATTERN, "").trim();
41787
+ if (rule === "todo") return {
41788
+ message: REACT_COMPILER_GENERIC_MESSAGE,
41789
+ help: appendReanimatedSharedValueHint(bailoutReason || help, rule, project)
41790
+ };
41791
+ const [reasonSummary = "", ...reasonDetailLines] = bailoutReason.split("\n");
41792
+ const reasonDetail = reasonDetailLines.join("\n").trim();
41793
+ return {
41794
+ message: buildReactCompilerMessage(reasonSummary.trim()),
41795
+ help: appendReanimatedSharedValueHint(reasonDetail || help, rule, project)
41796
+ };
41797
+ }
41702
41798
  return {
41703
41799
  message: message.replace(FILEPATH_WITH_LOCATION_PATTERN, "").trim() || message,
41704
41800
  help: help || getRuleRecommendation(rule, project) || ""
@@ -42365,7 +42461,7 @@ const ScoreApiResponseSchema = Struct({
42365
42461
  })))
42366
42462
  });
42367
42463
  const parseScoreResult = (value) => getOrNull(decodeUnknownOption(ScoreApiResponseSchema)(value));
42368
- const stripFilePaths = (diagnostics) => diagnostics.map(({ filePath: _filePath, ...rest }) => rest);
42464
+ const stripLocalFileFields = (diagnostics) => diagnostics.map(({ filePath: _filePath, fileContext: _fileContext, ...rest }) => rest);
42369
42465
  const isAbortError = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
42370
42466
  const describeFailure = (error) => {
42371
42467
  if (isAbortError(error)) return `timed out after ${FETCH_TIMEOUT_MS / 1e3}s`;
@@ -42378,7 +42474,7 @@ const calculateScore = async (diagnostics, options = {}) => {
42378
42474
  const requestUrl = options.isCi ? `${SCORE_API_URL}?ci=1` : SCORE_API_URL;
42379
42475
  try {
42380
42476
  const compressedBody = gzipSync(JSON.stringify({
42381
- diagnostics: stripFilePaths(diagnostics),
42477
+ diagnostics: stripLocalFileFields(diagnostics),
42382
42478
  ...options.metadata?.repo ? { repo: options.metadata.repo } : {},
42383
42479
  ...options.metadata?.sha ? { sha: options.metadata.sha } : {},
42384
42480
  ...options.metadata?.framework ? { framework: options.metadata.framework } : {},
@@ -42445,25 +42541,36 @@ const decodeArtifact = decodeUnknownOption(Struct({ score: optional(Struct({
42445
42541
  const SCORE_AXES = [
42446
42542
  {
42447
42543
  key: "supplyChain",
42448
- label: "supply chain"
42544
+ label: "supply chain",
42545
+ gates: true
42449
42546
  },
42450
42547
  {
42451
42548
  key: "vulnerability",
42452
- label: "vulnerability"
42549
+ label: "vulnerability",
42550
+ gates: true
42453
42551
  },
42454
42552
  {
42455
42553
  key: "maintenance",
42456
- label: "maintenance"
42554
+ label: "maintenance",
42555
+ gates: false
42457
42556
  },
42458
42557
  {
42459
42558
  key: "quality",
42460
- label: "quality"
42559
+ label: "quality",
42560
+ gates: false
42461
42561
  },
42462
42562
  {
42463
42563
  key: "license",
42464
- label: "license"
42564
+ label: "license",
42565
+ gates: false
42465
42566
  }
42466
42567
  ];
42568
+ const GATED_AXES = SCORE_AXES.filter((axis) => axis.gates);
42569
+ const worstGatedAxis = (score) => {
42570
+ let worst = GATED_AXES[0];
42571
+ for (const axis of GATED_AXES) if (score[axis.key] < score[worst.key]) worst = axis;
42572
+ return worst;
42573
+ };
42467
42574
  const clampScore = (value) => {
42468
42575
  if (!Number.isFinite(value)) return 50;
42469
42576
  return Math.min(Math.max(value, 0), 100);
@@ -42604,15 +42711,14 @@ const fetchSocketScore = (dependency) => tryPromise(async (signal) => {
42604
42711
  "socket.purl": toPurl(dependency)
42605
42712
  } }));
42606
42713
  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);
42714
+ const buildLowScoreDiagnostic = (dependency, score, failingAxis, options) => {
42609
42715
  const packagePageUrl = `${SOCKET_PACKAGE_PAGE_BASE}/${dependency.name}/overview/${dependency.version}`;
42610
42716
  return {
42611
42717
  filePath: "package.json",
42612
42718
  plugin: SUPPLY_CHAIN_PLUGIN,
42613
42719
  rule: SUPPLY_CHAIN_RULE,
42614
42720
  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)}.`,
42721
+ 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
42722
  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
42723
  url: packagePageUrl,
42618
42724
  line: dependency.line,
@@ -42647,7 +42753,9 @@ const collectSupplyChainScores = (input) => gen(function* () {
42647
42753
  * Scores every direct dependency in the project's `package.json` against
42648
42754
  * Socket.dev's free PURL endpoint (the same one Socket Firewall's free tier
42649
42755
  * uses — no API key) and returns a diagnostic for each dependency whose
42650
- * Socket `overall` score is below the configured `minScore`.
42756
+ * worst Socket *security* axis — supply chain or vulnerability — is below
42757
+ * the configured `minScore`. The quality / maintenance / license axes are
42758
+ * reported as context but never gate (see GATED_AXES).
42651
42759
  *
42652
42760
  * Lookups run with bounded concurrency via `Effect.forEach`. The check is
42653
42761
  * total/fail-open: each per-package lookup already recovers to `null`
@@ -42665,8 +42773,9 @@ const checkSupplyChain = (input) => gen(function* () {
42665
42773
  for (let index = 0; index < dependencies.length; index += 1) {
42666
42774
  const score = scores[index];
42667
42775
  if (!score) continue;
42668
- if (toHundred(score.overall) >= options.minScore) continue;
42669
- diagnostics.push(buildLowScoreDiagnostic(dependencies[index], score, options));
42776
+ const worstAxis = worstGatedAxis(score);
42777
+ if (toHundred(score[worstAxis.key]) >= options.minScore) continue;
42778
+ diagnostics.push(buildLowScoreDiagnostic(dependencies[index], score, worstAxis, options));
42670
42779
  }
42671
42780
  return diagnostics;
42672
42781
  });
@@ -42674,7 +42783,8 @@ const checkSupplyChain = (input) => gen(function* () {
42674
42783
  * `SupplyChain` scores the project's direct dependencies against Socket.dev's
42675
42784
  * free, keyless PURL endpoint — the same lookup Socket Firewall's free tier
42676
42785
  * (`sfw`) performs — and streams a diagnostic for each dependency whose
42677
- * Socket score falls below the configured `supplyChain.minScore`.
42786
+ * worst Socket security axis (supply chain or vulnerability) falls below
42787
+ * the configured `supplyChain.minScore`.
42678
42788
  *
42679
42789
  * Runs by default (one network request per dependency); the orchestrator
42680
42790
  * provides `layerOf([])` only when the user opts out via
@@ -43366,6 +43476,21 @@ const getDiffInfo = (directory, explicitBaseBranch) => runPromise(gen(function*
43366
43476
  }).pipe(provide(Git.layerNode)));
43367
43477
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
43368
43478
  /**
43479
+ * Programmatic façade over `Git.changedLineRanges` (the `lines` scope). Diffs
43480
+ * `files` with `--unified=0` against `baseRef` (or the index when `cached`),
43481
+ * returning per-file changed line ranges relative to `directory`. Returns
43482
+ * `null` when the ranges can't be computed (git unavailable / unsafe ref /
43483
+ * non-zero exit) so the caller degrades to file-level scope; an empty array
43484
+ * means git succeeded but the files added no lines.
43485
+ */
43486
+ const getChangedLineRanges = (input) => runPromise(gen(function* () {
43487
+ const ranges = yield* (yield* Git).changedLineRanges(input);
43488
+ return ranges === null ? null : ranges.map((entry) => ({
43489
+ file: entry.file,
43490
+ ranges: entry.ranges
43491
+ }));
43492
+ }).pipe(provide(Git.layerNode)));
43493
+ /**
43369
43494
  * Canonical URL for a rule's documentation page — its reviewer-tested fix
43370
43495
  * recipe rendered for humans — served at
43371
43496
  * `https://react.doctor/docs/rules/<plugin>/<rule>`. The CLI links here
@@ -43414,6 +43539,48 @@ const groupBy = (items, keyFn) => {
43414
43539
  * a 404. Gate the directive on this predicate.
43415
43540
  */
43416
43541
  const hasPublishedFixRecipe = (diagnostic) => diagnostic.plugin === "react-doctor" && Object.hasOwn(reactDoctorPlugin.rules, diagnostic.rule);
43542
+ const unionValues = (baseValues, overrideValues) => [...new Set([...baseValues, ...overrideValues])];
43543
+ const mergeIgnores = (baseIgnore, overrideIgnore) => {
43544
+ const mergedIgnore = {
43545
+ ...baseIgnore,
43546
+ ...overrideIgnore
43547
+ };
43548
+ if (baseIgnore.rules && overrideIgnore.rules) mergedIgnore.rules = unionValues(baseIgnore.rules, overrideIgnore.rules);
43549
+ if (baseIgnore.files && overrideIgnore.files) mergedIgnore.files = unionValues(baseIgnore.files, overrideIgnore.files);
43550
+ if (baseIgnore.tags && overrideIgnore.tags) mergedIgnore.tags = unionValues(baseIgnore.tags, overrideIgnore.tags);
43551
+ if (baseIgnore.overrides && overrideIgnore.overrides) mergedIgnore.overrides = [...baseIgnore.overrides, ...overrideIgnore.overrides];
43552
+ return mergedIgnore;
43553
+ };
43554
+ /**
43555
+ * Layer one `ReactDoctorConfig` on top of another, additively: `rules` /
43556
+ * `categories` / `supplyChain` merge per key, `ignore` lists union
43557
+ * (`ignore.overrides` concatenate), and every other field is a scalar the
43558
+ * override simply wins on when set. Returns the base unchanged when there
43559
+ * is no override, and vice versa — so callers can thread `null` /
43560
+ * `undefined` through without special-casing.
43561
+ */
43562
+ const mergeReactDoctorConfigs = (baseConfig, overrideConfig) => {
43563
+ if (overrideConfig === void 0) return baseConfig;
43564
+ if (baseConfig === null) return overrideConfig;
43565
+ const mergedConfig = {
43566
+ ...baseConfig,
43567
+ ...overrideConfig
43568
+ };
43569
+ if (baseConfig.rules && overrideConfig.rules) mergedConfig.rules = {
43570
+ ...baseConfig.rules,
43571
+ ...overrideConfig.rules
43572
+ };
43573
+ if (baseConfig.categories && overrideConfig.categories) mergedConfig.categories = {
43574
+ ...baseConfig.categories,
43575
+ ...overrideConfig.categories
43576
+ };
43577
+ if (baseConfig.supplyChain && overrideConfig.supplyChain) mergedConfig.supplyChain = {
43578
+ ...baseConfig.supplyChain,
43579
+ ...overrideConfig.supplyChain
43580
+ };
43581
+ if (baseConfig.ignore && overrideConfig.ignore) mergedConfig.ignore = mergeIgnores(baseConfig.ignore, overrideConfig.ignore);
43582
+ return mergedConfig;
43583
+ };
43417
43584
  //#endregion
43418
43585
  //#region src/cli/utils/is-ci-environment.ts
43419
43586
  const CI_ENVIRONMENT_VARIABLES = [
@@ -43511,6 +43678,7 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
43511
43678
  //#region src/cli/utils/constants.ts
43512
43679
  const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
43513
43680
  const BASELINE_FILES_TEMP_DIR_PREFIX = "react-doctor-baseline-";
43681
+ const GH_DEFAULT_BRANCH_PROBE_TIMEOUT_MS = 5e3;
43514
43682
  const CI_TRUST_COMPANIES = "PayPal, Rippling, and Alibaba";
43515
43683
  const WELCOME_EXPLANATION_HOLD_MS = 1e3;
43516
43684
  const CATEGORY_COUNTUP_SETTLE_HOLD_MS = 1e3;
@@ -43521,6 +43689,8 @@ const METRIC = {
43521
43689
  cliInvoked: "cli.invoked",
43522
43690
  cliError: "cli.error",
43523
43691
  projectDetected: "project.detected",
43692
+ projectPathSelected: "project.path_selected",
43693
+ projectConfigSelected: "project.config_selected",
43524
43694
  scanCompleted: "scan.completed",
43525
43695
  scanDuration: "scan.duration",
43526
43696
  scanPhaseDuration: "scan.phase_duration",
@@ -43590,7 +43760,7 @@ const makeNoopConsole = () => ({
43590
43760
  });
43591
43761
  //#endregion
43592
43762
  //#region src/cli/utils/version.ts
43593
- const VERSION = "0.5.1-dev.94f9f4f";
43763
+ const VERSION = "0.5.1-dev.9cc6555";
43594
43764
  //#endregion
43595
43765
  //#region src/cli/utils/json-mode.ts
43596
43766
  let context = null;
@@ -43948,13 +44118,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
43948
44118
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
43949
44119
  * standard `SENTRY_RELEASE` override.
43950
44120
  */
43951
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.5.1-dev.94f9f4f`;
44121
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.5.1-dev.9cc6555`;
43952
44122
  /**
43953
44123
  * Deployment environment shown in Sentry's environment filter. Defaults to
43954
44124
  * `production` for tagged releases and `development` for dev/unbuilt versions,
43955
44125
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
43956
44126
  */
43957
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.5.1-dev.94f9f4f") ? "development" : "production");
44127
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.5.1-dev.9cc6555") ? "development" : "production");
43958
44128
  /**
43959
44129
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
43960
44130
  * (set to `0` to disable tracing) and falls back to
@@ -47252,12 +47422,13 @@ const toSpanAttributes = (tags) => {
47252
47422
  /**
47253
47423
  * Clears the module-level run-scoped Sentry state — the current scanned project
47254
47424
  * 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).
47425
+ * again after a clean one, so a prior or just-finished scan can't attach its
47426
+ * project tags / trace to a later run or to a non-scan error (e.g.
47427
+ * inspectAction's post-loop finalize/handoff steps). A thrown scan error skips
47428
+ * the post-run reset, leaving the state for the command catch to attribute and
47429
+ * link the crash. Concurrent batch members (`concurrentScan`) never touch this
47430
+ * state — they neither write nor reset it. Safe to call when Sentry is off (the
47431
+ * refs are read only when an event is built).
47261
47432
  */
47262
47433
  const resetSentryRunState = () => {
47263
47434
  setSentryProjectInfo(null);
@@ -47280,8 +47451,13 @@ const resetSentryRunState = () => {
47280
47451
  * state right after a clean run and at the start of the next one, so the trace
47281
47452
  * is never attached to a non-scan error; on a thrown error the state is left in
47282
47453
  * place for the command catch, then the process exits.
47454
+ *
47455
+ * A `concurrentScan` (one member of the CLI's multi-project pool) still gets
47456
+ * its own root span, but skips recording the active run trace — the module-
47457
+ * level handle has single-scan semantics, and overlapping writers would link a
47458
+ * crash to an arbitrary sibling's trace.
47283
47459
  */
47284
- const withSentryRunSpan = (run) => {
47460
+ const withSentryRunSpan = (run, options = {}) => {
47285
47461
  if (!isSentryTracingEnabled()) return run(void 0);
47286
47462
  const { tags } = buildSentryScope();
47287
47463
  const command = typeof tags.command === "string" ? tags.command : "inspect";
@@ -47290,12 +47466,14 @@ const withSentryRunSpan = (run) => {
47290
47466
  op: "cli.inspect",
47291
47467
  attributes: toSpanAttributes(tags)
47292
47468
  }, (rootSpan) => {
47293
- const spanContext = rootSpan.spanContext();
47294
- setActiveRunTrace({
47295
- traceId: spanContext.traceId,
47296
- spanId: spanContext.spanId,
47297
- sampled: (spanContext.traceFlags & 1) === 1
47298
- });
47469
+ if (options.concurrentScan !== true) {
47470
+ const spanContext = rootSpan.spanContext();
47471
+ setActiveRunTrace({
47472
+ traceId: spanContext.traceId,
47473
+ spanId: spanContext.spanId,
47474
+ sampled: (spanContext.traceFlags & 1) === 1
47475
+ });
47476
+ }
47299
47477
  return run(rootSpan);
47300
47478
  });
47301
47479
  };
@@ -47306,9 +47484,15 @@ const withSentryRunSpan = (run) => {
47306
47484
  * run's root span so the transaction/trace carries the project shape too.
47307
47485
  * Always cheap — the span attribute set is skipped when `rootSpan` is absent
47308
47486
  * (tracing off), and storing the info is a plain assignment.
47487
+ *
47488
+ * A `concurrentScan` only sets the span attributes: the module-level project
47489
+ * ref has single-scan semantics, and overlapping writers would stamp events
47490
+ * and metrics with an arbitrary sibling's project. Wide events keep full
47491
+ * attribution (they ride the span); per-emit metrics simply omit the project
47492
+ * shape during a concurrent batch (absent, never wrong).
47309
47493
  */
47310
- const recordSentryProjectContext = (projectInfo, rootSpan) => {
47311
- setSentryProjectInfo(projectInfo);
47494
+ const recordSentryProjectContext = (projectInfo, rootSpan, options = {}) => {
47495
+ if (options.concurrentScan !== true) setSentryProjectInfo(projectInfo);
47312
47496
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
47313
47497
  };
47314
47498
  //#endregion
@@ -47545,6 +47729,12 @@ const buildOutcomeAttributes = (input) => {
47545
47729
  topRule = rule;
47546
47730
  topRuleCount = count;
47547
47731
  }
47732
+ let diagnosticsInTestFiles = 0;
47733
+ let diagnosticsInStoryFiles = 0;
47734
+ for (const diagnostic of result.diagnostics) {
47735
+ if (diagnostic.fileContext === "test") diagnosticsInTestFiles += 1;
47736
+ if (diagnostic.fileContext === "story") diagnosticsInStoryFiles += 1;
47737
+ }
47548
47738
  const attributes = {
47549
47739
  outcome,
47550
47740
  exitCode: wouldBlock ? 1 : 0,
@@ -47555,6 +47745,8 @@ const buildOutcomeAttributes = (input) => {
47555
47745
  errorCount: summary.errorCount,
47556
47746
  warningCount: summary.warningCount,
47557
47747
  affectedFiles: summary.affectedFileCount,
47748
+ diagnosticsInTestFiles,
47749
+ diagnosticsInStoryFiles,
47558
47750
  distinctRulesFired: countByRule.size,
47559
47751
  topRule,
47560
47752
  scannedFileCount: result.scannedFileCount ?? null,
@@ -47593,6 +47785,7 @@ const buildConfigAttributes = (input) => {
47593
47785
  const ruleKeys = Object.keys(ruleOverrides);
47594
47786
  return {
47595
47787
  mode: input.mode,
47788
+ scope: input.scope,
47596
47789
  parallel: input.parallel,
47597
47790
  workerCount: input.workerCount ?? null,
47598
47791
  lint: input.lint,
@@ -47601,6 +47794,7 @@ const buildConfigAttributes = (input) => {
47601
47794
  noScore: input.noScore,
47602
47795
  respectInlineDisables: input.respectInlineDisables,
47603
47796
  showWarnings: input.showWarnings,
47797
+ usedOutputDir: input.usedOutputDir,
47604
47798
  ignoredTagCount: input.ignoredTagCount,
47605
47799
  hasCustomConfig: input.hasCustomConfig,
47606
47800
  rulesConfigured: ruleKeys.length,
@@ -47634,6 +47828,9 @@ const recordRunEvent = (rootSpan, input) => {
47634
47828
  } catch {}
47635
47829
  };
47636
47830
  //#endregion
47831
+ //#region src/cli/utils/path-format.ts
47832
+ const toForwardSlashes = (filePath) => filePath.replaceAll("\\", "/");
47833
+ //#endregion
47637
47834
  //#region src/cli/utils/materialize-baseline-files.ts
47638
47835
  /**
47639
47836
  * Materializes the `ref` version of `files` into `tempDirectory` (via
@@ -47882,17 +48079,24 @@ const writeStdout = (text) => sync(() => {
47882
48079
  const POINTER = isUnicodeSupported() ? "›" : ">";
47883
48080
  const colorizeBySeverity = (text, severity) => severity === "error" ? highlighter.error(text) : highlighter.warn(text);
47884
48081
  const collectAffectedFiles = (diagnostics) => new Set(diagnostics.map((diagnostic) => diagnostic.filePath));
47885
- const buildVerboseSiteMap = (diagnostics) => {
47886
- const fileSites = /* @__PURE__ */ new Map();
48082
+ const formatFileContextTag = (diagnostic) => diagnostic.fileContext ? ` (${diagnostic.fileContext} file)` : "";
48083
+ const buildVerboseFileEntries = (diagnostics) => {
48084
+ const fileEntries = /* @__PURE__ */ new Map();
47887
48085
  for (const diagnostic of diagnostics) {
47888
- const sites = fileSites.get(diagnostic.filePath) ?? [];
47889
- if (diagnostic.line > 0) sites.push({
48086
+ let entry = fileEntries.get(diagnostic.filePath);
48087
+ if (entry === void 0) {
48088
+ entry = {
48089
+ contextTag: formatFileContextTag(diagnostic),
48090
+ sites: []
48091
+ };
48092
+ fileEntries.set(diagnostic.filePath, entry);
48093
+ }
48094
+ if (diagnostic.line > 0) entry.sites.push({
47890
48095
  line: diagnostic.line,
47891
48096
  suppressionHint: diagnostic.suppressionHint
47892
48097
  });
47893
- fileSites.set(diagnostic.filePath, sites);
47894
48098
  }
47895
- return fileSites;
48099
+ return fileEntries;
47896
48100
  };
47897
48101
  const formatSiteCountBadge = (count) => count > 1 ? `×${count}` : "";
47898
48102
  const formatTrailingSiteBadge = (count) => {
@@ -47981,10 +48185,11 @@ const clusterNearbyDiagnostics = (diagnostics) => {
47981
48185
  return clusters;
47982
48186
  };
47983
48187
  const formatClusterLocation = (cluster) => {
47984
- const { filePath } = cluster.diagnostics[0];
47985
- if (cluster.startLine <= 0) return filePath;
47986
- if (cluster.endLine > cluster.startLine) return `${filePath}:${cluster.startLine}-${cluster.endLine}`;
47987
- return `${filePath}:${cluster.startLine}`;
48188
+ const lead = cluster.diagnostics[0];
48189
+ const contextTag = formatFileContextTag(lead);
48190
+ if (cluster.startLine <= 0) return `${lead.filePath}${contextTag}`;
48191
+ if (cluster.endLine > cluster.startLine) return `${lead.filePath}:${cluster.startLine}-${cluster.endLine}${contextTag}`;
48192
+ return `${lead.filePath}:${cluster.startLine}${contextTag}`;
47988
48193
  };
47989
48194
  const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame) => {
47990
48195
  const lead = cluster.diagnostics[0];
@@ -48127,25 +48332,26 @@ const formatElapsedTime = (elapsedMilliseconds) => {
48127
48332
  };
48128
48333
  const formatRuleSummary = (ruleKey, ruleDiagnostics) => {
48129
48334
  const firstDiagnostic = ruleDiagnostics[0];
48335
+ const distinctMessages = [...new Set(ruleDiagnostics.map((diagnostic) => diagnostic.message))];
48130
48336
  const sections = [
48131
48337
  `Rule: ${ruleKey}`,
48132
48338
  `Severity: ${firstDiagnostic.severity}`,
48133
48339
  `Category: ${firstDiagnostic.category}`,
48134
48340
  `Count: ${ruleDiagnostics.length}`,
48135
48341
  "",
48136
- firstDiagnostic.message
48342
+ distinctMessages.join("\n\n")
48137
48343
  ];
48138
48344
  if (firstDiagnostic.help) sections.push("", `Suggestion: ${firstDiagnostic.help}`);
48139
48345
  if (firstDiagnostic.url) sections.push("", `Docs: ${firstDiagnostic.url}`);
48140
48346
  const fixRecipeLine = formatFixRecipeLine(firstDiagnostic);
48141
48347
  if (fixRecipeLine) sections.push("", fixRecipeLine);
48142
48348
  sections.push("", "Files:");
48143
- const fileSites = buildVerboseSiteMap(ruleDiagnostics);
48144
- for (const [filePath, sites] of fileSites) if (sites.length > 0) for (const site of sites) {
48145
- sections.push(` ${filePath}:${site.line}`);
48349
+ const fileEntries = buildVerboseFileEntries(ruleDiagnostics);
48350
+ for (const [filePath, { contextTag, sites }] of fileEntries) if (sites.length > 0) for (const site of sites) {
48351
+ sections.push(` ${filePath}:${site.line}${contextTag}`);
48146
48352
  if (site.suppressionHint) sections.push(` ${site.suppressionHint}`);
48147
48353
  }
48148
- else sections.push(` ${filePath}`);
48354
+ else sections.push(` ${filePath}${contextTag}`);
48149
48355
  return sections.join("\n") + "\n";
48150
48356
  };
48151
48357
  //#endregion
@@ -48415,15 +48621,22 @@ const printNoScoreHeader = (noScoreMessage) => gen(function* () {
48415
48621
  });
48416
48622
  //#endregion
48417
48623
  //#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));
48624
+ const ruleDumpFileName = (ruleKey) => ruleKey.replace(/\//g, "--") + ".txt";
48625
+ const readPreviousRuleDumpFileNames = (directory) => {
48626
+ try {
48627
+ const previous = JSON.parse(NFS.readFileSync(Path.join(directory, "diagnostics.json"), "utf8"));
48628
+ return new Set(previous.filter((d) => typeof d?.plugin === "string" && typeof d?.rule === "string").map((d) => ruleDumpFileName(`${d.plugin}/${d.rule}`)));
48629
+ } catch {
48630
+ return /* @__PURE__ */ new Set();
48424
48631
  }
48425
- NFS.writeFileSync(Path.join(outputDirectory, "diagnostics.json"), JSON.stringify(diagnostics));
48426
- return outputDirectory;
48632
+ };
48633
+ const writeDiagnosticsDirectory = (diagnostics, outputDirectory) => {
48634
+ const directory = outputDirectory ? Path.resolve(outputDirectory) : Path.join(tmpdir(), `react-doctor-${randomUUID()}`);
48635
+ if (outputDirectory) for (const fileName of readPreviousRuleDumpFileNames(directory)) NFS.rmSync(Path.join(directory, fileName), { force: true });
48636
+ NFS.mkdirSync(directory, { recursive: true });
48637
+ for (const [ruleKey, ruleDiagnostics] of buildSortedRuleGroups(diagnostics)) NFS.writeFileSync(Path.join(directory, ruleDumpFileName(ruleKey)), formatRuleSummary(ruleKey, ruleDiagnostics));
48638
+ NFS.writeFileSync(Path.join(directory, "diagnostics.json"), JSON.stringify(diagnostics));
48639
+ return directory;
48427
48640
  };
48428
48641
  //#endregion
48429
48642
  //#region src/cli/utils/render-summary.ts
@@ -48460,6 +48673,16 @@ const printFooter = (input) => gen(function* () {
48460
48673
  yield* log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
48461
48674
  yield* printFooterDescription("Report issues and star the repository!");
48462
48675
  });
48676
+ const printDiagnosticsDump = (diagnostics, outputDirectory, verbose, stream = "stdout") => gen(function* () {
48677
+ const writtenDirectory = yield* try_({
48678
+ try: () => writeDiagnosticsDirectory(diagnostics, outputDirectory),
48679
+ catch: (cause) => cause
48680
+ }).pipe(orElseSucceed(() => null));
48681
+ if (writtenDirectory !== null && (verbose || outputDirectory)) {
48682
+ const pathLine = highlighter.gray(` Full diagnostics written to ${writtenDirectory}`);
48683
+ yield* stream === "stderr" || Boolean(outputDirectory) && isJsonModeActive() ? sync(() => process.stderr.write(`${pathLine}\n`)) : log(pathLine);
48684
+ }
48685
+ });
48463
48686
  const printSummary = (input) => gen(function* () {
48464
48687
  if (input.scoreResult) {
48465
48688
  const animateProjection = Boolean(input.animateProjection) && input.potentialScore != null && !input.verbose;
@@ -48470,11 +48693,7 @@ const printSummary = (input) => gen(function* () {
48470
48693
  if (animateProjection) yield* animateScoreProjection(input.scoreResult, input.potentialScore, 5);
48471
48694
  }
48472
48695
  } 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}`));
48696
+ yield* printDiagnosticsDump(input.diagnostics, input.outputDirectory, input.verbose);
48478
48697
  });
48479
48698
  //#endregion
48480
48699
  //#region src/cli/utils/should-auto-select-current-choice.ts
@@ -48796,6 +49015,7 @@ const buildScanResultCacheKey = (input) => {
48796
49015
  ignoredTags: [...input.options.ignoredTags].sort(),
48797
49016
  concurrency: input.options.concurrency,
48798
49017
  baselineRef: input.options.baseline?.ref,
49018
+ changedLineRanges: input.options.changedLineRanges ?? void 0,
48799
49019
  noScore: input.options.noScore,
48800
49020
  isCi: input.options.isCi,
48801
49021
  suppressRendering: input.options.suppressRendering,
@@ -48844,6 +49064,16 @@ const recordOnboardingCompletion = (options) => {
48844
49064
  })) markOnboardingComplete();
48845
49065
  };
48846
49066
  const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
49067
+ const buildChangedLineMatcher = (directory, changedLineRanges) => {
49068
+ const rangesByFile = /* @__PURE__ */ new Map();
49069
+ for (const entry of changedLineRanges) rangesByFile.set(toForwardSlashes(entry.file), entry.ranges);
49070
+ return (diagnostic) => {
49071
+ const relativePath = toForwardSlashes(path.isAbsolute(diagnostic.filePath) ? path.relative(directory, diagnostic.filePath) : diagnostic.filePath);
49072
+ const ranges = rangesByFile.get(relativePath);
49073
+ if (ranges === void 0) return false;
49074
+ return ranges.some(([start, end]) => diagnostic.line >= start && diagnostic.line <= end);
49075
+ };
49076
+ };
48847
49077
  const buildIgnoredTags = (userConfig) => {
48848
49078
  const tags = /* @__PURE__ */ new Set();
48849
49079
  if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
@@ -48853,6 +49083,7 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
48853
49083
  lint: inputOptions.lint ?? userConfig?.lint ?? true,
48854
49084
  deadCode: inputOptions.deadCode ?? userConfig?.deadCode ?? true,
48855
49085
  verbose: inputOptions.verbose ?? userConfig?.verbose ?? false,
49086
+ outputDirectory: inputOptions.outputDirectory || null,
48856
49087
  scoreOnly: inputOptions.scoreOnly ?? false,
48857
49088
  noScore: inputOptions.noScore ?? userConfig?.noScore ?? false,
48858
49089
  isCi: inputOptions.isCi ?? false,
@@ -48869,11 +49100,19 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
48869
49100
  ignoredTags: buildIgnoredTags(userConfig),
48870
49101
  outputSurface: inputOptions.outputSurface ?? "cli",
48871
49102
  suppressRendering: inputOptions.suppressRendering ?? false,
49103
+ concurrentScan: inputOptions.concurrentScan ?? false,
48872
49104
  concurrency: inputOptions.concurrency,
48873
49105
  baseline: inputOptions.baseline ?? null,
49106
+ changedLineRanges: inputOptions.changedLineRanges ?? null,
48874
49107
  supplyChainManifestChanged: inputOptions.supplyChainManifestChanged ?? false
48875
49108
  });
49109
+ const deriveScope = (options) => {
49110
+ if (options.baseline) return "changed";
49111
+ if (options.changedLineRanges !== null) return "lines";
49112
+ return options.includePaths.length > 0 ? "files" : "full";
49113
+ };
48876
49114
  const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
49115
+ scope: deriveScope(options),
48877
49116
  parallel: options.concurrency !== void 0,
48878
49117
  workerCount: options.concurrency,
48879
49118
  lint: options.lint,
@@ -48882,13 +49121,15 @@ const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
48882
49121
  noScore: options.noScore,
48883
49122
  respectInlineDisables: options.respectInlineDisables,
48884
49123
  showWarnings: options.warnings,
49124
+ usedOutputDir: options.outputDirectory !== null,
48885
49125
  ignoredTagCount: options.ignoredTags.size,
48886
49126
  hasCustomConfig,
48887
49127
  userConfig
48888
49128
  });
48889
49129
  const inspect = async (directory, inputOptions = {}) => {
48890
49130
  const startTime = performance$1.now();
48891
- resetSentryRunState();
49131
+ const isConcurrentScan = inputOptions.concurrentScan === true;
49132
+ if (!isConcurrentScan) resetSentryRunState();
48892
49133
  const hasConfigOverride = inputOptions.configOverride !== void 0;
48893
49134
  let scanDirectory;
48894
49135
  let userConfig;
@@ -48896,7 +49137,7 @@ const inspect = async (directory, inputOptions = {}) => {
48896
49137
  if (hasConfigOverride) {
48897
49138
  scanDirectory = directory;
48898
49139
  userConfig = inputOptions.configOverride ?? null;
48899
- configSourceDirectory = null;
49140
+ configSourceDirectory = inputOptions.configSourceDirectory ?? null;
48900
49141
  } else {
48901
49142
  const scanTarget = await resolveScanTarget(directory);
48902
49143
  scanDirectory = scanTarget.resolvedDirectory;
@@ -48904,8 +49145,9 @@ const inspect = async (directory, inputOptions = {}) => {
48904
49145
  configSourceDirectory = scanTarget.configSourceDirectory;
48905
49146
  }
48906
49147
  const options = mergeInspectOptions(inputOptions, userConfig);
49148
+ const ownsSpinnerSilence = options.silent && !isConcurrentScan;
48907
49149
  const wasSpinnerSilent = isSpinnerSilent();
48908
- if (options.silent) setSpinnerSilent(true);
49150
+ if (ownsSpinnerSilence) setSpinnerSilent(true);
48909
49151
  try {
48910
49152
  const result = await withSentryRunSpan(async (rootSentrySpan) => {
48911
49153
  try {
@@ -48918,11 +49160,11 @@ const inspect = async (directory, inputOptions = {}) => {
48918
49160
  });
48919
49161
  throw error;
48920
49162
  }
48921
- });
48922
- resetSentryRunState();
49163
+ }, { concurrentScan: isConcurrentScan });
49164
+ if (!isConcurrentScan) resetSentryRunState();
48923
49165
  return result;
48924
49166
  } finally {
48925
- if (options.silent) setSpinnerSilent(wasSpinnerSilent);
49167
+ if (ownsSpinnerSilence) setSpinnerSilent(wasSpinnerSilent);
48926
49168
  }
48927
49169
  };
48928
49170
  /**
@@ -49011,7 +49253,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49011
49253
  const scanResultCache = cacheKey === null ? null : createScanResultCache(directory);
49012
49254
  const cachedPayload = cacheKey === null ? null : scanResultCache?.lookup(cacheKey) ?? null;
49013
49255
  if (cachedPayload) {
49014
- recordSentryProjectContext(cachedPayload.project, rootSentrySpan);
49256
+ recordSentryProjectContext(cachedPayload.project, rootSentrySpan, { concurrentScan: options.concurrentScan });
49015
49257
  recordCount(METRIC.projectDetected, 1);
49016
49258
  await renderCachedProjectDetection({
49017
49259
  payload: cachedPayload,
@@ -49033,7 +49275,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49033
49275
  recordOnboardingCompletion(options);
49034
49276
  return result;
49035
49277
  }
49036
- const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && options.lint && Boolean(resolvedNodeBinaryPath);
49278
+ const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && !options.suppressRendering && options.lint && Boolean(resolvedNodeBinaryPath);
49037
49279
  const layers = buildRuntimeLayers({
49038
49280
  directory,
49039
49281
  hasConfigOverride,
@@ -49062,7 +49304,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49062
49304
  suppressScanSummary: options.suppressRendering,
49063
49305
  supplyChainManifestChanged: options.supplyChainManifestChanged
49064
49306
  }, { beforeLint: (projectInfo, lintIncludePaths) => gen(function* () {
49065
- recordSentryProjectContext(projectInfo, rootSentrySpan);
49307
+ recordSentryProjectContext(projectInfo, rootSentrySpan, { concurrentScan: options.concurrentScan });
49066
49308
  recordCount(METRIC.projectDetected, 1);
49067
49309
  if (options.scoreOnly || options.suppressRendering) return;
49068
49310
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
@@ -49095,6 +49337,9 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
49095
49337
  inspectDiagnostics = comparison.displayDiagnostics;
49096
49338
  baselineDelta = comparison.baselineDelta;
49097
49339
  }
49340
+ } else if (options.changedLineRanges !== null && isDiffMode) {
49341
+ const isOnChangedLine = buildChangedLineMatcher(directory, options.changedLineRanges);
49342
+ inspectDiagnostics = output.diagnostics.filter(isOnChangedLine);
49098
49343
  }
49099
49344
  const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
49100
49345
  const score = didLintFail ? null : output.score;
@@ -49209,15 +49454,16 @@ const finalizeAndRender = (input) => gen(function* () {
49209
49454
  ...baselineDelta ? { baselineDelta } : {}
49210
49455
  });
49211
49456
  if (options.suppressRendering) return buildResult();
49457
+ const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
49458
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
49212
49459
  if (options.scoreOnly) {
49460
+ if (options.outputDirectory !== null) yield* printDiagnosticsDump(printedDiagnostics, options.outputDirectory, false, "stderr");
49213
49461
  if (score) yield* log(`${score.score}`);
49214
- else yield* log(highlighter.gray(noScoreMessage));
49462
+ else yield* error$1(highlighter.gray(noScoreMessage));
49215
49463
  return buildResult();
49216
49464
  }
49217
49465
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
49218
49466
  const pause = onboardingSectionPause(animateRender);
49219
- const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
49220
- const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
49221
49467
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
49222
49468
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
49223
49469
  if (printedDiagnostics.length === 0) {
@@ -49235,6 +49481,7 @@ const finalizeAndRender = (input) => gen(function* () {
49235
49481
  yield* log(highlighter.gray(" Score not shown — some checks could not complete."));
49236
49482
  } else if (score) yield* printScoreHeader(score);
49237
49483
  else yield* printNoScoreHeader(noScoreMessage);
49484
+ if (options.outputDirectory !== null) yield* printDiagnosticsDump(printedDiagnostics, options.outputDirectory);
49238
49485
  return buildResult();
49239
49486
  }
49240
49487
  yield* pause;
@@ -49259,6 +49506,7 @@ const finalizeAndRender = (input) => gen(function* () {
49259
49506
  totalSourceFileCount: lintSourceFileCount,
49260
49507
  noScoreMessage,
49261
49508
  verbose: options.verbose,
49509
+ outputDirectory: options.outputDirectory,
49262
49510
  animateProjection: animateRender
49263
49511
  });
49264
49512
  if (hasSkippedChecks) {
@@ -49430,9 +49678,9 @@ const isExpectedUserError = (error) => error instanceof CliInputError || isProje
49430
49678
  //#region src/cli/utils/build-handoff-payload.ts
49431
49679
  const buildHandoffPayload = (input) => {
49432
49680
  const topGroups = buildSortedRuleGroups(input.diagnostics).slice(0, 3);
49433
- let diagnosticsDirectory = null;
49681
+ let outputDirectory = null;
49434
49682
  try {
49435
- diagnosticsDirectory = writeDiagnosticsDirectory([...input.diagnostics]);
49683
+ outputDirectory = writeDiagnosticsDirectory([...input.diagnostics], input.outputDirectory);
49436
49684
  } catch {}
49437
49685
  const lines = [
49438
49686
  "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 +49707,7 @@ const buildHandoffPayload = (input) => {
49459
49707
  if (remainingFiles > 0) lines.push(` - +${remainingFiles} more files`);
49460
49708
  });
49461
49709
  lines.push("");
49462
- if (diagnosticsDirectory) lines.push(`Full results for all ${input.diagnostics.length} issues (diagnostics.json + a .txt per rule): ${diagnosticsDirectory}`, "");
49710
+ if (outputDirectory) lines.push(`Full results for all ${input.diagnostics.length} issues (diagnostics.json + a .txt per rule): ${outputDirectory}`, "");
49463
49711
  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
49712
  return lines.join("\n");
49465
49713
  };
@@ -49691,7 +49939,7 @@ const installReactDoctorScriptStep = (projectRoot) => {
49691
49939
  };
49692
49940
  //#endregion
49693
49941
  //#region src/cli/utils/install-github-workflow.ts
49694
- const buildWorkflowContent = () => `# React Doctor — finds security, performance, correctness, accessibility,
49942
+ const buildWorkflowContent = (defaultBranch) => `# React Doctor — finds security, performance, correctness, accessibility,
49695
49943
  # bundle-size, and architecture issues in React codebases.
49696
49944
  #
49697
49945
  # Docs: https://www.react.doctor/ci
@@ -49703,9 +49951,9 @@ on:
49703
49951
  # 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
49952
  pull_request:
49705
49953
  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.
49954
+ # Scans \`${defaultBranch}\` on every push to track the health-score trend and catch regressions that slipped past PR review.
49707
49955
  push:
49708
- branches: [main]
49956
+ branches: ["${defaultBranch}"]
49709
49957
 
49710
49958
  permissions:
49711
49959
  contents: read
@@ -49725,10 +49973,15 @@ jobs:
49725
49973
  - uses: actions/checkout@v5
49726
49974
 
49727
49975
  - uses: millionco/react-doctor@v2
49728
- # Common configuration knobs — uncomment any to override the default.
49976
+ # Advisory by default: React Doctor reports findings on every PR — a
49977
+ # sticky summary comment, inline review comments, and a commit status
49978
+ # with the health score — but never fails the check, so it won't red-X
49979
+ # a teammate's PR on day one. When your team trusts the signal, graduate
49980
+ # the gate: uncomment the block below and set blocking to "error" (fail
49981
+ # on new error-severity findings) or "warning" (fail on any finding).
49729
49982
  # Full reference: https://www.react.doctor/ci
49730
49983
  # with:
49731
- # blocking: warning # Gate level: "error" (default) | "warning" | "none" (advisory)
49984
+ # blocking: error # Gate level: "none" (advisory, the default) | "warning" | "error"
49732
49985
  # scope: full # On PRs, scan the whole project instead of just changed files
49733
49986
  # comment: false # Disable the sticky PR summary comment
49734
49987
  # review-comments: false # Disable inline review comments on changed lines
@@ -49760,7 +50013,7 @@ const upgradeWorkflowActionToV2 = (content) => {
49760
50013
  changed: upgraded !== content
49761
50014
  };
49762
50015
  };
49763
- const installReactDoctorWorkflow = (projectRoot) => {
50016
+ const installReactDoctorWorkflow = (projectRoot, defaultBranch = "main") => {
49764
50017
  const workflowPath = getReactDoctorWorkflowPath(projectRoot);
49765
50018
  if (NFS.existsSync(workflowPath)) return {
49766
50019
  status: "exists",
@@ -49768,7 +50021,7 @@ const installReactDoctorWorkflow = (projectRoot) => {
49768
50021
  };
49769
50022
  try {
49770
50023
  NFS.mkdirSync(Path.dirname(workflowPath), { recursive: true });
49771
- NFS.writeFileSync(workflowPath, buildWorkflowContent());
50024
+ NFS.writeFileSync(workflowPath, buildWorkflowContent(defaultBranch));
49772
50025
  return {
49773
50026
  status: "created",
49774
50027
  workflowPath
@@ -49944,19 +50197,14 @@ const askUpgradeActionVersion = async (prompt = prompts) => {
49944
50197
  return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
49945
50198
  };
49946
50199
  //#endregion
49947
- //#region src/cli/utils/open-workflow-pull-request.ts
49948
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
49949
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
49950
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
49951
- 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.
49952
-
49953
- Docs: https://www.react.doctor/ci`;
50200
+ //#region src/cli/utils/run-command.ts
49954
50201
  const execFileAsync$1 = promisify(execFile);
49955
- const run = async (command, args, cwd) => {
50202
+ const runCommand = async (command, args, cwd, timeoutMs) => {
49956
50203
  try {
49957
50204
  const { stdout, stderr } = await execFileAsync$1(command, [...args], {
49958
50205
  cwd,
49959
- encoding: "utf8"
50206
+ encoding: "utf8",
50207
+ timeout: timeoutMs
49960
50208
  });
49961
50209
  return {
49962
50210
  success: true,
@@ -49972,7 +50220,18 @@ const run = async (command, args, cwd) => {
49972
50220
  };
49973
50221
  }
49974
50222
  };
49975
- const detectDefaultBranch = async (cwd) => {
50223
+ //#endregion
50224
+ //#region src/cli/utils/detect-default-branch.ts
50225
+ const detectDefaultBranch = async (cwd, run = runCommand) => {
50226
+ const repoView = await run("gh", [
50227
+ "repo",
50228
+ "view",
50229
+ "--json",
50230
+ "defaultBranchRef",
50231
+ "--jq",
50232
+ ".defaultBranchRef.name"
50233
+ ], cwd, GH_DEFAULT_BRANCH_PROBE_TIMEOUT_MS);
50234
+ if (repoView.success && repoView.stdout !== "" && repoView.stdout !== "null") return repoView.stdout;
49976
50235
  const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
49977
50236
  if (symRef.success) {
49978
50237
  const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
@@ -49990,8 +50249,16 @@ const detectDefaultBranch = async (cwd) => {
49990
50249
  ], cwd)).success) return "master";
49991
50250
  return null;
49992
50251
  };
50252
+ //#endregion
50253
+ //#region src/cli/utils/open-workflow-pull-request.ts
50254
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
50255
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
50256
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
50257
+ 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.
50258
+
50259
+ Docs: https://www.react.doctor/ci`;
49993
50260
  const findUniqueBranchName = async (cwd) => {
49994
- if (!(await run("git", [
50261
+ if (!(await runCommand("git", [
49995
50262
  "rev-parse",
49996
50263
  "--verify",
49997
50264
  NEW_BRANCH_PREFIX
@@ -50003,7 +50270,7 @@ const openWorkflowPullRequest = async (params) => {
50003
50270
  const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
50004
50271
  const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
50005
50272
  const prBody = params.prBody ?? DEFAULT_PR_BODY;
50006
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50273
+ const repoRootProbe = await runCommand("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50007
50274
  if (!repoRootProbe.success) return {
50008
50275
  status: "not-attempted",
50009
50276
  reason: "not-a-git-repo"
@@ -50013,16 +50280,16 @@ const openWorkflowPullRequest = async (params) => {
50013
50280
  status: "not-attempted",
50014
50281
  reason: "gh-not-installed"
50015
50282
  };
50016
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
50283
+ if (!(await runCommand("gh", ["auth", "status"], cwd)).success) return {
50017
50284
  status: "not-attempted",
50018
50285
  reason: "gh-not-authenticated"
50019
50286
  };
50020
- const defaultBranch = await detectDefaultBranch(cwd);
50287
+ const defaultBranch = params.baseBranch ?? await detectDefaultBranch(cwd);
50021
50288
  if (!defaultBranch) return {
50022
50289
  status: "not-attempted",
50023
50290
  reason: "no-default-branch"
50024
50291
  };
50025
- const previousBranchProbe = await run("git", [
50292
+ const previousBranchProbe = await runCommand("git", [
50026
50293
  "rev-parse",
50027
50294
  "--abbrev-ref",
50028
50295
  "HEAD"
@@ -50032,13 +50299,13 @@ const openWorkflowPullRequest = async (params) => {
50032
50299
  reason: "detached-head"
50033
50300
  };
50034
50301
  const previousBranch = previousBranchProbe.stdout;
50035
- await run("git", [
50302
+ await runCommand("git", [
50036
50303
  "fetch",
50037
50304
  "origin",
50038
50305
  defaultBranch
50039
50306
  ], cwd);
50040
50307
  const newBranch = await findUniqueBranchName(cwd);
50041
- if (!(await run("git", [
50308
+ if (!(await runCommand("git", [
50042
50309
  "checkout",
50043
50310
  "-b",
50044
50311
  newBranch,
@@ -50048,14 +50315,14 @@ const openWorkflowPullRequest = async (params) => {
50048
50315
  reason: "checkout-failed"
50049
50316
  };
50050
50317
  const restoreToPreviousBranch = async (deleteNewBranch) => {
50051
- await run("git", ["checkout", previousBranch], cwd);
50052
- if (deleteNewBranch) await run("git", [
50318
+ await runCommand("git", ["checkout", previousBranch], cwd);
50319
+ if (deleteNewBranch) await runCommand("git", [
50053
50320
  "branch",
50054
50321
  "-D",
50055
50322
  newBranch
50056
50323
  ], cwd);
50057
50324
  };
50058
- if (!(await run("git", [
50325
+ if (!(await runCommand("git", [
50059
50326
  "add",
50060
50327
  "--",
50061
50328
  Path.relative(cwd, workflowPath)
@@ -50066,7 +50333,7 @@ const openWorkflowPullRequest = async (params) => {
50066
50333
  reason: "git-add-failed"
50067
50334
  };
50068
50335
  }
50069
- if (!(await run("git", [
50336
+ if (!(await runCommand("git", [
50070
50337
  "commit",
50071
50338
  "-m",
50072
50339
  commitMessage
@@ -50077,7 +50344,7 @@ const openWorkflowPullRequest = async (params) => {
50077
50344
  reason: "git-commit-failed"
50078
50345
  };
50079
50346
  }
50080
- if (!(await run("git", [
50347
+ if (!(await runCommand("git", [
50081
50348
  "push",
50082
50349
  "-u",
50083
50350
  "origin",
@@ -50089,7 +50356,7 @@ const openWorkflowPullRequest = async (params) => {
50089
50356
  reason: "git-push-failed"
50090
50357
  };
50091
50358
  }
50092
- const prCreate = await run("gh", [
50359
+ const prCreate = await runCommand("gh", [
50093
50360
  "pr",
50094
50361
  "create",
50095
50362
  "--title",
@@ -50113,9 +50380,9 @@ const openWorkflowPullRequest = async (params) => {
50113
50380
  };
50114
50381
  const stageWorkflowFile = async (params) => {
50115
50382
  const workflowPath = Path.resolve(params.workflowPath);
50116
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50383
+ const repoRootProbe = await runCommand("git", ["rev-parse", "--show-toplevel"], Path.dirname(workflowPath));
50117
50384
  if (!repoRootProbe.success) return false;
50118
- return (await run("git", [
50385
+ return (await runCommand("git", [
50119
50386
  "add",
50120
50387
  "--",
50121
50388
  Path.relative(repoRootProbe.stdout, workflowPath)
@@ -50144,7 +50411,8 @@ const setUpGitHubActions = async (options) => {
50144
50411
  installReactDoctorScriptStep(projectRoot);
50145
50412
  } catch {}
50146
50413
  const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
50147
- const workflowResult = installReactDoctorWorkflow(projectRoot);
50414
+ const defaultBranch = await detectDefaultBranch(projectRoot) ?? "main";
50415
+ const workflowResult = installReactDoctorWorkflow(projectRoot, defaultBranch);
50148
50416
  const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
50149
50417
  cliLogger.break();
50150
50418
  if (workflowResult.status === "failed") {
@@ -50153,7 +50421,10 @@ const setUpGitHubActions = async (options) => {
50153
50421
  }
50154
50422
  if (workflowResult.status === "created") {
50155
50423
  const pullRequestSpinner = spinner("Opening a pull request for review...").start();
50156
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
50424
+ const pullRequestResult = await openWorkflowPullRequest({
50425
+ workflowPath: workflowResult.workflowPath,
50426
+ baseBranch: defaultBranch
50427
+ });
50157
50428
  if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
50158
50429
  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}`);
50159
50430
  else {
@@ -50994,8 +51265,8 @@ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
50994
51265
  throw error;
50995
51266
  }
50996
51267
  };
50997
- const installReactDoctorWorkflowStep = (projectRoot) => {
50998
- return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
51268
+ const installReactDoctorWorkflowStep = async (projectRoot) => {
51269
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot, await detectDefaultBranch(projectRoot) ?? void 0), projectRoot);
50999
51270
  };
51000
51271
  const upgradeReactDoctorWorkflowStep = (projectRoot) => {
51001
51272
  const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
@@ -51063,7 +51334,7 @@ const runInstallReactDoctor = async (options = {}) => {
51063
51334
  let didInstallWorkflow = false;
51064
51335
  if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
51065
51336
  cliLogger.break();
51066
- if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
51337
+ if (shouldInstallWorkflow) didInstallWorkflow = await installReactDoctorWorkflowStep(projectRoot);
51067
51338
  else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
51068
51339
  }
51069
51340
  const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
@@ -51335,7 +51606,8 @@ const handoffToAgent = async (input) => {
51335
51606
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
51336
51607
  const payload = buildHandoffPayload({
51337
51608
  diagnostics: input.diagnostics,
51338
- projectName: input.projectName
51609
+ projectName: input.projectName,
51610
+ outputDirectory: input.outputDirectory
51339
51611
  });
51340
51612
  if (handoffTarget === CLIPBOARD_CHOICE) {
51341
51613
  if (await copyToClipboard(payload)) cliLogger.log("Copied the prompt to your clipboard.");
@@ -51530,9 +51802,6 @@ const reportErrorToSentry = async (error) => {
51530
51802
  }
51531
51803
  };
51532
51804
  //#endregion
51533
- //#region src/cli/utils/path-format.ts
51534
- const toForwardSlashes = (filePath) => filePath.replaceAll("\\", "/");
51535
- //#endregion
51536
51805
  //#region src/cli/utils/read-changed-files-from.ts
51537
51806
  const isSafeRelativePath = (filePath) => {
51538
51807
  if (filePath.length === 0) return false;
@@ -51559,6 +51828,9 @@ const readChangedFilesFrom = (filePath) => {
51559
51828
  return [...uniqueFiles];
51560
51829
  };
51561
51830
  //#endregion
51831
+ //#region src/cli/utils/filter-scans-for-surface.ts
51832
+ const filterScansForSurface = (completedScans, surface) => completedScans.flatMap((scan) => filterDiagnosticsForSurface([...scan.result.diagnostics], surface, scan.config));
51833
+ //#endregion
51562
51834
  //#region src/cli/utils/render-multi-project-summary.ts
51563
51835
  const getScoreLabel = (score) => {
51564
51836
  if (score >= 75) return "Great";
@@ -51586,10 +51858,10 @@ const findLowestScoredScan = (completedScans) => {
51586
51858
  return scoredScans.reduce((worst, scan) => scan.result.score.score < worst.result.score.score ? scan : worst);
51587
51859
  };
51588
51860
  const printMultiProjectSummary = (input) => gen(function* () {
51589
- const { completedScans, userConfig, verbose, isOffline, projectName } = input;
51861
+ const { completedScans, verbose, isOffline, projectName, totalElapsedMilliseconds } = input;
51590
51862
  const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
51591
51863
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
51592
- const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
51864
+ const displayDiagnostics = filterDiagnosticsByCategories(filterScansForSurface(completedScans, "cli"), categoryFilters);
51593
51865
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
51594
51866
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
51595
51867
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -51601,8 +51873,7 @@ const printMultiProjectSummary = (input) => gen(function* () {
51601
51873
  else fileCountFromScansWithoutPaths += scan.result.scannedFileCount ?? scan.result.project.sourceFileCount;
51602
51874
  }
51603
51875
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
51604
- const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
51605
- yield* log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
51876
+ yield* log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalElapsedMilliseconds)}`);
51606
51877
  if (displayDiagnostics.length > 0) {
51607
51878
  yield* log("");
51608
51879
  yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
@@ -51612,16 +51883,17 @@ const printMultiProjectSummary = (input) => gen(function* () {
51612
51883
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
51613
51884
  yield* printSummary({
51614
51885
  diagnostics: displayDiagnostics,
51615
- elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
51886
+ elapsedMilliseconds: totalElapsedMilliseconds,
51616
51887
  scoreResult: aggregateScore,
51617
- potentialScore: lowestScoredScan ? yield* promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
51888
+ potentialScore: lowestScoredScan ? yield* promise(() => computeProjectedScore(displayDiagnostics, filterScansForSurface([lowestScoredScan], "cli"), lowestScoredScan.result.score)) : null,
51618
51889
  totalSourceFileCount,
51619
51890
  noScoreMessage: "Score unavailable.",
51620
51891
  verbose,
51892
+ outputDirectory: input.outputDirectory,
51621
51893
  animateProjection: animateRender
51622
51894
  });
51623
51895
  const entries = completedScans.map((scan) => {
51624
- const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
51896
+ const projectDiagnostics = filterDiagnosticsByCategories(filterScansForSurface([scan], "cli"), categoryFilters);
51625
51897
  const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
51626
51898
  return {
51627
51899
  projectName: scan.result.project.projectName,
@@ -51718,6 +51990,7 @@ const resolveCliInspectOptions = (flags, userConfig) => {
51718
51990
  lint: flags.lint,
51719
51991
  deadCode: flags.deadCode,
51720
51992
  verbose: flags.verbose,
51993
+ outputDirectory: flags.outputDir,
51721
51994
  respectInlineDisables: flags.respectInlineDisables === false ? false : void 0,
51722
51995
  warnings: wantsWarningGate ? true : flags.warnings,
51723
51996
  scoreOnly: flags.score === true,
@@ -51729,22 +52002,101 @@ const resolveCliInspectOptions = (flags, userConfig) => {
51729
52002
  };
51730
52003
  };
51731
52004
  //#endregion
51732
- //#region src/cli/utils/resolve-diff-mode.ts
51733
- const resolveDiffMode = async (diffInfo, effectiveDiff, shouldSkipPrompts, isQuiet) => {
51734
- if (effectiveDiff !== void 0 && effectiveDiff !== false) {
51735
- if (diffInfo) return true;
51736
- if (!isQuiet) {
51737
- if (typeof effectiveDiff === "string") cliLogger.warn(`Could not compute diff against "${effectiveDiff}" (merge-base failed or HEAD has no history). Running full scan.`);
51738
- else cliLogger.warn("No feature branch or uncommitted changes detected. Running full scan.");
51739
- cliLogger.break();
51740
- }
51741
- return false;
52005
+ //#region src/cli/utils/resolve-scope.ts
52006
+ const SCOPE_VALUES = new Set([
52007
+ "full",
52008
+ "files",
52009
+ "changed",
52010
+ "lines"
52011
+ ]);
52012
+ const isScopeValue = (value) => SCOPE_VALUES.has(value);
52013
+ const coerceDeprecatedDiff = (value) => {
52014
+ if (value === void 0) return void 0;
52015
+ if (value === false || value === "false") return { scope: "full" };
52016
+ if (value === true || value === "true") return { scope: "changed" };
52017
+ if (value === "") return void 0;
52018
+ return {
52019
+ scope: "changed",
52020
+ base: value
52021
+ };
52022
+ };
52023
+ /**
52024
+ * Resolves the *requested* scope from flags + config without touching git.
52025
+ * Precedence mirrors `pickBlockingLevel`: flags win over config, and the new
52026
+ * `--scope` wins over the deprecated `--diff` alias on each side
52027
+ * (`flags.scope` > `flags.diff` > `config.scope` > `config.diff`). Returns
52028
+ * `scope: undefined` when nothing is set so the caller can default to `full`
52029
+ * or offer the interactive prompt.
52030
+ */
52031
+ const resolveScope = (flags, userConfig) => {
52032
+ const base = flags.base ?? userConfig?.base;
52033
+ if (typeof flags.scope === "string" && flags.scope.length > 0) {
52034
+ if (isScopeValue(flags.scope)) return {
52035
+ scope: flags.scope,
52036
+ base,
52037
+ usedDeprecatedDiff: false
52038
+ };
52039
+ cliLogger.warn(`Invalid --scope "${flags.scope}". Expected one of: full, files, changed, lines. Ignoring.`);
51742
52040
  }
51743
- if (effectiveDiff === false || !diffInfo) return false;
51744
- const changedSourceFiles = filterSourceFiles(diffInfo.changedFiles);
51745
- if (changedSourceFiles.length === 0) return false;
51746
- if (shouldSkipPrompts) return false;
51747
- if (isQuiet) return false;
52041
+ const flagDiff = coerceDeprecatedDiff(flags.diff);
52042
+ if (flagDiff !== void 0) return {
52043
+ scope: flagDiff.scope,
52044
+ base: base ?? flagDiff.base,
52045
+ usedDeprecatedDiff: true
52046
+ };
52047
+ if (userConfig?.scope !== void 0) {
52048
+ if (isScopeValue(userConfig.scope)) return {
52049
+ scope: userConfig.scope,
52050
+ base,
52051
+ usedDeprecatedDiff: false
52052
+ };
52053
+ cliLogger.warn(`Invalid scope "${userConfig.scope}" in config. Expected one of: full, files, changed, lines. Ignoring.`);
52054
+ }
52055
+ const configDiff = coerceDeprecatedDiff(userConfig?.diff);
52056
+ if (configDiff !== void 0) return {
52057
+ scope: configDiff.scope,
52058
+ base: base ?? configDiff.base,
52059
+ usedDeprecatedDiff: true
52060
+ };
52061
+ return {
52062
+ scope: void 0,
52063
+ base,
52064
+ usedDeprecatedDiff: false
52065
+ };
52066
+ };
52067
+ const warnDeprecatedDiff = (flags, userConfig) => {
52068
+ const usedFlag = flags.diff !== void 0;
52069
+ if (!usedFlag && userConfig?.diff === void 0) return;
52070
+ const targetScope = coerceDeprecatedDiff(usedFlag ? flags.diff : userConfig?.diff)?.scope ?? "changed";
52071
+ if (usedFlag) {
52072
+ const baseHint = targetScope === "changed" ? " (add `--base <ref>` to pin the base)" : "";
52073
+ cliLogger.warn(`The \`--diff\` flag is deprecated; use \`--scope ${targetScope}\`${baseHint} instead.`);
52074
+ return;
52075
+ }
52076
+ cliLogger.warn(`The \`diff\` config option is deprecated; use \`scope: "${targetScope}"\` instead.`);
52077
+ };
52078
+ const warnDiffUnavailable = (requested, isQuiet) => {
52079
+ if (isQuiet) return;
52080
+ 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.`);
52081
+ else cliLogger.warn("No feature branch or uncommitted changes detected. Running full scan.");
52082
+ cliLogger.break();
52083
+ };
52084
+ /**
52085
+ * Resolves the requested scope against the detected diff into the final scope.
52086
+ * An explicit non-`full` scope needs a usable `diffInfo`; without one it warns
52087
+ * and falls back to `full`. When nothing was requested, an interactive run on a
52088
+ * branch with changed source files is offered the "full vs changed" prompt.
52089
+ */
52090
+ const finalizeScope = async ({ requested, diffInfo, skipPrompts, isQuiet }) => {
52091
+ if (requested.scope !== void 0) {
52092
+ if (requested.scope === "full") return "full";
52093
+ if (diffInfo !== null) return requested.scope;
52094
+ warnDiffUnavailable(requested, isQuiet);
52095
+ return "full";
52096
+ }
52097
+ if (diffInfo === null || skipPrompts || isQuiet) return "full";
52098
+ const changedSourceFiles = filterSourceFiles([...diffInfo.changedFiles]);
52099
+ if (changedSourceFiles.length === 0) return "full";
51748
52100
  const { scanScope } = await prompts({
51749
52101
  type: "select",
51750
52102
  name: "scanScope",
@@ -51756,29 +52108,13 @@ const resolveDiffMode = async (diffInfo, effectiveDiff, shouldSkipPrompts, isQui
51756
52108
  }, {
51757
52109
  title: diffInfo.isCurrentChanges ? `Uncommitted changes (${changedSourceFiles.length})` : `Changed files on ${diffInfo.currentBranch ?? "this branch"} (${changedSourceFiles.length})`,
51758
52110
  description: diffInfo.isCurrentChanges ? "Compare working tree changes against HEAD" : `Compare against ${diffInfo.baseBranch} from the branch merge-base`,
51759
- value: "branch"
52111
+ value: "changed"
51760
52112
  }],
51761
52113
  initial: diffInfo.isCurrentChanges ? 0 : 1
51762
52114
  });
51763
- return scanScope === "branch";
52115
+ return scanScope === "changed" ? "changed" : "full";
51764
52116
  };
51765
52117
  //#endregion
51766
- //#region src/cli/utils/coerce-diff-value.ts
51767
- const coerceDiffValue = (value) => {
51768
- if (value === void 0) return void 0;
51769
- if (typeof value === "boolean") return value;
51770
- if (typeof value === "string") {
51771
- if (value.length === 0) return void 0;
51772
- if (value === "false") return false;
51773
- if (value === "true") return true;
51774
- return value;
51775
- }
51776
- process.stderr.write(`[react-doctor] invalid diff value (expected boolean or string): ${typeof value}. Falling back to no diff.\n`);
51777
- };
51778
- //#endregion
51779
- //#region src/cli/utils/resolve-effective-diff.ts
51780
- const resolveEffectiveDiff = (flags, userConfig) => coerceDiffValue(flags.diff ?? userConfig?.diff);
51781
- //#endregion
51782
52118
  //#region src/cli/utils/resolve-project-relative-directory.ts
51783
52119
  /**
51784
52120
  * The scanned project's directory relative to the diff root, forward-slashed —
@@ -51809,6 +52145,30 @@ const resolveProjectDiffIncludePaths = (rootDirectory, projectDirectory, diffInf
51809
52145
  return projectRelativePath.length > 0 ? [projectRelativePath] : [];
51810
52146
  });
51811
52147
  };
52148
+ /**
52149
+ * Re-keys repo-relative changed line ranges (from `getChangedLineRanges`) to
52150
+ * the scanned project, mirroring `resolveProjectDiffIncludePaths`'s boundary
52151
+ * rule so the `lines` scope filter inside `inspect()` matches the project-
52152
+ * relative diagnostic paths. Files outside the project are dropped.
52153
+ */
52154
+ const resolveProjectChangedLineRanges = (rootDirectory, projectDirectory, ranges) => {
52155
+ const relativeProjectDirectory = resolveProjectRelativeDirectory(rootDirectory, projectDirectory);
52156
+ if (relativeProjectDirectory === null) return [];
52157
+ if (relativeProjectDirectory.length === 0) return ranges.map((entry) => ({
52158
+ file: toForwardSlashes(entry.file),
52159
+ ranges: entry.ranges
52160
+ }));
52161
+ const projectPrefix = `${relativeProjectDirectory}/`;
52162
+ return ranges.flatMap((entry) => {
52163
+ const normalizedFilePath = toForwardSlashes(entry.file);
52164
+ if (!normalizedFilePath.startsWith(projectPrefix)) return [];
52165
+ const projectRelativePath = normalizedFilePath.slice(projectPrefix.length);
52166
+ return projectRelativePath.length > 0 ? [{
52167
+ file: projectRelativePath,
52168
+ ranges: entry.ranges
52169
+ }] : [];
52170
+ });
52171
+ };
51812
52172
  //#endregion
51813
52173
  //#region src/cli/utils/build-diagnostic-issue-url.ts
51814
52174
  const formatRuleIdentifier = (diagnostic) => `${diagnostic.plugin}/${diagnostic.rule}`;
@@ -51880,16 +52240,22 @@ const parseFileLineArgument = (rawArgument) => {
51880
52240
  };
51881
52241
  //#endregion
51882
52242
  //#region src/cli/utils/select-projects.ts
51883
- const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
52243
+ const selectProjects = async (rootDirectory, projectFlag, skipPrompts, configProjects) => {
51884
52244
  const hasRootPackageJson = isFile(Path.join(rootDirectory, "package.json"));
51885
52245
  let packages = listWorkspacePackages(rootDirectory);
51886
52246
  if (packages.length === 0 && (!hasRootPackageJson || isMonorepoRoot(rootDirectory))) packages = discoverReactSubprojects(rootDirectory);
52247
+ if (projectFlag) return resolveProjectFlag(projectFlag, packages, rootDirectory);
52248
+ const configRequestedNames = (configProjects ?? []).map((requestedName) => requestedName.trim()).filter((requestedName) => requestedName.length > 0);
52249
+ if (configRequestedNames.length > 0) {
52250
+ const resolvedDirectories = resolveRequestedProjects(configRequestedNames, packages, rootDirectory, "config");
52251
+ recordCount(METRIC.projectConfigSelected, resolvedDirectories.length);
52252
+ return resolvedDirectories;
52253
+ }
51887
52254
  if (packages.length === 0) return [rootDirectory];
51888
52255
  if (packages.length === 1) {
51889
52256
  cliLogger.log(`${highlighter.success("✔")} Select projects ${highlighter.dim("›")} ${packages[0].name}`);
51890
52257
  return [packages[0].directory];
51891
52258
  }
51892
- if (projectFlag) return resolveProjectFlag(projectFlag, packages);
51893
52259
  if (skipPrompts) {
51894
52260
  printDiscoveredProjects(packages);
51895
52261
  return packages.map((workspacePackage) => workspacePackage.directory);
@@ -51897,17 +52263,25 @@ const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
51897
52263
  return promptProjectSelection(packages, rootDirectory);
51898
52264
  };
51899
52265
  const ALL_PROJECTS_SENTINEL = "*";
51900
- const resolveProjectFlag = (projectFlag, workspacePackages) => {
52266
+ const resolveProjectFlag = (projectFlag, workspacePackages, rootDirectory) => {
51901
52267
  const requestedNames = projectFlag.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
51902
52268
  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.`);
51903
- if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.map((workspacePackage) => workspacePackage.directory);
51904
- const resolvedDirectories = [];
51905
- for (const requestedName of requestedNames) {
52269
+ return resolveRequestedProjects(requestedNames, workspacePackages, rootDirectory, "flag");
52270
+ };
52271
+ const resolveRequestedProjects = (requestedNames, workspacePackages, rootDirectory, source) => {
52272
+ if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.length > 0 ? workspacePackages.map((workspacePackage) => workspacePackage.directory) : [rootDirectory];
52273
+ const sourceLabel = source === "flag" ? "Project" : "Config \"projects\" entry";
52274
+ return requestedNames.map((requestedName) => {
51906
52275
  const matched = workspacePackages.find((workspacePackage) => workspacePackage.name === requestedName || Path.basename(workspacePackage.directory) === requestedName);
51907
- if (!matched) throw new CliInputError(`Project "${requestedName}" not found. Available: ${workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ")}`);
51908
- resolvedDirectories.push(matched.directory);
51909
- }
51910
- return resolvedDirectories;
52276
+ if (matched) return matched.directory;
52277
+ const candidateDirectory = Path.resolve(rootDirectory, requestedName);
52278
+ if (isDirectory(candidateDirectory)) {
52279
+ recordCount(METRIC.projectPathSelected);
52280
+ return candidateDirectory;
52281
+ }
52282
+ const availableNames = workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ");
52283
+ 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}.`);
52284
+ });
51911
52285
  };
51912
52286
  const printDiscoveredProjects = (packages) => {
51913
52287
  cliLogger.log(`${highlighter.success("✔")} Select projects ${highlighter.dim("›")} ${packages.map((workspacePackage) => workspacePackage.name).join(", ")}`);
@@ -52041,10 +52415,12 @@ const warnDeprecatedFailOn = (flags, userConfig) => {
52041
52415
  };
52042
52416
  //#endregion
52043
52417
  //#region src/cli/utils/validate-mode-flags.ts
52418
+ const usedDiffAlias = (flags) => flags.diff !== void 0 && flags.diff !== false && flags.diff !== "false" && flags.diff !== "";
52419
+ const usedScope = (flags) => typeof flags.scope === "string" && flags.scope.length > 0;
52044
52420
  const validateModeFlags = (flags) => {
52045
- const coercedDiff = coerceDiffValue(flags.diff);
52046
- const exclusiveModes = [flags.staged ? "--staged" : null, coercedDiff !== void 0 && coercedDiff !== false ? "--diff" : null].filter((modeName) => modeName !== null);
52047
- if (exclusiveModes.length > 1) throw new CliInputError(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
52421
+ if (usedScope(flags) && usedDiffAlias(flags)) throw new CliInputError("Cannot combine --scope and --diff; --diff is the deprecated alias.");
52422
+ if (flags.staged && usedDiffAlias(flags)) throw new CliInputError("Cannot combine --staged and --diff; pick one mode.");
52423
+ 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.`);
52048
52424
  if (flags.score && flags.json) throw new CliInputError("Cannot combine --score and --json; pick one output mode.");
52049
52425
  if (flags.score && flags.telemetry === false) throw new CliInputError("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
52050
52426
  if (flags.sfw) {
@@ -52052,7 +52428,8 @@ const validateModeFlags = (flags) => {
52052
52428
  flags.json ? "--json" : null,
52053
52429
  flags.score ? "--score" : null,
52054
52430
  flags.staged ? "--staged" : null,
52055
- coercedDiff !== void 0 && coercedDiff !== false ? "--diff" : null
52431
+ usedScope(flags) ? "--scope" : null,
52432
+ usedDiffAlias(flags) ? "--diff" : null
52056
52433
  ].find((name) => name !== null);
52057
52434
  if (conflictingFlag) throw new CliInputError(`Cannot combine --sfw with ${conflictingFlag}; --sfw is a standalone demo listing.`);
52058
52435
  }
@@ -52099,7 +52476,7 @@ const finalizeScans = (input) => {
52099
52476
  }));
52100
52477
  }
52101
52478
  if (input.isScoreOnly || baselineDegraded) return;
52102
- if (shouldBlockCi(filterDiagnosticsForSurface(input.diagnostics, "ciFailure", input.userConfig), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
52479
+ if (shouldBlockCi(filterScansForSurface(input.completedScans, "ciFailure"), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
52103
52480
  };
52104
52481
  const buildChangedFilesDiffInfo = (changedFiles) => ({
52105
52482
  currentBranch: process.env.GITHUB_HEAD_REF?.trim() || null,
@@ -52148,6 +52525,7 @@ const inspectAction = async (directory, flags) => {
52148
52525
  const resolvedDirectory = scanTarget.resolvedDirectory;
52149
52526
  setJsonReportDirectory(resolvedDirectory);
52150
52527
  warnDeprecatedFailOn(flags, userConfig);
52528
+ warnDeprecatedDiff(flags, userConfig);
52151
52529
  if (scanTarget.didRedirectViaRootDir && !isQuiet) {
52152
52530
  cliLogger.dim(`Redirected to ${highlighter.info(toRelativePath(resolvedDirectory, requestedDirectory))} via react-doctor config "rootDir".`);
52153
52531
  cliLogger.break();
@@ -52209,18 +52587,28 @@ const inspectAction = async (directory, flags) => {
52209
52587
  });
52210
52588
  throw error;
52211
52589
  });
52590
+ const stagedWantsLines = resolveScope(flags, userConfig).scope === "lines";
52591
+ const stagedLineRanges = stagedWantsLines ? await getChangedLineRanges({
52592
+ directory: resolvedDirectory,
52593
+ cached: true,
52594
+ files: snapshot.stagedFiles
52595
+ }) : null;
52596
+ if (stagedWantsLines && stagedLineRanges === null && !isQuiet) {
52597
+ cliLogger.warn("Could not determine staged changed lines; reporting all issues in staged files.");
52598
+ cliLogger.break();
52599
+ }
52212
52600
  try {
52213
52601
  const scanResult = await inspect(snapshot.tempDirectory, {
52214
52602
  ...scanOptions,
52215
52603
  includePaths: snapshot.stagedFiles,
52216
- configOverride: userConfig
52604
+ configOverride: userConfig,
52605
+ changedLineRanges: stagedLineRanges ?? void 0
52217
52606
  });
52218
52607
  const remappedDiagnostics = scanResult.diagnostics.map((diagnostic) => ({
52219
52608
  ...diagnostic,
52220
52609
  filePath: Path.isAbsolute(diagnostic.filePath) ? diagnostic.filePath.replaceAll(snapshot.tempDirectory, () => resolvedDirectory) : diagnostic.filePath
52221
52610
  }));
52222
52611
  finalizeScans({
52223
- diagnostics: remappedDiagnostics,
52224
52612
  completedScans: [{
52225
52613
  directory: resolvedDirectory,
52226
52614
  result: {
@@ -52230,7 +52618,8 @@ const inspectAction = async (directory, flags) => {
52230
52618
  ...scanResult.project,
52231
52619
  rootDirectory: resolvedDirectory
52232
52620
  }
52233
- }
52621
+ },
52622
+ config: userConfig
52234
52623
  }],
52235
52624
  mode: "staged",
52236
52625
  diff: null,
@@ -52248,12 +52637,35 @@ const inspectAction = async (directory, flags) => {
52248
52637
  }
52249
52638
  return;
52250
52639
  }
52251
- const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts);
52640
+ const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts, userConfig?.projects);
52252
52641
  const changedFilesDiffInfo = flags.changedFilesFrom ? buildChangedFilesDiffInfo(readChangedFilesFrom(Path.resolve(flags.changedFilesFrom))) : null;
52253
- const effectiveDiff = resolveEffectiveDiff(flags, userConfig);
52254
- const diffInfo = changedFilesDiffInfo ?? (changedFilesDiffInfo === null && (effectiveDiff !== void 0 && effectiveDiff !== false || !skipPrompts && !isQuiet) ? await getDiffInfo(resolvedDirectory, typeof effectiveDiff === "string" ? effectiveDiff : void 0) : null);
52255
- const isDiffMode = changedFilesDiffInfo !== null || await resolveDiffMode(diffInfo, effectiveDiff, skipPrompts, isQuiet);
52256
- const baselineRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
52642
+ const requestedScope = resolveScope(flags, userConfig);
52643
+ const scopeRequest = requestedScope.scope === void 0 && changedFilesDiffInfo !== null ? {
52644
+ ...requestedScope,
52645
+ scope: "changed"
52646
+ } : requestedScope;
52647
+ const wantsDiffMode = scopeRequest.scope !== void 0 && scopeRequest.scope !== "full";
52648
+ const shouldDetectDiff = changedFilesDiffInfo === null && (wantsDiffMode || scopeRequest.scope === void 0 && !skipPrompts && !isQuiet);
52649
+ const diffInfo = changedFilesDiffInfo ?? (shouldDetectDiff ? await getDiffInfo(resolvedDirectory, scopeRequest.base) : null);
52650
+ const scope = await finalizeScope({
52651
+ requested: scopeRequest,
52652
+ diffInfo,
52653
+ skipPrompts,
52654
+ isQuiet
52655
+ });
52656
+ const isDiffMode = scope !== "full";
52657
+ const comparisonBaseRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
52658
+ const baselineRef = scope === "changed" ? comparisonBaseRef : null;
52659
+ const linesBaseRef = diffInfo?.isCurrentChanges ? "HEAD" : comparisonBaseRef;
52660
+ const changedLineRanges = scope === "lines" && diffInfo !== null && (diffInfo.isCurrentChanges || linesBaseRef !== null) && diffInfo !== null ? await getChangedLineRanges({
52661
+ directory: resolvedDirectory,
52662
+ baseRef: linesBaseRef ?? void 0,
52663
+ files: [...diffInfo.changedFiles]
52664
+ }) : null;
52665
+ if (scope === "lines" && changedLineRanges === null && !isQuiet) {
52666
+ cliLogger.warn("Could not determine changed lines (no base ref or git diff failed); reporting all issues in changed files.");
52667
+ cliLogger.break();
52668
+ }
52257
52669
  setJsonReportMode(baselineRef ? "baseline" : isDiffMode ? "diff" : "full");
52258
52670
  if (isDiffMode && diffInfo && !isQuiet) {
52259
52671
  if (diffInfo.isCurrentChanges) cliLogger.log("Scanning uncommitted changes");
@@ -52263,59 +52675,91 @@ const inspectAction = async (directory, flags) => {
52263
52675
  }
52264
52676
  cliLogger.break();
52265
52677
  }
52266
- const allDiagnostics = [];
52267
52678
  const completedScans = [];
52268
52679
  const isMultiProject = projectDirectories.length > 1;
52269
- const supplyChainEnabled = userConfig?.supplyChain?.enabled !== false;
52270
- for (const projectDirectory of projectDirectories) {
52680
+ const scanProject = async (projectDirectory) => {
52681
+ const projectScanTarget = projectDirectory === resolvedDirectory ? scanTarget : await resolveScanTarget(projectDirectory, { allowAmbiguous: true });
52682
+ const scanDirectory = projectScanTarget.resolvedDirectory;
52683
+ const projectConfig = projectDirectory === resolvedDirectory ? userConfig : mergeReactDoctorConfigs(userConfig, projectScanTarget.userConfig ?? void 0);
52684
+ const projectConfigSourceDirectory = projectScanTarget.userConfig?.plugins === void 0 ? scanTarget.configSourceDirectory : projectScanTarget.configSourceDirectory;
52685
+ const supplyChainEnabled = projectConfig?.supplyChain?.enabled !== false;
52271
52686
  let includePaths;
52272
52687
  let supplyChainManifestChanged = false;
52273
52688
  if (isDiffMode) {
52274
- const changedSourceFiles = diffInfo === null ? [] : resolveProjectDiffIncludePaths(resolvedDirectory, projectDirectory, diffInfo);
52275
- supplyChainManifestChanged = supplyChainEnabled && diffInfo !== null && projectManifestChanged(resolvedDirectory, projectDirectory, diffInfo);
52689
+ const changedSourceFiles = diffInfo === null ? [] : resolveProjectDiffIncludePaths(resolvedDirectory, scanDirectory, diffInfo);
52690
+ supplyChainManifestChanged = supplyChainEnabled && diffInfo !== null && projectManifestChanged(resolvedDirectory, scanDirectory, diffInfo);
52276
52691
  if (changedSourceFiles.length === 0 && !supplyChainManifestChanged) {
52277
52692
  if (!isQuiet) {
52278
- cliLogger.dim(`No changed source files in ${projectDirectory}, skipping.`);
52693
+ cliLogger.dim(`No changed source files in ${scanDirectory}, skipping.`);
52279
52694
  cliLogger.break();
52280
52695
  }
52281
- continue;
52696
+ return null;
52282
52697
  }
52283
52698
  includePaths = [...changedSourceFiles];
52284
52699
  if (supplyChainManifestChanged) includePaths.push("package.json");
52285
52700
  }
52286
52701
  if (!isQuiet && !isMultiProject) cliLogger.dim(" ");
52287
- const scanResult = await inspect(projectDirectory, {
52702
+ const scanResult = await inspect(scanDirectory, {
52288
52703
  ...scanOptions,
52289
52704
  includePaths,
52290
- configOverride: userConfig,
52705
+ configOverride: projectConfig,
52706
+ configSourceDirectory: projectConfigSourceDirectory ?? void 0,
52291
52707
  suppressRendering: isMultiProject,
52708
+ concurrentScan: isMultiProject,
52292
52709
  baseline: baselineRef ? { ref: baselineRef } : void 0,
52710
+ changedLineRanges: scope === "lines" && changedLineRanges !== null ? resolveProjectChangedLineRanges(resolvedDirectory, scanDirectory, changedLineRanges) : void 0,
52293
52711
  supplyChainManifestChanged
52294
52712
  });
52295
- allDiagnostics.push(...scanResult.diagnostics);
52296
- completedScans.push({
52297
- directory: projectDirectory,
52298
- result: scanResult
52299
- });
52300
52713
  if (!isQuiet && !isMultiProject) cliLogger.break();
52714
+ return {
52715
+ directory: scanDirectory,
52716
+ result: scanResult,
52717
+ config: projectConfig
52718
+ };
52719
+ };
52720
+ const scanLoopStartTime = performance$1.now();
52721
+ const projectCount = projectDirectories.length;
52722
+ const batchSpinner = isMultiProject && !isQuiet ? spinner(`Scanning ${projectCount} projects…`).start() : null;
52723
+ const ownsBatchSpinnerSilence = isMultiProject && scanOptions.silent === true;
52724
+ const wasSpinnerSilent = isSpinnerSilent();
52725
+ if (ownsBatchSpinnerSilence) setSpinnerSilent(true);
52726
+ let finishedProjectCount = 0;
52727
+ let scanOutcomes;
52728
+ try {
52729
+ scanOutcomes = await mapWithConcurrency(projectDirectories, isMultiProject ? 4 : 1, async (projectDirectory) => {
52730
+ const scanOutcome = await scanProject(projectDirectory);
52731
+ finishedProjectCount += 1;
52732
+ batchSpinner?.update(`Scanning ${projectCount} projects… (${finishedProjectCount}/${projectCount})`);
52733
+ return scanOutcome;
52734
+ });
52735
+ } finally {
52736
+ if (ownsBatchSpinnerSilence) setSpinnerSilent(wasSpinnerSilent);
52737
+ batchSpinner?.stop();
52738
+ }
52739
+ for (const scanOutcome of scanOutcomes) {
52740
+ if (scanOutcome === null) continue;
52741
+ completedScans.push(scanOutcome);
52301
52742
  }
52302
52743
  if (!isQuiet && isMultiProject && completedScans.length > 0) {
52303
52744
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
52304
52745
  await runPromise(printMultiProjectSummary({
52305
52746
  completedScans,
52306
52747
  categoryFilters,
52307
- userConfig,
52308
52748
  verbose: Boolean(flags.verbose),
52749
+ outputDirectory: flags.outputDir,
52309
52750
  isOffline: !shouldShowShareLink,
52310
- projectName: Path.basename(resolvedDirectory)
52751
+ projectName: Path.basename(resolvedDirectory),
52752
+ totalElapsedMilliseconds: performance$1.now() - scanLoopStartTime
52311
52753
  }));
52312
52754
  }
52755
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterScansForSurface(completedScans, scanOptions.outputSurface ?? "cli"), categoryFilters);
52756
+ const didScansWriteDump = isMultiProject ? !isQuiet && completedScans.length > 0 : completedScans.length > 0;
52757
+ if (flags.outputDir && !didScansWriteDump) await runPromise(printDiagnosticsDump(selectedSurfaceDiagnostics, flags.outputDir, false, isQuiet ? "stderr" : "stdout"));
52313
52758
  finalizeScans({
52314
- diagnostics: allDiagnostics,
52315
52759
  completedScans,
52316
52760
  mode: baselineRef ? "baseline" : isDiffMode ? "diff" : "full",
52317
52761
  diff: isDiffMode ? diffInfo : null,
52318
- baselineIntended: isDiffMode && diffInfo !== null && !diffInfo.isCurrentChanges,
52762
+ baselineIntended: scope === "changed" && diffInfo !== null && !diffInfo.isCurrentChanges,
52319
52763
  isJsonMode,
52320
52764
  isScoreOnly,
52321
52765
  flags,
@@ -52324,13 +52768,13 @@ const inspectAction = async (directory, flags) => {
52324
52768
  resolvedDirectory,
52325
52769
  startTime
52326
52770
  });
52327
- const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
52328
52771
  if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
52329
52772
  await handoffToAgent({
52330
52773
  diagnostics: selectedSurfaceDiagnostics,
52331
52774
  projectName: Path.basename(resolvedDirectory),
52332
52775
  rootDirectory: resolvedDirectory,
52333
- interactive: true
52776
+ interactive: true,
52777
+ outputDirectory: flags.outputDir
52334
52778
  });
52335
52779
  return;
52336
52780
  }
@@ -53122,11 +53566,14 @@ const ROOT_FLAG_SPEC = {
53122
53566
  "--yes"
53123
53567
  ]),
53124
53568
  longOptionsWithRequiredValues: new Set([
53569
+ "--base",
53125
53570
  "--category",
53126
53571
  "--changed-files-from",
53127
53572
  "--blocking",
53573
+ "--output-dir",
53128
53574
  "--fail-on",
53129
- "--project"
53575
+ "--project",
53576
+ "--scope"
53130
53577
  ]),
53131
53578
  longOptionsWithOptionalValues: new Set(["--diff"]),
53132
53579
  shortOptionsWithoutValues: new Set([
@@ -53278,6 +53725,7 @@ ${formatExampleLines([
53278
53725
  ["react-doctor", "scan the current project"],
53279
53726
  ["react-doctor ./apps/web", "scan a specific directory"],
53280
53727
  ["react-doctor --diff main", "scan only files changed vs. main"],
53728
+ ["react-doctor --project modules/a,modules/b", "score each module separately (names or paths)"],
53281
53729
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
53282
53730
  ["react-doctor --category Security", "show only one diagnostic category"],
53283
53731
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
@@ -53309,9 +53757,9 @@ ${highlighter.dim("Learn more:")}
53309
53757
  ${highlighter.info(CANONICAL_GITHUB_URL)}
53310
53758
  `;
53311
53759
  const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
53312
- 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);
53760
+ 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);
53313
53761
  program.action(inspectAction);
53314
- 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));
53762
+ 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));
53315
53763
  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);
53316
53764
  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);
53317
53765
  const rules = program.command("rules").description("List, explain, and configure which React Doctor rules run");
@@ -53352,4 +53800,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
53352
53800
  export {};
53353
53801
 
53354
53802
  //# sourceMappingURL=cli.js.map
53355
- //# debugId=f25bdf09-ff57-565e-b47b-46ef237158c2
53803
+ //# debugId=5c7334de-5fd1-50a7-bb75-1a17b3b54e4e