react-doctor 0.2.15-dev.3fae9dd → 0.2.15-dev.520b0a9

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/README.md CHANGED
@@ -96,14 +96,14 @@ Prefer JSON? Use `doctor.config.json`:
96
96
 
97
97
  ## Telemetry
98
98
 
99
- The CLI reports crashes and basic run traces to [Sentry](https://sentry.io) to help us fix bugs. Events include the version, platform, Node version, how the CLI was invoked (which command, package manager, and whether it ran locally vs. CI vs. a coding agent), the detected project shape (framework, React version, TypeScript, project size — never the contents of your files), and de-minified stack traces.
99
+ The CLI reports crashes, basic run traces, and anonymous usage counters to [Sentry](https://sentry.io) to help us fix bugs and prioritize what to build. Events and metrics include the version, platform, Node version, how the CLI was invoked (which command, package manager, and whether it ran locally vs. CI vs. a coding agent), the detected project shape (framework, React version, TypeScript, project size — never the contents of your files), which rules fired (rule names only, e.g. `react-doctor/no-array-index-as-key`, with counts — never your code or specific findings), and de-minified stack traces.
100
100
 
101
101
  Telemetry is **anonymized** before it leaves your machine: no IP address is collected, your hostname and machine name are stripped, your OS username is removed from every path (your home directory is replaced with `~`), captured local variables are dropped, and known secrets/API keys/emails are masked. No source code or diagnostic findings are sent.
102
102
 
103
103
  Opt out at any time:
104
104
 
105
- - `npx react-doctor@latest --no-telemetry` disables Sentry entirely (crash reporting and tracing) for that run, alongside the hosted score API.
106
- - `SENTRY_TRACES_SAMPLE_RATE=0` keeps crash reporting but turns off performance tracing.
105
+ - `npx react-doctor@latest --no-telemetry` disables Sentry entirely (crash reporting, tracing, and usage counters) for that run, alongside the hosted score API.
106
+ - `SENTRY_TRACES_SAMPLE_RATE=0` keeps crash reporting and usage counters but turns off performance tracing.
107
107
 
108
108
  ## Contributing
109
109
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d012dbb2-27e9-5092-9eab-c7fa4573f0b2")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c8bf2d99-8f0b-55f1-a894-63e600bf000b")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as Path from "node:path";
@@ -8975,6 +8975,11 @@ const trimOrNull = (value) => {
8975
8975
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
8976
8976
  */
8977
8977
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
8978
+ /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
8979
+ const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
8980
+ /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
8981
+ const DIFF_RANGE_OPERATOR = "..";
8982
+ const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
8978
8983
  const isSafeGitRevision = (candidate) => {
8979
8984
  if (candidate.length === 0) return false;
8980
8985
  if (candidate.startsWith("-")) return false;
@@ -8982,6 +8987,31 @@ const isSafeGitRevision = (candidate) => {
8982
8987
  if (candidate.includes("..") || candidate.includes("@{")) return false;
8983
8988
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
8984
8989
  };
8990
+ /**
8991
+ * Splits a git revision range into its endpoints: three-dot `A...B`
8992
+ * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
8993
+ * when `value` carries no range operator so the caller falls back to
8994
+ * single-base resolution.
8995
+ *
8996
+ * Only the first operator is split on; any leftover `..` stays inside an
8997
+ * endpoint so `isSafeGitRevision` rejects malformed input like
8998
+ * `A..B..C` instead of silently guessing which pair the user meant.
8999
+ */
9000
+ const parseGitDiffRange = (value) => {
9001
+ const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
9002
+ if (symmetricIndex !== -1) return {
9003
+ base: value.slice(0, symmetricIndex),
9004
+ head: value.slice(symmetricIndex + 3),
9005
+ symmetric: true
9006
+ };
9007
+ const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
9008
+ if (rangeIndex !== -1) return {
9009
+ base: value.slice(0, rangeIndex),
9010
+ head: value.slice(rangeIndex + 2),
9011
+ symmetric: false
9012
+ };
9013
+ return null;
9014
+ };
8985
9015
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
8986
9016
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
8987
9017
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -9133,6 +9163,49 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9133
9163
  if (result.status !== 0) return null;
9134
9164
  return parseGithubViewerPermission(result.stdout);
9135
9165
  }).pipe(Effect.catch(() => Effect.succeed(null)));
9166
+ /**
9167
+ * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
9168
+ * selection. Each endpoint is validated with `isSafeGitRevision`
9169
+ * BEFORE it reaches `git` (so the range syntax can't smuggle a
9170
+ * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
9171
+ * verified to exist, then the diff runs between the two commits with
9172
+ * the same `--diff-filter=ACMR` shape the single-base path uses.
9173
+ */
9174
+ const resolveDiffRange = (input) => Effect.gen(function* () {
9175
+ if (input.range.base.length === 0 && input.range.head.length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" must name at least one commit (e.g. "main..feature").` }) }));
9176
+ const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
9177
+ const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
9178
+ for (const endpoint of [baseRef, headRef]) if (!isSafeGitRevision(endpoint)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" has an invalid endpoint "${endpoint}" (${GIT_REF_NAME_RULE}).` }) }));
9179
+ for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
9180
+ let diffBaseRef = baseRef;
9181
+ if (input.range.symmetric) {
9182
+ const mergeBase = yield* runGit(input.directory, [
9183
+ "merge-base",
9184
+ baseRef,
9185
+ headRef
9186
+ ]);
9187
+ if (mergeBase.status !== 0) return null;
9188
+ const mergeBaseRef = trimOrNull(mergeBase.stdout);
9189
+ if (mergeBaseRef === null) return null;
9190
+ diffBaseRef = mergeBaseRef;
9191
+ }
9192
+ const diff = yield* runGit(input.directory, [
9193
+ "diff",
9194
+ "-z",
9195
+ "--name-only",
9196
+ "--diff-filter=ACMR",
9197
+ "--relative",
9198
+ diffBaseRef,
9199
+ headRef
9200
+ ]);
9201
+ if (diff.status !== 0) return null;
9202
+ return {
9203
+ currentBranch: yield* currentBranch(input.directory),
9204
+ baseBranch: baseRef,
9205
+ changedFiles: splitNullSeparated(diff.stdout),
9206
+ isCurrentChanges: false
9207
+ };
9208
+ });
9136
9209
  return Git.of({
9137
9210
  currentBranch,
9138
9211
  defaultBranch,
@@ -9142,7 +9215,15 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9142
9215
  branchExists,
9143
9216
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
9144
9217
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
9145
- if (explicitBaseBranch !== void 0 && !isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (must match [A-Za-z0-9_./-] without leading '-', '..', or '@{').` }) }));
9218
+ if (explicitBaseBranch !== void 0) {
9219
+ const range = parseGitDiffRange(explicitBaseBranch);
9220
+ if (range !== null) return yield* resolveDiffRange({
9221
+ directory,
9222
+ range,
9223
+ raw: explicitBaseBranch
9224
+ });
9225
+ if (!isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (${GIT_REF_NAME_RULE}).` }) }));
9226
+ }
9146
9227
  const resolvedCurrentBranch = yield* currentBranch(directory);
