react-doctor 0.4.2-dev.727894a → 0.4.2-dev.773e235

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]="e5634721-88db-51c8-93e5-137793125d7a")}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";
@@ -34,7 +34,7 @@ import * as ChildProcess from "effect/unstable/process/ChildProcess";
34
34
  import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
35
35
  import * as ts from "typescript";
36
36
  import { gzipSync } from "node:zlib";
37
- import { createHash, randomUUID } from "node:crypto";
37
+ 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([
@@ -6361,6 +6361,7 @@ const SCORE_API_URL = "https://www.react.doctor/api/score";
6361
6361
  const ENTERPRISE_CONTACT_URL = "https://react.doctor/enterprise";
6362
6362
  const SHARE_BASE_URL = "https://react.doctor/share";
6363
6363
  const CI_URL = "https://react.doctor/ci";
6364
+ const GITHUB_ACTIONS_SETUP_URL = "https://www.react.doctor/docs/ci-and-prs/github-actions-setup";
6364
6365
  const DOCS_URL = "https://react.doctor/docs";
6365
6366
  const DOCS_RULES_BASE_URL = `${DOCS_URL}/rules`;
6366
6367
  const FETCH_TIMEOUT_MS = 1e4;
@@ -6391,6 +6392,29 @@ const STAGED_FILES_PROJECT_CONFIG_FILENAMES = [
6391
6392
  "oxlint.json",
6392
6393
  ".oxlintrc.json"
6393
6394
  ];
6395
+ const CONFIG_FINGERPRINT_FILENAMES = [
6396
+ "doctor.config.ts",
6397
+ "doctor.config.mts",
6398
+ "doctor.config.cts",
6399
+ "doctor.config.js",
6400
+ "doctor.config.mjs",
6401
+ "doctor.config.cjs",
6402
+ "doctor.config.json",
6403
+ "doctor.config.jsonc",
6404
+ "react-doctor.config.json",
6405
+ "package.json",
6406
+ "pnpm-workspace.yaml",
6407
+ "tsconfig.json",
6408
+ "tsconfig.base.json",
6409
+ ".oxlintrc.json",
6410
+ ".eslintrc.json",
6411
+ "pnpm-lock.yaml",
6412
+ "package-lock.json",
6413
+ "yarn.lock",
6414
+ "bun.lock",
6415
+ "bun.lockb",
6416
+ ".gitignore"
6417
+ ];
6394
6418
  const CANONICAL_GITHUB_URL = "https://github.com/millionco/react-doctor";
6395
6419
  const CANONICAL_DISCORD_URL = "https://react.doctor/discord";
6396
6420
  const SKILL_NAME = "react-doctor";
@@ -6724,7 +6748,6 @@ const LEGACY_RULE_KEY_TO_NATIVE_RULE_KEY = {
6724
6748
  "react/jsx-no-new-function-as-prop": "react-doctor/jsx-no-new-function-as-prop",
6725
6749
  "react/jsx-no-new-object-as-prop": "react-doctor/jsx-no-new-object-as-prop",
6726
6750
  "react/jsx-no-script-url": "react-doctor/jsx-no-script-url",
6727
- "react/jsx-no-target-blank": "react-doctor/jsx-no-target-blank",
6728
6751
  "react/jsx-no-undef": "react-doctor/jsx-no-undef",
6729
6752
  "react/jsx-no-useless-fragment": "react-doctor/jsx-no-useless-fragment",
6730
6753
  "react/jsx-pascal-case": "react-doctor/jsx-pascal-case",
@@ -7920,51 +7943,51 @@ const FLAGGED_DEPENDENCIES = [
7920
7943
  {
7921
7944
  packageName: "expo-modules-autolinking",
7922
7945
  rule: "expo-no-redundant-dependency",
7923
- message: "\"expo-modules-autolinking\" should not be a direct dependency — Expo installs it transitively as needed",
7946
+ 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
7947
  help: "Remove `expo-modules-autolinking` from your package.json"
7925
7948
  },
7926
7949
  {
7927
7950
  packageName: "expo-dev-launcher",
7928
7951
  rule: "expo-no-redundant-dependency",
7929
- message: "\"expo-dev-launcher\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7952
+ 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
7953
  help: "Remove `expo-dev-launcher` and depend on `expo-dev-client` instead"
7931
7954
  },
7932
7955
  {
7933
7956
  packageName: "expo-dev-menu",
7934
7957
  rule: "expo-no-redundant-dependency",
7935
- message: "\"expo-dev-menu\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7958
+ 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
7959
  help: "Remove `expo-dev-menu` and depend on `expo-dev-client` instead"
7937
7960
  },
7938
7961
  {
7939
7962
  packageName: "expo-modules-core",
7940
7963
  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",
7964
+ 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
7965
  help: "Remove `expo-modules-core` from your package.json and import from `expo` instead"
7943
7966
  },
7944
7967
  {
7945
7968
  packageName: "@expo/metro-config",
7946
7969
  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",
7970
+ 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
7971
  help: "Remove `@expo/metro-config` and import `expo/metro-config` in your metro.config.js"
7949
7972
  },
7950
7973
  {
7951
7974
  packageName: "@types/react-native",
7952
7975
  rule: "expo-no-redundant-dependency",
7953
- message: "\"@types/react-native\" should not be installed — React Native ships its own types since SDK 48",
7976
+ 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
7977
  help: "Remove `@types/react-native` from your package.json",
7955
7978
  minSdkMajor: 48
7956
7979
  },
7957
7980
  {
7958
7981
  packageName: "@expo/config-plugins",
7959
7982
  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",
7983
+ 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
7984
  help: "Remove `@expo/config-plugins`; config-plugin authors should import from `expo/config-plugins`. See https://github.com/expo/expo/pull/18855",
7962
7985
  minSdkMajor: 48
7963
7986
  },
7964
7987
  {
7965
7988
  packageName: "@expo/prebuild-config",
7966
7989
  rule: "expo-no-redundant-dependency",
7967
- message: "\"@expo/prebuild-config\" should not be a direct dependency — Expo installs it transitively",
7990
+ 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
7991
  help: "Remove `@expo/prebuild-config` from your package.json",
7969
7992
  minSdkMajor: 53
7970
7993
  },
@@ -7978,28 +8001,28 @@ const FLAGGED_DEPENDENCIES = [
7978
8001
  {
7979
8002
  packageName: "expo-app-loading",
7980
8003
  rule: "expo-no-redundant-dependency",
7981
- message: "\"expo-app-loading\" was removed in SDK 49",
8004
+ message: "\"expo-app-loading\" was removed in SDK 49, so keeping it can leave imports unresolved after upgrading Expo",
7982
8005
  help: "Remove `expo-app-loading` and use `expo-splash-screen` instead. See https://docs.expo.dev/versions/latest/sdk/splash-screen/",
7983
8006
  minSdkMajor: 49
7984
8007
  },
7985
8008
  {
7986
8009
  packageName: "expo-firebase-analytics",
7987
8010
  rule: "expo-no-redundant-dependency",
7988
- message: "\"expo-firebase-analytics\" was removed in SDK 48",
8011
+ message: "\"expo-firebase-analytics\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7989
8012
  help: FIREBASE_HELP,
7990
8013
  minSdkMajor: 48
7991
8014
  },
7992
8015
  {
7993
8016
  packageName: "expo-firebase-recaptcha",
7994
8017
  rule: "expo-no-redundant-dependency",
7995
- message: "\"expo-firebase-recaptcha\" was removed in SDK 48",
8018
+ message: "\"expo-firebase-recaptcha\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7996
8019
  help: FIREBASE_HELP,
7997
8020
  minSdkMajor: 48
7998
8021
  },
7999
8022
  {
8000
8023
  packageName: "expo-firebase-core",
8001
8024
  rule: "expo-no-redundant-dependency",
8002
- message: "\"expo-firebase-core\" was removed in SDK 48",
8025
+ message: "\"expo-firebase-core\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
8003
8026
  help: FIREBASE_HELP,
8004
8027
  minSdkMajor: 48
8005
8028
  }
@@ -8040,7 +8063,7 @@ const checkExpoGitignore = (context) => {
8040
8063
  }));
8041
8064
  if (findLocalModuleNativeFiles(rootDirectory).find((nativeFilePath) => isPathGitIgnored(rootDirectory, nativeFilePath) === true) !== void 0) diagnostics.push(buildExpoDiagnostic({
8042
8065
  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",
8066
+ 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
8067
  help: "Use anchored patterns like `/ios` and `/android` in .gitignore so only the top-level native directories are excluded, not those inside `modules/`"
8045
8068
  }));
8046
8069
  return diagnostics;
@@ -8102,17 +8125,16 @@ const checkExpoPackageJsonConflicts = (context) => {
8102
8125
  const conflictingScriptNames = CONFLICTING_SCRIPT_NAMES.filter((scriptName) => Boolean(packageJson.scripts?.[scriptName]));
8103
8126
  if (conflictingScriptNames.length > 0) {
8104
8127
  const quotedNames = conflictingScriptNames.map((name) => `"${name}"`).join(", ");
8105
- const shadowsExpoCli = conflictingScriptNames.includes("expo");
8106
8128
  diagnostics.push(buildExpoDiagnostic({
8107
8129
  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" : ""}`,
8130
+ 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
8131
  help: "Rename these scripts so they don't collide with the `expo` / `react-native` binaries"
8110
8132
  }));
8111
8133
  }
8112
8134
  const packageName = packageJson.name;
8113
8135
  if (typeof packageName === "string" && context.directDependencyNames.has(packageName)) diagnostics.push(buildExpoDiagnostic({
8114
8136
  rule: "expo-package-json-conflict",
8115
- message: `package.json "name" is "${packageName}", which collides with a dependency of the same name`,
8137
+ 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
8138
  help: "Rename your package so it no longer matches one of its dependencies"
8117
8139
  }));
8118
8140
  return diagnostics;
@@ -8183,7 +8205,7 @@ const checkExpoRouterReactNavigation = (context) => {
8183
8205
  if (reactNavigationNames.length === 0) return [];
8184
8206
  return [buildExpoDiagnostic({
8185
8207
  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"}`,
8208
+ 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
8209
  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
8210
  })];
8189
8211
  };
@@ -8555,7 +8577,9 @@ const setColorEnabled = (enabled) => {
8555
8577
  highlighter.gray = colors.gray;
8556
8578
  highlighter.bold = colors.bold;
8557
8579
  };
8558
- const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
8580
+ const NEXT_ENTRY_FILE_PATTERN = /^(?:\.\/)?(?:src\/)?(?:middleware|proxy)\.(?:tsx?|jsx?|mts|mjs)$/;
8581
+ const shouldIncludeExplicitLintPath = (filePath, project) => JSX_FILE_PATTERN.test(filePath) || project?.framework === "nextjs" && NEXT_ENTRY_FILE_PATTERN.test(filePath);
8582
+ const computeExplicitLintIncludePaths = (includePaths, project) => includePaths.length > 0 ? includePaths.filter((filePath) => shouldIncludeExplicitLintPath(filePath, project)) : void 0;
8559
8583
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
8560
8584
  const FALSY_VALUES = new Set([
8561
8585
  "false",
@@ -8635,7 +8659,7 @@ const collectIgnorePatterns = (rootDirectory) => {
8635
8659
  return patterns;
8636
8660
  };
8637
8661
  const KNIP_JSON_FILENAME = "knip.json";
8638
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8662
+ const isRecord$1$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8639
8663
  const readJsonFileSafe = (filePath) => {
8640
8664
  let rawContents;
8641
8665
  try {
@@ -8651,10 +8675,10 @@ const readJsonFileSafe = (filePath) => {
8651
8675
  };
8652
8676
  const readKnipConfig = (rootDirectory) => {
8653
8677
  const knipJson = readJsonFileSafe(path.join(rootDirectory, KNIP_JSON_FILENAME));
8654
- if (isRecord$1(knipJson)) return knipJson;
8678
+ if (isRecord$1$1(knipJson)) return knipJson;
8655
8679
  const packageJson = readJsonFileSafe(path.join(rootDirectory, "package.json"));
8656
- const packageKnipConfig = isRecord$1(packageJson) ? packageJson.knip : null;
8657
- return isRecord$1(packageKnipConfig) ? packageKnipConfig : null;
8680
+ const packageKnipConfig = isRecord$1$1(packageJson) ? packageJson.knip : null;
8681
+ return isRecord$1$1(packageKnipConfig) ? packageKnipConfig : null;
8658
8682
  };
8659
8683
  const normalizePatternList = (value) => {
8660
8684
  if (typeof value === "string" && value.length > 0) return [value];
@@ -8666,10 +8690,10 @@ const prefixWorkspacePatterns = (workspacePattern, patterns) => {
8666
8690
  return patterns.map((pattern) => pattern.startsWith("!") ? `!${normalizedWorkspacePattern}/${pattern.slice(1)}` : `${normalizedWorkspacePattern}/${pattern}`);
8667
8691
  };
8668
8692
  const collectKnipWorkspacePatterns = (workspaces, settingName) => {
8669
- if (!isRecord$1(workspaces)) return [];
8693
+ if (!isRecord$1$1(workspaces)) return [];
8670
8694
  const patterns = [];
8671
8695
  for (const [workspacePattern, workspaceConfig] of Object.entries(workspaces)) {
8672
- if (!isRecord$1(workspaceConfig)) continue;
8696
+ if (!isRecord$1$1(workspaceConfig)) continue;
8673
8697
  patterns.push(...prefixWorkspacePatterns(workspacePattern, normalizePatternList(workspaceConfig[settingName])));
8674
8698
  }
8675
8699
  return patterns;
@@ -8981,7 +9005,7 @@ const checkDeadCode = async (options) => {
8981
9005
  plugin: DEAD_CODE_PLUGIN,
8982
9006
  rule: "unused-file",
8983
9007
  severity: "warning",
8984
- message: "Unused file — not reachable from any entry point",
9008
+ message: "Unused file is not reachable from any entry point, so it adds maintenance surface without shipping any code.",
8985
9009
  help: "Delete the file if it is truly unreachable, or import it from an entry point.",
8986
9010
  line: 0,
8987
9011
  column: 0,
@@ -8994,7 +9018,7 @@ const checkDeadCode = async (options) => {
8994
9018
  plugin: DEAD_CODE_PLUGIN,
8995
9019
  rule: unusedExport.isTypeOnly ? "unused-type" : "unused-export",
8996
9020
  severity: "warning",
8997
- message: `Unused ${label}: \`${unusedExport.name}\``,
9021
+ 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
9022
  help: "Drop the `export` keyword (or remove the declaration) if no other module uses this symbol.",
8999
9023
  line: unusedExport.line,
9000
9024
  column: unusedExport.column,
@@ -9008,7 +9032,7 @@ const checkDeadCode = async (options) => {
9008
9032
  plugin: DEAD_CODE_PLUGIN,
9009
9033
  rule: unusedDependency.isDevDependency ? "unused-dev-dependency" : "unused-dependency",
9010
9034
  severity: "warning",
9011
- message: `Unused ${label}: \`${unusedDependency.name}\``,
9035
+ message: `Unused ${label}: \`${unusedDependency.name}\` is not imported by the project, so it adds install time and supply-chain surface without being used.`,
9012
9036
  help: "Remove the dependency from package.json if it is genuinely unused.",
9013
9037
  line: 0,
9014
9038
  column: 0,
@@ -9022,7 +9046,7 @@ const checkDeadCode = async (options) => {
9022
9046
  plugin: DEAD_CODE_PLUGIN,
9023
9047
  rule: "circular-dependency",
9024
9048
  severity: "warning",
9025
- message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}`,
9049
+ message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}. Modules in the cycle can observe partially initialized exports, causing order-dependent bugs.`,
9026
9050
  help: "Break the cycle by extracting the shared code into a third module that both files import.",
9027
9051
  line: 0,
9028
9052
  column: 0,
@@ -9105,11 +9129,11 @@ const listSourceFilesViaFilesystem = (rootDirectory) => {
9105
9129
  return filePaths;
9106
9130
  };
9107
9131
  const listSourceFiles = (rootDirectory) => excludeMinifiedFiles(rootDirectory, listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory));
9108
- const resolveLintIncludePaths = (rootDirectory, userConfig) => {
9132
+ const resolveLintIncludePaths = (rootDirectory, userConfig, project) => {
9109
9133
  if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
9110
9134
  const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
9111
9135
  return listSourceFiles(rootDirectory).filter((filePath) => {
9112
- if (!JSX_FILE_PATTERN.test(filePath)) return false;
9136
+ if (!shouldIncludeExplicitLintPath(filePath, project)) return false;
9113
9137
  return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
9114
9138
  });
9115
9139
  };
@@ -9889,16 +9913,16 @@ const readPluginShape = (pluginSpecifier, loadModule) => {
9889
9913
  ruleNames: new Set(Object.keys(rules))
9890
9914
  };
9891
9915
  };
9892
- const bundledRequire = createRequire(import.meta.url);
9916
+ const bundledRequire$1 = createRequire(import.meta.url);
9893
9917
  const resolveReactHooksJsPlugin = (hasReactCompiler, customRulesOnly) => {
9894
9918
  if (!hasReactCompiler || customRulesOnly) return null;
9895
9919
  let pluginSpecifier;
9896
9920
  try {
9897
- pluginSpecifier = bundledRequire.resolve("eslint-plugin-react-hooks");
9921
+ pluginSpecifier = bundledRequire$1.resolve("eslint-plugin-react-hooks");
9898
9922
  } catch {
9899
9923
  return null;
9900
9924
  }
9901
- const { ruleNames } = readPluginShape(pluginSpecifier, (spec) => bundledRequire(spec));
9925
+ const { ruleNames } = readPluginShape(pluginSpecifier, (spec) => bundledRequire$1(spec));
9902
9926
  return {
9903
9927
  entry: {
9904
9928
  name: "react-hooks-js",
@@ -11461,7 +11485,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
11461
11485
  directory: scanDirectory,
11462
11486
  repo
11463
11487
  }).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);
11488
+ const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeExplicitLintIncludePaths([...input.includePaths], project)) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config, project);
11465
11489
  const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path$1.resolve(scanDirectory, relativePath)) : [];
11466
11490
  const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
11467
11491
  const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
@@ -12047,6 +12071,22 @@ const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
12047
12071
  * instead of being improvised per diagnostic.
12048
12072
  */
12049
12073
  const buildRuleDocsUrl = (plugin, rule) => `${DOCS_RULES_BASE_URL}/${plugin}/${rule}`;
12074
+ const computeConfigFingerprint = (projectDirectory, version) => {
12075
+ const parts = [`v=${version}`];
12076
+ let directory = projectDirectory;
12077
+ for (;;) {
12078
+ for (const filename of CONFIG_FINGERPRINT_FILENAMES) try {
12079
+ const stat = fs.statSync(path.join(directory, filename));
12080
+ parts.push(`${directory}/${filename}=${stat.mtimeMs}:${stat.size}`);
12081
+ } catch {
12082
+ continue;
12083
+ }
12084
+ const parent = path.dirname(directory);
12085
+ if (parent === directory) break;
12086
+ directory = parent;
12087
+ }
12088
+ return crypto.createHash("sha1").update(parts.join("|")).digest("hex");
12089
+ };
12050
12090
  const groupBy = (items, keyFn) => {
12051
12091
  const groups = /* @__PURE__ */ new Map();
12052
12092
  for (const item of items) {
@@ -12247,7 +12287,7 @@ const makeNoopConsole = () => ({
12247
12287
  });
12248
12288
  //#endregion
12249
12289
  //#region src/cli/utils/version.ts
12250
- const VERSION = "0.4.2-dev.727894a";
12290
+ const VERSION = "0.4.2-dev.773e235";
12251
12291
  //#endregion
12252
12292
  //#region src/cli/utils/json-mode.ts
12253
12293
  let context = null;
@@ -12605,13 +12645,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12605
12645
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12606
12646
  * standard `SENTRY_RELEASE` override.
12607
12647
  */
12608
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.727894a`;
12648
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.773e235`;
12609
12649
  /**
12610
12650
  * Deployment environment shown in Sentry's environment filter. Defaults to
12611
12651
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12612
12652
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12613
12653
  */
12614
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.727894a") ? "development" : "production");
12654
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.773e235") ? "development" : "production");
12615
12655
  /**
12616
12656
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12617
12657
  * (set to `0` to disable tracing) and falls back to
@@ -15874,13 +15914,14 @@ const buildRuntimeLayers = (input) => {
15874
15914
  const linterLayer = input.shouldSkipLint ? Linter.layerOf([]) : Linter.layerOxlint;
15875
15915
  const deadCodeLayer = input.shouldRunDeadCode ? DeadCode.layerNode : DeadCode.layerOf([]);
15876
15916
  const scoreLayer = input.shouldComputeScore ? Score.layerHttp : Score.layerOf(null);
15917
+ const projectLayer = input.projectInfoOverride === void 0 ? Project.layerNode : Project.layerOf(input.projectInfoOverride);
15877
15918
  const progressLayer = input.shouldShowProgressSpinners ? Progress.layerOra(buildSpinnerProgressHandle) : Progress.layerNoop;
15878
15919
  const configLayer = input.hasConfigOverride ? Config.layerOf({
15879
15920
  config: input.userConfig,
15880
15921
  resolvedDirectory: input.directory,
15881
15922
  configSourceDirectory: input.configSourceDirectory
15882
15923
  }) : Config.layerNode;
15883
- const baseLayers = Layer.mergeAll(Project.layerNode, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15924
+ const baseLayers = Layer.mergeAll(projectLayer, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15884
15925
  return input.oxlintConcurrency === void 0 ? baseLayers : Layer.mergeAll(baseLayers, Layer.succeed(OxlintConcurrency, input.oxlintConcurrency));
15885
15926
  };
15886
15927
  //#endregion
@@ -16473,8 +16514,22 @@ const buildCodeFrame = (input) => {
16473
16514
  });
16474
16515
  };
16475
16516
  //#endregion
16517
+ //#region src/cli/utils/resolve-measure-width.ts
16518
+ const resolveClampedWidth = (input) => {
16519
+ const terminalColumns = process.stdout.columns;
16520
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16521
+ const availableColumns = terminalColumns - input.reservedColumns;
16522
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16523
+ };
16524
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16525
+ reservedColumns,
16526
+ fullWidth: 60,
16527
+ minWidth: 24
16528
+ });
16529
+ //#endregion
16476
16530
  //#region src/cli/utils/build-section-divider.ts
16477
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16531
+ const DIVIDER_INDENT = " ";
16532
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16478
16533
  //#endregion
16479
16534
  //#region src/cli/utils/indent-multiline-text.ts
16480
16535
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16634,7 +16689,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16634
16689
  endLine: isMultiSite ? cluster.endLine : void 0,
16635
16690
  rootDirectory: resolveSourceRoot(lead)
16636
16691
  }) : null;
16637
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16692
+ if (codeFrame) {
16693
+ const boxInnerWidth = resolveMeasureWidth(8);
16694
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16695
+ }
16638
16696
  const seenHints = /* @__PURE__ */ new Set();
16639
16697
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16640
16698
  seenHints.add(diagnostic.suppressionHint);
@@ -16652,8 +16710,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16652
16710
  const learnMoreLine = formatLearnMoreLine(representative);
16653
16711
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16654
16712
  }
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}`));
16713
+ for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16714
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16657
16715
  if (renderEverySite && isAgentEnvironment) {
16658
16716
  const fixRecipeLine = formatFixRecipeLine(representative);
16659
16717
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16789,6 +16847,9 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
16789
16847
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
16790
16848
  return potentialScore.score;
16791
16849
  };
16850
+ //#endregion
16851
+ //#region src/cli/utils/filter-diagnostics-by-categories.ts
16852
+ const filterDiagnosticsByCategories = (diagnostics, categories) => categories.size === 0 ? [...diagnostics] : diagnostics.filter((diagnostic) => categories.has(diagnostic.category));
16792
16853
  const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16793
16854
  const FALSY_FLAG_VALUES = new Set([
16794
16855
  "",
@@ -16847,14 +16908,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16847
16908
  const RAINBOW_GRADIENT_WIDTH = 80;
16848
16909
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16849
16910
  const RAINBOW_OKLCH_CHROMA = .129;
16911
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16912
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16913
+ const getScoreBarWidth = () => resolveClampedWidth({
16914
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16915
+ fullWidth: 50,
16916
+ minWidth: 10
16917
+ });
16850
16918
  const buildScoreBarSegments = (filledCount) => {
16851
- const emptyCount = 50 - filledCount;
16919
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16852
16920
  return {
16853
16921
  filledSegment: "█".repeat(filledCount),
16854
16922
  emptySegment: "░".repeat(emptyCount)
16855
16923
  };
16856
16924
  };
16857
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16925
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16858
16926
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16859
16927
  const buildRawScoreBar = (displayScore) => {
16860
16928
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16890,10 +16958,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16890
16958
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16891
16959
  };
16892
16960
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16961
+ const barWidth = getScoreBarWidth();
16893
16962
  const currentFill = getFilledCount(currentScore);
16894
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16963
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16895
16964
  const gainCount = Math.max(0, potentialFill - currentFill);
16896
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16965
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16897
16966
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16898
16967
  };
16899
16968
  const getDoctorFace = (score) => {
@@ -16906,7 +16975,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16906
16975
  const buildRawFaceLines = (score) => {
16907
16976
  const [eyes, mouth] = getDoctorFace(score);
16908
16977
  return [
16909
- "┌─────┐",
16978
+ FACE_BOX_TOP_BORDER,
16910
16979
  `│ ${eyes} │`,
16911
16980
  `│ ${mouth} │`,
16912
16981
  "└─────┘"
@@ -17048,6 +17117,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17048
17117
  };
17049
17118
  //#endregion
17050
17119
  //#region src/cli/utils/render-summary.ts
17120
+ const FOOTER_DESCRIPTION_INDENT = " ";
17121
+ const printFooterDescription = (description) => Effect.gen(function* () {
17122
+ const wrapWidth = resolveMeasureWidth(2);
17123
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17124
+ });
17051
17125
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17052
17126
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17053
17127
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17067,14 +17141,14 @@ const printFooter = (input) => Effect.gen(function* () {
17067
17141
  if (!input.isOffline) {
17068
17142
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17069
17143
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17070
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17144
+ yield* printFooterDescription("Tell others how you did on socials");
17071
17145
  yield* Console.log("");
17072
17146
  }
17073
17147
  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"));
17148
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17075
17149
  yield* Console.log("");
17076
17150
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17077
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17151
+ yield* printFooterDescription("Report issues and star the repository!");
17078
17152
  });
17079
17153
  const printSummary = (input) => Effect.gen(function* () {
17080
17154
  if (input.scoreResult) {
@@ -17206,11 +17280,259 @@ const resolveOxlintNodeEffect = (isLintEnabled, isQuiet) => Effect.gen(function*
17206
17280
  });
17207
17281
  const resolveOxlintNode = (isLintEnabled, isQuiet) => Effect.runPromise(resolveOxlintNodeEffect(isLintEnabled, isQuiet).pipe(Effect.provide(NodeResolver.layerNode)));
17208
17282
  //#endregion
17283
+ //#region src/cli/utils/cli-input-error.ts
17284
+ /**
17285
+ * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17286
+ * argument, mutually exclusive flags, or an unknown `--project` name. This is
17287
+ * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17288
+ * through `handleUserError`: a clean, single-line message with no Sentry
17289
+ * report and no "Something went wrong, open a prefilled issue" block.
17290
+ *
17291
+ * The `message` is rendered verbatim, so it must read as a complete,
17292
+ * human-readable sentence that tells the user how to fix their invocation.
17293
+ */
17294
+ var CliInputError = class extends Error {
17295
+ name = "CliInputError";
17296
+ };
17297
+ //#endregion
17298
+ //#region src/cli/utils/resolve-cli-categories.ts
17299
+ const categoryByLowercase = new Map(DIAGNOSTIC_CATEGORY_BUCKETS.map((category) => [category.toLowerCase(), category]));
17300
+ const knownCategoryList = DIAGNOSTIC_CATEGORY_BUCKETS.join(", ");
17301
+ const splitCategoryFlagValue = (value) => value.split(",").map((category) => category.trim()).filter((category) => category.length > 0);
17302
+ const resolveCliCategories = (categoryFlag) => {
17303
+ const rawCategoryValues = categoryFlag === void 0 ? [] : Array.isArray(categoryFlag) ? categoryFlag : [categoryFlag];
17304
+ const resolvedCategories = [];
17305
+ const seenCategories = /* @__PURE__ */ new Set();
17306
+ for (const rawCategoryValue of rawCategoryValues) for (const categoryQuery of splitCategoryFlagValue(rawCategoryValue)) {
17307
+ const matchedCategory = categoryByLowercase.get(categoryQuery.toLowerCase());
17308
+ if (matchedCategory === void 0) throw new CliInputError(`Unknown category "${categoryQuery}". Expected one of: ${knownCategoryList}.`);
17309
+ if (!seenCategories.has(matchedCategory)) {
17310
+ seenCategories.add(matchedCategory);
17311
+ resolvedCategories.push(matchedCategory);
17312
+ }
17313
+ }
17314
+ if (rawCategoryValues.length > 0 && resolvedCategories.length === 0) throw new CliInputError(`--category requires one of: ${knownCategoryList}.`);
17315
+ return resolvedCategories.length > 0 ? resolvedCategories : void 0;
17316
+ };
17317
+ //#endregion
17318
+ //#region src/cli/utils/scan-result-cache.ts
17319
+ const CACHE_DISABLED_VALUES = new Set(["1", "true"]);
17320
+ const TOOLCHAIN_PACKAGE_SPECIFIERS = [
17321
+ "oxlint",
17322
+ "oxlint/package.json",
17323
+ "oxlint-plugin-react-doctor",
17324
+ "deslop-js/package.json",
17325
+ "eslint-plugin-react-hooks/package.json"
17326
+ ];
17327
+ const bundledRequire = createRequire(import.meta.url);
17328
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17329
+ const normalizeForStableJson = (value) => {
17330
+ if (value === null) return null;
17331
+ if (value === void 0) return void 0;
17332
+ const valueType = typeof value;
17333
+ if (valueType === "string" || valueType === "number" || valueType === "boolean") return value;
17334
+ if (valueType === "bigint" || valueType === "function" || valueType === "symbol") throw new Error("Unsupported cache key value");
17335
+ if (Array.isArray(value)) return value.map((item) => {
17336
+ const normalized = normalizeForStableJson(item);
17337
+ return normalized === void 0 ? null : normalized;
17338
+ });
17339
+ const prototype = Object.getPrototypeOf(value);
17340
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("Unsupported cache key object");
17341
+ const record = value;
17342
+ const normalizedRecord = {};
17343
+ for (const key of Object.keys(record).sort()) {
17344
+ const normalized = normalizeForStableJson(record[key]);
17345
+ if (normalized !== void 0) normalizedRecord[key] = normalized;
17346
+ }
17347
+ return normalizedRecord;
17348
+ };
17349
+ const stringifyStableJson = (value) => {
17350
+ try {
17351
+ return JSON.stringify(normalizeForStableJson(value));
17352
+ } catch {
17353
+ return null;
17354
+ }
17355
+ };
17356
+ const hashString = (value) => crypto.createHash("sha1").update(value).digest("hex");
17357
+ const runGit$1 = (directory, args) => {
17358
+ try {
17359
+ return execFileSync("git", [...args], {
17360
+ cwd: directory,
17361
+ encoding: "utf8",
17362
+ stdio: [
17363
+ "ignore",
17364
+ "pipe",
17365
+ "ignore"
17366
+ ]
17367
+ }).trim();
17368
+ } catch {
17369
+ return null;
17370
+ }
17371
+ };
17372
+ const readHeadSha = (projectDirectory) => runGit$1(projectDirectory, ["rev-parse", "HEAD"]);
17373
+ const isWorktreeClean = (projectDirectory) => {
17374
+ const status = runGit$1(projectDirectory, [
17375
+ "status",
17376
+ "--porcelain=v1",
17377
+ "--untracked-files=normal"
17378
+ ]);
17379
+ return status !== null && status.length === 0;
17380
+ };
17381
+ const hasHiddenTrackedFileState = (projectDirectory) => {
17382
+ const output = runGit$1(projectDirectory, ["ls-files", "-v"]);
17383
+ if (output === null) return true;
17384
+ return output.split("\n").some((line) => line.length > 0 && line[0] !== "H");
17385
+ };
17386
+ const resolveCacheFilePath = (projectDirectory) => {
17387
+ const nodeModulesDirectory = path.join(projectDirectory, "node_modules");
17388
+ if (fs.existsSync(nodeModulesDirectory)) return path.join(nodeModulesDirectory, ".cache", "react-doctor", "scan-cache.json");
17389
+ const projectHash = hashString(projectDirectory).slice(0, 16);
17390
+ return path.join(os.tmpdir(), "react-doctor-cache", `scan-${projectHash}.json`);
17391
+ };
17392
+ const readPersistedCache = (cacheFilePath) => {
17393
+ try {
17394
+ const parsed = JSON.parse(fs.readFileSync(cacheFilePath, "utf8"));
17395
+ if (!isRecord$1(parsed) || parsed.version !== 1) return {
17396
+ version: 1,
17397
+ entries: []
17398
+ };
17399
+ if (!Array.isArray(parsed.entries)) return {
17400
+ version: 1,
17401
+ entries: []
17402
+ };
17403
+ const entries = [];
17404
+ for (const entry of parsed.entries) {
17405
+ if (!isRecord$1(entry) || typeof entry.key !== "string" || typeof entry.createdAtMs !== "number") continue;
17406
+ if (!isRecord$1(entry.payload) || !Array.isArray(entry.payload.diagnostics)) continue;
17407
+ entries.push(entry);
17408
+ }
17409
+ return {
17410
+ version: 1,
17411
+ entries
17412
+ };
17413
+ } catch {
17414
+ return {
17415
+ version: 1,
17416
+ entries: []
17417
+ };
17418
+ }
17419
+ };
17420
+ const writePersistedCache = (cacheFilePath, cache) => {
17421
+ try {
17422
+ fs.mkdirSync(path.dirname(cacheFilePath), { recursive: true });
17423
+ const tempPath = `${cacheFilePath}.${process.pid}.tmp`;
17424
+ fs.writeFileSync(tempPath, JSON.stringify(cache));
17425
+ fs.renameSync(tempPath, cacheFilePath);
17426
+ } catch {
17427
+ return;
17428
+ }
17429
+ };
17430
+ const isScanResultCacheDisabled = () => CACHE_DISABLED_VALUES.has(process.env.REACT_DOCTOR_NO_CACHE?.toLowerCase() ?? "");
17431
+ const resolveProjectIdentity = (projectDirectory) => {
17432
+ try {
17433
+ return fs.realpathSync.native(projectDirectory);
17434
+ } catch {
17435
+ return path.resolve(projectDirectory);
17436
+ }
17437
+ };
17438
+ const fileFingerprint = (filePath) => {
17439
+ try {
17440
+ const stat = fs.statSync(filePath);
17441
+ return `${filePath}:${stat.mtimeMs}:${stat.size}`;
17442
+ } catch {
17443
+ return null;
17444
+ }
17445
+ };
17446
+ const resolveToolchainFingerprint = (nodeBinaryPath) => {
17447
+ const fingerprints = [];
17448
+ if (nodeBinaryPath !== null) {
17449
+ const fingerprint = fileFingerprint(nodeBinaryPath);
17450
+ if (fingerprint !== null) fingerprints.push(`node=${fingerprint}`);
17451
+ }
17452
+ for (const specifier of TOOLCHAIN_PACKAGE_SPECIFIERS) try {
17453
+ const fingerprint = fileFingerprint(bundledRequire.resolve(specifier));
17454
+ if (fingerprint !== null) fingerprints.push(`${specifier}=${fingerprint}`);
17455
+ } catch {
17456
+ continue;
17457
+ }
17458
+ return fingerprints;
17459
+ };
17460
+ const buildScanResultCacheKey = (input) => {
17461
+ if (isScanResultCacheDisabled()) return null;
17462
+ if (!isWorktreeClean(input.projectDirectory)) return null;
17463
+ if (hasHiddenTrackedFileState(input.projectDirectory)) return null;
17464
+ const headSha = readHeadSha(input.projectDirectory);
17465
+ if (headSha === null) return null;
17466
+ if (stringifyStableJson(input.userConfig) === null) return null;
17467
+ const cacheKeyJson = stringifyStableJson({
17468
+ schemaVersion: 1,
17469
+ projectIdentity: resolveProjectIdentity(input.projectDirectory),
17470
+ headSha,
17471
+ reactDoctorVersion: input.version,
17472
+ nodeVersion: process.version,
17473
+ toolchainFingerprint: resolveToolchainFingerprint(input.nodeBinaryPath),
17474
+ configFingerprint: computeConfigFingerprint(input.projectDirectory, input.version),
17475
+ hasConfigOverride: input.hasConfigOverride,
17476
+ configSourceDirectory: input.configSourceDirectory,
17477
+ userConfig: input.userConfig,
17478
+ engineOptions: {
17479
+ lint: input.options.lint,
17480
+ deadCode: input.options.deadCode,
17481
+ includePaths: [...input.options.includePaths].sort(),
17482
+ customRulesOnly: input.options.customRulesOnly,
17483
+ respectInlineDisables: input.options.respectInlineDisables,
17484
+ warnings: input.options.warnings,
17485
+ adoptExistingLintConfig: input.options.adoptExistingLintConfig,
17486
+ ignoredTags: [...input.options.ignoredTags].sort(),
17487
+ concurrency: input.options.concurrency,
17488
+ baselineRef: input.options.baseline?.ref,
17489
+ noScore: input.options.noScore,
17490
+ isCi: input.options.isCi,
17491
+ suppressRendering: input.options.suppressRendering
17492
+ }
17493
+ });
17494
+ return cacheKeyJson === null ? null : hashString(cacheKeyJson);
17495
+ };
17496
+ const createScanResultCache = (projectDirectory) => {
17497
+ const cacheFilePath = resolveCacheFilePath(projectDirectory);
17498
+ const persistedCache = readPersistedCache(cacheFilePath);
17499
+ const entries = /* @__PURE__ */ new Map();
17500
+ for (const entry of persistedCache.entries) entries.set(entry.key, entry);
17501
+ const persist = () => {
17502
+ writePersistedCache(cacheFilePath, {
17503
+ version: 1,
17504
+ entries: [...entries.values()].sort((firstEntry, secondEntry) => secondEntry.createdAtMs - firstEntry.createdAtMs).slice(0, 20)
17505
+ });
17506
+ };
17507
+ return {
17508
+ lookup: (key) => entries.get(key)?.payload ?? null,
17509
+ store: (key, payload) => {
17510
+ entries.set(key, {
17511
+ key,
17512
+ createdAtMs: Date.now(),
17513
+ payload
17514
+ });
17515
+ persist();
17516
+ }
17517
+ };
17518
+ };
17519
+ const shouldStoreScanPayload = (payload) => !payload.didLintFail && !payload.didDeadCodeFail && payload.lintPartialFailures.length === 0;
17520
+ //#endregion
17209
17521
  //#region src/inspect.ts
17210
17522
  const silentConsole = makeNoopConsole();
17211
17523
  const runConsole = (effect) => {
17212
17524
  Effect.runSync(effect);
17213
17525
  };
17526
+ const recordOnboardingCompletion = (options) => {
17527
+ const forceOnboarding = isOnboardingForced();
17528
+ if (shouldRecordOnboarding({
17529
+ paceOnboardingSections: !options.silent && !options.scoreOnly && !options.suppressRendering && !options.verbose && canAnimateOnboarding(process.stdout) && (forceOnboarding || !hasCompletedOnboarding()),
17530
+ forceOnboarding,
17531
+ verbose: options.verbose,
17532
+ isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
17533
+ })) markOnboardingComplete();
17534
+ };
17535
+ const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
17214
17536
  const buildIgnoredTags = (userConfig) => {
17215
17537
  const tags = /* @__PURE__ */ new Set();
17216
17538
  if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
@@ -17231,6 +17553,7 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
17231
17553
  share: userConfig?.share ?? true,
17232
17554
  respectInlineDisables: inputOptions.respectInlineDisables ?? userConfig?.respectInlineDisables ?? true,
17233
17555
  warnings: inputOptions.warnings ?? userConfig?.warnings ?? true,
17556
+ categoryFilters: new Set(resolveCliCategories(inputOptions.categoryFilters) ?? []),
17234
17557
  adoptExistingLintConfig: userConfig?.adoptExistingLintConfig ?? true,
17235
17558
  ignoredTags: buildIgnoredTags(userConfig),
17236
17559
  outputSurface: inputOptions.outputSurface ?? "cli",
@@ -17317,6 +17640,7 @@ const runBaselineComparison = async (params) => {
17317
17640
  hasConfigOverride: true,
17318
17641
  userConfig: params.userConfig,
17319
17642
  configSourceDirectory: null,
17643
+ projectInfoOverride: params.headProjectInfo,
17320
17644
  shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
17321
17645
  shouldRunDeadCode: false,
17322
17646
  shouldComputeScore: false,
@@ -17363,6 +17687,40 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17363
17687
  const isDiffMode = options.includePaths.length > 0;
17364
17688
  const resolvedNodeBinaryPath = await resolveOxlintNode(options.lint, options.scoreOnly || options.silent);
17365
17689
  const lintBindingMissing = options.lint && !resolvedNodeBinaryPath;
17690
+ const cacheKey = buildScanResultCacheKey({
17691
+ projectDirectory: directory,
17692
+ version: VERSION,
17693
+ nodeBinaryPath: resolvedNodeBinaryPath,
17694
+ options,
17695
+ userConfig,
17696
+ hasConfigOverride,
17697
+ configSourceDirectory
17698
+ });
17699
+ const scanResultCache = cacheKey === null ? null : createScanResultCache(directory);
17700
+ const cachedPayload = cacheKey === null ? null : scanResultCache?.lookup(cacheKey) ?? null;
17701
+ if (cachedPayload) {
17702
+ recordSentryProjectContext(cachedPayload.project, rootSentrySpan);
17703
+ recordCount(METRIC.projectDetected, 1);
17704
+ await renderCachedProjectDetection({
17705
+ payload: cachedPayload,
17706
+ options,
17707
+ userConfig,
17708
+ isDiffMode
17709
+ });
17710
+ const baselineDegraded = Boolean(options.baseline) && isDiffMode && cachedPayload.baselineDelta === void 0;
17711
+ const result = await renderAndRecordScan({
17712
+ payload: cachedPayload,
17713
+ options,
17714
+ userConfig,
17715
+ hasCustomConfig: userConfig !== null,
17716
+ startTime,
17717
+ rootSentrySpan,
17718
+ scanMode: cachedPayload.baselineDelta ? "baseline" : isDiffMode ? "diff" : "full",
17719
+ baselineDegraded
17720
+ });
17721
+ recordOnboardingCompletion(options);
17722
+ return result;
17723
+ }
17366
17724
  const shouldShowProgressSpinners = !options.isCiOrCodingAgentEnvironment && !options.silent && !options.scoreOnly && options.lint && Boolean(resolvedNodeBinaryPath);
17367
17725
  const layers = buildRuntimeLayers({
17368
17726
  directory,
@@ -17416,6 +17774,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17416
17774
  directory,
17417
17775
  options,
17418
17776
  userConfig,
17777
+ headProjectInfo: output.project,
17419
17778
  headDiagnostics: output.diagnostics,
17420
17779
  resolvedNodeBinaryPath,
17421
17780
  baselineRef: options.baseline.ref
@@ -17427,12 +17786,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17427
17786
  }
17428
17787
  const baselineDegraded = Boolean(options.baseline) && isDiffMode && baselineDelta === void 0;
17429
17788
  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,
17789
+ const payload = {
17436
17790
  diagnostics: inspectDiagnostics,
17437
17791
  score,
17438
17792
  project: output.project,
@@ -17446,39 +17800,77 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17446
17800
  scannedFileCount: output.scannedFileCount,
17447
17801
  scannedFilePaths: output.scannedFilePaths,
17448
17802
  scanElapsedMilliseconds: output.scanElapsedMilliseconds,
17449
- baselineDelta
17803
+ baselineDelta,
17804
+ lintFailureReasonKind: lintBindingMissing ? "native-binding-missing" : output.lintFailureReasonKind
17450
17805
  };
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";
17806
+ if (cacheKey !== null && scanResultCache !== null && shouldStoreScanPayload(payload)) scanResultCache.store(cacheKey, payload);
17807
+ const result = await renderAndRecordScan({
17808
+ payload,
17809
+ options,
17810
+ userConfig,
17811
+ hasCustomConfig: userConfig !== null,
17812
+ startTime,
17813
+ rootSentrySpan,
17814
+ scanMode: baselineDelta ? "baseline" : isDiffMode ? "diff" : "full",
17815
+ baselineDegraded
17816
+ });
17817
+ recordOnboardingCompletion(options);
17818
+ return result;
17819
+ };
17820
+ const runMaybeSilent = (effect, silent) => silent ? effect.pipe(Effect.provideService(Console.Console, silentConsole)) : effect;
17821
+ const renderCachedProjectDetection = async (input) => {
17822
+ if (input.options.scoreOnly || input.options.suppressRendering) return;
17823
+ await Effect.runPromise(runMaybeSilent(printProjectDetection({
17824
+ projectInfo: input.payload.project,
17825
+ userConfig: input.userConfig,
17826
+ isDiffMode: input.isDiffMode,
17827
+ includePaths: input.options.includePaths,
17828
+ lintSourceFileCount: input.payload.scannedFileCount
17829
+ }), input.options.silent));
17830
+ };
17831
+ const renderAndRecordScan = async (input) => {
17832
+ const finalizeInput = {
17833
+ options: input.options,
17834
+ elapsedMilliseconds: performance.now() - input.startTime,
17835
+ diagnostics: input.payload.diagnostics,
17836
+ score: input.payload.score,
17837
+ project: input.payload.project,
17838
+ userConfig: input.payload.userConfig,
17839
+ didLintFail: input.payload.didLintFail,
17840
+ lintFailureReason: input.payload.lintFailureReason,
17841
+ lintPartialFailures: input.payload.lintPartialFailures,
17842
+ didDeadCodeFail: input.payload.didDeadCodeFail,
17843
+ deadCodeFailureReason: input.payload.deadCodeFailureReason,
17844
+ directory: input.payload.directory,
17845
+ scannedFileCount: input.payload.scannedFileCount,
17846
+ scannedFilePaths: input.payload.scannedFilePaths,
17847
+ scanElapsedMilliseconds: input.payload.scanElapsedMilliseconds,
17848
+ baselineDelta: input.payload.baselineDelta
17849
+ };
17850
+ const result = await Effect.runPromise(runMaybeSilent(finalizeAndRender(finalizeInput), input.options.silent));
17459
17851
  recordScanMetrics({
17460
17852
  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
17853
+ mode: input.scanMode,
17854
+ baselineDegraded: input.baselineDegraded,
17855
+ parallel: input.options.concurrency !== void 0,
17856
+ workerCount: input.options.concurrency,
17857
+ lint: input.options.lint,
17858
+ deadCode: input.options.deadCode,
17859
+ scoreOnly: input.options.scoreOnly,
17860
+ noScore: input.options.noScore,
17861
+ didLintFail: input.payload.didLintFail,
17862
+ lintFailureReasonKind: input.payload.lintFailureReasonKind,
17863
+ didDeadCodeFail: input.payload.didDeadCodeFail
17472
17864
  });
17473
- recordRunEvent(rootSentrySpan, {
17474
- ...buildRunEventConfig(options, userConfig, userConfig !== null),
17865
+ recordRunEvent(input.rootSentrySpan, {
17866
+ ...buildRunEventConfig(input.options, input.userConfig, input.hasCustomConfig),
17475
17867
  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
17868
+ mode: input.scanMode,
17869
+ gateExempt: input.baselineDegraded,
17870
+ didLintFail: input.payload.didLintFail,
17871
+ lintFailureReasonKind: input.payload.lintFailureReasonKind,
17872
+ lintPartialFailureCount: input.payload.lintPartialFailures.length,
17873
+ didDeadCodeFail: input.payload.didDeadCodeFail
17482
17874
  });
17483
17875
  return result;
17484
17876
  };
@@ -17514,14 +17906,16 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17514
17906
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
17515
17907
  const pause = onboardingSectionPause(animateRender);
17516
17908
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
17909
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
17517
17910
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
17518
17911
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
17519
- if (surfaceDiagnostics.length === 0) {
17912
+ if (printedDiagnostics.length === 0) {
17520
17913
  yield* pause;
17521
17914
  if (hasSkippedChecks) {
17522
17915
  const skippedLabel = skippedChecks.join(" and ");
17523
17916
  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.)`));
17917
+ } else if (options.categoryFilters.size > 0) yield* Console.log(highlighter.success(`No issues found in category ${formatCategorySelection(options.categoryFilters)}!`));
17918
+ else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17525
17919
  else yield* Console.log(highlighter.success("No issues found!"));
17526
17920
  yield* Console.log("");
17527
17921
  yield* pause;
@@ -17534,20 +17928,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17534
17928
  }
17535
17929
  yield* pause;
17536
17930
  yield* Console.log("");
17537
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17931
+ yield* printDiagnostics([...printedDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17538
17932
  sectionPause: pause,
17539
17933
  animateCountUp: animateRender
17540
17934
  });
17541
17935
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
17542
- if (demotedDiagnosticCount > 0) {
17936
+ if (options.categoryFilters.size === 0 && demotedDiagnosticCount > 0) {
17543
17937
  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
17938
  yield* Console.log("");
17545
17939
  }
17546
- const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
17940
+ const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...printedDiagnostics], [...surfaceDiagnostics], score)) : null;
17547
17941
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
17548
17942
  yield* pause;
17549
17943
  yield* printSummary({
17550
- diagnostics: [...surfaceDiagnostics],
17944
+ diagnostics: [...printedDiagnostics],
17551
17945
  elapsedMilliseconds,
17552
17946
  scoreResult: score,
17553
17947
  potentialScore,
@@ -17563,7 +17957,7 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17563
17957
  }
17564
17958
  yield* pause;
17565
17959
  yield* printFooter({
17566
- diagnostics: [...surfaceDiagnostics],
17960
+ diagnostics: [...printedDiagnostics],
17567
17961
  scoreResult: score,
17568
17962
  projectName: project.projectName,
17569
17963
  isOffline: !shouldShowShareLink
@@ -17694,21 +18088,6 @@ const handleUserError = (error, options = {}) => {
17694
18088
  process.exitCode = 1;
17695
18089
  };
17696
18090
  //#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
18091
  //#region src/cli/utils/is-expected-user-error.ts
17713
18092
  /**
17714
18093
  * Whether `error` is an expected, user-actionable failure — the user's project
@@ -17980,190 +18359,24 @@ const installDoctorScript = (options) => {
17980
18359
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17981
18360
  };
17982
18361
  };
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];
18362
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18363
+ const scriptName = scriptResult.scriptName ?? "doctor";
18364
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18365
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18366
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18367
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18368
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18369
+ return "Skipped package script: package.json missing or invalid.";
18029
18370
  };
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
- };
18371
+ const installReactDoctorScriptStep = (projectRoot) => {
18372
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18373
+ try {
18374
+ const scriptResult = installDoctorScript({ projectRoot });
18375
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18376
+ } catch (error) {
18377
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18378
+ throw error;
18379
+ }
18167
18380
  };
18168
18381
  //#endregion
18169
18382
  //#region src/cli/utils/install-github-workflow.ts
@@ -18176,37 +18389,20 @@ const buildWorkflowContent = () => `# React Doctor — finds security, performan
18176
18389
  name: React Doctor
18177
18390
 
18178
18391
  on:
18392
+ # 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
18393
  pull_request:
18180
18394
  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.
18395
+ # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
18186
18396
  push:
18187
18397
  branches: [main]
18188
18398
 
18189
18399
  permissions:
18190
- # \`actions/checkout\` needs this to read the repo source.
18191
18400
  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
18401
  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
18402
  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
18403
  statuses: write
18207
18404
 
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.
18405
+ # 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
18406
  concurrency:
18211
18407
  group: react-doctor-\${{ github.event.pull_request.number || github.ref }}
18212
18408
  cancel-in-progress: true
@@ -18273,1074 +18469,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18273
18469
  };
18274
18470
  }
18275
18471
  };
18472
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18473
+ const workflow = readReactDoctorWorkflow(projectRoot);
18474
+ if (!workflow) return {
18475
+ status: "not-needed",
18476
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18477
+ };
18478
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18479
+ if (!changed) return {
18480
+ status: "not-needed",
18481
+ workflowPath: workflow.workflowPath
18482
+ };
18483
+ try {
18484
+ fs$1.writeFileSync(workflow.workflowPath, content);
18485
+ return {
18486
+ status: "upgraded",
18487
+ workflowPath: workflow.workflowPath
18488
+ };
18489
+ } catch {
18490
+ return {
18491
+ status: "failed",
18492
+ workflowPath: workflow.workflowPath
18493
+ };
18494
+ }
18495
+ };
18276
18496
  //#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;
18497
+ //#region src/cli/utils/hash-project-root.ts
18498
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18499
+ //#endregion
18500
+ //#region src/cli/utils/action-upgrade-prompt.ts
18501
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18502
+ const getActionUpgradeStore = (options = {}) => new Conf({
18503
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18504
+ cwd: options.cwd
18505
+ });
18506
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18507
+ try {
18508
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18509
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18510
+ } catch {
18511
+ return true;
18282
18512
  }
18283
- if (result.status === "exists") {
18284
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18513
+ };
18514
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18515
+ try {
18516
+ const store = getActionUpgradeStore(storeOptions);
18517
+ const upgrades = store.get("actionUpgrades", {});
18518
+ store.set("actionUpgrades", {
18519
+ ...upgrades,
18520
+ [hashProjectRoot(projectRoot)]: {
18521
+ rootDirectory: path$1.resolve(projectRoot),
18522
+ outcome,
18523
+ at: (/* @__PURE__ */ new Date()).toISOString()
18524
+ }
18525
+ });
18526
+ return true;
18527
+ } catch {
18285
18528
  return false;
18286
18529
  }
18287
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18288
- recordCount(METRIC.installWorkflow, 1);
18289
- return true;
18290
18530
  };
