react-doctor 0.4.2-dev.7cf52d8 → 0.4.2-dev.93d4eec

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1486eaee-ed07-5eef-a9d7-51293140e237")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="299ab690-e278-5f22-b581-ff28a76a28b8")}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";
@@ -8,6 +8,7 @@ import * as fs$1 from "node:fs";
8
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
+ import * as ts from "typescript";
11
12
  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";
12
13
  import * as Cause from "effect/Cause";
13
14
  import * as Effect from "effect/Effect";
@@ -32,9 +33,8 @@ import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem";
32
33
  import * as NodePath from "@effect/platform-node-shared/NodePath";
33
34
  import * as ChildProcess from "effect/unstable/process/ChildProcess";
34
35
  import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
35
- import * as ts from "typescript";
36
36
  import { gzipSync } from "node:zlib";
37
- import { createHash, randomUUID } from "node:crypto";
37
+ import crypto, { createHash, randomUUID } from "node:crypto";
38
38
  import * as Exit from "effect/Exit";
39
39
  import * as Sentry from "@sentry/node";
40
40
  import { performance } from "node:perf_hooks";
@@ -5151,8 +5151,8 @@ const isFile = (filePath) => {
5151
5151
  return false;
5152
5152
  }
5153
5153
  };
5154
- const SOURCE_FILE_PATTERN = /\.(tsx?|jsx?)$/;
5155
- const GENERATED_BUNDLE_FILE_PATTERN = /\.(iife|umd|global|min)\.js$/i;
5154
+ const SOURCE_FILE_PATTERN = /\.(tsx?|jsx?|mts|mjs)$/;
5155
+ const GENERATED_BUNDLE_FILE_PATTERN = /\.(iife|umd|global|min)\.m?js$/i;
5156
5156
  const MINIFIED_SNIFF_BYTES = 65536;
5157
5157
  const GIT_LS_FILES_MAX_BUFFER_BYTES = 50 * 1024 * 1024;