9147
9228
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
9148
9229
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -11524,12 +11605,13 @@ const buildSkippedChecks = (input) => {
11524
11605
  * Git service runs through Effect's `ChildProcess` (true subprocess
11525
11606
  * spawn, not `spawnSync`).
11526
11607
  *
11527
- * Tagged-reason errors are dispatched via `Effect.catchReasons`
11528
- * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
11529
- * union without manual `instanceof` checks). The recovered branches
11530
- * raise plain `Error`s so existing thrown-class consumers continue
11531
- * to work — anything else (real `GitInvocationFailed`, etc.)
11532
- * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
11608
+ * Failures propagate as the tagged `ReactDoctorError` (rejected by
11609
+ * `Effect.runPromise`) rather than being flattened into a plain
11610
+ * `Error`. The message is unchanged — `ReactDoctorError.message`
11611
+ * defers to `reason.message` — so message-matching callers keep
11612
+ * working, while the CLI can now dispatch on `error.reason._tag` to
11613
+ * render diff-base mistakes (`GitBaseBranchInvalid` /
11614
+ * `GitBaseBranchMissing`) as clean user errors instead of crashes.
11533
11615
  */
11534
11616
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
11535
11617
  const selection = yield* (yield* Git).diffSelection({
@@ -11543,10 +11625,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
11543
11625
  changedFiles: [...selection.changedFiles],
11544
11626
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
11545
11627
  };
11546
- }).pipe(Effect.provide(Git.layerNode), Effect.catchReasons("ReactDoctorError", {
11547
- GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
11548
- GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
11549
- })));
11628
+ }).pipe(Effect.provide(Git.layerNode)));
11550
11629
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
11551
11630
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
11552
11631
  let p = process || {}, argv = p.argv || [], env = p.env || {};
@@ -11760,6 +11839,33 @@ const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
11760
11839
  const INTERNAL_ERROR_JSON_FALLBACK = "{\"schemaVersion\":1,\"ok\":false,\"error\":{\"message\":\"Internal error\",\"name\":\"Error\",\"chain\":[]}}\n";
11761
11840
  const SENTRY_FLUSH_TIMEOUT_MS = 2e3;
11762
11841
  const NANOSECONDS_PER_SECOND = 1000000000n;
11842
+ const METRIC = {
11843
+ cliInvoked: "cli.invoked",
11844
+ cliError: "cli.error",
11845
+ projectDetected: "project.detected",
11846
+ scanCompleted: "scan.completed",
11847
+ scanDuration: "scan.duration",
11848
+ scanPhaseDuration: "scan.phase_duration",
11849
+ scanFiles: "scan.files",
11850
+ scanScore: "scan.score",
11851
+ scanClean: "scan.clean",
11852
+ scanCheckSkipped: "scan.check_skipped",
11853
+ ruleFired: "rule.fired",
11854
+ lintFailed: "lint.failed",
11855
+ deadCodeFailed: "deadcode.failed",
11856
+ scoreUnavailable: "score.unavailable",
11857
+ oxlintWorkers: "oxlint.workers",
11858
+ agentHandoff: "agent.handoff",
11859
+ agentInstallHintShown: "agent.install_hint_shown",
11860
+ installCompleted: "install.completed",
11861
+ installAgent: "install.agent",
11862
+ installGitHook: "install.git_hook",
11863
+ installWorkflow: "install.workflow",
11864
+ installAgentHooks: "install.agent_hooks",
11865
+ installDependency: "install.dependency",
11866
+ rulesChanged: "rules.changed",
11867
+ rulesQueried: "rules.queried"
11868
+ };
11763
11869
  //#endregion
11764
11870
  //#region src/cli/utils/noop-console.ts
11765
11871
  /**
@@ -11801,7 +11907,7 @@ const makeNoopConsole = () => ({
11801
11907
  });
11802
11908
  //#endregion
11803
11909
  //#region src/cli/utils/version.ts
11804
- const VERSION = "0.2.15-dev.3fae9dd";
11910
+ const VERSION = "0.2.15-dev.520b0a9";
11805
11911
  //#endregion
11806
11912
  //#region src/cli/utils/json-mode.ts
11807
11913
  let context = null;
@@ -12025,13 +12131,20 @@ const buildSentryScope = (runContext = buildRunContext()) => {
12025
12131
  };
12026
12132
  };
12027
12133
  //#endregion
12028
- //#region src/cli/utils/scrub-sentry-event.ts
12134
+ //#region src/cli/utils/anonymize-text.ts
12135
+ /**
12136
+ * Free-text fields can carry both a home-directory path (the OS username) and a
12137
+ * secret/email echoed from user code, so run both scrubbers: strip the username
12138
+ * from paths, then mask any known credential/PII shape. Shared by the Sentry
12139
+ * event scrubber ({@link scrubSentryEvent}) and metric scrubber
12140
+ * ({@link scrubSentryMetric}).
12141
+ */
12029
12142
  const anonymizeText = (text) => redactSensitiveText(scrubSensitivePaths(text));
12030
12143
  /**
12031
12144
  * Recursively rewrites every string within an arbitrary value (object / array /
12032
12145
  * primitive) through {@link anonymizeText}, mutating in place. Used to sweep the
12033
- * unstructured corners of an event (contexts, extra, tags, breadcrumb data,
12034
- * span attributes) where a path or secret could hide.
12146
+ * unstructured corners of a Sentry payload (event contexts/extra/tags, breadcrumb
12147
+ * data, span attributes, metric attributes) where a path or secret could hide.
12035
12148
  */