18291
18531
  //#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,
18532
+ //#region src/cli/utils/open-url.ts
18533
+ const resolveOpenCommand = (url) => {
18534
+ if (process$1.platform === "darwin") return {
18535
+ command: "open",
18536
+ args: [url]
18537
+ };
18538
+ if (process$1.platform === "win32") return {
18539
+ command: "cmd",
18540
+ args: [
18541
+ "/c",
18542
+ "start",
18345
18543
  "",
18346
- hookBlock.trimEnd(),
18347
- ...remainingLines
18348
- ].join("\n");
18349
- }
18350
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18544
+ url
18545
+ ]
18546
+ };
18547
+ return {
18548
+ command: "xdg-open",
18549
+ args: [url]
18550
+ };
18351
18551
  };
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 {}
18552
+ const openUrl = (url) => {
18553
+ try {
18554
+ const { command, args } = resolveOpenCommand(url);
18555
+ const child = spawn(command, args, {
18556
+ detached: true,
18557
+ stdio: "ignore"
18558
+ });
18559
+ child.on("error", () => {});
18560
+ child.unref();
18561
+ return true;
18562
+ } catch {
18563
+ return false;
18564
+ }
18358
18565
  };
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
- };
18566
+ //#endregion
18567
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18568
+ const CI_YES_CHOICE = "ci-yes";
18569
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18570
+ const CI_NO_CHOICE = "ci-no";
18571
+ const SGR_BOLD_OFF = "\x1B[22m";
18572
+ const ciQuestionMessage = [
18573
+ "Add React Doctor to GitHub Actions?",
18574
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18575
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18576
+ ].join("\n");
18577
+ const askAddToGitHubActions = async (prompt = prompts) => {
18578
+ while (true) {
18579
+ const { ciChoice } = await prompt({
18580
+ type: "select",
18581
+ name: "ciChoice",
18582
+ message: ciQuestionMessage,
18583
+ hint: " ",
18584
+ choices: [
18585
+ {
18586
+ title: "Yes",
18587
+ description: "Adds the workflow file and a doctor package script",
18588
+ value: CI_YES_CHOICE
18589
+ },
18590
+ {
18591
+ title: "Learn more",
18592
+ description: "Opens the docs page in your browser",
18593
+ value: CI_LEARN_MORE_CHOICE
18594
+ },
18595
+ {
18596
+ title: "No",
18597
+ description: "Skip for now",
18598
+ value: CI_NO_CHOICE
18599
+ }
18600
+ ],
18601
+ initial: 0
18602
+ }, { onCancel: () => true });
18603
+ if (ciChoice === void 0) return "cancel";
18604
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18605
+ if (ciChoice === CI_NO_CHOICE) return "no";
18606
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18607
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18608
+ cliLogger.break();
18609
+ }
18376
18610
  };