5158
5158
  const IGNORED_DIRECTORIES = new Set([
@@ -6064,6 +6064,204 @@ const resolveEffectiveReactMajor = (reactVersion, packageJson) => {
6064
6064
  if (peerFloor === null) return hasUpperBoundOnlyPeerRange(peerReactRange) ? null : installedReactMajor;
6065
6065
  return installedReactMajor !== null ? Math.min(installedReactMajor, peerFloor) : peerFloor;
6066
6066
  };
6067
+ const JSX_FILE_PATTERN = /\.(tsx|jsx)$/;
6068
+ const MILLISECONDS_PER_SECOND = 1e3;
6069
+ const SCORE_API_URL = "https://www.react.doctor/api/score";
6070
+ const ENTERPRISE_CONTACT_URL = "https://react.doctor/enterprise";
6071
+ const SHARE_BASE_URL = "https://react.doctor/share";
6072
+ const CI_URL = "https://react.doctor/ci";
6073
+ const GITHUB_ACTIONS_SETUP_URL = "https://www.react.doctor/docs/ci-and-prs/github-actions-setup";
6074
+ const DOCS_URL = "https://react.doctor/docs";
6075
+ const DOCS_RULES_BASE_URL = `${DOCS_URL}/rules`;
6076
+ const FETCH_TIMEOUT_MS = 1e4;
6077
+ const GITHUB_VIEWER_PERMISSION_TIMEOUT_MS = 2e3;
6078
+ const DEFAULT_BRANCH_CANDIDATES = ["main", "master"];
6079
+ const ADOPTABLE_LINT_CONFIG_FILENAMES = [".oxlintrc.json", ".eslintrc.json"];
6080
+ const OXLINT_NODE_REQUIREMENT = "^20.19.0 || >=22.12.0";
6081
+ const GIT_SHOW_MAX_BUFFER_BYTES = 10 * 1024 * 1024;
6082
+ const ES_TARGET_YEAR_BY_NAME = {
6083
+ es3: 1999,
6084
+ es5: 2009,
6085
+ es6: 2015,
6086
+ es2015: 2015,
6087
+ es2016: 2016,
6088
+ es2017: 2017,
6089
+ es2018: 2018,
6090
+ es2019: 2019,
6091
+ es2020: 2020,
6092
+ es2021: 2021,
6093
+ es2022: 2022,
6094
+ es2023: 2023,
6095
+ es2024: 2024,
6096
+ es2025: 2025,
6097
+ esnext: 9999
6098
+ };
6099
+ /**
6100
+ * Project-config files that `StagedFiles.materialize` copies into
6101
+ * the temp directory alongside staged sources so oxlint resolves
6102
+ * `tsconfig` / `package.json` / lint configs the same way it would
6103
+ * in the working tree. Hoisted out of the staged-files helper so
6104
+ * the constant lives next to the rest of the IO budget knobs.
6105
+ */
6106
+ const STAGED_FILES_PROJECT_CONFIG_FILENAMES = [
6107
+ "tsconfig.json",
6108
+ "tsconfig.base.json",
6109
+ "package.json",
6110
+ "doctor.config.ts",
6111
+ "doctor.config.mts",
6112
+ "doctor.config.cts",
6113
+ "doctor.config.js",
6114
+ "doctor.config.mjs",
6115
+ "doctor.config.cjs",
6116
+ "doctor.config.json",
6117
+ "doctor.config.jsonc",
6118
+ "oxlint.json",
6119
+ ".oxlintrc.json"
6120
+ ];
6121
+ const CONFIG_FINGERPRINT_FILENAMES = [
6122
+ "doctor.config.ts",
6123
+ "doctor.config.mts",
6124
+ "doctor.config.cts",
6125
+ "doctor.config.js",
6126
+ "doctor.config.mjs",
6127
+ "doctor.config.cjs",
6128
+ "doctor.config.json",
6129
+ "doctor.config.jsonc",
6130
+ "react-doctor.config.json",
6131
+ "package.json",
6132
+ "pnpm-workspace.yaml",
6133
+ "tsconfig.json",
6134
+ "tsconfig.base.json",
6135
+ ".oxlintrc.json",
6136
+ ".eslintrc.json",
6137
+ "pnpm-lock.yaml",
6138
+ "package-lock.json",
6139
+ "yarn.lock",
6140
+ "bun.lock",
6141
+ "bun.lockb",
6142
+ ".gitignore"
6143
+ ];
6144
+ const CANONICAL_GITHUB_URL = "https://github.com/millionco/react-doctor";
6145
+ const CANONICAL_DISCORD_URL = "https://react.doctor/discord";
6146
+ const SKILL_NAME = "react-doctor";
6147
+ const OXLINT_OUTPUT_MAX_BYTES = 50 * 1024 * 1024;
6148
+ const OXLINT_SPAWN_TIMEOUT_MS = 6e4;
6149
+ const DEAD_CODE_WORKER_MAX_OLD_SPACE_MB = 8192;
6150
+ const RECOMMENDED_PNPM_MINIMUM_RELEASE_AGE_MINUTES = 10080;
6151
+ const DIAGNOSTIC_CATEGORY_BUCKETS = [
6152
+ "Security",
6153
+ "Bugs",
6154
+ "Performance",
6155
+ "Accessibility",
6156
+ "Maintainability"
6157
+ ];
6158
+ const APP_ONLY_RULE_KEYS = new Set([
6159
+ "react-hooks-js/static-components",
6160
+ "react-doctor/no-render-prop-children",
6161
+ "react-doctor/prefer-explicit-variants"
6162
+ ]);
6163
+ const COMPILER_CLEANUP_BUCKET = "compiler-cleanup";
6164
+ const COMPILER_CLEANUP_RULE_KEYS = new Set(["react-doctor/react-compiler-no-manual-memoization"]);
6165
+ const MAX_GLOB_PATTERN_LENGTH_CHARS = 1024;
6166
+ const CONFIG_CACHE_TTL_MS = 300 * 1e3;
6167
+ const TSCONFIG_FILENAME = "tsconfig.json";
6168
+ const isRelativeExtendsValue = (extendsValue) => extendsValue.startsWith("./") || extendsValue.startsWith("../") || path$1.isAbsolute(extendsValue);
6169
+ const ensureJsonExtension = (filePath) => path$1.extname(filePath) === "" ? `${filePath}.json` : filePath;
6170
+ const resolvePackageExtendsPath = (extendsValue, fromConfigDirectory) => {
6171
+ const requireFromConfig = createRequire(path$1.join(fromConfigDirectory, "tsconfig.json"));
6172
+ const candidates = [
6173
+ extendsValue,
6174
+ ensureJsonExtension(extendsValue),
6175
+ `${extendsValue.replace(/\/$/, "")}/tsconfig.json`
6176
+ ];
6177
+ for (const candidate of candidates) try {
6178
+ return requireFromConfig.resolve(candidate);
6179
+ } catch {
6180
+ continue;
6181
+ }
6182
+ return null;
6183
+ };
6184
+ const resolveExtendsPath = (extendsValue, fromConfigDirectory) => {
6185
+ if (isRelativeExtendsValue(extendsValue)) return ensureJsonExtension(path$1.resolve(fromConfigDirectory, extendsValue));
6186
+ return resolvePackageExtendsPath(extendsValue, fromConfigDirectory);
6187
+ };
6188
+ const normalizeCompilerOptions = (compilerOptions) => {
6189
+ if (!isPlainObject(compilerOptions)) return { hasExplicitLib: false };
6190
+ const target = typeof compilerOptions.target === "string" ? compilerOptions.target : void 0;
6191
+ const hasExplicitLib = Object.hasOwn(compilerOptions, "lib");
6192
+ return {
6193
+ target,
6194
+ lib: Array.isArray(compilerOptions.lib) ? compilerOptions.lib.filter((entry) => typeof entry === "string") : void 0,
6195
+ hasExplicitLib
6196
+ };
6197
+ };
6198
+ const readTsConfig = (filePath) => {
6199
+ let content;
6200
+ try {
6201
+ content = fs$1.readFileSync(filePath, "utf-8");
6202
+ } catch {
6203
+ return null;
6204
+ }
6205
+ const parsed = ts.parseConfigFileTextToJson(filePath, content);
6206
+ if (!isPlainObject(parsed.config)) return null;
6207
+ return {
6208
+ extends: typeof parsed.config.extends === "string" ? parsed.config.extends : void 0,
6209
+ compilerOptions: normalizeCompilerOptions(parsed.config.compilerOptions)
6210
+ };
6211
+ };
6212
+ const mergeCompilerOptions = (inherited, current) => {
6213
+ const target = current.target ?? inherited?.target;
6214
+ const hasExplicitLib = current.hasExplicitLib || Boolean(inherited?.hasExplicitLib);
6215
+ return {
6216
+ target,
6217
+ lib: current.hasExplicitLib ? current.lib : inherited?.lib,
6218
+ hasExplicitLib
6219
+ };
6220
+ };
6221
+ const readResolvedCompilerOptions = (tsConfigPath, extendsDepth, visitedPaths) => {
6222
+ const realPath = fs$1.realpathSync.native(tsConfigPath);
6223
+ if (visitedPaths.has(realPath)) return null;
6224
+ const tsConfig = readTsConfig(realPath);
6225
+ if (!tsConfig) return null;
6226
+ const nextVisitedPaths = new Set(visitedPaths);
6227
+ nextVisitedPaths.add(realPath);
6228
+ if (tsConfig.extends && extendsDepth < 8) {
6229
+ const parentPath = resolveExtendsPath(tsConfig.extends, path$1.dirname(realPath));
6230
+ if (parentPath && isFile(parentPath)) return mergeCompilerOptions(readResolvedCompilerOptions(parentPath, extendsDepth + 1, nextVisitedPaths), tsConfig.compilerOptions);
6231
+ }
6232
+ return tsConfig.compilerOptions;
6233
+ };
6234
+ const targetYearIsPreES2023 = (target) => {
6235
+ const year = ES_TARGET_YEAR_BY_NAME[target.toLowerCase()];
6236
+ return year !== void 0 && year < 2023;
6237
+ };
6238
+ const libEntryIncludesES2023Array = (entry) => {
6239
+ const normalizedEntry = entry.toLowerCase();
6240
+ if (normalizedEntry === "esnext" || normalizedEntry === "esnext.array") return true;
6241
+ const esYearMatch = /^es(\d{4})(?:\.(.+))?$/.exec(normalizedEntry);
6242
+ if (!esYearMatch) return false;
6243
+ if (Number(esYearMatch[1]) < 2023) return false;
6244
+ const component = esYearMatch[2];
6245
+ return component === void 0 || component === "array";
6246
+ };
6247
+ const libIncludesES2023 = (lib) => lib.some(libEntryIncludesES2023Array);
6248
+ const compilerOptionsArePreES2023 = (compilerOptions) => {
6249
+ if (compilerOptions.hasExplicitLib) return !libIncludesES2023(compilerOptions.lib ?? []);
6250
+ if (compilerOptions.target) return targetYearIsPreES2023(compilerOptions.target);
6251
+ return false;
6252
+ };
6253
+ const compilerOptionsDeclareTargetOrLib = (compilerOptions) => compilerOptions.hasExplicitLib || compilerOptions.target !== void 0;
6254
+ const detectPreES2023FromConfig = (tsConfigPath) => {
6255
+ const compilerOptions = readResolvedCompilerOptions(tsConfigPath, 0, /* @__PURE__ */ new Set());
6256
+ if (!compilerOptions) return false;
6257
+ if (!compilerOptionsDeclareTargetOrLib(compilerOptions)) return false;
6258
+ return compilerOptionsArePreES2023(compilerOptions);
6259
+ };
6260
+ const detectPreES2023Target = (directory) => {
6261
+ const tsConfigPath = path$1.join(directory, TSCONFIG_FILENAME);
6262
+ if (isFile(tsConfigPath)) return detectPreES2023FromConfig(tsConfigPath);
6263
+ return false;
6264
+ };
6067
6265
  const REACT_DEPENDENCY_NAMES = new Set([
6068
6266
  "react",
6069
6267
  "react-native",
@@ -6175,11 +6373,63 @@ const discoverReactSubprojects = (rootDirectory) => {
6175
6373
  return discoverReactSubprojectsByFilesystem(rootDirectory);
6176
6374
  };
6177
6375
  const cachedProjectInfos = /* @__PURE__ */ new Map();
6376
+ /**
6377
+ * Build a `ProjectInfo` for a directory that has no `package.json` of
6378
+ * its own — a monorepo subfolder like `repo/packages`, or any loose tree
6379
+ * of TypeScript/JavaScript files. Dependency + framework detection is
6380
+ * inherited from the enclosing workspace root when there is one, so
6381
+ * scanning a subdirectory of a React monorepo still gets the React
6382
+ * capabilities; a standalone non-React directory simply scans with the
6383
+ * framework-agnostic rules. Throws only when the directory has nothing
6384
+ * to scan (no enclosing project and no source files of its own).
6385
+ */
6386
+ const discoverProjectWithoutPackageJson = (directory) => {
6387
+ const sourceFileCount = countSourceFiles(directory);
6388
+ const hasOwnTsConfig = fs$1.existsSync(path$1.join(directory, "tsconfig.json"));
6389
+ const monorepoRoot = findMonorepoRoot(directory);
6390
+ const enclosingProject = monorepoRoot !== null && isFile(path$1.join(monorepoRoot, "package.json")) ? discoverProject(monorepoRoot) : null;
6391
+ if (enclosingProject !== null) return {
6392
+ ...enclosingProject,
6393
+ rootDirectory: directory,
6394
+ projectName: path$1.basename(directory),
6395
+ hasTypeScript: hasOwnTsConfig || enclosingProject.hasTypeScript,
6396
+ sourceFileCount
6397
+ };
6398
+ if (sourceFileCount === 0) throw new PackageJsonNotFoundError(directory);
6399
+ return {
6400
+ rootDirectory: directory,
6401
+ projectName: path$1.basename(directory),
6402
+ reactVersion: null,
6403
+ reactMajorVersion: null,
6404
+ tailwindVersion: null,
6405
+ zodVersion: null,
6406
+ zodMajorVersion: null,
6407
+ framework: "unknown",
6408
+ hasTypeScript: hasOwnTsConfig,
6409
+ hasReactCompiler: false,
6410
+ hasTanStackQuery: false,
6411
+ preactVersion: null,
6412
+ preactMajorVersion: null,
6413
+ hasReactNativeWorkspace: false,
6414
+ nextjsVersion: null,
6415
+ nextjsMajorVersion: null,
6416
+ expoVersion: null,
6417
+ shopifyFlashListVersion: null,
6418
+ shopifyFlashListMajorVersion: null,
6419
+ hasReanimated: false,
6420
+ isPreES2023Target: hasOwnTsConfig && detectPreES2023Target(directory),
6421
+ sourceFileCount
6422
+ };
6423
+ };
6178
6424
  const discoverProject = (directory) => {
6179
6425
  const cached = cachedProjectInfos.get(directory);
6180
6426
  if (cached !== void 0) return cached;
6181
6427
  const packageJsonPath = path$1.join(directory, "package.json");
6182
- if (!isFile(packageJsonPath)) throw new PackageJsonNotFoundError(directory);
6428
+ if (!isFile(packageJsonPath)) {
6429
+ const synthesized = discoverProjectWithoutPackageJson(directory);
6430
+ cachedProjectInfos.set(directory, synthesized);
6431
+ return synthesized;
6432
+ }
6183
6433
  const packageJson = readPackageJson$1(packageJsonPath);
6184
6434
  let { reactVersion, tailwindVersion, zodVersion, framework } = extractDependencyInfo(packageJson);
6185
6435
  const reactDeclaration = getDependencyDeclaration({
@@ -6265,6 +6515,7 @@ const discoverProject = (directory) => {
6265
6515
  version: findNextjsVersion(directory, packageJson)
6266
6516
  }) : null;
6267
6517
  const preactVersion = getPreactVersion(packageJson);
6518
+ const isPreES2023Target = hasTypeScript && detectPreES2023Target(directory);
6268
6519
  const projectInfo = {
6269
6520
  rootDirectory: directory,
6270
6521
  projectName,
@@ -6286,12 +6537,22 @@ const discoverProject = (directory) => {
6286
6537
  shopifyFlashListVersion,
6287
6538
  shopifyFlashListMajorVersion: shopifyFlashListVersion === null ? null : getLowestDependencyMajor(shopifyFlashListVersion),
6288
6539
  hasReanimated,
6540
+ isPreES2023Target,
6289
6541
  sourceFileCount
6290
6542
  };
6291
6543
  cachedProjectInfos.set(directory, projectInfo);
6292
6544
  return projectInfo;
6293
6545
  };
6294
- const isAnalyzableProject = (project) => project.reactVersion !== null || project.preactVersion !== null;
6546
+ /**
6547
+ * A project is worth scanning when it has React/Preact (the framework-
6548
+ * specific rules apply) OR it simply has source files to lint. The
6549
+ * second arm is what lets a plain TypeScript/JavaScript codebase — no
6550
+ * React dependency at all — run the framework-agnostic rules
6551
+ * (security, architecture, zod, bundle-size, …) instead of hard-failing
6552
+ * with "No React dependency". Only a directory with neither React nor a
6553
+ * single source file has nothing to analyze.
6554
+ */
6555
+ const isAnalyzableProject = (project) => project.reactVersion !== null || project.preactVersion !== null || project.sourceFileCount > 0;
6295
6556
  const MAJOR_MINOR_PATTERN = /(\d{1,4})\.(\d{1,4})/;
6296
6557
  const MAJOR_ONLY_PATTERN = /(\d{1,4})/;
6297
6558
  const UPPER_BOUND_COMPARATOR_PATTERN = /<=?\s{0,8}\d{1,4}(?:\.\d{1,4}){0,2}(?:-[^\s,|]+)?/g;
@@ -6355,65 +6616,6 @@ const isTailwindAtLeast = (detected, required) => {
6355
6616
  if (detected.major !== required.major) return detected.major > required.major;
6356
6617
  return detected.minor >= required.minor;
6357
6618
  };
6358
- const JSX_FILE_PATTERN = /\.(tsx|jsx)$/;
6359
- const MILLISECONDS_PER_SECOND = 1e3;
6360
- const SCORE_API_URL = "https://www.react.doctor/api/score";
6361
- const ENTERPRISE_CONTACT_URL = "https://react.doctor/enterprise";
6362
- const SHARE_BASE_URL = "https://react.doctor/share";
6363
- const CI_URL = "https://react.doctor/ci";
6364
- const DOCS_URL = "https://react.doctor/docs";
6365
- const DOCS_RULES_BASE_URL = `${DOCS_URL}/rules`;
6366
- const FETCH_TIMEOUT_MS = 1e4;
6367
- const GITHUB_VIEWER_PERMISSION_TIMEOUT_MS = 2e3;
6368
- const DEFAULT_BRANCH_CANDIDATES = ["main", "master"];
6369
- const ADOPTABLE_LINT_CONFIG_FILENAMES = [".oxlintrc.json", ".eslintrc.json"];
6370
- const OXLINT_NODE_REQUIREMENT = "^20.19.0 || >=22.12.0";
6371
- const GIT_SHOW_MAX_BUFFER_BYTES = 10 * 1024 * 1024;
6372
- /**
6373
- * Project-config files that `StagedFiles.materialize` copies into
6374
- * the temp directory alongside staged sources so oxlint resolves
6375
- * `tsconfig` / `package.json` / lint configs the same way it would
6376
- * in the working tree. Hoisted out of the staged-files helper so
6377
- * the constant lives next to the rest of the IO budget knobs.
6378
- */
6379
- const STAGED_FILES_PROJECT_CONFIG_FILENAMES = [
6380
- "tsconfig.json",
6381
- "tsconfig.base.json",
6382
- "package.json",
6383
- "doctor.config.ts",
6384
- "doctor.config.mts",
6385
- "doctor.config.cts",
6386
- "doctor.config.js",
6387
- "doctor.config.mjs",
6388
- "doctor.config.cjs",
6389
- "doctor.config.json",
6390
- "doctor.config.jsonc",
6391
- "oxlint.json",
6392
- ".oxlintrc.json"
6393
- ];
6394
- const CANONICAL_GITHUB_URL = "https://github.com/millionco/react-doctor";
6395
- const CANONICAL_DISCORD_URL = "https://react.doctor/discord";
6396
- const SKILL_NAME = "react-doctor";
6397
- const OXLINT_OUTPUT_MAX_BYTES = 50 * 1024 * 1024;
6398
- const OXLINT_SPAWN_TIMEOUT_MS = 6e4;
6399
- const DEAD_CODE_WORKER_MAX_OLD_SPACE_MB = 8192;
6400
- const RECOMMENDED_PNPM_MINIMUM_RELEASE_AGE_MINUTES = 10080;
6401
- const DIAGNOSTIC_CATEGORY_BUCKETS = [
6402
- "Security",
6403
- "Bugs",
6404
- "Performance",
6405
- "Accessibility",
6406
- "Maintainability"
6407
- ];
6408
- const APP_ONLY_RULE_KEYS = new Set([
6409
- "react-hooks-js/static-components",
6410
- "react-doctor/no-render-prop-children",
6411
- "react-doctor/prefer-explicit-variants"
6412
- ]);
6413
- const COMPILER_CLEANUP_BUCKET = "compiler-cleanup";
6414
- const COMPILER_CLEANUP_RULE_KEYS = new Set(["react-doctor/react-compiler-no-manual-memoization"]);
6415
- const MAX_GLOB_PATTERN_LENGTH_CHARS = 1024;
6416
- const CONFIG_CACHE_TTL_MS = 300 * 1e3;
6417
6619
  var InvalidGlobPatternError = class extends Error {
6418
6620
  pattern;
6419
6621
  reason;
@@ -6724,7 +6926,6 @@ const LEGACY_RULE_KEY_TO_NATIVE_RULE_KEY = {
6724
6926
  "react/jsx-no-new-function-as-prop": "react-doctor/jsx-no-new-function-as-prop",
6725
6927
  "react/jsx-no-new-object-as-prop": "react-doctor/jsx-no-new-object-as-prop",
6726
6928
  "react/jsx-no-script-url": "react-doctor/jsx-no-script-url",
6727
- "react/jsx-no-target-blank": "react-doctor/jsx-no-target-blank",
6728
6929
  "react/jsx-no-undef": "react-doctor/jsx-no-undef",
6729
6930
  "react/jsx-no-useless-fragment": "react-doctor/jsx-no-useless-fragment",
6730
6931
  "react/jsx-pascal-case": "react-doctor/jsx-pascal-case",
@@ -7920,51 +8121,51 @@ const FLAGGED_DEPENDENCIES = [
7920
8121
  {
7921
8122
  packageName: "expo-modules-autolinking",
7922
8123
  rule: "expo-no-redundant-dependency",
7923
- message: "\"expo-modules-autolinking\" should not be a direct dependency — Expo installs it transitively as needed",
8124
+ message: "\"expo-modules-autolinking\" should not be a direct dependency. Expo pins the compatible version through the SDK, and a direct entry can drift to a version that breaks prebuild, Metro, or native builds",
7924
8125
  help: "Remove `expo-modules-autolinking` from your package.json"
7925
8126
  },
7926
8127
  {
7927
8128
  packageName: "expo-dev-launcher",
7928
8129
  rule: "expo-no-redundant-dependency",
7929
- message: "\"expo-dev-launcher\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
8130
+ message: "\"expo-dev-launcher\" should not be a direct dependency. `expo-dev-client` pins the compatible launcher, and a direct entry can drift to a version that breaks native builds",
7930
8131
  help: "Remove `expo-dev-launcher` and depend on `expo-dev-client` instead"
7931
8132
  },
7932
8133
  {
7933
8134
  packageName: "expo-dev-menu",
7934
8135
  rule: "expo-no-redundant-dependency",
7935
- message: "\"expo-dev-menu\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
8136
+ message: "\"expo-dev-menu\" should not be a direct dependency. `expo-dev-client` pins the compatible dev menu, and a direct entry can drift to a version that breaks native builds",
7936
8137
  help: "Remove `expo-dev-menu` and depend on `expo-dev-client` instead"
7937
8138
  },
7938
8139
  {
7939
8140
  packageName: "expo-modules-core",
7940
8141
  rule: "expo-no-redundant-dependency",
7941
- message: "\"expo-modules-core\" should not be a direct dependency — use the API re-exported from the `expo` package",
8142
+ message: "\"expo-modules-core\" should not be a direct dependency. Expo pins the compatible native core, and a direct entry can drift to a version that breaks prebuild or native builds",
7942
8143
  help: "Remove `expo-modules-core` from your package.json and import from `expo` instead"
7943
8144
  },
7944
8145
  {
7945
8146
  packageName: "@expo/metro-config",
7946
8147
  rule: "expo-no-redundant-dependency",
7947
- message: "\"@expo/metro-config\" should not be a direct dependency — use the `expo/metro-config` sub-export of the `expo` package",
8148
+ message: "\"@expo/metro-config\" should not be a direct dependency. Expo pins the compatible Metro config, and a direct entry can drift to a version that breaks bundling",
7948
8149
  help: "Remove `@expo/metro-config` and import `expo/metro-config` in your metro.config.js"
7949
8150
  },
7950
8151
  {
7951
8152
  packageName: "@types/react-native",
7952
8153
  rule: "expo-no-redundant-dependency",
7953
- message: "\"@types/react-native\" should not be installed — React Native ships its own types since SDK 48",
8154
+ message: "\"@types/react-native\" should not be installed. React Native ships its own types since SDK 48, so the extra package can introduce duplicate or stale type definitions",
7954
8155
  help: "Remove `@types/react-native` from your package.json",
7955
8156
  minSdkMajor: 48
7956
8157
  },
7957
8158
  {
7958
8159
  packageName: "@expo/config-plugins",
7959
8160
  rule: "expo-no-redundant-dependency",
7960
- message: "\"@expo/config-plugins\" should not be a direct dependency — use the `expo/config-plugins` sub-export of the `expo` package",
8161
+ message: "\"@expo/config-plugins\" should not be a direct dependency. Expo pins the compatible config-plugin API, and a direct entry can drift to a version that breaks prebuild",
7961
8162
  help: "Remove `@expo/config-plugins`; config-plugin authors should import from `expo/config-plugins`. See https://github.com/expo/expo/pull/18855",
7962
8163
  minSdkMajor: 48
7963
8164
  },
7964
8165
  {
7965
8166
  packageName: "@expo/prebuild-config",
7966
8167
  rule: "expo-no-redundant-dependency",
7967
- message: "\"@expo/prebuild-config\" should not be a direct dependency — Expo installs it transitively",
8168
+ message: "\"@expo/prebuild-config\" should not be a direct dependency. Expo pins the compatible prebuild config, and a direct entry can drift to a version that breaks prebuild",
7968
8169
  help: "Remove `@expo/prebuild-config` from your package.json",
7969
8170
  minSdkMajor: 53
7970
8171
  },
@@ -7978,28 +8179,28 @@ const FLAGGED_DEPENDENCIES = [
7978
8179
  {
7979
8180
  packageName: "expo-app-loading",
7980
8181
  rule: "expo-no-redundant-dependency",
7981
- message: "\"expo-app-loading\" was removed in SDK 49",
8182
+ message: "\"expo-app-loading\" was removed in SDK 49, so keeping it can leave imports unresolved after upgrading Expo",
7982
8183
  help: "Remove `expo-app-loading` and use `expo-splash-screen` instead. See https://docs.expo.dev/versions/latest/sdk/splash-screen/",
7983
8184
  minSdkMajor: 49
7984
8185
  },
7985
8186
  {
7986
8187
  packageName: "expo-firebase-analytics",
7987
8188
  rule: "expo-no-redundant-dependency",
7988
- message: "\"expo-firebase-analytics\" was removed in SDK 48",
8189
+ message: "\"expo-firebase-analytics\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7989
8190
  help: FIREBASE_HELP,
7990
8191
  minSdkMajor: 48
7991
8192
  },
7992
8193
  {
7993
8194
  packageName: "expo-firebase-recaptcha",
7994
8195
  rule: "expo-no-redundant-dependency",
7995
- message: "\"expo-firebase-recaptcha\" was removed in SDK 48",
8196
+ message: "\"expo-firebase-recaptcha\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7996
8197
  help: FIREBASE_HELP,
7997
8198
  minSdkMajor: 48
7998
8199
  },
7999
8200
  {
8000
8201
  packageName: "expo-firebase-core",
8001
8202
  rule: "expo-no-redundant-dependency",
8002
- message: "\"expo-firebase-core\" was removed in SDK 48",
8203
+ message: "\"expo-firebase-core\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
8003
8204
  help: FIREBASE_HELP,
8004
8205
  minSdkMajor: 48
8005
8206
  }
@@ -8040,7 +8241,7 @@ const checkExpoGitignore = (context) => {
8040
8241
  }));
8041
8242
  if (findLocalModuleNativeFiles(rootDirectory).find((nativeFilePath) => isPathGitIgnored(rootDirectory, nativeFilePath) === true) !== void 0) diagnostics.push(buildExpoDiagnostic({
8042
8243
  rule: "expo-gitignore",
8043
- message: "The native `ios`/`android` directories of a local Expo module under `modules/` are gitignored — usually caused by an overly broad `ios`/`android` ignore rule",
8244
+ message: "The native `ios`/`android` directories of a local Expo module under `modules/` are gitignored, so required native code can be missing from CI or teammate checkouts.",
8044
8245
  help: "Use anchored patterns like `/ios` and `/android` in .gitignore so only the top-level native directories are excluded, not those inside `modules/`"
8045
8246
  }));
8046
8247
  return diagnostics;
@@ -8102,17 +8303,16 @@ const checkExpoPackageJsonConflicts = (context) => {
8102
8303
  const conflictingScriptNames = CONFLICTING_SCRIPT_NAMES.filter((scriptName) => Boolean(packageJson.scripts?.[scriptName]));
8103
8304
  if (conflictingScriptNames.length > 0) {
8104
8305
  const quotedNames = conflictingScriptNames.map((name) => `"${name}"`).join(", ");
8105
- const shadowsExpoCli = conflictingScriptNames.includes("expo");
8106
8306
  diagnostics.push(buildExpoDiagnostic({
8107
8307
  rule: "expo-package-json-conflict",
8108
- message: `package.json defines ${quotedNames} ${conflictingScriptNames.length === 1 ? "as a script that conflicts" : "as scripts that conflict"} with binaries in node_modules/.bin${shadowsExpoCli ? " — a `expo` script shadows the Expo CLI and will likely cause build failures" : ""}`,
8308
+ message: `package.json defines ${quotedNames} ${conflictingScriptNames.length === 1 ? "as a script that shadows" : "as scripts that shadow"} Expo/React Native binaries in node_modules/.bin, so tooling can run the local script instead of the expected CLI and fail builds.`,
8109
8309
  help: "Rename these scripts so they don't collide with the `expo` / `react-native` binaries"
8110
8310
  }));
8111
8311
  }
8112
8312
  const packageName = packageJson.name;
8113
8313
  if (typeof packageName === "string" && context.directDependencyNames.has(packageName)) diagnostics.push(buildExpoDiagnostic({
8114
8314
  rule: "expo-package-json-conflict",
8115
- message: `package.json "name" is "${packageName}", which collides with a dependency of the same name`,
8315
+ message: `package.json "name" is "${packageName}", which collides with a dependency of the same name, so package self-resolution can shadow the dependency and break imports that expect the installed package.`,
8116
8316
  help: "Rename your package so it no longer matches one of its dependencies"
8117
8317
  }));
8118
8318
  return diagnostics;
@@ -8183,7 +8383,7 @@ const checkExpoRouterReactNavigation = (context) => {
8183
8383
  if (reactNavigationNames.length === 0) return [];
8184
8384
  return [buildExpoDiagnostic({
8185
8385
  rule: "expo-router-no-react-navigation",
8186
- message: `As of SDK 56, expo-router is no longer compatible with react-navigation, but ${reactNavigationNames.map((name) => `"${name}"`).join(", ")} ${reactNavigationNames.length === 1 ? "is" : "are"} installed as direct ${reactNavigationNames.length === 1 ? "dependency" : "dependencies"}`,
8386
+ message: `As of SDK 56, expo-router is no longer compatible with directly installed @react-navigation packages, so keeping ${reactNavigationNames.map((name) => `"${name}"`).join(", ")} can break routing or linking behavior after the SDK upgrade.`,
8187
8387
  help: "Remove these `@react-navigation/*` packages and replace direct imports with their expo-router equivalents. See https://docs.expo.dev/router/migrate/sdk-55-to-56/"
8188
8388
  })];
8189
8389
  };
@@ -8555,7 +8755,9 @@ const setColorEnabled = (enabled) => {
8555
8755
  highlighter.gray = colors.gray;
8556
8756
  highlighter.bold = colors.bold;
8557
8757
  };
8558
- const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
8758
+ const NEXT_ENTRY_FILE_PATTERN = /^(?:\.\/)?(?:src\/)?(?:middleware|proxy)\.(?:tsx?|jsx?|mts|mjs)$/;
8759
+ const shouldIncludeExplicitLintPath = (filePath, project) => JSX_FILE_PATTERN.test(filePath) || project?.framework === "nextjs" && NEXT_ENTRY_FILE_PATTERN.test(filePath);
8760
+ const computeExplicitLintIncludePaths = (includePaths, project) => includePaths.length > 0 ? includePaths.filter((filePath) => shouldIncludeExplicitLintPath(filePath, project)) : void 0;
8559
8761
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
8560
8762
  const FALSY_VALUES = new Set([
8561
8763
  "false",
@@ -8635,7 +8837,7 @@ const collectIgnorePatterns = (rootDirectory) => {
8635
8837
  return patterns;
8636
8838
  };
8637
8839
  const KNIP_JSON_FILENAME = "knip.json";
8638
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8840
+ const isRecord$1$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8639
8841
  const readJsonFileSafe = (filePath) => {
8640
8842
  let rawContents;
8641
8843
  try {
@@ -8651,10 +8853,10 @@ const readJsonFileSafe = (filePath) => {
8651
8853
  };
8652
8854
  const readKnipConfig = (rootDirectory) => {
8653
8855
  const knipJson = readJsonFileSafe(path.join(rootDirectory, KNIP_JSON_FILENAME));
8654
- if (isRecord$1(knipJson)) return knipJson;
8856
+ if (isRecord$1$1(knipJson)) return knipJson;
8655
8857
  const packageJson = readJsonFileSafe(path.join(rootDirectory, "package.json"));
8656
- const packageKnipConfig = isRecord$1(packageJson) ? packageJson.knip : null;
8657
- return isRecord$1(packageKnipConfig) ? packageKnipConfig : null;
8858
+ const packageKnipConfig = isRecord$1$1(packageJson) ? packageJson.knip : null;
8859
+ return isRecord$1$1(packageKnipConfig) ? packageKnipConfig : null;
8658
8860
  };
8659
8861
  const normalizePatternList = (value) => {
8660
8862
  if (typeof value === "string" && value.length > 0) return [value];
@@ -8666,10 +8868,10 @@ const prefixWorkspacePatterns = (workspacePattern, patterns) => {
8666
8868
  return patterns.map((pattern) => pattern.startsWith("!") ? `!${normalizedWorkspacePattern}/${pattern.slice(1)}` : `${normalizedWorkspacePattern}/${pattern}`);
8667
8869
  };
8668
8870
  const collectKnipWorkspacePatterns = (workspaces, settingName) => {
8669
- if (!isRecord$1(workspaces)) return [];
8871
+ if (!isRecord$1$1(workspaces)) return [];
8670
8872
  const patterns = [];
8671
8873
  for (const [workspacePattern, workspaceConfig] of Object.entries(workspaces)) {
8672
- if (!isRecord$1(workspaceConfig)) continue;
8874
+ if (!isRecord$1$1(workspaceConfig)) continue;
8673
8875
  patterns.push(...prefixWorkspacePatterns(workspacePattern, normalizePatternList(workspaceConfig[settingName])));
8674
8876
  }
8675
8877
  return patterns;
@@ -8981,7 +9183,7 @@ const checkDeadCode = async (options) => {
8981
9183
  plugin: DEAD_CODE_PLUGIN,
8982
9184
  rule: "unused-file",
8983
9185
  severity: "warning",
8984
- message: "Unused file — not reachable from any entry point",
9186
+ message: "Unused file is not reachable from any entry point, so it adds maintenance surface without shipping any code.",
8985
9187
  help: "Delete the file if it is truly unreachable, or import it from an entry point.",
8986
9188
  line: 0,
8987
9189
  column: 0,
@@ -8994,7 +9196,7 @@ const checkDeadCode = async (options) => {
8994
9196
  plugin: DEAD_CODE_PLUGIN,
8995
9197
  rule: unusedExport.isTypeOnly ? "unused-type" : "unused-export",
8996
9198
  severity: "warning",
8997
- message: `Unused ${label}: \`${unusedExport.name}\``,
9199
+ message: `Unused ${label}: \`${unusedExport.name}\` is exported but no module imports it, so it expands the public surface and can mislead callers about supported API.`,
8998
9200
  help: "Drop the `export` keyword (or remove the declaration) if no other module uses this symbol.",
8999
9201
  line: unusedExport.line,
9000
9202
  column: unusedExport.column,
@@ -9009,7 +9211,7 @@ const checkDeadCode = async (options) => {
9009
9211
  rule: unusedDependency.isDevDependency ? "unused-dev-dependency" : "unused-dependency",
9010
9212
  severity: "warning",
9011
9213
  message: `Unused ${label}: \`${unusedDependency.name}\``,
9012
- help: "Remove the dependency from package.json if it is genuinely unused.",
9214
+ help: `An unused ${label} adds install time and supply-chain surface without being used; remove it from package.json if it is genuinely unused.`,
9013
9215
  line: 0,
9014
9216
  column: 0,
9015
9217
  category: DEAD_CODE_CATEGORY
@@ -9022,7 +9224,7 @@ const checkDeadCode = async (options) => {
9022
9224
  plugin: DEAD_CODE_PLUGIN,
9023
9225
  rule: "circular-dependency",
9024
9226
  severity: "warning",
9025
- message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}`,
9227
+ message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}. Modules in the cycle can observe partially initialized exports, causing order-dependent bugs.`,
9026
9228
  help: "Break the cycle by extracting the shared code into a third module that both files import.",
9027
9229
  line: 0,
9028
9230
  column: 0,
@@ -9105,11 +9307,11 @@ const listSourceFilesViaFilesystem = (rootDirectory) => {
9105
9307
  return filePaths;
9106
9308
  };
9107
9309
  const listSourceFiles = (rootDirectory) => excludeMinifiedFiles(rootDirectory, listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory));
9108
- const resolveLintIncludePaths = (rootDirectory, userConfig) => {
9310
+ const resolveLintIncludePaths = (rootDirectory, userConfig, project) => {
9109
9311
  if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
9110
9312
  const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
9111
9313
  return listSourceFiles(rootDirectory).filter((filePath) => {
9112
- if (!JSX_FILE_PATTERN.test(filePath)) return false;
9314
+ if (!shouldIncludeExplicitLintPath(filePath, project)) return false;
9113
9315
  return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
9114
9316
  });
9115
9317
  };
@@ -9812,6 +10014,7 @@ const neutralizeDisableDirectives = async (rootDirectory, includePaths) => {
9812
10014
  const buildCapabilities = (project) => {
9813
10015
  const capabilities = /* @__PURE__ */ new Set();
9814
10016
  capabilities.add(project.framework);
10017
+ if (project.reactVersion !== null || project.preactVersion !== null) capabilities.add("react");
9815
10018
  if (project.framework === "expo" || project.framework === "react-native" || project.hasReactNativeWorkspace) capabilities.add("react-native");
9816
10019
  if (project.expoVersion !== null) capabilities.add("expo");
9817
10020
  if (project.nextjsMajorVersion !== null && project.nextjsMajorVersion >= 15) capabilities.add("nextjs:15");
@@ -9837,6 +10040,7 @@ const buildCapabilities = (project) => {
9837
10040
  capabilities.add("zod");
9838
10041
  if (project.zodMajorVersion !== null && project.zodMajorVersion >= 4) capabilities.add("zod:4");
9839
10042
  }
10043
+ if (project.isPreES2023Target) capabilities.add("pre-es2023");
9840
10044
  if (project.hasReactCompiler) capabilities.add("react-compiler");
9841
10045
  if (project.hasTanStackQuery) capabilities.add("tanstack-query");
9842
10046
  if (project.hasTypeScript) capabilities.add("typescript");
@@ -9855,6 +10059,7 @@ const shouldEnableRule = (requires, tags, capabilities, ignoredTags, disabledBy)
9855
10059
  if (requires) {
9856
10060
  for (const capability of requires) if (!capabilities.has(capability)) return false;
9857
10061
  }
10062
+ if (tags?.includes("react-jsx-only") && !capabilities.has("react")) return false;
9858
10063
  if (disabledBy) {
9859
10064
  for (const capability of disabledBy) if (capabilities.has(capability)) return false;
9860
10065
  }
@@ -9889,16 +10094,16 @@ const readPluginShape = (pluginSpecifier, loadModule) => {
9889
10094
  ruleNames: new Set(Object.keys(rules))
9890
10095
  };
9891
10096
  };
9892
- const bundledRequire = createRequire(import.meta.url);
10097
+ const bundledRequire$1 = createRequire(import.meta.url);
9893
10098
  const resolveReactHooksJsPlugin = (hasReactCompiler, customRulesOnly) => {
9894
10099
  if (!hasReactCompiler || customRulesOnly) return null;
9895
10100
  let pluginSpecifier;
9896
10101
  try {
9897
- pluginSpecifier = bundledRequire.resolve("eslint-plugin-react-hooks");
10102
+ pluginSpecifier = bundledRequire$1.resolve("eslint-plugin-react-hooks");
9898
10103
  } catch {
9899
10104
  return null;
9900
10105
  }
9901
- const { ruleNames } = readPluginShape(pluginSpecifier, (spec) => bundledRequire(spec));
10106
+ const { ruleNames } = readPluginShape(pluginSpecifier, (spec) => bundledRequire$1(spec));
9902
10107
  return {
9903
10108
  entry: {
9904
10109
  name: "react-hooks-js",
@@ -11461,7 +11666,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
11461
11666
  directory: scanDirectory,
11462
11667
  repo
11463
11668
  }).pipe(Effect.orElseSucceed(() => null)) : Effect.succeed(null));
11464
- const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeJsxIncludePaths([...input.includePaths])) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
11669
+ const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeExplicitLintIncludePaths([...input.includePaths], project)) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config, project);
11465
11670
  const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path$1.resolve(scanDirectory, relativePath)) : [];
11466
11671
  const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
11467
11672
  const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
@@ -12047,6 +12252,22 @@ const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
12047
12252
  * instead of being improvised per diagnostic.
12048
12253
  */
12049
12254
  const buildRuleDocsUrl = (plugin, rule) => `${DOCS_RULES_BASE_URL}/${plugin}/${rule}`;
12255
+ const computeConfigFingerprint = (projectDirectory, version) => {
12256
+ const parts = [`v=${version}`];
12257
+ let directory = projectDirectory;
12258
+ for (;;) {
12259
+ for (const filename of CONFIG_FINGERPRINT_FILENAMES) try {
12260
+ const stat = fs.statSync(path.join(directory, filename));
12261
+ parts.push(`${directory}/${filename}=${stat.mtimeMs}:${stat.size}`);
12262
+ } catch {
12263
+ continue;
12264
+ }
12265
+ const parent = path.dirname(directory);
12266
+ if (parent === directory) break;
12267
+ directory = parent;
12268
+ }
12269
+ return crypto.createHash("sha1").update(parts.join("|")).digest("hex");
12270
+ };
12050
12271
  const groupBy = (items, keyFn) => {
12051
12272
  const groups = /* @__PURE__ */ new Map();
12052
12273
  for (const item of items) {
@@ -12247,7 +12468,7 @@ const makeNoopConsole = () => ({
12247
12468
  });
12248
12469
  //#endregion
12249
12470
  //#region src/cli/utils/version.ts
12250
- const VERSION = "0.4.2-dev.7cf52d8";
12471
+ const VERSION = "0.4.2-dev.93d4eec";
12251
12472
  //#endregion
12252
12473
  //#region src/cli/utils/json-mode.ts
12253
12474
  let context = null;
@@ -12605,13 +12826,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12605
12826
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12606
12827
  * standard `SENTRY_RELEASE` override.
12607
12828
  */
12608
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.7cf52d8`;
12829
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.93d4eec`;
12609
12830
  /**
12610
12831
  * Deployment environment shown in Sentry's environment filter. Defaults to
12611
12832
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12612
12833
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12613
12834
  */
12614
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.7cf52d8") ? "development" : "production");
12835
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.93d4eec") ? "development" : "production");
12615
12836
  /**
12616
12837
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12617
12838
  * (set to `0` to disable tracing) and falls back to
@@ -15874,13 +16095,14 @@ const buildRuntimeLayers = (input) => {
15874
16095
  const linterLayer = input.shouldSkipLint ? Linter.layerOf([]) : Linter.layerOxlint;
15875
16096
  const deadCodeLayer = input.shouldRunDeadCode ? DeadCode.layerNode : DeadCode.layerOf([]);
15876
16097
  const scoreLayer = input.shouldComputeScore ? Score.layerHttp : Score.layerOf(null);
16098
+ const projectLayer = input.projectInfoOverride === void 0 ? Project.layerNode : Project.layerOf(input.projectInfoOverride);
15877
16099
  const progressLayer = input.shouldShowProgressSpinners ? Progress.layerOra(buildSpinnerProgressHandle) : Progress.layerNoop;
15878
16100
  const configLayer = input.hasConfigOverride ? Config.layerOf({
15879
16101
  config: input.userConfig,
15880
16102
  resolvedDirectory: input.directory,
15881
16103
  configSourceDirectory: input.configSourceDirectory
15882
16104
  }) : Config.layerNode;
15883
- const baseLayers = Layer.mergeAll(Project.layerNode, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
16105
+ const baseLayers = Layer.mergeAll(projectLayer, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15884
16106
  return input.oxlintConcurrency === void 0 ? baseLayers : Layer.mergeAll(baseLayers, Layer.succeed(OxlintConcurrency, input.oxlintConcurrency));
15885
16107
  };
15886
16108
  //#endregion
@@ -16473,8 +16695,22 @@ const buildCodeFrame = (input) => {
16473
16695
  });
16474
16696
  };
16475
16697
  //#endregion
16698
+ //#region src/cli/utils/resolve-measure-width.ts
16699
+ const resolveClampedWidth = (input) => {
16700
+ const terminalColumns = process.stdout.columns;
16701
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16702
+ const availableColumns = terminalColumns - input.reservedColumns;
16703
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16704
+ };
16705
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16706
+ reservedColumns,
16707
+ fullWidth: 60,
16708
+ minWidth: 24
16709
+ });
16710
+ //#endregion
16476
16711
  //#region src/cli/utils/build-section-divider.ts
16477
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16712
+ const DIVIDER_INDENT = " ";
16713
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16478
16714
  //#endregion
16479
16715
  //#region src/cli/utils/indent-multiline-text.ts
16480
16716
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16592,6 +16828,11 @@ const printCategoryCountUp = (tallies) => Effect.gen(function* () {
16592
16828
  });
16593
16829
  const TOP_ERROR_DETAIL_INDENT = " ";
16594
16830
  const pickRepresentativeDiagnostic = (ruleDiagnostics) => ruleDiagnostics.find((diagnostic) => diagnostic.line > 0) ?? ruleDiagnostics[0];
16831
+ const hasIndistinctSiteLocations = (ruleDiagnostics) => {
16832
+ const firstDiagnostic = ruleDiagnostics[0];
16833
+ if (firstDiagnostic === void 0) return false;
16834
+ return ruleDiagnostics.every((diagnostic) => diagnostic.line <= 0 && diagnostic.filePath === firstDiagnostic.filePath);
16835
+ };
16595
16836
  const FRAME_CONTEXT_REACH_LINES = 3;
16596
16837
  const clusterNearbyDiagnostics = (diagnostics) => {
16597
16838
  const byFile = groupBy(diagnostics, (diagnostic) => diagnostic.filePath);
@@ -16634,7 +16875,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16634
16875
  endLine: isMultiSite ? cluster.endLine : void 0,
16635
16876
  rootDirectory: resolveSourceRoot(lead)
16636
16877
  }) : null;
16637
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16878
+ if (codeFrame) {
16879
+ const boxInnerWidth = resolveMeasureWidth(8);
16880
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16881
+ }
16638
16882
  const seenHints = /* @__PURE__ */ new Set();
16639
16883
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16640
16884
  seenHints.add(diagnostic.suppressionHint);
@@ -16652,15 +16896,17 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16652
16896
  const learnMoreLine = formatLearnMoreLine(representative);
16653
16897
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16654
16898
  }
16655
- if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16656
- if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16899
+ const isCollapsedWarningGroup = severity === "warning" && hasIndistinctSiteLocations(ruleDiagnostics);
16900
+ const impactMessages = isCollapsedWarningGroup ? [...new Set(ruleDiagnostics.map((diagnostic) => diagnostic.message))] : [representative.message];
16901
+ for (const impactMessage of impactMessages) for (const explanationLine of wrapTextToWidth(impactMessage, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16902
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16657
16903
  if (renderEverySite && isAgentEnvironment) {
16658
16904
  const fixRecipeLine = formatFixRecipeLine(representative);
16659
16905
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
16660
16906
  }
16661
16907
  const renderCodeFrame = severity === "error";
16662
16908
  const sites = renderEverySite ? ruleDiagnostics : [representative];
16663
- for (const cluster of clusterNearbyDiagnostics(sites)) lines.push(...buildDiagnosticClusterLines(cluster, resolveSourceRoot, renderCodeFrame));
16909
+ if (!(isCollapsedWarningGroup && representative.help.includes(representative.filePath))) for (const cluster of clusterNearbyDiagnostics(sites)) lines.push(...buildDiagnosticClusterLines(cluster, resolveSourceRoot, renderCodeFrame));
16664
16910
  return lines;
16665
16911
  };
16666
16912
  const selectErrorRuleGroups = (diagnostics, rulePriority) => buildSortedRuleGroups(diagnostics.filter((diagnostic) => diagnostic.severity === "error"), rulePriority);
@@ -16789,6 +17035,9 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
16789
17035
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
16790
17036
  return potentialScore.score;
16791
17037
  };
17038
+ //#endregion
17039
+ //#region src/cli/utils/filter-diagnostics-by-categories.ts
17040
+ const filterDiagnosticsByCategories = (diagnostics, categories) => categories.size === 0 ? [...diagnostics] : diagnostics.filter((diagnostic) => categories.has(diagnostic.category));
16792
17041
  const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16793
17042
  const FALSY_FLAG_VALUES = new Set([
16794
17043
  "",
@@ -16847,14 +17096,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16847
17096
  const RAINBOW_GRADIENT_WIDTH = 80;
16848
17097
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16849
17098
  const RAINBOW_OKLCH_CHROMA = .129;
17099
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
17100
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
17101
+ const getScoreBarWidth = () => resolveClampedWidth({
17102
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
17103
+ fullWidth: 50,
17104
+ minWidth: 10
17105
+ });
16850
17106
  const buildScoreBarSegments = (filledCount) => {
16851
- const emptyCount = 50 - filledCount;
17107
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16852
17108
  return {
16853
17109
  filledSegment: "█".repeat(filledCount),
16854
17110
  emptySegment: "░".repeat(emptyCount)
16855
17111
  };
16856
17112
  };
16857
- const getFilledCount = (score) => Math.round(score / 100 * 50);
17113
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16858
17114
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16859
17115
  const buildRawScoreBar = (displayScore) => {
16860
17116
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16890,10 +17146,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16890
17146
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16891
17147
  };
16892
17148
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
17149
+ const barWidth = getScoreBarWidth();
16893
17150
  const currentFill = getFilledCount(currentScore);
16894
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
17151
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16895
17152
  const gainCount = Math.max(0, potentialFill - currentFill);
16896
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
17153
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16897
17154
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16898
17155
  };
16899
17156
  const getDoctorFace = (score) => {
@@ -16906,7 +17163,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16906
17163
  const buildRawFaceLines = (score) => {
16907
17164
  const [eyes, mouth] = getDoctorFace(score);
16908
17165
  return [
16909
- "┌─────┐",
17166
+ FACE_BOX_TOP_BORDER,
16910
17167
  `│ ${eyes} │`,
16911
17168
  `│ ${mouth} │`,
16912
17169
  "└─────┘"
@@ -17048,6 +17305,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17048
17305
  };
17049
17306
  //#endregion
17050
17307
  //#region src/cli/utils/render-summary.ts
17308
+ const FOOTER_DESCRIPTION_INDENT = " ";
17309
+ const printFooterDescription = (description) => Effect.gen(function* () {
17310
+ const wrapWidth = resolveMeasureWidth(2);
17311
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17312
+ });
17051
17313
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17052
17314
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17053
17315
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17067,14 +17329,14 @@ const printFooter = (input) => Effect.gen(function* () {
17067
17329
  if (!input.isOffline) {
17068
17330
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17069
17331
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17070
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17332
+ yield* printFooterDescription("Tell others how you did on socials");
17071
17333
  yield* Console.log("");
17072
17334
  }
17073
17335
  yield* Console.log(` ${highlighter.bold("Docs:")} ${highlighter.info(DOCS_URL)}`);
17074
- yield* Console.log(highlighter.dim(" Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file"));
17336
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17075
17337
  yield* Console.log("");
17076
17338
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17077
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17339
+ yield* printFooterDescription("Report issues and star the repository!");
17078
17340
  });
17079
17341
  const printSummary = (input) => Effect.gen(function* () {
17080
17342
  if (input.scoreResult) {
@@ -17206,55 +17468,304 @@ const resolveOxlintNodeEffect = (isLintEnabled, isQuiet) => Effect.gen(function*
17206
17468
  });
17207
17469
  const resolveOxlintNode = (isLintEnabled, isQuiet) => Effect.runPromise(resolveOxlintNodeEffect(isLintEnabled, isQuiet).pipe(Effect.provide(NodeResolver.layerNode)));
17208
17470
  //#endregion
17209
- //#region src/inspect.ts
17210
- const silentConsole = makeNoopConsole();
17211
- const runConsole = (effect) => {
17212
- Effect.runSync(effect);
17471
+ //#region src/cli/utils/cli-input-error.ts
17472
+ /**
17473
+ * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17474
+ * argument, mutually exclusive flags, or an unknown `--project` name. This is
17475
+ * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17476
+ * through `handleUserError`: a clean, single-line message with no Sentry
17477
+ * report and no "Something went wrong, open a prefilled issue" block.
17478
+ *
17479
+ * The `message` is rendered verbatim, so it must read as a complete,
17480
+ * human-readable sentence that tells the user how to fix their invocation.
17481
+ */
17482
+ var CliInputError = class extends Error {
17483
+ name = "CliInputError";
17213
17484
  };
17214
- const buildIgnoredTags = (userConfig) => {
17215
- const tags = /* @__PURE__ */ new Set();
17216
- if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
17217
- return tags;
17485
+ //#endregion
17486
+ //#region src/cli/utils/resolve-cli-categories.ts
17487
+ const categoryByLowercase = new Map(DIAGNOSTIC_CATEGORY_BUCKETS.map((category) => [category.toLowerCase(), category]));
17488
+ const knownCategoryList = DIAGNOSTIC_CATEGORY_BUCKETS.join(", ");
17489
+ const splitCategoryFlagValue = (value) => value.split(",").map((category) => category.trim()).filter((category) => category.length > 0);
17490
+ const resolveCliCategories = (categoryFlag) => {
17491
+ const rawCategoryValues = categoryFlag === void 0 ? [] : Array.isArray(categoryFlag) ? categoryFlag : [categoryFlag];
17492
+ const resolvedCategories = [];
17493
+ const seenCategories = /* @__PURE__ */ new Set();
17494
+ for (const rawCategoryValue of rawCategoryValues) for (const categoryQuery of splitCategoryFlagValue(rawCategoryValue)) {
17495
+ const matchedCategory = categoryByLowercase.get(categoryQuery.toLowerCase());
17496
+ if (matchedCategory === void 0) throw new CliInputError(`Unknown category "${categoryQuery}". Expected one of: ${knownCategoryList}.`);
17497
+ if (!seenCategories.has(matchedCategory)) {
17498
+ seenCategories.add(matchedCategory);
17499
+ resolvedCategories.push(matchedCategory);
17500
+ }
17501
+ }
17502
+ if (rawCategoryValues.length > 0 && resolvedCategories.length === 0) throw new CliInputError(`--category requires one of: ${knownCategoryList}.`);
17503
+ return resolvedCategories.length > 0 ? resolvedCategories : void 0;
17218
17504
  };
17219
- const mergeInspectOptions = (inputOptions, userConfig) => ({
17220
- lint: inputOptions.lint ?? userConfig?.lint ?? true,
17221
- deadCode: inputOptions.deadCode ?? userConfig?.deadCode ?? true,
17222
- verbose: inputOptions.verbose ?? userConfig?.verbose ?? false,
17223
- scoreOnly: inputOptions.scoreOnly ?? false,
17224
- noScore: inputOptions.noScore ?? userConfig?.noScore ?? false,
17225
- isCi: inputOptions.isCi ?? false,
17226
- isCiOrCodingAgentEnvironment: isCiOrCodingAgentEnvironment(),
17227
- isNonInteractiveEnvironment: isNonInteractiveEnvironment(),
17228
- silent: inputOptions.silent ?? false,
17229
- includePaths: inputOptions.includePaths ?? [],
17230
- customRulesOnly: userConfig?.customRulesOnly ?? false,
17231
- share: userConfig?.share ?? true,
17232
- respectInlineDisables: inputOptions.respectInlineDisables ?? userConfig?.respectInlineDisables ?? true,
17233
- warnings: inputOptions.warnings ?? userConfig?.warnings ?? true,
17234
- adoptExistingLintConfig: userConfig?.adoptExistingLintConfig ?? true,
17235
- ignoredTags: buildIgnoredTags(userConfig),
17236
- outputSurface: inputOptions.outputSurface ?? "cli",
17237
- suppressRendering: inputOptions.suppressRendering ?? false,
17238
- concurrency: inputOptions.concurrency,
17239
- baseline: inputOptions.baseline ?? null
17240
- });
17241
- const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
17242
- parallel: options.concurrency !== void 0,
17243
- workerCount: options.concurrency,
17244
- lint: options.lint,
17245
- deadCode: options.deadCode,
17246
- scoreOnly: options.scoreOnly,
17247
- noScore: options.noScore,
17248
- respectInlineDisables: options.respectInlineDisables,
17249
- showWarnings: options.warnings,
17250
- ignoredTagCount: options.ignoredTags.size,
17251
- hasCustomConfig,
17252
- userConfig
17253
- });
17254
- const inspect = async (directory, inputOptions = {}) => {
17255
- const startTime = performance.now();
17256
- resetSentryRunState();
17257
- const hasConfigOverride = inputOptions.configOverride !== void 0;
17505
+ //#endregion
17506
+ //#region src/cli/utils/scan-result-cache.ts
17507
+ const CACHE_DISABLED_VALUES = new Set(["1", "true"]);
17508
+ const TOOLCHAIN_PACKAGE_SPECIFIERS = [
17509
+ "oxlint",
17510
+ "oxlint/package.json",
17511
+ "oxlint-plugin-react-doctor",
17512
+ "deslop-js/package.json",
17513
+ "eslint-plugin-react-hooks/package.json"
17514
+ ];
17515
+ const bundledRequire = createRequire(import.meta.url);
17516
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17517
+ const normalizeForStableJson = (value) => {
17518
+ if (value === null) return null;
17519
+ if (value === void 0) return void 0;
17520
+ const valueType = typeof value;
17521
+ if (valueType === "string" || valueType === "number" || valueType === "boolean") return value;
17522
+ if (valueType === "bigint" || valueType === "function" || valueType === "symbol") throw new Error("Unsupported cache key value");
17523
+ if (Array.isArray(value)) return value.map((item) => {
17524
+ const normalized = normalizeForStableJson(item);
17525
+ return normalized === void 0 ? null : normalized;
17526
+ });
17527
+ const prototype = Object.getPrototypeOf(value);
17528
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("Unsupported cache key object");
17529
+ const record = value;
17530
+ const normalizedRecord = {};
17531
+ for (const key of Object.keys(record).sort()) {
17532
+ const normalized = normalizeForStableJson(record[key]);
17533
+ if (normalized !== void 0) normalizedRecord[key] = normalized;
17534
+ }
17535
+ return normalizedRecord;
17536
+ };
17537
+ const stringifyStableJson = (value) => {
17538
+ try {
17539
+ return JSON.stringify(normalizeForStableJson(value));
17540
+ } catch {
17541
+ return null;
17542
+ }
17543
+ };
17544
+ const hashString = (value) => crypto.createHash("sha1").update(value).digest("hex");
17545
+ const runGit$1 = (directory, args) => {
17546
+ try {
17547
+ return execFileSync("git", [...args], {
17548
+ cwd: directory,
17549
+ encoding: "utf8",
17550
+ stdio: [
17551
+ "ignore",
17552
+ "pipe",
17553
+ "ignore"
17554
+ ]
17555
+ }).trim();
17556
+ } catch {
17557
+ return null;
17558
+ }
17559
+ };
17560
+ const readHeadSha = (projectDirectory) => runGit$1(projectDirectory, ["rev-parse", "HEAD"]);
17561
+ const isWorktreeClean = (projectDirectory) => {
17562
+ const status = runGit$1(projectDirectory, [
17563
+ "status",
17564
+ "--porcelain=v1",
17565
+ "--untracked-files=normal"
17566
+ ]);
17567
+ return status !== null && status.length === 0;
17568
+ };
17569
+ const hasHiddenTrackedFileState = (projectDirectory) => {
17570
+ const output = runGit$1(projectDirectory, ["ls-files", "-v"]);
17571
+ if (output === null) return true;
17572
+ return output.split("\n").some((line) => line.length > 0 && line[0] !== "H");
17573
+ };
17574
+ const resolveCacheFilePath = (projectDirectory) => {
17575
+ const nodeModulesDirectory = path.join(projectDirectory, "node_modules");
17576
+ if (fs.existsSync(nodeModulesDirectory)) return path.join(nodeModulesDirectory, ".cache", "react-doctor", "scan-cache.json");
17577
+ const projectHash = hashString(projectDirectory).slice(0, 16);
17578
+ return path.join(os.tmpdir(), "react-doctor-cache", `scan-${projectHash}.json`);
17579
+ };
17580
+ const readPersistedCache = (cacheFilePath) => {
17581
+ try {
17582
+ const parsed = JSON.parse(fs.readFileSync(cacheFilePath, "utf8"));
17583
+ if (!isRecord$1(parsed) || parsed.version !== 1) return {
17584
+ version: 1,
17585
+ entries: []
17586
+ };
17587
+ if (!Array.isArray(parsed.entries)) return {
17588
+ version: 1,
17589
+ entries: []
17590
+ };
17591
+ const entries = [];
17592
+ for (const entry of parsed.entries) {
17593
+ if (!isRecord$1(entry) || typeof entry.key !== "string" || typeof entry.createdAtMs !== "number") continue;
17594
+ if (!isRecord$1(entry.payload) || !Array.isArray(entry.payload.diagnostics)) continue;
17595
+ entries.push(entry);
17596
+ }
17597
+ return {
17598
+ version: 1,
17599
+ entries
17600
+ };
17601
+ } catch {
17602
+ return {
17603
+ version: 1,
17604
+ entries: []
17605
+ };
17606
+ }
17607
+ };
17608
+ const writePersistedCache = (cacheFilePath, cache) => {
17609
+ try {
17610
+ fs.mkdirSync(path.dirname(cacheFilePath), { recursive: true });
17611
+ const tempPath = `${cacheFilePath}.${process.pid}.tmp`;
17612
+ fs.writeFileSync(tempPath, JSON.stringify(cache));
17613
+ fs.renameSync(tempPath, cacheFilePath);
17614
+ } catch {
17615
+ return;
17616
+ }
17617
+ };
17618
+ const isScanResultCacheDisabled = () => CACHE_DISABLED_VALUES.has(process.env.REACT_DOCTOR_NO_CACHE?.toLowerCase() ?? "");
17619
+ const resolveProjectIdentity = (projectDirectory) => {
17620
+ try {
17621
+ return fs.realpathSync.native(projectDirectory);
17622
+ } catch {
17623
+ return path.resolve(projectDirectory);
17624
+ }
17625
+ };
17626
+ const fileFingerprint = (filePath) => {
17627
+ try {
17628
+ const stat = fs.statSync(filePath);
17629
+ return `${filePath}:${stat.mtimeMs}:${stat.size}`;
17630
+ } catch {
17631
+ return null;
17632
+ }
17633
+ };
17634
+ const resolveToolchainFingerprint = (nodeBinaryPath) => {
17635
+ const fingerprints = [];
17636
+ if (nodeBinaryPath !== null) {
17637
+ const fingerprint = fileFingerprint(nodeBinaryPath);
17638
+ if (fingerprint !== null) fingerprints.push(`node=${fingerprint}`);
17639
+ }
17640
+ for (const specifier of TOOLCHAIN_PACKAGE_SPECIFIERS) try {
17641
+ const fingerprint = fileFingerprint(bundledRequire.resolve(specifier));
17642
+ if (fingerprint !== null) fingerprints.push(`${specifier}=${fingerprint}`);
17643
+ } catch {
17644
+ continue;
17645
+ }
17646
+ return fingerprints;
17647
+ };
17648
+ const buildScanResultCacheKey = (input) => {
17649
+ if (isScanResultCacheDisabled()) return null;
17650
+ if (!isWorktreeClean(input.projectDirectory)) return null;
17651
+ if (hasHiddenTrackedFileState(input.projectDirectory)) return null;
17652
+ const headSha = readHeadSha(input.projectDirectory);
17653
+ if (headSha === null) return null;
17654
+ if (stringifyStableJson(input.userConfig) === null) return null;
17655
+ const cacheKeyJson = stringifyStableJson({
17656
+ schemaVersion: 1,
17657
+ projectIdentity: resolveProjectIdentity(input.projectDirectory),
17658
+ headSha,
17659
+ reactDoctorVersion: input.version,
17660
+ nodeVersion: process.version,
17661
+ toolchainFingerprint: resolveToolchainFingerprint(input.nodeBinaryPath),
17662
+ configFingerprint: computeConfigFingerprint(input.projectDirectory, input.version),
17663
+ hasConfigOverride: input.hasConfigOverride,
17664
+ configSourceDirectory: input.configSourceDirectory,
17665
+ userConfig: input.userConfig,
17666
+ engineOptions: {
17667
+ lint: input.options.lint,
17668
+ deadCode: input.options.deadCode,
17669
+ includePaths: [...input.options.includePaths].sort(),
17670
+ customRulesOnly: input.options.customRulesOnly,
17671
+ respectInlineDisables: input.options.respectInlineDisables,
17672
+ warnings: input.options.warnings,
17673
+ adoptExistingLintConfig: input.options.adoptExistingLintConfig,
17674
+ ignoredTags: [...input.options.ignoredTags].sort(),
17675
+ concurrency: input.options.concurrency,
17676
+ baselineRef: input.options.baseline?.ref,
17677
+ noScore: input.options.noScore,
17678
+ isCi: input.options.isCi,
17679
+ suppressRendering: input.options.suppressRendering
17680
+ }
17681
+ });
17682
+ return cacheKeyJson === null ? null : hashString(cacheKeyJson);
17683
+ };
17684
+ const createScanResultCache = (projectDirectory) => {
17685
+ const cacheFilePath = resolveCacheFilePath(projectDirectory);
17686
+ const persistedCache = readPersistedCache(cacheFilePath);
17687
+ const entries = /* @__PURE__ */ new Map();
17688
+ for (const entry of persistedCache.entries) entries.set(entry.key, entry);
17689
+ const persist = () => {
17690
+ writePersistedCache(cacheFilePath, {
17691
+ version: 1,
17692
+ entries: [...entries.values()].sort((firstEntry, secondEntry) => secondEntry.createdAtMs - firstEntry.createdAtMs).slice(0, 20)
17693
+ });
17694
+ };
17695
+ return {
17696
+ lookup: (key) => entries.get(key)?.payload ?? null,
17697
+ store: (key, payload) => {
17698
+ entries.set(key, {
17699
+ key,
17700
+ createdAtMs: Date.now(),
17701
+ payload
17702
+ });
17703
+ persist();
17704
+ }
17705
+ };
17706
+ };
17707
+ const shouldStoreScanPayload = (payload) => !payload.didLintFail && !payload.didDeadCodeFail && payload.lintPartialFailures.length === 0;
17708
+ //#endregion
17709
+ //#region src/inspect.ts
17710
+ const silentConsole = makeNoopConsole();
17711
+ const runConsole = (effect) => {
17712
+ Effect.runSync(effect);
17713
+ };
17714
+ const recordOnboardingCompletion = (options) => {
17715
+ const forceOnboarding = isOnboardingForced();
17716
+ if (shouldRecordOnboarding({
17717
+ paceOnboardingSections: !options.silent && !options.scoreOnly && !options.suppressRendering && !options.verbose && canAnimateOnboarding(process.stdout) && (forceOnboarding || !hasCompletedOnboarding()),
17718
+ forceOnboarding,
17719
+ verbose: options.verbose,
17720
+ isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
17721
+ })) markOnboardingComplete();
17722
+ };
17723
+ const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
17724
+ const buildIgnoredTags = (userConfig) => {
17725
+ const tags = /* @__PURE__ */ new Set();
17726
+ if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
17727
+ return tags;
17728
+ };
17729
+ const mergeInspectOptions = (inputOptions, userConfig) => ({
17730
+ lint: inputOptions.lint ?? userConfig?.lint ?? true,
17731
+ deadCode: inputOptions.deadCode ?? userConfig?.deadCode ?? true,
17732
+ verbose: inputOptions.verbose ?? userConfig?.verbose ?? false,
17733
+ scoreOnly: inputOptions.scoreOnly ?? false,
17734
+ noScore: inputOptions.noScore ?? userConfig?.noScore ?? false,
17735
+ isCi: inputOptions.isCi ?? false,
17736
+ isCiOrCodingAgentEnvironment: isCiOrCodingAgentEnvironment(),
17737
+ isNonInteractiveEnvironment: isNonInteractiveEnvironment(),
17738
+ silent: inputOptions.silent ?? false,
17739
+ includePaths: inputOptions.includePaths ?? [],
17740
+ customRulesOnly: userConfig?.customRulesOnly ?? false,
17741
+ share: userConfig?.share ?? true,
17742
+ respectInlineDisables: inputOptions.respectInlineDisables ?? userConfig?.respectInlineDisables ?? true,
17743
+ warnings: inputOptions.warnings ?? userConfig?.warnings ?? true,
17744
+ categoryFilters: new Set(resolveCliCategories(inputOptions.categoryFilters) ?? []),
17745
+ adoptExistingLintConfig: userConfig?.adoptExistingLintConfig ?? true,
17746
+ ignoredTags: buildIgnoredTags(userConfig),
17747
+ outputSurface: inputOptions.outputSurface ?? "cli",
17748
+ suppressRendering: inputOptions.suppressRendering ?? false,
17749
+ concurrency: inputOptions.concurrency,
17750
+ baseline: inputOptions.baseline ?? null
17751
+ });
17752
+ const buildRunEventConfig = (options, userConfig, hasCustomConfig) => ({
17753
+ parallel: options.concurrency !== void 0,
17754
+ workerCount: options.concurrency,
17755
+ lint: options.lint,
17756
+ deadCode: options.deadCode,
17757
+ scoreOnly: options.scoreOnly,
17758
+ noScore: options.noScore,
17759
+ respectInlineDisables: options.respectInlineDisables,
17760
+ showWarnings: options.warnings,
17761
+ ignoredTagCount: options.ignoredTags.size,
17762
+ hasCustomConfig,
17763
+ userConfig
17764
+ });
17765
+ const inspect = async (directory, inputOptions = {}) => {
17766
+ const startTime = performance.now();
17767
+ resetSentryRunState();
17768
+ const hasConfigOverride = inputOptions.configOverride !== void 0;
17258
17769
  let scanDirectory;
17259
17770
  let userConfig;
17260
17771
  let configSourceDirectory;
@@ -17317,6 +17828,7 @@ const runBaselineComparison = async (params) => {
17317
17828
  hasConfigOverride: true,
17318
17829
  userConfig: params.userConfig,
17319
17830
  configSourceDirectory: null,
17831
+ projectInfoOverride: params.headProjectInfo,
17320
17832
  shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
17321
17833
  shouldRunDeadCode: false,
17322
17834
  shouldComputeScore: false,
@@ -17363,6 +17875,40 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17363
17875
  const isDiffMode = options.includePaths.length > 0;
17364
17876
  const resolvedNodeBinaryPath = await resolveOxlintNode(options.lint, options.scoreOnly || options.silent);
17365
17877
  const lintBindingMissing = options.lint && !resolvedNodeBinaryPath;
17878
+ const cacheKey = buildScanResultCacheKey({
17879
+ projectDirectory: directory,
17880
+ version: VERSION,
17881
+ nodeBinaryPath: resolvedNodeBinaryPath,
17882
+ options,
17883
+ userConfig,
17884
+ hasConfigOverride,
17885
+ configSourceDirectory
17886
+ });
17887
+ const scanResultCache = cacheKey === null ? null : createScanResultCache(directory);
17888
+ const cachedPayload = cacheKey === null ? null : scanResultCache?.lookup(cacheKey) ?? null;
17889
+ if (cachedPayload) {
17890
+ recordSentryProjectContext(cachedPayload.project, rootSentrySpan);
17891
+ recordCount(METRIC.projectDetected, 1);
17892
+ await renderCachedProjectDetection({
17893
+ payload: cachedPayload,
17894
+ options,
17895
+ userConfig,
17896
+ isDiffMode
17897
+ });
17898
+ const baselineDegraded = Boolean(options.baseline) && isDiffMode && cachedPayload.baselineDelta === void 0;
17899
+ const result = await renderAndRecordScan({
17900
+ payload: cachedPayload,
17901
+ options,
17902
+ userConfig,
17903
+ hasCustomConfig: userConfig !== null,
17904
+ startTime,
17905
+ rootSentrySpan,
17906
+ scanMode: cachedPayload.baselineDelta ? "baseline" : isDiffMode ? "diff" : "full",
17907
+ baselineDegraded
17908
+ });
17909
+ recordOnboardingCompletion(options);
17910
+ return result;
17911
+ }
17366
17912
  const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && options.lint && Boolean(resolvedNodeBinaryPath);
17367
17913
  const layers = buildRuntimeLayers({
17368
17914
  directory,
@@ -17416,6 +17962,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17416
17962
  directory,
17417
17963
  options,
17418
17964
  userConfig,
17965
+ headProjectInfo: output.project,
17419
17966
  headDiagnostics: output.diagnostics,
17420
17967
  resolvedNodeBinaryPath,
17421
17968
  baselineRef: options.baseline.ref
@@ -17427,12 +17974,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17427
17974
  }
17428
17975
  const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
17429
17976
  const score = didLintFail ? null : output.score;
17430
- const elapsedMilliseconds = performance.now() - startTime;
17431
- const forceOnboarding = isOnboardingForced();
17432
- const paceOnboardingSections = !options.silent && !options.scoreOnly && !options.suppressRendering && !options.verbose && canAnimateOnboarding(process.stdout) && (forceOnboarding || !hasCompletedOnboarding());
17433
- const finalizeInput = {
17434
- options,
17435
- elapsedMilliseconds,
17977
+ const payload = {
17436
17978
  diagnostics: inspectDiagnostics,
17437
17979
  score,
17438
17980
  project: output.project,
@@ -17446,39 +17988,77 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17446
17988
  scannedFileCount: output.scannedFileCount,
17447
17989
  scannedFilePaths: output.scannedFilePaths,
17448
17990
  scanElapsedMilliseconds: output.scanElapsedMilliseconds,
17449
- baselineDelta
17991
+ baselineDelta,
17992
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind
17450
17993
  };
17451
- const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
17452
- if (shouldRecordOnboarding({
17453
- paceOnboardingSections,
17454
- forceOnboarding,
17455
- verbose: options.verbose,
17456
- isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
17457
- })) markOnboardingComplete();
17458
- const scanMode = baselineDelta ? "baseline" : isDiffMode ? "diff" : "full";
17994
+ if (cacheKey !== null && scanResultCache !== null && shouldStoreScanPayload(payload)) scanResultCache.store(cacheKey, payload);
17995
+ const result = await renderAndRecordScan({
17996
+ payload,
17997
+ options,
17998
+ userConfig,
17999
+ hasCustomConfig: userConfig !== null,
18000
+ startTime,
18001
+ rootSentrySpan,
18002
+ scanMode: baselineDelta ? "baseline" : isDiffMode ? "diff" : "full",
18003
+ baselineDegraded
18004
+ });
18005
+ recordOnboardingCompletion(options);
18006
+ return result;
18007
+ };
18008
+ const runMaybeSilent = (effect, silent) => silent ? effect.pipe(Effect.provideService(Console.Console, silentConsole)) : effect;
18009
+ const renderCachedProjectDetection = async (input) => {
18010
+ if (input.options.scoreOnly || input.options.suppressRendering) return;
18011
+ await Effect.runPromise(runMaybeSilent(printProjectDetection({
18012
+ projectInfo: input.payload.project,
18013
+ userConfig: input.userConfig,
18014
+ isDiffMode: input.isDiffMode,
18015
+ includePaths: input.options.includePaths,
18016
+ lintSourceFileCount: input.payload.scannedFileCount
18017
+ }), input.options.silent));
18018
+ };
18019
+ const renderAndRecordScan = async (input) => {
18020
+ const finalizeInput = {
18021
+ options: input.options,
18022
+ elapsedMilliseconds: performance.now() - input.startTime,
18023
+ diagnostics: input.payload.diagnostics,
18024
+ score: input.payload.score,
18025
+ project: input.payload.project,
18026
+ userConfig: input.payload.userConfig,
18027
+ didLintFail: input.payload.didLintFail,
18028
+ lintFailureReason: input.payload.lintFailureReason,
18029
+ lintPartialFailures: input.payload.lintPartialFailures,
18030
+ didDeadCodeFail: input.payload.didDeadCodeFail,
18031
+ deadCodeFailureReason: input.payload.deadCodeFailureReason,
18032
+ directory: input.payload.directory,
18033
+ scannedFileCount: input.payload.scannedFileCount,
18034
+ scannedFilePaths: input.payload.scannedFilePaths,
18035
+ scanElapsedMilliseconds: input.payload.scanElapsedMilliseconds,
18036
+ baselineDelta: input.payload.baselineDelta
18037
+ };
18038
+ const result = await Effect.runPromise(runMaybeSilent(finalizeAndRender(finalizeInput), input.options.silent));
17459
18039
  recordScanMetrics({
17460
18040
  result,
17461
- mode: scanMode,
17462
- baselineDegraded,
17463
- parallel: options.concurrency !== void 0,
17464
- workerCount: options.concurrency,
17465
- lint: options.lint,
17466
- deadCode: options.deadCode,
17467
- scoreOnly: options.scoreOnly,
17468
- noScore: options.noScore,
17469
- didLintFail,
17470
- lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
17471
- didDeadCodeFail: output.didDeadCodeFail
18041
+ mode: input.scanMode,
18042
+ baselineDegraded: input.baselineDegraded,
18043
+ parallel: input.options.concurrency !== void 0,
18044
+ workerCount: input.options.concurrency,
18045
+ lint: input.options.lint,
18046
+ deadCode: input.options.deadCode,
18047
+ scoreOnly: input.options.scoreOnly,
18048
+ noScore: input.options.noScore,
18049
+ didLintFail: input.payload.didLintFail,
18050
+ lintFailureReasonKind: input.payload.lintFailureReasonKind,
18051
+ didDeadCodeFail: input.payload.didDeadCodeFail
17472
18052
  });
17473
- recordRunEvent(rootSentrySpan, {
17474
- ...buildRunEventConfig(options, userConfig, userConfig !== null),
18053
+ recordRunEvent(input.rootSentrySpan, {
18054
+ ...buildRunEventConfig(input.options, input.userConfig, input.hasCustomConfig),
17475
18055
  result,
17476
- mode: scanMode,
17477
- gateExempt: baselineDegraded,
17478
- didLintFail,
17479
- lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind,
17480
- lintPartialFailureCount: output.lintPartialFailures.length,
17481
- didDeadCodeFail: output.didDeadCodeFail
18056
+ mode: input.scanMode,
18057
+ gateExempt: input.baselineDegraded,
18058
+ didLintFail: input.payload.didLintFail,
18059
+ lintFailureReasonKind: input.payload.lintFailureReasonKind,
18060
+ lintPartialFailureCount: input.payload.lintPartialFailures.length,
18061
+ didDeadCodeFail: input.payload.didDeadCodeFail
17482
18062
  });
17483
18063
  return result;
17484
18064
  };
@@ -17514,14 +18094,16 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17514
18094
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
17515
18095
  const pause = onboardingSectionPause(animateRender);
17516
18096
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
18097
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
17517
18098
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
17518
18099
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
17519
- if (surfaceDiagnostics.length === 0) {
18100
+ if (printedDiagnostics.length === 0) {
17520
18101
  yield* pause;
17521
18102
  if (hasSkippedChecks) {
17522
18103
  const skippedLabel = skippedChecks.join(" and ");
17523
18104
  yield* Console.warn(highlighter.warn(`No issues detected, but ${skippedLabel} checks failed — results are incomplete.`));
17524
- } else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
18105
+ } else if (options.categoryFilters.size > 0) yield* Console.log(highlighter.success(`No issues found in category ${formatCategorySelection(options.categoryFilters)}!`));
18106
+ else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17525
18107
  else yield* Console.log(highlighter.success("No issues found!"));
17526
18108
  yield* Console.log("");
17527
18109
  yield* pause;
@@ -17534,20 +18116,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17534
18116
  }
17535
18117
  yield* pause;
17536
18118
  yield* Console.log("");
17537
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
18119
+ yield* printDiagnostics([...printedDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17538
18120
  sectionPause: pause,
17539
18121
  animateCountUp: animateRender
17540
18122
  });
17541
18123
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
17542
- if (demotedDiagnosticCount > 0) {
18124
+ if (options.categoryFilters.size === 0 && demotedDiagnosticCount > 0) {
17543
18125
  yield* Console.log(highlighter.gray(` ${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface (e.g. design cleanup) — run \`npx react-doctor@latest .\` locally for the full list.`));
17544
18126
  yield* Console.log("");
17545
18127
  }
17546
- const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
18128
+ const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...printedDiagnostics], [...surfaceDiagnostics], score)) : null;
17547
18129
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
17548
18130
  yield* pause;
17549
18131
  yield* printSummary({
17550
- diagnostics: [...surfaceDiagnostics],
18132
+ diagnostics: [...printedDiagnostics],
17551
18133
  elapsedMilliseconds,
17552
18134
  scoreResult: score,
17553
18135
  potentialScore,
@@ -17563,7 +18145,7 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17563
18145
  }
17564
18146
  yield* pause;
17565
18147
  yield* printFooter({
17566
- diagnostics: [...surfaceDiagnostics],
18148
+ diagnostics: [...printedDiagnostics],
17567
18149
  scoreResult: score,
17568
18150
  projectName: project.projectName,
17569
18151
  isOffline: !shouldShowShareLink
@@ -17694,21 +18276,6 @@ const handleUserError = (error, options = {}) => {
17694
18276
  process.exitCode = 1;
17695
18277
  };
17696
18278
  //#endregion
17697
- //#region src/cli/utils/cli-input-error.ts
17698
- /**
17699
- * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17700
- * argument, mutually exclusive flags, or an unknown `--project` name. This is
17701
- * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17702
- * through `handleUserError`: a clean, single-line message with no Sentry
17703
- * report and no "Something went wrong, open a prefilled issue" block.
17704
- *
17705
- * The `message` is rendered verbatim, so it must read as a complete,
17706
- * human-readable sentence that tells the user how to fix their invocation.
17707
- */
17708
- var CliInputError = class extends Error {
17709
- name = "CliInputError";
17710
- };
17711
- //#endregion
17712
18279
  //#region src/cli/utils/is-expected-user-error.ts
17713
18280
  /**
17714
18281
  * Whether `error` is an expected, user-actionable failure — the user's project
@@ -17980,190 +18547,24 @@ const installDoctorScript = (options) => {
17980
18547
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17981
18548
  };
17982
18549
  };
17983
- //#endregion
17984
- //#region src/cli/utils/install-agent-hooks.ts
17985
- const CLAUDE_AGENT = "claude-code";
17986
- const CURSOR_AGENT = "cursor";
17987
- const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
17988
- const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
17989
- const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
17990
- const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
17991
- const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
17992
- const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
17993
- const CURSOR_HOOKS_SCHEMA_VERSION = 1;
17994
- const JSON_INDENT_SPACES$1 = 2;
17995
- const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
17996
- const readJsonFile = (filePath, fallback) => {
17997
- if (!fs$1.existsSync(filePath)) return fallback;
17998
- const content = fs$1.readFileSync(filePath, "utf8").trim();
17999
- if (content.length === 0) return fallback;
18000
- return JSON.parse(content);
18001
- };
18002
- const writeJsonFile = (filePath, value) => {
18003
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18004
- fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18005
- };
18006
- const writeHookScript = (filePath) => {
18007
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18008
- fs$1.writeFileSync(filePath, buildAgentHookScript());
18009
- fs$1.chmodSync(filePath, 493);
18010
- };
18011
- const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18012
- const installClaudeHook = (projectRoot) => {
18013
- const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18014
- const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18015
- const settings = readJsonFile(settingsPath, {});
18016
- const hooks = { ...settings.hooks ?? {} };
18017
- const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18018
- if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18019
- type: "command",
18020
- command: CLAUDE_HOOK_COMMAND
18021
- }] });
18022
- hooks.PostToolBatch = postToolBatchHooks;
18023
- writeJsonFile(settingsPath, {
18024
- ...settings,
18025
- hooks
18026
- });
18027
- writeHookScript(hookPath);
18028
- return [settingsPath, hookPath];
18550
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18551
+ const scriptName = scriptResult.scriptName ?? "doctor";
18552
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18553
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18554
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18555
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18556
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18557
+ return "Skipped package script: package.json missing or invalid.";
18029
18558
  };
18030
- const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18031
- const installCursorHook = (projectRoot) => {
18032
- const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18033
- const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18034
- const config = readJsonFile(configPath, {});
18035
- const hooks = { ...config.hooks ?? {} };
18036
- const postToolUseHooks = [...hooks.postToolUse ?? []];
18037
- if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18038
- command: CURSOR_HOOK_RELATIVE_PATH,
18039
- matcher: CURSOR_HOOK_MATCHER,
18040
- timeout: 120
18041
- });
18042
- hooks.postToolUse = postToolUseHooks;
18043
- writeJsonFile(configPath, {
18044
- ...config,
18045
- version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18046
- hooks
18047
- });
18048
- writeHookScript(hookPath);
18049
- return [configPath, hookPath];
18050
- };
18051
- const buildAgentHookScript = () => [
18052
- "#!/bin/sh",
18053
- "set -u",
18054
- "",
18055
- "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18056
- "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18057
- "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18058
- "cat > \"$input_file\"",
18059
- "",
18060
- "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18061
- "project_root=${CLAUDE_PROJECT_DIR:-}",
18062
- "if [ -z \"$project_root\" ]; then",
18063
- " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18064
- "fi",
18065
- "if ! cd \"$project_root\"; then",
18066
- " exit 0",
18067
- "fi",
18068
- "",
18069
- "should_scan() {",
18070
- " if ! command -v node >/dev/null 2>&1; then",
18071
- " return 0",
18072
- " fi",
18073
- "",
18074
- " node - \"$input_file\" <<'NODE'",
18075
- "const fs = require('node:fs');",
18076
- "const inputPath = process.argv[2];",
18077
- "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18078
- "try {",
18079
- " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18080
- " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18081
- " if (eventName === 'PostToolBatch') {",
18082
- " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18083
- " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18084
- " }",
18085
- " const toolName = input.tool_name || input.toolName || input.tool;",
18086
- " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18087
- "} catch {",
18088
- " process.exit(0);",
18089
- "}",
18090
- "NODE",
18091
- "}",
18092
- "",
18093
- "run_react_doctor() {",
18094
- " if [ -x ./node_modules/.bin/react-doctor ]; then",
18095
- " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18096
- " return",
18097
- " fi",
18098
- "",
18099
- " if command -v react-doctor >/dev/null 2>&1; then",
18100
- " react-doctor --verbose --diff --blocking warning --no-score",
18101
- " return",
18102
- " fi",
18103
- "",
18104
- " if command -v pnpm >/dev/null 2>&1; then",
18105
- " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18106
- " return",
18107
- " fi",
18108
- "",
18109
- " if command -v npx >/dev/null 2>&1; then",
18110
- " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18111
- " return",
18112
- " fi",
18113
- "",
18114
- " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18115
- " return 0",
18116
- "}",
18117
- "",
18118
- "if ! should_scan; then",
18119
- " exit 0",
18120
- "fi",
18121
- "",
18122
- "if run_react_doctor > \"$output_file\" 2>&1; then",
18123
- " exit 0",
18124
- "fi",
18125
- "",
18126
- "node - \"$input_file\" \"$output_file\" <<'NODE'",
18127
- "const fs = require('node:fs');",
18128
- "const inputPath = process.argv[2];",
18129
- "const outputPath = process.argv[3];",
18130
- "const readInput = () => {",
18131
- " try {",
18132
- " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18133
- " } catch {",
18134
- " return {};",
18135
- " }",
18136
- "};",
18137
- "const input = readInput();",
18138
- "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18139
- "if (!scanOutput) process.exit(0);",
18140
- "const message = `React Doctor found issues in the changed files. Review this output and fix the regressions before finishing. For confirmed issues that cannot be fixed now, create GitHub issues with the rule, file/line, confidence, impact, and proposed fix.\\n\\n${scanOutput}`;",
18141
- "if (input.hook_event_name === 'PostToolBatch') {",
18142
- " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18143
- "} else {",
18144
- " console.log(JSON.stringify({ additional_context: message }));",
18145
- "}",
18146
- "NODE",
18147
- ""
18148
- ].join("\n");
18149
- const installReactDoctorAgentHooks = (options) => {
18150
- const installedAgents = [];
18151
- const files = [];
18152
- const requestedAgents = options.agents.filter(isSupportedAgent);
18153
- for (const agent of requestedAgents) {
18154
- if (agent === CLAUDE_AGENT) {
18155
- files.push(...installClaudeHook(options.projectRoot));
18156
- installedAgents.push(agent);
18157
- }
18158
- if (agent === CURSOR_AGENT) {
18159
- files.push(...installCursorHook(options.projectRoot));
18160
- installedAgents.push(agent);
18161
- }
18162
- }
18163
- return {
18164
- installedAgents,
18165
- files
18166
- };
18559
+ const installReactDoctorScriptStep = (projectRoot) => {
18560
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18561
+ try {
18562
+ const scriptResult = installDoctorScript({ projectRoot });
18563
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18564
+ } catch (error) {
18565
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18566
+ throw error;
18567
+ }
18167
18568
  };
18168
18569
  //#endregion
18169
18570
  //#region src/cli/utils/install-github-workflow.ts
@@ -18176,37 +18577,20 @@ const buildWorkflowContent = () => `# React Doctor — finds security, performan
18176
18577
  name: React Doctor
18177
18578
 
18178
18579
  on:
18580
+ # Scans the PR's changed files and posts a sticky summary comment listing only the new issues introduced relative to the merge base of the target branch.
18179
18581
  pull_request:
18180
18582
  types: [opened, synchronize, reopened, ready_for_review]
18181
- # Scans \`main\` on every push so you get a health-score trend on the
18182
- # default branch — useful for tracking the overall number commit-by-commit
18183
- # and catching regressions that slipped past PR review. PR-specific steps
18184
- # (the sticky summary comment) are skipped automatically on \`push\` events.
18185
- # Comment this block out if you only want PR-time scans.
18583
+ # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
18186
18584
  push:
18187
18585
  branches: [main]
18188
18586
 
18189
18587
  permissions:
18190
- # \`actions/checkout\` needs this to read the repo source.
18191
18588
  contents: read
18192
- # Two uses: (1) reads the PR's changed-file list so the scan only checks
18193
- # what the PR touched (faster, scoped to the diff), and (2) posts/updates
18194
- # the sticky React Doctor summary comment on the PR. Downgrade \`write\` to
18195
- # \`read\` to keep the changed-file scan but disable comment posting.
18196
18589
  pull-requests: write
18197
- # The sticky-comment step uses GitHub's \`issues.createComment\` /
18198
- # \`issues.updateComment\` endpoints — those are the same APIs that back PR
18199
- # comments (PRs are issues under the hood). Not exercised on \`push\`
18200
- # events, so safe to drop if you only run on \`main\`.
18201
18590
  issues: write
18202
- # Lets the action publish a commit status with the score + error/warning
18203
- # counts (links to the run). This is how a \`push\` to \`main\` surfaces its
18204
- # result, since the PR comment is skipped off pull requests. Drop it to
18205
- # disable the status (or set \`commit-status: false\` below).
18206
18591
  statuses: write
18207
18592
 
18208
- # Cancels any in-flight scan for the same PR (or branch, on push) the moment
18209
- # a new commit arrives, so reviewers only ever see the latest run.
18593
+ # Cancels any in-flight scan for the same PR (or branch, on push) the moment a new commit arrives, so reviewers only ever see the latest run.
18210
18594
  concurrency:
18211
18595
  group: react-doctor-\${{ github.event.pull_request.number || github.ref }}
18212
18596
  cancel-in-progress: true
@@ -18273,1074 +18657,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18273
18657
  };
18274
18658
  }
18275
18659
  };
18660
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18661
+ const workflow = readReactDoctorWorkflow(projectRoot);
18662
+ if (!workflow) return {
18663
+ status: "not-needed",
18664
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18665
+ };
18666
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18667
+ if (!changed) return {
18668
+ status: "not-needed",
18669
+ workflowPath: workflow.workflowPath
18670
+ };
18671
+ try {
18672
+ fs$1.writeFileSync(workflow.workflowPath, content);
18673
+ return {
18674
+ status: "upgraded",
18675
+ workflowPath: workflow.workflowPath
18676
+ };
18677
+ } catch {
18678
+ return {
18679
+ status: "failed",
18680
+ workflowPath: workflow.workflowPath
18681
+ };
18682
+ }
18683
+ };
18276
18684
  //#endregion
18277
- //#region src/cli/utils/report-workflow-result.ts
18278
- const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18279
- if (result.status === "failed") {
18280
- workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18281
- return false;
18685
+ //#region src/cli/utils/hash-project-root.ts
18686
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18687
+ //#endregion
18688
+ //#region src/cli/utils/action-upgrade-prompt.ts
18689
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18690
+ const getActionUpgradeStore = (options = {}) => new Conf({
18691
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18692
+ cwd: options.cwd
18693
+ });
18694
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18695
+ try {
18696
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18697
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18698
+ } catch {
18699
+ return true;
18282
18700
  }
18283
- if (result.status === "exists") {
18284
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18701
+ };
18702
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18703
+ try {
18704
+ const store = getActionUpgradeStore(storeOptions);
18705
+ const upgrades = store.get("actionUpgrades", {});
18706
+ store.set("actionUpgrades", {
18707
+ ...upgrades,
18708
+ [hashProjectRoot(projectRoot)]: {
18709
+ rootDirectory: path$1.resolve(projectRoot),
18710
+ outcome,
18711
+ at: (/* @__PURE__ */ new Date()).toISOString()
18712
+ }
18713
+ });
18714
+ return true;
18715
+ } catch {
18285
18716
  return false;
18286
18717
  }
18287
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18288
- recordCount(METRIC.installWorkflow, 1);
18289
- return true;
18290
18718
  };
18291
18719
  //#endregion
18292
- //#region src/cli/utils/install-git-hook-file.ts
18293
- const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18294
- const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18295
- const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\s\\S]*?${REACT_DOCTOR_BLOCK_END}\\n?|# react-doctor hook launcher start[\\s\\S]*?# react-doctor hook launcher end\\n?)`);
18296
- const SHEBANG = "#!/bin/sh";
18297
- const SHEBANG_PREFIX = "#!";
18298
- const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18299
- const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18300
- const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18301
- const buildReactDoctorHookBlock = () => [
18302
- REACT_DOCTOR_BLOCK_START,
18303
- "react_doctor_scan_staged_files() {",
18304
- ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18305
- ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18306
- " return",
18307
- " fi",
18308
- "",
18309
- " if command -v react-doctor >/dev/null 2>&1; then",
18310
- ` ${REACT_DOCTOR_COMMAND}`,
18311
- " return",
18312
- " fi",
18313
- "",
18314
- " if command -v pnpm >/dev/null 2>&1; then",
18315
- ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18316
- " return",
18317
- " fi",
18318
- "",
18319
- " if command -v npx >/dev/null 2>&1; then",
18320
- ` ${NPX_REACT_DOCTOR_COMMAND}`,
18321
- " return",
18322
- " fi",
18323
- "",
18324
- " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18325
- "}",
18326
- "",
18327
- "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18328
- "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18329
- " rm -f \"$react_doctor_output\"",
18330
- "else",
18331
- " rm -f \"$react_doctor_output\"",
18332
- ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
18333
- "fi",
18334
- REACT_DOCTOR_BLOCK_END
18335
- ].join("\n");
18336
- const mergeHookContent = (existingContent) => {
18337
- const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18338
- if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18339
- if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18340
- const normalizedExistingContent = ensureTrailingNewline(existingContent);
18341
- if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18342
- const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18343
- return [
18344
- shebangLine,
18720
+ //#region src/cli/utils/open-url.ts
18721
+ const resolveOpenCommand = (url) => {
18722
+ if (process$1.platform === "darwin") return {
18723
+ command: "open",
18724
+ args: [url]
18725
+ };
18726
+ if (process$1.platform === "win32") return {
18727
+ command: "cmd",
18728
+ args: [
18729
+ "/c",
18730
+ "start",
18345
18731
  "",
18346
- hookBlock.trimEnd(),
18347
- ...remainingLines
18348
- ].join("\n");
18732
+ url
18733
+ ]
18734
+ };
18735
+ return {
18736
+ command: "xdg-open",
18737
+ args: [url]
18738
+ };
18739
+ };
18740
+ const openUrl = (url) => {
18741
+ try {
18742
+ const { command, args } = resolveOpenCommand(url);
18743
+ const child = spawn(command, args, {
18744
+ detached: true,
18745
+ stdio: "ignore"
18746
+ });
18747
+ child.on("error", () => {});
18748
+ child.unref();
18749
+ return true;
18750
+ } catch {
18751
+ return false;
18349
18752
  }
18350
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18351
18753
  };
18352
- const removeLegacyManagedRunner = (projectRoot) => {
18353
- const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18354
- fs$1.rmSync(runnerPath, { force: true });
18355
- for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18356
- fs$1.rmdirSync(directory);
18357
- } catch {}
18358
- };
18359
- const installDirectGitHook = (options) => {
18360
- const didHookExist = fs$1.existsSync(options.hookPath);
18361
- const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18362
- if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18363
- "config",
18364
- "core.hooksPath",
18365
- options.hooksPathConfig
18366
- ]);
18367
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18368
- fs$1.writeFileSync(options.hookPath, nextContent);
18369
- fs$1.chmodSync(options.hookPath, 493);
18370
- removeLegacyManagedRunner(options.projectRoot);
18371
- return {
18372
- hookPath: options.hookPath,
18373
- kind: options.kind ?? "git",
18374
- status: didHookExist ? "updated" : "created"
18375
- };
18754
+ //#endregion
18755
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18756
+ const CI_YES_CHOICE = "ci-yes";
18757
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18758
+ const CI_NO_CHOICE = "ci-no";
18759
+ const SGR_BOLD_OFF = "\x1B[22m";
18760
+ const ciQuestionMessage = [
18761
+ "Add React Doctor to GitHub Actions?",
18762
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18763
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18764
+ ].join("\n");
18765
+ const askAddToGitHubActions = async (prompt = prompts) => {
18766
+ while (true) {
18767
+ const { ciChoice } = await prompt({
18768
+ type: "select",
18769
+ name: "ciChoice",
18770
+ message: ciQuestionMessage,
18771
+ hint: " ",
18772
+ choices: [
18773
+ {
18774
+ title: "Yes",
18775
+ description: "Adds the workflow file and a doctor package script",
18776
+ value: CI_YES_CHOICE
18777
+ },
18778
+ {
18779
+ title: "Learn more",
18780
+ description: "Opens the docs page in your browser",
18781
+ value: CI_LEARN_MORE_CHOICE
18782
+ },
18783
+ {
18784
+ title: "No",
18785
+ description: "Skip for now",
18786
+ value: CI_NO_CHOICE
18787
+ }
18788
+ ],
18789
+ initial: 0
18790
+ }, { onCancel: () => true });
18791
+ if (ciChoice === void 0) return "cancel";
18792
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18793
+ if (ciChoice === CI_NO_CHOICE) return "no";
18794
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18795
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18796
+ cliLogger.break();
18797
+ }
18376
18798
  };
18377
18799
  //#endregion
18378
- //#region src/cli/utils/install-git-hook-config-managers.ts
18379
- const appendStringCommand = (existingCommand) => {
18380
- const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18381
- return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18800
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18801
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18802
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18803
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18804
+ const { upgradeChoice } = await prompt({
18805
+ type: "select",
18806
+ name: "upgradeChoice",
18807
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18808
+ hint: " ",
18809
+ choices: [{
18810
+ title: "Yes (recommended)",
18811
+ description: "Bump the workflow to millionco/react-doctor@v2",
18812
+ value: UPGRADE_YES_CHOICE
18813
+ }, {
18814
+ title: "No, thanks",
18815
+ description: "Keep @v1 — won't ask again for this repo",
18816
+ value: UPGRADE_NO_CHOICE
18817
+ }],
18818
+ initial: 0
18819
+ }, { onCancel: () => true });
18820
+ if (upgradeChoice === void 0) return "cancel";
18821
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18382
18822
  };
18383
- const appendArrayCommand = (existingCommands) => {
18384
- const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18385
- return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18823
+ //#endregion
18824
+ //#region src/cli/utils/open-workflow-pull-request.ts
18825
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18826
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18827
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18828
+ 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.
18829
+
18830
+ Docs: https://www.react.doctor/ci`;
18831
+ const execFileAsync$1 = promisify(execFile);
18832
+ const run = async (command, args, cwd) => {
18833
+ try {
18834
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18835
+ cwd,
18836
+ encoding: "utf8"
18837
+ });
18838
+ return {
18839
+ success: true,
18840
+ stdout: stdout.trim(),
18841
+ stderr: stderr.trim()
18842
+ };
18843
+ } catch (error) {
18844
+ const failure = error;
18845
+ return {
18846
+ success: false,
18847
+ stdout: (failure.stdout ?? "").trim(),
18848
+ stderr: (failure.stderr ?? "").trim()
18849
+ };
18850
+ }
18386
18851
  };
18387
- const installPackageJsonHook = (options, strategy) => {
18388
- const packageJsonPath = getPackageJsonPath(options.projectRoot);
18389
- const didHookExist = fs$1.existsSync(packageJsonPath);
18390
- const packageJson = readPackageJson(options.projectRoot);
18391
- const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18392
- const parentKeys = strategy.path.slice(0, -1);
18393
- const leafKey = strategy.path[strategy.path.length - 1];
18394
- let parent = nextPackageJson;
18395
- for (const key of parentKeys) {
18396
- const existing = parent[key];
18397
- const cloned = isRecord(existing) ? { ...existing } : {};
18398
- parent[key] = cloned;
18399
- parent = cloned;
18852
+ const detectDefaultBranch = async (cwd) => {
18853
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18854
+ if (symRef.success) {
18855
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18856
+ if (branchMatch) return branchMatch[1];
18400
18857
  }
18401
- parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18402
- writeJsonFile$1(packageJsonPath, nextPackageJson);
18403
- removeLegacyManagedRunner(options.projectRoot);
18404
- return {
18405
- hookPath: packageJsonPath,
18406
- kind: strategy.kind,
18407
- status: didHookExist ? "updated" : "created"
18408
- };
18858
+ if ((await run("git", [
18859
+ "rev-parse",
18860
+ "--verify",
18861
+ "origin/main"
18862
+ ], cwd)).success) return "main";
18863
+ if ((await run("git", [
18864
+ "rev-parse",
18865
+ "--verify",
18866
+ "origin/master"
18867
+ ], cwd)).success) return "master";
18868
+ return null;
18409
18869
  };
18410
- const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18411
- kind: "simple-git-hooks",
18412
- path: ["simple-git-hooks", "pre-commit"],
18413
- leafShape: "string"
18414
- });
18415
- const installGhooks = (options) => installPackageJsonHook(options, {
18416
- kind: "ghooks",
18417
- path: [
18418
- "config",
18419
- "ghooks",
18420
- "pre-commit"
18421
- ],
18422
- leafShape: "string"
18423
- });
18424
- const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18425
- kind: "pre-commit-npm",
18426
- path: ["pre-commit"],
18427
- leafShape: "array"
18428
- });
18429
- const installPrettyQuick = (options) => installPackageJsonHook(options, {
18430
- kind: "pretty-quick",
18431
- path: ["gitHooks", "pre-commit"],
18432
- leafShape: "string"
18433
- });
18434
- const installYorkie = (options) => installPackageJsonHook(options, {
18435
- kind: "yorkie",
18436
- path: ["gitHooks", "pre-commit"],
18437
- leafShape: "string"
18438
- });
18439
- const installGitHooksJs = (options) => installPackageJsonHook(options, {
18440
- kind: "git-hooks-js",
18441
- path: ["git-hooks", "pre-commit"],
18442
- leafShape: "string"
18443
- });
18444
- const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18445
- const normalizedContent = ensureTrailingNewline(content);
18446
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18447
- if (match === null) return ensureTrailingNewline([
18448
- normalizedContent.trimEnd(),
18449
- "",
18450
- `${sectionName}:`,
18451
- ...block,
18452
- ""
18453
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18454
- const sectionStartIndex = match.index;
18455
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18456
- nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18457
- let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18458
- while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18459
- const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18460
- const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18461
- const suffix = normalizedContent.slice(insertIndex);
18462
- return ensureTrailingNewline([
18463
- prefix,
18464
- ...block,
18465
- suffix.trimStart()
18466
- ].join("\n"));
18870
+ const findUniqueBranchName = async (cwd) => {
18871
+ if (!(await run("git", [
18872
+ "rev-parse",
18873
+ "--verify",
18874
+ NEW_BRANCH_PREFIX
18875
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18876
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18467
18877
  };
18468
- const findTopLevelSectionRange = (content, sectionName) => {
18469
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18470
- if (match === null) return null;
18471
- const headerLineEndIndex = content.indexOf("\n", match.index);
18472
- const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18473
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18474
- nextSectionPattern.lastIndex = headerEndIndex;
18475
- return {
18476
- headerEndIndex,
18477
- contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18878
+ const openWorkflowPullRequest = async (params) => {
18879
+ const workflowPath = path$1.resolve(params.workflowPath);
18880
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18881
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18882
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18883
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18884
+ if (!repoRootProbe.success) return {
18885
+ status: "not-attempted",
18886
+ reason: "not-a-git-repo"
18478
18887
  };
18479
- };
18480
- const appendLefthookCommand = (content) => {
18481
- const normalizedContent = ensureTrailingNewline(content);
18482
- const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18483
- const reactDoctorCommandBlock = [
18484
- " react-doctor:",
18485
- ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18486
- ""
18487
- ];
18488
- if (sectionRange === null) return ensureTrailingNewline([
18489
- normalizedContent.trimEnd(),
18490
- "",
18491
- "pre-commit:",
18492
- " commands:",
18493
- ...reactDoctorCommandBlock
18494
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18495
- const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18496
- const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18497
- const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18498
- const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18499
- return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18500
- };
18501
- const installLefthook = (options) => {
18502
- const didHookExist = fs$1.existsSync(options.hookPath);
18503
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18504
- if (!existingContent.includes("react-doctor")) {
18505
- const nextContent = appendLefthookCommand(existingContent);
18506
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18507
- fs$1.writeFileSync(options.hookPath, nextContent);
18508
- }
18509
- removeLegacyManagedRunner(options.projectRoot);
18510
- return {
18511
- hookPath: options.hookPath,
18512
- kind: "lefthook",
18513
- status: didHookExist ? "updated" : "created"
18514
- };
18515
- };
18516
- const installPreCommit = (options) => {
18517
- const didHookExist = fs$1.existsSync(options.hookPath);
18518
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18519
- if (!existingContent.includes("id: react-doctor")) {
18520
- const hasReposKey = /^repos:\s*$/m.test(existingContent);
18521
- const localHookBlock = [
18522
- " - repo: local",
18523
- " hooks:",
18524
- " - id: react-doctor",
18525
- " name: react-doctor",
18526
- ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18527
- " language: system",
18528
- " pass_filenames: false",
18529
- ""
18530
- ].join("\n");
18531
- const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18532
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18533
- fs$1.writeFileSync(options.hookPath, nextContent);
18534
- }
18535
- removeLegacyManagedRunner(options.projectRoot);
18536
- return {
18537
- hookPath: options.hookPath,
18538
- kind: "pre-commit",
18539
- status: didHookExist ? "updated" : "created"
18540
- };
18541
- };
18542
- const installOvercommit = (options) => {
18543
- const didHookExist = fs$1.existsSync(options.hookPath);
18544
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18545
- if (!existingContent.includes("ReactDoctor")) {
18546
- const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18547
- " ReactDoctor:",
18548
- " enabled: true",
18549
- ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18550
- ""
18551
- ]);
18552
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18553
- fs$1.writeFileSync(options.hookPath, nextContent);
18554
- }
18555
- removeLegacyManagedRunner(options.projectRoot);
18556
- return {
18557
- hookPath: options.hookPath,
18558
- kind: "overcommit",
18559
- status: didHookExist ? "updated" : "created"
18560
- };
18561
- };
18562
- //#endregion
18563
- //#region src/cli/utils/install-git-hook.ts
18564
- const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18565
- const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18566
- const isSimpleGitHooksProject = (projectRoot) => {
18567
- const packageJson = readPackageJson(projectRoot);
18568
- return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
18569
- };
18570
- const getLefthookConfigPath = (projectRoot) => {
18571
- for (const fileName of LEFTHOOK_CONFIG_FILES) {
18572
- const filePath = path$1.join(projectRoot, fileName);
18573
- if (fs$1.existsSync(filePath)) return filePath;
18574
- }
18575
- return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
18576
- };
18577
- const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18578
- const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18579
- const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18580
- const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
18581
- const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
18582
- const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
18583
- const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
18584
- const detectGitHookTarget = (projectRoot) => {
18585
- if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
18586
- const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
18587
- const configuredHooksPath = runGit(projectRoot, [
18588
- "config",
18589
- "--path",
18590
- "--get",
18591
- "core.hooksPath"
18592
- ]);
18593
- if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
18594
- hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
18595
- runnerRoot: topLevel,
18596
- kind: "configured"
18597
- };
18598
- if (isHuskyProject(topLevel)) return {
18599
- hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
18600
- runnerRoot: topLevel,
18601
- kind: "husky",
18602
- hooksPathConfig: HUSKY_HOOKS_PATH
18603
- };
18604
- if (isVitePlusProject(topLevel)) return {
18605
- hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
18606
- runnerRoot: topLevel,
18607
- kind: "vite-plus",
18608
- hooksPathConfig: VITE_PLUS_HOOKS_PATH
18609
- };
18610
- if (isSimpleGitHooksProject(topLevel)) return {
18611
- hookPath: path$1.join(topLevel, "package.json"),
18612
- runnerRoot: topLevel,
18613
- kind: "simple-git-hooks"
18614
- };
18615
- const lefthookConfigPath = getLefthookConfigPath(topLevel);
18616
- if (lefthookConfigPath !== null) return {
18617
- hookPath: lefthookConfigPath,
18618
- runnerRoot: topLevel,
18619
- kind: "lefthook"
18620
- };
18621
- if (isPreCommitProject(topLevel)) return {
18622
- hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
18623
- runnerRoot: topLevel,
18624
- kind: "pre-commit"
18888
+ const cwd = repoRootProbe.stdout;
18889
+ if (!isCommandAvailable("gh")) return {
18890
+ status: "not-attempted",
18891
+ reason: "gh-not-installed"
18625
18892
  };
18626
- if (isOvercommitProject(topLevel)) return {
18627
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18628
- runnerRoot: topLevel,
18629
- kind: "overcommit"
18893
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18894
+ status: "not-attempted",
18895
+ reason: "gh-not-authenticated"
18630
18896
  };
18631
- if (isYorkieProject(topLevel)) return {
18632
- hookPath: getPackageJsonPath(topLevel),
18633
- runnerRoot: topLevel,
18634
- kind: "yorkie"
18897
+ const defaultBranch = await detectDefaultBranch(cwd);
18898
+ if (!defaultBranch) return {
18899
+ status: "not-attempted",
18900
+ reason: "no-default-branch"
18635
18901
  };
18636
- if (isGhooksProject(topLevel)) return {
18637
- hookPath: getPackageJsonPath(topLevel),
18638
- runnerRoot: topLevel,
18639
- kind: "ghooks"
18902
+ const previousBranchProbe = await run("git", [
18903
+ "rev-parse",
18904
+ "--abbrev-ref",
18905
+ "HEAD"
18906
+ ], cwd);
18907
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18908
+ status: "not-attempted",
18909
+ reason: "detached-head"
18640
18910
  };
18641
- if (isGitHooksJsProject(topLevel)) return {
18642
- hookPath: getPackageJsonPath(topLevel),
18643
- runnerRoot: topLevel,
18644
- kind: "git-hooks-js"
18911
+ const previousBranch = previousBranchProbe.stdout;
18912
+ await run("git", [
18913
+ "fetch",
18914
+ "origin",
18915
+ defaultBranch
18916
+ ], cwd);
18917
+ const newBranch = await findUniqueBranchName(cwd);
18918
+ if (!(await run("git", [
18919
+ "checkout",
18920
+ "-b",
18921
+ newBranch,
18922
+ `origin/${defaultBranch}`
18923
+ ], cwd)).success) return {
18924
+ status: "not-attempted",
18925
+ reason: "checkout-failed"
18645
18926
  };
18646
- if (isPreCommitNpmProject(topLevel)) return {
18647
- hookPath: getPackageJsonPath(topLevel),
18648
- runnerRoot: topLevel,
18649
- kind: "pre-commit-npm"
18927
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18928
+ await run("git", ["checkout", previousBranch], cwd);
18929
+ if (deleteNewBranch) await run("git", [
18930
+ "branch",
18931
+ "-D",
18932
+ newBranch
18933
+ ], cwd);
18650
18934
  };
18651
- if (isPrettyQuickProject(topLevel)) return {
18652
- hookPath: getPackageJsonPath(topLevel),
18653
- runnerRoot: topLevel,
18654
- kind: "pretty-quick"
18935
+ if (!(await run("git", [
18936
+ "add",
18937
+ "--",
18938
+ path$1.relative(cwd, workflowPath)
18939
+ ], cwd)).success) {
18940
+ await restoreToPreviousBranch(true);
18941
+ return {
18942
+ status: "not-attempted",
18943
+ reason: "git-add-failed"
18944
+ };
18945
+ }
18946
+ if (!(await run("git", [
18947
+ "commit",
18948
+ "-m",
18949
+ commitMessage
18950
+ ], cwd)).success) {
18951
+ await restoreToPreviousBranch(true);
18952
+ return {
18953
+ status: "not-attempted",
18954
+ reason: "git-commit-failed"
18955
+ };
18956
+ }
18957
+ if (!(await run("git", [
18958
+ "push",
18959
+ "-u",
18960
+ "origin",
18961
+ newBranch
18962
+ ], cwd)).success) {
18963
+ await restoreToPreviousBranch(true);
18964
+ return {
18965
+ status: "not-attempted",
18966
+ reason: "git-push-failed"
18967
+ };
18968
+ }
18969
+ const prCreate = await run("gh", [
18970
+ "pr",
18971
+ "create",
18972
+ "--title",
18973
+ prTitle,
18974
+ "--body",
18975
+ prBody,
18976
+ "--base",
18977
+ defaultBranch,
18978
+ "--head",
18979
+ newBranch
18980
+ ], cwd);
18981
+ await restoreToPreviousBranch(false);
18982
+ if (!prCreate.success) return {
18983
+ status: "branch-pushed",
18984
+ branch: newBranch
18655
18985
  };
18656
- const hookPath = runGit(projectRoot, [
18657
- "rev-parse",
18658
- "--git-path",
18659
- HOOK_RELATIVE_PATH
18660
- ]);
18661
- if (hookPath === null || hookPath.length === 0) return null;
18662
18986
  return {
18663
- hookPath: resolveGitPath(projectRoot, hookPath),
18664
- runnerRoot: topLevel,
18665
- kind: "git"
18987
+ status: "pr-opened",
18988
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18666
18989
  };
18667
18990
  };
18668
- const installReactDoctorGitHook = (options) => {
18669
- if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
18670
- if (options.kind === "lefthook") return installLefthook(options);
18671
- if (options.kind === "pre-commit") return installPreCommit(options);
18672
- if (options.kind === "overcommit") return installOvercommit(options);
18673
- if (options.kind === "yorkie") return installYorkie(options);
18674
- if (options.kind === "ghooks") return installGhooks(options);
18675
- if (options.kind === "git-hooks-js") return installGitHooksJs(options);
18676
- if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
18677
- if (options.kind === "pretty-quick") return installPrettyQuick(options);
18678
- return installDirectGitHook(options);
18991
+ const stageWorkflowFile = async (params) => {
18992
+ const workflowPath = path$1.resolve(params.workflowPath);
18993
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18994
+ if (!repoRootProbe.success) return false;
18995
+ return (await run("git", [
18996
+ "add",
18997
+ "--",
18998
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18999
+ ], repoRootProbe.stdout)).success;
18679
19000
  };
18680
19001
  //#endregion
18681
- //#region src/cli/utils/should-skip-prompts.ts
18682
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19002
+ //#region src/cli/utils/report-workflow-result.ts
19003
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
19004
+ if (result.status === "failed") {
19005
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
19006
+ return false;
19007
+ }
19008
+ if (result.status === "exists") {
19009
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
19010
+ return false;
19011
+ }
19012
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
19013
+ recordCount(METRIC.installWorkflow, 1);
19014
+ return true;
19015
+ };
18683
19016
  //#endregion
18684
- //#region src/cli/utils/install-react-doctor.ts
18685
- const SETUP_OPTION_GIT_HOOK = "git-hook";
18686
- const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
18687
- const SETUP_OPTION_WORKFLOW = "workflow";
18688
- const SETUP_OPTION_SKIP = "skip";
18689
- const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
18690
- "ghooks",
18691
- "git-hooks-js",
18692
- "lefthook",
18693
- "overcommit",
18694
- "pre-commit",
18695
- "pre-commit-npm",
18696
- "pretty-quick",
18697
- "simple-git-hooks",
18698
- "yorkie"
18699
- ]);
18700
- const PACKAGE_MANAGER_LOCKFILES = [
18701
- {
18702
- packageManager: "pnpm",
18703
- fileName: "pnpm-lock.yaml"
18704
- },
18705
- {
18706
- packageManager: "yarn",
18707
- fileName: "yarn.lock"
18708
- },
18709
- {
18710
- packageManager: "bun",
18711
- fileName: "bun.lockb"
18712
- },
18713
- {
18714
- packageManager: "bun",
18715
- fileName: "bun.lock"
18716
- },
18717
- {
18718
- packageManager: "npm",
18719
- fileName: "package-lock.json"
19017
+ //#region src/cli/utils/set-up-github-actions.ts
19018
+ const setUpGitHubActions = async (options) => {
19019
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
19020
+ try {
19021
+ installReactDoctorScriptStep(projectRoot);
19022
+ } catch {}
19023
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
19024
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
19025
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
19026
+ cliLogger.break();
19027
+ if (workflowResult.status === "failed") {
19028
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
19029
+ return false;
18720
19030
  }
18721
- ];
18722
- const findNearestFileDirectory = (startDirectory, fileNames) => {
18723
- let currentDirectory = path$1.resolve(startDirectory);
18724
- while (true) {
18725
- if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
18726
- const parentDirectory = path$1.dirname(currentDirectory);
18727
- if (parentDirectory === currentDirectory) return null;
18728
- currentDirectory = parentDirectory;
19031
+ if (workflowResult.status === "created") {
19032
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
19033
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
19034
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
19035
+ else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
19036
+ else {
19037
+ pullRequestSpinner.stop();
19038
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
19039
+ cliLogger.log(didStage ? ` Staged the workflow file. Commit it to start scanning every pull request.` : " React Doctor will now scan every new pull request automatically.");
19040
+ }
19041
+ }
19042
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
19043
+ return didCreateWorkflow;
19044
+ };
19045
+ //#endregion
19046
+ //#region src/cli/utils/install-agent-hooks.ts
19047
+ const CLAUDE_AGENT = "claude-code";
19048
+ const CURSOR_AGENT = "cursor";
19049
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
19050
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
19051
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
19052
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
19053
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
19054
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
19055
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
19056
+ const JSON_INDENT_SPACES$1 = 2;
19057
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
19058
+ const readJsonFile = (filePath, fallback) => {
19059
+ if (!fs$1.existsSync(filePath)) return fallback;
19060
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
19061
+ if (content.length === 0) return fallback;
19062
+ return JSON.parse(content);
19063
+ };
19064
+ const writeJsonFile = (filePath, value) => {
19065
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
19066
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
19067
+ };
19068
+ const writeHookScript = (filePath) => {
19069
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
19070
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
19071
+ fs$1.chmodSync(filePath, 493);
19072
+ };
19073
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
19074
+ const installClaudeHook = (projectRoot) => {
19075
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
19076
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
19077
+ const settings = readJsonFile(settingsPath, {});
19078
+ const hooks = { ...settings.hooks ?? {} };
19079
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
19080
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
19081
+ type: "command",
19082
+ command: CLAUDE_HOOK_COMMAND
19083
+ }] });
19084
+ hooks.PostToolBatch = postToolBatchHooks;
19085
+ writeJsonFile(settingsPath, {
19086
+ ...settings,
19087
+ hooks
19088
+ });
19089
+ writeHookScript(hookPath);
19090
+ return [settingsPath, hookPath];
19091
+ };
19092
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
19093
+ const installCursorHook = (projectRoot) => {
19094
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
19095
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
19096
+ const config = readJsonFile(configPath, {});
19097
+ const hooks = { ...config.hooks ?? {} };
19098
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
19099
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
19100
+ command: CURSOR_HOOK_RELATIVE_PATH,
19101
+ matcher: CURSOR_HOOK_MATCHER,
19102
+ timeout: 120
19103
+ });
19104
+ hooks.postToolUse = postToolUseHooks;
19105
+ writeJsonFile(configPath, {
19106
+ ...config,
19107
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
19108
+ hooks
19109
+ });
19110
+ writeHookScript(hookPath);
19111
+ return [configPath, hookPath];
19112
+ };
19113
+ const buildAgentHookScript = () => [
19114
+ "#!/bin/sh",
19115
+ "set -u",
19116
+ "",
19117
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
19118
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
19119
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
19120
+ "cat > \"$input_file\"",
19121
+ "",
19122
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
19123
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
19124
+ "if [ -z \"$project_root\" ]; then",
19125
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
19126
+ "fi",
19127
+ "if ! cd \"$project_root\"; then",
19128
+ " exit 0",
19129
+ "fi",
19130
+ "",
19131
+ "should_scan() {",
19132
+ " if ! command -v node >/dev/null 2>&1; then",
19133
+ " return 0",
19134
+ " fi",
19135
+ "",
19136
+ " node - \"$input_file\" <<'NODE'",
19137
+ "const fs = require('node:fs');",
19138
+ "const inputPath = process.argv[2];",
19139
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
19140
+ "try {",
19141
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
19142
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
19143
+ " if (eventName === 'PostToolBatch') {",
19144
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
19145
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
19146
+ " }",
19147
+ " const toolName = input.tool_name || input.toolName || input.tool;",
19148
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
19149
+ "} catch {",
19150
+ " process.exit(0);",
19151
+ "}",
19152
+ "NODE",
19153
+ "}",
19154
+ "",
19155
+ "run_react_doctor() {",
19156
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
19157
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
19158
+ " return",
19159
+ " fi",
19160
+ "",
19161
+ " if command -v react-doctor >/dev/null 2>&1; then",
19162
+ " react-doctor --verbose --diff --blocking warning --no-score",
19163
+ " return",
19164
+ " fi",
19165
+ "",
19166
+ " if command -v pnpm >/dev/null 2>&1; then",
19167
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
19168
+ " return",
19169
+ " fi",
19170
+ "",
19171
+ " if command -v npx >/dev/null 2>&1; then",
19172
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
19173
+ " return",
19174
+ " fi",
19175
+ "",
19176
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
19177
+ " return 0",
19178
+ "}",
19179
+ "",
19180
+ "if ! should_scan; then",
19181
+ " exit 0",
19182
+ "fi",
19183
+ "",
19184
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
19185
+ " exit 0",
19186
+ "fi",
19187
+ "",
19188
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
19189
+ "const fs = require('node:fs');",
19190
+ "const inputPath = process.argv[2];",
19191
+ "const outputPath = process.argv[3];",
19192
+ "const readInput = () => {",
19193
+ " try {",
19194
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
19195
+ " } catch {",
19196
+ " return {};",
19197
+ " }",
19198
+ "};",
19199
+ "const input = readInput();",
19200
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
19201
+ "if (!scanOutput) process.exit(0);",
19202
+ "const message = `React Doctor found issues in the changed files. Review this output and fix the regressions before finishing. For confirmed issues that cannot be fixed now, create GitHub issues with the rule, file/line, confidence, impact, and proposed fix.\\n\\n${scanOutput}`;",
19203
+ "if (input.hook_event_name === 'PostToolBatch') {",
19204
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
19205
+ "} else {",
19206
+ " console.log(JSON.stringify({ additional_context: message }));",
19207
+ "}",
19208
+ "NODE",
19209
+ ""
19210
+ ].join("\n");
19211
+ const installReactDoctorAgentHooks = (options) => {
19212
+ const installedAgents = [];
19213
+ const files = [];
19214
+ const requestedAgents = options.agents.filter(isSupportedAgent);
19215
+ for (const agent of requestedAgents) {
19216
+ if (agent === CLAUDE_AGENT) {
19217
+ files.push(...installClaudeHook(options.projectRoot));
19218
+ installedAgents.push(agent);
19219
+ }
19220
+ if (agent === CURSOR_AGENT) {
19221
+ files.push(...installCursorHook(options.projectRoot));
19222
+ installedAgents.push(agent);
19223
+ }
18729
19224
  }
19225
+ return {
19226
+ installedAgents,
19227
+ files
19228
+ };
18730
19229
  };
18731
- const detectPackageManager = (projectRoot) => {
18732
- let currentDirectory = path$1.resolve(projectRoot);
18733
- while (true) {
18734
- const packageJson = readPackageJson(currentDirectory);
18735
- if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
18736
- const packageManagerName = packageJson.packageManager.split("@")[0];
18737
- if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
18738
- }
18739
- const parentDirectory = path$1.dirname(currentDirectory);
18740
- if (parentDirectory === currentDirectory) break;
18741
- currentDirectory = parentDirectory;
19230
+ //#endregion
19231
+ //#region src/cli/utils/install-git-hook-file.ts
19232
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
19233
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
19234
+ const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\s\\S]*?${REACT_DOCTOR_BLOCK_END}\\n?|# react-doctor hook launcher start[\\s\\S]*?# react-doctor hook launcher end\\n?)`);
19235
+ const SHEBANG = "#!/bin/sh";
19236
+ const SHEBANG_PREFIX = "#!";
19237
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
19238
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
19239
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
19240
+ const buildReactDoctorHookBlock = () => [
19241
+ REACT_DOCTOR_BLOCK_START,
19242
+ "react_doctor_scan_staged_files() {",
19243
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
19244
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
19245
+ " return",
19246
+ " fi",
19247
+ "",
19248
+ " if command -v react-doctor >/dev/null 2>&1; then",
19249
+ ` ${REACT_DOCTOR_COMMAND}`,
19250
+ " return",
19251
+ " fi",
19252
+ "",
19253
+ " if command -v pnpm >/dev/null 2>&1; then",
19254
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
19255
+ " return",
19256
+ " fi",
19257
+ "",
19258
+ " if command -v npx >/dev/null 2>&1; then",
19259
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
19260
+ " return",
19261
+ " fi",
19262
+ "",
19263
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
19264
+ "}",
19265
+ "",
19266
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
19267
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
19268
+ " rm -f \"$react_doctor_output\"",
19269
+ "else",
19270
+ " rm -f \"$react_doctor_output\"",
19271
+ ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
19272
+ "fi",
19273
+ REACT_DOCTOR_BLOCK_END
19274
+ ].join("\n");
19275
+ const mergeHookContent = (existingContent) => {
19276
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
19277
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
19278
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
19279
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
19280
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
19281
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
19282
+ return [
19283
+ shebangLine,
19284
+ "",
19285
+ hookBlock.trimEnd(),
19286
+ ...remainingLines
19287
+ ].join("\n");
18742
19288
  }
18743
- const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
18744
- return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19289
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18745
19290
  };
18746
- const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
18747
- const buildInstallCommand = (projectRoot) => {
18748
- const packageManager = detectPackageManager(projectRoot);
18749
- const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
18750
- if (packageManager === "npm") return {
18751
- command: "npm",
18752
- args: [
18753
- "install",
18754
- "--save-dev",
18755
- packageSpecifier
18756
- ],
18757
- cwd: projectRoot
18758
- };
18759
- if (packageManager === "yarn") return {
18760
- command: "yarn",
18761
- args: [
18762
- "add",
18763
- "--dev",
18764
- packageSpecifier
18765
- ],
18766
- cwd: projectRoot
18767
- };
18768
- if (packageManager === "bun") return {
18769
- command: "bun",
18770
- args: [
18771
- "add",
18772
- "--dev",
18773
- packageSpecifier
18774
- ],
18775
- cwd: projectRoot
18776
- };
19291
+ const removeLegacyManagedRunner = (projectRoot) => {
19292
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
19293
+ fs$1.rmSync(runnerPath, { force: true });
19294
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
19295
+ fs$1.rmdirSync(directory);
19296
+ } catch {}
19297
+ };
19298
+ const installDirectGitHook = (options) => {
19299
+ const didHookExist = fs$1.existsSync(options.hookPath);
19300
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
19301
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
19302
+ "config",
19303
+ "core.hooksPath",
19304
+ options.hooksPathConfig
19305
+ ]);
19306
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19307
+ fs$1.writeFileSync(options.hookPath, nextContent);
19308
+ fs$1.chmodSync(options.hookPath, 493);
19309
+ removeLegacyManagedRunner(options.projectRoot);
18777
19310
  return {
18778
- command: "pnpm",
18779
- args: [
18780
- "add",
18781
- "--save-dev",
18782
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18783
- packageSpecifier
18784
- ],
18785
- cwd: projectRoot
19311
+ hookPath: options.hookPath,
19312
+ kind: options.kind ?? "git",
19313
+ status: didHookExist ? "updated" : "created"
18786
19314
  };
18787
19315
  };
18788
- const execFileAsync$1 = promisify(execFile);
18789
- const defaultInstallDependencyRunner = async (input) => {
18790
- await execFileAsync$1(input.command, [...input.args], {
18791
- cwd: input.cwd,
18792
- env: {
18793
- ...process.env,
18794
- REACT_DOCTOR_INSTALL: "1"
18795
- },
18796
- shell: process.platform === "win32"
18797
- });
19316
+ //#endregion
19317
+ //#region src/cli/utils/install-git-hook-config-managers.ts
19318
+ const appendStringCommand = (existingCommand) => {
19319
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
19320
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18798
19321
  };
18799
- const isSupplyChainTrustError = (error) => {
18800
- const candidate = error;
18801
- const haystack = [
18802
- candidate?.stderr,
18803
- candidate?.stdout,
18804
- candidate?.message
18805
- ].map((part) => String(part ?? "")).join("\n");
18806
- return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19322
+ const appendArrayCommand = (existingCommands) => {
19323
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
19324
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18807
19325
  };
18808
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18809
- const installReactDoctorDependency = async (options) => {
19326
+ const installPackageJsonHook = (options, strategy) => {
19327
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
19328
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18810
19329
  const packageJson = readPackageJson(options.projectRoot);
18811
- if (!isRecord(packageJson)) return {
18812
- dependencyStatus: "skipped",
18813
- dependencyReason: "missing-or-invalid-package-json"
18814
- };
18815
- if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
18816
- if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
18817
- dependencyStatus: "skipped",
18818
- dependencyReason: "invalid-dev-dependencies"
18819
- };
18820
- const runnerInput = buildInstallCommand(options.projectRoot);
18821
- try {
18822
- await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
18823
- } catch (error) {
18824
- return {
18825
- dependencyStatus: "skipped",
18826
- dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
18827
- installCommand: formatInstallCommand(runnerInput)
18828
- };
19330
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
19331
+ const parentKeys = strategy.path.slice(0, -1);
19332
+ const leafKey = strategy.path[strategy.path.length - 1];
19333
+ let parent = nextPackageJson;
19334
+ for (const key of parentKeys) {
19335
+ const existing = parent[key];
19336
+ const cloned = isRecord(existing) ? { ...existing } : {};
19337
+ parent[key] = cloned;
19338
+ parent = cloned;
18829
19339
  }
18830
- return { dependencyStatus: "created" };
19340
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
19341
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
19342
+ removeLegacyManagedRunner(options.projectRoot);
19343
+ return {
19344
+ hookPath: packageJsonPath,
19345
+ kind: strategy.kind,
19346
+ status: didHookExist ? "updated" : "created"
19347
+ };
18831
19348
  };
18832
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18833
- hookPath,
18834
- runnerRoot: projectRoot,
18835
- kind: "git"
19349
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
19350
+ kind: "simple-git-hooks",
19351
+ path: ["simple-git-hooks", "pre-commit"],
19352
+ leafShape: "string"
19353
+ });
19354
+ const installGhooks = (options) => installPackageJsonHook(options, {
19355
+ kind: "ghooks",
19356
+ path: [
19357
+ "config",
19358
+ "ghooks",
19359
+ "pre-commit"
19360
+ ],
19361
+ leafShape: "string"
19362
+ });
19363
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
19364
+ kind: "pre-commit-npm",
19365
+ path: ["pre-commit"],
19366
+ leafShape: "array"
19367
+ });
19368
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
19369
+ kind: "pretty-quick",
19370
+ path: ["gitHooks", "pre-commit"],
19371
+ leafShape: "string"
18836
19372
  });
18837
- const formatGitHookInstallMessage = (hookResult) => {
18838
- if (CONFIG_ONLY_GIT_HOOK_KINDS.has(hookResult.kind)) return `React Doctor pre-commit config ${hookResult.status} at ${hookResult.hookPath}. Run your hook manager's install command if hooks are not already installed.`;
18839
- return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
18840
- };
18841
- const formatDoctorScriptInstallMessage = (scriptResult) => {
18842
- const messages = [];
18843
- const scriptName = scriptResult.scriptName ?? "doctor";
18844
- if (scriptResult.scriptStatus === "created") messages.push(`Added package script: ${scriptName}.`);
18845
- else if (scriptResult.scriptStatus === "existing") messages.push(`Package script already exists: ${scriptName}.`);
18846
- else if (scriptResult.scriptReason === "script-names-taken") messages.push("Skipped package script: doctor and react-doctor are already taken.");
18847
- else if (scriptResult.scriptReason === "doctor-script-taken") messages.push("Skipped package script: doctor and react-doctor scripts already exist.");
18848
- else if (scriptResult.scriptReason === "invalid-scripts") messages.push(`Skipped package script: scripts field is not an object.`);
18849
- else messages.push("Skipped package script: package.json missing or invalid.");
18850
- return messages.join(" ");
18851
- };
18852
- const formatDependencyInstallMessage = (result) => {
18853
- if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
18854
- if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
18855
- if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
18856
- if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
18857
- if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
18858
- return "Skipped dev dependency install: package.json missing or invalid.";
19373
+ const installYorkie = (options) => installPackageJsonHook(options, {
19374
+ kind: "yorkie",
19375
+ path: ["gitHooks", "pre-commit"],
19376
+ leafShape: "string"
19377
+ });
19378
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
19379
+ kind: "git-hooks-js",
19380
+ path: ["git-hooks", "pre-commit"],
19381
+ leafShape: "string"
19382
+ });
19383
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
19384
+ const normalizedContent = ensureTrailingNewline(content);
19385
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
19386
+ if (match === null) return ensureTrailingNewline([
19387
+ normalizedContent.trimEnd(),
19388
+ "",
19389
+ `${sectionName}:`,
19390
+ ...block,
19391
+ ""
19392
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
19393
+ const sectionStartIndex = match.index;
19394
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
19395
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
19396
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
19397
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
19398
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
19399
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
19400
+ const suffix = normalizedContent.slice(insertIndex);
19401
+ return ensureTrailingNewline([
19402
+ prefix,
19403
+ ...block,
19404
+ suffix.trimStart()
19405
+ ].join("\n"));
18859
19406
  };
18860
- const buildDependencyFollowUp = (result) => {
18861
- if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
18862
- return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19407
+ const findTopLevelSectionRange = (content, sectionName) => {
19408
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
19409
+ if (match === null) return null;
19410
+ const headerLineEndIndex = content.indexOf("\n", match.index);
19411
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
19412
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
19413
+ nextSectionPattern.lastIndex = headerEndIndex;
19414
+ return {
19415
+ headerEndIndex,
19416
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
19417
+ };
18863
19418
  };
18864
- const installReactDoctorScriptStep = (projectRoot) => {
18865
- const scriptSpinner = spinner("Installing React Doctor package script...").start();
18866
- try {
18867
- const scriptResult = installDoctorScript({ projectRoot });
18868
- scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18869
- } catch (error) {
18870
- scriptSpinner.fail("Failed to install React Doctor package script.");
18871
- throw error;
18872
- }
19419
+ const appendLefthookCommand = (content) => {
19420
+ const normalizedContent = ensureTrailingNewline(content);
19421
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
19422
+ const reactDoctorCommandBlock = [
19423
+ " react-doctor:",
19424
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
19425
+ ""
19426
+ ];
19427
+ if (sectionRange === null) return ensureTrailingNewline([
19428
+ normalizedContent.trimEnd(),
19429
+ "",
19430
+ "pre-commit:",
19431
+ " commands:",
19432
+ ...reactDoctorCommandBlock
19433
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
19434
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
19435
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
19436
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
19437
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
19438
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18873
19439
  };
18874
- const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
18875
- installReactDoctorScriptStep(projectRoot);
18876
- const dependencySpinner = spinner("Installing React Doctor package...").start();
18877
- try {
18878
- const dependencyResult = await installReactDoctorDependency({
18879
- projectRoot,
18880
- runner: dependencyRunner
18881
- });
18882
- recordCount(METRIC.installDependency, 1, {
18883
- status: dependencyResult.dependencyStatus,
18884
- reason: dependencyResult.dependencyReason ?? null,
18885
- packageManager: detectPackageManager(projectRoot)
18886
- });
18887
- if (dependencyResult.dependencyStatus === "skipped") {
18888
- const message = formatDependencyInstallMessage(dependencyResult);
18889
- if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
18890
- else dependencySpinner.fail(message);
18891
- const followUp = buildDependencyFollowUp(dependencyResult);
18892
- if (followUp !== void 0) cliLogger.dim(followUp);
18893
- return dependencyResult;
18894
- }
18895
- dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
18896
- return dependencyResult;
18897
- } catch (error) {
18898
- dependencySpinner.fail("Failed to install React Doctor package.");
18899
- throw error;
19440
+ const installLefthook = (options) => {
19441
+ const didHookExist = fs$1.existsSync(options.hookPath);
19442
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19443
+ if (!existingContent.includes("react-doctor")) {
19444
+ const nextContent = appendLefthookCommand(existingContent);
19445
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19446
+ fs$1.writeFileSync(options.hookPath, nextContent);
18900
19447
  }
19448
+ removeLegacyManagedRunner(options.projectRoot);
19449
+ return {
19450
+ hookPath: options.hookPath,
19451
+ kind: "lefthook",
19452
+ status: didHookExist ? "updated" : "created"
19453
+ };
18901
19454
  };
18902
- const getSkillSourceDirectory = () => {
18903
- const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18904
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18905
- };
18906
- const findBundledSiblingSkills = (primarySkillDir) => {
18907
- const skillsParent = path$1.dirname(primarySkillDir);
18908
- if (!fs$1.existsSync(skillsParent)) return [];
18909
- const resolvedPrimary = path$1.resolve(primarySkillDir);
18910
- return fs$1.readdirSync(skillsParent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => ({
18911
- name: entry.name,
18912
- source: path$1.join(skillsParent, entry.name)
18913
- })).filter((sibling) => path$1.resolve(sibling.source) !== resolvedPrimary && fs$1.existsSync(path$1.join(sibling.source, SKILL_MANIFEST_FILE)));
18914
- };
18915
- const installBundledSiblingSkills = async (primarySkillDir, agents, projectRoot) => {
18916
- const installedSkillNames = [];
18917
- for (const sibling of findBundledSiblingSkills(primarySkillDir)) {
18918
- const result = await installSkillsFromSource({
18919
- source: sibling.source,
18920
- agents: [...agents],
18921
- cwd: projectRoot,
18922
- mode: "copy"
18923
- });
18924
- if (result.failed.length > 0) throw new Error(result.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
18925
- if (result.skills.length > 0) installedSkillNames.push(sibling.name);
19455
+ const installPreCommit = (options) => {
19456
+ const didHookExist = fs$1.existsSync(options.hookPath);
19457
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19458
+ if (!existingContent.includes("id: react-doctor")) {
19459
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
19460
+ const localHookBlock = [
19461
+ " - repo: local",
19462
+ " hooks:",
19463
+ " - id: react-doctor",
19464
+ " name: react-doctor",
19465
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
19466
+ " language: system",
19467
+ " pass_filenames: false",
19468
+ ""
19469
+ ].join("\n");
19470
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
19471
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19472
+ fs$1.writeFileSync(options.hookPath, nextContent);
18926
19473
  }
18927
- return installedSkillNames;
19474
+ removeLegacyManagedRunner(options.projectRoot);
19475
+ return {
19476
+ hookPath: options.hookPath,
19477
+ kind: "pre-commit",
19478
+ status: didHookExist ? "updated" : "created"
19479
+ };
18928
19480
  };
18929
- const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
18930
- const runInstallReactDoctor = async (options = {}) => {
18931
- const requestedProjectRoot = options.projectRoot ?? process.cwd();
18932
- const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
18933
- const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
18934
- if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
18935
- cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
18936
- process.exitCode = 1;
18937
- return;
18938
- }
18939
- const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
18940
- if (detectedAgents.length === 0) {
18941
- cliLogger.error("No supported coding agents detected.");
18942
- cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
18943
- cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
18944
- process.exitCode = 1;
18945
- return;
18946
- }
18947
- const skipPrompts = shouldSkipPrompts({ yes: options.yes });
18948
- const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
18949
- const gitHookPath = gitHookTarget?.hookPath;
18950
- const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
18951
- const prompt = options.prompt ?? prompts;
18952
- const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
18953
- type: "multiselect",
18954
- name: "agents",
18955
- message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
18956
- choices: detectedAgents.map((agent) => ({
18957
- title: getSkillAgentConfig(agent).displayName,
18958
- value: agent,
18959
- selected: true
18960
- })),
18961
- instructions: false,
18962
- min: 1
18963
- }, promptOptions)).agents ?? [];
18964
- if (selectedAgents.length === 0) return;
18965
- const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
18966
- const canInstallWorkflow = !isReactDoctorWorkflowInstalled(projectRoot);
18967
- const setupActionChoices = [
18968
- ...gitHookPath === null || gitHookPath === void 0 ? [] : [{
18969
- title: "Pre-commit hook",
18970
- description: "Check staged changes before each commit",
18971
- value: SETUP_OPTION_GIT_HOOK,
18972
- selected: true
18973
- }],
18974
- ...canInstallNativeAgentHooks(selectedAgents) ? [{
18975
- title: "Agent hooks",
18976
- description: "Ask Claude Code or Cursor to scan after code edits",
18977
- value: SETUP_OPTION_AGENT_HOOKS,
18978
- selected: Boolean(options.agentHooks)
18979
- }] : [],
18980
- ...canInstallWorkflow ? [{
18981
- title: "GitHub Actions workflow",
18982
- description: "Scan pull requests in CI",
18983
- value: SETUP_OPTION_WORKFLOW,
18984
- selected: true
18985
- }] : []
18986
- ];
18987
- const setupChoices = setupActionChoices.length === 0 ? [] : [{
18988
- title: "Skip optional setup",
18989
- description: "Install only the agent skill and package setup",
18990
- value: SETUP_OPTION_SKIP,
18991
- selected: false
18992
- }, ...setupActionChoices];
18993
- const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
18994
- type: "multiselect",
18995
- name: "setupOptions",
18996
- message: "Select additional React Doctor setup:",
18997
- choices: setupChoices,
18998
- instructions: false
18999
- }, promptOptions)).setupOptions ?? [];
19000
- const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19001
- const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19002
- const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19003
- const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19004
- const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_WORKFLOW));
19005
- if (options.dryRun) {
19006
- cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19007
- for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19008
- cliLogger.dim(` Source: ${sourceDir}`);
19009
- for (const sibling of findBundledSiblingSkills(sourceDir)) cliLogger.dim(` Also installs skill: ${sibling.name}`);
19010
- cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19011
- cliLogger.dim(" Dev dependency: react-doctor");
19012
- if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19013
- if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19014
- if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19015
- return;
19016
- }
19017
- const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19018
- try {
19019
- const installResult = await installSkillsFromSource({
19020
- source: sourceDir,
19021
- agents: selectedAgents,
19022
- cwd: projectRoot,
19023
- mode: "copy"
19024
- });
19025
- if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19026
- if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19027
- installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19028
- } catch (error) {
19029
- installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19030
- throw error;
19031
- }
19032
- try {
19033
- const installedSiblingSkills = await installBundledSiblingSkills(sourceDir, selectedAgents, projectRoot);
19034
- if (installedSiblingSkills.length > 0) cliLogger.dim(` Also installed the ${installedSiblingSkills.join(", ")} skill.`);
19035
- } catch {
19036
- cliLogger.dim(" Skipped bundled sibling skills (install error).");
19037
- }
19038
- const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19039
- if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
19040
- const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19041
- try {
19042
- const hookResult = installReactDoctorGitHook({
19043
- hookPath: gitHookTarget.hookPath,
19044
- projectRoot: gitHookTarget.runnerRoot,
19045
- kind: gitHookTarget.kind,
19046
- hooksPathConfig: gitHookTarget.hooksPathConfig
19047
- });
19048
- hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19049
- recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19050
- } catch (error) {
19051
- hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19052
- throw error;
19053
- }
19481
+ const installOvercommit = (options) => {
19482
+ const didHookExist = fs$1.existsSync(options.hookPath);
19483
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19484
+ if (!existingContent.includes("ReactDoctor")) {
19485
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
19486
+ " ReactDoctor:",
19487
+ " enabled: true",
19488
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
19489
+ ""
19490
+ ]);
19491
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19492
+ fs$1.writeFileSync(options.hookPath, nextContent);
19054
19493
  }
19055
- if (shouldInstallAgentHooks) {
19056
- const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19057
- try {
19058
- const hookResult = installReactDoctorAgentHooks({
19059
- projectRoot,
19060
- agents: selectedAgents
19061
- });
19062
- if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19063
- else {
19064
- hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19065
- recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19066
- }
19067
- } catch (error) {
19068
- hookSpinner.fail("Failed to install React Doctor agent hooks.");
19069
- throw error;
19070
- }
19494
+ removeLegacyManagedRunner(options.projectRoot);
19495
+ return {
19496
+ hookPath: options.hookPath,
19497
+ kind: "overcommit",
19498
+ status: didHookExist ? "updated" : "created"
19499
+ };
19500
+ };
19501
+ //#endregion
19502
+ //#region src/cli/utils/install-git-hook.ts
19503
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
19504
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
19505
+ const isSimpleGitHooksProject = (projectRoot) => {
19506
+ const packageJson = readPackageJson(projectRoot);
19507
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19508
+ };
19509
+ const getLefthookConfigPath = (projectRoot) => {
19510
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
19511
+ const filePath = path$1.join(projectRoot, fileName);
19512
+ if (fs$1.existsSync(filePath)) return filePath;
19071
19513
  }
19072
- let didInstallWorkflow = false;
19073
- if (shouldInstallWorkflow) didInstallWorkflow = reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19074
- recordCount(METRIC.installCompleted, 1, {
19075
- agentsCount: selectedAgents.length,
19076
- gitHook: shouldInstallGitHook,
19077
- agentHooks: shouldInstallAgentHooks,
19078
- workflow: didInstallWorkflow,
19079
- dependencyStatus: dependencyResult.dependencyStatus,
19080
- packageManager: detectPackageManager(projectRoot)
19081
- });
19082
- for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19514
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19515
+ };
19516
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
19517
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
19518
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
19519
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
19520
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
19521
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
19522
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
19523
+ const detectGitHookTarget = (projectRoot) => {
19524
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
19525
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
19526
+ const configuredHooksPath = runGit(projectRoot, [
19527
+ "config",
19528
+ "--path",
19529
+ "--get",
19530
+ "core.hooksPath"
19531
+ ]);
19532
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
19533
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
19534
+ runnerRoot: topLevel,
19535
+ kind: "configured"
19536
+ };
19537
+ if (isHuskyProject(topLevel)) return {
19538
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19539
+ runnerRoot: topLevel,
19540
+ kind: "husky",
19541
+ hooksPathConfig: HUSKY_HOOKS_PATH
19542
+ };
19543
+ if (isVitePlusProject(topLevel)) return {
19544
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19545
+ runnerRoot: topLevel,
19546
+ kind: "vite-plus",
19547
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19548
+ };
19549
+ if (isSimpleGitHooksProject(topLevel)) return {
19550
+ hookPath: path$1.join(topLevel, "package.json"),
19551
+ runnerRoot: topLevel,
19552
+ kind: "simple-git-hooks"
19553
+ };
19554
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19555
+ if (lefthookConfigPath !== null) return {
19556
+ hookPath: lefthookConfigPath,
19557
+ runnerRoot: topLevel,
19558
+ kind: "lefthook"
19559
+ };
19560
+ if (isPreCommitProject(topLevel)) return {
19561
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19562
+ runnerRoot: topLevel,
19563
+ kind: "pre-commit"
19564
+ };
19565
+ if (isOvercommitProject(topLevel)) return {
19566
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19567
+ runnerRoot: topLevel,
19568
+ kind: "overcommit"
19569
+ };
19570
+ if (isYorkieProject(topLevel)) return {
19571
+ hookPath: getPackageJsonPath(topLevel),
19572
+ runnerRoot: topLevel,
19573
+ kind: "yorkie"
19574
+ };
19575
+ if (isGhooksProject(topLevel)) return {
19576
+ hookPath: getPackageJsonPath(topLevel),
19577
+ runnerRoot: topLevel,
19578
+ kind: "ghooks"
19579
+ };
19580
+ if (isGitHooksJsProject(topLevel)) return {
19581
+ hookPath: getPackageJsonPath(topLevel),
19582
+ runnerRoot: topLevel,
19583
+ kind: "git-hooks-js"
19584
+ };
19585
+ if (isPreCommitNpmProject(topLevel)) return {
19586
+ hookPath: getPackageJsonPath(topLevel),
19587
+ runnerRoot: topLevel,
19588
+ kind: "pre-commit-npm"
19589
+ };
19590
+ if (isPrettyQuickProject(topLevel)) return {
19591
+ hookPath: getPackageJsonPath(topLevel),
19592
+ runnerRoot: topLevel,
19593
+ kind: "pretty-quick"
19594
+ };
19595
+ const hookPath = runGit(projectRoot, [
19596
+ "rev-parse",
19597
+ "--git-path",
19598
+ HOOK_RELATIVE_PATH
19599
+ ]);
19600
+ if (hookPath === null || hookPath.length === 0) return null;
19601
+ return {
19602
+ hookPath: resolveGitPath(projectRoot, hookPath),
19603
+ runnerRoot: topLevel,
19604
+ kind: "git"
19605
+ };
19606
+ };
19607
+ const installReactDoctorGitHook = (options) => {
19608
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19609
+ if (options.kind === "lefthook") return installLefthook(options);
19610
+ if (options.kind === "pre-commit") return installPreCommit(options);
19611
+ if (options.kind === "overcommit") return installOvercommit(options);
19612
+ if (options.kind === "yorkie") return installYorkie(options);
19613
+ if (options.kind === "ghooks") return installGhooks(options);
19614
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19615
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19616
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19617
+ return installDirectGitHook(options);
19083
19618
  };
19084
19619
  //#endregion
19085
- //#region src/cli/utils/hash-project-root.ts
19086
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19620
+ //#region src/cli/utils/should-skip-prompts.ts
19621
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19087
19622
  //#endregion
19088
- //#region src/cli/utils/action-upgrade-prompt.ts
19089
- const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
19090
- const getActionUpgradeStore = (options = {}) => new Conf({
19091
- projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
19092
- cwd: options.cwd
19093
- });
19094
- const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
19095
- try {
19096
- const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
19097
- return Boolean(upgrades[hashProjectRoot(projectRoot)]);
19098
- } catch {
19099
- return true;
19623
+ //#region src/cli/utils/install-react-doctor.ts
19624
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19625
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19626
+ const SETUP_OPTION_SKIP = "skip";
19627
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19628
+ "ghooks",
19629
+ "git-hooks-js",
19630
+ "lefthook",
19631
+ "overcommit",
19632
+ "pre-commit",
19633
+ "pre-commit-npm",
19634
+ "pretty-quick",
19635
+ "simple-git-hooks",
19636
+ "yorkie"
19637
+ ]);
19638
+ const PACKAGE_MANAGER_LOCKFILES = [
19639
+ {
19640
+ packageManager: "pnpm",
19641
+ fileName: "pnpm-lock.yaml"
19642
+ },
19643
+ {
19644
+ packageManager: "yarn",
19645
+ fileName: "yarn.lock"
19646
+ },
19647
+ {
19648
+ packageManager: "bun",
19649
+ fileName: "bun.lockb"
19650
+ },
19651
+ {
19652
+ packageManager: "bun",
19653
+ fileName: "bun.lock"
19654
+ },
19655
+ {
19656
+ packageManager: "npm",
19657
+ fileName: "package-lock.json"
19100
19658
  }
19101
- };
19102
- const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
19103
- try {
19104
- const store = getActionUpgradeStore(storeOptions);
19105
- const upgrades = store.get("actionUpgrades", {});
19106
- store.set("actionUpgrades", {
19107
- ...upgrades,
19108
- [hashProjectRoot(projectRoot)]: {
19109
- rootDirectory: path$1.resolve(projectRoot),
19110
- outcome,
19111
- at: (/* @__PURE__ */ new Date()).toISOString()
19112
- }
19113
- });
19114
- return true;
19115
- } catch {
19116
- return false;
19659
+ ];
19660
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19661
+ let currentDirectory = path$1.resolve(startDirectory);
19662
+ while (true) {
19663
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19664
+ const parentDirectory = path$1.dirname(currentDirectory);
19665
+ if (parentDirectory === currentDirectory) return null;
19666
+ currentDirectory = parentDirectory;
19117
19667
  }
19118
19668
  };
19119
- //#endregion
19120
- //#region src/cli/utils/install-skill-for-agent.ts
19121
- const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19122
- const source = getSkillSourceDirectory();
19123
- if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19124
- const result = await installSkillsFromSource({
19125
- source,
19126
- agents: [agent],
19127
- cwd: projectRoot,
19128
- mode: "copy"
19129
- });
19130
- return result.skills.length > 0 && result.failed.length === 0;
19669
+ const detectPackageManager = (projectRoot) => {
19670
+ let currentDirectory = path$1.resolve(projectRoot);
19671
+ while (true) {
19672
+ const packageJson = readPackageJson(currentDirectory);
19673
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19674
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19675
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19676
+ }
19677
+ const parentDirectory = path$1.dirname(currentDirectory);
19678
+ if (parentDirectory === currentDirectory) break;
19679
+ currentDirectory = parentDirectory;
19680
+ }
19681
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19682
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19131
19683
  };
19132
- //#endregion
19133
- //#region src/cli/utils/open-url.ts
19134
- const resolveOpenCommand = (url) => {
19135
- if (process$1.platform === "darwin") return {
19136
- command: "open",
19137
- args: [url]
19684
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19685
+ const buildInstallCommand = (projectRoot) => {
19686
+ const packageManager = detectPackageManager(projectRoot);
19687
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19688
+ if (packageManager === "npm") return {
19689
+ command: "npm",
19690
+ args: [
19691
+ "install",
19692
+ "--save-dev",
19693
+ packageSpecifier
19694
+ ],
19695
+ cwd: projectRoot
19138
19696
  };
19139
- if (process$1.platform === "win32") return {
19140
- command: "cmd",
19697
+ if (packageManager === "yarn") return {
19698
+ command: "yarn",
19141
19699
  args: [
19142
- "/c",
19143
- "start",
19144
- "",
19145
- url
19146
- ]
19700
+ "add",
19701
+ "--dev",
19702
+ packageSpecifier
19703
+ ],
19704
+ cwd: projectRoot
19705
+ };
19706
+ if (packageManager === "bun") return {
19707
+ command: "bun",
19708
+ args: [
19709
+ "add",
19710
+ "--dev",
19711
+ packageSpecifier
19712
+ ],
19713
+ cwd: projectRoot
19147
19714
  };
19148
19715
  return {
19149
- command: "xdg-open",
19150
- args: [url]
19716
+ command: "pnpm",
19717
+ args: [
19718
+ "add",
19719
+ "--save-dev",
19720
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19721
+ packageSpecifier
19722
+ ],
19723
+ cwd: projectRoot
19151
19724
  };
19152
19725
  };
19153
- const openUrl = (url) => {
19154
- try {
19155
- const { command, args } = resolveOpenCommand(url);
19156
- const child = spawn(command, args, {
19157
- detached: true,
19158
- stdio: "ignore"
19159
- });
19160
- child.on("error", () => {});
19161
- child.unref();
19162
- return true;
19163
- } catch {
19164
- return false;
19165
- }
19166
- };
19167
- //#endregion
19168
- //#region src/cli/utils/open-workflow-pull-request.ts
19169
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
19170
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
19171
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
19172
- 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.
19173
-
19174
- Docs: https://www.react.doctor/ci`;
19175
19726
  const execFileAsync = promisify(execFile);
19176
- const run = async (command, args, cwd) => {
19727
+ const defaultInstallDependencyRunner = async (input) => {
19728
+ await execFileAsync(input.command, [...input.args], {
19729
+ cwd: input.cwd,
19730
+ env: {
19731
+ ...process.env,
19732
+ REACT_DOCTOR_INSTALL: "1"
19733
+ },
19734
+ shell: process.platform === "win32"
19735
+ });
19736
+ };
19737
+ const isSupplyChainTrustError = (error) => {
19738
+ const candidate = error;
19739
+ const haystack = [
19740
+ candidate?.stderr,
19741
+ candidate?.stdout,
19742
+ candidate?.message
19743
+ ].map((part) => String(part ?? "")).join("\n");
19744
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19745
+ };
19746
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19747
+ const installReactDoctorDependency = async (options) => {
19748
+ const packageJson = readPackageJson(options.projectRoot);
19749
+ if (!isRecord(packageJson)) return {
19750
+ dependencyStatus: "skipped",
19751
+ dependencyReason: "missing-or-invalid-package-json"
19752
+ };
19753
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19754
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19755
+ dependencyStatus: "skipped",
19756
+ dependencyReason: "invalid-dev-dependencies"
19757
+ };
19758
+ const runnerInput = buildInstallCommand(options.projectRoot);
19177
19759
  try {
19178
- const { stdout, stderr } = await execFileAsync(command, [...args], {
19179
- cwd,
19180
- encoding: "utf8"
19181
- });
19182
- return {
19183
- success: true,
19184
- stdout: stdout.trim(),
19185
- stderr: stderr.trim()
19186
- };
19760
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19187
19761
  } catch (error) {
19188
- const failure = error;
19189
19762
  return {
19190
- success: false,
19191
- stdout: (failure.stdout ?? "").trim(),
19192
- stderr: (failure.stderr ?? "").trim()
19763
+ dependencyStatus: "skipped",
19764
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19765
+ installCommand: formatInstallCommand(runnerInput)
19193
19766
  };
19194
19767
  }
19768
+ return { dependencyStatus: "created" };
19195
19769
  };
19196
- const detectDefaultBranch = async (cwd) => {
19197
- const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
19198
- if (symRef.success) {
19199
- const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
19200
- if (branchMatch) return branchMatch[1];
19201
- }
19202
- if ((await run("git", [
19203
- "rev-parse",
19204
- "--verify",
19205
- "origin/main"
19206
- ], cwd)).success) return "main";
19207
- if ((await run("git", [
19208
- "rev-parse",
19209
- "--verify",
19210
- "origin/master"
19211
- ], cwd)).success) return "master";
19212
- return null;
19770
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19771
+ hookPath,
19772
+ runnerRoot: projectRoot,
19773
+ kind: "git"
19774
+ });
19775
+ const formatGitHookInstallMessage = (hookResult) => {
19776
+ if (CONFIG_ONLY_GIT_HOOK_KINDS.has(hookResult.kind)) return `React Doctor pre-commit config ${hookResult.status} at ${hookResult.hookPath}. Run your hook manager's install command if hooks are not already installed.`;
19777
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19213
19778
  };
19214
- const findUniqueBranchName = async (cwd) => {
19215
- if (!(await run("git", [
19216
- "rev-parse",
19217
- "--verify",
19218
- NEW_BRANCH_PREFIX
19219
- ], cwd)).success) return NEW_BRANCH_PREFIX;
19220
- return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
19779
+ const formatDependencyInstallMessage = (result) => {
19780
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19781
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19782
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19783
+ if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
19784
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19785
+ return "Skipped dev dependency install: package.json missing or invalid.";
19221
19786
  };
19222
- const openWorkflowPullRequest = async (params) => {
19223
- const workflowPath = path$1.resolve(params.workflowPath);
19224
- const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
19225
- const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
19226
- const prBody = params.prBody ?? DEFAULT_PR_BODY;
19227
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19228
- if (!repoRootProbe.success) return {
19229
- status: "not-attempted",
19230
- reason: "not-a-git-repo"
19231
- };
19232
- const cwd = repoRootProbe.stdout;
19233
- if (!isCommandAvailable("gh")) return {
19234
- status: "not-attempted",
19235
- reason: "gh-not-installed"
19236
- };
19237
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
19238
- status: "not-attempted",
19239
- reason: "gh-not-authenticated"
19240
- };
19241
- const defaultBranch = await detectDefaultBranch(cwd);
19242
- if (!defaultBranch) return {
19243
- status: "not-attempted",
19244
- reason: "no-default-branch"
19245
- };
19246
- const previousBranchProbe = await run("git", [
19247
- "rev-parse",
19248
- "--abbrev-ref",
19249
- "HEAD"
19250
- ], cwd);
19251
- if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
19252
- status: "not-attempted",
19253
- reason: "detached-head"
19254
- };
19255
- const previousBranch = previousBranchProbe.stdout;
19256
- await run("git", [
19257
- "fetch",
19258
- "origin",
19259
- defaultBranch
19260
- ], cwd);
19261
- const newBranch = await findUniqueBranchName(cwd);
19262
- if (!(await run("git", [
19263
- "checkout",
19264
- "-b",
19265
- newBranch,
19266
- `origin/${defaultBranch}`
19267
- ], cwd)).success) return {
19268
- status: "not-attempted",
19269
- reason: "checkout-failed"
19270
- };
19271
- const restoreToPreviousBranch = async (deleteNewBranch) => {
19272
- await run("git", ["checkout", previousBranch], cwd);
19273
- if (deleteNewBranch) await run("git", [
19274
- "branch",
19275
- "-D",
19276
- newBranch
19277
- ], cwd);
19278
- };
19279
- if (!(await run("git", [
19280
- "add",
19281
- "--",
19282
- path$1.relative(cwd, workflowPath)
19283
- ], cwd)).success) {
19284
- await restoreToPreviousBranch(true);
19285
- return {
19286
- status: "not-attempted",
19287
- reason: "git-add-failed"
19288
- };
19787
+ const buildDependencyFollowUp = (result) => {
19788
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19789
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19790
+ };
19791
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19792
+ installReactDoctorScriptStep(projectRoot);
19793
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19794
+ try {
19795
+ const dependencyResult = await installReactDoctorDependency({
19796
+ projectRoot,
19797
+ runner: dependencyRunner
19798
+ });
19799
+ recordCount(METRIC.installDependency, 1, {
19800
+ status: dependencyResult.dependencyStatus,
19801
+ reason: dependencyResult.dependencyReason ?? null,
19802
+ packageManager: detectPackageManager(projectRoot)
19803
+ });
19804
+ if (dependencyResult.dependencyStatus === "skipped") {
19805
+ const message = formatDependencyInstallMessage(dependencyResult);
19806
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19807
+ else dependencySpinner.fail(message);
19808
+ const followUp = buildDependencyFollowUp(dependencyResult);
19809
+ if (followUp !== void 0) cliLogger.dim(followUp);
19810
+ return dependencyResult;
19811
+ }
19812
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19813
+ return dependencyResult;
19814
+ } catch (error) {
19815
+ dependencySpinner.fail("Failed to install React Doctor package.");
19816
+ throw error;
19817
+ }
19818
+ };
19819
+ const getSkillSourceDirectory = () => {
19820
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19821
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19822
+ };
19823
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19824
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19825
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19826
+ try {
19827
+ const installResult = await installSkillsFromSource({
19828
+ source: sourceDir,
19829
+ agents: selectedAgents,
19830
+ cwd: projectRoot,
19831
+ mode: "copy"
19832
+ });
19833
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19834
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19835
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19836
+ } catch (error) {
19837
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19838
+ throw error;
19289
19839
  }
19290
- if (!(await run("git", [
19291
- "commit",
19292
- "-m",
19293
- commitMessage
19294
- ], cwd)).success) {
19295
- await restoreToPreviousBranch(true);
19296
- return {
19297
- status: "not-attempted",
19298
- reason: "git-commit-failed"
19299
- };
19840
+ };
19841
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19842
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19843
+ try {
19844
+ const hookResult = installReactDoctorGitHook({
19845
+ hookPath: gitHookTarget.hookPath,
19846
+ projectRoot: gitHookTarget.runnerRoot,
19847
+ kind: gitHookTarget.kind,
19848
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19849
+ });
19850
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19851
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19852
+ } catch (error) {
19853
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19854
+ throw error;
19300
19855
  }
19301
- if (!(await run("git", [
19302
- "push",
19303
- "-u",
19304
- "origin",
19305
- newBranch
19306
- ], cwd)).success) {
19307
- await restoreToPreviousBranch(true);
19308
- return {
19309
- status: "not-attempted",
19310
- reason: "git-push-failed"
19311
- };
19856
+ };
19857
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19858
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19859
+ try {
19860
+ const hookResult = installReactDoctorAgentHooks({
19861
+ projectRoot,
19862
+ agents: selectedAgents
19863
+ });
19864
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19865
+ else {
19866
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19867
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19868
+ }
19869
+ } catch (error) {
19870
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19871
+ throw error;
19312
19872
  }
19313
- const prCreate = await run("gh", [
19314
- "pr",
19315
- "create",
19316
- "--title",
19317
- prTitle,
19318
- "--body",
19319
- prBody,
19320
- "--base",
19321
- defaultBranch,
19322
- "--head",
19323
- newBranch
19324
- ], cwd);
19325
- await restoreToPreviousBranch(false);
19326
- if (!prCreate.success) return {
19327
- status: "branch-pushed",
19328
- branch: newBranch
19329
- };
19330
- return {
19331
- status: "pr-opened",
19332
- url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
19333
- };
19334
19873
  };
19335
- const stageWorkflowFile = async (params) => {
19336
- const workflowPath = path$1.resolve(params.workflowPath);
19337
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19338
- if (!repoRootProbe.success) return false;
19339
- return (await run("git", [
19340
- "add",
19341
- "--",
19342
- path$1.relative(repoRootProbe.stdout, workflowPath)
19343
- ], repoRootProbe.stdout)).success;
19874
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19875
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19876
+ };
19877
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19878
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19879
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19880
+ if (upgradeResult.status === "failed") {
19881
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19882
+ return false;
19883
+ }
19884
+ if (upgradeResult.status === "not-needed") {
19885
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19886
+ return false;
19887
+ }
19888
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19889
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19890
+ return true;
19891
+ };
19892
+ const runInstallReactDoctor = async (options = {}) => {
19893
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19894
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19895
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19896
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19897
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19898
+ process.exitCode = 1;
19899
+ return;
19900
+ }
19901
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19902
+ if (detectedAgents.length === 0) {
19903
+ cliLogger.error("No supported coding agents detected.");
19904
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19905
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19906
+ process.exitCode = 1;
19907
+ return;
19908
+ }
19909
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19910
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19911
+ const gitHookPath = gitHookTarget?.hookPath;
19912
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19913
+ const prompt = options.prompt ?? prompts;
19914
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19915
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19916
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19917
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19918
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19919
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19920
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19921
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19922
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19923
+ type: "multiselect",
19924
+ name: "agents",
19925
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19926
+ choices: detectedAgents.map((agent) => ({
19927
+ title: getSkillAgentConfig(agent).displayName,
19928
+ value: agent,
19929
+ selected: true
19930
+ })),
19931
+ instructions: false,
19932
+ min: 1
19933
+ }, promptOptions)).agents ?? [];
19934
+ if (selectedAgents.length === 0) return;
19935
+ let dependencyResult;
19936
+ if (!options.dryRun) {
19937
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19938
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19939
+ }
19940
+ let didInstallWorkflow = false;
19941
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19942
+ cliLogger.break();
19943
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19944
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19945
+ }
19946
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19947
+ title: "Pre-commit hook",
19948
+ description: "Check staged changes before each commit",
19949
+ value: SETUP_OPTION_GIT_HOOK,
19950
+ selected: true
19951
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19952
+ title: "Agent hooks",
19953
+ description: "Ask Claude Code or Cursor to scan after code edits",
19954
+ value: SETUP_OPTION_AGENT_HOOKS,
19955
+ selected: Boolean(options.agentHooks)
19956
+ }] : []];
19957
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19958
+ title: "Skip optional setup",
19959
+ description: "Install only the agent skill and package setup",
19960
+ value: SETUP_OPTION_SKIP,
19961
+ selected: false
19962
+ }, ...setupActionChoices];
19963
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19964
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19965
+ type: "multiselect",
19966
+ name: "setupOptions",
19967
+ message: "Select additional React Doctor setup:",
19968
+ choices: setupChoices,
19969
+ instructions: false
19970
+ }, promptOptions)).setupOptions ?? [];
19971
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19972
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19973
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19974
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19975
+ if (!options.dryRun) {
19976
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19977
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19978
+ }
19979
+ if (options.dryRun) {
19980
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19981
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19982
+ cliLogger.dim(` Source: ${sourceDir}`);
19983
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19984
+ cliLogger.dim(" Dev dependency: react-doctor");
19985
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19986
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19987
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19988
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19989
+ return;
19990
+ }
19991
+ recordCount(METRIC.installCompleted, 1, {
19992
+ agentsCount: selectedAgents.length,
19993
+ gitHook: shouldInstallGitHook,
19994
+ agentHooks: shouldInstallAgentHooks,
19995
+ workflow: didInstallWorkflow,
19996
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19997
+ packageManager: detectPackageManager(projectRoot)
19998
+ });
19999
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
20000
+ };
20001
+ //#endregion
20002
+ //#region src/cli/utils/install-skill-for-agent.ts
20003
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
20004
+ const source = getSkillSourceDirectory();
20005
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
20006
+ const result = await installSkillsFromSource({
20007
+ source,
20008
+ agents: [agent],
20009
+ cwd: projectRoot,
20010
+ mode: "copy"
20011
+ });
20012
+ return result.skills.length > 0 && result.failed.length === 0;
19344
20013
  };