12036
12149
  const anonymizeInPlace = (value) => {
12037
12150
  if (Array.isArray(value)) {
@@ -12049,6 +12162,8 @@ const anonymizeInPlace = (value) => {
12049
12162
  else anonymizeInPlace(inner);
12050
12163
  }
12051
12164
  };
12165
+ //#endregion
12166
+ //#region src/cli/utils/scrub-sentry-event.ts
12052
12167
  /**
12053
12168
  * Anonymizes a Sentry event (error or transaction) before it leaves the
12054
12169
  * machine. Strips identity the SDK attaches automatically — the IP-bearing
@@ -12096,6 +12211,27 @@ const scrubSentryEvent = (event) => {
12096
12211
  }
12097
12212
  };
12098
12213
  //#endregion
12214
+ //#region src/cli/utils/scrub-sentry-metric.ts
12215
+ /**
12216
+ * Anonymizes a Sentry metric before it leaves the machine, mirroring
12217
+ * {@link scrubSentryEvent}. Drops the `server.address` default attribute (the
12218
+ * hostname) and scrubs home-directory paths + known secrets/emails from every
12219
+ * remaining attribute value (metric names are our own constants, so they're
12220
+ * left intact to avoid splitting a series). Returns `null` on any failure so an
12221
+ * un-anonymized metric is never sent. Wired into `beforeSendMetric`.
12222
+ */
12223
+ const scrubSentryMetric = (metric) => {
12224
+ try {
12225
+ if (metric.attributes) {
12226
+ delete metric.attributes["server.address"];
12227
+ anonymizeInPlace(metric.attributes);
12228
+ }
12229
+ return metric;
12230
+ } catch {
12231
+ return null;
12232
+ }
12233
+ };
12234
+ //#endregion
12099
12235
  //#region src/instrument.ts
12100
12236
  let isInitialized = false;
12101
12237
  let resolvedTracesSampleRate = 0;
@@ -12117,13 +12253,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12117
12253
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12118
12254
  * standard `SENTRY_RELEASE` override.
12119
12255
  */
12120
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.3fae9dd`;
12256
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.15-dev.520b0a9`;
12121
12257
  /**
12122
12258
  * Deployment environment shown in Sentry's environment filter. Defaults to
12123
12259
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12124
12260
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12125
12261
  */
12126
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.3fae9dd") ? "development" : "production");
12262
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.15-dev.520b0a9") ? "development" : "production");
12127
12263
  /**
12128
12264
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12129
12265
  * (set to `0` to disable tracing) and falls back to
@@ -12191,7 +12327,8 @@ const initializeSentry = () => {
12191
12327
  contexts
12192
12328
  },
12193
12329
  beforeSend: (event) => scrubSentryEvent(event),
12194
- beforeSendTransaction: (event) => scrubSentryEvent(event)
12330
+ beforeSendTransaction: (event) => scrubSentryEvent(event),
12331
+ beforeSendMetric: (metric) => scrubSentryMetric(metric)
12195
12332
  });
12196
12333
  };
12197
12334
  //#endregion
@@ -15463,6 +15600,122 @@ const recordSentryProjectContext = (projectInfo, rootSpan) => {
15463
15600
  rootSpan?.setAttributes(toSpanAttributes(buildSentryProjectContext(projectInfo).tags));
15464
15601
  };
15465
15602
  //#endregion
15603
+ //#region src/cli/utils/record-metric.ts
15604
+ const cleanAttributes = (attributes) => {
15605
+ const cleaned = {};
15606
+ if (!attributes) return cleaned;
15607
+ for (const [key, value] of Object.entries(attributes)) if (value !== null && value !== void 0) cleaned[key] = value;
15608
+ return cleaned;
15609
+ };
15610
+ const withRunAttributes = (attributes) => ({
15611
+ ...toSpanAttributes(buildSentryScope().tags),
15612
+ ...cleanAttributes(attributes)
15613
+ });
15614
+ /**
15615
+ * Emits a Sentry counter. A guarded, swallow-on-throw no-op unless the CLI's
15616
+ * Sentry SDK is live, so it's inert under `--no-score`, tests, and the
15617
+ * programmatic `@react-doctor/api` library (none of which initialize Sentry).
15618
+ * Metrics flow independently of performance tracing, so counters are still
15619
+ * recorded when `SENTRY_TRACES_SAMPLE_RATE=0`.
15620
+ */
15621
+ const recordCount = (name, value = 1, attributes) => {
15622
+ if (!Sentry.isInitialized()) return;
15623
+ try {
15624
+ Sentry.metrics.count(name, value, { attributes: withRunAttributes(attributes) });
15625
+ } catch {}
15626
+ };
15627
+ /**
15628
+ * Emits a Sentry distribution (value ranges — durations, sizes, scores). Same
15629
+ * gating and run-attribute handling as {@link recordCount}.
15630
+ */
15631
+ const recordDistribution = (name, value, options = {}) => {
15632
+ if (!Sentry.isInitialized()) return;
15633
+ try {
15634
+ Sentry.metrics.distribution(name, value, {
15635
+ unit: options.unit,
15636
+ attributes: withRunAttributes(options.attributes)
15637
+ });
15638
+ } catch {}
15639
+ };
15640
+ //#endregion
15641
+ //#region src/cli/utils/record-scan-metrics.ts
15642
+ /**
15643
+ * Aggregates diagnostics into per-`(rule, severity)` firing counts, reusing the
15644
+ * canonical `getDiagnosticRuleIdentity` so the `<plugin>/<rule>` key and
15645
+ * category match every other rule-keyed surface. Pure and exported so the
15646
+ * bucketing is unit-testable without an active Sentry client (the emit helpers
15647
+ * no-op under tests). Grouping the emitted `rule.fired` counter by `category`
15648
+ * or `severity` in Sentry reproduces a coarser breakdown.
15649
+ */
15650
+ const summarizeRuleFirings = (diagnostics) => {
15651
+ const firings = /* @__PURE__ */ new Map();
15652
+ for (const diagnostic of diagnostics) {
15653
+ const { ruleKey, category } = getDiagnosticRuleIdentity(diagnostic);
15654
+ const firingKey = `${ruleKey}\u0000${diagnostic.severity}`;
15655
+ const existing = firings.get(firingKey);
15656
+ firings.set(firingKey, existing ? {
15657
+ ...existing,
15658
+ count: existing.count + 1
15659
+ } : {
15660
+ rule: ruleKey,
15661
+ plugin: diagnostic.plugin,
15662
+ category,
15663
+ severity: diagnostic.severity,
15664
+ count: 1
15665
+ });
15666
+ }
15667
+ return [...firings.values()];
15668
+ };
15669
+ /**
15670
+ * Emits the per-scan engineering + product counters/distributions for one
15671
+ * `inspect()` run (fires once per project in a workspace scan). Every emission
15672
+ * is a no-op unless Sentry is live, and the shared run/project attributes ride
15673
+ * along from the global scope, so call sites only pass scan-specific dimensions.
15674
+ */
15675
+ const recordScanMetrics = (input) => {
15676
+ const { result } = input;
15677
+ const hasSkippedChecks = result.skippedChecks.length > 0;
15678
+ recordCount(METRIC.scanCompleted, 1, {
15679
+ mode: input.mode,
15680
+ lint: input.lint,
15681
+ deadCode: input.deadCode,
15682
+ parallel: input.parallel,
15683
+ scoreOnly: input.scoreOnly,
15684
+ didLintFail: input.didLintFail,
15685
+ didDeadCodeFail: input.didDeadCodeFail,
15686
+ hasSkippedChecks
15687
+ });
15688
+ recordDistribution(METRIC.scanDuration, result.elapsedMilliseconds, {
15689
+ unit: "millisecond",
15690
+ attributes: {
15691
+ mode: input.mode,
15692
+ parallel: input.parallel,
15693
+ scoreOnly: input.scoreOnly
15694
+ }
15695
+ });
15696
+ if (result.scanElapsedMilliseconds !== void 0) recordDistribution(METRIC.scanPhaseDuration, result.scanElapsedMilliseconds, {
15697
+ unit: "millisecond",
15698
+ attributes: { mode: input.mode }
15699
+ });
15700
+ if (result.scannedFileCount !== void 0) recordDistribution(METRIC.scanFiles, result.scannedFileCount, { attributes: { mode: input.mode } });
15701
+ if (input.workerCount !== void 0) recordDistribution(METRIC.oxlintWorkers, input.workerCount, { attributes: { mode: input.mode } });
15702
+ for (const firing of summarizeRuleFirings(result.diagnostics)) recordCount(METRIC.ruleFired, firing.count, {
15703
+ rule: firing.rule,
15704
+ plugin: firing.plugin,
15705
+ category: firing.category,
15706
+ severity: firing.severity
15707
+ });
15708
+ if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
15709
+ if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
15710
+ else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
15711
+ if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
15712
+ if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
15713
+ for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
15714
+ check,
15715
+ reason: result.skippedCheckReasons?.[check] ?? null
15716
+ });
15717
+ };
15718
+ //#endregion
15466
15719
  //#region src/cli/utils/build-no-score-message.ts
