react-doctor 0.3.0-dev.915745e → 0.3.0-dev.9a8ad6e

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,11 +1,11 @@
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]="5f1571ca-529b-5db6-ba79-f7bc1c4d6d2d")}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]="3c457dc9-865a-5459-b923-a0fb762b158f")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as path$1 from "node:path";
6
6
  import path from "node:path";
7
7
  import * as fs$1 from "node:fs";
8
- import fs from "node:fs";
8
+ import fs, { mkdtempSync, rmSync } from "node:fs";
9
9
  import process$1 from "node:process";
10
10
  import * as Schema from "effect/Schema";
11
11
  import reactDoctorPlugin, { ALL_REACT_DOCTOR_RULE_KEYS, FRAMEWORK_SPECIFIC_RULE_KEYS, MOTION_LIBRARY_PACKAGES, REACT_COMPILER_RULES, REACT_DOCTOR_RULES } from "oxlint-plugin-react-doctor";
@@ -34,10 +34,10 @@ import * as ChildProcess from "effect/unstable/process/ChildProcess";
34
34
  import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
35
35
  import * as ts from "typescript";
36
36
  import { gzipSync } from "node:zlib";
37
+ import { createHash, randomUUID } from "node:crypto";
37
38
  import * as Exit from "effect/Exit";
38
39
  import * as Sentry from "@sentry/node";
39
40
  import { performance } from "node:perf_hooks";
40
- import { createHash, randomUUID } from "node:crypto";
41
41
  import * as Tracer from "effect/Tracer";
42
42
  import { promisify, stripVTControlCharacters } from "node:util";
43
43
  import tty from "node:tty";