19345
20014
  //#endregion
19346
20015
  //#region src/cli/utils/launch-agent.ts
@@ -19431,9 +20100,6 @@ const copyToClipboard = (text) => {
19431
20100
  };
19432
20101
  //#endregion
19433
20102
  //#region src/cli/utils/handoff-to-agent.ts
19434
- const CI_YES_CHOICE = "ci-yes";
19435
- const CI_LEARN_MORE_CHOICE = "ci-learn-more";
19436
- const CI_NO_CHOICE = "ci-no";
19437
20103
  const CLIPBOARD_CHOICE = "clipboard";
19438
20104
  const SKIP_CHOICE = "skip";
19439
20105
  const printPayload = (payload) => {
@@ -19442,59 +20108,11 @@ const printPayload = (payload) => {
19442
20108
  cliLogger.log(payload);
19443
20109
  cliLogger.log(highlighter.dim("──────────────────────"));
19444
20110
  };
19445
- const setUpGitHubActions = async (rootDirectory) => {
19446
- const projectRoot = findNearestPackageDirectory(rootDirectory) ?? rootDirectory;
19447
- try {
19448
- installReactDoctorScriptStep(projectRoot);
19449
- } catch {}
19450
- const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
19451
- const workflowResult = installReactDoctorWorkflow(projectRoot);
19452
- reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
19453
- cliLogger.break();
19454
- if (workflowResult.status === "failed") {
19455
- cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
19456
- return;
19457
- }
19458
- if (workflowResult.status === "created") {
19459
- const pullRequestSpinner = spinner("Opening a pull request for review...").start();
19460
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
19461
- if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
19462
- else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
19463
- else {
19464
- pullRequestSpinner.stop();
19465
- if (await stageWorkflowFile({ workflowPath: workflowResult.workflowPath })) cliLogger.log(` Staged the workflow file. Commit it to start scanning every pull request.`);
19466
- else cliLogger.log(" React Doctor will now scan every new pull request automatically.");
19467
- }
19468
- }
19469
- cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
19470
- };
19471
- const UPGRADE_YES_CHOICE = "upgrade-yes";
19472
- const UPGRADE_NO_CHOICE = "upgrade-no";
19473
20111
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19474
20112
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19475
20113
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19476
20114
 
19477
20115
  Docs: https://www.react.doctor/ci`;
19478
- const askUpgradeActionVersion = async () => {
19479
- const { upgradeChoice } = await prompts({
19480
- type: "select",
19481
- name: "upgradeChoice",
19482
- message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
19483
- hint: " ",
19484
- choices: [{
19485
- title: "Yes (recommended)",
19486
- description: "Open a PR bumping the workflow to millionco/react-doctor@v2",
19487
- value: UPGRADE_YES_CHOICE
19488
- }, {
19489
- title: "No, thanks",
19490
- description: "Keep @v1 — won't ask again for this repo",
19491
- value: UPGRADE_NO_CHOICE
19492
- }],
19493
- initial: 0
19494
- }, { onCancel: () => true });
19495
- if (upgradeChoice === void 0) return "cancel";
19496
- return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
19497
- };
19498
20116
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19499
20117
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19500
20118
  if (!changed) return false;
@@ -19539,46 +20157,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19539
20157
  }