15467
15720
  const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
15468
15721
  const buildNoScoreMessage = (isScoreDisabled) => {
@@ -16370,6 +16623,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16370
16623
  suppressScanSummary: options.suppressRendering
16371
16624
  }, { beforeLint: (projectInfo, lintIncludePaths) => Effect.gen(function* () {
16372
16625
  recordSentryProjectContext(projectInfo, rootSentrySpan);
16626
+ recordCount(METRIC.projectDetected, 1);
16373
16627
  if (options.scoreOnly || options.suppressRendering) return;
16374
16628
  const lintSourceFileCount = lintIncludePaths?.length ?? projectInfo.sourceFileCount;
16375
16629
  yield* printProjectDetection({
@@ -16405,7 +16659,21 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16405
16659
  scannedFilePaths: output.scannedFilePaths,
16406
16660
  scanElapsedMilliseconds: output.scanElapsedMilliseconds
16407
16661
  };
16408
- return await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16662
+ const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16663
+ recordScanMetrics({
16664
+ result,
16665
+ mode: isDiffMode ? "diff" : "full",
16666
+ parallel: options.concurrency !== void 0,
16667
+ workerCount: options.concurrency,
16668
+ lint: options.lint,
16669
+ deadCode: options.deadCode,
16670
+ scoreOnly: options.scoreOnly,
16671
+ noScore: options.noScore,
16672
+ didLintFail,
16673
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
16674
+ didDeadCodeFail: output.didDeadCodeFail
16675
+ });
16676
+ return result;
16409
16677
  };
16410
16678
  const finalizeAndRender = (input) => Effect.gen(function* () {
16411
16679
  const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
@@ -16589,6 +16857,21 @@ const handleError = (error, options = {}) => {
16589
16857
  if (options.shouldExit !== false) process.exit(1);
16590
16858
  process.exitCode = 1;
16591
16859
  };
16860
+ /**
16861
+ * Renderer for expected, user-actionable failures — a bad `--diff` value or
16862
+ * a base branch that isn't fetched. Prints just the (already human-readable)
16863
+ * message — no "Something went wrong", prefilled issue, Discord link, or
16864
+ * Sentry reference — because there is no bug to report.
16865
+ */
16866
+ const handleUserError = (error, options = {}) => {
16867
+ Effect.runSync(Effect.gen(function* () {
16868
+ yield* Console.error("");
16869
+ yield* Console.error(highlighter.error(formatErrorForReport(error)));
16870
+ yield* Console.error("");
16871
+ }));
16872
+ if (options.shouldExit !== false) process.exit(1);
16873
+ process.exitCode = 1;
16874
+ };
16592
16875
  //#endregion
16593
16876
  //#region src/cli/utils/build-handoff-payload.ts
16594
16877
  const buildHandoffPayload = (input) => {
@@ -17597,11 +17880,17 @@ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) =>
17597
17880
  projectRoot,
17598
17881
  runner: dependencyRunner
17599
17882
  });
17883
+ recordCount(METRIC.installDependency, 1, {
17884
+ status: dependencyResult.dependencyStatus,
17885
+ reason: dependencyResult.dependencyReason ?? null,
17886
+ packageManager: detectPackageManager(projectRoot)
17887
+ });
17600
17888
  if (dependencyResult.dependencyStatus === "skipped") {
17601
17889
  dependencySpinner.fail(formatDependencyInstallMessage(dependencyResult));
17602
- return;
17890
+ return dependencyResult;
17603
17891
  }
17604
17892
  dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
17893
+ return dependencyResult;
17605
17894
  } catch (error) {
17606
17895
  dependencySpinner.fail("Failed to install React Doctor package.");
17607
17896
  throw error;
@@ -17769,7 +18058,7 @@ const runInstallReactDoctor = async (options = {}) => {
17769
18058
  } catch {
17770
18059
  cliLogger.dim(" Skipped bundled sibling skills (install error).");
17771
18060
  }
17772
- await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
18061
+ const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
17773
18062
  if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
17774
18063
  const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
17775
18064
  try {
@@ -17780,6 +18069,7 @@ const runInstallReactDoctor = async (options = {}) => {
17780
18069
  hooksPathConfig: gitHookTarget.hooksPathConfig
17781
18070
  });
17782
18071
  hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
18072
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
17783
18073
  } catch (error) {
17784
18074
  hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
17785
18075
  throw error;
@@ -17793,7 +18083,10 @@ const runInstallReactDoctor = async (options = {}) => {
17793
18083
  agents: selectedAgents
17794
18084
  });
17795
18085
  if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
17796
- else hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18086
+ else {
18087
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18088
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
18089
+ }
17797
18090
  } catch (error) {
17798
18091
  hookSpinner.fail("Failed to install React Doctor agent hooks.");
17799
18092
  throw error;
@@ -17805,11 +18098,21 @@ const runInstallReactDoctor = async (options = {}) => {
17805
18098
  try {
17806
18099
  writeFileSync(workflowTargetPath, buildWorkflowContent());
17807
18100
  workflowSpinner.succeed(`GitHub Actions workflow added at ${path.relative(projectRoot, workflowTargetPath)}.`);
18101
+ recordCount(METRIC.installWorkflow, 1);
17808
18102
  } catch (error) {
17809
18103
  workflowSpinner.fail("Failed to add GitHub Actions workflow.");
17810
18104
  throw error;
17811
18105
  }
17812
18106
  }
18107
+ recordCount(METRIC.installCompleted, 1, {
18108
+ agentsCount: selectedAgents.length,
18109
+ gitHook: shouldInstallGitHook,
18110
+ agentHooks: shouldInstallAgentHooks,
18111
+ workflow: shouldInstallWorkflow,
18112
+ dependencyStatus: dependencyResult.dependencyStatus,
18113
+ packageManager: detectPackageManager(projectRoot)
18114
+ });
18115
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
17813
18116
  };
17814
18117
  //#endregion
17815
18118
  //#region src/cli/utils/install-skill-for-agent.ts
@@ -17922,6 +18225,16 @@ const handoffToAgent = async (input) => {
17922
18225
  ],
17923
18226
  initial: 0
17924
18227
  }, { onCancel: () => true });
