react-doctor 0.3.0 → 0.4.0-dev.36ecd05
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 +22 -5
- package/bin/react-doctor.js +9 -1
- package/dist/cli.js +819 -255
- package/dist/index.d.ts +141 -12
- package/dist/index.js +190 -60
- package/dist/lsp.js +10805 -0
- package/package.json +8 -4
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]="
|
|
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]="97daaac0-bc19-511e-baba-f43ac0b855ea")}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,11 +34,11 @@ 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";
|
|
38
|
+
import * as Exit from "effect/Exit";
|
|
37
39
|
import * as Sentry from "@sentry/node";
|
|
38
40
|
import { performance } from "node:perf_hooks";
|
|
39
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
40
41
|
import * as Tracer from "effect/Tracer";
|
|
41
|
-
import * as Exit from "effect/Exit";
|
|
42
42
|
import { promisify, stripVTControlCharacters } from "node:util";
|
|
43
43
|
import tty from "node:tty";
|
|
44
44
|
import { codeFrameColumns } from "@babel/code-frame";
|
|
@@ -3085,6 +3085,16 @@ const { program: program$1, createCommand, createArgument, createOption, Command
|
|
|
3085
3085
|
//#endregion
|
|
3086
3086
|
//#region ../core/dist/schemas.js
|
|
3087
3087
|
const Severity = Schema.Literals(["error", "warning"]);
|
|
3088
|
+
var DiagnosticRelatedLocation = class extends Schema.Class("DiagnosticRelatedLocation")({
|
|
3089
|
+
filePath: Schema.String,
|
|
3090
|
+
line: Schema.Number,
|
|
3091
|
+
column: Schema.Number,
|
|
3092
|
+
offset: Schema.optional(Schema.Number),
|
|
3093
|
+
length: Schema.optional(Schema.Number),
|
|
3094
|
+
endLine: Schema.optional(Schema.Number),
|
|
3095
|
+
endColumn: Schema.optional(Schema.Number),
|
|
3096
|
+
message: Schema.String
|
|
3097
|
+
}) {};
|
|
3088
3098
|
var Diagnostic = class extends Schema.Class("Diagnostic")({
|
|
3089
3099
|
filePath: Schema.String,
|
|
3090
3100
|
plugin: Schema.String,
|
|
@@ -3096,13 +3106,19 @@ var Diagnostic = class extends Schema.Class("Diagnostic")({
|
|
|
3096
3106
|
url: Schema.optional(Schema.String),
|
|
3097
3107
|
line: Schema.Number,
|
|
3098
3108
|
column: Schema.Number,
|
|
3109
|
+
offset: Schema.optional(Schema.Number),
|
|
3110
|
+
length: Schema.optional(Schema.Number),
|
|
3111
|
+
endLine: Schema.optional(Schema.Number),
|
|
3112
|
+
endColumn: Schema.optional(Schema.Number),
|
|
3099
3113
|
category: Schema.String,
|
|
3100
|
-
suppressionHint: Schema.optional(Schema.String)
|
|
3114
|
+
suppressionHint: Schema.optional(Schema.String),
|
|
3115
|
+
relatedLocations: Schema.optional(Schema.Array(DiagnosticRelatedLocation))
|
|
3101
3116
|
}) {};
|
|
3102
3117
|
const JsonReportMode = Schema.Literals([
|
|
3103
3118
|
"full",
|
|
3104
3119
|
"diff",
|
|
3105
|
-
"staged"
|
|
3120
|
+
"staged",
|
|
3121
|
+
"baseline"
|
|
3106
3122
|
]);
|
|
3107
3123
|
var JsonReportSummary = class extends Schema.Class("JsonReportSummary")({
|
|
3108
3124
|
errorCount: Schema.Number,
|
|
@@ -3121,7 +3137,9 @@ var JsonReportDiffInfo = class extends Schema.Class("JsonReportDiffInfo")({
|
|
|
3121
3137
|
var JsonReportError = class extends Schema.Class("JsonReportError")({
|
|
3122
3138
|
message: Schema.String,
|
|
3123
3139
|
name: Schema.String,
|
|
3124
|
-
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))
|
|
3125
3143
|
}) {};
|
|
3126
3144
|
/**
|
|
3127
3145
|
* Schema for a single project entry within a JsonReport. `project` is
|
|
@@ -3158,7 +3176,33 @@ var JsonReportV1 = class extends Schema.Class("JsonReportV1")({
|
|
|
3158
3176
|
elapsedMilliseconds: Schema.Number,
|
|
3159
3177
|
error: Schema.NullOr(JsonReportError)
|
|
3160
3178
|
}) {};
|
|
3161
|
-
Schema.
|
|
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]);
|
|
3162
3206
|
//#endregion
|
|
3163
3207
|
//#region ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/constants.js
|
|
3164
3208
|
var require_constants = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
|
|
@@ -8350,6 +8394,7 @@ const checkReducedMotion = (rootDirectory) => {
|
|
|
8350
8394
|
if (!hasMotionLibrary) return [];
|
|
8351
8395
|
const result = spawnSync("git", [
|
|
8352
8396
|
"grep",
|
|
8397
|
+
"--untracked",
|
|
8353
8398
|
"-ql",
|
|
8354
8399
|
"-E",
|
|
8355
8400
|
REDUCED_MOTION_GREP_PATTERN,
|
|
@@ -9281,6 +9326,11 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9281
9326
|
branch
|
|
9282
9327
|
]).pipe(Effect.map((result) => result.status === 0));
|
|
9283
9328
|
const headSha = (directory) => runGit(directory, ["rev-parse", "HEAD"]).pipe(Effect.map((result) => result.status === 0 ? trimOrNull(result.stdout) : null));
|
|
9329
|
+
const mergeBase = (input) => isSafeGitRevision(input.ref) ? runGit(input.directory, [
|
|
9330
|
+
"merge-base",
|
|
9331
|
+
input.ref,
|
|
9332
|
+
"HEAD"
|
|
9333
|
+
]).pipe(Effect.map((result) => result.status === 0 ? trimOrNull(result.stdout) : null)) : Effect.succeed(null);
|
|
9284
9334
|
const githubRepo = (directory) => runGit(directory, [
|
|
9285
9335
|
"config",
|
|
9286
9336
|
"--get",
|
|
@@ -9356,6 +9406,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9356
9406
|
return {
|
|
9357
9407
|
currentBranch: yield* currentBranch(input.directory),
|
|
9358
9408
|
baseBranch: baseRef,
|
|
9409
|
+
diffBaseRef,
|
|
9359
9410
|
changedFiles: splitNullSeparated(diff.stdout),
|
|
9360
9411
|
isCurrentChanges: false
|
|
9361
9412
|
};
|
|
@@ -9367,6 +9418,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9367
9418
|
githubRepo,
|
|
9368
9419
|
githubViewerPermission,
|
|
9369
9420
|
branchExists,
|
|
9421
|
+
mergeBase,
|
|
9370
9422
|
diffSelection: ({ directory, explicitBaseBranch }) => Effect.gen(function* () {
|
|
9371
9423
|
if (explicitBaseBranch !== void 0 && explicitBaseBranch.trim().length === 0) return yield* Effect.fail(new ReactDoctorError({ reason: new GitBaseBranchInvalid({ detail: "Diff base branch cannot be empty." }) }));
|
|
9372
9424
|
if (explicitBaseBranch !== void 0) {
|
|
@@ -9424,6 +9476,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9424
9476
|
return {
|
|
9425
9477
|
currentBranch: resolvedCurrentBranch,
|
|
9426
9478
|
baseBranch,
|
|
9479
|
+
diffBaseRef: mergeBaseRef,
|
|
9427
9480
|
changedFiles: splitNullSeparated(diff.stdout),
|
|
9428
9481
|
isCurrentChanges: false
|
|
9429
9482
|
};
|
|
@@ -9445,6 +9498,12 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9445
9498
|
directory,
|
|
9446
9499
|
maxStdoutBytes: options?.maxBufferBytes
|
|
9447
9500
|
}).pipe(Effect.map((result) => result.status === 0 ? result.stdout : null)),
|
|
9501
|
+
showRefContent: ({ directory, ref, relativePath, options }) => isSafeGitRevision(ref) ? runCommand({
|
|
9502
|
+
command: "git",
|
|
9503
|
+
args: ["show", `${ref}:./${relativePath}`],
|
|
9504
|
+
directory,
|
|
9505
|
+
maxStdoutBytes: options?.maxBufferBytes
|
|
9506
|
+
}).pipe(Effect.map((result) => result.status === 0 ? result.stdout : null)) : Effect.succeed(null),
|
|
9448
9507
|
grep: (input) => Effect.gen(function* () {
|
|
9449
9508
|
const args = ["grep"];
|
|
9450
9509
|
if (input.listMatchingFiles ?? true) args.push("-l");
|
|
@@ -9480,9 +9539,11 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
|
|
|
9480
9539
|
githubRepo: () => Effect.succeed(snapshot.githubRepo ?? null),
|
|
9481
9540
|
githubViewerPermission: () => Effect.succeed(snapshot.githubViewerPermission ?? null),
|
|
9482
9541
|
branchExists: (_directory, branch) => Effect.succeed(snapshot.branchExists?.get(branch) ?? false),
|
|
9542
|
+
mergeBase: ({ ref }) => Effect.succeed(snapshot.mergeBase?.get(ref) ?? null),
|
|
9483
9543
|
diffSelection: () => Effect.succeed(snapshot.diffSelection ?? null),
|
|
9484
9544
|
stagedFilePaths: () => Effect.succeed(snapshot.stagedFiles ?? []),
|
|
9485
9545
|
showStagedContent: (_directory, relativePath) => Effect.succeed(snapshot.stagedContent?.get(relativePath) ?? null),
|
|
9546
|
+
showRefContent: ({ ref, relativePath }) => Effect.succeed(snapshot.refContent?.get(`${ref}:${relativePath}`) ?? null),
|
|
9486
9547
|
grep: () => Effect.sync(() => {
|
|
9487
9548
|
const matches = snapshot.grepMatches;
|
|
9488
9549
|
if (matches === null || matches === void 0) return null;
|
|
@@ -10537,6 +10598,30 @@ const parseRuleCode = (code) => {
|
|
|
10537
10598
|
};
|
|
10538
10599
|
};
|
|
10539
10600
|
const resolveDiagnosticCategory = (plugin, rule) => getRuleCategory(rule) ?? lookupOwnString(PLUGIN_CATEGORY_MAP, plugin) ?? "Bugs";
|
|
10601
|
+
/**
|
|
10602
|
+
* Maps oxlint's non-primary labels (`labels[1..]`) into related source
|
|
10603
|
+
* locations. Editors surface these as a diagnostic's
|
|
10604
|
+
* `relatedInformation`; non-editor consumers ignore the field. Labels
|
|
10605
|
+
* with empty text still carry a useful jump target, so they're kept
|
|
10606
|
+
* with a neutral message.
|
|
10607
|
+
*/
|
|
10608
|
+
const buildRelatedLocations = (labels, filePath) => {
|
|
10609
|
+
if (labels.length <= 1) return [];
|
|
10610
|
+
const related = [];
|
|
10611
|
+
for (let labelIndex = 1; labelIndex < labels.length; labelIndex++) {
|
|
10612
|
+
const label = labels[labelIndex];
|
|
10613
|
+
if (!label?.span) continue;
|
|
10614
|
+
related.push({
|
|
10615
|
+
filePath,
|
|
10616
|
+
line: label.span.line ?? 0,
|
|
10617
|
+
column: label.span.column ?? 0,
|
|
10618
|
+
offset: label.span.offset,
|
|
10619
|
+
length: label.span.length,
|
|
10620
|
+
message: label.label ?? ""
|
|
10621
|
+
});
|
|
10622
|
+
}
|
|
10623
|
+
return related;
|
|
10624
|
+
};
|
|
10540
10625
|
const isOxlintOutput = (value) => {
|
|
10541
10626
|
if (typeof value !== "object" || value === null) return false;
|
|
10542
10627
|
const candidate = value;
|
|
@@ -10573,8 +10658,11 @@ const parseOxlintOutput = (stdout, project, rootDirectory) => {
|
|
|
10573
10658
|
const { plugin, rule } = parseRuleCode(diagnostic.code);
|
|
10574
10659
|
const primaryLabel = diagnostic.labels[0];
|
|
10575
10660
|
const cleaned = cleanDiagnosticMessage(diagnostic.message, diagnostic.help, plugin, rule, project);
|
|
10661
|
+
const normalizedFilePath = diagnostic.filename.replaceAll("\\", "/");
|
|
10662
|
+
const primarySpan = primaryLabel?.span;
|
|
10663
|
+
const relatedLocations = buildRelatedLocations(diagnostic.labels, normalizedFilePath);
|
|
10576
10664
|
return {
|
|
10577
|
-
filePath:
|
|
10665
|
+
filePath: normalizedFilePath,
|
|
10578
10666
|
plugin,
|
|
10579
10667
|
rule,
|
|
10580
10668
|
severity: diagnostic.severity,
|
|
@@ -10582,9 +10670,14 @@ const parseOxlintOutput = (stdout, project, rootDirectory) => {
|
|
|
10582
10670
|
message: cleaned.message,
|
|
10583
10671
|
help: cleaned.help,
|
|
10584
10672
|
url: diagnostic.url,
|
|
10585
|
-
line:
|
|
10586
|
-
column:
|
|
10587
|
-
|
|
10673
|
+
line: primarySpan?.line ?? 0,
|
|
10674
|
+
column: primarySpan?.column ?? 0,
|
|
10675
|
+
...primarySpan ? {
|
|
10676
|
+
offset: primarySpan.offset,
|
|
10677
|
+
length: primarySpan.length
|
|
10678
|
+
} : {},
|
|
10679
|
+
category: resolveDiagnosticCategory(plugin, rule),
|
|
10680
|
+
...relatedLocations.length > 0 ? { relatedLocations } : {}
|
|
10588
10681
|
};
|
|
10589
10682
|
});
|
|
10590
10683
|
};
|
|
@@ -11313,7 +11406,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
|
|
|
11313
11406
|
directory: scanDirectory,
|
|
11314
11407
|
repo
|
|
11315
11408
|
}).pipe(Effect.orElseSucceed(() => null)) : Effect.succeed(null));
|
|
11316
|
-
const lintIncludePaths = computeJsxIncludePaths([...input.includePaths]) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
|
|
11409
|
+
const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeJsxIncludePaths([...input.includePaths])) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
|
|
11317
11410
|
const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path$1.resolve(scanDirectory, relativePath)) : [];
|
|
11318
11411
|
const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
|
|
11319
11412
|
const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
|
|
@@ -11559,19 +11652,60 @@ var NodeResolver = class NodeResolver extends Context.Service()("react-doctor/No
|
|
|
11559
11652
|
});
|
|
11560
11653
|
};
|
|
11561
11654
|
/**
|
|
11562
|
-
* Zip-Slip defense:
|
|
11563
|
-
*
|
|
11564
|
-
*
|
|
11565
|
-
*
|
|
11566
|
-
* working tree) can include `..` segments that escape the temp
|
|
11567
|
-
* tree. Resolve the candidate against the temp dir and reject any
|
|
11568
|
-
* result that lands outside it before `writeFileSync` runs.
|
|
11655
|
+
* Zip-Slip defense: relative paths come from git (`diff --name-only`), which
|
|
11656
|
+
* normalizes during ordinary adds, but a crafted index/pack/symlinked tree can
|
|
11657
|
+
* smuggle `..` segments that escape the temp root. Resolve against the temp dir
|
|
11658
|
+
* and reject anything that lands outside before writing.
|
|
11569
11659
|
*/
|
|
11570
11660
|
const isPathInsideDirectory = (childAbsolutePath, parentAbsolutePath) => {
|
|
11571
|
-
const relative = path
|
|
11572
|
-
return Boolean(relative) && !relative.startsWith("..") && !path
|
|
11661
|
+
const relative = path.relative(parentAbsolutePath, childAbsolutePath);
|
|
11662
|
+
return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
11573
11663
|
};
|
|
11574
11664
|
/**
|
|
11665
|
+
* Writes a set of source files (supplied by `readContent` — e.g.
|
|
11666
|
+
* `git show <ref>:<path>` for a baseline tree, or `git show :<path>` for the
|
|
11667
|
+
* index) into a temp tree that mirrors the project layout, copying the
|
|
11668
|
+
* well-known project-config files from `directory` so oxlint resolves
|
|
11669
|
+
* tsconfig / lint config identically to the working tree. Shared by the staged
|
|
11670
|
+
* and baseline scan paths so the zip-slip guard lives in one audited place.
|
|
11671
|
+
* Per-file read failures skip that file (the scan proceeds with whatever read
|
|
11672
|
+
* cleanly) rather than sinking the whole snapshot.
|
|
11673
|
+
*/
|
|
11674
|
+
const materializeSourceTree = (input) => Effect.gen(function* () {
|
|
11675
|
+
const materializedFiles = [];
|
|
11676
|
+
const resolvedTempDirectory = path.resolve(input.tempDirectory);
|
|
11677
|
+
for (const relativePath of input.files) {
|
|
11678
|
+
const content = yield* input.readContent(relativePath).pipe(Effect.orElseSucceed(() => null));
|
|
11679
|
+
if (content === null) continue;
|
|
11680
|
+
const candidateTargetPath = path.resolve(resolvedTempDirectory, relativePath);
|
|
11681
|
+
if (!isPathInsideDirectory(candidateTargetPath, resolvedTempDirectory)) continue;
|
|
11682
|
+
yield* Effect.sync(() => {
|
|
11683
|
+
fs.mkdirSync(path.dirname(candidateTargetPath), { recursive: true });
|
|
11684
|
+
fs.writeFileSync(candidateTargetPath, content);
|
|
11685
|
+
});
|
|
11686
|
+
materializedFiles.push(relativePath);
|
|
11687
|
+
}
|
|
11688
|
+
yield* Effect.sync(() => {
|
|
11689
|
+
for (const configFilename of STAGED_FILES_PROJECT_CONFIG_FILENAMES) {
|
|
11690
|
+
const sourcePath = path.join(input.directory, configFilename);
|
|
11691
|
+
const targetPath = path.join(resolvedTempDirectory, configFilename);
|
|
11692
|
+
if (fs.existsSync(sourcePath) && !fs.existsSync(targetPath)) fs.cpSync(sourcePath, targetPath);
|
|
11693
|
+
}
|
|
11694
|
+
});
|
|
11695
|
+
return {
|
|
11696
|
+
tempDirectory: input.tempDirectory,
|
|
11697
|
+
materializedFiles,
|
|
11698
|
+
cleanup: () => {
|
|
11699
|
+
try {
|
|
11700
|
+
fs.rmSync(input.tempDirectory, {
|
|
11701
|
+
recursive: true,
|
|
11702
|
+
force: true
|
|
11703
|
+
});
|
|
11704
|
+
} catch {}
|
|
11705
|
+
}
|
|
11706
|
+
};
|
|
11707
|
+
});
|
|
11708
|
+
/**
|
|
11575
11709
|
* `StagedFiles` materializes the git-staged source files of a
|
|
11576
11710
|
* directory into a temp tree (mirroring the project layout and
|
|
11577
11711
|
* carrying over a fixed set of project config files) so oxlint can
|
|
@@ -11588,40 +11722,16 @@ var StagedFiles = class StagedFiles extends Context.Service()("react-doctor/Stag
|
|
|
11588
11722
|
const git = yield* Git;
|
|
11589
11723
|
return StagedFiles.of({
|
|
11590
11724
|
discoverSourceFiles: (directory) => git.stagedFilePaths(directory).pipe(Effect.map((entries) => entries.filter(isLintableSourceFile))),
|
|
11591
|
-
materialize: ({ directory, stagedFiles, tempDirectory }) =>
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
|
|
11598
|
-
|
|
11599
|
-
|
|
11600
|
-
|
|
11601
|
-
fs$1.writeFileSync(candidateTargetPath, content);
|
|
11602
|
-
});
|
|
11603
|
-
materializedFiles.push(relativePath);
|
|
11604
|
-
}
|
|
11605
|
-
yield* Effect.sync(() => {
|
|
11606
|
-
for (const configFilename of STAGED_FILES_PROJECT_CONFIG_FILENAMES) {
|
|
11607
|
-
const sourcePath = path$1.join(directory, configFilename);
|
|
11608
|
-
const targetPath = path$1.join(resolvedTempDirectory, configFilename);
|
|
11609
|
-
if (fs$1.existsSync(sourcePath) && !fs$1.existsSync(targetPath)) fs$1.cpSync(sourcePath, targetPath);
|
|
11610
|
-
}
|
|
11611
|
-
});
|
|
11612
|
-
return {
|
|
11613
|
-
tempDirectory,
|
|
11614
|
-
stagedFiles: materializedFiles,
|
|
11615
|
-
cleanup: () => {
|
|
11616
|
-
try {
|
|
11617
|
-
fs$1.rmSync(tempDirectory, {
|
|
11618
|
-
recursive: true,
|
|
11619
|
-
force: true
|
|
11620
|
-
});
|
|
11621
|
-
} catch {}
|
|
11622
|
-
}
|
|
11623
|
-
};
|
|
11624
|
-
})
|
|
11725
|
+
materialize: ({ directory, stagedFiles, tempDirectory }) => materializeSourceTree({
|
|
11726
|
+
directory,
|
|
11727
|
+
files: stagedFiles,
|
|
11728
|
+
tempDirectory,
|
|
11729
|
+
readContent: (relativePath) => git.showStagedContent(directory, relativePath, { maxBufferBytes: GIT_SHOW_MAX_BUFFER_BYTES })
|
|
11730
|
+
}).pipe(Effect.map((tree) => ({
|
|
11731
|
+
tempDirectory: tree.tempDirectory,
|
|
11732
|
+
stagedFiles: tree.materializedFiles,
|
|
11733
|
+
cleanup: tree.cleanup
|
|
11734
|
+
})))
|
|
11625
11735
|
});
|
|
11626
11736
|
}));
|
|
11627
11737
|
/**
|
|
@@ -11668,18 +11778,22 @@ const safeGetErrorChain = (error) => {
|
|
|
11668
11778
|
};
|
|
11669
11779
|
const buildJsonReportError = (input) => {
|
|
11670
11780
|
const chain = safeGetErrorChain(input.error);
|
|
11781
|
+
const sentryEventId = input.sentryEventId ?? null;
|
|
11671
11782
|
const errorPayload = isReactDoctorError(input.error) ? {
|
|
11672
11783
|
message: formatReactDoctorError(input.error),
|
|
11673
11784
|
name: `ReactDoctorError(${input.error.reason._tag})`,
|
|
11674
|
-
chain
|
|
11785
|
+
chain,
|
|
11786
|
+
sentryEventId
|
|
11675
11787
|
} : input.error instanceof Error ? {
|
|
11676
11788
|
message: input.error.message || input.error.name || "Error",
|
|
11677
11789
|
name: input.error.name || "Error",
|
|
11678
|
-
chain
|
|
11790
|
+
chain,
|
|
11791
|
+
sentryEventId
|
|
11679
11792
|
} : {
|
|
11680
11793
|
message: safeStringify(input.error),
|
|
11681
11794
|
name: "Error",
|
|
11682
|
-
chain
|
|
11795
|
+
chain,
|
|
11796
|
+
sentryEventId
|
|
11683
11797
|
};
|
|
11684
11798
|
return {
|
|
11685
11799
|
schemaVersion: 1,
|
|
@@ -11755,12 +11869,10 @@ const buildJsonReport = (input) => {
|
|
|
11755
11869
|
const flattenedDiagnostics = projects.flatMap((entry) => entry.diagnostics);
|
|
11756
11870
|
const worstScoredProject = findWorstScoredProject(projects);
|
|
11757
11871
|
const summary = summarizeDiagnostics(flattenedDiagnostics, worstScoredProject?.score?.score ?? null, worstScoredProject?.score?.label ?? null);
|
|
11758
|
-
|
|
11759
|
-
schemaVersion: 1,
|
|
11872
|
+
const shared = {
|
|
11760
11873
|
version: input.version,
|
|
11761
11874
|
ok: true,
|
|
11762
11875
|
directory: input.directory,
|
|
11763
|
-
mode: input.mode,
|
|
11764
11876
|
diff: toJsonDiff(input.diff),
|
|
11765
11877
|
projects,
|
|
11766
11878
|
diagnostics: flattenedDiagnostics,
|
|
@@ -11768,6 +11880,22 @@ const buildJsonReport = (input) => {
|
|
|
11768
11880
|
elapsedMilliseconds: input.totalElapsedMilliseconds,
|
|
11769
11881
|
error: null
|
|
11770
11882
|
};
|
|
11883
|
+
if (input.baseline) return {
|
|
11884
|
+
schemaVersion: 2,
|
|
11885
|
+
mode: "baseline",
|
|
11886
|
+
baseline: {
|
|
11887
|
+
baseRef: input.baseline.baseRef,
|
|
11888
|
+
newCount: summary.totalDiagnosticCount,
|
|
11889
|
+
fixedCount: input.baseline.fixedCount,
|
|
11890
|
+
baseTotalCount: input.baseline.baseTotalCount
|
|
11891
|
+
},
|
|
11892
|
+
...shared
|
|
11893
|
+
};
|
|
11894
|
+
return {
|
|
11895
|
+
schemaVersion: 1,
|
|
11896
|
+
mode: input.mode,
|
|
11897
|
+
...shared
|
|
11898
|
+
};
|
|
11771
11899
|
};
|
|
11772
11900
|
/**
|
|
11773
11901
|
* Single source of truth for the skipped-check accounting shared by the
|
|
@@ -11789,6 +11917,45 @@ const buildSkippedChecks = (input) => {
|
|
|
11789
11917
|
skippedCheckReasons
|
|
11790
11918
|
};
|
|
11791
11919
|
};
|
|
11920
|
+
const fingerprintDiagnostic = (diagnostic, lineText) => {
|
|
11921
|
+
const ruleKey = `${diagnostic.plugin}/${diagnostic.rule}`;
|
|
11922
|
+
const snippet = lineText === null ? "" : createHash("sha1").update(lineText.trim()).digest("hex");
|
|
11923
|
+
return `${diagnostic.filePath}\u0000${ruleKey}\u0000${snippet}`;
|
|
11924
|
+
};
|
|
11925
|
+
/**
|
|
11926
|
+
* Diffs a head scan against a base scan to isolate the diagnostics a change
|
|
11927
|
+
* introduced (and count the ones it resolved). Matching is a multiset over a
|
|
11928
|
+
* position-independent fingerprint — `(filePath, plugin/rule, hash(flagged
|
|
11929
|
+
* line text))` — so inserting lines above an existing issue doesn't make it
|
|
11930
|
+
* look new, while a genuinely new occurrence (new line text, or one more of
|
|
11931
|
+
* the same) surfaces. Identical repeated findings are matched by count.
|
|
11932
|
+
*
|
|
11933
|
+
* v1 limitation: the fingerprint keys on the head-relative `filePath`, and base
|
|
11934
|
+
* content is read at that same path. A file renamed by the change therefore has
|
|
11935
|
+
* no base match, so its pre-existing findings are reported as new. This
|
|
11936
|
+
* over-reports (never hides a real issue) and is rare; rename-aware base
|
|
11937
|
+
* resolution is a follow-up.
|
|
11938
|
+
*/
|
|
11939
|
+
const computeDiagnosticDelta = (input) => {
|
|
11940
|
+
const unmatchedBaseByFingerprint = /* @__PURE__ */ new Map();
|
|
11941
|
+
for (const diagnostic of input.baseDiagnostics) {
|
|
11942
|
+
const key = fingerprintDiagnostic(diagnostic, input.readBaseLine(diagnostic.filePath, diagnostic.line));
|
|
11943
|
+
unmatchedBaseByFingerprint.set(key, (unmatchedBaseByFingerprint.get(key) ?? 0) + 1);
|
|
11944
|
+
}
|
|
11945
|
+
const newDiagnostics = [];
|
|
11946
|
+
for (const diagnostic of input.headDiagnostics) {
|
|
11947
|
+
const key = fingerprintDiagnostic(diagnostic, input.readHeadLine(diagnostic.filePath, diagnostic.line));
|
|
11948
|
+
const availableMatches = unmatchedBaseByFingerprint.get(key) ?? 0;
|
|
11949
|
+
if (availableMatches > 0) unmatchedBaseByFingerprint.set(key, availableMatches - 1);
|
|
11950
|
+
else newDiagnostics.push(diagnostic);
|
|
11951
|
+
}
|
|
11952
|
+
let fixedCount = 0;
|
|
11953
|
+
for (const remaining of unmatchedBaseByFingerprint.values()) fixedCount += remaining;
|
|
11954
|
+
return {
|
|
11955
|
+
newDiagnostics,
|
|
11956
|
+
fixedCount
|
|
11957
|
+
};
|
|
11958
|
+
};
|
|
11792
11959
|
/**
|
|
11793
11960
|
* Programmatic façade over `Git.diffSelection`. Async because the
|
|
11794
11961
|
* Git service runs through Effect's `ChildProcess` (true subprocess
|
|
@@ -11811,6 +11978,7 @@ const getDiffInfo = (directory, explicitBaseBranch) => Effect.runPromise(Effect.
|
|
|
11811
11978
|
return {
|
|
11812
11979
|
currentBranch: selection.currentBranch,
|
|
11813
11980
|
baseBranch: selection.baseBranch,
|
|
11981
|
+
...selection.diffBaseRef !== void 0 ? { diffBaseRef: selection.diffBaseRef } : {},
|
|
11814
11982
|
changedFiles: [...selection.changedFiles],
|
|
11815
11983
|
...selection.isCurrentChanges ? { isCurrentChanges: true } : {}
|
|
11816
11984
|
};
|
|
@@ -11870,10 +12038,9 @@ const CI_PROVIDER_BY_ENVIRONMENT_VARIABLE = [
|
|
|
11870
12038
|
];
|
|
11871
12039
|
const GITHUB_ACTION_MARKER_ENVIRONMENT_VARIABLE = "REACT_DOCTOR_GITHUB_ACTION";
|
|
11872
12040
|
const ACTION_INPUT_ENVIRONMENT_VARIABLES = {
|
|
11873
|
-
|
|
11874
|
-
nonBlocking: "REACT_DOCTOR_ACTION_NON_BLOCKING",
|
|
12041
|
+
blocking: "REACT_DOCTOR_ACTION_BLOCKING",
|
|
11875
12042
|
comment: "REACT_DOCTOR_ACTION_COMMENT",
|
|
11876
|
-
|
|
12043
|
+
reviewComments: "REACT_DOCTOR_ACTION_REVIEW_COMMENTS",
|
|
11877
12044
|
version: "REACT_DOCTOR_ACTION_VERSION"
|
|
11878
12045
|
};
|
|
11879
12046
|
const CODING_AGENT_BY_ENVIRONMENT_VARIABLE = [
|
|
@@ -11945,6 +12112,7 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
|
|
|
11945
12112
|
//#endregion
|
|
11946
12113
|
//#region src/cli/utils/constants.ts
|
|
11947
12114
|
const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
|
|
12115
|
+
const BASELINE_FILES_TEMP_DIR_PREFIX = "react-doctor-baseline-";
|
|
11948
12116
|
const CI_TRUST_COMPANIES = "PayPal, Rippling, and Alibaba";
|
|
11949
12117
|
const WELCOME_EXPLANATION_HOLD_MS = 1e3;
|
|
11950
12118
|
const CATEGORY_COUNTUP_SETTLE_HOLD_MS = 1e3;
|
|
@@ -11962,6 +12130,7 @@ const METRIC = {
|
|
|
11962
12130
|
scanScore: "scan.score",
|
|
11963
12131
|
scanClean: "scan.clean",
|
|
11964
12132
|
scanCheckSkipped: "scan.check_skipped",
|
|
12133
|
+
baselineDegraded: "baseline.degraded",
|
|
11965
12134
|
ruleFired: "rule.fired",
|
|
11966
12135
|
lintFailed: "lint.failed",
|
|
11967
12136
|
deadCodeFailed: "deadcode.failed",
|
|
@@ -11976,7 +12145,11 @@ const METRIC = {
|
|
|
11976
12145
|
installAgentHooks: "install.agent_hooks",
|
|
11977
12146
|
installDependency: "install.dependency",
|
|
11978
12147
|
rulesChanged: "rules.changed",
|
|
11979
|
-
rulesQueried: "rules.queried"
|
|
12148
|
+
rulesQueried: "rules.queried",
|
|
12149
|
+
lspSessionStarted: "lsp.session.started",
|
|
12150
|
+
lspScanCompleted: "lsp.scan.completed",
|
|
12151
|
+
lspScanDuration: "lsp.scan.duration",
|
|
12152
|
+
lspScanDiagnostics: "lsp.scan.diagnostics"
|
|
11980
12153
|
};
|
|
11981
12154
|
//#endregion
|
|
11982
12155
|
//#region src/cli/utils/noop-console.ts
|
|
@@ -12019,7 +12192,7 @@ const makeNoopConsole = () => ({
|
|
|
12019
12192
|
});
|
|
12020
12193
|
//#endregion
|
|
12021
12194
|
//#region src/cli/utils/version.ts
|
|
12022
|
-
const VERSION = "0.
|
|
12195
|
+
const VERSION = "0.4.0-dev.36ecd05";
|
|
12023
12196
|
//#endregion
|
|
12024
12197
|
//#region src/cli/utils/json-mode.ts
|
|
12025
12198
|
let context = null;
|
|
@@ -12077,7 +12250,7 @@ const writeJsonReport = (report) => {
|
|
|
12077
12250
|
const serialized = context?.compact ? JSON.stringify(report) : JSON.stringify(report, null, 2);
|
|
12078
12251
|
process.stdout.write(`${serialized}\n`);
|
|
12079
12252
|
};
|
|
12080
|
-
const writeJsonErrorReport = (error) => {
|
|
12253
|
+
const writeJsonErrorReport = (error, sentryEventId) => {
|
|
12081
12254
|
if (!context) return;
|
|
12082
12255
|
try {
|
|
12083
12256
|
writeJsonReport(buildJsonReportError({
|
|
@@ -12085,7 +12258,8 @@ const writeJsonErrorReport = (error) => {
|
|
|
12085
12258
|
directory: context.directory,
|
|
12086
12259
|
error,
|
|
12087
12260
|
elapsedMilliseconds: performance.now() - context.startTime,
|
|
12088
|
-
mode: context.mode
|
|
12261
|
+
mode: context.mode,
|
|
12262
|
+
sentryEventId
|
|
12089
12263
|
}));
|
|
12090
12264
|
} catch {
|
|
12091
12265
|
process.stdout.write(INTERNAL_ERROR_JSON_FALLBACK);
|
|
@@ -12356,15 +12530,14 @@ const scrubSentryMetric = (metric) => {
|
|
|
12356
12530
|
}
|
|
12357
12531
|
};
|
|
12358
12532
|
//#endregion
|
|
12359
|
-
//#region src/
|
|
12360
|
-
|
|
12361
|
-
|
|
12362
|
-
|
|
12363
|
-
|
|
12364
|
-
|
|
12365
|
-
|
|
12366
|
-
|
|
12367
|
-
const isEnvFlagEnabled = (value) => value === "1" || value?.toLowerCase() === "true";
|
|
12533
|
+
//#region src/cli/utils/sentry-config.ts
|
|
12534
|
+
/**
|
|
12535
|
+
* Shared Sentry configuration resolution — release, environment, and tracing
|
|
12536
|
+
* sample rate — derived from `VERSION` and the standard `SENTRY_*` env
|
|
12537
|
+
* overrides. Lives apart from `instrument.ts` (the CLI's run-context-aware
|
|
12538
|
+
* init) so both the CLI and the editor language server can resolve identical
|
|
12539
|
+
* release/environment values without the LSP pulling in CLI run-context code.
|
|
12540
|
+
*/
|
|
12368
12541
|
/**
|
|
12369
12542
|
* A version is a "dev" build when it's the unbuilt placeholder (`0.0.0`) or
|
|
12370
12543
|
* carries a prerelease suffix (e.g. the `-dev.<sha>` snapshots published from
|
|
@@ -12377,13 +12550,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
|
|
|
12377
12550
|
* uploads source-map artifacts under, so stack frames symbolicate. Honors the
|
|
12378
12551
|
* standard `SENTRY_RELEASE` override.
|
|
12379
12552
|
*/
|
|
12380
|
-
const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.
|
|
12553
|
+
const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.0-dev.36ecd05`;
|
|
12381
12554
|
/**
|
|
12382
12555
|
* Deployment environment shown in Sentry's environment filter. Defaults to
|
|
12383
12556
|
* `production` for tagged releases and `development` for dev/unbuilt versions,
|
|
12384
12557
|
* overridable via the standard `SENTRY_ENVIRONMENT` env var.
|
|
12385
12558
|
*/
|
|
12386
|
-
const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.
|
|
12559
|
+
const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.0-dev.36ecd05") ? "development" : "production");
|
|
12387
12560
|
/**
|
|
12388
12561
|
* Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
|
|
12389
12562
|
* (set to `0` to disable tracing) and falls back to
|
|
@@ -12397,6 +12570,16 @@ const resolveTracesSampleRate = () => {
|
|
|
12397
12570
|
if (Number.isNaN(parsed) || parsed < 0 || parsed > 1) return 1;
|
|
12398
12571
|
return parsed;
|
|
12399
12572
|
};
|
|
12573
|
+
//#endregion
|
|
12574
|
+
//#region src/instrument.ts
|
|
12575
|
+
let isInitialized = false;
|
|
12576
|
+
let resolvedTracesSampleRate = 0;
|
|
12577
|
+
const shouldEnableSentry = () => {
|
|
12578
|
+
if (process.argv.includes("--no-score") || process.argv.includes("--no-telemetry")) return false;
|
|
12579
|
+
if (process.env.VITEST || process.env.NODE_ENV === "test") return false;
|
|
12580
|
+
return true;
|
|
12581
|
+
};
|
|
12582
|
+
const isEnvFlagEnabled = (value) => value === "1" || value?.toLowerCase() === "true";
|
|
12400
12583
|
/**
|
|
12401
12584
|
* Whether performance traces will actually be recorded — Sentry is live and the
|
|
12402
12585
|
* resolved sample rate is above zero. Used to gate the per-run root span and
|
|
@@ -15838,6 +16021,7 @@ const recordScanMetrics = (input) => {
|
|
|
15838
16021
|
if (result.diagnostics.length === 0 && !hasSkippedChecks) recordCount(METRIC.scanClean, 1, { mode: input.mode });
|
|
15839
16022
|
if (result.score) recordDistribution(METRIC.scanScore, result.score.score, { attributes: { mode: input.mode } });
|
|
15840
16023
|
else if (!input.noScore && !input.didLintFail) recordCount(METRIC.scoreUnavailable, 1, { mode: input.mode });
|
|
16024
|
+
if (input.baselineDegraded) recordCount(METRIC.baselineDegraded, 1);
|
|
15841
16025
|
if (input.didLintFail) recordCount(METRIC.lintFailed, 1, { reasonKind: input.lintFailureReasonKind });
|
|
15842
16026
|
if (input.didDeadCodeFail) recordCount(METRIC.deadCodeFailed, 1);
|
|
15843
16027
|
for (const check of result.skippedChecks) recordCount(METRIC.scanCheckSkipped, 1, {
|
|
@@ -15846,19 +16030,74 @@ const recordScanMetrics = (input) => {
|
|
|
15846
16030
|
});
|
|
15847
16031
|
};
|
|
15848
16032
|
//#endregion
|
|
15849
|
-
//#region src/cli/utils/
|
|
15850
|
-
|
|
15851
|
-
|
|
15852
|
-
|
|
15853
|
-
|
|
16033
|
+
//#region src/cli/utils/cli-logger.ts
|
|
16034
|
+
/**
|
|
16035
|
+
* Thin synchronous façade over Effect's `Console` module. Used by
|
|
16036
|
+
* the imperative CLI helper files (`select-projects`, `run-explain`,
|
|
16037
|
+
* `install-react-doctor`, the legacy paths in `cli/commands/inspect.ts`)
|
|
16038
|
+
* that aren't yet Effect-typed. Every call drains into a single
|
|
16039
|
+
* `Console.*` Effect via `Effect.runSync`, so the underlying logging
|
|
16040
|
+
* pipeline is identical to the canonical `yield* Console.log(...)`
|
|
16041
|
+
* call sites in the renderers. Convert callers to `Effect.gen` to
|
|
16042
|
+
* drop the bridge.
|
|
16043
|
+
*/
|
|
16044
|
+
const cliLogger = {
|
|
16045
|
+
log: (message) => {
|
|
16046
|
+
Effect.runSync(Console.log(message));
|
|
16047
|
+
},
|
|
16048
|
+
warn: (message) => {
|
|
16049
|
+
Effect.runSync(Console.warn(highlighter.warn(message)));
|
|
16050
|
+
},
|
|
16051
|
+
error: (message) => {
|
|
16052
|
+
Effect.runSync(Console.error(highlighter.error(message)));
|
|
16053
|
+
},
|
|
16054
|
+
info: (message) => {
|
|
16055
|
+
Effect.runSync(Console.info(highlighter.info(message)));
|
|
16056
|
+
},
|
|
16057
|
+
dim: (message) => {
|
|
16058
|
+
Effect.runSync(Console.log(highlighter.gray(message)));
|
|
16059
|
+
},
|
|
16060
|
+
success: (message) => {
|
|
16061
|
+
Effect.runSync(Console.log(highlighter.success(message)));
|
|
16062
|
+
},
|
|
16063
|
+
break: () => {
|
|
16064
|
+
Effect.runSync(Console.log(""));
|
|
16065
|
+
}
|
|
15854
16066
|
};
|
|
15855
16067
|
//#endregion
|
|
15856
|
-
//#region src/cli/utils/
|
|
15857
|
-
const
|
|
16068
|
+
//#region src/cli/utils/resolve-blocking-level.ts
|
|
16069
|
+
const VALID_BLOCKING_LEVELS = new Set([
|
|
15858
16070
|
"error",
|
|
15859
16071
|
"warning",
|
|
15860
16072
|
"none"
|
|
15861
16073
|
]);
|
|
16074
|
+
const DEFAULT_BLOCKING_LEVEL = "error";
|
|
16075
|
+
const isValidBlockingLevel = (level) => VALID_BLOCKING_LEVELS.has(level);
|
|
16076
|
+
const pickBlockingLevel = (flags, userConfig) => flags.blocking ?? flags.failOn ?? userConfig?.blocking ?? userConfig?.failOn;
|
|
16077
|
+
const resolveBlockingLevel = (flags, userConfig) => {
|
|
16078
|
+
const sourceValue = pickBlockingLevel(flags, userConfig) ?? DEFAULT_BLOCKING_LEVEL;
|
|
16079
|
+
if (isValidBlockingLevel(sourceValue)) return sourceValue;
|
|
16080
|
+
cliLogger.warn(`Invalid blocking level "${sourceValue}". Expected one of: error, warning, none. Falling back to "${DEFAULT_BLOCKING_LEVEL}".`);
|
|
16081
|
+
return DEFAULT_BLOCKING_LEVEL;
|
|
16082
|
+
};
|
|
16083
|
+
//#endregion
|
|
16084
|
+
//#region src/cli/utils/should-block-ci.ts
|
|
16085
|
+
const shouldBlockCi = (diagnostics, blockingLevel) => {
|
|
16086
|
+
if (blockingLevel === "none") return false;
|
|
16087
|
+
if (blockingLevel === "warning") return diagnostics.length > 0;
|
|
16088
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
16089
|
+
};
|
|
16090
|
+
//#endregion
|
|
16091
|
+
//#region src/cli/utils/to-category-key.ts
|
|
16092
|
+
/**
|
|
16093
|
+
* Lowercase, key-safe form of a rule category for the `diag.category.*`
|
|
16094
|
+
* telemetry attribute namespace (categories carry spaces / capitals, e.g.
|
|
16095
|
+
* "Performance" → `performance`, "Dead Code" → `dead_code`). Shared by the
|
|
16096
|
+
* CLI run event and the editor LSP wide event so both namespace identically.
|
|
16097
|
+
*/
|
|
16098
|
+
const toCategoryKey = (category) => category.toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
16099
|
+
//#endregion
|
|
16100
|
+
//#region src/cli/utils/build-run-event.ts
|
|
15862
16101
|
const readEnvBoolean = (name) => {
|
|
15863
16102
|
const value = process.env[name];
|
|
15864
16103
|
if (value === void 0) return null;
|
|
@@ -15870,12 +16109,11 @@ const resolveVersionPin = (versionInput) => {
|
|
|
15870
16109
|
if (/^(\.\.?\/|\/)/.test(versionInput)) return "local";
|
|
15871
16110
|
return "pinned";
|
|
15872
16111
|
};
|
|
15873
|
-
const
|
|
15874
|
-
const fromAction = process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.
|
|
15875
|
-
if (fromAction !== void 0 &&
|
|
15876
|
-
return userConfig?.failOn ?? "
|
|
16112
|
+
const resolveTelemetryBlocking = (userConfig) => {
|
|
16113
|
+
const fromAction = process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.blocking];
|
|
16114
|
+
if (fromAction !== void 0 && isValidBlockingLevel(fromAction)) return fromAction;
|
|
16115
|
+
return userConfig?.blocking ?? userConfig?.failOn ?? "error";
|
|
15877
16116
|
};
|
|
15878
|
-
const toCategoryKey = (category) => category.toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
15879
16117
|
const buildOutcomeAttributes = (input) => {
|
|
15880
16118
|
if (input.result === void 0) {
|
|
15881
16119
|
const error = input.error;
|
|
@@ -15889,9 +16127,9 @@ const buildOutcomeAttributes = (input) => {
|
|
|
15889
16127
|
}
|
|
15890
16128
|
const result = input.result;
|
|
15891
16129
|
const summary = summarizeDiagnostics(result.diagnostics);
|
|
15892
|
-
const
|
|
16130
|
+
const blockingLevel = resolveTelemetryBlocking(input.userConfig);
|
|
15893
16131
|
const gateDiagnostics = filterDiagnosticsForSurface(result.diagnostics, "ciFailure", input.userConfig);
|
|
15894
|
-
const wouldBlock = !input.scoreOnly &&
|
|
16132
|
+
const wouldBlock = !input.scoreOnly && !input.gateExempt && shouldBlockCi(gateDiagnostics, blockingLevel);
|
|
15895
16133
|
const hasSkippedChecks = result.skippedChecks.length > 0;
|
|
15896
16134
|
const isClean = result.diagnostics.length === 0 && !hasSkippedChecks;
|
|
15897
16135
|
const outcome = wouldBlock ? "blocked" : isClean ? "clean" : "ok";
|
|
@@ -15912,7 +16150,7 @@ const buildOutcomeAttributes = (input) => {
|
|
|
15912
16150
|
outcome,
|
|
15913
16151
|
exitCode: wouldBlock ? 1 : 0,
|
|
15914
16152
|
wouldBlock,
|
|
15915
|
-
|
|
16153
|
+
blocking: blockingLevel,
|
|
15916
16154
|
scanClean: isClean,
|
|
15917
16155
|
totalDiagnostics: summary.totalDiagnosticCount,
|
|
15918
16156
|
errorCount: summary.errorCount,
|
|
@@ -15933,6 +16171,12 @@ const buildOutcomeAttributes = (input) => {
|
|
|
15933
16171
|
didDeadCodeFail: input.didDeadCodeFail ?? null
|
|
15934
16172
|
};
|
|
15935
16173
|
for (const [category, count] of countByCategory) attributes[`diag.category.${toCategoryKey(category)}`] = count;
|
|
16174
|
+
if (result.baselineDelta) {
|
|
16175
|
+
attributes["baseline.new"] = summary.totalDiagnosticCount;
|
|
16176
|
+
attributes["baseline.fixed"] = result.baselineDelta.fixedCount;
|
|
16177
|
+
attributes["baseline.baseTotal"] = result.baselineDelta.baseTotalCount;
|
|
16178
|
+
attributes["baseline.degraded"] = false;
|
|
16179
|
+
} else if (input.gateExempt) attributes["baseline.degraded"] = true;
|
|
15936
16180
|
return attributes;
|
|
15937
16181
|
};
|
|
15938
16182
|
const buildCiAttributes = () => {
|
|
@@ -15940,9 +16184,8 @@ const buildCiAttributes = () => {
|
|
|
15940
16184
|
return {
|
|
15941
16185
|
actorAssociation: githubActorAssociation ?? null,
|
|
15942
16186
|
runnerOs: detectRunnerOs(),
|
|
15943
|
-
nonBlocking: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.nonBlocking),
|
|
15944
16187
|
comment: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.comment),
|
|
15945
|
-
|
|
16188
|
+
reviewComments: readEnvBoolean(ACTION_INPUT_ENVIRONMENT_VARIABLES.reviewComments),
|
|
15946
16189
|
versionPin: resolveVersionPin(process.env[ACTION_INPUT_ENVIRONMENT_VARIABLES.version])
|
|
15947
16190
|
};
|
|
15948
16191
|
};
|
|
@@ -15992,6 +16235,66 @@ const recordRunEvent = (rootSpan, input) => {
|
|
|
15992
16235
|
} catch {}
|
|
15993
16236
|
};
|
|
15994
16237
|
//#endregion
|
|
16238
|
+
//#region src/cli/utils/materialize-baseline-files.ts
|
|
16239
|
+
/**
|
|
16240
|
+
* Materializes the `ref` version of `files` into `tempDirectory` (via
|
|
16241
|
+
* `git show <ref>:<path>`), mirroring the project layout + head's config files
|
|
16242
|
+
* so the base lints under the same rules as head. Reuses the shared,
|
|
16243
|
+
* zip-slip-guarded `materializeSourceTree`. Per-file read misses (e.g. a file
|
|
16244
|
+
* the PR added, absent at base) are skipped, which is exactly what we want:
|
|
16245
|
+
* a brand-new file has no base counterpart, so all its findings are "new".
|
|
16246
|
+
*/
|
|
16247
|
+
const materializeBaselineFiles = (input) => Effect.runPromise(Effect.gen(function* () {
|
|
16248
|
+
const git = yield* Git;
|
|
16249
|
+
return yield* materializeSourceTree({
|
|
16250
|
+
directory: input.directory,
|
|
16251
|
+
files: input.files,
|
|
16252
|
+
tempDirectory: input.tempDirectory,
|
|
16253
|
+
readContent: (relativePath) => git.showRefContent({
|
|
16254
|
+
directory: input.directory,
|
|
16255
|
+
ref: input.ref,
|
|
16256
|
+
relativePath,
|
|
16257
|
+
options: { maxBufferBytes: GIT_SHOW_MAX_BUFFER_BYTES }
|
|
16258
|
+
})
|
|
16259
|
+
});
|
|
16260
|
+
}).pipe(Effect.provide(Git.layerNode)));
|
|
16261
|
+
/**
|
|
16262
|
+
* Resolves the commit a baseline scan should read base content from — the
|
|
16263
|
+
* merge-base of `ref` and HEAD, so "introduced" is measured against the branch
|
|
16264
|
+
* point. `null` when unresolvable (ref missing/unsafe, no merge-base).
|
|
16265
|
+
*/
|
|
16266
|
+
const resolveMergeBaseRef = async (directory, ref) => {
|
|
16267
|
+
try {
|
|
16268
|
+
return await Effect.runPromise(Effect.gen(function* () {
|
|
16269
|
+
return yield* (yield* Git).mergeBase({
|
|
16270
|
+
directory,
|
|
16271
|
+
ref
|
|
16272
|
+
});
|
|
16273
|
+
}).pipe(Effect.provide(Git.layerNode)));
|
|
16274
|
+
} catch {
|
|
16275
|
+
return null;
|
|
16276
|
+
}
|
|
16277
|
+
};
|
|
16278
|
+
//#endregion
|
|
16279
|
+
//#region src/cli/utils/read-source-line.ts
|
|
16280
|
+
/**
|
|
16281
|
+
* Builds a cached `(filePath, line) -> source text` reader rooted at
|
|
16282
|
+
* `rootDirectory`, used to fingerprint a diagnostic by the content of its
|
|
16283
|
+
* flagged line (see `computeDiagnosticDelta`). Wraps core's
|
|
16284
|
+
* `createNodeReadFileLinesSync` with per-file memoization + 1-indexed line
|
|
16285
|
+
* lookup; unreadable files / out-of-range lines return `null`.
|
|
16286
|
+
*/
|
|
16287
|
+
const createSourceLineReader = (rootDirectory) => {
|
|
16288
|
+
const readFileLines = createNodeReadFileLinesSync(rootDirectory);
|
|
16289
|
+
const fileLinesCache = /* @__PURE__ */ new Map();
|
|
16290
|
+
return (filePath, line) => {
|
|
16291
|
+
if (!fileLinesCache.has(filePath)) fileLinesCache.set(filePath, readFileLines(filePath));
|
|
16292
|
+
const lines = fileLinesCache.get(filePath) ?? null;
|
|
16293
|
+
if (lines === null || line < 1 || line > lines.length) return null;
|
|
16294
|
+
return lines[line - 1] ?? null;
|
|
16295
|
+
};
|
|
16296
|
+
};
|
|
16297
|
+
//#endregion
|
|
15995
16298
|
//#region src/cli/utils/build-no-score-message.ts
|
|
15996
16299
|
const ENTERPRISE_CONTACT_HINT = `Want something custom to your company? Contact us at ${ENTERPRISE_CONTACT_URL}.`;
|
|
15997
16300
|
const buildNoScoreMessage = (isScoreDisabled) => {
|
|
@@ -16450,10 +16753,10 @@ const canAnimateOnboarding = (stream = process.stdout) => {
|
|
|
16450
16753
|
};
|
|
16451
16754
|
//#endregion
|
|
16452
16755
|
//#region src/cli/utils/onboarding-state.ts
|
|
16453
|
-
const GLOBAL_CONFIG_PROJECT_NAME$
|
|
16756
|
+
const GLOBAL_CONFIG_PROJECT_NAME$2 = "react-doctor";
|
|
16454
16757
|
const ONBOARDED_AT_KEY = "onboardedAt";
|
|
16455
16758
|
const getOnboardingStore = (options = {}) => new Conf({
|
|
16456
|
-
projectName: GLOBAL_CONFIG_PROJECT_NAME$
|
|
16759
|
+
projectName: GLOBAL_CONFIG_PROJECT_NAME$2,
|
|
16457
16760
|
cwd: options.cwd
|
|
16458
16761
|
});
|
|
16459
16762
|
const hasCompletedOnboarding = (options = {}) => {
|
|
@@ -16735,41 +17038,6 @@ const printSummary = (input) => Effect.gen(function* () {
|
|
|
16735
17038
|
if (diagnosticsDirectory !== null && input.verbose) yield* Console.log(highlighter.gray(` Full diagnostics written to ${diagnosticsDirectory}`));
|
|
16736
17039
|
});
|
|
16737
17040
|
//#endregion
|
|
16738
|
-
//#region src/cli/utils/cli-logger.ts
|
|
16739
|
-
/**
|
|
16740
|
-
* Thin synchronous façade over Effect's `Console` module. Used by
|
|
16741
|
-
* the imperative CLI helper files (`select-projects`, `run-explain`,
|
|
16742
|
-
* `install-react-doctor`, the legacy paths in `cli/commands/inspect.ts`)
|
|
16743
|
-
* that aren't yet Effect-typed. Every call drains into a single
|
|
16744
|
-
* `Console.*` Effect via `Effect.runSync`, so the underlying logging
|
|
16745
|
-
* pipeline is identical to the canonical `yield* Console.log(...)`
|
|
16746
|
-
* call sites in the renderers. Convert callers to `Effect.gen` to
|
|
16747
|
-
* drop the bridge.
|
|
16748
|
-
*/
|
|
16749
|
-
const cliLogger = {
|
|
16750
|
-
log: (message) => {
|
|
16751
|
-
Effect.runSync(Console.log(message));
|
|
16752
|
-
},
|
|
16753
|
-
warn: (message) => {
|
|
16754
|
-
Effect.runSync(Console.warn(highlighter.warn(message)));
|
|
16755
|
-
},
|
|
16756
|
-
error: (message) => {
|
|
16757
|
-
Effect.runSync(Console.error(highlighter.error(message)));
|
|
16758
|
-
},
|
|
16759
|
-
info: (message) => {
|
|
16760
|
-
Effect.runSync(Console.info(highlighter.info(message)));
|
|
16761
|
-
},
|
|
16762
|
-
dim: (message) => {
|
|
16763
|
-
Effect.runSync(Console.log(highlighter.gray(message)));
|
|
16764
|
-
},
|
|
16765
|
-
success: (message) => {
|
|
16766
|
-
Effect.runSync(Console.log(highlighter.success(message)));
|
|
16767
|
-
},
|
|
16768
|
-
break: () => {
|
|
16769
|
-
Effect.runSync(Console.log(""));
|
|
16770
|
-
}
|
|
16771
|
-
};
|
|
16772
|
-
//#endregion
|
|
16773
17041
|
//#region src/cli/utils/should-auto-select-current-choice.ts
|
|
16774
17042
|
const shouldAutoSelectCurrentChoice = (choiceStates, cursor) => {
|
|
16775
17043
|
if (choiceStates.some((choiceState) => choiceState.selected)) return false;
|
|
@@ -16912,7 +17180,8 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
|
|
|
16912
17180
|
ignoredTags: buildIgnoredTags(userConfig),
|
|
16913
17181
|
outputSurface: inputOptions.outputSurface ?? "cli",
|
|
16914
17182
|
suppressRendering: inputOptions.suppressRendering ?? false,
|
|
16915
|
-
concurrency: inputOptions.concurrency
|
|
17183
|
+
concurrency: inputOptions.concurrency,
|
|
17184
|
+
baseline: inputOptions.baseline ?? null
|
|
16916
17185
|
});
|
|
16917
17186
|
const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
|
|
16918
17187
|
parallel: options.concurrency !== void 0,
|
|
@@ -16966,6 +17235,75 @@ const inspect = async (directory, inputOptions = {}) => {
|
|
|
16966
17235
|
if (options.silent) setSpinnerSilent(wasSpinnerSilent);
|
|
16967
17236
|
}
|
|
16968
17237
|
};
|
|
17238
|
+
/**
|
|
17239
|
+
* Runs a second, lint-only scan over the changed files as they existed at the
|
|
17240
|
+
* baseline ref (materialized into a temp tree with head's config) and diffs it
|
|
17241
|
+
* against the head diagnostics, returning only the findings the change
|
|
17242
|
+
* introduced plus the fixed / base counts. No score, dead-code, progress, or
|
|
17243
|
+
* telemetry — it's a pure comparison pass. The temp tree is always cleaned up.
|
|
17244
|
+
*/
|
|
17245
|
+
const runBaselineComparison = async (params) => {
|
|
17246
|
+
const tempDirectory = mkdtempSync(path.join(tmpdir(), BASELINE_FILES_TEMP_DIR_PREFIX));
|
|
17247
|
+
const snapshot = await materializeBaselineFiles({
|
|
17248
|
+
directory: params.directory,
|
|
17249
|
+
ref: params.baselineRef,
|
|
17250
|
+
files: params.options.includePaths,
|
|
17251
|
+
tempDirectory
|
|
17252
|
+
}).catch((error) => {
|
|
17253
|
+
rmSync(tempDirectory, {
|
|
17254
|
+
recursive: true,
|
|
17255
|
+
force: true
|
|
17256
|
+
});
|
|
17257
|
+
throw error;
|
|
17258
|
+
});
|
|
17259
|
+
try {
|
|
17260
|
+
const baseLayers = buildRuntimeLayers({
|
|
17261
|
+
directory: snapshot.tempDirectory,
|
|
17262
|
+
hasConfigOverride: true,
|
|
17263
|
+
userConfig: params.userConfig,
|
|
17264
|
+
configSourceDirectory: null,
|
|
17265
|
+
shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
|
|
17266
|
+
shouldRunDeadCode: false,
|
|
17267
|
+
shouldComputeScore: false,
|
|
17268
|
+
shouldShowProgressSpinners: false,
|
|
17269
|
+
oxlintConcurrency: params.options.concurrency
|
|
17270
|
+
});
|
|
17271
|
+
const baseProgram = runInspect({
|
|
17272
|
+
directory: snapshot.tempDirectory,
|
|
17273
|
+
includePaths: params.options.includePaths,
|
|
17274
|
+
customRulesOnly: params.options.customRulesOnly,
|
|
17275
|
+
respectInlineDisables: params.options.respectInlineDisables,
|
|
17276
|
+
warnings: params.options.warnings,
|
|
17277
|
+
adoptExistingLintConfig: params.options.adoptExistingLintConfig,
|
|
17278
|
+
ignoredTags: params.options.ignoredTags,
|
|
17279
|
+
nodeBinaryPath: params.resolvedNodeBinaryPath ?? void 0,
|
|
17280
|
+
runDeadCode: false,
|
|
17281
|
+
isCi: params.options.isCi,
|
|
17282
|
+
doctorVersion: VERSION,
|
|
17283
|
+
runId: getRunId(),
|
|
17284
|
+
resolveLocalGithubViewerPermission: false,
|
|
17285
|
+
suppressScanSummary: true
|
|
17286
|
+
}, {});
|
|
17287
|
+
const baseOutput = await Effect.runPromise(restoreLegacyThrow(baseProgram.pipe(Effect.provide(baseLayers), Effect.provideService(Console.Console, silentConsole))));
|
|
17288
|
+
if (baseOutput.didLintFail) return null;
|
|
17289
|
+
const delta = computeDiagnosticDelta({
|
|
17290
|
+
headDiagnostics: params.headDiagnostics,
|
|
17291
|
+
baseDiagnostics: baseOutput.diagnostics,
|
|
17292
|
+
readHeadLine: createSourceLineReader(params.directory),
|
|
17293
|
+
readBaseLine: createSourceLineReader(snapshot.tempDirectory)
|
|
17294
|
+
});
|
|
17295
|
+
return {
|
|
17296
|
+
displayDiagnostics: delta.newDiagnostics,
|
|
17297
|
+
baselineDelta: {
|
|
17298
|
+
baseRef: params.baselineRef,
|
|
17299
|
+
fixedCount: delta.fixedCount,
|
|
17300
|
+
baseTotalCount: baseOutput.diagnostics.length
|
|
17301
|
+
}
|
|
17302
|
+
};
|
|
17303
|
+
} finally {
|
|
17304
|
+
snapshot.cleanup();
|
|
17305
|
+
}
|
|
17306
|
+
};
|
|
16969
17307
|
const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOverride, configSourceDirectory, startTime, rootSentrySpan) => {
|
|
16970
17308
|
const isDiffMode = options.includePaths.length > 0;
|
|
16971
17309
|
const resolvedNodeBinaryPath = await resolveOxlintNode(options.lint, options.scoreOnly || options.silent);
|
|
@@ -17016,7 +17354,23 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
|
|
|
17016
17354
|
const lintFailureReason = lintBindingMissing ? `oxlint native binding not found for Node ${process.version}; expected one matching ${OXLINT_NODE_REQUIREMENT}` : output.lintFailureReason;
|
|
17017
17355
|
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`)));
|
|
17018
17356
|
else runConsole(Console.error(highlighter.error(lintFailureReason)));
|
|
17019
|
-
|
|
17357
|
+
let inspectDiagnostics = output.diagnostics;
|
|
17358
|
+
let baselineDelta;
|
|
17359
|
+
if (options.baseline && isDiffMode && !didLintFail) {
|
|
17360
|
+
const comparison = await runBaselineComparison({
|
|
17361
|
+
directory,
|
|
17362
|
+
options,
|
|
17363
|
+
userConfig,
|
|
17364
|
+
headDiagnostics: output.diagnostics,
|
|
17365
|
+
resolvedNodeBinaryPath,
|
|
17366
|
+
baselineRef: options.baseline.ref
|
|
17367
|
+
});
|
|
17368
|
+
if (comparison) {
|
|
17369
|
+
inspectDiagnostics = comparison.displayDiagnostics;
|
|
17370
|
+
baselineDelta = comparison.baselineDelta;
|
|
17371
|
+
}
|
|
17372
|
+
}
|
|
17373
|
+
const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
|
|
17020
17374
|
const score = didLintFail ? null : output.score;
|
|
17021
17375
|
const elapsedMilliseconds = performance.now() - startTime;
|
|
17022
17376
|
const forceOnboarding = isOnboardingForced();
|
|
@@ -17036,7 +17390,8 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
|
|
|
17036
17390
|
directory: output.resolvedDirectory,
|
|
17037
17391
|
scannedFileCount: output.scannedFileCount,
|
|
17038
17392
|
scannedFilePaths: output.scannedFilePaths,
|
|
17039
|
-
scanElapsedMilliseconds: output.scanElapsedMilliseconds
|
|
17393
|
+
scanElapsedMilliseconds: output.scanElapsedMilliseconds,
|
|
17394
|
+
baselineDelta
|
|
17040
17395
|
};
|
|
17041
17396
|
const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
|
|
17042
17397
|
if (shouldRecordOnboarding({
|
|
@@ -17045,9 +17400,11 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
|
|
|
17045
17400
|
verbose: options.verbose,
|
|
17046
17401
|
isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
|
|
17047
17402
|
})) markOnboardingComplete();
|
|
17403
|
+
const scanMode = baselineDelta ? "baseline" : isDiffMode ? "diff" : "full";
|
|
17048
17404
|
recordScanMetrics({
|
|
17049
17405
|
result,
|
|
17050
|
-
mode:
|
|
17406
|
+
mode: scanMode,
|
|
17407
|
+
baselineDegraded,
|
|
17051
17408
|
parallel: options.concurrency !== void 0,
|
|
17052
17409
|
workerCount: options.concurrency,
|
|
17053
17410
|
lint: options.lint,
|
|
@@ -17061,7 +17418,8 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
|
|
|
17061
17418
|
recordRunEvent(rootSentrySpan, {
|
|
17062
17419
|
...buildRunEventConfig(options, userConfig, userConfig !== null),
|
|
17063
17420
|
result,
|
|
17064
|
-
mode:
|
|
17421
|
+
mode: scanMode,
|
|
17422
|
+
gateExempt: baselineDegraded,
|
|
17065
17423
|
didLintFail,
|
|
17066
17424
|
lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
|
|
17067
17425
|
lintPartialFailureCount: output.lintPartialFailures.length,
|
|
@@ -17070,7 +17428,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
|
|
|
17070
17428
|
return result;
|
|
17071
17429
|
};
|
|
17072
17430
|
const finalizeAndRender = (input) => Effect.gen(function* () {
|
|
17073
|
-
const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds } = input;
|
|
17431
|
+
const { options, elapsedMilliseconds, diagnostics, score, project, userConfig, didLintFail, lintFailureReason, lintPartialFailures, didDeadCodeFail, deadCodeFailureReason, directory, scannedFileCount, scannedFilePaths, scanElapsedMilliseconds, baselineDelta } = input;
|
|
17074
17432
|
const { skippedChecks, skippedCheckReasons } = buildSkippedChecks({
|
|
17075
17433
|
didLintFail,
|
|
17076
17434
|
lintFailureReason,
|
|
@@ -17089,7 +17447,8 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
|
|
|
17089
17447
|
elapsedMilliseconds,
|
|
17090
17448
|
scannedFileCount,
|
|
17091
17449
|
scannedFilePaths,
|
|
17092
|
-
scanElapsedMilliseconds
|
|
17450
|
+
scanElapsedMilliseconds,
|
|
17451
|
+
...baselineDelta ? { baselineDelta } : {}
|
|
17093
17452
|
});
|
|
17094
17453
|
if (options.suppressRendering) return buildResult();
|
|
17095
17454
|
if (options.scoreOnly) {
|
|
@@ -17361,9 +17720,9 @@ const buildHandoffPayload = (input) => {
|
|
|
17361
17720
|
};
|
|
17362
17721
|
//#endregion
|
|
17363
17722
|
//#region src/cli/utils/is-command-available.ts
|
|
17364
|
-
const isWindows = process.platform === "win32";
|
|
17723
|
+
const isWindows$1 = process.platform === "win32";
|
|
17365
17724
|
const candidateFileNames = (command) => {
|
|
17366
|
-
if (!isWindows || path$1.extname(command)) return [command];
|
|
17725
|
+
if (!isWindows$1 || path$1.extname(command)) return [command];
|
|
17367
17726
|
return [command, ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean).map((extension) => `${command}${extension}`)];
|
|
17368
17727
|
};
|
|
17369
17728
|
const isCommandAvailable = (command) => {
|
|
@@ -17372,7 +17731,7 @@ const isCommandAvailable = (command) => {
|
|
|
17372
17731
|
const binaryPath = path$1.join(directory, fileName);
|
|
17373
17732
|
try {
|
|
17374
17733
|
if (!fs$1.statSync(binaryPath).isFile()) continue;
|
|
17375
|
-
if (!isWindows) fs$1.accessSync(binaryPath, fs$1.constants.X_OK);
|
|
17734
|
+
if (!isWindows$1) fs$1.accessSync(binaryPath, fs$1.constants.X_OK);
|
|
17376
17735
|
return true;
|
|
17377
17736
|
} catch {}
|
|
17378
17737
|
}
|
|
@@ -17409,7 +17768,7 @@ const VITE_PLUS_HOOKS_PATH = ".vite-hooks";
|
|
|
17409
17768
|
const LEFTHOOK_CONFIG_FILES = ["lefthook.yml", "lefthook.yaml"];
|
|
17410
17769
|
const PRE_COMMIT_CONFIG_FILE = ".pre-commit-config.yaml";
|
|
17411
17770
|
const OVERCOMMIT_CONFIG_FILE = ".overcommit.yml";
|
|
17412
|
-
const REACT_DOCTOR_COMMAND = "react-doctor --staged --
|
|
17771
|
+
const REACT_DOCTOR_COMMAND = "react-doctor --staged --blocking warning";
|
|
17413
17772
|
const NON_BLOCKING_REACT_DOCTOR_COMMAND = [
|
|
17414
17773
|
"react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\");",
|
|
17415
17774
|
`if ${REACT_DOCTOR_COMMAND} > "$react_doctor_output" 2>&1; then`,
|
|
@@ -17678,22 +18037,22 @@ const buildAgentHookScript = () => [
|
|
|
17678
18037
|
"",
|
|
17679
18038
|
"run_react_doctor() {",
|
|
17680
18039
|
" if [ -x ./node_modules/.bin/react-doctor ]; then",
|
|
17681
|
-
" ./node_modules/.bin/react-doctor --verbose --diff --
|
|
18040
|
+
" ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
|
|
17682
18041
|
" return",
|
|
17683
18042
|
" fi",
|
|
17684
18043
|
"",
|
|
17685
18044
|
" if command -v react-doctor >/dev/null 2>&1; then",
|
|
17686
|
-
" react-doctor --verbose --diff --
|
|
18045
|
+
" react-doctor --verbose --diff --blocking warning --no-score",
|
|
17687
18046
|
" return",
|
|
17688
18047
|
" fi",
|
|
17689
18048
|
"",
|
|
17690
18049
|
" if command -v pnpm >/dev/null 2>&1; then",
|
|
17691
|
-
" pnpm dlx react-doctor@latest --verbose --diff --
|
|
18050
|
+
" pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
|
|
17692
18051
|
" return",
|
|
17693
18052
|
" fi",
|
|
17694
18053
|
"",
|
|
17695
18054
|
" if command -v npx >/dev/null 2>&1; then",
|
|
17696
|
-
" npx --yes react-doctor@latest --verbose --diff --
|
|
18055
|
+
" npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
|
|
17697
18056
|
" return",
|
|
17698
18057
|
" fi",
|
|
17699
18058
|
"",
|
|
@@ -17785,6 +18144,11 @@ permissions:
|
|
|
17785
18144
|
# comments (PRs are issues under the hood). Not exercised on \`push\`
|
|
17786
18145
|
# events, so safe to drop if you only run on \`main\`.
|
|
17787
18146
|
issues: write
|
|
18147
|
+
# Lets the action publish a commit status with the score + error/warning
|
|
18148
|
+
# counts (links to the run). This is how a \`push\` to \`main\` surfaces its
|
|
18149
|
+
# result, since the PR comment is skipped off pull requests. Drop it to
|
|
18150
|
+
# disable the status (or set \`commit-status: false\` below).
|
|
18151
|
+
statuses: write
|
|
17788
18152
|
|
|
17789
18153
|
# Cancels any in-flight scan for the same PR (or branch, on push) the moment
|
|
17790
18154
|
# a new commit arrives, so reviewers only ever see the latest run.
|
|
@@ -17798,20 +18162,42 @@ jobs:
|
|
|
17798
18162
|
steps:
|
|
17799
18163
|
- uses: actions/checkout@v5
|
|
17800
18164
|
|
|
17801
|
-
- uses: millionco/react-doctor@
|
|
18165
|
+
- uses: millionco/react-doctor@v2
|
|
17802
18166
|
# Common configuration knobs — uncomment any to override the default.
|
|
17803
18167
|
# Full reference: https://www.react.doctor/ci
|
|
17804
18168
|
# with:
|
|
17805
|
-
#
|
|
17806
|
-
#
|
|
18169
|
+
# blocking: warning # Gate level: "error" (default) | "warning" | "none" (advisory)
|
|
18170
|
+
# scope: full # On PRs, scan the whole project instead of just changed files
|
|
17807
18171
|
# comment: false # Disable the sticky PR summary comment
|
|
17808
|
-
#
|
|
17809
|
-
#
|
|
18172
|
+
# review-comments: false # Disable inline review comments on changed lines
|
|
18173
|
+
# commit-status: false # Disable the commit status (score + counts, links to the run)
|
|
18174
|
+
# version: "0.4.0" # Pin to a specific react-doctor version instead of "latest"
|
|
17810
18175
|
# directory: apps/web # Scan a sub-directory (default: ".")
|
|
17811
18176
|
# project: "web,admin" # In a monorepo, scan specific workspace project(s)
|
|
17812
18177
|
`;
|
|
17813
18178
|
const getReactDoctorWorkflowPath = (projectRoot) => path$1.join(projectRoot, ".github", "workflows", "react-doctor.yml");
|
|
17814
18179
|
const isReactDoctorWorkflowInstalled = (projectRoot) => fs$1.existsSync(getReactDoctorWorkflowPath(projectRoot));
|
|
18180
|
+
const V1_FLOATING_ACTION_REF = String.raw`millionco/react-doctor@v1(?![\w.])`;
|
|
18181
|
+
const V2_FLOATING_ACTION_REF = "millionco/react-doctor@v2";
|
|
18182
|
+
const readReactDoctorWorkflow = (projectRoot) => {
|
|
18183
|
+
const workflowPath = getReactDoctorWorkflowPath(projectRoot);
|
|
18184
|
+
try {
|
|
18185
|
+
return {
|
|
18186
|
+
workflowPath,
|
|
18187
|
+
content: fs$1.readFileSync(workflowPath, "utf8")
|
|
18188
|
+
};
|
|
18189
|
+
} catch {
|
|
18190
|
+
return null;
|
|
18191
|
+
}
|
|
18192
|
+
};
|
|
18193
|
+
const workflowUsesV1Action = (content) => new RegExp(V1_FLOATING_ACTION_REF).test(content);
|
|
18194
|
+
const upgradeWorkflowActionToV2 = (content) => {
|
|
18195
|
+
const upgraded = content.replace(new RegExp(V1_FLOATING_ACTION_REF, "g"), V2_FLOATING_ACTION_REF);
|
|
18196
|
+
return {
|
|
18197
|
+
content: upgraded,
|
|
18198
|
+
changed: upgraded !== content
|
|
18199
|
+
};
|
|
18200
|
+
};
|
|
17815
18201
|
const installReactDoctorWorkflow = (projectRoot) => {
|
|
17816
18202
|
const workflowPath = getReactDoctorWorkflowPath(projectRoot);
|
|
17817
18203
|
if (fs$1.existsSync(workflowPath)) return {
|
|
@@ -17855,8 +18241,8 @@ const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\
|
|
|
17855
18241
|
const SHEBANG = "#!/bin/sh";
|
|
17856
18242
|
const SHEBANG_PREFIX = "#!";
|
|
17857
18243
|
const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
|
|
17858
|
-
const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --
|
|
17859
|
-
const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --
|
|
18244
|
+
const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
|
|
18245
|
+
const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
|
|
17860
18246
|
const buildReactDoctorHookBlock = () => [
|
|
17861
18247
|
REACT_DOCTOR_BLOCK_START,
|
|
17862
18248
|
"react_doctor_scan_staged_files() {",
|
|
@@ -17937,11 +18323,11 @@ const installDirectGitHook = (options) => {
|
|
|
17937
18323
|
//#region src/cli/utils/install-git-hook-config-managers.ts
|
|
17938
18324
|
const appendStringCommand = (existingCommand) => {
|
|
17939
18325
|
const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
|
|
17940
|
-
return existingCommandText.includes("react-doctor --staged --
|
|
18326
|
+
return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
|
|
17941
18327
|
};
|
|
17942
18328
|
const appendArrayCommand = (existingCommands) => {
|
|
17943
18329
|
const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
|
|
17944
|
-
return commands.some((command) => command.includes("react-doctor --staged --
|
|
18330
|
+
return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
|
|
17945
18331
|
};
|
|
17946
18332
|
const installPackageJsonHook = (options, strategy) => {
|
|
17947
18333
|
const packageJsonPath = getPackageJsonPath(options.projectRoot);
|
|
@@ -18238,7 +18624,7 @@ const installReactDoctorGitHook = (options) => {
|
|
|
18238
18624
|
};
|
|
18239
18625
|
//#endregion
|
|
18240
18626
|
//#region src/cli/utils/should-skip-prompts.ts
|
|
18241
|
-
const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.
|
|
18627
|
+
const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
|
|
18242
18628
|
//#endregion
|
|
18243
18629
|
//#region src/cli/utils/install-react-doctor.ts
|
|
18244
18630
|
const SETUP_OPTION_GIT_HOOK = "git-hook";
|
|
@@ -18641,6 +19027,41 @@ const runInstallReactDoctor = async (options = {}) => {
|
|
|
18641
19027
|
for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
|
|
18642
19028
|
};
|
|
18643
19029
|
//#endregion
|
|
19030
|
+
//#region src/cli/utils/hash-project-root.ts
|
|
19031
|
+
const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
|
|
19032
|
+
//#endregion
|
|
19033
|
+
//#region src/cli/utils/action-upgrade-prompt.ts
|
|
19034
|
+
const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
|
|
19035
|
+
const getActionUpgradeStore = (options = {}) => new Conf({
|
|
19036
|
+
projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
|
|
19037
|
+
cwd: options.cwd
|
|
19038
|
+
});
|
|
19039
|
+
const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
|
|
19040
|
+
try {
|
|
19041
|
+
const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
|
|
19042
|
+
return Boolean(upgrades[hashProjectRoot(projectRoot)]);
|
|
19043
|
+
} catch {
|
|
19044
|
+
return true;
|
|
19045
|
+
}
|
|
19046
|
+
};
|
|
19047
|
+
const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
|
|
19048
|
+
try {
|
|
19049
|
+
const store = getActionUpgradeStore(storeOptions);
|
|
19050
|
+
const upgrades = store.get("actionUpgrades", {});
|
|
19051
|
+
store.set("actionUpgrades", {
|
|
19052
|
+
...upgrades,
|
|
19053
|
+
[hashProjectRoot(projectRoot)]: {
|
|
19054
|
+
rootDirectory: path$1.resolve(projectRoot),
|
|
19055
|
+
outcome,
|
|
19056
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
19057
|
+
}
|
|
19058
|
+
});
|
|
19059
|
+
return true;
|
|
19060
|
+
} catch {
|
|
19061
|
+
return false;
|
|
19062
|
+
}
|
|
19063
|
+
};
|
|
19064
|
+
//#endregion
|
|
18644
19065
|
//#region src/cli/utils/install-skill-for-agent.ts
|
|
18645
19066
|
const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
|
|
18646
19067
|
const source = getSkillSourceDirectory();
|
|
@@ -18691,9 +19112,9 @@ const openUrl = (url) => {
|
|
|
18691
19112
|
//#endregion
|
|
18692
19113
|
//#region src/cli/utils/open-workflow-pull-request.ts
|
|
18693
19114
|
const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
|
|
18694
|
-
const
|
|
18695
|
-
const
|
|
18696
|
-
const
|
|
19115
|
+
const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
|
|
19116
|
+
const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
|
|
19117
|
+
const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
|
|
18697
19118
|
|
|
18698
19119
|
Docs: https://www.react.doctor/ci`;
|
|
18699
19120
|
const execFileAsync = promisify(execFile);
|
|
@@ -18745,6 +19166,9 @@ const findUniqueBranchName = async (cwd) => {
|
|
|
18745
19166
|
};
|
|
18746
19167
|
const openWorkflowPullRequest = async (params) => {
|
|
18747
19168
|
const workflowPath = path$1.resolve(params.workflowPath);
|
|
19169
|
+
const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
|
|
19170
|
+
const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
|
|
19171
|
+
const prBody = params.prBody ?? DEFAULT_PR_BODY;
|
|
18748
19172
|
const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
|
|
18749
19173
|
if (!repoRootProbe.success) return {
|
|
18750
19174
|
status: "not-attempted",
|
|
@@ -18811,7 +19235,7 @@ const openWorkflowPullRequest = async (params) => {
|
|
|
18811
19235
|
if (!(await run("git", [
|
|
18812
19236
|
"commit",
|
|
18813
19237
|
"-m",
|
|
18814
|
-
|
|
19238
|
+
commitMessage
|
|
18815
19239
|
], cwd)).success) {
|
|
18816
19240
|
await restoreToPreviousBranch(true);
|
|
18817
19241
|
return {
|
|
@@ -18835,9 +19259,9 @@ const openWorkflowPullRequest = async (params) => {
|
|
|
18835
19259
|
"pr",
|
|
18836
19260
|
"create",
|
|
18837
19261
|
"--title",
|
|
18838
|
-
|
|
19262
|
+
prTitle,
|
|
18839
19263
|
"--body",
|
|
18840
|
-
|
|
19264
|
+
prBody,
|
|
18841
19265
|
"--base",
|
|
18842
19266
|
defaultBranch,
|
|
18843
19267
|
"--head",
|
|
@@ -18865,6 +19289,7 @@ const stageWorkflowFile = async (params) => {
|
|
|
18865
19289
|
};
|
|
18866
19290
|
//#endregion
|
|
18867
19291
|
//#region src/cli/utils/launch-agent.ts
|
|
19292
|
+
const isWindows = process.platform === "win32";
|
|
18868
19293
|
const CLI_AGENT_BINARIES = {
|
|
18869
19294
|
"claude-code": "claude",
|
|
18870
19295
|
codex: "codex",
|
|
@@ -18875,14 +19300,47 @@ const CLI_AGENT_AUTO_FLAGS = {
|
|
|
18875
19300
|
codex: ["--yolo"],
|
|
18876
19301
|
cursor: ["--force"]
|
|
18877
19302
|
};
|
|
18878
|
-
const
|
|
18879
|
-
|
|
19303
|
+
const resolveWindowsCmdEntryScript = (command) => {
|
|
19304
|
+
if (!isWindows) return null;
|
|
19305
|
+
const pathDirectories = (process.env.PATH ?? "").split(path$1.delimiter).filter(Boolean);
|
|
19306
|
+
for (const directory of pathDirectories) {
|
|
19307
|
+
const cmdFilePath = path$1.join(directory, `${command}.cmd`);
|
|
19308
|
+
try {
|
|
19309
|
+
if (!fs$1.statSync(cmdFilePath).isFile()) continue;
|
|
19310
|
+
} catch {
|
|
19311
|
+
continue;
|
|
19312
|
+
}
|
|
19313
|
+
try {
|
|
19314
|
+
const entryScriptMatch = fs$1.readFileSync(cmdFilePath, "utf8").match(/"%(?:~dp0|dp0%)\\([^"]+\.(?:m?js|cjs))"/);
|
|
19315
|
+
if (!entryScriptMatch) continue;
|
|
19316
|
+
const resolvedScriptPath = path$1.resolve(directory, entryScriptMatch[1]);
|
|
19317
|
+
if (fs$1.statSync(resolvedScriptPath).isFile()) return resolvedScriptPath;
|
|
19318
|
+
} catch {}
|
|
19319
|
+
}
|
|
19320
|
+
return null;
|
|
19321
|
+
};
|
|
19322
|
+
const spawnAgent = (command, args, cwd, shell = false) => new Promise((resolve, reject) => {
|
|
19323
|
+
const child = spawn(command, [...args], {
|
|
18880
19324
|
cwd,
|
|
18881
|
-
stdio: "inherit"
|
|
19325
|
+
stdio: "inherit",
|
|
19326
|
+
shell
|
|
18882
19327
|
});
|
|
18883
19328
|
child.on("error", reject);
|
|
18884
19329
|
child.on("close", (code) => resolve(code ?? 0));
|
|
18885
19330
|
});
|
|
19331
|
+
const launchCliAgent = async (agentId, prompt, cwd) => {
|
|
19332
|
+
const binary = CLI_AGENT_BINARIES[agentId];
|
|
19333
|
+
const agentArgs = [...CLI_AGENT_AUTO_FLAGS[agentId], prompt];
|
|
19334
|
+
if (isWindows) {
|
|
19335
|
+
const entryScript = resolveWindowsCmdEntryScript(binary);
|
|
19336
|
+
if (entryScript) return spawnAgent(process.execPath, [entryScript, ...agentArgs], cwd);
|
|
19337
|
+
}
|
|
19338
|
+
try {
|
|
19339
|
+
return await spawnAgent(binary, agentArgs, cwd);
|
|
19340
|
+
} catch {
|
|
19341
|
+
throw new Error(`Failed to launch ${binary}`);
|
|
19342
|
+
}
|
|
19343
|
+
};
|
|
18886
19344
|
const CLIPBOARD_COMMANDS = [
|
|
18887
19345
|
{
|
|
18888
19346
|
binary: "pbcopy",
|
|
@@ -18955,6 +19413,77 @@ const setUpGitHubActions = async (rootDirectory) => {
|
|
|
18955
19413
|
}
|
|
18956
19414
|
cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
|
|
18957
19415
|
};
|
|
19416
|
+
const UPGRADE_YES_CHOICE = "upgrade-yes";
|
|
19417
|
+
const UPGRADE_NO_CHOICE = "upgrade-no";
|
|
19418
|
+
const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
|
|
19419
|
+
const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
|
|
19420
|
+
const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
|
|
19421
|
+
|
|
19422
|
+
Docs: https://www.react.doctor/ci`;
|
|
19423
|
+
const askUpgradeActionVersion = async () => {
|
|
19424
|
+
const { upgradeChoice } = await prompts({
|
|
19425
|
+
type: "select",
|
|
19426
|
+
name: "upgradeChoice",
|
|
19427
|
+
message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
|
|
19428
|
+
hint: " ",
|
|
19429
|
+
choices: [{
|
|
19430
|
+
title: "Yes (recommended)",
|
|
19431
|
+
description: "Open a PR bumping the workflow to millionco/react-doctor@v2",
|
|
19432
|
+
value: UPGRADE_YES_CHOICE
|
|
19433
|
+
}, {
|
|
19434
|
+
title: "No, thanks",
|
|
19435
|
+
description: "Keep @v1 — won't ask again for this repo",
|
|
19436
|
+
value: UPGRADE_NO_CHOICE
|
|
19437
|
+
}],
|
|
19438
|
+
initial: 0
|
|
19439
|
+
}, { onCancel: () => true });
|
|
19440
|
+
if (upgradeChoice === void 0) return "cancel";
|
|
19441
|
+
return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
|
|
19442
|
+
};
|
|
19443
|
+
const upgradeGitHubActionsWorkflow = async (workflow) => {
|
|
19444
|
+
const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
|
|
19445
|
+
if (!changed) return false;
|
|
19446
|
+
const upgradeSpinner = spinner("Opening a pull request to upgrade React Doctor to v2...").start();
|
|
19447
|
+
try {
|
|
19448
|
+
fs$1.writeFileSync(workflow.workflowPath, content);
|
|
19449
|
+
} catch {
|
|
19450
|
+
upgradeSpinner.fail("Couldn't update the workflow file.");
|
|
19451
|
+
return false;
|
|
19452
|
+
}
|
|
19453
|
+
const pullRequestResult = await openWorkflowPullRequest({
|
|
19454
|
+
workflowPath: workflow.workflowPath,
|
|
19455
|
+
commitMessage: UPGRADE_COMMIT_MESSAGE,
|
|
19456
|
+
prTitle: UPGRADE_PR_TITLE,
|
|
19457
|
+
prBody: UPGRADE_PR_BODY
|
|
19458
|
+
});
|
|
19459
|
+
if (pullRequestResult.status === "pr-opened") upgradeSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
|
|
19460
|
+
else if (pullRequestResult.status === "branch-pushed") upgradeSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
|
|
19461
|
+
else {
|
|
19462
|
+
upgradeSpinner.stop();
|
|
19463
|
+
try {
|
|
19464
|
+
fs$1.writeFileSync(workflow.workflowPath, content);
|
|
19465
|
+
} catch {
|
|
19466
|
+
cliLogger.log(" Couldn't finish the upgrade. Re-run React Doctor to try again.");
|
|
19467
|
+
return false;
|
|
19468
|
+
}
|
|
19469
|
+
const didStage = await stageWorkflowFile({ workflowPath: workflow.workflowPath });
|
|
19470
|
+
cliLogger.log(didStage ? " Updated the workflow to @v2 and staged it. Commit it to finish the upgrade." : " Updated the workflow to @v2. Commit the change to finish the upgrade.");
|
|
19471
|
+
}
|
|
19472
|
+
return true;
|
|
19473
|
+
};
|
|
19474
|
+
const maybeOfferActionUpgrade = async (projectRoot) => {
|
|
19475
|
+
const workflow = readReactDoctorWorkflow(projectRoot);
|
|
19476
|
+
if (!workflow || !workflowUsesV1Action(workflow.content)) return;
|
|
19477
|
+
if (hasHandledActionUpgrade(projectRoot)) return;
|
|
19478
|
+
const outcome = await askUpgradeActionVersion();
|
|
19479
|
+
if (outcome === "cancel") return;
|
|
19480
|
+
recordCount(METRIC.agentHandoff, 1, { outcome: outcome === "yes" ? "upgrade-accepted" : "upgrade-declined" });
|
|
19481
|
+
if (outcome === "no") {
|
|
19482
|
+
recordActionUpgradeDecision(projectRoot, "declined");
|
|
19483
|
+
return;
|
|
19484
|
+
}
|
|
19485
|
+
if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
|
|
19486
|
+
};
|
|
18958
19487
|
const SGR_BOLD_OFF = "\x1B[22m";
|
|
18959
19488
|
const ciQuestionMessage = [
|
|
18960
19489
|
"Add React Doctor to GitHub Actions?",
|
|
@@ -19002,7 +19531,8 @@ const detectLaunchableAgents = async () => {
|
|
|
19002
19531
|
const handoffToAgent = async (input) => {
|
|
19003
19532
|
if (!input.interactive || input.diagnostics.length === 0) return;
|
|
19004
19533
|
cliLogger.break();
|
|
19005
|
-
|
|
19534
|
+
const projectRootForCi = findNearestPackageDirectory(input.rootDirectory) ?? input.rootDirectory;
|
|
19535
|
+
if (!isReactDoctorWorkflowInstalled(projectRootForCi)) {
|
|
19006
19536
|
const ciOutcome = await askAddToGitHubActions();
|
|
19007
19537
|
recordCount(METRIC.agentHandoff, 1, {
|
|
19008
19538
|
outcome: `ci-${ciOutcome}`,
|
|
@@ -19013,7 +19543,7 @@ const handoffToAgent = async (input) => {
|
|
|
19013
19543
|
await setUpGitHubActions(input.rootDirectory);
|
|
19014
19544
|
cliLogger.break();
|
|
19015
19545
|
}
|
|
19016
|
-
}
|
|
19546
|
+
} else await maybeOfferActionUpgrade(projectRootForCi);
|
|
19017
19547
|
const { handoffTarget } = await prompts({
|
|
19018
19548
|
type: "select",
|
|
19019
19549
|
name: "handoffTarget",
|
|
@@ -19139,20 +19669,6 @@ export default ${serializeTsObjectLiteral(config)} satisfies ReactDoctorConfig;
|
|
|
19139
19669
|
return targetPath;
|
|
19140
19670
|
};
|
|
19141
19671
|
//#endregion
|
|
19142
|
-
//#region src/cli/utils/annotation-encoding.ts
|
|
19143
|
-
const encodeAnnotationProperty = (value) => value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A").replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
19144
|
-
const encodeAnnotationMessage = (value) => value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
|
|
19145
|
-
//#endregion
|
|
19146
|
-
//#region src/cli/utils/print-annotations.ts
|
|
19147
|
-
const printAnnotations = (diagnostics, routeToStderr) => {
|
|
19148
|
-
const writeLine = routeToStderr ? (line) => process.stderr.write(`${line}\n`) : (line) => process.stdout.write(`${line}\n`);
|
|
19149
|
-
for (const diagnostic of diagnostics) {
|
|
19150
|
-
const level = diagnostic.severity === "error" ? "error" : "warning";
|
|
19151
|
-
const title = `${diagnostic.plugin}/${diagnostic.rule}`;
|
|
19152
|
-
writeLine(`::${level} ${`file=${encodeAnnotationProperty(diagnostic.filePath)}`}${diagnostic.line > 0 ? `,line=${diagnostic.line}` : ""}${`,title=${encodeAnnotationProperty(title)}`}::${encodeAnnotationMessage(diagnostic.message)}`);
|
|
19153
|
-
}
|
|
19154
|
-
};
|
|
19155
|
-
//#endregion
|
|
19156
19672
|
//#region src/cli/utils/print-branded-header.ts
|
|
19157
19673
|
/**
|
|
19158
19674
|
* Single branded line every command prints first when not in JSON
|
|
@@ -19361,7 +19877,7 @@ const getSetupPromptStore = (options = {}) => new Conf({
|
|
|
19361
19877
|
projectName: GLOBAL_CONFIG_PROJECT_NAME,
|
|
19362
19878
|
cwd: options.cwd
|
|
19363
19879
|
});
|
|
19364
|
-
const getSetupPromptProjectKey = (projectRoot) =>
|
|
19880
|
+
const getSetupPromptProjectKey = (projectRoot) => hashProjectRoot(projectRoot);
|
|
19365
19881
|
const hasDisabledSetupPrompt = (projectRoot, storeOptions = {}) => {
|
|
19366
19882
|
try {
|
|
19367
19883
|
return getSetupPromptStore(storeOptions).get("projects", {})[getSetupPromptProjectKey(projectRoot)]?.setupPrompt === false;
|
|
@@ -19418,28 +19934,26 @@ const resolveParallelFlag = (parallel) => parallel === false ? 1 : void 0;
|
|
|
19418
19934
|
/**
|
|
19419
19935
|
* Translates CLI flags into the `InspectOptions` contract `inspect()`
|
|
19420
19936
|
* accepts. Flag-specific computed fields (`scoreOnly`, `noScore`,
|
|
19421
|
-
* `silent`, `
|
|
19422
|
-
*
|
|
19423
|
-
*
|
|
19424
|
-
*
|
|
19425
|
-
*
|
|
19426
|
-
*
|
|
19427
|
-
* can apply the one flag-and-config rule that flags own
|
|
19937
|
+
* `silent`, `isCi`) live here — there's no `userConfig` knob for them,
|
|
19938
|
+
* only flag derivation. The plain boolean knobs (`lint`, `deadCode`,
|
|
19939
|
+
* `verbose`) pass through unchanged: `inspect()` owns the
|
|
19940
|
+
* userConfig-fallback layer so the merge logic isn't duplicated. The
|
|
19941
|
+
* shell still hands `userConfig` in via `configOverride` and `noScore`
|
|
19942
|
+
* so this resolver can apply the one flag-and-config rule that flags own
|
|
19428
19943
|
* (`--score false` wins, otherwise inherit `userConfig.noScore`).
|
|
19429
19944
|
*/
|
|
19430
19945
|
const resolveCliInspectOptions = (flags, userConfig) => {
|
|
19431
|
-
const wantsWarningGate = (flags
|
|
19946
|
+
const wantsWarningGate = pickBlockingLevel(flags, userConfig) === "warning";
|
|
19432
19947
|
return {
|
|
19433
19948
|
lint: flags.lint,
|
|
19434
19949
|
deadCode: flags.deadCode,
|
|
19435
19950
|
verbose: flags.verbose,
|
|
19436
|
-
respectInlineDisables: flags.respectInlineDisables,
|
|
19437
|
-
warnings:
|
|
19951
|
+
respectInlineDisables: flags.respectInlineDisables === false ? false : void 0,
|
|
19952
|
+
warnings: wantsWarningGate ? true : flags.warnings,
|
|
19438
19953
|
scoreOnly: flags.score === true,
|
|
19439
19954
|
noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
|
|
19440
19955
|
isCi: isCiEnvironment(),
|
|
19441
19956
|
silent: Boolean(flags.json),
|
|
19442
|
-
outputSurface: flags.prComment ? "prComment" : "cli",
|
|
19443
19957
|
concurrency: resolveParallelFlag(flags.parallel)
|
|
19444
19958
|
};
|
|
19445
19959
|
};
|
|
@@ -19492,25 +20006,7 @@ const coerceDiffValue = (value) => {
|
|
|
19492
20006
|
};
|
|
19493
20007
|
//#endregion
|
|
19494
20008
|
//#region src/cli/utils/resolve-effective-diff.ts
|
|
19495
|
-
const resolveEffectiveDiff = (flags, userConfig) =>
|
|
19496
|
-
if (flags.full) return false;
|
|
19497
|
-
return coerceDiffValue(flags.diff ?? userConfig?.diff);
|
|
19498
|
-
};
|
|
19499
|
-
//#endregion
|
|
19500
|
-
//#region src/cli/utils/resolve-fail-on-level.ts
|
|
19501
|
-
const VALID_FAIL_ON_LEVELS = new Set([
|
|
19502
|
-
"error",
|
|
19503
|
-
"warning",
|
|
19504
|
-
"none"
|
|
19505
|
-
]);
|
|
19506
|
-
const DEFAULT_FAIL_ON_LEVEL = "none";
|
|
19507
|
-
const isValidFailOnLevel = (level) => VALID_FAIL_ON_LEVELS.has(level);
|
|
19508
|
-
const resolveFailOnLevel = (flags, userConfig) => {
|
|
19509
|
-
const sourceValue = flags.failOn ?? userConfig?.failOn ?? DEFAULT_FAIL_ON_LEVEL;
|
|
19510
|
-
if (isValidFailOnLevel(sourceValue)) return sourceValue;
|
|
19511
|
-
cliLogger.warn(`Invalid failOn level "${sourceValue}". Expected one of: error, warning, none. Falling back to "${DEFAULT_FAIL_ON_LEVEL}".`);
|
|
19512
|
-
return DEFAULT_FAIL_ON_LEVEL;
|
|
19513
|
-
};
|
|
20009
|
+
const resolveEffectiveDiff = (flags, userConfig) => coerceDiffValue(flags.diff ?? userConfig?.diff);
|
|
19514
20010
|
//#endregion
|
|
19515
20011
|
//#region src/cli/utils/resolve-project-diff-include-paths.ts
|
|
19516
20012
|
const resolveProjectDiffIncludePaths = (rootDirectory, projectDirectory, diffInfo) => {
|
|
@@ -19614,8 +20110,11 @@ const selectProjects = async (rootDirectory, projectFlag, skipPrompts) => {
|
|
|
19614
20110
|
}
|
|
19615
20111
|
return promptProjectSelection(packages, rootDirectory);
|
|
19616
20112
|
};
|
|
20113
|
+
const ALL_PROJECTS_SENTINEL = "*";
|
|
19617
20114
|
const resolveProjectFlag = (projectFlag, workspacePackages) => {
|
|
19618
|
-
const requestedNames = projectFlag.split(",").map((name) => name.trim());
|
|
20115
|
+
const requestedNames = projectFlag.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
|
|
20116
|
+
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.`);
|
|
20117
|
+
if (requestedNames.includes(ALL_PROJECTS_SENTINEL)) return workspacePackages.map((workspacePackage) => workspacePackage.directory);
|
|
19619
20118
|
const resolvedDirectories = [];
|
|
19620
20119
|
for (const requestedName of requestedNames) {
|
|
19621
20120
|
const matched = workspacePackages.find((workspacePackage) => workspacePackage.name === requestedName || path$1.basename(workspacePackage.directory) === requestedName);
|
|
@@ -19688,6 +20187,16 @@ const runExplain = async (fileLineArgument, context) => {
|
|
|
19688
20187
|
}
|
|
19689
20188
|
};
|
|
19690
20189
|
//#endregion
|
|
20190
|
+
//#region src/cli/utils/warn-deprecated-fail-on.ts
|
|
20191
|
+
const warnDeprecatedFailOn = (flags, userConfig) => {
|
|
20192
|
+
const usedFlag = flags.failOn !== void 0;
|
|
20193
|
+
const usedConfig = userConfig?.failOn !== void 0;
|
|
20194
|
+
if (!usedFlag && !usedConfig) return;
|
|
20195
|
+
const source = usedFlag ? "The `--fail-on` flag" : "The `failOn` config option";
|
|
20196
|
+
const replacement = usedFlag ? "`--blocking <level>`" : "`blocking`";
|
|
20197
|
+
cliLogger.warn(`${source} is deprecated; rename it to ${replacement}.`);
|
|
20198
|
+
};
|
|
20199
|
+
//#endregion
|
|
19691
20200
|
//#region src/cli/utils/validate-mode-flags.ts
|
|
19692
20201
|
const validateModeFlags = (flags) => {
|
|
19693
20202
|
const coercedDiff = coerceDiffValue(flags.diff);
|
|
@@ -19695,36 +20204,44 @@ const validateModeFlags = (flags) => {
|
|
|
19695
20204
|
if (exclusiveModes.length > 1) throw new CliInputError(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
|
|
19696
20205
|
if (flags.score && flags.json) throw new CliInputError("Cannot combine --score and --json; pick one output mode.");
|
|
19697
20206
|
if (flags.score && flags.telemetry === false) throw new CliInputError("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
|
|
19698
|
-
if (flags.prComment && (flags.json || flags.score)) throw new CliInputError("--pr-comment cannot be combined with --json or --score.");
|
|
19699
|
-
if (flags.annotations && flags.score) throw new CliInputError("--annotations cannot be combined with --score.");
|
|
19700
|
-
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.");
|
|
19701
|
-
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.");
|
|
19702
20207
|
};
|
|
19703
20208
|
//#endregion
|
|
19704
20209
|
//#region src/cli/commands/inspect.ts
|
|
19705
20210
|
/**
|
|
19706
20211
|
* Post-scan finalization shared by the staged-arm and project-loop
|
|
19707
|
-
* paths of `inspectAction`: emit the JSON report (when in JSON mode)
|
|
19708
|
-
*
|
|
19709
|
-
* `
|
|
19710
|
-
*
|
|
20212
|
+
* paths of `inspectAction`: emit the JSON report (when in JSON mode)
|
|
20213
|
+
* and set `process.exitCode = 1` when a diagnostic at or above the
|
|
20214
|
+
* `--blocking` threshold (default `"error"`) reaches the `ciFailure`
|
|
20215
|
+
* surface. `--blocking none` keeps the scan advisory (always exits 0).
|
|
19711
20216
|
*/
|
|
19712
20217
|
const finalizeScans = (input) => {
|
|
19713
|
-
|
|
19714
|
-
|
|
19715
|
-
|
|
19716
|
-
|
|
19717
|
-
|
|
19718
|
-
|
|
19719
|
-
|
|
19720
|
-
|
|
19721
|
-
|
|
19722
|
-
|
|
19723
|
-
|
|
20218
|
+
const baselineDeltas = input.completedScans.flatMap((scan) => scan.result.baselineDelta ? [scan.result.baselineDelta] : []);
|
|
20219
|
+
const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
|
|
20220
|
+
const baselineDegraded = input.baselineIntended && !baselineComputed;
|
|
20221
|
+
const mode = baselineDegraded ? "diff" : input.mode;
|
|
20222
|
+
if (input.isJsonMode) {
|
|
20223
|
+
const baseline = baselineComputed && baselineDeltas.length > 0 ? {
|
|
20224
|
+
baseRef: baselineDeltas[0].baseRef,
|
|
20225
|
+
fixedCount: baselineDeltas.reduce((total, delta) => total + delta.fixedCount, 0),
|
|
20226
|
+
baseTotalCount: baselineDeltas.reduce((total, delta) => total + delta.baseTotalCount, 0)
|
|
20227
|
+
} : void 0;
|
|
20228
|
+
writeJsonReport(buildJsonReport({
|
|
20229
|
+
version: VERSION,
|
|
20230
|
+
directory: input.resolvedDirectory,
|
|
20231
|
+
mode,
|
|
20232
|
+
diff: input.diff,
|
|
20233
|
+
scans: input.completedScans,
|
|
20234
|
+
totalElapsedMilliseconds: performance.now() - input.startTime,
|
|
20235
|
+
baseline
|
|
20236
|
+
}));
|
|
20237
|
+
}
|
|
20238
|
+
if (input.isScoreOnly || baselineDegraded) return;
|
|
20239
|
+
if (shouldBlockCi(filterDiagnosticsForSurface(input.diagnostics, "ciFailure", input.userConfig), resolveBlockingLevel(input.flags, input.userConfig))) process.exitCode = 1;
|
|
19724
20240
|
};
|
|
19725
20241
|
const buildChangedFilesDiffInfo = (changedFiles) => ({
|
|
19726
20242
|
currentBranch: process.env.GITHUB_HEAD_REF?.trim() || null,
|
|
19727
20243
|
baseBranch: process.env.GITHUB_BASE_REF?.trim() || "pull request target",
|
|
20244
|
+
baseSha: process.env.REACT_DOCTOR_BASE_SHA?.trim() || void 0,
|
|
19728
20245
|
changedFiles,
|
|
19729
20246
|
isCurrentChanges: false
|
|
19730
20247
|
});
|
|
@@ -19767,11 +20284,12 @@ const inspectAction = async (directory, flags) => {
|
|
|
19767
20284
|
const userConfig = scanTarget.userConfig;
|
|
19768
20285
|
const resolvedDirectory = scanTarget.resolvedDirectory;
|
|
19769
20286
|
setJsonReportDirectory(resolvedDirectory);
|
|
20287
|
+
warnDeprecatedFailOn(flags, userConfig);
|
|
19770
20288
|
if (scanTarget.didRedirectViaRootDir && !isQuiet) {
|
|
19771
20289
|
cliLogger.dim(`Redirected to ${highlighter.info(toRelativePath(resolvedDirectory, requestedDirectory))} via react-doctor config "rootDir".`);
|
|
19772
20290
|
cliLogger.break();
|
|
19773
20291
|
}
|
|
19774
|
-
const explainArgument = flags.explain
|
|
20292
|
+
const explainArgument = flags.explain;
|
|
19775
20293
|
if (explainArgument !== void 0) {
|
|
19776
20294
|
await runExplain(explainArgument, {
|
|
19777
20295
|
resolvedDirectory,
|
|
@@ -19788,7 +20306,6 @@ const inspectAction = async (directory, flags) => {
|
|
|
19788
20306
|
const scanOptions = resolveCliInspectOptions(flags, userConfig);
|
|
19789
20307
|
const skipPrompts = shouldSkipPrompts({
|
|
19790
20308
|
yes: flags.yes,
|
|
19791
|
-
full: flags.full,
|
|
19792
20309
|
json: flags.json
|
|
19793
20310
|
});
|
|
19794
20311
|
if (flags.staged) {
|
|
@@ -19843,6 +20360,7 @@ const inspectAction = async (directory, flags) => {
|
|
|
19843
20360
|
}],
|
|
19844
20361
|
mode: "staged",
|
|
19845
20362
|
diff: null,
|
|
20363
|
+
baselineIntended: false,
|
|
19846
20364
|
isJsonMode,
|
|
19847
20365
|
isScoreOnly,
|
|
19848
20366
|
flags,
|
|
@@ -19856,11 +20374,12 @@ const inspectAction = async (directory, flags) => {
|
|
|
19856
20374
|
return;
|
|
19857
20375
|
}
|
|
19858
20376
|
const projectDirectories = await selectProjects(resolvedDirectory, flags.project, skipPrompts);
|
|
19859
|
-
const changedFilesDiffInfo = flags.changedFilesFrom
|
|
20377
|
+
const changedFilesDiffInfo = flags.changedFilesFrom ? buildChangedFilesDiffInfo(readChangedFilesFrom(path$1.resolve(flags.changedFilesFrom))) : null;
|
|
19860
20378
|
const effectiveDiff = resolveEffectiveDiff(flags, userConfig);
|
|
19861
20379
|
const diffInfo = changedFilesDiffInfo ?? (changedFilesDiffInfo === null && (effectiveDiff !== void 0 && effectiveDiff !== false || !skipPrompts && !isQuiet) ? await getDiffInfo(resolvedDirectory, typeof effectiveDiff === "string" ? effectiveDiff : void 0) : null);
|
|
19862
20380
|
const isDiffMode = changedFilesDiffInfo !== null || await resolveDiffMode(diffInfo, effectiveDiff, skipPrompts, isQuiet);
|
|
19863
|
-
|
|
20381
|
+
const baselineRef = isDiffMode && diffInfo && !diffInfo.isCurrentChanges ? diffInfo.baseSha ? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseSha) : diffInfo.diffBaseRef ?? await resolveMergeBaseRef(resolvedDirectory, diffInfo.baseBranch) : null;
|
|
20382
|
+
setJsonReportMode(baselineRef ? "baseline" : isDiffMode ? "diff" : "full");
|
|
19864
20383
|
if (isDiffMode && diffInfo && !isQuiet) {
|
|
19865
20384
|
if (diffInfo.isCurrentChanges) cliLogger.log("Scanning uncommitted changes");
|
|
19866
20385
|
else {
|
|
@@ -19890,7 +20409,8 @@ const inspectAction = async (directory, flags) => {
|
|
|
19890
20409
|
...scanOptions,
|
|
19891
20410
|
includePaths,
|
|
19892
20411
|
configOverride: userConfig,
|
|
19893
|
-
suppressRendering: isMultiProject
|
|
20412
|
+
suppressRendering: isMultiProject,
|
|
20413
|
+
baseline: baselineRef ? { ref: baselineRef } : void 0
|
|
19894
20414
|
});
|
|
19895
20415
|
allDiagnostics.push(...scanResult.diagnostics);
|
|
19896
20416
|
completedScans.push({
|
|
@@ -19912,8 +20432,9 @@ const inspectAction = async (directory, flags) => {
|
|
|
19912
20432
|
finalizeScans({
|
|
19913
20433
|
diagnostics: allDiagnostics,
|
|
19914
20434
|
completedScans,
|
|
19915
|
-
mode: isDiffMode ? "diff" : "full",
|
|
20435
|
+
mode: baselineRef ? "baseline" : isDiffMode ? "diff" : "full",
|
|
19916
20436
|
diff: isDiffMode ? diffInfo : null,
|
|
20437
|
+
baselineIntended: isDiffMode && diffInfo !== null && !diffInfo.isCurrentChanges,
|
|
19917
20438
|
isJsonMode,
|
|
19918
20439
|
isScoreOnly,
|
|
19919
20440
|
flags,
|
|
@@ -19951,7 +20472,7 @@ const inspectAction = async (directory, flags) => {
|
|
|
19951
20472
|
const isUserError = isExpectedUserError(error);
|
|
19952
20473
|
const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
|
|
19953
20474
|
if (isJsonMode) {
|
|
19954
|
-
writeJsonErrorReport(error);
|
|
20475
|
+
writeJsonErrorReport(error, sentryEventId);
|
|
19955
20476
|
process.exitCode = 1;
|
|
19956
20477
|
return;
|
|
19957
20478
|
}
|
|
@@ -20540,6 +21061,20 @@ const versionAction = () => {
|
|
|
20540
21061
|
process.stdout.write(`${buildVersionString()}\n`);
|
|
20541
21062
|
};
|
|
20542
21063
|
//#endregion
|
|
21064
|
+
//#region src/cli/commands/why.ts
|
|
21065
|
+
/**
|
|
21066
|
+
* `why <file:line>` — explains why a rule fired (or why a suppression didn't
|
|
21067
|
+
* apply) at a specific location. A thin wrapper over the inspect flow's
|
|
21068
|
+
* single-location explain path so it reuses the same scan, config resolution,
|
|
21069
|
+
* and clean error handling. (Replaces the former `--explain` / `--why` flags.)
|
|
21070
|
+
*/
|
|
21071
|
+
const whyAction = async (location, options) => {
|
|
21072
|
+
await inspectAction(options.cwd ?? process.cwd(), {
|
|
21073
|
+
explain: location,
|
|
21074
|
+
project: options.project
|
|
21075
|
+
});
|
|
21076
|
+
};
|
|
21077
|
+
//#endregion
|
|
20543
21078
|
//#region src/cli/utils/apply-color-preference.ts
|
|
20544
21079
|
/**
|
|
20545
21080
|
* Resolve an explicit color preference from `--color` / `--no-color` or the
|
|
@@ -20641,13 +21176,32 @@ const normalizeHelpInvocation = (argv, knownCommands) => {
|
|
|
20641
21176
|
return [...nodeArguments, "--help"];
|
|
20642
21177
|
};
|
|
20643
21178
|
//#endregion
|
|
21179
|
+
//#region src/cli/utils/removed-cli-flags.ts
|
|
21180
|
+
const REMOVED_FLAGS = new Map([
|
|
21181
|
+
["--full", "use `--diff false` to force a full scan"],
|
|
21182
|
+
["--explain", "use the `why <file>:<line>` command"],
|
|
21183
|
+
["--why", "use the `why <file>:<line>` command"],
|
|
21184
|
+
["--pr-comment", "the GitHub Action posts the PR comment for you; remove this flag"]
|
|
21185
|
+
]);
|
|
21186
|
+
/**
|
|
21187
|
+
* Throws a clean {@link CliInputError} when a removed flag appears in argv,
|
|
21188
|
+
* pointing to its replacement. Run before flag stripping so a removed flag is a
|
|
21189
|
+
* loud, actionable error rather than a silent no-op.
|
|
21190
|
+
*/
|
|
21191
|
+
const assertNoRemovedFlags = (argv) => {
|
|
21192
|
+
for (const argument of argv.slice(2)) {
|
|
21193
|
+
if (argument === "--") return;
|
|
21194
|
+
const optionName = argument.includes("=") ? argument.slice(0, argument.indexOf("=")) : argument;
|
|
21195
|
+
const guidance = REMOVED_FLAGS.get(optionName);
|
|
21196
|
+
if (guidance !== void 0) throw new CliInputError(`\`${optionName}\` was removed — ${guidance}.`);
|
|
21197
|
+
}
|
|
21198
|
+
};
|
|
21199
|
+
//#endregion
|
|
20644
21200
|
//#region src/cli/utils/strip-unknown-cli-flags.ts
|
|
20645
21201
|
const ROOT_FLAG_SPEC = {
|
|
20646
21202
|
longOptionsWithoutValues: new Set([
|
|
20647
|
-
"--annotations",
|
|
20648
21203
|
"--color",
|
|
20649
21204
|
"--dead-code",
|
|
20650
|
-
"--full",
|
|
20651
21205
|
"--help",
|
|
20652
21206
|
"--json",
|
|
20653
21207
|
"--json-compact",
|
|
@@ -20660,8 +21214,6 @@ const ROOT_FLAG_SPEC = {
|
|
|
20660
21214
|
"--no-score",
|
|
20661
21215
|
"--no-telemetry",
|
|
20662
21216
|
"--no-warnings",
|
|
20663
|
-
"--pr-comment",
|
|
20664
|
-
"--respect-inline-disables",
|
|
20665
21217
|
"--score",
|
|
20666
21218
|
"--staged",
|
|
20667
21219
|
"--verbose",
|
|
@@ -20671,10 +21223,9 @@ const ROOT_FLAG_SPEC = {
|
|
|
20671
21223
|
]),
|
|
20672
21224
|
longOptionsWithRequiredValues: new Set([
|
|
20673
21225
|
"--changed-files-from",
|
|
20674
|
-
"--
|
|
21226
|
+
"--blocking",
|
|
20675
21227
|
"--fail-on",
|
|
20676
|
-
"--project"
|
|
20677
|
-
"--why"
|
|
21228
|
+
"--project"
|
|
20678
21229
|
]),
|
|
20679
21230
|
longOptionsWithOptionalValues: new Set(["--diff"]),
|
|
20680
21231
|
shortOptionsWithoutValues: new Set([
|
|
@@ -20730,6 +21281,17 @@ const COMMAND_FLAG_SPECS = new Map([
|
|
|
20730
21281
|
longOptionsWithOptionalValues: /* @__PURE__ */ new Set(),
|
|
20731
21282
|
shortOptionsWithoutValues: new Set(["-h"]),
|
|
20732
21283
|
shortOptionsWithRequiredValues: new Set(["-c"])
|
|
21284
|
+
}],
|
|
21285
|
+
["why", {
|
|
21286
|
+
longOptionsWithoutValues: new Set([
|
|
21287
|
+
"--color",
|
|
21288
|
+
"--help",
|
|
21289
|
+
"--no-color"
|
|
21290
|
+
]),
|
|
21291
|
+
longOptionsWithRequiredValues: new Set(["--cwd", "--project"]),
|
|
21292
|
+
longOptionsWithOptionalValues: /* @__PURE__ */ new Set(),
|
|
21293
|
+
shortOptionsWithoutValues: new Set(["-h"]),
|
|
21294
|
+
shortOptionsWithRequiredValues: new Set(["-c"])
|
|
20733
21295
|
}]
|
|
20734
21296
|
]);
|
|
20735
21297
|
const isFlagLike = (argument) => argument.startsWith("-") && argument !== "-";
|
|
@@ -20816,9 +21378,9 @@ ${formatExampleLines([
|
|
|
20816
21378
|
["react-doctor ./apps/web", "scan a specific directory"],
|
|
20817
21379
|
["react-doctor --diff main", "scan only files changed vs. main"],
|
|
20818
21380
|
["react-doctor --staged", "scan staged files (pre-commit hook)"],
|
|
20819
|
-
["react-doctor --
|
|
21381
|
+
["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
|
|
20820
21382
|
["react-doctor --json > report.json", "write a machine-readable report"],
|
|
20821
|
-
["react-doctor
|
|
21383
|
+
["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
|
|
20822
21384
|
["react-doctor install", "set up the agent skill and git hook"]
|
|
20823
21385
|
])}
|
|
20824
21386
|
|
|
@@ -20844,8 +21406,9 @@ ${formatExampleLines([
|
|
|
20844
21406
|
${highlighter.dim("Learn more:")}
|
|
20845
21407
|
${highlighter.info(CANONICAL_GITHUB_URL)}
|
|
20846
21408
|
`;
|
|
20847
|
-
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("--
|
|
21409
|
+
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);
|
|
20848
21410
|
program.action(inspectAction);
|
|
21411
|
+
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));
|
|
20849
21412
|
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);
|
|
20850
21413
|
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);
|
|
20851
21414
|
const rules = program.command("rules").description("List, explain, and configure which React Doctor rules run");
|
|
@@ -20857,6 +21420,7 @@ rules.command("disable <rule>").description("Disable a rule so it never runs").o
|
|
|
20857
21420
|
rules.command("category <category> <severity>").description("Set the severity for a whole category (off, warn, error)").option("-c, --cwd <cwd>", "working directory", process.cwd()).action((category, severity, _options, command) => rulesCategoryAction(category, severity, command.optsWithGlobals()));
|
|
20858
21421
|
rules.command("ignore-tag <tag>").description("Skip a whole rule family by tag before linting (e.g. design)").option("-c, --cwd <cwd>", "working directory", process.cwd()).action((tag, _options, command) => rulesIgnoreTagAction(tag, command.optsWithGlobals()));
|
|
20859
21422
|
rules.command("unignore-tag <tag>").description("Stop ignoring a tag previously skipped via ignore-tag").option("-c, --cwd <cwd>", "working directory", process.cwd()).action((tag, _options, command) => rulesUnignoreTagAction(tag, command.optsWithGlobals()));
|
|
21423
|
+
program.command("experimental-lsp", { hidden: false }).description("[experimental] run the React Doctor language server over stdio (for editors)").allowUnknownOption().action(() => {});
|
|
20860
21424
|
process.stdout.on("error", (error) => {
|
|
20861
21425
|
if (error.code === "EPIPE") process.exit(0);
|
|
20862
21426
|
});
|
|
@@ -20868,11 +21432,11 @@ if (process.argv.includes("-V") && !strippedArgv.includes("-V")) {
|
|
|
20868
21432
|
}
|
|
20869
21433
|
applyColorPreference(strippedArgv);
|
|
20870
21434
|
const argv = normalizeHelpInvocation(strippedArgv, knownCommands);
|
|
20871
|
-
program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
|
|
21435
|
+
Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => program.parseAsync(argv)).then(() => flushSentry()).catch(async (error) => {
|
|
20872
21436
|
const isUserError = isExpectedUserError(error);
|
|
20873
21437
|
const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
|
|
20874
21438
|
if (isJsonModeActive()) {
|
|
20875
|
-
writeJsonErrorReport(error);
|
|
21439
|
+
writeJsonErrorReport(error, sentryEventId);
|
|
20876
21440
|
process.exit(1);
|
|
20877
21441
|
}
|
|
20878
21442
|
if (isUserError) {
|
|
@@ -20885,4 +21449,4 @@ program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
|
|
|
20885
21449
|
export {};
|
|
20886
21450
|
|
|
20887
21451
|
//# sourceMappingURL=cli.js.map
|
|
20888
|
-
//# debugId=
|
|
21452
|
+
//# debugId=97daaac0-bc19-511e-baba-f43ac0b855ea
|