19540
20158
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19541
20159
  };
19542
- const SGR_BOLD_OFF = "\x1B[22m";
19543
- const ciQuestionMessage = [
19544
- "Add React Doctor to GitHub Actions?",
19545
- `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
19546
- `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
19547
- ].join("\n");
19548
- const askAddToGitHubActions = async () => {
19549
- while (true) {
19550
- const { ciChoice } = await prompts({
19551
- type: "select",
19552
- name: "ciChoice",
19553
- message: ciQuestionMessage,
19554
- hint: " ",
19555
- choices: [
19556
- {
19557
- title: "Yes (recommended)",
19558
- description: "Adds the workflow file and a doctor package script",
19559
- value: CI_YES_CHOICE
19560
- },
19561
- {
19562
- title: "Learn more",
19563
- description: highlighter.info(CI_URL),
19564
- value: CI_LEARN_MORE_CHOICE
19565
- },
19566
- {
19567
- title: "No, thanks",
19568
- description: "Continue to the agent handoff",
19569
- value: CI_NO_CHOICE
19570
- }
19571
- ],
19572
- initial: 0
19573
- }, { onCancel: () => true });
19574
- if (ciChoice === void 0) return "cancel";
19575
- if (ciChoice === CI_YES_CHOICE) return "yes";
19576
- if (ciChoice === CI_NO_CHOICE) return "no";
19577
- const opened = openUrl(CI_URL);
19578
- cliLogger.log(opened ? `Opened ${highlighter.info(CI_URL)} in your browser.` : `Visit ${highlighter.info(CI_URL)} to learn more.`);
19579
- cliLogger.break();
19580
- }
19581
- };
19582
20160
  const detectLaunchableAgents = async () => {
19583
20161
  const detected = new Set(await detectAvailableAgents());
19584
20162
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19595,7 +20173,7 @@ const handoffToAgent = async (input) => {
19595
20173
  });