18228
+ let handoffOutcome = "launch";
18229
+ if (handoffTarget === void 0) handoffOutcome = "cancel";
18230
+ else if (handoffTarget === SKIP_CHOICE) handoffOutcome = "skip";
18231
+ else if (handoffTarget === PRINT_CHOICE) handoffOutcome = "print";
18232
+ else if (handoffTarget === CLIPBOARD_CHOICE) handoffOutcome = "clipboard";
18233
+ recordCount(METRIC.agentHandoff, 1, {
18234
+ outcome: handoffOutcome,
18235
+ agent: handoffOutcome === "launch" ? handoffTarget : void 0,
18236
+ diagnosticsCount: input.diagnostics.length
18237
+ });
17925
18238
  if (handoffTarget === void 0 || handoffTarget === SKIP_CHOICE) return;
17926
18239
  const payload = buildHandoffPayload({
17927
18240
  diagnostics: input.diagnostics,
@@ -18067,6 +18380,13 @@ const reportErrorToSentry = async (error) => {
18067
18380
  if (!Sentry.isInitialized()) return void 0;
18068
18381
  try {
18069
18382
  const { tags, contexts } = buildSentryScope();
18383
+ let reason = "unknown";
18384
+ if (isReactDoctorError(error)) reason = error.reason._tag;
18385
+ else if (error instanceof Error) reason = error.name;
18386
+ recordCount(METRIC.cliError, 1, {
18387
+ command: typeof tags.command === "string" ? tags.command : void 0,
18388
+ reason
18389
+ });
18070
18390
  const runTrace = getActiveRunTrace();
18071
18391
  const eventId = Sentry.withScope((scope) => {
18072
18392
  for (const [name, context] of Object.entries(contexts)) scope.setContext(name, context);
@@ -18612,6 +18932,7 @@ const inspectAction = async (directory, flags) => {
18612
18932
  compact: Boolean(flags.jsonCompact),
18613
18933
  directory: requestedDirectory
18614
18934
  });
18935
+ recordCount(METRIC.cliInvoked, 1, { command: "inspect" });
18615
18936
  try {
18616
18937
  validateModeFlags(flags);
18617
18938
  maybeMigrateLegacyConfig(requestedDirectory, {
@@ -18789,21 +19110,30 @@ const inspectAction = async (directory, flags) => {
18789
19110
  isJsonMode,
18790
19111
  isScoreOnly,
18791
19112
  isStaged: Boolean(flags.staged)
18792
- })) printAgentInstallHint();
19113
+ })) {
19114
+ printAgentInstallHint();
19115
+ recordCount(METRIC.agentInstallHintShown, 1);
19116
+ }
18793
19117
  }
18794
19118
  } catch (error) {
18795
- const sentryEventId = await reportErrorToSentry(error);
19119
+ const isUserError = isReactDoctorError(error) && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
19120
+ const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
18796
19121
  if (isJsonMode) {
18797
19122
  writeJsonErrorReport(error);
18798
19123
  process.exitCode = 1;
18799
19124
  return;
18800
19125
  }
19126
+ if (isUserError) {
19127
+ handleUserError(error);
19128
+ return;
19129
+ }
18801
19130
  handleError(error, { sentryEventId });
18802
19131
  }
18803
19132
  };
18804
19133
  //#endregion
18805
19134
  //#region src/cli/commands/install.ts