@@ -3117,7 +3117,8 @@ var Diagnostic = class extends Schema.Class("Diagnostic")({
3117
3117
  const JsonReportMode = Schema.Literals([
3118
3118
  "full",
3119
3119
  "diff",
3120
- "staged"
3120
+ "staged",
3121
+ "baseline"
3121
3122
  ]);
3122
3123
  var JsonReportSummary = class extends Schema.Class("JsonReportSummary")({
3123
3124
  errorCount: Schema.Number,
@@ -3136,7 +3137,9 @@ var JsonReportDiffInfo = class extends Schema.Class("JsonReportDiffInfo")({
3136
3137
  var JsonReportError = class extends Schema.Class("JsonReportError")({
3137
3138
  message: Schema.String,
3138
3139
  name: Schema.String,
3139
- chain: Schema.Array(Schema.String)
3140
+ chain: Schema.Array(Schema.String),
3141
+ /** Sentry event id for the crash, when one was reported. */
3142
+ sentryEventId: Schema.optional(Schema.NullOr(Schema.String))
3140
3143
  }) {};
3141
3144
  /**
3142
3145
  * Schema for a single project entry within a JsonReport. `project` is
@@ -3173,7 +3176,33 @@ var JsonReportV1 = class extends Schema.Class("JsonReportV1")({
3173
3176
  elapsedMilliseconds: Schema.Number,
3174
3177
  error: Schema.NullOr(JsonReportError)
3175
3178
  }) {};
3176
- Schema.Union([JsonReportV1]);
3179
+ var JsonReportBaseline = class extends Schema.Class("JsonReportBaseline")({
3180
+ baseRef: Schema.String,
3181
+ newCount: Schema.Number,
3182
+ fixedCount: Schema.Number,
3183
+ baseTotalCount: Schema.Number
3184
+ }) {};
3185
+ /**
3186
+ * Baseline (PR-introduced-issues-only) report — `schemaVersion: 2`. A
3187
+ * superset of v1: same fields, plus a `baseline` block. `diagnostics` /
3188
+ * `summary` counts are the introduced findings only; `summary.score` stays
3189
+ * the head project-health score. Consumers branch on `schemaVersion`.
3190
+ */
3191
+ var JsonReportV2 = class extends Schema.Class("JsonReportV2")({
3192
+ schemaVersion: Schema.Literal(2),
3193
+ version: Schema.String,
3194
+ ok: Schema.Boolean,
3195
+ directory: Schema.String,
3196
+ mode: JsonReportMode,
3197
+ diff: Schema.NullOr(JsonReportDiffInfo),
3198
+ baseline: JsonReportBaseline,
3199
+ projects: Schema.Array(JsonReportProjectEntry),
3200
+ diagnostics: Schema.Array(Diagnostic),
3201
+ summary: JsonReportSummary,
3202
+ elapsedMilliseconds: Schema.Number,
3203
+ error: Schema.NullOr(JsonReportError)
3204
+ }) {};
3205
+ Schema.Union([JsonReportV1, JsonReportV2]);
3177
3206
  //#endregion
3178
3207
  //#region ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/constants.js
3179
3208
  var require_constants = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
@@ -9296,6 +9325,11 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9296
9325
  branch
9297
9326
  ]).pipe(Effect.map((result) => result.status === 0));
9298
9327
  const headSha = (directory) => runGit(directory, ["rev-parse", "HEAD"]).pipe(Effect.map((result) => result.status === 0 ? trimOrNull(result.stdout) : null));
9328
+ const mergeBase = (input) => isSafeGitRevision(input.ref) ? runGit(input.directory, [
9329
+ "merge-base",
9330
+ input.ref,
9331
+ "HEAD"
9332
+ ]).pipe(Effect.map((result) => result.status === 0 ? trimOrNull(result.stdout) : null)) : Effect.succeed(null);
9299
9333
  const githubRepo = (directory) => runGit(directory, [
9300
9334
  "config",
9301
9335
  "--get",
@@ -9371,6 +9405,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9371
9405
  return {
9372
9406
  currentBranch: yield* currentBranch(input.directory),
9373
9407
  baseBranch: baseRef,
9408
+ diffBaseRef,
9374
9409
  changedFiles: splitNullSeparated(diff.stdout),
9375
9410
  isCurrentChanges: false
9376
9411
  };
@@ -9382,6 +9417,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9382
9417
  githubRepo,
9383
9418
  githubViewerPermission,
9384
9419
  branchExists,
9420
+ mergeBase,
9385
9421
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
9386
9422
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
9387
9423
  if (explicitBaseBranch !== void 0) {
@@ -9439,6 +9475,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9439
9475
  return {
9440
9476
  currentBranch: resolvedCurrentBranch,
9441
9477
  baseBranch,
9478
+ diffBaseRef: mergeBaseRef,
9442
9479
  changedFiles: splitNullSeparated(diff.stdout),
9443
9480
  isCurrentChanges: false
9444
9481
  };
@@ -9460,6 +9497,12 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9460
9497
  directory,
9461
9498
  maxStdoutBytes: options?.maxBufferBytes
9462
9499
  }).pipe(Effect.map((result) => result.status === 0 ? result.stdout : null)),
9500
+ showRefContent: ({ directory, ref, relativePath, options }) => isSafeGitRevision(ref) ? runCommand({
9501
+ command: "git",
9502
+ args: ["show", `${ref}:./${relativePath}`],
9503
+ directory,
9504
+ maxStdoutBytes: options?.maxBufferBytes
9505
+ }).pipe(Effect.map((result) => result.status === 0 ? result.stdout : null)) : Effect.succeed(null),
9463
9506
  grep: (input) => Effect.gen(function* () {
9464
9507
  const args = ["grep"];
9465
9508
  if (input.listMatchingFiles ?? true) args.push("-l");
@@ -9495,9 +9538,11 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9495
9538
  githubRepo: () => Effect.succeed(snapshot.githubRepo ?? null),
9496
9539
  githubViewerPermission: () => Effect.succeed(snapshot.githubViewerPermission ?? null),
9497
9540
  branchExists: (_directory, branch) => Effect.succeed(snapshot.branchExists?.get(branch) ?? false),
9541
+ mergeBase: ({ ref }) => Effect.succeed(snapshot.mergeBase?.get(ref) ?? null),
9498
9542
  diffSelection: () => Effect.succeed(snapshot.diffSelection ?? null),
9499
9543
  stagedFilePaths: () => Effect.succeed(snapshot.stagedFiles ?? []),
9500
9544
  showStagedContent: (_directory, relativePath) => Effect.succeed(snapshot.stagedContent?.get(relativePath) ?? null),
9545
+ showRefContent: ({ ref, relativePath }) => Effect.succeed(snapshot.refContent?.get(`${ref}:${relativePath}`) ?? null),
9501
9546
  grep: () => Effect.sync(() => {
9502
9547
  const matches = snapshot.grepMatches;
9503
9548
  if (matches === null || matches === void 0) return null;
@@ -11606,19 +11651,60 @@ var NodeResolver = class NodeResolver extends Context.Service()("react-doctor/No
11606
11651
  });
11607
11652
  };
11608
11653
  /**
11609
- * Zip-Slip defense: `git diff --cached --name-only` is the source
11610
- * of `relativePath`, and git normalizes paths during ordinary
11611
- * `git add`. But a deliberately crafted index entry (via
11612
- * `git update-index --add`, a malicious pack, or a symlinked
11613
- * working tree) can include `..` segments that escape the temp
11614
- * tree. Resolve the candidate against the temp dir and reject any
11615
- * result that lands outside it before `writeFileSync` runs.
11654
+ * Zip-Slip defense: relative paths come from git (`diff --name-only`), which
11655
+ * normalizes during ordinary adds, but a crafted index/pack/symlinked tree can
11656
+ * smuggle `..` segments that escape the temp root. Resolve against the temp dir
11657
+ * and reject anything that lands outside before writing.
11616
11658
  */
11617
11659
  const isPathInsideDirectory = (childAbsolutePath, parentAbsolutePath) => {
11618
- const relative = path$1.relative(parentAbsolutePath, childAbsolutePath);
11619
- return Boolean(relative) && !relative.startsWith("..") && !path$1.isAbsolute(relative);
11660
+ const relative = path.relative(parentAbsolutePath, childAbsolutePath);
11661
+ return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
11620
11662
  };
11621
11663
  /**
11664
+ * Writes a set of source files (supplied by `readContent` — e.g.
11665
+ * `git show <ref>:<path>` for a baseline tree, or `git show :<path>` for the
11666
+ * index) into a temp tree that mirrors the project layout, copying the
11667
+ * well-known project-config files from `directory` so oxlint resolves
11668
+ * tsconfig / lint config identically to the working tree. Shared by the staged
11669
+ * and baseline scan paths so the zip-slip guard lives in one audited place.
11670
+ * Per-file read failures skip that file (the scan proceeds with whatever read
11671
+ * cleanly) rather than sinking the whole snapshot.
11672
+ */
11673
+ const materializeSourceTree = (input) => Effect.gen(function* () {
11674
+ const materializedFiles = [];
11675
+ const resolvedTempDirectory = path.resolve(input.tempDirectory);
11676
+ for (const relativePath of input.files) {
11677
+ const content = yield* input.readContent(relativePath).pipe(Effect.orElseSucceed(() => null));
11678
+ if (content === null) continue;
11679
+ const candidateTargetPath = path.resolve(resolvedTempDirectory, relativePath);
11680
+ if (!isPathInsideDirectory(candidateTargetPath, resolvedTempDirectory)) continue;
11681
+ yield* Effect.sync(() => {
11682
+ fs.mkdirSync(path.dirname(candidateTargetPath), { recursive: true });
11683
+ fs.writeFileSync(candidateTargetPath, content);
11684
+ });
11685
+ materializedFiles.push(relativePath);
11686
+ }
11687
+ yield* Effect.sync(() => {
11688
+ for (const configFilename of STAGED_FILES_PROJECT_CONFIG_FILENAMES) {
11689
+ const sourcePath = path.join(input.directory, configFilename);
11690
+ const targetPath = path.join(resolvedTempDirectory, configFilename);
11691
+ if (fs.existsSync(sourcePath) && !fs.existsSync(targetPath)) fs.cpSync(sourcePath, targetPath);
11692
+ }
11693
+ });
11694
+ return {
11695
+ tempDirectory: input.tempDirectory,
11696
+ materializedFiles,
11697
+ cleanup: () => {
11698
+ try {
11699
+ fs.rmSync(input.tempDirectory, {
11700
+ recursive: true,
11701
+ force: true
11702
+ });
11703
+ } catch {}
11704
+ }
11705
+ };
11706
+ });
11707
+ /**
11622
11708
  * `StagedFiles` materializes the git-staged source files of a
11623
11709
  * directory into a temp tree (mirroring the project layout and
11624
11710
  * carrying over a fixed set of project config files) so oxlint can
@@ -11635,40 +11721,16 @@ var StagedFiles = class StagedFiles extends Context.Service()("react-doctor/Stag
11635
11721
  const git = yield* Git;
11636
11722
  return StagedFiles.of({
11637
11723
  discoverSourceFiles: (directory) => git.stagedFilePaths(directory).pipe(Effect.map((entries) => entries.filter(isLintableSourceFile))),
11638
- materialize: ({ directory, stagedFiles, tempDirectory }) => Effect.gen(function* () {
11639
- const materializedFiles = [];
11640
- const resolvedTempDirectory = path$1.resolve(tempDirectory);
11641
- for (const relativePath of stagedFiles) {
11642
- const content = yield* git.showStagedContent(directory, relativePath, { maxBufferBytes: GIT_SHOW_MAX_BUFFER_BYTES }).pipe(Effect.orElseSucceed(() => null));
11643
- if (content === null) continue;
11644
- const candidateTargetPath = path$1.resolve(resolvedTempDirectory, relativePath);
11645
- if (!isPathInsideDirectory(candidateTargetPath, resolvedTempDirectory)) continue;
11646
- yield* Effect.sync(() => {
11647
- fs$1.mkdirSync(path$1.dirname(candidateTargetPath), { recursive: true });
11648
- fs$1.writeFileSync(candidateTargetPath, content);
11649
- });
11650
- materializedFiles.push(relativePath);
11651
- }
11652
- yield* Effect.sync(() => {
11653
- for (const configFilename of STAGED_FILES_PROJECT_CONFIG_FILENAMES) {
11654
- const sourcePath = path$1.join(directory, configFilename);
11655
- const targetPath = path$1.join(resolvedTempDirectory, configFilename);
11656
- if (fs$1.existsSync(sourcePath) && !fs$1.existsSync(targetPath)) fs$1.cpSync(sourcePath, targetPath);
11657
- }
11658
- });
11659
- return {
11660
- tempDirectory,
11661
- stagedFiles: materializedFiles,
11662
- cleanup: () => {
11663
- try {
11664
- fs$1.rmSync(tempDirectory, {
11665
- recursive: true,
11666
- force: true
11667
- });
11668
- } catch {}
11669
- }
11670
- };
11671
- })
11724
+ materialize: ({ directory, stagedFiles, tempDirectory }) => materializeSourceTree({
11725
+ directory,
11726
+ files: stagedFiles,
11727
+ tempDirectory,
11728
+ readContent: (relativePath) => git.showStagedContent(directory, relativePath, { maxBufferBytes: GIT_SHOW_MAX_BUFFER_BYTES })
11729
+ }).pipe(Effect.map((tree) => ({
11730
+ tempDirectory: tree.tempDirectory,
11731
+ stagedFiles: tree.materializedFiles,
11732
+ cleanup: tree.cleanup
11733
+ })))
11672
11734
  });
11673
11735
  }));
11674
11736
  /**
@@ -11715,18 +11777,22 @@ const safeGetErrorChain = (error) => {
11715
11777
  };
11716
11778
  const buildJsonReportError = (input) => {
11717
11779
  const chain = safeGetErrorChain(input.error);
11780
+ const sentryEventId = input.sentryEventId ?? null;
11718
11781
  const errorPayload = isReactDoctorError(input.error) ? {
11719
11782
  message: formatReactDoctorError(input.error),
11720
11783
  name: `ReactDoctorError(${input.error.reason._tag})`,
11721
- chain
11784
+ chain,
11785
+ sentryEventId
11722
11786
  } : input.error instanceof Error ? {
11723
11787
  message: input.error.message || input.error.name || "Error",
11724
11788
  name: input.error.name || "Error",
11725
- chain
11789
+ chain,
11790
+ sentryEventId
11726
11791
  } : {
11727
11792
  message: safeStringify(input.error),
11728
11793
  name: "Error",
11729
- chain
11794
+ chain,
11795
+ sentryEventId
11730
11796
  };
11731
11797
  return {
11732
11798
  schemaVersion: 1,
@@ -11802,12 +11868,10 @@ const buildJsonReport = (input) => {
11802
11868
  const flattenedDiagnostics = projects.flatMap((entry) => entry.diagnostics);
11803
11869
  const worstScoredProject = findWorstScoredProject(projects);
11804
11870
  const summary = summarizeDiagnostics(flattenedDiagnostics, worstScoredProject?.score?.score ?? null, worstScoredProject?.score?.label ?? null);
11805
- return {
11806
- schemaVersion: 1,
11871
+ const shared = {
11807
11872
  version: input.version,
11808
11873
  ok: true,
11809
11874
  directory: input.directory,
11810
- mode: input.mode,
11811
11875
  diff: toJsonDiff(input.diff),
11812
11876
  projects,
11813
11877
  diagnostics: flattenedDiagnostics,
@@ -11815,6 +11879,22 @@ const buildJsonReport = (input) => {
11815
11879
  elapsedMilliseconds: input.totalElapsedMilliseconds,
11816
11880
  error: null
11817
11881
  };
11882
+ if (input.baseline) return {
11883
+ schemaVersion: 2,
11884
+ mode: "baseline",
11885
+ baseline: {
11886
+ baseRef: input.baseline.baseRef,
11887
+ newCount: summary.totalDiagnosticCount,
11888
+ fixedCount: input.baseline.fixedCount,
11889
+ baseTotalCount: input.baseline.baseTotalCount
11890
+ },
11891
+ ...shared
11892
+ };
11893
+ return {
11894
+ schemaVersion: 1,
11895
+ mode: input.mode,
11896
+ ...shared
11897
+ };
11818
11898
  };
11819
11899
  /**
11820
11900
  * Single source of truth for the skipped-check accounting shared by the
@@ -11836,6 +11916,45 @@ const buildSkippedChecks = (input) => {
11836
11916
  skippedCheckReasons
11837
11917
  };
11838
11918
  };
11919
+ const fingerprintDiagnostic = (diagnostic, lineText) => {
11920
+ const ruleKey = `${diagnostic.plugin}/${diagnostic.rule}`;
11921
+ const snippet = lineText === null ? "" : createHash("sha1").update(lineText.trim()).digest("hex");
11922
+ return `${diagnostic.filePath}\u0000${ruleKey}\u0000${snippet}`;
11923
+ };
11924
+ /**
11925
+ * Diffs a head scan against a base scan to isolate the diagnostics a change
11926
+ * introduced (and count the ones it resolved). Matching is a multiset over a
11927
+ * position-independent fingerprint — `(filePath, plugin/rule, hash(flagged
11928
+ * line text))` — so inserting lines above an existing issue doesn't make it
11929
+ * look new, while a genuinely new occurrence (new line text, or one more of
11930
+ * the same) surfaces. Identical repeated findings are matched by count.
11931
+ *
11932
+ * v1 limitation: the fingerprint keys on the head-relative `filePath`, and base
11933
+ * content is read at that same path. A file renamed by the change therefore has
11934
+ * no base match, so its pre-existing findings are reported as new. This
11935
+ * over-reports (never hides a real issue) and is rare; rename-aware base
11936
+ * resolution is a follow-up.
11937
+ */
11938
+ const computeDiagnosticDelta = (input) => {
11939
+ const unmatchedBaseByFingerprint = /* @__PURE__ */ new Map();
11940
+ for (const diagnostic of input.baseDiagnostics) {
11941
+ const key = fingerprintDiagnostic(diagnostic, input.readBaseLine(diagnostic.filePath, diagnostic.line));
11942
+ unmatchedBaseByFingerprint.set(key, (unmatchedBaseByFingerprint.get(key) ?? 0) + 1);
11943
+ }
11944
+ const newDiagnostics = [];
11945
+ for (const diagnostic of input.headDiagnostics) {
11946
+ const key = fingerprintDiagnostic(diagnostic, input.readHeadLine(diagnostic.filePath, diagnostic.line));
11947
+ const availableMatches = unmatchedBaseByFingerprint.get(key) ?? 0;
11948
+ if (availableMatches > 0) unmatchedBaseByFingerprint.set(key, availableMatches - 1);
11949
+ else newDiagnostics.push(diagnostic);
11950
+ }
11951
+ let fixedCount = 0;
11952
+ for (const remaining of unmatchedBaseByFingerprint.values()) fixedCount += remaining;
11953
+ return {
11954
+ newDiagnostics,
11955
+ fixedCount
11956
+ };
11957
+ };
11839
11958
  /**
11840
11959
  * Programmatic façade over `Git.diffSelection`. Async because the
11841
11960
  * Git service runs through Effect's `ChildProcess` (true subprocess
@@ -11858,6 +11977,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
11858
11977
  return {
11859
11978
  currentBranch: selection.currentBranch,
11860
11979
  baseBranch: selection.baseBranch,
11980
+ ...selection.diffBaseRef !== void 0 ? { diffBaseRef: selection.diffBaseRef } : {},
11861
11981
  changedFiles: [...selection.changedFiles],
11862
11982
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
11863
11983
  };
@@ -11917,10 +12037,9 @@ const CI_PROVIDER_BY_ENVIRONMENT_VARIABLE = [
11917
12037
  ];
11918
12038
  const GITHUB_ACTION_MARKER_ENVIRONMENT_VARIABLE = "REACT_DOCTOR_GITHUB_ACTION";
11919
12039
  const ACTION_INPUT_ENVIRONMENT_VARIABLES = {
11920
- failOn: "REACT_DOCTOR_ACTION_FAIL_ON",
11921
- nonBlocking: "REACT_DOCTOR_ACTION_NON_BLOCKING",
12040
+ blocking: "REACT_DOCTOR_ACTION_BLOCKING",
11922
12041
  comment: "REACT_DOCTOR_ACTION_COMMENT",
11923
- annotations: "REACT_DOCTOR_ACTION_ANNOTATIONS",
12042
+ reviewComments: "REACT_DOCTOR_ACTION_REVIEW_COMMENTS",
11924
12043
  version: "REACT_DOCTOR_ACTION_VERSION"
11925
12044
  };
11926
12045
  const CODING_AGENT_BY_ENVIRONMENT_VARIABLE = [
@@ -11992,6 +12111,7 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
11992
12111
  //#endregion
11993
12112
  //#region src/cli/utils/constants.ts
11994
12113
  const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
12114
+ const BASELINE_FILES_TEMP_DIR_PREFIX = "react-doctor-baseline-";
11995
12115
  const CI_TRUST_COMPANIES = "PayPal, Rippling, and Alibaba";
11996
12116
  const WELCOME_EXPLANATION_HOLD_MS = 1e3;
11997
12117
  const CATEGORY_COUNTUP_SETTLE_HOLD_MS = 1e3;
@@ -12009,6 +12129,7 @@ const METRIC = {
12009
12129
  scanScore: "scan.score",
12010
12130
  scanClean: "scan.clean",
12011
12131
  scanCheckSkipped: "scan.check_skipped",
12132
+ baselineDegraded: "baseline.degraded",
12012
12133
  ruleFired: "rule.fired",
12013
12134
  lintFailed: "lint.failed",
12014
12135
  deadCodeFailed: "deadcode.failed",
@@ -12070,7 +12191,7 @@ const makeNoopConsole = () => ({
12070
12191
  });
12071
12192
  //#endregion
12072
12193
  //#region src/cli/utils/version.ts
12073
- const VERSION = "0.3.0-dev.915745e";
12194
+ const VERSION = "0.3.0-dev.9a8ad6e";
12074
12195
  //#endregion
12075
12196
  //#region src/cli/utils/json-mode.ts
12076
12197
  let context = null;
@@ -12128,7 +12249,7 @@ const writeJsonReport = (report) => {
12128
12249
  const serialized = context?.compact ? JSON.stringify(report) : JSON.stringify(report, null, 2);
12129
12250
  process.stdout.write(`${serialized}\n`);
12130
12251
  };
12131
- const writeJsonErrorReport = (error) => {
12252
+ const writeJsonErrorReport = (error, sentryEventId) => {
12132
12253
  if (!context) return;
12133
12254
  try {
12134
12255
  writeJsonReport(buildJsonReportError({
@@ -12136,7 +12257,8 @@ const writeJsonErrorReport = (error) => {
12136
12257
  directory: context.directory,
12137
12258
  error,
12138
12259
  elapsedMilliseconds: performance.now() - context.startTime,
12139
- mode: context.mode
12260
+ mode: context.mode,
12261
+ sentryEventId
12140
12262
  }));
12141
12263
  } catch {
12142
12264
  process.stdout.write(INTERNAL_ERROR_JSON_FALLBACK);
@@ -12427,13 +12549,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12427
12549
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12428
12550
  * standard `SENTRY_RELEASE` override.
12429
12551
  */
12430
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.3.0-dev.915745e`;
12552
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.3.0-dev.9a8ad6e`;
12431
12553
  /**
12432
12554
  * Deployment environment shown in Sentry's environment filter. Defaults to
12433
12555
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12434
12556
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12435
12557
  */
12436
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.3.0-dev.915745e") ? "development" : "production");
12558
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.3.0-dev.9a8ad6e") ? "development" : "production");
12437
12559
  /**
12438
12560
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12439
12561
  * (set to `0` to disable tracing) and falls back to
@@ -15898,6 +16020,7 @@ const recordScanMetrics = (input) => {
15898
16020
  if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
15899
16021
  if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
15900
16022
  else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
16023
+ if (input.baselineDegraded) recordCount(METRIC.baselineDegraded, 1);
15901
16024
  if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
15902
16025
  if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
15903
16026
  for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
@@ -15906,10 +16029,61 @@ const recordScanMetrics = (input) => {
15906
16029
  });
15907
16030
  };
15908
16031
  //#endregion
15909
- //#region src/cli/utils/should-fail-for-diagnostics.ts
15910
- const shouldFailForDiagnostics = (diagnostics, failOnLevel) => {
15911
- if (failOnLevel === "none") return false;
15912
- if (failOnLevel === "warning") return diagnostics.length > 0;
16032
+ //#region src/cli/utils/cli-logger.ts
16033
+ /**
16034
+ * Thin synchronous façade over Effect's `Console` module. Used by
16035
+ * the imperative CLI helper files (`select-projects`, `run-explain`,
16036
+ * `install-react-doctor`, the legacy paths in `cli/commands/inspect.ts`)
16037
+ * that aren't yet Effect-typed. Every call drains into a single
16038
+ * `Console.*` Effect via `Effect.runSync`, so the underlying logging
16039
+ * pipeline is identical to the canonical `yield* Console.log(...)`
16040
+ * call sites in the renderers. Convert callers to `Effect.gen` to
16041
+ * drop the bridge.
16042
+ */
16043
+ const cliLogger = {
16044
+ log: (message) => {
16045
+ Effect.runSync(Console.log(message));
16046
+ },
16047
+ warn: (message) => {
16048
+ Effect.runSync(Console.warn(highlighter.warn(message)));
16049
+ },
16050
+ error: (message) => {
16051
+ Effect.runSync(Console.error(highlighter.error(message)));
16052
+ },
16053
+ info: (message) => {
16054
+ Effect.runSync(Console.info(highlighter.info(message)));
16055
+ },
16056
+ dim: (message) => {
16057
+ Effect.runSync(Console.log(highlighter.gray(message)));
16058
+ },
16059
+ success: (message) => {
16060
+ Effect.runSync(Console.log(highlighter.success(message)));
16061
+ },
16062
+ break: () => {
16063
+ Effect.runSync(Console.log(""));
16064
+ }
16065
+ };
16066
+ //#endregion
16067
+ //#region src/cli/utils/resolve-blocking-level.ts
16068
+ const VALID_BLOCKING_LEVELS = new Set([
16069
+ "error",
16070
+ "warning",
16071
+ "none"
16072
+ ]);
16073
+ const DEFAULT_BLOCKING_LEVEL = "error";
16074
+ const isValidBlockingLevel = (level) => VALID_BLOCKING_LEVELS.has(level);
16075
+ const pickBlockingLevel = (flags, userConfig) => flags.blocking ?? flags.failOn ?? userConfig?.blocking ?? userConfig?.failOn;
16076
+ const resolveBlockingLevel = (flags, userConfig) => {
16077
+ const sourceValue = pickBlockingLevel(flags, userConfig) ?? DEFAULT_BLOCKING_LEVEL;
16078
+ if (isValidBlockingLevel(sourceValue)) return sourceValue;
16079
+ cliLogger.warn(`Invalid blocking level "${sourceValue}". Expected one of: error, warning, none. Falling back to "${DEFAULT_BLOCKING_LEVEL}".`);
16080
+ return DEFAULT_BLOCKING_LEVEL;
16081
+ };
16082
+ //#endregion
16083
+ //#region src/cli/utils/should-block-ci.ts
16084
+ const shouldBlockCi = (diagnostics, blockingLevel) => {
16085
+ if (blockingLevel === "none") return false;
16086
+ if (blockingLevel === "warning") return diagnostics.length > 0;
15913
16087
  return diagnostics.some((diagnostic) => diagnostic.severity === "error");
15914
16088
  };
15915
16089
  //#endregion
@@ -15923,11 +16097,6 @@ const shouldFailForDiagnostics = (diagnostics, failOnLevel) => {
15923
16097
  const toCategoryKey = (category) => category.toLowerCase().replace(/[^a-z0-9]+/g, "_");
15924
16098
  //#endregion
15925
16099
  //#region src/cli/utils/build-run-event.ts
15926
- const FAIL_ON_LEVELS = new Set([
15927
- "error",
15928
- "warning",
15929
- "none"
15930
- ]);
15931
16100
  const readEnvBoolean = (name) => {
15932
16101
  const value = process.env[name];
15933
16102
  if (value === void 0) return null;
@@ -15939,10 +16108,10 @@ const resolveVersionPin = (versionInput) => {
15939
16108
  if (/^(\.\.?\/|\/)/.test(versionInput)) return "local";
15940
16109
  return "pinned";
15941
16110
  };
15942
- const resolveTelemetryFailOn = (userConfig) => {
15943
- const fromAction = process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.failOn];
15944
- if (fromAction !== void 0 && FAIL_ON_LEVELS.has(fromAction)) return fromAction;
15945
- return userConfig?.failOn ?? "none";
16111
+ const resolveTelemetryBlocking = (userConfig) => {
16112
+ const fromAction = process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.blocking];
16113
+ if (fromAction !== void 0 && isValidBlockingLevel(fromAction)) return fromAction;
16114
+ return userConfig?.blocking ?? userConfig?.failOn ?? "error";
15946
16115
  };
15947
16116
  const buildOutcomeAttributes = (input) => {
15948
16117
  if (input.result === void 0) {
@@ -15957,9 +16126,9 @@ const buildOutcomeAttributes = (input) => {
15957
16126
  }
15958
16127
  const result = input.result;
15959
16128
  const summary = summarizeDiagnostics(result.diagnostics);
15960
- const failOnLevel = resolveTelemetryFailOn(input.userConfig);
16129
+ const blockingLevel = resolveTelemetryBlocking(input.userConfig);
15961
16130
  const gateDiagnostics = filterDiagnosticsForSurface(result.diagnostics, "ciFailure", input.userConfig);
15962
- const wouldBlock = !input.scoreOnly && shouldFailForDiagnostics(gateDiagnostics, failOnLevel);
16131
+ const wouldBlock = !input.scoreOnly && !input.gateExempt && shouldBlockCi(gateDiagnostics, blockingLevel);
15963
16132
  const hasSkippedChecks = result.skippedChecks.length > 0;
15964
16133
  const isClean = result.diagnostics.length === 0 && !hasSkippedChecks;
15965
16134
  const outcome = wouldBlock ? "blocked" : isClean ? "clean" : "ok";
@@ -15980,7 +16149,7 @@ const buildOutcomeAttributes = (input) => {
15980
16149
  outcome,
15981
16150
  exitCode: wouldBlock ? 1 : 0,
15982
16151
  wouldBlock,
15983
- failOn: failOnLevel,
16152
+ blocking: blockingLevel,
15984
16153
  scanClean: isClean,
15985
16154
  totalDiagnostics: summary.totalDiagnosticCount,
15986
16155
  errorCount: summary.errorCount,
@@ -16001,6 +16170,12 @@ const buildOutcomeAttributes = (input) => {
16001
16170
  didDeadCodeFail: input.didDeadCodeFail ?? null
16002
16171
  };
16003
16172
  for (const [category, count] of countByCategory) attributes[`diag.category.${toCategoryKey(category)}`] = count;
16173
+ if (result.baselineDelta) {
16174
+ attributes["baseline.new"] = summary.totalDiagnosticCount;
16175
+ attributes["baseline.fixed"] = result.baselineDelta.fixedCount;
16176
+ attributes["baseline.baseTotal"] = result.baselineDelta.baseTotalCount;
16177
+ attributes["baseline.degraded"] = false;
16178
+ } else if (input.gateExempt) attributes["baseline.degraded"] = true;
16004
16179
  return attributes;
16005
16180
  };
16006
16181
  const buildCiAttributes = () => {
@@ -16008,9 +16183,8 @@ const buildCiAttributes = () => {
16008
16183
  return {
16009
16184
  actorAssociation: githubActorAssociation ?? null,
16010
16185
  runnerOs: detectRunnerOs(),
16011
- nonBlocking: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.nonBlocking),
16012
16186
  comment: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.comment),
16013
- annotations: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.annotations),
16187
+ reviewComments: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.reviewComments),
16014
16188
  versionPin: resolveVersionPin(process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.version])
16015
16189
  };
16016
16190
  };
@@ -16060,6 +16234,66 @@ const recordRunEvent = (rootSpan, input) => {
16060
16234
  } catch {}
16061
16235
  };
16062
16236
  //#endregion
16237
+ //#region src/cli/utils/materialize-baseline-files.ts
16238
+ /**
16239
+ * Materializes the `ref` version of `files` into `tempDirectory` (via
16240
+ * `git show <ref>:<path>`), mirroring the project layout + head's config files
16241
+ * so the base lints under the same rules as head. Reuses the shared,
16242
+ * zip-slip-guarded `materializeSourceTree`. Per-file read misses (e.g. a file
16243
+ * the PR added, absent at base) are skipped, which is exactly what we want:
16244
+ * a brand-new file has no base counterpart, so all its findings are "new".
16245
+ */
16246
+ const materializeBaselineFiles = (input) => Effect.runPromise(Effect.gen(function* () {
16247
+ const git = yield* Git;
16248
+ return yield* materializeSourceTree({
16249
+ directory: input.directory,
16250
+ files: input.files,
16251
+ tempDirectory: input.tempDirectory,
16252
+ readContent: (relativePath) => git.showRefContent({
16253
+ directory: input.directory,
16254
+ ref: input.ref,
16255
+ relativePath,
16256
+ options: { maxBufferBytes: GIT_SHOW_MAX_BUFFER_BYTES }
16257
+ })
16258
+ });
16259
+ }).pipe(Effect.provide(Git.layerNode)));
16260
+ /**
16261
+ * Resolves the commit a baseline scan should read base content from — the
16262
+ * merge-base of `ref` and HEAD, so "introduced" is measured against the branch
16263
+ * point. `null` when unresolvable (ref missing/unsafe, no merge-base).
16264
+ */
16265
+ const resolveMergeBaseRef = async (directory, ref) => {
16266
+ try {
16267
+ return await Effect.runPromise(Effect.gen(function* () {
16268
+ return yield* (yield* Git).mergeBase({
16269
+ directory,
16270
+ ref
16271
+ });
16272
+ }).pipe(Effect.provide(Git.layerNode)));
16273
+ } catch {
16274
+ return null;
16275
+ }
16276
+ };
16277
+ //#endregion
16278
+ //#region src/cli/utils/read-source-line.ts
16279
+ /**
16280
+ * Builds a cached `(filePath, line) -> source text` reader rooted at
16281
+ * `rootDirectory`, used to fingerprint a diagnostic by the content of its
16282
+ * flagged line (see `computeDiagnosticDelta`). Wraps core's
16283
+ * `createNodeReadFileLinesSync` with per-file memoization + 1-indexed line
16284
+ * lookup; unreadable files / out-of-range lines return `null`.
16285
+ */
16286
+ const createSourceLineReader = (rootDirectory) => {
16287
+ const readFileLines = createNodeReadFileLinesSync(rootDirectory);
16288
+ const fileLinesCache = /* @__PURE__ */ new Map();
16289
+ return (filePath, line) => {
16290
+ if (!fileLinesCache.has(filePath)) fileLinesCache.set(filePath, readFileLines(filePath));
16291
+ const lines = fileLinesCache.get(filePath) ?? null;
16292
+ if (lines === null || line < 1 || line > lines.length) return null;
16293
+ return lines[line - 1] ?? null;
16294
+ };
16295
+ };
16296
+ //#endregion
16063
16297
  //#region src/cli/utils/build-no-score-message.ts
16064
16298
  const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
16065
16299
  const buildNoScoreMessage = (isScoreDisabled) => {
@@ -16803,41 +17037,6 @@ const printSummary = (input) => Effect.gen(function* () {
16803
17037
  if (diagnosticsDirectory !== null && input.verbose) yield* Console.log(highlighter.gray(` Full diagnostics written to ${diagnosticsDirectory}`));
16804
17038
  });
16805
17039
  //#endregion
16806
- //#region src/cli/utils/cli-logger.ts
16807
- /**
16808
- * Thin synchronous façade over Effect's `Console` module. Used by
16809
- * the imperative CLI helper files (`select-projects`, `run-explain`,
16810
- * `install-react-doctor`, the legacy paths in `cli/commands/inspect.ts`)
16811
- * that aren't yet Effect-typed. Every call drains into a single
16812
- * `Console.*` Effect via `Effect.runSync`, so the underlying logging
16813
- * pipeline is identical to the canonical `yield* Console.log(...)`
16814
- * call sites in the renderers. Convert callers to `Effect.gen` to
16815
- * drop the bridge.
16816
- */
16817
- const cliLogger = {
16818
- log: (message) => {
16819
- Effect.runSync(Console.log(message));
16820
- },
16821
- warn: (message) => {
16822
- Effect.runSync(Console.warn(highlighter.warn(message)));
16823
- },
16824
- error: (message) => {
16825
- Effect.runSync(Console.error(highlighter.error(message)));
16826
- },
16827
- info: (message) => {
16828
- Effect.runSync(Console.info(highlighter.info(message)));
16829
- },
16830
- dim: (message) => {
16831
- Effect.runSync(Console.log(highlighter.gray(message)));
16832
- },
16833
- success: (message) => {
16834
- Effect.runSync(Console.log(highlighter.success(message)));
16835
- },
16836
- break: () => {
16837
- Effect.runSync(Console.log(""));
16838
- }
16839
- };
16840
- //#endregion
16841
17040
  //#region src/cli/utils/should-auto-select-current-choice.ts
16842
17041
  const shouldAutoSelectCurrentChoice = (choiceStates, cursor) => {
16843
17042
  if (choiceStates.some((choiceState) => choiceState.selected)) return false;
@@ -16980,7 +17179,8 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
16980
17179
  ignoredTags: buildIgnoredTags(userConfig),
16981
17180
  outputSurface: inputOptions.outputSurface ?? "cli",
16982
17181
  suppressRendering: inputOptions.suppressRendering ?? false,
16983
- concurrency: inputOptions.concurrency
17182
+ concurrency: inputOptions.concurrency,
17183
+ baseline: inputOptions.baseline ?? null
16984
17184
  });
16985
17185
  const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
16986
17186
  parallel: options.concurrency !== void 0,
@@ -17034,6 +17234,75 @@ const inspect = async (directory, inputOptions = {}) => {
17034
17234
  if (options.silent) setSpinnerSilent(wasSpinnerSilent);
17035
17235
  }
17036
17236
  };
17237
+ /**
17238
+ * Runs a second, lint-only scan over the changed files as they existed at the
17239
+ * baseline ref (materialized into a temp tree with head's config) and diffs it
17240
+ * against the head diagnostics, returning only the findings the change
17241
+ * introduced plus the fixed / base counts. No score, dead-code, progress, or
17242
+ * telemetry — it's a pure comparison pass. The temp tree is always cleaned up.
17243
+ */
17244
+ const runBaselineComparison = async (params) => {
17245
+ const tempDirectory = mkdtempSync(path.join(tmpdir(), BASELINE_FILES_TEMP_DIR_PREFIX));
17246
+ const snapshot = await materializeBaselineFiles({
17247
+ directory: params.directory,
17248
+ ref: params.baselineRef,
17249
+ files: params.options.includePaths,
17250
+ tempDirectory
17251
+ }).catch((error) => {
17252
+ rmSync(tempDirectory, {
17253
+ recursive: true,
17254
+ force: true
17255
+ });
17256
+ throw error;
17257
+ });
17258
+ try {
17259
+ const baseLayers = buildRuntimeLayers({
17260
+ directory: snapshot.tempDirectory,
17261
+ hasConfigOverride: true,
17262
+ userConfig: params.userConfig,
17263
+ configSourceDirectory: null,
17264
+ shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
17265
+ shouldRunDeadCode: false,
17266
+ shouldComputeScore: false,
17267
+ shouldShowProgressSpinners: false,
17268
+ oxlintConcurrency: params.options.concurrency
17269
+ });
17270
+ const baseProgram = runInspect({
17271
+ directory: snapshot.tempDirectory,
17272
+ includePaths: params.options.includePaths,
17273
+ customRulesOnly: params.options.customRulesOnly,
17274
+ respectInlineDisables: params.options.respectInlineDisables,
17275
+ warnings: params.options.warnings,
17276
+ adoptExistingLintConfig: params.options.adoptExistingLintConfig,
17277
+ ignoredTags: params.options.ignoredTags,
17278
+ nodeBinaryPath: params.resolvedNodeBinaryPath ?? void 0,
17279
+ runDeadCode: false,
17280
+ isCi: params.options.isCi,
17281
+ doctorVersion: VERSION,
17282
+ runId: getRunId(),
17283
+ resolveLocalGithubViewerPermission: false,
17284
+ suppressScanSummary: true
17285
+ }, {});
17286
+ const baseOutput = await Effect.runPromise(restoreLegacyThrow(baseProgram.pipe(Effect.provide(baseLayers), Effect.provideService(Console.Console, silentConsole))));
17287
+ if (baseOutput.didLintFail) return null;
17288
+ const delta = computeDiagnosticDelta({
17289
+ headDiagnostics: params.headDiagnostics,
17290
+ baseDiagnostics: baseOutput.diagnostics,
17291
+ readHeadLine: createSourceLineReader(params.directory),
17292
+ readBaseLine: createSourceLineReader(snapshot.tempDirectory)
17293
+ });
17294
+ return {
17295
+ displayDiagnostics: delta.newDiagnostics,
17296
+ baselineDelta: {
17297
+ baseRef: params.baselineRef,
17298
+ fixedCount: delta.fixedCount,
17299
+ baseTotalCount: baseOutput.diagnostics.length
17300
+ }
17301
+ };
17302
+ } finally {
17303
+ snapshot.cleanup();
17304
+ }
17305
+ };
17037
17306
  const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOverride, configSourceDirectory, startTime, rootSentrySpan) => {
17038
17307
  const isDiffMode = options.includePaths.length > 0;
17039
17308
  const resolvedNodeBinaryPath = await resolveOxlintNode(options.lint, options.scoreOnly || options.silent);
@@ -17084,7 +17353,23 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17084
17353
  const lintFailureReason = lintBindingMissing ? `oxlint native binding not found for Node ${process.version}; expected one matching ${OXLINT_NODE_REQUIREMENT}` : output.lintFailureReason;
17085
17354
  if (!options.scoreOnly && !lintBindingMissing && output.didLintFail && lintFailureReason !== null) if (output.lintFailureReasonKind === "native-binding-missing") runConsole(Console.log(highlighter.gray(` Upgrade to Node ${OXLINT_NODE_REQUIREMENT} or run: npx -p oxlint@latest react-doctor@latest`)));
17086
17355
  else runConsole(Console.error(highlighter.error(lintFailureReason)));
17087
- const inspectDiagnostics = output.diagnostics;
17356
+ let inspectDiagnostics = output.diagnostics;
17357
+ let baselineDelta;
17358
+ if (options.baseline && isDiffMode && !didLintFail) {
17359
+ const comparison = await runBaselineComparison({
17360
+ directory,
17361
+ options,
17362
+ userConfig,
17363
+ headDiagnostics: output.diagnostics,
17364
+ resolvedNodeBinaryPath,
17365
+ baselineRef: options.baseline.ref
17366
+ });
17367
+ if (comparison) {
17368
+ inspectDiagnostics = comparison.displayDiagnostics;
17369
+ baselineDelta = comparison.baselineDelta;
17370
+ }
17371
+ }
17372
+ const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
17088
17373
  const score = didLintFail ? null : output.score;
17089
17374
  const elapsedMilliseconds = performance.now() - startTime;
17090
17375
  const forceOnboarding = isOnboardingForced();
@@ -17104,7 +17389,8 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17104
17389
  directory: output.resolvedDirectory,
17105
17390
  scannedFileCount: output.scannedFileCount,
17106
17391
  scannedFilePaths: output.scannedFilePaths,
17107
- scanElapsedMilliseconds: output.scanElapsedMilliseconds
17392
+ scanElapsedMilliseconds: output.scanElapsedMilliseconds,
17393
+ baselineDelta
17108
17394
  };
17109
17395
  const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
17110
17396
  if (shouldRecordOnboarding({
@@ -17113,9 +17399,11 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17113
17399
  verbose: options.verbose,
17114
17400
  isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
17115
17401
  })) markOnboardingComplete();
17402
+ const scanMode = baselineDelta ? "baseline" : isDiffMode ? "diff" : "full";
17116
17403
  recordScanMetrics({
17117
17404
  result,
17118
- mode: isDiffMode ? "diff" : "full",
17405
+ mode: scanMode,
17406
+ baselineDegraded,
17119
17407
  parallel: options.concurrency !== void 0,
17120
17408
  workerCount: options.concurrency,
17121
17409
  lint: options.lint,
@@ -17129,7 +17417,8 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17129
17417
  recordRunEvent(rootSentrySpan, {
17130
17418
  ...buildRunEventConfig(options, userConfig, userConfig !== null),
17131
17419
  result,
17132
- mode: isDiffMode ? "diff" : "full",
17420
+ mode: scanMode,
17421
+ gateExempt: baselineDegraded,
17133
17422
  didLintFail,
17134
17423
  lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
17135
17424
  lintPartialFailureCount: output.lintPartialFailures.length,
@@ -17138,7 +17427,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17138
17427
  return result;
17139
17428
  };
17140
17429
  const finalizeAndRender = (input) => Effect.gen(function* () {
17141
- const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
17430
+ const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds, baselineDelta } = input;
17142
17431
  const { skippedChecks, skippedCheckReasons } = buildSkippedChecks({
17143
17432
  didLintFail,
17144
17433
  lintFailureReason,
@@ -17157,7 +17446,8 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17157
17446
  elapsedMilliseconds,
17158
17447
  scannedFileCount,
17159
17448
  scannedFilePaths,
17160
- scanElapsedMilliseconds
17449
+ scanElapsedMilliseconds,
17450
+ ...baselineDelta ? { baselineDelta } : {}
17161
17451
  });
17162
17452
  if (options.suppressRendering) return buildResult();
17163
17453
  if (options.scoreOnly) {
@@ -17477,7 +17767,7 @@ const VITE_PLUS_HOOKS_PATH = ".vite-hooks";
17477
17767
  const LEFTHOOK_CONFIG_FILES = ["lefthook.yml", "lefthook.yaml"];
17478
17768
  const PRE_COMMIT_CONFIG_FILE = ".pre-commit-config.yaml";
17479
17769
  const OVERCOMMIT_CONFIG_FILE = ".overcommit.yml";
17480
- const REACT_DOCTOR_COMMAND = "react-doctor --staged --fail-on warning";
17770
+ const REACT_DOCTOR_COMMAND = "react-doctor --staged --blocking warning";
17481
17771
  const NON_BLOCKING_REACT_DOCTOR_COMMAND = [
17482
17772
  "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\");",
17483
17773
  `if ${REACT_DOCTOR_COMMAND} > "$react_doctor_output" 2>&1; then`,
@@ -17746,22 +18036,22 @@ const buildAgentHookScript = () => [
17746
18036
  "",
17747
18037
  "run_react_doctor() {",
17748
18038
  " if [ -x ./node_modules/.bin/react-doctor ]; then",
17749
- " ./node_modules/.bin/react-doctor --verbose --diff --fail-on warning --no-score",
18039
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
17750
18040
  " return",
17751
18041
  " fi",
17752
18042
  "",
17753
18043
  " if command -v react-doctor >/dev/null 2>&1; then",
17754
- " react-doctor --verbose --diff --fail-on warning --no-score",
18044
+ " react-doctor --verbose --diff --blocking warning --no-score",
17755
18045
  " return",
17756
18046
  " fi",
17757
18047
  "",
17758
18048
  " if command -v pnpm >/dev/null 2>&1; then",
17759
- " pnpm dlx react-doctor@latest --verbose --diff --fail-on warning --no-score",
18049
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
17760
18050
  " return",
17761
18051
  " fi",
17762
18052
  "",
17763
18053
  " if command -v npx >/dev/null 2>&1; then",
17764
- " npx --yes react-doctor@latest --verbose --diff --fail-on warning --no-score",
18054
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
17765
18055
  " return",
17766
18056
  " fi",
17767
18057
  "",
@@ -17923,8 +18213,8 @@ const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\
17923
18213
  const SHEBANG = "#!/bin/sh";
17924
18214
  const SHEBANG_PREFIX = "#!";
17925
18215
  const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
17926
- const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --fail-on warning";
17927
- const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --fail-on warning";
18216
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18217
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
17928
18218
  const buildReactDoctorHookBlock = () => [
17929
18219
  REACT_DOCTOR_BLOCK_START,
17930
18220
  "react_doctor_scan_staged_files() {",
@@ -18005,11 +18295,11 @@ const installDirectGitHook = (options) => {
18005
18295
  //#region src/cli/utils/install-git-hook-config-managers.ts
18006
18296
  const appendStringCommand = (existingCommand) => {
18007
18297
  const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18008
- return existingCommandText.includes("react-doctor --staged --fail-on warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18298
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18009
18299
  };
18010
18300
  const appendArrayCommand = (existingCommands) => {
18011
18301
  const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18012
- return commands.some((command) => command.includes("react-doctor --staged --fail-on warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18302
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18013
18303
  };
18014
18304
  const installPackageJsonHook = (options, strategy) => {
18015
18305
  const packageJsonPath = getPackageJsonPath(options.projectRoot);
@@ -18306,7 +18596,7 @@ const installReactDoctorGitHook = (options) => {
18306
18596
  };
18307
18597
  //#endregion
18308
18598
  //#region src/cli/utils/should-skip-prompts.ts
18309
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.full) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18599
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18310
18600
  //#endregion
18311
18601
  //#region src/cli/utils/install-react-doctor.ts
18312
18602
  const SETUP_OPTION_GIT_HOOK = "git-hook";
@@ -19207,20 +19497,6 @@ export default ${serializeTsObjectLiteral(config)} satisfies ReactDoctorConfig;
19207
19497
  return targetPath;
19208
19498
  };
19209
19499
  //#endregion
19210
- //#region src/cli/utils/annotation-encoding.ts
19211
- const encodeAnnotationProperty = (value) => value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A").replaceAll(":", "%3A").replaceAll(",", "%2C");
19212
- const encodeAnnotationMessage = (value) => value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
19213
- //#endregion
19214
- //#region src/cli/utils/print-annotations.ts
19215
- const printAnnotations = (diagnostics, routeToStderr) => {
19216
- const writeLine = routeToStderr ? (line) => process.stderr.write(`${line}\n`) : (line) => process.stdout.write(`${line}\n`);
19217
- for (const diagnostic of diagnostics) {
19218
- const level = diagnostic.severity === "error" ? "error" : "warning";
19219
- const title = `${diagnostic.plugin}/${diagnostic.rule}`;
19220
- writeLine(`::${level} ${`file=${encodeAnnotationProperty(diagnostic.filePath)}`}${diagnostic.line > 0 ? `,line=${diagnostic.line}` : ""}${`,title=${encodeAnnotationProperty(title)}`}::${encodeAnnotationMessage(diagnostic.message)}`);
19221
- }
19222
- };
19223
- //#endregion
19224
19500
  //#region src/cli/utils/print-branded-header.ts
19225
19501
  /**
19226
19502
  * Single branded line every command prints first when not in JSON
@@ -19486,28 +19762,26 @@ const resolveParallelFlag = (parallel) => parallel === false ? 1 : void 0;
19486
19762
  /**
19487
19763
  * Translates CLI flags into the `InspectOptions` contract `inspect()`
19488
19764
  * accepts. Flag-specific computed fields (`scoreOnly`, `noScore`,
19489
- * `silent`, `outputSurface`, `isCi`) live here — there's no
19490
- * `userConfig` knob for them, only flag derivation. The remaining
19491
- * boolean knobs (`lint`, `deadCode`, `verbose`, `respectInlineDisables`)
19492
- * pass through unchanged: `inspect()` owns the userConfig-fallback
19493
- * layer so the merge logic isn't duplicated. The shell still hands
19494
- * `userConfig` in via `configOverride` and `noScore` so this resolver
19495
- * can apply the one flag-and-config rule that flags own
19765
+ * `silent`, `isCi`) live here — there's no `userConfig` knob for them,
19766
+ * only flag derivation. The plain boolean knobs (`lint`, `deadCode`,
19767
+ * `verbose`) pass through unchanged: `inspect()` owns the
19768
+ * userConfig-fallback layer so the merge logic isn't duplicated. The
19769
+ * shell still hands `userConfig` in via `configOverride` and `noScore`
19770
+ * so this resolver can apply the one flag-and-config rule that flags own
19496
19771
  * (`--score false` wins, otherwise inherit `userConfig.noScore`).
19497
19772
  */
19498
19773
  const resolveCliInspectOptions = (flags, userConfig) => {
19499
- const wantsWarningGate = (flags.failOn ?? userConfig?.failOn) === "warning";
19774
+ const wantsWarningGate = pickBlockingLevel(flags, userConfig) === "warning";
19500
19775
  return {
19501
19776
  lint: flags.lint,
19502
19777
  deadCode: flags.deadCode,
19503
19778
  verbose: flags.verbose,
19504
- respectInlineDisables: flags.respectInlineDisables,
19505
- warnings: flags.warnings ?? (wantsWarningGate ? true : void 0),
19779
+ respectInlineDisables: flags.respectInlineDisables === false ? false : void 0,
19780
+ warnings: wantsWarningGate ? true : flags.warnings,
19506
19781
  scoreOnly: flags.score === true,
19507
19782
  noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
19508
19783
  isCi: isCiEnvironment(),
19509
19784
  silent: Boolean(flags.json),
19510
- outputSurface: flags.prComment ? "prComment" : "cli",
19511
19785
  concurrency: resolveParallelFlag(flags.parallel)
19512
19786
  };
19513
19787
  };
@@ -19560,25 +19834,7 @@ const coerceDiffValue = (value) => {
19560
19834
  };
19561
19835
  //#endregion
19562
19836
  //#region src/cli/utils/resolve-effective-diff.ts
19563
- const resolveEffectiveDiff = (flags, userConfig) => {
19564
- if (flags.full) return false;
19565
- return coerceDiffValue(flags.diff ?? userConfig?.diff);
19566
- };
19567
- //#endregion
19568
- //#region src/cli/utils/resolve-fail-on-level.ts
19569
- const VALID_FAIL_ON_LEVELS = new Set([
19570
- "error",
19571
- "warning",
19572
- "none"
19573
- ]);
19574
- const DEFAULT_FAIL_ON_LEVEL = "none";
19575
- const isValidFailOnLevel = (level) => VALID_FAIL_ON_LEVELS.has(level);
19576
- const resolveFailOnLevel = (flags, userConfig) => {
19577
- const sourceValue = flags.failOn ?? userConfig?.failOn ?? DEFAULT_FAIL_ON_LEVEL;
19578
- if (isValidFailOnLevel(sourceValue)) return sourceValue;
19579
- cliLogger.warn(`Invalid failOn level "${sourceValue}". Expected one of: error, warning, none. Falling back to "${DEFAULT_FAIL_ON_LEVEL}".`);
19580
- return DEFAULT_FAIL_ON_LEVEL;
19581
- };
19837
+ const resolveEffectiveDiff = (flags, userConfig) => coerceDiffValue(flags.diff ?? userConfig?.diff);
19582
19838
  //#endregion
19583
19839
  //#region src/cli/utils/resolve-project-diff-include-paths.ts
19584
19840
  const resolveProjectDiffIncludePaths = (rootDirectory, projectDirectory, diffInfo) => {
@@ -19682,8 +19938,11 @@ const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
19682
19938
  }
19683
19939
  return promptProjectSelection(packages, rootDirectory);
19684
19940
  };
19941
+ const ALL_PROJECTS_SENTINEL = "*";
19685
19942
  const resolveProjectFlag = (projectFlag, workspacePackages) => {
19686
- const requestedNames = projectFlag.split(",").map((name) => name.trim());
19943
+ const requestedNames = projectFlag.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
19944
+ 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.`);
19945
+ if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.map((workspacePackage) => workspacePackage.directory);
19687
19946
  const resolvedDirectories = [];
19688
19947
  for (const requestedName of requestedNames) {
19689
19948
  const matched = workspacePackages.find((workspacePackage) => workspacePackage.name === requestedName || path$1.basename(workspacePackage.directory) === requestedName);
@@ -19756,6 +20015,16 @@ const runExplain = async (fileLineArgument, context) => {
19756
20015
  }
19757
20016
  };
19758
20017
  //#endregion
20018
+ //#region src/cli/utils/warn-deprecated-fail-on.ts
20019
+ const warnDeprecatedFailOn = (flags, userConfig) => {
20020
+ const usedFlag = flags.failOn !== void 0;
20021
+ const usedConfig = userConfig?.failOn !== void 0;
20022
+ if (!usedFlag && !usedConfig) return;
20023
+ const source = usedFlag ? "The `--fail-on` flag" : "The `failOn` config option";
20024
+ const replacement = usedFlag ? "`--blocking <level>`" : "`blocking`";
20025
+ cliLogger.warn(`${source} is deprecated; rename it to ${replacement}.`);
20026
+ };
20027
+ //#endregion
19759
20028
  //#region src/cli/utils/validate-mode-flags.ts
19760
20029
  const validateModeFlags = (flags) => {
19761
20030
  const coercedDiff = coerceDiffValue(flags.diff);
@@ -19763,36 +20032,44 @@ const validateModeFlags = (flags) => {
19763
20032
  if (exclusiveModes.length > 1) throw new CliInputError(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
19764
20033
  if (flags.score && flags.json) throw new CliInputError("Cannot combine --score and --json; pick one output mode.");
19765
20034
  if (flags.score && flags.telemetry === false) throw new CliInputError("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
19766
- if (flags.prComment && (flags.json || flags.score)) throw new CliInputError("--pr-comment cannot be combined with --json or --score.");
19767
- if (flags.annotations && flags.score) throw new CliInputError("--annotations cannot be combined with --score.");
19768
- if (flags.explain !== void 0 && flags.why !== void 0) throw new CliInputError("Use --explain or --why, not both — they're aliases of the same flag.");
19769
- if ((flags.explain ?? flags.why) !== void 0 && (flags.json || flags.score || flags.annotations || flags.staged)) throw new CliInputError("--explain cannot be combined with --json, --score, --annotations, or --staged.");
19770
20035
  };
19771
20036
  //#endregion
19772
20037
  //#region src/cli/commands/inspect.ts
19773
20038
  /**
19774
20039
  * Post-scan finalization shared by the staged-arm and project-loop
19775
- * paths of `inspectAction`: emit the JSON report (when in JSON mode),
19776
- * print PR annotations (when `--annotations`), and set
19777
- * `process.exitCode = 1` when the configured fail-on threshold is
19778
- * crossed. Both arms previously inlined the same four-step shape.
20040
+ * paths of `inspectAction`: emit the JSON report (when in JSON mode)
20041
+ * and set `process.exitCode = 1` when a diagnostic at or above the
20042
+ * `--blocking` threshold (default `"error"`) reaches the `ciFailure`
20043
+ * surface. `--blocking none` keeps the scan advisory (always exits 0).
19779
20044
  */
19780
20045
  const finalizeScans = (input) => {
19781
- if (input.isJsonMode) writeJsonReport(buildJsonReport({
19782
- version: VERSION,
19783
- directory: input.resolvedDirectory,
19784
- mode: input.mode,
19785
- diff: input.diff,
19786
- scans: input.completedScans,
19787
- totalElapsedMilliseconds: performance.now() - input.startTime
19788
- }));
19789
- if (input.flags.annotations) printAnnotations(input.diagnostics, input.isJsonMode);
19790
- const ciFailureDiagnostics = filterDiagnosticsForSurface(input.diagnostics, "ciFailure", input.userConfig);
19791
- if (!input.isScoreOnly && shouldFailForDiagnostics(ciFailureDiagnostics, resolveFailOnLevel(input.flags, input.userConfig))) process.exitCode = 1;
20046
+ const baselineDeltas = input.completedScans.flatMap((scan) => scan.result.baselineDelta ? [scan.result.baselineDelta] : []);
20047
+ const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
20048
+ const baselineDegraded = input.baselineIntended && !baselineComputed;
20049
+ const mode = baselineDegraded ? "diff" : input.mode;
20050
+ if (input.isJsonMode) {
20051
+ const baseline = baselineComputed && baselineDeltas.length > 0 ? {
20052
+ baseRef: baselineDeltas[0].baseRef,
20053
+ fixedCount: baselineDeltas.reduce((total, delta) => total + delta.fixedCount, 0),
20054
+ baseTotalCount: baselineDeltas.reduce((total, delta) => total + delta.baseTotalCount, 0)
20055
+ } : void 0;
20056
+ writeJsonReport(buildJsonReport({
20057
+ version: VERSION,
20058
+ directory: input.resolvedDirectory,
20059
+ mode,
20060
+ diff: input.diff,
20061
+ scans: input.completedScans,
20062
+ totalElapsedMilliseconds: performance.now() - input.startTime,
20063
+ baseline
20064
+ }));
20065
+ }
20066
+ if (input.isScoreOnly || baselineDegraded) return;
20067
+ if (shouldBlockCi(filterDiagnosticsForSurface(input.diagnostics, "ciFailure", input.userConfig), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
19792
20068
  };
19793
20069
  const buildChangedFilesDiffInfo = (changedFiles) => ({
19794
20070
  currentBranch: process.env.GITHUB_HEAD_REF?.trim() || null,
19795
20071
  baseBranch: process.env.GITHUB_BASE_REF?.trim() || "pull request target",
20072
+ baseSha: process.env.REACT_DOCTOR_BASE_SHA?.trim() || void 0,
19796
20073
  changedFiles,
19797
20074
  isCurrentChanges: false
19798
20075
  });
@@ -19835,11 +20112,12 @@ const inspectAction = async (directory, flags) => {
19835
20112
  const userConfig = scanTarget.userConfig;
19836
20113
  const resolvedDirectory = scanTarget.resolvedDirectory;
19837
20114
  setJsonReportDirectory(resolvedDirectory);
20115
+ warnDeprecatedFailOn(flags, userConfig);
19838
20116
  if (scanTarget.didRedirectViaRootDir && !isQuiet) {
19839
20117
  cliLogger.dim(`Redirected to ${highlighter.info(toRelativePath(resolvedDirectory, requestedDirectory))} via react-doctor config "rootDir".`);
19840
20118
  cliLogger.break();
19841
20119
  }
19842
- const explainArgument = flags.explain ?? flags.why;
20120
+ const explainArgument = flags.explain;
19843
20121
  if (explainArgument !== void 0) {
19844
20122
  await runExplain(explainArgument, {
19845
20123
  resolvedDirectory,
@@ -19856,7 +20134,6 @@ const inspectAction = async (directory, flags) => {
19856
20134
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
19857
20135
  const skipPrompts = shouldSkipPrompts({
19858
20136
  yes: flags.yes,
19859
- full: flags.full,
19860
20137
  json: flags.json
19861
20138
  });
19862
20139
  if (flags.staged) {
@@ -19911,6 +20188,7 @@ const inspectAction = async (directory, flags) => {
19911
20188
  }],
19912
20189
  mode: "staged",
19913
20190
  diff: null,
20191
+ baselineIntended: false,
19914
20192
  isJsonMode,
19915
20193
  isScoreOnly,
19916
20194
  flags,
@@ -19924,11 +20202,12 @@ const inspectAction = async (directory, flags) => {
19924
20202
  return;
19925
20203
  }
19926
20204
  const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts);
19927
- const changedFilesDiffInfo = flags.changedFilesFrom && !flags.full ? buildChangedFilesDiffInfo(readChangedFilesFrom(path$1.resolve(flags.changedFilesFrom))) : null;
20205
+ const changedFilesDiffInfo = flags.changedFilesFrom ? buildChangedFilesDiffInfo(readChangedFilesFrom(path$1.resolve(flags.changedFilesFrom))) : null;
19928
20206
  const effectiveDiff = resolveEffectiveDiff(flags, userConfig);
19929
20207
  const diffInfo = changedFilesDiffInfo ?? (changedFilesDiffInfo === null && (effectiveDiff !== void 0 && effectiveDiff !== false || !skipPrompts && !isQuiet) ? await getDiffInfo(resolvedDirectory, typeof effectiveDiff === "string" ? effectiveDiff : void 0) : null);
19930
20208
  const isDiffMode = changedFilesDiffInfo !== null || await resolveDiffMode(diffInfo, effectiveDiff, skipPrompts, isQuiet);
19931
- setJsonReportMode(isDiffMode ? "diff" : "full");
20209
+ const baselineRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
20210
+ setJsonReportMode(baselineRef ? "baseline" : isDiffMode ? "diff" : "full");
19932
20211
  if (isDiffMode && diffInfo && !isQuiet) {
19933
20212
  if (diffInfo.isCurrentChanges) cliLogger.log("Scanning uncommitted changes");
19934
20213
  else {
@@ -19958,7 +20237,8 @@ const inspectAction = async (directory, flags) => {
19958
20237
  ...scanOptions,
19959
20238
  includePaths,
19960
20239
  configOverride: userConfig,
19961
- suppressRendering: isMultiProject
20240
+ suppressRendering: isMultiProject,
20241
+ baseline: baselineRef ? { ref: baselineRef } : void 0
19962
20242
  });
19963
20243
  allDiagnostics.push(...scanResult.diagnostics);
19964
20244
  completedScans.push({
@@ -19980,8 +20260,9 @@ const inspectAction = async (directory, flags) => {
19980
20260
  finalizeScans({
19981
20261
  diagnostics: allDiagnostics,
19982
20262
  completedScans,
19983
- mode: isDiffMode ? "diff" : "full",
20263
+ mode: baselineRef ? "baseline" : isDiffMode ? "diff" : "full",
19984
20264
  diff: isDiffMode ? diffInfo : null,
20265
+ baselineIntended: isDiffMode && diffInfo !== null && !diffInfo.isCurrentChanges,
19985
20266
  isJsonMode,
19986
20267
  isScoreOnly,
19987
20268
  flags,
@@ -20019,7 +20300,7 @@ const inspectAction = async (directory, flags) => {
20019
20300
  const isUserError = isExpectedUserError(error);
20020
20301
  const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
20021
20302
  if (isJsonMode) {
20022
- writeJsonErrorReport(error);
20303
+ writeJsonErrorReport(error, sentryEventId);
20023
20304
  process.exitCode = 1;
20024
20305
  return;
20025
20306
  }
@@ -20608,6 +20889,20 @@ const versionAction = () => {
20608
20889
  process.stdout.write(`${buildVersionString()}\n`);
20609
20890
  };
20610
20891
  //#endregion
20892
+ //#region src/cli/commands/why.ts
20893
+ /**
20894
+ * `why <file:line>` — explains why a rule fired (or why a suppression didn't
20895
+ * apply) at a specific location. A thin wrapper over the inspect flow's
20896
+ * single-location explain path so it reuses the same scan, config resolution,
20897
+ * and clean error handling. (Replaces the former `--explain` / `--why` flags.)
20898
+ */
20899
+ const whyAction = async (location, options) => {
20900
+ await inspectAction(options.cwd ?? process.cwd(), {
20901
+ explain: location,
20902
+ project: options.project
20903
+ });
20904
+ };
20905
+ //#endregion
20611
20906
  //#region src/cli/utils/apply-color-preference.ts
20612
20907
  /**
20613
20908
  * Resolve an explicit color preference from `--color` / `--no-color` or the
@@ -20709,13 +21004,32 @@ const normalizeHelpInvocation = (argv, knownCommands) => {
20709
21004
  return [...nodeArguments, "--help"];
20710
21005
  };
20711
21006
  //#endregion
21007
+ //#region src/cli/utils/removed-cli-flags.ts
21008
+ const REMOVED_FLAGS = new Map([
21009
+ ["--full", "use `--diff false` to force a full scan"],
21010
+ ["--explain", "use the `why <file>:<line>` command"],
21011
+ ["--why", "use the `why <file>:<line>` command"],
21012
+ ["--pr-comment", "the GitHub Action posts the PR comment for you; remove this flag"]
21013
+ ]);
21014
+ /**
21015
+ * Throws a clean {@link CliInputError} when a removed flag appears in argv,
21016
+ * pointing to its replacement. Run before flag stripping so a removed flag is a
21017
+ * loud, actionable error rather than a silent no-op.
21018
+ */
21019
+ const assertNoRemovedFlags = (argv) => {
21020
+ for (const argument of argv.slice(2)) {
21021
+ if (argument === "--") return;
21022
+ const optionName = argument.includes("=") ? argument.slice(0, argument.indexOf("=")) : argument;
21023
+ const guidance = REMOVED_FLAGS.get(optionName);
21024
+ if (guidance !== void 0) throw new CliInputError(`\`${optionName}\` was removed — ${guidance}.`);
21025
+ }
21026
+ };
21027
+ //#endregion
20712
21028
  //#region src/cli/utils/strip-unknown-cli-flags.ts
20713
21029
  const ROOT_FLAG_SPEC = {
20714
21030
  longOptionsWithoutValues: new Set([
20715
- "--annotations",
20716
21031
  "--color",
20717
21032
  "--dead-code",
20718
- "--full",
20719
21033
  "--help",
20720
21034
  "--json",
20721
21035
  "--json-compact",
@@ -20728,8 +21042,6 @@ const ROOT_FLAG_SPEC = {
20728
21042
  "--no-score",
20729
21043
  "--no-telemetry",
20730
21044
  "--no-warnings",
20731
- "--pr-comment",
20732
- "--respect-inline-disables",
20733
21045
  "--score",
20734
21046
  "--staged",
20735
21047
  "--verbose",
@@ -20739,10 +21051,9 @@ const ROOT_FLAG_SPEC = {
20739
21051
  ]),
20740
21052
  longOptionsWithRequiredValues: new Set([
20741
21053
  "--changed-files-from",
20742
- "--explain",
21054
+ "--blocking",
20743
21055
  "--fail-on",
20744
- "--project",
20745
- "--why"
21056
+ "--project"
20746
21057
  ]),
20747
21058
  longOptionsWithOptionalValues: new Set(["--diff"]),
20748
21059
  shortOptionsWithoutValues: new Set([
@@ -20798,6 +21109,17 @@ const COMMAND_FLAG_SPECS = new Map([
20798
21109
  longOptionsWithOptionalValues: /* @__PURE__ */ new Set(),
20799
21110
  shortOptionsWithoutValues: new Set(["-h"]),
20800
21111
  shortOptionsWithRequiredValues: new Set(["-c"])
21112
+ }],
21113
+ ["why", {
21114
+ longOptionsWithoutValues: new Set([
21115
+ "--color",
21116
+ "--help",
21117
+ "--no-color"
21118
+ ]),
21119
+ longOptionsWithRequiredValues: new Set(["--cwd", "--project"]),
21120
+ longOptionsWithOptionalValues: /* @__PURE__ */ new Set(),
21121
+ shortOptionsWithoutValues: new Set(["-h"]),
21122
+ shortOptionsWithRequiredValues: new Set(["-c"])
20801
21123
  }]
20802
21124
  ]);
20803
21125
  const isFlagLike = (argument) => argument.startsWith("-") && argument !== "-";
@@ -20884,9 +21206,9 @@ ${formatExampleLines([
20884
21206
  ["react-doctor ./apps/web", "scan a specific directory"],
20885
21207
  ["react-doctor --diff main", "scan only files changed vs. main"],
20886
21208
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
20887
- ["react-doctor --fail-on warning", "exit non-zero on warnings (CI gate)"],
21209
+ ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
20888
21210
  ["react-doctor --json > report.json", "write a machine-readable report"],
20889
- ["react-doctor --explain src/App.tsx:42", "explain why a rule fired there"],
21211
+ ["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
20890
21212
  ["react-doctor install", "set up the agent skill and git hook"]
20891
21213
  ])}
20892
21214
 
@@ -20912,8 +21234,9 @@ ${formatExampleLines([
20912
21234
  ${highlighter.dim("Learn more:")}
20913
21235
  ${highlighter.info(CANONICAL_GITHUB_URL)}
20914
21236
  `;
20915
- const program = new Command().name("react-doctor").description("Diagnose React codebase health").version(VERSION, "-v, --version", "display the version number").argument("[directory]", "project directory to scan", ".").option("--lint", "enable linting").option("--no-lint", "skip linting").option("--dead-code", "enable dead-code analysis (default)").option("--no-dead-code", "skip dead-code analysis (unused files / exports / dependencies, circular imports)").option("--verbose", "show every rule and per-file details (default shows top 3 rules)").option("--score", "output only the score").option("--json", "output a single structured JSON report (suppresses other output)").option("--json-compact", "with --json, emit compact JSON (no indentation)").option("-y, --yes", "skip prompts, scan all workspace projects").option("--full", "force a full scan (overrides any `diff` value in config or `--diff`)").option("--no-parallel", "lint serially with one worker (default: parallel across CPU cores; set the worker count with REACT_DOCTOR_PARALLEL)").option("--project <name>", "select workspace project (comma-separated for multiple)").option("--diff [base]", "scan only files changed vs base branch (pass `false` to disable; overridden by --full)").option("--changed-files-from <file>", "internal: scan source files listed in a newline-delimited changed-files file").option("--no-score", "skip the score API, the share URL, and crash reporting").option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--fail-on <level>", "exit with error code on diagnostics: error, warning, none (default: none)").option("--annotations", "output diagnostics as GitHub Actions annotations").option("--pr-comment", "tune CLI output for sticky PR comments (drops weak-signal rule families like `design` from the printed list and the fail-on gate; configure via config.surfaces)").option("--explain <file:line>", "diagnose why a rule fired or why a suppression didn't apply at a specific location").option("--why <file:line>", "alias for --explain").option("--respect-inline-disables", "respect inline `// eslint-disable*` / `// oxlint-disable*` comments (default)").option("--no-respect-inline-disables", "audit mode: neutralize inline lint suppressions before scanning").option("--warnings", "show warning-severity diagnostics (default)").option("--no-warnings", "hide warning-severity diagnostics (errors only)").option("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
21237
+ 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$1("--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").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$1("--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("--color", "force colored output").option("--no-color", "disable colored output (also honors NO_COLOR)").addHelpText("after", renderRootHelpEpilog);
20916
21238
  program.action(inspectAction);
21239
+ 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));
20917
21240
  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);
20918
21241
  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);
20919
21242
  const rules = program.command("rules").description("List, explain, and configure which React Doctor rules run");
@@ -20937,11 +21260,11 @@ if (process.argv.includes("-V") && !strippedArgv.includes("-V")) {
20937
21260
  }
20938
21261
  applyColorPreference(strippedArgv);
20939
21262
  const argv = normalizeHelpInvocation(strippedArgv, knownCommands);
20940
- program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
21263
+ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => program.parseAsync(argv)).then(() => flushSentry()).catch(async (error) => {
20941
21264
  const isUserError = isExpectedUserError(error);
20942
21265
  const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
20943
21266
  if (isJsonModeActive()) {
20944
- writeJsonErrorReport(error);
21267
+ writeJsonErrorReport(error, sentryEventId);
20945
21268
  process.exit(1);
20946
21269
  }
20947
21270
  if (isUserError) {
@@ -20954,4 +21277,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
20954
21277
  export {};
20955
21278
 
20956
21279
  //# sourceMappingURL=cli.js.map
20957
- //# debugId=5f1571ca-529b-5db6-ba79-f7bc1c4d6d2d
21280
+ //# debugId=3c457dc9-865a-5459-b923-a0fb762b158f