19596
20174
  if (ciOutcome === "cancel") return;
19597
20175
  if (ciOutcome === "yes") {
19598
- await setUpGitHubActions(input.rootDirectory);
20176
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19599
20177
  cliLogger.break();
19600
20178
  }
19601
20179
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19746,6 +20324,14 @@ const HAPPY_FACE_LINES = [
19746
20324
  "│ ▽ │",
19747
20325
  "└─────┘"
19748
20326
  ];
20327
+ const FACE_INDENT = " ";
20328
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
20329
+ const clampToColumns = (text, maxColumns) => {
20330
+ if (maxColumns <= 0) return "";
20331
+ if (text.length <= maxColumns) return text;
20332
+ if (maxColumns === 1) return "…";
20333
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
20334
+ };
19749
20335
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19750
20336
  const characters = [...text];
19751
20337
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19759,13 +20345,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19759
20345
  const interLineDelayMs = 250 / speedMultiplier;
19760
20346
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19761
20347
  const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
19762
- const mouthPrefix = ` ${face[2] ?? ""} `;
19763
- yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
20348
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
20349
+ const terminalColumns = process.stdout.columns;
20350
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
20351
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
20352
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
20353
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19764
20354
  yield* writeStdout("\x1B[3A");
19765
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
20355
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19766
20356
  yield* Effect.sleep(interLineDelayMs);