18806
19135
  const installAction = async (options, command) => {
19136
+ recordCount(METRIC.cliInvoked, 1, { command: "install" });
18807
19137
  Effect.runSync(printBrandedHeader);
18808
19138
  try {
18809
19139
  const parentOptions = command?.parent?.opts?.();
@@ -19124,6 +19454,7 @@ const SEVERITY_VALUES = [
19124
19454
  "warn",
19125
19455
  "error"
19126
19456
  ];
19457
+ const recordRulesInvocation = () => recordCount(METRIC.cliInvoked, 1, { command: "rules" });
19127
19458
  const resolveProjectRoot = (options) => {
19128
19459
  const requestedDirectory = path.resolve(options.cwd ?? process.cwd());
19129
19460
  return findNearestPackageDirectory(requestedDirectory) ?? requestedDirectory;
@@ -19166,6 +19497,11 @@ const reportManualEdit = (target, nextConfig) => {
19166
19497
  process.exitCode = 1;
19167
19498
  };
19168
19499
  const rulesListAction = async (options) => {
19500
+ recordRulesInvocation();
19501
+ recordCount(METRIC.rulesQueried, 1, {
19502
+ subcommand: "list",
19503
+ hadFilter: Boolean(options.category || options.tag || options.framework || options.configured)
19504
+ });
19169
19505
  const catalog = buildRuleCatalog();
19170
19506
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
19171
19507
  const categoryFilter = options.category?.toLowerCase();
@@ -19197,6 +19533,8 @@ const rulesListAction = async (options) => {
19197
19533
  cliLogger.log(renderRuleCatalog(rows));
19198
19534
  };
19199
19535
  const rulesExplainAction = async (ruleQuery, options) => {
19536
+ recordRulesInvocation();
19537
+ recordCount(METRIC.rulesQueried, 1, { subcommand: "explain" });
19200
19538
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19201
19539
  if (!entry) {
19202
19540
  reportRuleNotFound(ruleQuery);
@@ -19224,7 +19562,7 @@ const rulesExplainAction = async (ruleQuery, options) => {
19224
19562
  effective
19225
19563
  }));
19226
19564
  };
19227
- const setRuleSeverityAndReport = async (entry, severity, options) => {
19565
+ const setRuleSeverityAndReport = async (entry, severity, options, action) => {
19228
19566
  const { target, nextConfig, written } = await applyConfigChange(options, (config) => setRuleSeverity(config, entry.key, severity));
19229
19567
  if (!written) {
19230
19568
  reportManualEdit(target, nextConfig);
@@ -19232,8 +19570,14 @@ const setRuleSeverityAndReport = async (entry, severity, options) => {
19232
19570
  }
19233
19571
  cliLogger.success(`Set ${entry.key} → ${severity}`);
19234
19572
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19573
+ recordCount(METRIC.rulesChanged, 1, {
19574
+ action,
19575
+ severity,
19576
+ target: entry.key
19577
+ });
19235
19578
  };
19236
19579
  const rulesSetAction = async (ruleQuery, severityValue, options) => {
19580
+ recordRulesInvocation();
19237
19581
  const severity = parseSeverity(severityValue);
19238
19582
  if (!severity) {
19239
19583
  reportInvalidSeverity(severityValue);
@@ -19244,16 +19588,17 @@ const rulesSetAction = async (ruleQuery, severityValue, options) => {
19244
19588
  reportRuleNotFound(ruleQuery);
19245
19589
  return;
19246
19590
  }
19247
- await setRuleSeverityAndReport(entry, severity, options);
19591
+ await setRuleSeverityAndReport(entry, severity, options, "set");
19248
19592
  };
19249
19593
  const rulesEnableAction = async (ruleQuery, options) => {
19594
+ recordRulesInvocation();
19250
19595
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19251
19596
  if (!entry) {
19252
19597
  reportRuleNotFound(ruleQuery);
19253
19598
  return;
19254
19599
  }
19255
19600
  if (options.severity === void 0) {
19256
- await setRuleSeverityAndReport(entry, entry.defaultSeverity, options);
19601
+ await setRuleSeverityAndReport(entry, entry.defaultSeverity, options, "enable");
19257
19602
  return;
19258
19603
  }
19259
19604
  const severity = parseSeverity(options.severity);
@@ -19266,17 +19611,19 @@ const rulesEnableAction = async (ruleQuery, options) => {
19266
19611
  process.exitCode = 1;
19267
19612
  return;
19268
19613
  }
19269
- await setRuleSeverityAndReport(entry, severity, options);
19614
+ await setRuleSeverityAndReport(entry, severity, options, "enable");
19270
19615
  };
19271
19616
  const rulesDisableAction = async (ruleQuery, options) => {
19617
+ recordRulesInvocation();
19272
19618
  const entry = findRuleInCatalog(buildRuleCatalog(), ruleQuery);
19273
19619
  if (!entry) {
19274
19620
  reportRuleNotFound(ruleQuery);
19275
19621
  return;
19276
19622
  }
19277
- await setRuleSeverityAndReport(entry, "off", options);
19623
+ await setRuleSeverityAndReport(entry, "off", options, "disable");
19278
19624
  };
19279
19625
  const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19626
+ recordRulesInvocation();
19280
19627
  const severity = parseSeverity(severityValue);
19281
19628
  if (!severity) {
19282
19629
  reportInvalidSeverity(severityValue);
@@ -19297,8 +19644,14 @@ const rulesCategoryAction = async (categoryQuery, severityValue, options) => {
19297
19644
  }
19298
19645
  cliLogger.success(`Set category "${matchedCategory}" → ${severity}`);
19299
19646
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19647
+ recordCount(METRIC.rulesChanged, 1, {
19648
+ action: "category",
19649
+ severity,
19650
+ target: matchedCategory
19651
+ });
19300
19652
  };
19301
19653
  const rulesIgnoreTagAction = async (tag, options) => {
19654
+ recordRulesInvocation();
19302
19655
  const knownTags = listRuleTags(buildRuleCatalog());
19303
19656
  if (!knownTags.includes(tag)) {
19304
19657
  cliLogger.error(`Unknown tag "${tag}".`);
@@ -19313,8 +19666,13 @@ const rulesIgnoreTagAction = async (tag, options) => {
19313
19666
  }
19314
19667
  cliLogger.success(`Ignoring tag "${tag}" (rules with this tag are skipped before linting)`);
19315
19668
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19669
+ recordCount(METRIC.rulesChanged, 1, {
19670
+ action: "ignoreTag",
19671
+ target: tag
19672
+ });
19316
19673
  };
19317
19674
  const rulesUnignoreTagAction = async (tag, options) => {
19675
+ recordRulesInvocation();
19318
19676
  const target = await resolveRuleConfigTarget(resolveProjectRoot(options));
19319
19677
  if (!(target.config.ignore?.tags ?? []).includes(tag)) {
19320
19678
  cliLogger.dim(`Tag "${tag}" was not being ignored; nothing to change.`);
@@ -19328,6 +19686,10 @@ const rulesUnignoreTagAction = async (tag, options) => {
19328
19686
  }
19329
19687
  cliLogger.success(`Tag "${tag}" is no longer ignored`);
19330
19688
  cliLogger.dim(` Updated ${describeTargetPath(target)}`);
19689
+ recordCount(METRIC.rulesChanged, 1, {
19690
+ action: "unignoreTag",
19691
+ target: tag
19692
+ });
19331
19693
  };
19332
19694
  //#endregion
19333
19695
  //#region src/cli/commands/version.ts
@@ -19340,6 +19702,7 @@ const rulesUnignoreTagAction = async (tag, options) => {
19340
19702
  */
19341
19703
  const buildVersionString = () => `react-doctor/${VERSION} ${process.platform}-${process.arch} node-${process.version}`;
19342
19704
  const versionAction = () => {
19705
+ recordCount(METRIC.cliInvoked, 1, { command: "version" });
19343
19706
  process.stdout.write(`${buildVersionString()}\n`);
19344
19707
  };
19345
19708
  //#endregion
@@ -19657,4 +20020,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
19657
20020
  export {};
19658
20021
 
19659
20022
  //# sourceMappingURL=cli.js.map
19660
- //# debugId=d012dbb2-27e9-5092-9eab-c7fa4573f0b2
20023
+ //# debugId=c8bf2d99-8f0b-55f1-a894-63e600bf000b
package/dist/index.d.ts CHANGED
@@ -772,12 +772,13 @@ declare const buildJsonReport: (input: BuildJsonReportInput) => JsonReport; //#e
772
772
  * Git service runs through Effect's `ChildProcess` (true subprocess
773
773
  * spawn, not `spawnSync`).
774
774
  *
775
- * Tagged-reason errors are dispatched via `Effect.catchReasons`
776
- * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
777
- * union without manual `instanceof` checks). The recovered branches
778
- * raise plain `Error`s so existing thrown-class consumers continue
779
- * to work — anything else (real `GitInvocationFailed`, etc.)
780
- * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
775
+ * Failures propagate as the tagged `ReactDoctorError` (rejected by
776
+ * `Effect.runPromise`) rather than being flattened into a plain
777
+ * `Error`. The message is unchanged — `ReactDoctorError.message`
778
+ * defers to `reason.message` — so message-matching callers keep
779
+ * working, while the CLI can now dispatch on `error.reason._tag` to
780
+ * render diff-base mistakes (`GitBaseBranchInvalid` /
781
+ * `GitBaseBranchMissing`) as clean user errors instead of crashes.
781
782
  */
782
783
  declare const getDiffInfo: (directory: string, explicitBaseBranch?: string) => Promise<DiffInfo | null>;
783
784
  declare const filterSourceFiles: (filePaths: string[]) => string[]; //#endregion
package/dist/index.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]="df20b0d3-9e4e-52e0-8991-ce8a6349a04a")}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]="3967254f-df21-5398-99d5-ee0d17b33e7b")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as fs$1 from "node:fs";
@@ -5928,6 +5928,11 @@ const trimOrNull = (value) => {
5928
5928
  * `@{` reflog suffix, or any character outside `[A-Za-z0-9_./-]`.
5929
5929
  */
5930
5930
  const SAFE_GIT_REVISION_PATTERN = /^[A-Za-z0-9_./-]+$/;
5931
+ /** Human-readable summary of the `isSafeGitRevision` contract, reused across error details. */
5932
+ const GIT_REF_NAME_RULE = "must match [A-Za-z0-9_./-] without leading '-', '..', or '@{'";
5933
+ /** git's two range operators: two-dot (direct) and three-dot (merge-base). */
5934
+ const DIFF_RANGE_OPERATOR = "..";
5935
+ const SYMMETRIC_DIFF_RANGE_OPERATOR = "...";
5931
5936
  const isSafeGitRevision = (candidate) => {
5932
5937
  if (candidate.length === 0) return false;
5933
5938
  if (candidate.startsWith("-")) return false;
@@ -5935,6 +5940,31 @@ const isSafeGitRevision = (candidate) => {
5935
5940
  if (candidate.includes("..") || candidate.includes("@{")) return false;
5936
5941
  return SAFE_GIT_REVISION_PATTERN.test(candidate);
5937
5942
  };
5943
+ /**
5944
+ * Splits a git revision range into its endpoints: three-dot `A...B`
5945
+ * (symmetric, merge-base) or two-dot `A..B` (direct). Returns `null`
5946
+ * when `value` carries no range operator so the caller falls back to
5947
+ * single-base resolution.
5948
+ *
5949
+ * Only the first operator is split on; any leftover `..` stays inside an
5950
+ * endpoint so `isSafeGitRevision` rejects malformed input like
5951
+ * `A..B..C` instead of silently guessing which pair the user meant.
5952
+ */
5953
+ const parseGitDiffRange = (value) => {
5954
+ const symmetricIndex = value.indexOf(SYMMETRIC_DIFF_RANGE_OPERATOR);
5955
+ if (symmetricIndex !== -1) return {
5956
+ base: value.slice(0, symmetricIndex),
5957
+ head: value.slice(symmetricIndex + 3),
5958
+ symmetric: true
5959
+ };
5960
+ const rangeIndex = value.indexOf(DIFF_RANGE_OPERATOR);
5961
+ if (rangeIndex !== -1) return {
5962
+ base: value.slice(0, rangeIndex),
5963
+ head: value.slice(rangeIndex + 2),
5964
+ symmetric: false
5965
+ };
5966
+ return null;
5967
+ };
5938
5968
  const parseGithubRepoFromRemoteUrl = (remoteUrl) => {
5939
5969
  const withoutGitSuffix = remoteUrl.trim().replace(/\.git$/, "");
5940
5970
  const sshMatch = /^git@github\.com:([^/\s]+)\/([^/\s]+)$/.exec(withoutGitSuffix);
@@ -6086,6 +6116,49 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
6086
6116
  if (result.status !== 0) return null;
6087
6117
  return parseGithubViewerPermission(result.stdout);
6088
6118
  }).pipe(Effect.catch(() => Effect.succeed(null)));
6119
+ /**
6120
+ * Resolves a `--diff A..B` / `A...B` commit range into a changed-file
6121
+ * selection. Each endpoint is validated with `isSafeGitRevision`
6122
+ * BEFORE it reaches `git` (so the range syntax can't smuggle a
6123
+ * `--upload-pack=…`-style option past the CVE-2018-17456 guard) and
6124
+ * verified to exist, then the diff runs between the two commits with
6125
+ * the same `--diff-filter=ACMR` shape the single-base path uses.
6126
+ */
6127
+ const resolveDiffRange = (input) => Effect.gen(function* () {
6128
+ if (input.range.base.length === 0 && input.range.head.length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" must name at least one commit (e.g. "main..feature").` }) }));
6129
+ const baseRef = input.range.base.length === 0 ? "HEAD" : input.range.base;
6130
+ const headRef = input.range.head.length === 0 ? "HEAD" : input.range.head;
6131
+ for (const endpoint of [baseRef, headRef]) if (!isSafeGitRevision(endpoint)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff range "${input.raw}" has an invalid endpoint "${endpoint}" (${GIT_REF_NAME_RULE}).` }) }));
6132
+ for (const endpoint of [baseRef, headRef]) if (!(yield* branchExists(input.directory, endpoint))) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchMissing({ branch: endpoint }) }));
6133
+ let diffBaseRef = baseRef;
6134
+ if (input.range.symmetric) {
6135
+ const mergeBase = yield* runGit(input.directory, [
6136
+ "merge-base",
6137
+ baseRef,
6138
+ headRef
6139
+ ]);
6140
+ if (mergeBase.status !== 0) return null;
6141
+ const mergeBaseRef = trimOrNull(mergeBase.stdout);
6142
+ if (mergeBaseRef === null) return null;
6143
+ diffBaseRef = mergeBaseRef;
6144
+ }
6145
+ const diff = yield* runGit(input.directory, [
6146
+ "diff",
6147
+ "-z",
6148
+ "--name-only",
6149
+ "--diff-filter=ACMR",
6150
+ "--relative",
6151
+ diffBaseRef,
6152
+ headRef
6153
+ ]);
6154
+ if (diff.status !== 0) return null;
6155
+ return {
6156
+ currentBranch: yield* currentBranch(input.directory),
6157
+ baseBranch: baseRef,
6158
+ changedFiles: splitNullSeparated(diff.stdout),
6159
+ isCurrentChanges: false
6160
+ };
6161
+ });
6089
6162
  return Git.of({
6090
6163
  currentBranch,
6091
6164
  defaultBranch,
@@ -6095,7 +6168,15 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
6095
6168
  branchExists,
6096
6169
  diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
6097
6170
  if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
6098
- if (explicitBaseBranch !== void 0 && !isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (must match [A-Za-z0-9_./-] without leading '-', '..', or '@{').` }) }));
6171
+ if (explicitBaseBranch !== void 0) {
6172
+ const range = parseGitDiffRange(explicitBaseBranch);
6173
+ if (range !== null) return yield* resolveDiffRange({
6174
+ directory,
6175
+ range,
6176
+ raw: explicitBaseBranch
6177
+ });
6178
+ if (!isSafeGitRevision(explicitBaseBranch)) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: `Diff base branch "${explicitBaseBranch}" is not a valid git ref name (${GIT_REF_NAME_RULE}).` }) }));
6179
+ }
6099
6180
  const resolvedCurrentBranch = yield* currentBranch(directory);