18377
18611
  //#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");
18612
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18613
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18614
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18615
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18616
+ const { upgradeChoice } = await prompt({
18617
+ type: "select",
18618
+ name: "upgradeChoice",
18619
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18620
+ hint: " ",
18621
+ choices: [{
18622
+ title: "Yes (recommended)",
18623
+ description: "Bump the workflow to millionco/react-doctor@v2",
18624
+ value: UPGRADE_YES_CHOICE
18625
+ }, {
18626
+ title: "No, thanks",
18627
+ description: "Keep @v1 — won't ask again for this repo",
18628
+ value: UPGRADE_NO_CHOICE
18629
+ }],
18630
+ initial: 0
18631
+ }, { onCancel: () => true });
18632
+ if (upgradeChoice === void 0) return "cancel";
18633
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18382
18634
  };
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];
18635
+ //#endregion
18636
+ //#region src/cli/utils/open-workflow-pull-request.ts
18637
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18638
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18639
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18640
+ 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.
18641
+
18642
+ Docs: https://www.react.doctor/ci`;
18643
+ const execFileAsync$1 = promisify(execFile);
18644
+ const run = async (command, args, cwd) => {
18645
+ try {
18646
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18647
+ cwd,
18648
+ encoding: "utf8"
18649
+ });
18650
+ return {
18651
+ success: true,
18652
+ stdout: stdout.trim(),
18653
+ stderr: stderr.trim()
18654
+ };
18655
+ } catch (error) {
18656
+ const failure = error;
18657
+ return {
18658
+ success: false,
18659
+ stdout: (failure.stdout ?? "").trim(),
18660
+ stderr: (failure.stderr ?? "").trim()
18661
+ };
18662
+ }
18386
18663
  };
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;
18664
+ const detectDefaultBranch = async (cwd) => {
18665
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18666
+ if (symRef.success) {
18667
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18668
+ if (branchMatch) return branchMatch[1];
18400
18669
  }
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
- };
18670
+ if ((await run("git", [
18671
+ "rev-parse",
18672
+ "--verify",
18673
+ "origin/main"
18674
+ ], cwd)).success) return "main";
18675
+ if ((await run("git", [
18676
+ "rev-parse",
18677
+ "--verify",
18678
+ "origin/master"
18679
+ ], cwd)).success) return "master";
18680
+ return null;
18409
18681
  };
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"));
18682
+ const findUniqueBranchName = async (cwd) => {
18683
+ if (!(await run("git", [
18684
+ "rev-parse",
18685
+ "--verify",
18686
+ NEW_BRANCH_PREFIX
18687
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18688
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18467
18689
  };
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
18690
+ const openWorkflowPullRequest = async (params) => {
18691
+ const workflowPath = path$1.resolve(params.workflowPath);
18692
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18693
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18694
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18695
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18696
+ if (!repoRootProbe.success) return {
18697
+ status: "not-attempted",
18698
+ reason: "not-a-git-repo"
18478
18699
  };
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"
18700
+ const cwd = repoRootProbe.stdout;
18701
+ if (!isCommandAvailable("gh")) return {
18702
+ status: "not-attempted",
18703
+ reason: "gh-not-installed"
18625
18704
  };
18626
- if (isOvercommitProject(topLevel)) return {
18627
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18628
- runnerRoot: topLevel,
18629
- kind: "overcommit"
18705
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18706
+ status: "not-attempted",
18707
+ reason: "gh-not-authenticated"
18630
18708
  };
18631
- if (isYorkieProject(topLevel)) return {
18632
- hookPath: getPackageJsonPath(topLevel),
18633
- runnerRoot: topLevel,
18634
- kind: "yorkie"
18709
+ const defaultBranch = await detectDefaultBranch(cwd);
18710
+ if (!defaultBranch) return {
18711
+ status: "not-attempted",
18712
+ reason: "no-default-branch"
18635
18713
  };
18636
- if (isGhooksProject(topLevel)) return {
18637
- hookPath: getPackageJsonPath(topLevel),
18638
- runnerRoot: topLevel,
18639
- kind: "ghooks"
18714
+ const previousBranchProbe = await run("git", [
18715
+ "rev-parse",
18716
+ "--abbrev-ref",
18717
+ "HEAD"
18718
+ ], cwd);
18719
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18720
+ status: "not-attempted",
18721
+ reason: "detached-head"
18640
18722
  };
18641
- if (isGitHooksJsProject(topLevel)) return {
18642
- hookPath: getPackageJsonPath(topLevel),
18643
- runnerRoot: topLevel,
18644
- kind: "git-hooks-js"
18723
+ const previousBranch = previousBranchProbe.stdout;
18724
+ await run("git", [
18725
+ "fetch",
18726
+ "origin",
18727
+ defaultBranch
18728
+ ], cwd);
18729
+ const newBranch = await findUniqueBranchName(cwd);
18730
+ if (!(await run("git", [
18731
+ "checkout",
18732
+ "-b",
18733
+ newBranch,
18734
+ `origin/${defaultBranch}`
18735
+ ], cwd)).success) return {
18736
+ status: "not-attempted",
18737
+ reason: "checkout-failed"
18645
18738
  };
18646
- if (isPreCommitNpmProject(topLevel)) return {
18647
- hookPath: getPackageJsonPath(topLevel),
18648
- runnerRoot: topLevel,
18649
- kind: "pre-commit-npm"
18739
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18740
+ await run("git", ["checkout", previousBranch], cwd);
18741
+ if (deleteNewBranch) await run("git", [
18742
+ "branch",
18743
+ "-D",
18744
+ newBranch
18745
+ ], cwd);
18650
18746
  };
18651
- if (isPrettyQuickProject(topLevel)) return {
18652
- hookPath: getPackageJsonPath(topLevel),
18653
- runnerRoot: topLevel,
18654
- kind: "pretty-quick"
18747
+ if (!(await run("git", [
18748
+ "add",
18749
+ "--",
18750
+ path$1.relative(cwd, workflowPath)
18751
+ ], cwd)).success) {
18752
+ await restoreToPreviousBranch(true);
18753
+ return {
18754
+ status: "not-attempted",
18755
+ reason: "git-add-failed"
18756
+ };
18757
+ }
18758
+ if (!(await run("git", [
18759
+ "commit",
18760
+ "-m",
18761
+ commitMessage
18762
+ ], cwd)).success) {
18763
+ await restoreToPreviousBranch(true);
18764
+ return {
18765
+ status: "not-attempted",
18766
+ reason: "git-commit-failed"
18767
+ };
18768
+ }
18769
+ if (!(await run("git", [
18770
+ "push",
18771
+ "-u",
18772
+ "origin",
18773
+ newBranch
18774
+ ], cwd)).success) {
18775
+ await restoreToPreviousBranch(true);
18776
+ return {
18777
+ status: "not-attempted",
18778
+ reason: "git-push-failed"
18779
+ };
18780
+ }
18781
+ const prCreate = await run("gh", [
18782
+ "pr",
18783
+ "create",
18784
+ "--title",
18785
+ prTitle,
18786
+ "--body",
18787
+ prBody,
18788
+ "--base",
18789
+ defaultBranch,
18790
+ "--head",
18791
+ newBranch
18792
+ ], cwd);
18793
+ await restoreToPreviousBranch(false);
18794
+ if (!prCreate.success) return {
18795
+ status: "branch-pushed",
18796
+ branch: newBranch
18655
18797
  };
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
18798
  return {
18663
- hookPath: resolveGitPath(projectRoot, hookPath),
18664
- runnerRoot: topLevel,
18665
- kind: "git"
18799
+ status: "pr-opened",
18800
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18666
18801
  };
18667
18802
  };
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);
18803
+ const stageWorkflowFile = async (params) => {
18804
+ const workflowPath = path$1.resolve(params.workflowPath);
18805
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18806
+ if (!repoRootProbe.success) return false;
18807
+ return (await run("git", [
18808
+ "add",
18809
+ "--",
18810
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18811
+ ], repoRootProbe.stdout)).success;
18679
18812
  };
18680
18813
  //#endregion
18681
- //#region src/cli/utils/should-skip-prompts.ts
18682
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18814
+ //#region src/cli/utils/report-workflow-result.ts
18815
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18816
+ if (result.status === "failed") {
18817
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18818
+ return false;
18819
+ }
18820
+ if (result.status === "exists") {
18821
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18822
+ return false;
18823
+ }
18824
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18825
+ recordCount(METRIC.installWorkflow, 1);
18826
+ return true;
18827
+ };
18683
18828
  //#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"
18829
+ //#region src/cli/utils/set-up-github-actions.ts
18830
+ const setUpGitHubActions = async (options) => {
18831
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18832
+ try {
18833
+ installReactDoctorScriptStep(projectRoot);
18834
+ } catch {}
18835
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18836
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18837
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18838
+ cliLogger.break();
18839
+ if (workflowResult.status === "failed") {
18840
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18841
+ return false;
18720
18842
  }
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;
18843
+ if (workflowResult.status === "created") {
18844
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18845
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18846
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18847
+ 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}`);
18848
+ else {
18849
+ pullRequestSpinner.stop();
18850
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18851
+ 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.");
18852
+ }
18853
+ }
18854
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18855
+ return didCreateWorkflow;
18856
+ };
18857
+ //#endregion
18858
+ //#region src/cli/utils/install-agent-hooks.ts
18859
+ const CLAUDE_AGENT = "claude-code";
18860
+ const CURSOR_AGENT = "cursor";
18861
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18862
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18863
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18864
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18865
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18866
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18867
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18868
+ const JSON_INDENT_SPACES$1 = 2;
18869
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18870
+ const readJsonFile = (filePath, fallback) => {
18871
+ if (!fs$1.existsSync(filePath)) return fallback;
18872
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18873
+ if (content.length === 0) return fallback;
18874
+ return JSON.parse(content);
18875
+ };
18876
+ const writeJsonFile = (filePath, value) => {
18877
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18878
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18879
+ };
18880
+ const writeHookScript = (filePath) => {
18881
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18882
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18883
+ fs$1.chmodSync(filePath, 493);
18884
+ };
18885
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18886
+ const installClaudeHook = (projectRoot) => {
18887
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18888
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18889
+ const settings = readJsonFile(settingsPath, {});
18890
+ const hooks = { ...settings.hooks ?? {} };
18891
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18892
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18893
+ type: "command",
18894
+ command: CLAUDE_HOOK_COMMAND
18895
+ }] });
18896
+ hooks.PostToolBatch = postToolBatchHooks;
18897
+ writeJsonFile(settingsPath, {
18898
+ ...settings,
18899
+ hooks
18900
+ });
18901
+ writeHookScript(hookPath);
18902
+ return [settingsPath, hookPath];
18903
+ };
18904
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18905
+ const installCursorHook = (projectRoot) => {
18906
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18907
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18908
+ const config = readJsonFile(configPath, {});
18909
+ const hooks = { ...config.hooks ?? {} };
18910
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18911
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18912
+ command: CURSOR_HOOK_RELATIVE_PATH,
18913
+ matcher: CURSOR_HOOK_MATCHER,
18914
+ timeout: 120
18915
+ });
18916
+ hooks.postToolUse = postToolUseHooks;
18917
+ writeJsonFile(configPath, {
18918
+ ...config,
18919
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18920
+ hooks
18921
+ });
18922
+ writeHookScript(hookPath);
18923
+ return [configPath, hookPath];
18924
+ };
18925
+ const buildAgentHookScript = () => [
18926
+ "#!/bin/sh",
18927
+ "set -u",
18928
+ "",
18929
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18930
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18931
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18932
+ "cat > \"$input_file\"",
18933
+ "",
18934
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18935
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18936
+ "if [ -z \"$project_root\" ]; then",
18937
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18938
+ "fi",
18939
+ "if ! cd \"$project_root\"; then",
18940
+ " exit 0",
18941
+ "fi",
18942
+ "",
18943
+ "should_scan() {",
18944
+ " if ! command -v node >/dev/null 2>&1; then",
18945
+ " return 0",
18946
+ " fi",
18947
+ "",
18948
+ " node - \"$input_file\" <<'NODE'",
18949
+ "const fs = require('node:fs');",
18950
+ "const inputPath = process.argv[2];",
18951
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18952
+ "try {",
18953
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18954
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18955
+ " if (eventName === 'PostToolBatch') {",
18956
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18957
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18958
+ " }",
18959
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18960
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18961
+ "} catch {",
18962
+ " process.exit(0);",
18963
+ "}",
18964
+ "NODE",
18965
+ "}",
18966
+ "",
18967
+ "run_react_doctor() {",
18968
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18969
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18970
+ " return",
18971
+ " fi",
18972
+ "",
18973
+ " if command -v react-doctor >/dev/null 2>&1; then",
18974
+ " react-doctor --verbose --diff --blocking warning --no-score",
18975
+ " return",
18976
+ " fi",
18977
+ "",
18978
+ " if command -v pnpm >/dev/null 2>&1; then",
18979
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18980
+ " return",
18981
+ " fi",
18982
+ "",
18983
+ " if command -v npx >/dev/null 2>&1; then",
18984
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18985
+ " return",
18986
+ " fi",
18987
+ "",
18988
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18989
+ " return 0",
18990
+ "}",
18991
+ "",
18992
+ "if ! should_scan; then",
18993
+ " exit 0",
18994
+ "fi",
18995
+ "",
18996
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18997
+ " exit 0",
18998
+ "fi",
18999
+ "",
19000
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
19001
+ "const fs = require('node:fs');",
19002
+ "const inputPath = process.argv[2];",
19003
+ "const outputPath = process.argv[3];",
19004
+ "const readInput = () => {",
19005
+ " try {",
19006
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
19007
+ " } catch {",
19008
+ " return {};",
19009
+ " }",
19010
+ "};",
19011
+ "const input = readInput();",
19012
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
19013
+ "if (!scanOutput) process.exit(0);",
19014
+ "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}`;",
19015
+ "if (input.hook_event_name === 'PostToolBatch') {",
19016
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
19017
+ "} else {",
19018
+ " console.log(JSON.stringify({ additional_context: message }));",
19019
+ "}",
19020
+ "NODE",
19021
+ ""
19022
+ ].join("\n");
19023
+ const installReactDoctorAgentHooks = (options) => {
19024
+ const installedAgents = [];
19025
+ const files = [];
19026
+ const requestedAgents = options.agents.filter(isSupportedAgent);
19027
+ for (const agent of requestedAgents) {
19028
+ if (agent === CLAUDE_AGENT) {
19029
+ files.push(...installClaudeHook(options.projectRoot));
19030
+ installedAgents.push(agent);
19031
+ }
19032
+ if (agent === CURSOR_AGENT) {
19033
+ files.push(...installCursorHook(options.projectRoot));
19034
+ installedAgents.push(agent);
19035
+ }
18729
19036
  }
19037
+ return {
19038
+ installedAgents,
19039
+ files
19040
+ };
18730
19041
  };
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;
19042
+ //#endregion
19043
+ //#region src/cli/utils/install-git-hook-file.ts
19044
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
19045
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
19046
+ 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?)`);
19047
+ const SHEBANG = "#!/bin/sh";
19048
+ const SHEBANG_PREFIX = "#!";
19049
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
19050
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
19051
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
19052
+ const buildReactDoctorHookBlock = () => [
19053
+ REACT_DOCTOR_BLOCK_START,
19054
+ "react_doctor_scan_staged_files() {",
19055
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
19056
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
19057
+ " return",
19058
+ " fi",
19059
+ "",
19060
+ " if command -v react-doctor >/dev/null 2>&1; then",
19061
+ ` ${REACT_DOCTOR_COMMAND}`,
19062
+ " return",
19063
+ " fi",
19064
+ "",
19065
+ " if command -v pnpm >/dev/null 2>&1; then",
19066
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
19067
+ " return",
19068
+ " fi",
19069
+ "",
19070
+ " if command -v npx >/dev/null 2>&1; then",
19071
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
19072
+ " return",
19073
+ " fi",
19074
+ "",
19075
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
19076
+ "}",
19077
+ "",
19078
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
19079
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
19080
+ " rm -f \"$react_doctor_output\"",
19081
+ "else",
19082
+ " rm -f \"$react_doctor_output\"",
19083
+ ` 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`,
19084
+ "fi",
19085
+ REACT_DOCTOR_BLOCK_END
19086
+ ].join("\n");
19087
+ const mergeHookContent = (existingContent) => {
19088
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
19089
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
19090
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
19091
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
19092
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
19093
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
19094
+ return [
19095
+ shebangLine,
19096
+ "",
19097
+ hookBlock.trimEnd(),
19098
+ ...remainingLines
19099
+ ].join("\n");
18742
19100
  }
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";
19101
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18745
19102
  };
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
- };
19103
+ const removeLegacyManagedRunner = (projectRoot) => {
19104
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
19105
+ fs$1.rmSync(runnerPath, { force: true });
19106
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
19107
+ fs$1.rmdirSync(directory);
19108
+ } catch {}
19109
+ };
19110
+ const installDirectGitHook = (options) => {
19111
+ const didHookExist = fs$1.existsSync(options.hookPath);
19112
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
19113
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
19114
+ "config",
19115
+ "core.hooksPath",
19116
+ options.hooksPathConfig
19117
+ ]);
19118
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19119
+ fs$1.writeFileSync(options.hookPath, nextContent);
19120
+ fs$1.chmodSync(options.hookPath, 493);
19121
+ removeLegacyManagedRunner(options.projectRoot);
18777
19122
  return {
18778
- command: "pnpm",
18779
- args: [
18780
- "add",
18781
- "--save-dev",
18782
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18783
- packageSpecifier
18784
- ],
18785
- cwd: projectRoot
19123
+ hookPath: options.hookPath,
19124
+ kind: options.kind ?? "git",
19125
+ status: didHookExist ? "updated" : "created"
18786
19126
  };
18787
19127
  };
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
- });
19128
+ //#endregion
19129
+ //#region src/cli/utils/install-git-hook-config-managers.ts
19130
+ const appendStringCommand = (existingCommand) => {
19131
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
19132
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18798
19133
  };
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);
19134
+ const appendArrayCommand = (existingCommands) => {
19135
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
19136
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18807
19137
  };
18808
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18809
- const installReactDoctorDependency = async (options) => {
19138
+ const installPackageJsonHook = (options, strategy) => {
19139
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
19140
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18810
19141
  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
- };
19142
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
19143
+ const parentKeys = strategy.path.slice(0, -1);
19144
+ const leafKey = strategy.path[strategy.path.length - 1];
19145
+ let parent = nextPackageJson;
19146
+ for (const key of parentKeys) {
19147
+ const existing = parent[key];
19148
+ const cloned = isRecord(existing) ? { ...existing } : {};
19149
+ parent[key] = cloned;
19150
+ parent = cloned;
18829
19151
  }
18830
- return { dependencyStatus: "created" };
19152
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
19153
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
19154
+ removeLegacyManagedRunner(options.projectRoot);
19155
+ return {
19156
+ hookPath: packageJsonPath,
19157
+ kind: strategy.kind,
19158
+ status: didHookExist ? "updated" : "created"
19159
+ };
18831
19160
  };
18832
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18833
- hookPath,
18834
- runnerRoot: projectRoot,
18835
- kind: "git"
19161
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
19162
+ kind: "simple-git-hooks",
19163
+ path: ["simple-git-hooks", "pre-commit"],
19164
+ leafShape: "string"
19165
+ });
19166
+ const installGhooks = (options) => installPackageJsonHook(options, {
19167
+ kind: "ghooks",
19168
+ path: [
19169
+ "config",
19170
+ "ghooks",
19171
+ "pre-commit"
19172
+ ],
19173
+ leafShape: "string"
19174
+ });
19175
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
19176
+ kind: "pre-commit-npm",
19177
+ path: ["pre-commit"],
19178
+ leafShape: "array"
19179
+ });
19180
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
19181
+ kind: "pretty-quick",
19182
+ path: ["gitHooks", "pre-commit"],
19183
+ leafShape: "string"
18836
19184
  });
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.";
19185
+ const installYorkie = (options) => installPackageJsonHook(options, {
19186
+ kind: "yorkie",
19187
+ path: ["gitHooks", "pre-commit"],
19188
+ leafShape: "string"
19189
+ });
19190
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
19191
+ kind: "git-hooks-js",
19192
+ path: ["git-hooks", "pre-commit"],
19193
+ leafShape: "string"
19194
+ });
19195
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
19196
+ const normalizedContent = ensureTrailingNewline(content);
19197
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
19198
+ if (match === null) return ensureTrailingNewline([
19199
+ normalizedContent.trimEnd(),
19200
+ "",
19201
+ `${sectionName}:`,
19202
+ ...block,
19203
+ ""
19204
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
19205
+ const sectionStartIndex = match.index;
19206
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
19207
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
19208
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
19209
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
19210
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
19211
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
19212
+ const suffix = normalizedContent.slice(insertIndex);
19213
+ return ensureTrailingNewline([
19214
+ prefix,
19215
+ ...block,
19216
+ suffix.trimStart()
19217
+ ].join("\n"));
18859
19218
  };
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`}`;
19219
+ const findTopLevelSectionRange = (content, sectionName) => {
19220
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
19221
+ if (match === null) return null;
19222
+ const headerLineEndIndex = content.indexOf("\n", match.index);
19223
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
19224
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
19225
+ nextSectionPattern.lastIndex = headerEndIndex;
19226
+ return {
19227
+ headerEndIndex,
19228
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
19229
+ };
18863
19230
  };
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
- }
19231
+ const appendLefthookCommand = (content) => {
19232
+ const normalizedContent = ensureTrailingNewline(content);
19233
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
19234
+ const reactDoctorCommandBlock = [
19235
+ " react-doctor:",
19236
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
19237
+ ""
19238
+ ];
19239
+ if (sectionRange === null) return ensureTrailingNewline([
19240
+ normalizedContent.trimEnd(),
19241
+ "",
19242
+ "pre-commit:",
19243
+ " commands:",
19244
+ ...reactDoctorCommandBlock
19245
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
19246
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
19247
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
19248
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
19249
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
19250
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18873
19251
  };
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;
19252
+ const installLefthook = (options) => {
19253
+ const didHookExist = fs$1.existsSync(options.hookPath);
19254
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19255
+ if (!existingContent.includes("react-doctor")) {
19256
+ const nextContent = appendLefthookCommand(existingContent);
19257
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19258
+ fs$1.writeFileSync(options.hookPath, nextContent);
18900
19259
  }
19260
+ removeLegacyManagedRunner(options.projectRoot);
19261
+ return {
19262
+ hookPath: options.hookPath,
19263
+ kind: "lefthook",
19264
+ status: didHookExist ? "updated" : "created"
19265
+ };
18901
19266
  };
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);
19267
+ const installPreCommit = (options) => {
19268
+ const didHookExist = fs$1.existsSync(options.hookPath);
19269
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19270
+ if (!existingContent.includes("id: react-doctor")) {
19271
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
19272
+ const localHookBlock = [
19273
+ " - repo: local",
19274
+ " hooks:",
19275
+ " - id: react-doctor",
19276
+ " name: react-doctor",
19277
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
19278
+ " language: system",
19279
+ " pass_filenames: false",
19280
+ ""
19281
+ ].join("\n");
19282
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
19283
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19284
+ fs$1.writeFileSync(options.hookPath, nextContent);
18926
19285
  }
18927
- return installedSkillNames;
19286
+ removeLegacyManagedRunner(options.projectRoot);
19287
+ return {
19288
+ hookPath: options.hookPath,
19289
+ kind: "pre-commit",
19290
+ status: didHookExist ? "updated" : "created"
19291
+ };
18928
19292
  };
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
- }
19293
+ const installOvercommit = (options) => {
19294
+ const didHookExist = fs$1.existsSync(options.hookPath);
19295
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
19296
+ if (!existingContent.includes("ReactDoctor")) {
19297
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
19298
+ " ReactDoctor:",
19299
+ " enabled: true",
19300
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
19301
+ ""
19302
+ ]);
19303
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
19304
+ fs$1.writeFileSync(options.hookPath, nextContent);
19054
19305
  }
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
- }
19306
+ removeLegacyManagedRunner(options.projectRoot);
19307
+ return {
19308
+ hookPath: options.hookPath,
19309
+ kind: "overcommit",
19310
+ status: didHookExist ? "updated" : "created"
19311
+ };
19312
+ };
19313
+ //#endregion
19314
+ //#region src/cli/utils/install-git-hook.ts
19315
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
19316
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
19317
+ const isSimpleGitHooksProject = (projectRoot) => {
19318
+ const packageJson = readPackageJson(projectRoot);
19319
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19320
+ };
19321
+ const getLefthookConfigPath = (projectRoot) => {
19322
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
19323
+ const filePath = path$1.join(projectRoot, fileName);
19324
+ if (fs$1.existsSync(filePath)) return filePath;
19071
19325
  }
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 });
19326
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19327
+ };
19328
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
19329
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
19330
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
19331
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
19332
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
19333
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
19334
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
19335
+ const detectGitHookTarget = (projectRoot) => {
19336
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
19337
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
19338
+ const configuredHooksPath = runGit(projectRoot, [
19339
+ "config",
19340
+ "--path",
19341
+ "--get",
19342
+ "core.hooksPath"
19343
+ ]);
19344
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
19345
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
19346
+ runnerRoot: topLevel,
19347
+ kind: "configured"
19348
+ };
19349
+ if (isHuskyProject(topLevel)) return {
19350
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19351
+ runnerRoot: topLevel,
19352
+ kind: "husky",
19353
+ hooksPathConfig: HUSKY_HOOKS_PATH
19354
+ };
19355
+ if (isVitePlusProject(topLevel)) return {
19356
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19357
+ runnerRoot: topLevel,
19358
+ kind: "vite-plus",
19359
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19360
+ };
19361
+ if (isSimpleGitHooksProject(topLevel)) return {
19362
+ hookPath: path$1.join(topLevel, "package.json"),
19363
+ runnerRoot: topLevel,
19364
+ kind: "simple-git-hooks"
19365
+ };
19366
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19367
+ if (lefthookConfigPath !== null) return {
19368
+ hookPath: lefthookConfigPath,
19369
+ runnerRoot: topLevel,
19370
+ kind: "lefthook"
19371
+ };
19372
+ if (isPreCommitProject(topLevel)) return {
19373
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19374
+ runnerRoot: topLevel,
19375
+ kind: "pre-commit"
19376
+ };
19377
+ if (isOvercommitProject(topLevel)) return {
19378
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19379
+ runnerRoot: topLevel,
19380
+ kind: "overcommit"
19381
+ };
19382
+ if (isYorkieProject(topLevel)) return {
19383
+ hookPath: getPackageJsonPath(topLevel),
19384
+ runnerRoot: topLevel,
19385
+ kind: "yorkie"
19386
+ };
19387
+ if (isGhooksProject(topLevel)) return {
19388
+ hookPath: getPackageJsonPath(topLevel),
19389
+ runnerRoot: topLevel,
19390
+ kind: "ghooks"
19391
+ };
19392
+ if (isGitHooksJsProject(topLevel)) return {
19393
+ hookPath: getPackageJsonPath(topLevel),
19394
+ runnerRoot: topLevel,
19395
+ kind: "git-hooks-js"
19396
+ };
19397
+ if (isPreCommitNpmProject(topLevel)) return {
19398
+ hookPath: getPackageJsonPath(topLevel),
19399
+ runnerRoot: topLevel,
19400
+ kind: "pre-commit-npm"
19401
+ };
19402
+ if (isPrettyQuickProject(topLevel)) return {
19403
+ hookPath: getPackageJsonPath(topLevel),
19404
+ runnerRoot: topLevel,
19405
+ kind: "pretty-quick"
19406
+ };
19407
+ const hookPath = runGit(projectRoot, [
19408
+ "rev-parse",
19409
+ "--git-path",
19410
+ HOOK_RELATIVE_PATH
19411
+ ]);
19412
+ if (hookPath === null || hookPath.length === 0) return null;
19413
+ return {
19414
+ hookPath: resolveGitPath(projectRoot, hookPath),
19415
+ runnerRoot: topLevel,
19416
+ kind: "git"
19417
+ };
19418
+ };
19419
+ const installReactDoctorGitHook = (options) => {
19420
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19421
+ if (options.kind === "lefthook") return installLefthook(options);
19422
+ if (options.kind === "pre-commit") return installPreCommit(options);
19423
+ if (options.kind === "overcommit") return installOvercommit(options);
19424
+ if (options.kind === "yorkie") return installYorkie(options);
19425
+ if (options.kind === "ghooks") return installGhooks(options);
19426
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19427
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19428
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19429
+ return installDirectGitHook(options);
19083
19430
  };
19084
19431
  //#endregion
19085
- //#region src/cli/utils/hash-project-root.ts
19086
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19432
+ //#region src/cli/utils/should-skip-prompts.ts
19433
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19087
19434
  //#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;
19435
+ //#region src/cli/utils/install-react-doctor.ts
19436
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19437
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19438
+ const SETUP_OPTION_SKIP = "skip";
19439
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19440
+ "ghooks",
19441
+ "git-hooks-js",
19442
+ "lefthook",
19443
+ "overcommit",
19444
+ "pre-commit",
19445
+ "pre-commit-npm",
19446
+ "pretty-quick",
19447
+ "simple-git-hooks",
19448
+ "yorkie"
19449
+ ]);
19450
+ const PACKAGE_MANAGER_LOCKFILES = [
19451
+ {
19452
+ packageManager: "pnpm",
19453
+ fileName: "pnpm-lock.yaml"
19454
+ },
19455
+ {
19456
+ packageManager: "yarn",
19457
+ fileName: "yarn.lock"
19458
+ },
19459
+ {
19460
+ packageManager: "bun",
19461
+ fileName: "bun.lockb"
19462
+ },
19463
+ {
19464
+ packageManager: "bun",
19465
+ fileName: "bun.lock"
19466
+ },
19467
+ {
19468
+ packageManager: "npm",
19469
+ fileName: "package-lock.json"
19100
19470
  }
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;
19471
+ ];
19472
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19473
+ let currentDirectory = path$1.resolve(startDirectory);
19474
+ while (true) {
19475
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19476
+ const parentDirectory = path$1.dirname(currentDirectory);
19477
+ if (parentDirectory === currentDirectory) return null;
19478
+ currentDirectory = parentDirectory;
19117
19479
  }
19118
19480
  };
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;
19481
+ const detectPackageManager = (projectRoot) => {
19482
+ let currentDirectory = path$1.resolve(projectRoot);
19483
+ while (true) {
19484
+ const packageJson = readPackageJson(currentDirectory);
19485
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19486
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19487
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19488
+ }
19489
+ const parentDirectory = path$1.dirname(currentDirectory);
19490
+ if (parentDirectory === currentDirectory) break;
19491
+ currentDirectory = parentDirectory;
19492
+ }
19493
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19494
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19131
19495
  };
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]
19496
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19497
+ const buildInstallCommand = (projectRoot) => {
19498
+ const packageManager = detectPackageManager(projectRoot);
19499
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19500
+ if (packageManager === "npm") return {
19501
+ command: "npm",
19502
+ args: [
19503
+ "install",
19504
+ "--save-dev",
19505
+ packageSpecifier
19506
+ ],
19507
+ cwd: projectRoot
19138
19508
  };
19139
- if (process$1.platform === "win32") return {
19140
- command: "cmd",
19509
+ if (packageManager === "yarn") return {
19510
+ command: "yarn",
19141
19511
  args: [
19142
- "/c",
19143
- "start",
19144
- "",
19145
- url
19146
- ]
19512
+ "add",
19513
+ "--dev",
19514
+ packageSpecifier
19515
+ ],
19516
+ cwd: projectRoot
19517
+ };
19518
+ if (packageManager === "bun") return {
19519
+ command: "bun",
19520
+ args: [
19521
+ "add",
19522
+ "--dev",
19523
+ packageSpecifier
19524
+ ],
19525
+ cwd: projectRoot
19147
19526
  };
19148
19527
  return {
19149
- command: "xdg-open",
19150
- args: [url]
19528
+ command: "pnpm",
19529
+ args: [
19530
+ "add",
19531
+ "--save-dev",
19532
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19533
+ packageSpecifier
19534
+ ],
19535
+ cwd: projectRoot
19151
19536
  };
19152
19537
  };
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
19538
  const execFileAsync = promisify(execFile);
19176
- const run = async (command, args, cwd) => {
19539
+ const defaultInstallDependencyRunner = async (input) => {
19540
+ await execFileAsync(input.command, [...input.args], {
19541
+ cwd: input.cwd,
19542
+ env: {
19543
+ ...process.env,
19544
+ REACT_DOCTOR_INSTALL: "1"
19545
+ },
19546
+ shell: process.platform === "win32"
19547
+ });
19548
+ };
19549
+ const isSupplyChainTrustError = (error) => {
19550
+ const candidate = error;
19551
+ const haystack = [
19552
+ candidate?.stderr,
19553
+ candidate?.stdout,
19554
+ candidate?.message
19555
+ ].map((part) => String(part ?? "")).join("\n");
19556
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19557
+ };
19558
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19559
+ const installReactDoctorDependency = async (options) => {
19560
+ const packageJson = readPackageJson(options.projectRoot);
19561
+ if (!isRecord(packageJson)) return {
19562
+ dependencyStatus: "skipped",
19563
+ dependencyReason: "missing-or-invalid-package-json"
19564
+ };
19565
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19566
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19567
+ dependencyStatus: "skipped",
19568
+ dependencyReason: "invalid-dev-dependencies"
19569
+ };
19570
+ const runnerInput = buildInstallCommand(options.projectRoot);
19177
19571
  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
- };
19572
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19187
19573
  } catch (error) {
19188
- const failure = error;
19189
19574
  return {
19190
- success: false,
19191
- stdout: (failure.stdout ?? "").trim(),
19192
- stderr: (failure.stderr ?? "").trim()
19575
+ dependencyStatus: "skipped",
19576
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19577
+ installCommand: formatInstallCommand(runnerInput)
19193
19578
  };
19194
19579
  }
19580
+ return { dependencyStatus: "created" };
19195
19581
  };
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;
19582
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19583
+ hookPath,
19584
+ runnerRoot: projectRoot,
19585
+ kind: "git"
19586
+ });
19587
+ const formatGitHookInstallMessage = (hookResult) => {
19588
+ 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.`;
19589
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19213
19590
  };
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, "")}`;
19591
+ const formatDependencyInstallMessage = (result) => {
19592
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19593
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19594
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19595
+ 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).";
19596
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19597
+ return "Skipped dev dependency install: package.json missing or invalid.";
19221
19598
  };
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
- };
19599
+ const buildDependencyFollowUp = (result) => {
19600
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19601
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19602
+ };
19603
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19604
+ installReactDoctorScriptStep(projectRoot);
19605
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19606
+ try {
19607
+ const dependencyResult = await installReactDoctorDependency({
19608
+ projectRoot,
19609
+ runner: dependencyRunner
19610
+ });
19611
+ recordCount(METRIC.installDependency, 1, {
19612
+ status: dependencyResult.dependencyStatus,
19613
+ reason: dependencyResult.dependencyReason ?? null,
19614
+ packageManager: detectPackageManager(projectRoot)
19615
+ });
19616
+ if (dependencyResult.dependencyStatus === "skipped") {
19617
+ const message = formatDependencyInstallMessage(dependencyResult);
19618
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19619
+ else dependencySpinner.fail(message);
19620
+ const followUp = buildDependencyFollowUp(dependencyResult);
19621
+ if (followUp !== void 0) cliLogger.dim(followUp);
19622
+ return dependencyResult;
19623
+ }
19624
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19625
+ return dependencyResult;
19626
+ } catch (error) {
19627
+ dependencySpinner.fail("Failed to install React Doctor package.");
19628
+ throw error;
19629
+ }
19630
+ };
19631
+ const getSkillSourceDirectory = () => {
19632
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19633
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19634
+ };
19635
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19636
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19637
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19638
+ try {
19639
+ const installResult = await installSkillsFromSource({
19640
+ source: sourceDir,
19641
+ agents: selectedAgents,
19642
+ cwd: projectRoot,
19643
+ mode: "copy"
19644
+ });
19645
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19646
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19647
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19648
+ } catch (error) {
19649
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19650
+ throw error;
19289
19651
  }
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
- };
19652
+ };
19653
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19654
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19655
+ try {
19656
+ const hookResult = installReactDoctorGitHook({
19657
+ hookPath: gitHookTarget.hookPath,
19658
+ projectRoot: gitHookTarget.runnerRoot,
19659
+ kind: gitHookTarget.kind,
19660
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19661
+ });
19662
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19663
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19664
+ } catch (error) {
19665
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19666
+ throw error;
19300
19667
  }
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
- };
19668
+ };
19669
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19670
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19671
+ try {
19672
+ const hookResult = installReactDoctorAgentHooks({
19673
+ projectRoot,
19674
+ agents: selectedAgents
19675
+ });
19676
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19677
+ else {
19678
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19679
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19680
+ }
19681
+ } catch (error) {
19682
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19683
+ throw error;
19312
19684
  }
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
19685
  };
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;
19686
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19687
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19688
+ };
19689
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19690
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19691
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19692
+ if (upgradeResult.status === "failed") {
19693
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19694
+ return false;
19695
+ }
19696
+ if (upgradeResult.status === "not-needed") {
19697
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19698
+ return false;
19699
+ }
19700
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19701
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19702
+ return true;
19703
+ };
19704
+ const runInstallReactDoctor = async (options = {}) => {
19705
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19706
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19707
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19708
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19709
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19710
+ process.exitCode = 1;
19711
+ return;
19712
+ }
19713
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19714
+ if (detectedAgents.length === 0) {
19715
+ cliLogger.error("No supported coding agents detected.");
19716
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19717
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19718
+ process.exitCode = 1;
19719
+ return;
19720
+ }
19721
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19722
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19723
+ const gitHookPath = gitHookTarget?.hookPath;
19724
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19725
+ const prompt = options.prompt ?? prompts;
19726
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19727
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19728
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19729
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19730
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19731
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19732
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19733
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19734
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19735
+ type: "multiselect",
19736
+ name: "agents",
19737
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19738
+ choices: detectedAgents.map((agent) => ({
19739
+ title: getSkillAgentConfig(agent).displayName,
19740
+ value: agent,
19741
+ selected: true
19742
+ })),
19743
+ instructions: false,
19744
+ min: 1
19745
+ }, promptOptions)).agents ?? [];
19746
+ if (selectedAgents.length === 0) return;
19747
+ let dependencyResult;
19748
+ if (!options.dryRun) {
19749
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19750
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19751
+ }
19752
+ let didInstallWorkflow = false;
19753
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19754
+ cliLogger.break();
19755
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19756
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19757
+ }
19758
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19759
+ title: "Pre-commit hook",
19760
+ description: "Check staged changes before each commit",
19761
+ value: SETUP_OPTION_GIT_HOOK,
19762
+ selected: true
19763
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19764
+ title: "Agent hooks",
19765
+ description: "Ask Claude Code or Cursor to scan after code edits",
19766
+ value: SETUP_OPTION_AGENT_HOOKS,
19767
+ selected: Boolean(options.agentHooks)
19768
+ }] : []];
19769
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19770
+ title: "Skip optional setup",
19771
+ description: "Install only the agent skill and package setup",
19772
+ value: SETUP_OPTION_SKIP,
19773
+ selected: false
19774
+ }, ...setupActionChoices];
19775
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19776
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19777
+ type: "multiselect",
19778
+ name: "setupOptions",
19779
+ message: "Select additional React Doctor setup:",
19780
+ choices: setupChoices,
19781
+ instructions: false
19782
+ }, promptOptions)).setupOptions ?? [];
19783
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19784
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19785
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19786
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19787
+ if (!options.dryRun) {
19788
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19789
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19790
+ }
19791
+ if (options.dryRun) {
19792
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19793
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19794
+ cliLogger.dim(` Source: ${sourceDir}`);
19795
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19796
+ cliLogger.dim(" Dev dependency: react-doctor");
19797
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19798
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19799
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19800
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19801
+ return;
19802
+ }
19803
+ recordCount(METRIC.installCompleted, 1, {
19804
+ agentsCount: selectedAgents.length,
19805
+ gitHook: shouldInstallGitHook,
19806
+ agentHooks: shouldInstallAgentHooks,
19807
+ workflow: didInstallWorkflow,
19808
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19809
+ packageManager: detectPackageManager(projectRoot)
19810
+ });
19811
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19812
+ };
19813
+ //#endregion
19814
+ //#region src/cli/utils/install-skill-for-agent.ts
19815
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19816
+ const source = getSkillSourceDirectory();
19817
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19818
+ const result = await installSkillsFromSource({
19819
+ source,
19820
+ agents: [agent],
19821
+ cwd: projectRoot,
19822
+ mode: "copy"
19823
+ });
19824
+ return result.skills.length > 0 && result.failed.length === 0;
19344
19825
  };
19345
19826
  //#endregion
19346
19827
  //#region src/cli/utils/launch-agent.ts
@@ -19431,9 +19912,6 @@ const copyToClipboard = (text) => {
19431
19912
  };
19432
19913
  //#endregion
19433
19914
  //#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
19915
  const CLIPBOARD_CHOICE = "clipboard";
19438
19916
  const SKIP_CHOICE = "skip";
19439
19917
  const printPayload = (payload) => {
@@ -19442,59 +19920,11 @@ const printPayload = (payload) => {
19442
19920
  cliLogger.log(payload);
19443
19921
  cliLogger.log(highlighter.dim("──────────────────────"));
19444
19922
  };
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
19923
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19474
19924
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19475
19925
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19476
19926
 
19477
19927
  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
19928
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19499
19929
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19500
19930
  if (!changed) return false;
@@ -19539,46 +19969,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19539
19969
  }
19540
19970
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19541
19971
  };
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
19972
  const detectLaunchableAgents = async () => {
19583
19973
  const detected = new Set(await detectAvailableAgents());
19584
19974
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19595,7 +19985,7 @@ const handoffToAgent = async (input) => {
19595
19985
  });
19596
19986
  if (ciOutcome === "cancel") return;
19597
19987
  if (ciOutcome === "yes") {
19598
- await setUpGitHubActions(input.rootDirectory);
19988
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19599
19989
  cliLogger.break();
19600
19990
  }
19601
19991
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19746,6 +20136,14 @@ const HAPPY_FACE_LINES = [
19746
20136
  "│ ▽ │",
19747
20137
  "└─────┘"
19748
20138
  ];
20139
+ const FACE_INDENT = " ";
20140
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
20141
+ const clampToColumns = (text, maxColumns) => {
20142
+ if (maxColumns <= 0) return "";
20143
+ if (text.length <= maxColumns) return text;
20144
+ if (maxColumns === 1) return "…";
20145
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
20146
+ };
19749
20147
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19750
20148
  const characters = [...text];
19751
20149
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19759,13 +20157,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19759
20157
  const interLineDelayMs = 250 / speedMultiplier;
19760
20158
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19761
20159
  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`);