19767
20357
  yield* writeStdout("\x1B[1B");
19768
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
20358
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19769
20359
  yield* Effect.sleep(explanationHoldMs);
19770
20360
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19771
20361
  });
@@ -19874,8 +20464,9 @@ const findLowestScoredScan = (completedScans) => {
19874
20464
  };
19875
20465
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
19876
20466
  const { completedScans, userConfig, verbose, isOffline, projectName } = input;
20467
+ const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
19877
20468
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
19878
- const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
20469
+ const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
19879
20470
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
19880
20471
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
19881
20472
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -19889,29 +20480,30 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19889
20480
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
19890
20481
  const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
19891
20482
  yield* Console.log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
19892
- if (surfaceDiagnostics.length > 0) {
20483
+ if (displayDiagnostics.length > 0) {
19893
20484
  yield* Console.log("");
19894
- yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
20485
+ yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19895
20486
  }
19896
20487
  const lowestScoredScan = findLowestScoredScan(completedScans);
19897
20488
  const aggregateScore = lowestScoredScan?.result.score ?? null;
19898
20489
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
19899
20490
  yield* printSummary({
19900
- diagnostics: surfaceDiagnostics,
20491
+ diagnostics: displayDiagnostics,
19901
20492
  elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
19902
20493
  scoreResult: aggregateScore,
19903
- potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
20494
+ potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
19904
20495
  totalSourceFileCount,
19905
20496
  noScoreMessage: "Score unavailable.",
19906
20497
  verbose,
19907
20498
  animateProjection: animateRender
19908
20499
  });
19909
20500
  const entries = completedScans.map((scan) => {
19910
- const errorCount = scan.result.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
20501
+ const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
20502
+ const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19911
20503
  return {
19912
20504
  projectName: scan.result.project.projectName,
19913
20505
  score: scan.result.score?.score ?? null,
19914
- issueCount: scan.result.diagnostics.length,
20506
+ issueCount: projectDiagnostics.length,
19915
20507
  errorCount
19916
20508
  };
19917
20509
  });
@@ -19919,7 +20511,7 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19919
20511
  yield* Console.log("");
19920
20512
  for (const entry of entries) yield* Console.log(buildSummaryLine(entry, longestProjectNameLength));
19921
20513
  yield* printFooter({
19922
- diagnostics: surfaceDiagnostics,
20514
+ diagnostics: displayDiagnostics,
19923
20515
  scoreResult: aggregateScore,
19924
20516
  projectName,
19925
20517
  isOffline
@@ -20009,7 +20601,8 @@ const resolveCliInspectOptions = (flags, userConfig) => {
20009
20601
  noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
20010
20602
  isCi: isCiEnvironment(),
20011
20603
  silent: Boolean(flags.json),
20012
- concurrency: resolveParallelFlag(flags.parallel)
20604
+ concurrency: resolveParallelFlag(flags.parallel),
20605
+ categoryFilters: resolveCliCategories(flags.category)
20013
20606
  };
20014
20607
  };
20015
20608
  //#endregion
@@ -20262,6 +20855,16 @@ const validateModeFlags = (flags) => {
20262
20855
  };
20263
20856
  //#endregion
20264
20857
  //#region src/cli/commands/inspect.ts
20858
+ const filterCompletedScansByCategories = (completedScans, categoryFilters) => {
20859
+ if (categoryFilters.size === 0) return [...completedScans];
20860
+ return completedScans.map((scan) => ({
20861
+ ...scan,
20862
+ result: {
20863
+ ...scan.result,
20864
+ diagnostics: filterDiagnosticsByCategories(scan.result.diagnostics, categoryFilters)
20865
+ }
20866
+ }));
20867
+ };
20265
20868
  /**
20266
20869
  * Post-scan finalization shared by the staged-arm and project-loop
20267
20870
  * paths of `inspectAction`: emit the JSON report (when in JSON mode)
@@ -20274,6 +20877,7 @@ const finalizeScans = (input) => {
20274
20877
  const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
20275
20878
  const baselineDegraded = input.baselineIntended && !baselineComputed;
20276
20879
  const mode = baselineDegraded ? "diff" : input.mode;
20880
+ const jsonCompletedScans = filterCompletedScansByCategories(input.completedScans, input.categoryFilters);
20277
20881
  if (input.isJsonMode) {
20278
20882
  const baseline = baselineComputed && baselineDeltas.length > 0 ? {
20279
20883
  baseRef: baselineDeltas[0].baseRef,
@@ -20285,7 +20889,7 @@ const finalizeScans = (input) => {
20285
20889
  directory: input.resolvedDirectory,
20286
20890
  mode,
20287
20891
  diff: input.diff,
20288
- scans: input.completedScans,
20892
+ scans: jsonCompletedScans,
20289
20893
  totalElapsedMilliseconds: performance.now() - input.startTime,
20290
20894
  baseline
20291
20895
  }));
@@ -20359,6 +20963,7 @@ const inspectAction = async (directory, flags) => {
20359
20963
  await Effect.runPromise(playWelcomeScene({ speedMultiplier: isReturningUser ? 2 : 1 }));
20360
20964
  } else Effect.runSync(printBrandedHeader);
20361
20965
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
20966
+ const categoryFilters = new Set(scanOptions.categoryFilters ?? []);
20362
20967
  const skipPrompts = shouldSkipPrompts({
20363
20968
  yes: flags.yes,
20364
20969
  json: flags.json
@@ -20419,6 +21024,7 @@ const inspectAction = async (directory, flags) => {
20419
21024
  isJsonMode,
20420
21025
  isScoreOnly,
20421
21026
  flags,
21027
+ categoryFilters,
20422
21028
  userConfig,
20423
21029
  resolvedDirectory,
20424
21030
  startTime
@@ -20478,6 +21084,7 @@ const inspectAction = async (directory, flags) => {
20478
21084
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
20479
21085
  await Effect.runPromise(printMultiProjectSummary({
20480
21086
  completedScans,
21087
+ categoryFilters,
20481
21088
  userConfig,
20482
21089
  verbose: Boolean(flags.verbose),
20483
21090
  isOffline: !shouldShowShareLink,
@@ -20493,14 +21100,15 @@ const inspectAction = async (directory, flags) => {
20493
21100
  isJsonMode,
20494
21101
  isScoreOnly,
20495
21102
  flags,
21103
+ categoryFilters,
20496
21104
  userConfig,
20497
21105
  resolvedDirectory,
20498
21106
  startTime
20499
21107
  });
20500
- const surfaceDiagnostics = filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig);
20501
- if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && surfaceDiagnostics.length > 0) {
21108
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
21109
+ if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
20502
21110
  await handoffToAgent({
20503
- diagnostics: surfaceDiagnostics,
21111
+ diagnostics: selectedSurfaceDiagnostics,
20504
21112
  projectName: path$1.basename(resolvedDirectory),
20505
21113
  rootDirectory: resolvedDirectory,
20506
21114
  interactive: true
@@ -20931,7 +21539,7 @@ const rulesListAction = async (options) => {
20931
21539
  });
20932
21540
  const catalog = buildRuleCatalog();
20933
21541
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
20934
- const categoryFilter = options.category?.toLowerCase();
21542
+ const categoryFilter = typeof options.category === "string" ? options.category.toLowerCase() : void 0;
20935
21543
  const frameworkFilter = options.framework?.toLowerCase();
20936
21544
  const rows = catalog.filter((entry) => {
20937
21545
  if (categoryFilter && entry.category.toLowerCase() !== categoryFilter) return false;
@@ -21294,6 +21902,7 @@ const ROOT_FLAG_SPEC = {
21294
21902
  "--yes"
21295
21903
  ]),
21296
21904
  longOptionsWithRequiredValues: new Set([
21905
+ "--category",
21297
21906
  "--changed-files-from",
21298
21907
  "--blocking",
21299
21908
  "--fail-on",
@@ -21450,6 +22059,7 @@ ${formatExampleLines([
21450
22059
  ["react-doctor ./apps/web", "scan a specific directory"],
21451
22060
  ["react-doctor --diff main", "scan only files changed vs. main"],
21452
22061
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
22062
+ ["react-doctor --category Security", "show only one diagnostic category"],
21453
22063
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
21454
22064
  ["react-doctor --json > report.json", "write a machine-readable report"],
21455
22065
  ["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
@@ -21478,7 +22088,8 @@ ${formatExampleLines([
21478
22088
  ${highlighter.dim("Learn more:")}
21479
22089
  ${highlighter.info(CANONICAL_GITHUB_URL)}
21480
22090
  `;
21481
- 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);
22091
+ const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
22092
+ 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").addOption(new Option$1("--category <category>", "only show diagnostics in a category (repeatable; e.g. Security)").argParser(collectCategoryOption)).option("--no-telemetry", "alias for --no-score (skip the score API, share URL, and crash reporting)").option("--staged", "scan only staged (git index) files for pre-commit hooks").option("--blocking <level>", "severity that fails CI: error (default), warning, or none (advisory)").addOption(new Option$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);
21482
22093
  program.action(inspectAction);
21483
22094
  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));
21484
22095
  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);
@@ -21521,4 +22132,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21521
22132
  export {};
21522
22133
 
21523
22134
  //# sourceMappingURL=cli.js.map
21524
- //# debugId=1486eaee-ed07-5eef-a9d7-51293140e237
22135
+ //# debugId=299ab690-e278-5f22-b581-ff28a76a28b8