6100
6181
  if (resolvedCurrentBranch === null && explicitBaseBranch === void 0) return null;
6101
6182
  const baseBranch = explicitBaseBranch ?? (yield* defaultBranch(directory));
@@ -8453,12 +8534,13 @@ const buildSkippedChecks = (input) => {
8453
8534
  * Git service runs through Effect's `ChildProcess` (true subprocess
8454
8535
  * spawn, not `spawnSync`).
8455
8536
  *
8456
- * Tagged-reason errors are dispatched via `Effect.catchReasons`
8457
- * (a v4-native API for narrowing inside a `Schema.TaggedErrorClass`
8458
- * union without manual `instanceof` checks). The recovered branches
8459
- * raise plain `Error`s so existing thrown-class consumers continue
8460
- * to work — anything else (real `GitInvocationFailed`, etc.)
8461
- * propagates as the tagged `ReactDoctorError` through `Effect.runPromise`.
8537
+ * Failures propagate as the tagged `ReactDoctorError` (rejected by
8538
+ * `Effect.runPromise`) rather than being flattened into a plain
8539
+ * `Error`. The message is unchanged — `ReactDoctorError.message`
8540
+ * defers to `reason.message` — so message-matching callers keep
8541
+ * working, while the CLI can now dispatch on `error.reason._tag` to
8542
+ * render diff-base mistakes (`GitBaseBranchInvalid` /
8543
+ * `GitBaseBranchMissing`) as clean user errors instead of crashes.
8462
8544
  */