20160
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
20161
+ const terminalColumns = process.stdout.columns;
20162
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
20163
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
20164
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
20165
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19764
20166
  yield* writeStdout("\x1B[3A");
19765
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
20167
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19766
20168
  yield* Effect.sleep(interLineDelayMs);
19767
20169
  yield* writeStdout("\x1B[1B");
19768
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
20170
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19769
20171
  yield* Effect.sleep(explanationHoldMs);
19770
20172
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19771
20173
  });
@@ -19874,8 +20276,9 @@ const findLowestScoredScan = (completedScans) => {
19874
20276
  };
19875
20277
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
19876
20278
  const { completedScans, userConfig, verbose, isOffline, projectName } = input;
20279
+ const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
19877
20280
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
19878
- const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
20281
+ const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
19879
20282
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
19880
20283
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
19881
20284
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -19889,29 +20292,30 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19889
20292
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
19890
20293
  const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
19891
20294
  yield* Console.log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
19892
- if (surfaceDiagnostics.length > 0) {
20295
+ if (displayDiagnostics.length > 0) {
19893
20296
  yield* Console.log("");
19894
- yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
20297
+ yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19895
20298
  }
19896
20299
  const lowestScoredScan = findLowestScoredScan(completedScans);
19897
20300
  const aggregateScore = lowestScoredScan?.result.score ?? null;
19898
20301
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
19899
20302
  yield* printSummary({
19900
- diagnostics: surfaceDiagnostics,
20303
+ diagnostics: displayDiagnostics,
19901
20304
  elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
19902
20305
  scoreResult: aggregateScore,
19903
- potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
20306
+ potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
19904
20307
  totalSourceFileCount,
19905
20308
  noScoreMessage: "Score unavailable.",
19906
20309
  verbose,
19907
20310
  animateProjection: animateRender
19908
20311
  });
19909
20312
  const entries = completedScans.map((scan) => {
19910
- const errorCount = scan.result.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
20313
+ const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
20314
+ const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19911
20315
  return {
19912
20316
  projectName: scan.result.project.projectName,
19913
20317
  score: scan.result.score?.score ?? null,
19914
- issueCount: scan.result.diagnostics.length,
20318
+ issueCount: projectDiagnostics.length,
19915
20319
  errorCount
19916
20320
  };
19917
20321
  });
@@ -19919,7 +20323,7 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19919
20323
  yield* Console.log("");
19920
20324
  for (const entry of entries) yield* Console.log(buildSummaryLine(entry, longestProjectNameLength));
19921
20325
  yield* printFooter({
19922
- diagnostics: surfaceDiagnostics,
20326
+ diagnostics: displayDiagnostics,
19923
20327
  scoreResult: aggregateScore,
19924
20328
  projectName,
19925
20329
  isOffline
@@ -20009,7 +20413,8 @@ const resolveCliInspectOptions = (flags, userConfig) => {
20009
20413
  noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
20010
20414
  isCi: isCiEnvironment(),
20011
20415
  silent: Boolean(flags.json),
20012
- concurrency: resolveParallelFlag(flags.parallel)
20416
+ concurrency: resolveParallelFlag(flags.parallel),
20417
+ categoryFilters: resolveCliCategories(flags.category)
20013
20418
  };
20014
20419
  };
20015
20420
  //#endregion
@@ -20262,6 +20667,16 @@ const validateModeFlags = (flags) => {
20262
20667
  };
20263
20668
  //#endregion
20264
20669
  //#region src/cli/commands/inspect.ts
20670
+ const filterCompletedScansByCategories = (completedScans, categoryFilters) => {
20671
+ if (categoryFilters.size === 0) return [...completedScans];
20672
+ return completedScans.map((scan) => ({
20673
+ ...scan,
20674
+ result: {
20675
+ ...scan.result,
20676
+ diagnostics: filterDiagnosticsByCategories(scan.result.diagnostics, categoryFilters)
20677
+ }
20678
+ }));
20679
+ };
20265
20680
  /**
20266
20681
  * Post-scan finalization shared by the staged-arm and project-loop
20267
20682
  * paths of `inspectAction`: emit the JSON report (when in JSON mode)
@@ -20274,6 +20689,7 @@ const finalizeScans = (input) => {
20274
20689
  const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
20275
20690
  const baselineDegraded = input.baselineIntended && !baselineComputed;
20276
20691
  const mode = baselineDegraded ? "diff" : input.mode;
20692
+ const jsonCompletedScans = filterCompletedScansByCategories(input.completedScans, input.categoryFilters);
20277
20693
  if (input.isJsonMode) {
20278
20694
  const baseline = baselineComputed && baselineDeltas.length > 0 ? {
20279
20695
  baseRef: baselineDeltas[0].baseRef,
@@ -20285,7 +20701,7 @@ const finalizeScans = (input) => {
20285
20701
  directory: input.resolvedDirectory,
20286
20702
  mode,
20287
20703
  diff: input.diff,
20288
- scans: input.completedScans,
20704
+ scans: jsonCompletedScans,
20289
20705
  totalElapsedMilliseconds: performance.now() - input.startTime,
20290
20706
  baseline
20291
20707
  }));
@@ -20359,6 +20775,7 @@ const inspectAction = async (directory, flags) => {
20359
20775
  await Effect.runPromise(playWelcomeScene({ speedMultiplier: isReturningUser ? 2 : 1 }));
20360
20776
  } else Effect.runSync(printBrandedHeader);
20361
20777
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
20778
+ const categoryFilters = new Set(scanOptions.categoryFilters ?? []);
20362
20779
  const skipPrompts = shouldSkipPrompts({
20363
20780
  yes: flags.yes,
20364
20781
  json: flags.json
@@ -20419,6 +20836,7 @@ const inspectAction = async (directory, flags) => {
20419
20836
  isJsonMode,
20420
20837
  isScoreOnly,
20421
20838
  flags,
20839
+ categoryFilters,
20422
20840
  userConfig,
20423
20841
  resolvedDirectory,
20424
20842
  startTime
@@ -20478,6 +20896,7 @@ const inspectAction = async (directory, flags) => {
20478
20896
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
20479
20897
  await Effect.runPromise(printMultiProjectSummary({
20480
20898
  completedScans,
20899
+ categoryFilters,
20481
20900
  userConfig,
20482
20901
  verbose: Boolean(flags.verbose),
20483
20902
  isOffline: !shouldShowShareLink,
@@ -20493,14 +20912,15 @@ const inspectAction = async (directory, flags) => {
20493
20912
  isJsonMode,
20494
20913
  isScoreOnly,
20495
20914
  flags,
20915
+ categoryFilters,
20496
20916
  userConfig,
20497
20917
  resolvedDirectory,
20498
20918
  startTime
20499
20919
  });
20500
- const surfaceDiagnostics = filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig);
20501
- if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && surfaceDiagnostics.length > 0) {
20920
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
20921
+ if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
20502
20922
  await handoffToAgent({
20503
- diagnostics: surfaceDiagnostics,
20923
+ diagnostics: selectedSurfaceDiagnostics,
20504
20924
  projectName: path$1.basename(resolvedDirectory),
20505
20925
  rootDirectory: resolvedDirectory,
20506
20926
  interactive: true
@@ -20931,7 +21351,7 @@ const rulesListAction = async (options) => {
20931
21351
  });
20932
21352
  const catalog = buildRuleCatalog();
20933
21353
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
20934
- const categoryFilter = options.category?.toLowerCase();
21354
+ const categoryFilter = typeof options.category === "string" ? options.category.toLowerCase() : void 0;
20935
21355
  const frameworkFilter = options.framework?.toLowerCase();
20936
21356
  const rows = catalog.filter((entry) => {
20937
21357
  if (categoryFilter && entry.category.toLowerCase() !== categoryFilter) return false;
@@ -21294,6 +21714,7 @@ const ROOT_FLAG_SPEC = {
21294
21714
  "--yes"
21295
21715
  ]),
21296
21716
  longOptionsWithRequiredValues: new Set([
21717
+ "--category",
21297
21718
  "--changed-files-from",
21298
21719
  "--blocking",
21299
21720
  "--fail-on",
@@ -21450,6 +21871,7 @@ ${formatExampleLines([
21450
21871
  ["react-doctor ./apps/web", "scan a specific directory"],
21451
21872
  ["react-doctor --diff main", "scan only files changed vs. main"],
21452
21873
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
21874
+ ["react-doctor --category Security", "show only one diagnostic category"],
21453
21875
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
21454
21876
  ["react-doctor --json > report.json", "write a machine-readable report"],
21455
21877
  ["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
@@ -21478,7 +21900,8 @@ ${formatExampleLines([
21478
21900
  ${highlighter.dim("Learn more:")}
21479
21901
  ${highlighter.info(CANONICAL_GITHUB_URL)}
21480
21902
  `;
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);
21903
+ const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
21904
+ 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
21905
  program.action(inspectAction);
21483
21906
  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
21907
  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 +21944,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21521
21944
  export {};
21522
21945
 
21523
21946
  //# sourceMappingURL=cli.js.map
21524
- //# debugId=1486eaee-ed07-5eef-a9d7-51293140e237
21947
+ //# debugId=e5634721-88db-51c8-93e5-137793125d7a