8463
8545
  const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.gen(function* () {
8464
8546
  const selection = yield* (yield* Git).diffSelection({
@@ -8472,10 +8554,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
8472
8554
  changedFiles: [...selection.changedFiles],
8473
8555
  ...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
8474
8556
  };
8475
- }).pipe(Effect.provide(Git.layerNode), Effect.catchReasons("ReactDoctorError", {
8476
- GitBaseBranchInvalid: (reason) => Effect.die(new Error(reason.detail)),
8477
- GitBaseBranchMissing: (reason) => Effect.die(new Error(reason.message))
8478
- })));
8557
+ }).pipe(Effect.provide(Git.layerNode)));
8479
8558
  const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
8480
8559
  var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
8481
8560
  let p = process || {}, argv = p.argv || [], env = p.env || {};
@@ -8620,4 +8699,4 @@ const toJsonReport = (result, options) => buildJsonReport({
8620
8699
  export { AmbiguousProjectError, NoReactDependencyError, NotADirectoryError, PackageJsonNotFoundError, ProjectNotFoundError, ReactDoctorError, buildJsonReport, buildJsonReportError, clearCaches, diagnose, filterSourceFiles, getDiffInfo, isProjectDiscoveryError, isReactDoctorError, summarizeDiagnostics, toJsonReport };
8621
8700
 
8622
8701
  //# sourceMappingURL=index.js.map
8623
- //# debugId=df20b0d3-9e4e-52e0-8991-ce8a6349a04a
8702
+ //# debugId=3967254f-df21-5398-99d5-ee0d17b33e7b
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-doctor",
3
- "version": "0.2.15-dev.3fae9dd",
3
+ "version": "0.2.15-dev.520b0a9",
4
4
  "description": "Diagnose and fix React codebases for security, performance, correctness, accessibility, bundle-size, and architecture issues",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -63,7 +63,7 @@
63
63
  "oxlint": "^1.66.0",
64
64
  "prompts": "^2.4.2",
65
65
  "typescript": ">=5.0.4 <7",
66
- "oxlint-plugin-react-doctor": "0.2.15-dev.3fae9dd"
66
+ "oxlint-plugin-react-doctor": "0.2.15-dev.520b0a9"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/babel__code-frame": "^7.27.0",
@@ -71,8 +71,8 @@
71
71
  "@xterm/headless": "^6.0.0",
72
72
  "commander": "^14.0.3",
73
73
  "ora": "^9.4.0",
74
- "@react-doctor/api": "0.2.15",
75
- "@react-doctor/core": "0.2.15"
74
+ "@react-doctor/core": "0.2.15",
75
+ "@react-doctor/api": "0.2.15"
76
76
  },
77
77
  "engines": {
78
78
  "node": "^20.19.0 || >=22.12.0"