react-doctor 0.4.1 → 0.4.2-dev.1044e29

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]="30809678-4fe4-55cc-938c-ee6301ab7888")}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]="d1b95aab-fa59-5a23-83a0-37e1ff08b002")}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";
@@ -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;
@@ -6724,7 +6725,6 @@ const LEGACY_RULE_KEY_TO_NATIVE_RULE_KEY = {
6724
6725
  "react/jsx-no-new-function-as-prop": "react-doctor/jsx-no-new-function-as-prop",
6725
6726
  "react/jsx-no-new-object-as-prop": "react-doctor/jsx-no-new-object-as-prop",
6726
6727
  "react/jsx-no-script-url": "react-doctor/jsx-no-script-url",
6727
- "react/jsx-no-target-blank": "react-doctor/jsx-no-target-blank",
6728
6728
  "react/jsx-no-undef": "react-doctor/jsx-no-undef",
6729
6729
  "react/jsx-no-useless-fragment": "react-doctor/jsx-no-useless-fragment",
6730
6730
  "react/jsx-pascal-case": "react-doctor/jsx-pascal-case",
@@ -7629,6 +7629,35 @@ const loadPackageJsonConfig = (directory) => {
7629
7629
  format: "package-json"
7630
7630
  };
7631
7631
  };
7632
+ const loadLegacyConfig = (directory) => {
7633
+ const legacyFilePath = path$1.join(directory, LEGACY_CONFIG_FILENAME);
7634
+ if (!isFile(legacyFilePath)) return {
7635
+ status: "absent",
7636
+ loaded: null
7637
+ };
7638
+ try {
7639
+ const parsed = readDataConfig(legacyFilePath);
7640
+ if (isPlainObject(parsed)) {
7641
+ warn(`${LEGACY_CONFIG_FILENAME} is deprecated — rename it to ${CONFIG_BASENAME}.json (or author a ${CONFIG_BASENAME}.ts). It is still read for now.`);
7642
+ return {
7643
+ status: "found",
7644
+ loaded: {
7645
+ config: validateConfigTypes(parsed),
7646
+ sourceDirectory: directory,
7647
+ configFilePath: legacyFilePath,
7648
+ format: "json"
7649
+ }
7650
+ };
7651
+ }
7652
+ warn(`${LEGACY_CONFIG_FILENAME} must contain an object, ignoring.`);
7653
+ } catch (error) {
7654
+ warn(`Failed to load ${LEGACY_CONFIG_FILENAME}: ${formatError(error)}`);
7655
+ }
7656
+ return {
7657
+ status: "invalid",
7658
+ loaded: null
7659
+ };
7660
+ };
7632
7661
  const loadConfigFromDirectory = async (directory) => {
7633
7662
  let sawBrokenConfigFile = false;
7634
7663
  for (const extension of CONFIG_EXTENSIONS) {
@@ -7658,7 +7687,8 @@ const loadConfigFromDirectory = async (directory) => {
7658
7687
  status: "found",
7659
7688
  loaded: packageJsonConfig
7660
7689
  };
7661
- if (isFile(path$1.join(directory, LEGACY_CONFIG_FILENAME))) warn(`${LEGACY_CONFIG_FILENAME} is no longer read — rename it to ${CONFIG_BASENAME}.json (or author a ${CONFIG_BASENAME}.ts).`);
7690
+ const legacyResult = loadLegacyConfig(directory);
7691
+ if (legacyResult.status !== "absent") return legacyResult;
7662
7692
  return {
7663
7693
  status: sawBrokenConfigFile ? "invalid" : "absent",
7664
7694
  loaded: null
@@ -7695,7 +7725,9 @@ const directoryHasCurrentConfig = (directory) => {
7695
7725
  /**
7696
7726
  * Walks up from `rootDirectory` (same boundary semantics as
7697
7727
  * `loadConfigWithSource`) looking for a pre-migration
7698
- * `react-doctor.config.json` that is no longer read. Returns the first one
7728
+ * `react-doctor.config.json`. The loader still reads this file as a deprecated
7729
+ * fallback (see `loadLegacyConfig`); this detector is what lets the interactive
7730
+ * CLI offer to rename it to a current-format config. Returns the first one
7699
7731
  * found, or `null` when a current-format config supersedes it or none exists
7700
7732
  * before a project boundary. Detection only — the CLI performs the rename.
7701
7733
  */
@@ -7888,51 +7920,51 @@ const FLAGGED_DEPENDENCIES = [
7888
7920
  {
7889
7921
  packageName: "expo-modules-autolinking",
7890
7922
  rule: "expo-no-redundant-dependency",
7891
- message: "\"expo-modules-autolinking\" should not be a direct dependency — Expo installs it transitively as needed",
7923
+ 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",
7892
7924
  help: "Remove `expo-modules-autolinking` from your package.json"
7893
7925
  },
7894
7926
  {
7895
7927
  packageName: "expo-dev-launcher",
7896
7928
  rule: "expo-no-redundant-dependency",
7897
- message: "\"expo-dev-launcher\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7929
+ 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",
7898
7930
  help: "Remove `expo-dev-launcher` and depend on `expo-dev-client` instead"
7899
7931
  },
7900
7932
  {
7901
7933
  packageName: "expo-dev-menu",
7902
7934
  rule: "expo-no-redundant-dependency",
7903
- message: "\"expo-dev-menu\" should not be a direct dependency — it is pulled in by `expo-dev-client`",
7935
+ 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",
7904
7936
  help: "Remove `expo-dev-menu` and depend on `expo-dev-client` instead"
7905
7937
  },
7906
7938
  {
7907
7939
  packageName: "expo-modules-core",
7908
7940
  rule: "expo-no-redundant-dependency",
7909
- message: "\"expo-modules-core\" should not be a direct dependency — use the API re-exported from the `expo` package",
7941
+ 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",
7910
7942
  help: "Remove `expo-modules-core` from your package.json and import from `expo` instead"
7911
7943
  },
7912
7944
  {
7913
7945
  packageName: "@expo/metro-config",
7914
7946
  rule: "expo-no-redundant-dependency",
7915
- message: "\"@expo/metro-config\" should not be a direct dependency — use the `expo/metro-config` sub-export of the `expo` package",
7947
+ 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",
7916
7948
  help: "Remove `@expo/metro-config` and import `expo/metro-config` in your metro.config.js"
7917
7949
  },
7918
7950
  {
7919
7951
  packageName: "@types/react-native",
7920
7952
  rule: "expo-no-redundant-dependency",
7921
- message: "\"@types/react-native\" should not be installed — React Native ships its own types since SDK 48",
7953
+ 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",
7922
7954
  help: "Remove `@types/react-native` from your package.json",
7923
7955
  minSdkMajor: 48
7924
7956
  },
7925
7957
  {
7926
7958
  packageName: "@expo/config-plugins",
7927
7959
  rule: "expo-no-redundant-dependency",
7928
- message: "\"@expo/config-plugins\" should not be a direct dependency — use the `expo/config-plugins` sub-export of the `expo` package",
7960
+ 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",
7929
7961
  help: "Remove `@expo/config-plugins`; config-plugin authors should import from `expo/config-plugins`. See https://github.com/expo/expo/pull/18855",
7930
7962
  minSdkMajor: 48
7931
7963
  },
7932
7964
  {
7933
7965
  packageName: "@expo/prebuild-config",
7934
7966
  rule: "expo-no-redundant-dependency",
7935
- message: "\"@expo/prebuild-config\" should not be a direct dependency — Expo installs it transitively",
7967
+ 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",
7936
7968
  help: "Remove `@expo/prebuild-config` from your package.json",
7937
7969
  minSdkMajor: 53
7938
7970
  },
@@ -7946,28 +7978,28 @@ const FLAGGED_DEPENDENCIES = [
7946
7978
  {
7947
7979
  packageName: "expo-app-loading",
7948
7980
  rule: "expo-no-redundant-dependency",
7949
- message: "\"expo-app-loading\" was removed in SDK 49",
7981
+ message: "\"expo-app-loading\" was removed in SDK 49, so keeping it can leave imports unresolved after upgrading Expo",
7950
7982
  help: "Remove `expo-app-loading` and use `expo-splash-screen` instead. See https://docs.expo.dev/versions/latest/sdk/splash-screen/",
7951
7983
  minSdkMajor: 49
7952
7984
  },
7953
7985
  {
7954
7986
  packageName: "expo-firebase-analytics",
7955
7987
  rule: "expo-no-redundant-dependency",
7956
- message: "\"expo-firebase-analytics\" was removed in SDK 48",
7988
+ message: "\"expo-firebase-analytics\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7957
7989
  help: FIREBASE_HELP,
7958
7990
  minSdkMajor: 48
7959
7991
  },
7960
7992
  {
7961
7993
  packageName: "expo-firebase-recaptcha",
7962
7994
  rule: "expo-no-redundant-dependency",
7963
- message: "\"expo-firebase-recaptcha\" was removed in SDK 48",
7995
+ message: "\"expo-firebase-recaptcha\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7964
7996
  help: FIREBASE_HELP,
7965
7997
  minSdkMajor: 48
7966
7998
  },
7967
7999
  {
7968
8000
  packageName: "expo-firebase-core",
7969
8001
  rule: "expo-no-redundant-dependency",
7970
- message: "\"expo-firebase-core\" was removed in SDK 48",
8002
+ message: "\"expo-firebase-core\" was removed in SDK 48, so keeping it can leave imports unresolved or fail native builds after upgrading Expo",
7971
8003
  help: FIREBASE_HELP,
7972
8004
  minSdkMajor: 48
7973
8005
  }
@@ -8008,7 +8040,7 @@ const checkExpoGitignore = (context) => {
8008
8040
  }));
8009
8041
  if (findLocalModuleNativeFiles(rootDirectory).find((nativeFilePath) => isPathGitIgnored(rootDirectory, nativeFilePath) === true) !== void 0) diagnostics.push(buildExpoDiagnostic({
8010
8042
  rule: "expo-gitignore",
8011
- 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",
8043
+ 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.",
8012
8044
  help: "Use anchored patterns like `/ios` and `/android` in .gitignore so only the top-level native directories are excluded, not those inside `modules/`"
8013
8045
  }));
8014
8046
  return diagnostics;
@@ -8070,17 +8102,16 @@ const checkExpoPackageJsonConflicts = (context) => {
8070
8102
  const conflictingScriptNames = CONFLICTING_SCRIPT_NAMES.filter((scriptName) => Boolean(packageJson.scripts?.[scriptName]));
8071
8103
  if (conflictingScriptNames.length > 0) {
8072
8104
  const quotedNames = conflictingScriptNames.map((name) => `"${name}"`).join(", ");
8073
- const shadowsExpoCli = conflictingScriptNames.includes("expo");
8074
8105
  diagnostics.push(buildExpoDiagnostic({
8075
8106
  rule: "expo-package-json-conflict",
8076
- 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" : ""}`,
8107
+ 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.`,
8077
8108
  help: "Rename these scripts so they don't collide with the `expo` / `react-native` binaries"
8078
8109
  }));
8079
8110
  }
8080
8111
  const packageName = packageJson.name;
8081
8112
  if (typeof packageName === "string" && context.directDependencyNames.has(packageName)) diagnostics.push(buildExpoDiagnostic({
8082
8113
  rule: "expo-package-json-conflict",
8083
- message: `package.json "name" is "${packageName}", which collides with a dependency of the same name`,
8114
+ 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.`,
8084
8115
  help: "Rename your package so it no longer matches one of its dependencies"
8085
8116
  }));
8086
8117
  return diagnostics;
@@ -8151,7 +8182,7 @@ const checkExpoRouterReactNavigation = (context) => {
8151
8182
  if (reactNavigationNames.length === 0) return [];
8152
8183
  return [buildExpoDiagnostic({
8153
8184
  rule: "expo-router-no-react-navigation",
8154
- 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"}`,
8185
+ 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.`,
8155
8186
  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/"
8156
8187
  })];
8157
8188
  };
@@ -8523,7 +8554,9 @@ const setColorEnabled = (enabled) => {
8523
8554
  highlighter.gray = colors.gray;
8524
8555
  highlighter.bold = colors.bold;
8525
8556
  };
8526
- const computeJsxIncludePaths = (includePaths) => includePaths.length > 0 ? includePaths.filter((filePath) => JSX_FILE_PATTERN.test(filePath)) : void 0;
8557
+ const NEXT_ENTRY_FILE_PATTERN = /^(?:\.\/)?(?:src\/)?(?:middleware|proxy)\.(?:tsx?|jsx?|mts|mjs)$/;
8558
+ const shouldIncludeExplicitLintPath = (filePath, project) => JSX_FILE_PATTERN.test(filePath) || project?.framework === "nextjs" && NEXT_ENTRY_FILE_PATTERN.test(filePath);
8559
+ const computeExplicitLintIncludePaths = (includePaths, project) => includePaths.length > 0 ? includePaths.filter((filePath) => shouldIncludeExplicitLintPath(filePath, project)) : void 0;
8527
8560
  const LINGUIST_ATTRIBUTE_PATTERN = /^linguist-(?:vendored|generated)(?:=([a-zA-Z0-9]+))?$/i;
8528
8561
  const FALSY_VALUES = new Set([
8529
8562
  "false",
@@ -8949,7 +8982,7 @@ const checkDeadCode = async (options) => {
8949
8982
  plugin: DEAD_CODE_PLUGIN,
8950
8983
  rule: "unused-file",
8951
8984
  severity: "warning",
8952
- message: "Unused file — not reachable from any entry point",
8985
+ message: "Unused file is not reachable from any entry point, so it adds maintenance surface without shipping any code.",
8953
8986
  help: "Delete the file if it is truly unreachable, or import it from an entry point.",
8954
8987
  line: 0,
8955
8988
  column: 0,
@@ -8962,7 +8995,7 @@ const checkDeadCode = async (options) => {
8962
8995
  plugin: DEAD_CODE_PLUGIN,
8963
8996
  rule: unusedExport.isTypeOnly ? "unused-type" : "unused-export",
8964
8997
  severity: "warning",
8965
- message: `Unused ${label}: \`${unusedExport.name}\``,
8998
+ 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.`,
8966
8999
  help: "Drop the `export` keyword (or remove the declaration) if no other module uses this symbol.",
8967
9000
  line: unusedExport.line,
8968
9001
  column: unusedExport.column,
@@ -8976,7 +9009,7 @@ const checkDeadCode = async (options) => {
8976
9009
  plugin: DEAD_CODE_PLUGIN,
8977
9010
  rule: unusedDependency.isDevDependency ? "unused-dev-dependency" : "unused-dependency",
8978
9011
  severity: "warning",
8979
- message: `Unused ${label}: \`${unusedDependency.name}\``,
9012
+ message: `Unused ${label}: \`${unusedDependency.name}\` is not imported by the project, so it adds install time and supply-chain surface without being used.`,
8980
9013
  help: "Remove the dependency from package.json if it is genuinely unused.",
8981
9014
  line: 0,
8982
9015
  column: 0,
@@ -8990,7 +9023,7 @@ const checkDeadCode = async (options) => {
8990
9023
  plugin: DEAD_CODE_PLUGIN,
8991
9024
  rule: "circular-dependency",
8992
9025
  severity: "warning",
8993
- message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}`,
9026
+ message: `Circular import cycle: ${cycle.files.map(toRelative).join(" → ")}. Modules in the cycle can observe partially initialized exports, causing order-dependent bugs.`,
8994
9027
  help: "Break the cycle by extracting the shared code into a third module that both files import.",
8995
9028
  line: 0,
8996
9029
  column: 0,
@@ -9073,11 +9106,11 @@ const listSourceFilesViaFilesystem = (rootDirectory) => {
9073
9106
  return filePaths;
9074
9107
  };
9075
9108
  const listSourceFiles = (rootDirectory) => excludeMinifiedFiles(rootDirectory, listSourceFilesViaGit(rootDirectory) ?? listSourceFilesViaFilesystem(rootDirectory));
9076
- const resolveLintIncludePaths = (rootDirectory, userConfig) => {
9109
+ const resolveLintIncludePaths = (rootDirectory, userConfig, project) => {
9077
9110
  if (!Array.isArray(userConfig?.ignore?.files) || userConfig.ignore.files.length === 0) return;
9078
9111
  const ignoredPatterns = compileIgnoredFilePatterns(userConfig);
9079
9112
  return listSourceFiles(rootDirectory).filter((filePath) => {
9080
- if (!JSX_FILE_PATTERN.test(filePath)) return false;
9113
+ if (!shouldIncludeExplicitLintPath(filePath, project)) return false;
9081
9114
  return !isFileIgnoredByPatterns(filePath, rootDirectory, ignoredPatterns);
9082
9115
  });
9083
9116
  };
@@ -11429,7 +11462,7 @@ const runInspect = (input, hooks = {}) => Effect.gen(function* () {
11429
11462
  directory: scanDirectory,
11430
11463
  repo
11431
11464
  }).pipe(Effect.orElseSucceed(() => null)) : Effect.succeed(null));
11432
- const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeJsxIncludePaths([...input.includePaths])) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config);
11465
+ const lintIncludePaths = (input.skipJsxIncludeFilter ? input.includePaths.length > 0 ? [...input.includePaths] : void 0 : computeExplicitLintIncludePaths([...input.includePaths], project)) ?? resolveLintIncludePaths(scanDirectory, resolvedConfig.config, project);
11433
11466
  const scannedFilePaths = input.suppressScanSummary ? (lintIncludePaths ?? (yield* filesService.listSourceFiles(scanDirectory))).map((relativePath) => path$1.resolve(scanDirectory, relativePath)) : [];
11434
11467
  const beforeLint = hooks.beforeLint ?? NO_HOOKS.beforeLint;
11435
11468
  const afterLint = hooks.afterLint ?? NO_HOOKS.afterLint;
@@ -12215,7 +12248,7 @@ const makeNoopConsole = () => ({
12215
12248
  });
12216
12249
  //#endregion
12217
12250
  //#region src/cli/utils/version.ts
12218
- const VERSION = "0.4.1";
12251
+ const VERSION = "0.4.2-dev.1044e29";
12219
12252
  //#endregion
12220
12253
  //#region src/cli/utils/json-mode.ts
12221
12254
  let context = null;
@@ -12573,13 +12606,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12573
12606
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12574
12607
  * standard `SENTRY_RELEASE` override.
12575
12608
  */
12576
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.1`;
12609
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.1044e29`;
12577
12610
  /**
12578
12611
  * Deployment environment shown in Sentry's environment filter. Defaults to
12579
12612
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12580
12613
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12581
12614
  */
12582
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.1") ? "development" : "production");
12615
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.1044e29") ? "development" : "production");
12583
12616
  /**
12584
12617
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12585
12618
  * (set to `0` to disable tracing) and falls back to
@@ -15842,13 +15875,14 @@ const buildRuntimeLayers = (input) => {
15842
15875
  const linterLayer = input.shouldSkipLint ? Linter.layerOf([]) : Linter.layerOxlint;
15843
15876
  const deadCodeLayer = input.shouldRunDeadCode ? DeadCode.layerNode : DeadCode.layerOf([]);
15844
15877
  const scoreLayer = input.shouldComputeScore ? Score.layerHttp : Score.layerOf(null);
15878
+ const projectLayer = input.projectInfoOverride === void 0 ? Project.layerNode : Project.layerOf(input.projectInfoOverride);
15845
15879
  const progressLayer = input.shouldShowProgressSpinners ? Progress.layerOra(buildSpinnerProgressHandle) : Progress.layerNoop;
15846
15880
  const configLayer = input.hasConfigOverride ? Config.layerOf({
15847
15881
  config: input.userConfig,
15848
15882
  resolvedDirectory: input.directory,
15849
15883
  configSourceDirectory: input.configSourceDirectory
15850
15884
  }) : Config.layerNode;
15851
- const baseLayers = Layer.mergeAll(Project.layerNode, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15885
+ const baseLayers = Layer.mergeAll(projectLayer, configLayer, Files.layerNode, Git.layerNode, linterLayer, LintPartialFailures.layerLive, deadCodeLayer, progressLayer, Reporter.layerNoop, scoreLayer);
15852
15886
  return input.oxlintConcurrency === void 0 ? baseLayers : Layer.mergeAll(baseLayers, Layer.succeed(OxlintConcurrency, input.oxlintConcurrency));
15853
15887
  };
15854
15888
  //#endregion
@@ -16441,8 +16475,22 @@ const buildCodeFrame = (input) => {
16441
16475
  });
16442
16476
  };
16443
16477
  //#endregion
16478
+ //#region src/cli/utils/resolve-measure-width.ts
16479
+ const resolveClampedWidth = (input) => {
16480
+ const terminalColumns = process.stdout.columns;
16481
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16482
+ const availableColumns = terminalColumns - input.reservedColumns;
16483
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16484
+ };
16485
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16486
+ reservedColumns,
16487
+ fullWidth: 60,
16488
+ minWidth: 24
16489
+ });
16490
+ //#endregion
16444
16491
  //#region src/cli/utils/build-section-divider.ts
16445
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16492
+ const DIVIDER_INDENT = " ";
16493
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16446
16494
  //#endregion
16447
16495
  //#region src/cli/utils/indent-multiline-text.ts
16448
16496
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16602,7 +16650,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16602
16650
  endLine: isMultiSite ? cluster.endLine : void 0,
16603
16651
  rootDirectory: resolveSourceRoot(lead)
16604
16652
  }) : null;
16605
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16653
+ if (codeFrame) {
16654
+ const boxInnerWidth = resolveMeasureWidth(8);
16655
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16656
+ }
16606
16657
  const seenHints = /* @__PURE__ */ new Set();
16607
16658
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16608
16659
  seenHints.add(diagnostic.suppressionHint);
@@ -16620,8 +16671,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16620
16671
  const learnMoreLine = formatLearnMoreLine(representative);
16621
16672
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16622
16673
  }
16623
- if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16624
- if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16674
+ for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16675
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16625
16676
  if (renderEverySite && isAgentEnvironment) {
16626
16677
  const fixRecipeLine = formatFixRecipeLine(representative);
16627
16678
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16757,6 +16808,9 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
16757
16808
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
16758
16809
  return potentialScore.score;
16759
16810
  };
16811
+ //#endregion
16812
+ //#region src/cli/utils/filter-diagnostics-by-categories.ts
16813
+ const filterDiagnosticsByCategories = (diagnostics, categories) => categories.size === 0 ? [...diagnostics] : diagnostics.filter((diagnostic) => categories.has(diagnostic.category));
16760
16814
  const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16761
16815
  const FALSY_FLAG_VALUES = new Set([
16762
16816
  "",
@@ -16815,14 +16869,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16815
16869
  const RAINBOW_GRADIENT_WIDTH = 80;
16816
16870
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16817
16871
  const RAINBOW_OKLCH_CHROMA = .129;
16872
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16873
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16874
+ const getScoreBarWidth = () => resolveClampedWidth({
16875
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16876
+ fullWidth: 50,
16877
+ minWidth: 10
16878
+ });
16818
16879
  const buildScoreBarSegments = (filledCount) => {
16819
- const emptyCount = 50 - filledCount;
16880
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16820
16881
  return {
16821
16882
  filledSegment: "█".repeat(filledCount),
16822
16883
  emptySegment: "░".repeat(emptyCount)
16823
16884
  };
16824
16885
  };
16825
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16886
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16826
16887
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16827
16888
  const buildRawScoreBar = (displayScore) => {
16828
16889
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16858,10 +16919,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16858
16919
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16859
16920
  };
16860
16921
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16922
+ const barWidth = getScoreBarWidth();
16861
16923
  const currentFill = getFilledCount(currentScore);
16862
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16924
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16863
16925
  const gainCount = Math.max(0, potentialFill - currentFill);
16864
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16926
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16865
16927
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16866
16928
  };
16867
16929
  const getDoctorFace = (score) => {
@@ -16874,7 +16936,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16874
16936
  const buildRawFaceLines = (score) => {
16875
16937
  const [eyes, mouth] = getDoctorFace(score);
16876
16938
  return [
16877
- "┌─────┐",
16939
+ FACE_BOX_TOP_BORDER,
16878
16940
  `│ ${eyes} │`,
16879
16941
  `│ ${mouth} │`,
16880
16942
  "└─────┘"
@@ -17016,6 +17078,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17016
17078
  };
17017
17079
  //#endregion
17018
17080
  //#region src/cli/utils/render-summary.ts
17081
+ const FOOTER_DESCRIPTION_INDENT = " ";
17082
+ const printFooterDescription = (description) => Effect.gen(function* () {
17083
+ const wrapWidth = resolveMeasureWidth(2);
17084
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17085
+ });
17019
17086
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17020
17087
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17021
17088
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17035,14 +17102,14 @@ const printFooter = (input) => Effect.gen(function* () {
17035
17102
  if (!input.isOffline) {
17036
17103
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17037
17104
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17038
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17105
+ yield* printFooterDescription("Tell others how you did on socials");
17039
17106
  yield* Console.log("");
17040
17107
  }
17041
17108
  yield* Console.log(` ${highlighter.bold("Docs:")} ${highlighter.info(DOCS_URL)}`);
17042
- yield* Console.log(highlighter.dim(" Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file"));
17109
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17043
17110
  yield* Console.log("");
17044
17111
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17045
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17112
+ yield* printFooterDescription("Report issues and star the repository!");
17046
17113
  });
17047
17114
  const printSummary = (input) => Effect.gen(function* () {
17048
17115
  if (input.scoreResult) {
@@ -17174,11 +17241,47 @@ const resolveOxlintNodeEffect = (isLintEnabled, isQuiet) => Effect.gen(function*
17174
17241
  });
17175
17242
  const resolveOxlintNode = (isLintEnabled, isQuiet) => Effect.runPromise(resolveOxlintNodeEffect(isLintEnabled, isQuiet).pipe(Effect.provide(NodeResolver.layerNode)));
17176
17243
  //#endregion
17244
+ //#region src/cli/utils/cli-input-error.ts
17245
+ /**
17246
+ * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17247
+ * argument, mutually exclusive flags, or an unknown `--project` name. This is
17248
+ * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17249
+ * through `handleUserError`: a clean, single-line message with no Sentry
17250
+ * report and no "Something went wrong, open a prefilled issue" block.
17251
+ *
17252
+ * The `message` is rendered verbatim, so it must read as a complete,
17253
+ * human-readable sentence that tells the user how to fix their invocation.
17254
+ */
17255
+ var CliInputError = class extends Error {
17256
+ name = "CliInputError";
17257
+ };
17258
+ //#endregion
17259
+ //#region src/cli/utils/resolve-cli-categories.ts
17260
+ const categoryByLowercase = new Map(DIAGNOSTIC_CATEGORY_BUCKETS.map((category) => [category.toLowerCase(), category]));
17261
+ const knownCategoryList = DIAGNOSTIC_CATEGORY_BUCKETS.join(", ");
17262
+ const splitCategoryFlagValue = (value) => value.split(",").map((category) => category.trim()).filter((category) => category.length > 0);
17263
+ const resolveCliCategories = (categoryFlag) => {
17264
+ const rawCategoryValues = categoryFlag === void 0 ? [] : Array.isArray(categoryFlag) ? categoryFlag : [categoryFlag];
17265
+ const resolvedCategories = [];
17266
+ const seenCategories = /* @__PURE__ */ new Set();
17267
+ for (const rawCategoryValue of rawCategoryValues) for (const categoryQuery of splitCategoryFlagValue(rawCategoryValue)) {
17268
+ const matchedCategory = categoryByLowercase.get(categoryQuery.toLowerCase());
17269
+ if (matchedCategory === void 0) throw new CliInputError(`Unknown category "${categoryQuery}". Expected one of: ${knownCategoryList}.`);
17270
+ if (!seenCategories.has(matchedCategory)) {
17271
+ seenCategories.add(matchedCategory);
17272
+ resolvedCategories.push(matchedCategory);
17273
+ }
17274
+ }
17275
+ if (rawCategoryValues.length > 0 && resolvedCategories.length === 0) throw new CliInputError(`--category requires one of: ${knownCategoryList}.`);
17276
+ return resolvedCategories.length > 0 ? resolvedCategories : void 0;
17277
+ };
17278
+ //#endregion
17177
17279
  //#region src/inspect.ts
17178
17280
  const silentConsole = makeNoopConsole();
17179
17281
  const runConsole = (effect) => {
17180
17282
  Effect.runSync(effect);
17181
17283
  };
17284
+ const formatCategorySelection = (categoryFilters) => [...categoryFilters].join(", ");
17182
17285
  const buildIgnoredTags = (userConfig) => {
17183
17286
  const tags = /* @__PURE__ */ new Set();
17184
17287
  if (userConfig?.ignore?.tags) for (const tag of userConfig.ignore.tags) tags.add(tag);
@@ -17199,6 +17302,7 @@ const mergeInspectOptions = (inputOptions, userConfig) => ({
17199
17302
  share: userConfig?.share ?? true,
17200
17303
  respectInlineDisables: inputOptions.respectInlineDisables ?? userConfig?.respectInlineDisables ?? true,
17201
17304
  warnings: inputOptions.warnings ?? userConfig?.warnings ?? true,
17305
+ categoryFilters: new Set(resolveCliCategories(inputOptions.categoryFilters) ?? []),
17202
17306
  adoptExistingLintConfig: userConfig?.adoptExistingLintConfig ?? true,
17203
17307
  ignoredTags: buildIgnoredTags(userConfig),
17204
17308
  outputSurface: inputOptions.outputSurface ?? "cli",
@@ -17285,6 +17389,7 @@ const runBaselineComparison = async (params) => {
17285
17389
  hasConfigOverride: true,
17286
17390
  userConfig: params.userConfig,
17287
17391
  configSourceDirectory: null,
17392
+ projectInfoOverride: params.headProjectInfo,
17288
17393
  shouldSkipLint: !params.options.lint || !params.resolvedNodeBinaryPath,
17289
17394
  shouldRunDeadCode: false,
17290
17395
  shouldComputeScore: false,
@@ -17384,6 +17489,7 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
17384
17489
  directory,
17385
17490
  options,
17386
17491
  userConfig,
17492
+ headProjectInfo: output.project,
17387
17493
  headDiagnostics: output.diagnostics,
17388
17494
  resolvedNodeBinaryPath,
17389
17495
  baselineRef: options.baseline.ref
@@ -17482,14 +17588,16 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17482
17588
  const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
17483
17589
  const pause = onboardingSectionPause(animateRender);
17484
17590
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
17591
+ const printedDiagnostics = filterDiagnosticsByCategories(surfaceDiagnostics, options.categoryFilters);
17485
17592
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
17486
17593
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
17487
- if (surfaceDiagnostics.length === 0) {
17594
+ if (printedDiagnostics.length === 0) {
17488
17595
  yield* pause;
17489
17596
  if (hasSkippedChecks) {
17490
17597
  const skippedLabel = skippedChecks.join(" and ");
17491
17598
  yield* Console.warn(highlighter.warn(`No issues detected, but ${skippedLabel} checks failed — results are incomplete.`));
17492
- } else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17599
+ } else if (options.categoryFilters.size > 0) yield* Console.log(highlighter.success(`No issues found in category ${formatCategorySelection(options.categoryFilters)}!`));
17600
+ else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
17493
17601
  else yield* Console.log(highlighter.success("No issues found!"));
17494
17602
  yield* Console.log("");
17495
17603
  yield* pause;
@@ -17502,20 +17610,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17502
17610
  }
17503
17611
  yield* pause;
17504
17612
  yield* Console.log("");
17505
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17613
+ yield* printDiagnostics([...printedDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
17506
17614
  sectionPause: pause,
17507
17615
  animateCountUp: animateRender
17508
17616
  });
17509
17617
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
17510
- if (demotedDiagnosticCount > 0) {
17618
+ if (options.categoryFilters.size === 0 && demotedDiagnosticCount > 0) {
17511
17619
  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.`));
17512
17620
  yield* Console.log("");
17513
17621
  }
17514
- const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
17622
+ const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...printedDiagnostics], [...surfaceDiagnostics], score)) : null;
17515
17623
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
17516
17624
  yield* pause;
17517
17625
  yield* printSummary({
17518
- diagnostics: [...surfaceDiagnostics],
17626
+ diagnostics: [...printedDiagnostics],
17519
17627
  elapsedMilliseconds,
17520
17628
  scoreResult: score,
17521
17629
  potentialScore,
@@ -17531,7 +17639,7 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
17531
17639
  }
17532
17640
  yield* pause;
17533
17641
  yield* printFooter({
17534
- diagnostics: [...surfaceDiagnostics],
17642
+ diagnostics: [...printedDiagnostics],
17535
17643
  scoreResult: score,
17536
17644
  projectName: project.projectName,
17537
17645
  isOffline: !shouldShowShareLink
@@ -17662,21 +17770,6 @@ const handleUserError = (error, options = {}) => {
17662
17770
  process.exitCode = 1;
17663
17771
  };
17664
17772
  //#endregion
17665
- //#region src/cli/utils/cli-input-error.ts
17666
- /**
17667
- * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17668
- * argument, mutually exclusive flags, or an unknown `--project` name. This is
17669
- * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17670
- * through `handleUserError`: a clean, single-line message with no Sentry
17671
- * report and no "Something went wrong, open a prefilled issue" block.
17672
- *
17673
- * The `message` is rendered verbatim, so it must read as a complete,
17674
- * human-readable sentence that tells the user how to fix their invocation.
17675
- */
17676
- var CliInputError = class extends Error {
17677
- name = "CliInputError";
17678
- };
17679
- //#endregion
17680
17773
  //#region src/cli/utils/is-expected-user-error.ts
17681
17774
  /**
17682
17775
  * Whether `error` is an expected, user-actionable failure — the user's project
@@ -17948,190 +18041,24 @@ const installDoctorScript = (options) => {
17948
18041
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17949
18042
  };
17950
18043
  };
17951
- //#endregion
17952
- //#region src/cli/utils/install-agent-hooks.ts
17953
- const CLAUDE_AGENT = "claude-code";
17954
- const CURSOR_AGENT = "cursor";
17955
- const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
17956
- const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
17957
- const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
17958
- const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
17959
- const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
17960
- const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
17961
- const CURSOR_HOOKS_SCHEMA_VERSION = 1;
17962
- const JSON_INDENT_SPACES$1 = 2;
17963
- const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
17964
- const readJsonFile = (filePath, fallback) => {
17965
- if (!fs$1.existsSync(filePath)) return fallback;
17966
- const content = fs$1.readFileSync(filePath, "utf8").trim();
17967
- if (content.length === 0) return fallback;
17968
- return JSON.parse(content);
17969
- };
17970
- const writeJsonFile = (filePath, value) => {
17971
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
17972
- fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
17973
- };
17974
- const writeHookScript = (filePath) => {
17975
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
17976
- fs$1.writeFileSync(filePath, buildAgentHookScript());
17977
- fs$1.chmodSync(filePath, 493);
17978
- };
17979
- const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
17980
- const installClaudeHook = (projectRoot) => {
17981
- const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
17982
- const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
17983
- const settings = readJsonFile(settingsPath, {});
17984
- const hooks = { ...settings.hooks ?? {} };
17985
- const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
17986
- if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
17987
- type: "command",
17988
- command: CLAUDE_HOOK_COMMAND
17989
- }] });
17990
- hooks.PostToolBatch = postToolBatchHooks;
17991
- writeJsonFile(settingsPath, {
17992
- ...settings,
17993
- hooks
17994
- });
17995
- writeHookScript(hookPath);
17996
- return [settingsPath, hookPath];
17997
- };
17998
- const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
17999
- const installCursorHook = (projectRoot) => {
18000
- const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18001
- const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18002
- const config = readJsonFile(configPath, {});
18003
- const hooks = { ...config.hooks ?? {} };
18004
- const postToolUseHooks = [...hooks.postToolUse ?? []];
18005
- if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18006
- command: CURSOR_HOOK_RELATIVE_PATH,
18007
- matcher: CURSOR_HOOK_MATCHER,
18008
- timeout: 120
18009
- });
18010
- hooks.postToolUse = postToolUseHooks;
18011
- writeJsonFile(configPath, {
18012
- ...config,
18013
- version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18014
- hooks
18015
- });
18016
- writeHookScript(hookPath);
18017
- return [configPath, hookPath];
18044
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18045
+ const scriptName = scriptResult.scriptName ?? "doctor";
18046
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18047
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18048
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18049
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18050
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18051
+ return "Skipped package script: package.json missing or invalid.";
18018
18052
  };
18019
- const buildAgentHookScript = () => [
18020
- "#!/bin/sh",
18021
- "set -u",
18022
- "",
18023
- "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18024
- "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18025
- "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18026
- "cat > \"$input_file\"",
18027
- "",
18028
- "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18029
- "project_root=${CLAUDE_PROJECT_DIR:-}",
18030
- "if [ -z \"$project_root\" ]; then",
18031
- " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18032
- "fi",
18033
- "if ! cd \"$project_root\"; then",
18034
- " exit 0",
18035
- "fi",
18036
- "",
18037
- "should_scan() {",
18038
- " if ! command -v node >/dev/null 2>&1; then",
18039
- " return 0",
18040
- " fi",
18041
- "",
18042
- " node - \"$input_file\" <<'NODE'",
18043
- "const fs = require('node:fs');",
18044
- "const inputPath = process.argv[2];",
18045
- "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18046
- "try {",
18047
- " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18048
- " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18049
- " if (eventName === 'PostToolBatch') {",
18050
- " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18051
- " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18052
- " }",
18053
- " const toolName = input.tool_name || input.toolName || input.tool;",
18054
- " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18055
- "} catch {",
18056
- " process.exit(0);",
18057
- "}",
18058
- "NODE",
18059
- "}",
18060
- "",
18061
- "run_react_doctor() {",
18062
- " if [ -x ./node_modules/.bin/react-doctor ]; then",
18063
- " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18064
- " return",
18065
- " fi",
18066
- "",
18067
- " if command -v react-doctor >/dev/null 2>&1; then",
18068
- " react-doctor --verbose --diff --blocking warning --no-score",
18069
- " return",
18070
- " fi",
18071
- "",
18072
- " if command -v pnpm >/dev/null 2>&1; then",
18073
- " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18074
- " return",
18075
- " fi",
18076
- "",
18077
- " if command -v npx >/dev/null 2>&1; then",
18078
- " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18079
- " return",
18080
- " fi",
18081
- "",
18082
- " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18083
- " return 0",
18084
- "}",
18085
- "",
18086
- "if ! should_scan; then",
18087
- " exit 0",
18088
- "fi",
18089
- "",
18090
- "if run_react_doctor > \"$output_file\" 2>&1; then",
18091
- " exit 0",
18092
- "fi",
18093
- "",
18094
- "node - \"$input_file\" \"$output_file\" <<'NODE'",
18095
- "const fs = require('node:fs');",
18096
- "const inputPath = process.argv[2];",
18097
- "const outputPath = process.argv[3];",
18098
- "const readInput = () => {",
18099
- " try {",
18100
- " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18101
- " } catch {",
18102
- " return {};",
18103
- " }",
18104
- "};",
18105
- "const input = readInput();",
18106
- "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18107
- "if (!scanOutput) process.exit(0);",
18108
- "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}`;",
18109
- "if (input.hook_event_name === 'PostToolBatch') {",
18110
- " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18111
- "} else {",
18112
- " console.log(JSON.stringify({ additional_context: message }));",
18113
- "}",
18114
- "NODE",
18115
- ""
18116
- ].join("\n");
18117
- const installReactDoctorAgentHooks = (options) => {
18118
- const installedAgents = [];
18119
- const files = [];
18120
- const requestedAgents = options.agents.filter(isSupportedAgent);
18121
- for (const agent of requestedAgents) {
18122
- if (agent === CLAUDE_AGENT) {
18123
- files.push(...installClaudeHook(options.projectRoot));
18124
- installedAgents.push(agent);
18125
- }
18126
- if (agent === CURSOR_AGENT) {
18127
- files.push(...installCursorHook(options.projectRoot));
18128
- installedAgents.push(agent);
18129
- }
18053
+ const installReactDoctorScriptStep = (projectRoot) => {
18054
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18055
+ try {
18056
+ const scriptResult = installDoctorScript({ projectRoot });
18057
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18058
+ } catch (error) {
18059
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18060
+ throw error;
18130
18061
  }
18131
- return {
18132
- installedAgents,
18133
- files
18134
- };
18135
18062
  };
18136
18063
  //#endregion
18137
18064
  //#region src/cli/utils/install-github-workflow.ts
@@ -18144,37 +18071,20 @@ const buildWorkflowContent = () => `# React Doctor — finds security, performan
18144
18071
  name: React Doctor
18145
18072
 
18146
18073
  on:
18074
+ # 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.
18147
18075
  pull_request:
18148
18076
  types: [opened, synchronize, reopened, ready_for_review]
18149
- # Scans \`main\` on every push so you get a health-score trend on the
18150
- # default branch — useful for tracking the overall number commit-by-commit
18151
- # and catching regressions that slipped past PR review. PR-specific steps
18152
- # (the sticky summary comment) are skipped automatically on \`push\` events.
18153
- # Comment this block out if you only want PR-time scans.
18077
+ # Scans \`main\` on every push to track the health-score trend and catch regressions that slipped past PR review.
18154
18078
  push:
18155
18079
  branches: [main]
18156
18080
 
18157
18081
  permissions:
18158
- # \`actions/checkout\` needs this to read the repo source.
18159
18082
  contents: read
18160
- # Two uses: (1) reads the PR's changed-file list so the scan only checks
18161
- # what the PR touched (faster, scoped to the diff), and (2) posts/updates
18162
- # the sticky React Doctor summary comment on the PR. Downgrade \`write\` to
18163
- # \`read\` to keep the changed-file scan but disable comment posting.
18164
18083
  pull-requests: write
18165
- # The sticky-comment step uses GitHub's \`issues.createComment\` /
18166
- # \`issues.updateComment\` endpoints — those are the same APIs that back PR
18167
- # comments (PRs are issues under the hood). Not exercised on \`push\`
18168
- # events, so safe to drop if you only run on \`main\`.
18169
18084
  issues: write
18170
- # Lets the action publish a commit status with the score + error/warning
18171
- # counts (links to the run). This is how a \`push\` to \`main\` surfaces its
18172
- # result, since the PR comment is skipped off pull requests. Drop it to
18173
- # disable the status (or set \`commit-status: false\` below).
18174
18085
  statuses: write
18175
18086
 
18176
- # Cancels any in-flight scan for the same PR (or branch, on push) the moment
18177
- # a new commit arrives, so reviewers only ever see the latest run.
18087
+ # 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.
18178
18088
  concurrency:
18179
18089
  group: react-doctor-\${{ github.event.pull_request.number || github.ref }}
18180
18090
  cancel-in-progress: true
@@ -18241,1074 +18151,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18241
18151
  };
18242
18152
  }
18243
18153
  };
18244
- //#endregion
18245
- //#region src/cli/utils/report-workflow-result.ts
18246
- const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18247
- if (result.status === "failed") {
18248
- workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18249
- return false;
18250
- }
18251
- if (result.status === "exists") {
18252
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18253
- return false;
18154
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18155
+ const workflow = readReactDoctorWorkflow(projectRoot);
18156
+ if (!workflow) return {
18157
+ status: "not-needed",
18158
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18159
+ };
18160
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18161
+ if (!changed) return {
18162
+ status: "not-needed",
18163
+ workflowPath: workflow.workflowPath
18164
+ };
18165
+ try {
18166
+ fs$1.writeFileSync(workflow.workflowPath, content);
18167
+ return {
18168
+ status: "upgraded",
18169
+ workflowPath: workflow.workflowPath
18170
+ };
18171
+ } catch {
18172
+ return {
18173
+ status: "failed",
18174
+ workflowPath: workflow.workflowPath
18175
+ };
18254
18176
  }
18255
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18256
- recordCount(METRIC.installWorkflow, 1);
18257
- return true;
18258
18177
  };
18259
18178
  //#endregion
18260
- //#region src/cli/utils/install-git-hook-file.ts
18261
- const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18262
- const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18263
- 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?)`);
18264
- const SHEBANG = "#!/bin/sh";
18265
- const SHEBANG_PREFIX = "#!";
18266
- const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18267
- const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18268
- const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18269
- const buildReactDoctorHookBlock = () => [
18270
- REACT_DOCTOR_BLOCK_START,
18271
- "react_doctor_scan_staged_files() {",
18272
- ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18273
- ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18274
- " return",
18275
- " fi",
18276
- "",
18277
- " if command -v react-doctor >/dev/null 2>&1; then",
18278
- ` ${REACT_DOCTOR_COMMAND}`,
18279
- " return",
18280
- " fi",
18281
- "",
18282
- " if command -v pnpm >/dev/null 2>&1; then",
18283
- ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18284
- " return",
18285
- " fi",
18286
- "",
18287
- " if command -v npx >/dev/null 2>&1; then",
18288
- ` ${NPX_REACT_DOCTOR_COMMAND}`,
18289
- " return",
18290
- " fi",
18291
- "",
18292
- " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18293
- "}",
18294
- "",
18295
- "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18296
- "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18297
- " rm -f \"$react_doctor_output\"",
18298
- "else",
18299
- " rm -f \"$react_doctor_output\"",
18300
- ` 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`,
18301
- "fi",
18302
- REACT_DOCTOR_BLOCK_END
18303
- ].join("\n");
18304
- const mergeHookContent = (existingContent) => {
18305
- const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18306
- if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18307
- if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18308
- const normalizedExistingContent = ensureTrailingNewline(existingContent);
18309
- if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18310
- const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18311
- return [
18312
- shebangLine,
18313
- "",
18314
- hookBlock.trimEnd(),
18315
- ...remainingLines
18316
- ].join("\n");
18179
+ //#region src/cli/utils/hash-project-root.ts
18180
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18181
+ //#endregion
18182
+ //#region src/cli/utils/action-upgrade-prompt.ts
18183
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18184
+ const getActionUpgradeStore = (options = {}) => new Conf({
18185
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18186
+ cwd: options.cwd
18187
+ });
18188
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18189
+ try {
18190
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18191
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18192
+ } catch {
18193
+ return true;
18317
18194
  }
18318
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18319
18195
  };
18320
- const removeLegacyManagedRunner = (projectRoot) => {
18321
- const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18322
- fs$1.rmSync(runnerPath, { force: true });
18323
- for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18324
- fs$1.rmdirSync(directory);
18325
- } catch {}
18196
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18197
+ try {
18198
+ const store = getActionUpgradeStore(storeOptions);
18199
+ const upgrades = store.get("actionUpgrades", {});
18200
+ store.set("actionUpgrades", {
18201
+ ...upgrades,
18202
+ [hashProjectRoot(projectRoot)]: {
18203
+ rootDirectory: path$1.resolve(projectRoot),
18204
+ outcome,
18205
+ at: (/* @__PURE__ */ new Date()).toISOString()
18206
+ }
18207
+ });
18208
+ return true;
18209
+ } catch {
18210
+ return false;
18211
+ }
18326
18212
  };
18327
- const installDirectGitHook = (options) => {
18328
- const didHookExist = fs$1.existsSync(options.hookPath);
18329
- const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18330
- if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18331
- "config",
18332
- "core.hooksPath",
18333
- options.hooksPathConfig
18334
- ]);
18335
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18336
- fs$1.writeFileSync(options.hookPath, nextContent);
18337
- fs$1.chmodSync(options.hookPath, 493);
18338
- removeLegacyManagedRunner(options.projectRoot);
18213
+ //#endregion
18214
+ //#region src/cli/utils/open-url.ts
18215
+ const resolveOpenCommand = (url) => {
18216
+ if (process$1.platform === "darwin") return {
18217
+ command: "open",
18218
+ args: [url]
18219
+ };
18220
+ if (process$1.platform === "win32") return {
18221
+ command: "cmd",
18222
+ args: [
18223
+ "/c",
18224
+ "start",
18225
+ "",
18226
+ url
18227
+ ]
18228
+ };
18339
18229
  return {
18340
- hookPath: options.hookPath,
18341
- kind: options.kind ?? "git",
18342
- status: didHookExist ? "updated" : "created"
18230
+ command: "xdg-open",
18231
+ args: [url]
18343
18232
  };
18344
18233
  };
18345
- //#endregion
18346
- //#region src/cli/utils/install-git-hook-config-managers.ts
18347
- const appendStringCommand = (existingCommand) => {
18348
- const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18349
- return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18350
- };
18351
- const appendArrayCommand = (existingCommands) => {
18352
- const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18353
- return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18234
+ const openUrl = (url) => {
18235
+ try {
18236
+ const { command, args } = resolveOpenCommand(url);
18237
+ const child = spawn(command, args, {
18238
+ detached: true,
18239
+ stdio: "ignore"
18240
+ });
18241
+ child.on("error", () => {});
18242
+ child.unref();
18243
+ return true;
18244
+ } catch {
18245
+ return false;
18246
+ }
18354
18247
  };
18355
- const installPackageJsonHook = (options, strategy) => {
18356
- const packageJsonPath = getPackageJsonPath(options.projectRoot);
18357
- const didHookExist = fs$1.existsSync(packageJsonPath);
18358
- const packageJson = readPackageJson(options.projectRoot);
18359
- const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18360
- const parentKeys = strategy.path.slice(0, -1);
18361
- const leafKey = strategy.path[strategy.path.length - 1];
18362
- let parent = nextPackageJson;
18363
- for (const key of parentKeys) {
18364
- const existing = parent[key];
18365
- const cloned = isRecord(existing) ? { ...existing } : {};
18366
- parent[key] = cloned;
18367
- parent = cloned;
18248
+ //#endregion
18249
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18250
+ const CI_YES_CHOICE = "ci-yes";
18251
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18252
+ const CI_NO_CHOICE = "ci-no";
18253
+ const SGR_BOLD_OFF = "\x1B[22m";
18254
+ const ciQuestionMessage = [
18255
+ "Add React Doctor to GitHub Actions?",
18256
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18257
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18258
+ ].join("\n");
18259
+ const askAddToGitHubActions = async (prompt = prompts) => {
18260
+ while (true) {
18261
+ const { ciChoice } = await prompt({
18262
+ type: "select",
18263
+ name: "ciChoice",
18264
+ message: ciQuestionMessage,
18265
+ hint: " ",
18266
+ choices: [
18267
+ {
18268
+ title: "Yes",
18269
+ description: "Adds the workflow file and a doctor package script",
18270
+ value: CI_YES_CHOICE
18271
+ },
18272
+ {
18273
+ title: "Learn more",
18274
+ description: "Opens the docs page in your browser",
18275
+ value: CI_LEARN_MORE_CHOICE
18276
+ },
18277
+ {
18278
+ title: "No",
18279
+ description: "Skip for now",
18280
+ value: CI_NO_CHOICE
18281
+ }
18282
+ ],
18283
+ initial: 0
18284
+ }, { onCancel: () => true });
18285
+ if (ciChoice === void 0) return "cancel";
18286
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18287
+ if (ciChoice === CI_NO_CHOICE) return "no";
18288
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18289
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18290
+ cliLogger.break();
18368
18291
  }
18369
- parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18370
- writeJsonFile$1(packageJsonPath, nextPackageJson);
18371
- removeLegacyManagedRunner(options.projectRoot);
18372
- return {
18373
- hookPath: packageJsonPath,
18374
- kind: strategy.kind,
18375
- status: didHookExist ? "updated" : "created"
18376
- };
18377
18292
  };
18378
- const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18379
- kind: "simple-git-hooks",
18380
- path: ["simple-git-hooks", "pre-commit"],
18381
- leafShape: "string"
18382
- });
18383
- const installGhooks = (options) => installPackageJsonHook(options, {
18384
- kind: "ghooks",
18385
- path: [
18386
- "config",
18387
- "ghooks",
18388
- "pre-commit"
18389
- ],
18390
- leafShape: "string"
18391
- });
18392
- const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18393
- kind: "pre-commit-npm",
18394
- path: ["pre-commit"],
18395
- leafShape: "array"
18396
- });
18397
- const installPrettyQuick = (options) => installPackageJsonHook(options, {
18398
- kind: "pretty-quick",
18399
- path: ["gitHooks", "pre-commit"],
18400
- leafShape: "string"
18401
- });
18402
- const installYorkie = (options) => installPackageJsonHook(options, {
18403
- kind: "yorkie",
18404
- path: ["gitHooks", "pre-commit"],
18405
- leafShape: "string"
18406
- });
18407
- const installGitHooksJs = (options) => installPackageJsonHook(options, {
18408
- kind: "git-hooks-js",
18409
- path: ["git-hooks", "pre-commit"],
18410
- leafShape: "string"
18411
- });
18412
- const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18413
- const normalizedContent = ensureTrailingNewline(content);
18414
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18415
- if (match === null) return ensureTrailingNewline([
18416
- normalizedContent.trimEnd(),
18417
- "",
18418
- `${sectionName}:`,
18419
- ...block,
18420
- ""
18421
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18422
- const sectionStartIndex = match.index;
18423
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18424
- nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18425
- let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18426
- while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18427
- const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18428
- const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18429
- const suffix = normalizedContent.slice(insertIndex);
18430
- return ensureTrailingNewline([
18431
- prefix,
18432
- ...block,
18433
- suffix.trimStart()
18434
- ].join("\n"));
18435
- };
18436
- const findTopLevelSectionRange = (content, sectionName) => {
18437
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18438
- if (match === null) return null;
18439
- const headerLineEndIndex = content.indexOf("\n", match.index);
18440
- const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18441
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18442
- nextSectionPattern.lastIndex = headerEndIndex;
18443
- return {
18444
- headerEndIndex,
18445
- contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18446
- };
18447
- };
18448
- const appendLefthookCommand = (content) => {
18449
- const normalizedContent = ensureTrailingNewline(content);
18450
- const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18451
- const reactDoctorCommandBlock = [
18452
- " react-doctor:",
18453
- ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18454
- ""
18455
- ];
18456
- if (sectionRange === null) return ensureTrailingNewline([
18457
- normalizedContent.trimEnd(),
18458
- "",
18459
- "pre-commit:",
18460
- " commands:",
18461
- ...reactDoctorCommandBlock
18462
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18463
- const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18464
- const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18465
- const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18466
- const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18467
- return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18468
- };
18469
- const installLefthook = (options) => {
18470
- const didHookExist = fs$1.existsSync(options.hookPath);
18471
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18472
- if (!existingContent.includes("react-doctor")) {
18473
- const nextContent = appendLefthookCommand(existingContent);
18474
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18475
- fs$1.writeFileSync(options.hookPath, nextContent);
18476
- }
18477
- removeLegacyManagedRunner(options.projectRoot);
18478
- return {
18479
- hookPath: options.hookPath,
18480
- kind: "lefthook",
18481
- status: didHookExist ? "updated" : "created"
18482
- };
18293
+ //#endregion
18294
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18295
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18296
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18297
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18298
+ const { upgradeChoice } = await prompt({
18299
+ type: "select",
18300
+ name: "upgradeChoice",
18301
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18302
+ hint: " ",
18303
+ choices: [{
18304
+ title: "Yes (recommended)",
18305
+ description: "Bump the workflow to millionco/react-doctor@v2",
18306
+ value: UPGRADE_YES_CHOICE
18307
+ }, {
18308
+ title: "No, thanks",
18309
+ description: "Keep @v1 — won't ask again for this repo",
18310
+ value: UPGRADE_NO_CHOICE
18311
+ }],
18312
+ initial: 0
18313
+ }, { onCancel: () => true });
18314
+ if (upgradeChoice === void 0) return "cancel";
18315
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18483
18316
  };
18484
- const installPreCommit = (options) => {
18485
- const didHookExist = fs$1.existsSync(options.hookPath);
18486
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18487
- if (!existingContent.includes("id: react-doctor")) {
18488
- const hasReposKey = /^repos:\s*$/m.test(existingContent);
18489
- const localHookBlock = [
18490
- " - repo: local",
18491
- " hooks:",
18492
- " - id: react-doctor",
18493
- " name: react-doctor",
18494
- ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18495
- " language: system",
18496
- " pass_filenames: false",
18497
- ""
18498
- ].join("\n");
18499
- const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18500
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18501
- fs$1.writeFileSync(options.hookPath, nextContent);
18317
+ //#endregion
18318
+ //#region src/cli/utils/open-workflow-pull-request.ts
18319
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18320
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18321
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18322
+ 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.
18323
+
18324
+ Docs: https://www.react.doctor/ci`;
18325
+ const execFileAsync$1 = promisify(execFile);
18326
+ const run = async (command, args, cwd) => {
18327
+ try {
18328
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18329
+ cwd,
18330
+ encoding: "utf8"
18331
+ });
18332
+ return {
18333
+ success: true,
18334
+ stdout: stdout.trim(),
18335
+ stderr: stderr.trim()
18336
+ };
18337
+ } catch (error) {
18338
+ const failure = error;
18339
+ return {
18340
+ success: false,
18341
+ stdout: (failure.stdout ?? "").trim(),
18342
+ stderr: (failure.stderr ?? "").trim()
18343
+ };
18502
18344
  }
18503
- removeLegacyManagedRunner(options.projectRoot);
18504
- return {
18505
- hookPath: options.hookPath,
18506
- kind: "pre-commit",
18507
- status: didHookExist ? "updated" : "created"
18508
- };
18509
18345
  };
18510
- const installOvercommit = (options) => {
18511
- const didHookExist = fs$1.existsSync(options.hookPath);
18512
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18513
- if (!existingContent.includes("ReactDoctor")) {
18514
- const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18515
- " ReactDoctor:",
18516
- " enabled: true",
18517
- ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18518
- ""
18519
- ]);
18520
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18521
- fs$1.writeFileSync(options.hookPath, nextContent);
18346
+ const detectDefaultBranch = async (cwd) => {
18347
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18348
+ if (symRef.success) {
18349
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18350
+ if (branchMatch) return branchMatch[1];
18522
18351
  }
18523
- removeLegacyManagedRunner(options.projectRoot);
18524
- return {
18525
- hookPath: options.hookPath,
18526
- kind: "overcommit",
18527
- status: didHookExist ? "updated" : "created"
18528
- };
18529
- };
18530
- //#endregion
18531
- //#region src/cli/utils/install-git-hook.ts
18532
- const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18533
- const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18534
- const isSimpleGitHooksProject = (projectRoot) => {
18535
- const packageJson = readPackageJson(projectRoot);
18536
- return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
18352
+ if ((await run("git", [
18353
+ "rev-parse",
18354
+ "--verify",
18355
+ "origin/main"
18356
+ ], cwd)).success) return "main";
18357
+ if ((await run("git", [
18358
+ "rev-parse",
18359
+ "--verify",
18360
+ "origin/master"
18361
+ ], cwd)).success) return "master";
18362
+ return null;
18537
18363
  };
18538
- const getLefthookConfigPath = (projectRoot) => {
18539
- for (const fileName of LEFTHOOK_CONFIG_FILES) {
18540
- const filePath = path$1.join(projectRoot, fileName);
18541
- if (fs$1.existsSync(filePath)) return filePath;
18542
- }
18543
- return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
18364
+ const findUniqueBranchName = async (cwd) => {
18365
+ if (!(await run("git", [
18366
+ "rev-parse",
18367
+ "--verify",
18368
+ NEW_BRANCH_PREFIX
18369
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18370
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18544
18371
  };
18545
- const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18546
- const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18547
- const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18548
- const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
18549
- const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
18550
- const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
18551
- const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
18552
- const detectGitHookTarget = (projectRoot) => {
18553
- if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
18554
- const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
18555
- const configuredHooksPath = runGit(projectRoot, [
18556
- "config",
18557
- "--path",
18558
- "--get",
18559
- "core.hooksPath"
18560
- ]);
18561
- if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
18562
- hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
18563
- runnerRoot: topLevel,
18564
- kind: "configured"
18565
- };
18566
- if (isHuskyProject(topLevel)) return {
18567
- hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
18568
- runnerRoot: topLevel,
18569
- kind: "husky",
18570
- hooksPathConfig: HUSKY_HOOKS_PATH
18372
+ const openWorkflowPullRequest = async (params) => {
18373
+ const workflowPath = path$1.resolve(params.workflowPath);
18374
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18375
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18376
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18377
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18378
+ if (!repoRootProbe.success) return {
18379
+ status: "not-attempted",
18380
+ reason: "not-a-git-repo"
18571
18381
  };
18572
- if (isVitePlusProject(topLevel)) return {
18573
- hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
18574
- runnerRoot: topLevel,
18575
- kind: "vite-plus",
18576
- hooksPathConfig: VITE_PLUS_HOOKS_PATH
18382
+ const cwd = repoRootProbe.stdout;
18383
+ if (!isCommandAvailable("gh")) return {
18384
+ status: "not-attempted",
18385
+ reason: "gh-not-installed"
18577
18386
  };
18578
- if (isSimpleGitHooksProject(topLevel)) return {
18579
- hookPath: path$1.join(topLevel, "package.json"),
18580
- runnerRoot: topLevel,
18581
- kind: "simple-git-hooks"
18387
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18388
+ status: "not-attempted",
18389
+ reason: "gh-not-authenticated"
18582
18390
  };
18583
- const lefthookConfigPath = getLefthookConfigPath(topLevel);
18584
- if (lefthookConfigPath !== null) return {
18585
- hookPath: lefthookConfigPath,
18586
- runnerRoot: topLevel,
18587
- kind: "lefthook"
18391
+ const defaultBranch = await detectDefaultBranch(cwd);
18392
+ if (!defaultBranch) return {
18393
+ status: "not-attempted",
18394
+ reason: "no-default-branch"
18588
18395
  };
18589
- if (isPreCommitProject(topLevel)) return {
18590
- hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
18591
- runnerRoot: topLevel,
18592
- kind: "pre-commit"
18593
- };
18594
- if (isOvercommitProject(topLevel)) return {
18595
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18596
- runnerRoot: topLevel,
18597
- kind: "overcommit"
18598
- };
18599
- if (isYorkieProject(topLevel)) return {
18600
- hookPath: getPackageJsonPath(topLevel),
18601
- runnerRoot: topLevel,
18602
- kind: "yorkie"
18603
- };
18604
- if (isGhooksProject(topLevel)) return {
18605
- hookPath: getPackageJsonPath(topLevel),
18606
- runnerRoot: topLevel,
18607
- kind: "ghooks"
18396
+ const previousBranchProbe = await run("git", [
18397
+ "rev-parse",
18398
+ "--abbrev-ref",
18399
+ "HEAD"
18400
+ ], cwd);
18401
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18402
+ status: "not-attempted",
18403
+ reason: "detached-head"
18608
18404
  };
18609
- if (isGitHooksJsProject(topLevel)) return {
18610
- hookPath: getPackageJsonPath(topLevel),
18611
- runnerRoot: topLevel,
18612
- kind: "git-hooks-js"
18405
+ const previousBranch = previousBranchProbe.stdout;
18406
+ await run("git", [
18407
+ "fetch",
18408
+ "origin",
18409
+ defaultBranch
18410
+ ], cwd);
18411
+ const newBranch = await findUniqueBranchName(cwd);
18412
+ if (!(await run("git", [
18413
+ "checkout",
18414
+ "-b",
18415
+ newBranch,
18416
+ `origin/${defaultBranch}`
18417
+ ], cwd)).success) return {
18418
+ status: "not-attempted",
18419
+ reason: "checkout-failed"
18613
18420
  };
18614
- if (isPreCommitNpmProject(topLevel)) return {
18615
- hookPath: getPackageJsonPath(topLevel),
18616
- runnerRoot: topLevel,
18617
- kind: "pre-commit-npm"
18421
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18422
+ await run("git", ["checkout", previousBranch], cwd);
18423
+ if (deleteNewBranch) await run("git", [
18424
+ "branch",
18425
+ "-D",
18426
+ newBranch
18427
+ ], cwd);
18618
18428
  };
18619
- if (isPrettyQuickProject(topLevel)) return {
18620
- hookPath: getPackageJsonPath(topLevel),
18621
- runnerRoot: topLevel,
18622
- kind: "pretty-quick"
18429
+ if (!(await run("git", [
18430
+ "add",
18431
+ "--",
18432
+ path$1.relative(cwd, workflowPath)
18433
+ ], cwd)).success) {
18434
+ await restoreToPreviousBranch(true);
18435
+ return {
18436
+ status: "not-attempted",
18437
+ reason: "git-add-failed"
18438
+ };
18439
+ }
18440
+ if (!(await run("git", [
18441
+ "commit",
18442
+ "-m",
18443
+ commitMessage
18444
+ ], cwd)).success) {
18445
+ await restoreToPreviousBranch(true);
18446
+ return {
18447
+ status: "not-attempted",
18448
+ reason: "git-commit-failed"
18449
+ };
18450
+ }
18451
+ if (!(await run("git", [
18452
+ "push",
18453
+ "-u",
18454
+ "origin",
18455
+ newBranch
18456
+ ], cwd)).success) {
18457
+ await restoreToPreviousBranch(true);
18458
+ return {
18459
+ status: "not-attempted",
18460
+ reason: "git-push-failed"
18461
+ };
18462
+ }
18463
+ const prCreate = await run("gh", [
18464
+ "pr",
18465
+ "create",
18466
+ "--title",
18467
+ prTitle,
18468
+ "--body",
18469
+ prBody,
18470
+ "--base",
18471
+ defaultBranch,
18472
+ "--head",
18473
+ newBranch
18474
+ ], cwd);
18475
+ await restoreToPreviousBranch(false);
18476
+ if (!prCreate.success) return {
18477
+ status: "branch-pushed",
18478
+ branch: newBranch
18623
18479
  };
18624
- const hookPath = runGit(projectRoot, [
18625
- "rev-parse",
18626
- "--git-path",
18627
- HOOK_RELATIVE_PATH
18628
- ]);
18629
- if (hookPath === null || hookPath.length === 0) return null;
18630
18480
  return {
18631
- hookPath: resolveGitPath(projectRoot, hookPath),
18632
- runnerRoot: topLevel,
18633
- kind: "git"
18481
+ status: "pr-opened",
18482
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18634
18483
  };
18635
18484
  };
18636
- const installReactDoctorGitHook = (options) => {
18637
- if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
18638
- if (options.kind === "lefthook") return installLefthook(options);
18639
- if (options.kind === "pre-commit") return installPreCommit(options);
18640
- if (options.kind === "overcommit") return installOvercommit(options);
18641
- if (options.kind === "yorkie") return installYorkie(options);
18642
- if (options.kind === "ghooks") return installGhooks(options);
18643
- if (options.kind === "git-hooks-js") return installGitHooksJs(options);
18644
- if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
18645
- if (options.kind === "pretty-quick") return installPrettyQuick(options);
18646
- return installDirectGitHook(options);
18485
+ const stageWorkflowFile = async (params) => {
18486
+ const workflowPath = path$1.resolve(params.workflowPath);
18487
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18488
+ if (!repoRootProbe.success) return false;
18489
+ return (await run("git", [
18490
+ "add",
18491
+ "--",
18492
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18493
+ ], repoRootProbe.stdout)).success;
18647
18494
  };
18648
18495
  //#endregion
18649
- //#region src/cli/utils/should-skip-prompts.ts
18650
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18651
- //#endregion
18652
- //#region src/cli/utils/install-react-doctor.ts
18653
- const SETUP_OPTION_GIT_HOOK = "git-hook";
18654
- const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
18655
- const SETUP_OPTION_WORKFLOW = "workflow";
18656
- const SETUP_OPTION_SKIP = "skip";
18657
- const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
18658
- "ghooks",
18659
- "git-hooks-js",
18660
- "lefthook",
18661
- "overcommit",
18662
- "pre-commit",
18663
- "pre-commit-npm",
18664
- "pretty-quick",
18665
- "simple-git-hooks",
18666
- "yorkie"
18667
- ]);
18668
- const PACKAGE_MANAGER_LOCKFILES = [
18669
- {
18670
- packageManager: "pnpm",
18671
- fileName: "pnpm-lock.yaml"
18672
- },
18673
- {
18674
- packageManager: "yarn",
18675
- fileName: "yarn.lock"
18676
- },
18677
- {
18678
- packageManager: "bun",
18679
- fileName: "bun.lockb"
18680
- },
18681
- {
18682
- packageManager: "bun",
18683
- fileName: "bun.lock"
18684
- },
18685
- {
18686
- packageManager: "npm",
18687
- fileName: "package-lock.json"
18496
+ //#region src/cli/utils/report-workflow-result.ts
18497
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18498
+ if (result.status === "failed") {
18499
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18500
+ return false;
18688
18501
  }
18689
- ];
18690
- const findNearestFileDirectory = (startDirectory, fileNames) => {
18691
- let currentDirectory = path$1.resolve(startDirectory);
18692
- while (true) {
18693
- if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
18694
- const parentDirectory = path$1.dirname(currentDirectory);
18695
- if (parentDirectory === currentDirectory) return null;
18696
- currentDirectory = parentDirectory;
18502
+ if (result.status === "exists") {
18503
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18504
+ return false;
18697
18505
  }
18506
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18507
+ recordCount(METRIC.installWorkflow, 1);
18508
+ return true;
18698
18509
  };
18699
- const detectPackageManager = (projectRoot) => {
18700
- let currentDirectory = path$1.resolve(projectRoot);
18701
- while (true) {
18702
- const packageJson = readPackageJson(currentDirectory);
18703
- if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
18704
- const packageManagerName = packageJson.packageManager.split("@")[0];
18705
- if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
18510
+ //#endregion
18511
+ //#region src/cli/utils/set-up-github-actions.ts
18512
+ const setUpGitHubActions = async (options) => {
18513
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18514
+ try {
18515
+ installReactDoctorScriptStep(projectRoot);
18516
+ } catch {}
18517
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18518
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18519
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18520
+ cliLogger.break();
18521
+ if (workflowResult.status === "failed") {
18522
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18523
+ return false;
18524
+ }
18525
+ if (workflowResult.status === "created") {
18526
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18527
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18528
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18529
+ 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}`);
18530
+ else {
18531
+ pullRequestSpinner.stop();
18532
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18533
+ 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.");
18706
18534
  }
18707
- const parentDirectory = path$1.dirname(currentDirectory);
18708
- if (parentDirectory === currentDirectory) break;
18709
- currentDirectory = parentDirectory;
18710
18535
  }
18711
- const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
18712
- return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
18536
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18537
+ return didCreateWorkflow;
18713
18538
  };
18714
- const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
18715
- const buildInstallCommand = (projectRoot) => {
18716
- const packageManager = detectPackageManager(projectRoot);
18717
- const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
18718
- if (packageManager === "npm") return {
18719
- command: "npm",
18720
- args: [
18721
- "install",
18722
- "--save-dev",
18723
- packageSpecifier
18724
- ],
18725
- cwd: projectRoot
18726
- };
18727
- if (packageManager === "yarn") return {
18728
- command: "yarn",
18729
- args: [
18730
- "add",
18731
- "--dev",
18732
- packageSpecifier
18733
- ],
18734
- cwd: projectRoot
18735
- };
18736
- if (packageManager === "bun") return {
18737
- command: "bun",
18738
- args: [
18739
- "add",
18740
- "--dev",
18741
- packageSpecifier
18742
- ],
18743
- cwd: projectRoot
18744
- };
18745
- return {
18746
- command: "pnpm",
18747
- args: [
18748
- "add",
18749
- "--save-dev",
18750
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18751
- packageSpecifier
18752
- ],
18753
- cwd: projectRoot
18754
- };
18539
+ //#endregion
18540
+ //#region src/cli/utils/install-agent-hooks.ts
18541
+ const CLAUDE_AGENT = "claude-code";
18542
+ const CURSOR_AGENT = "cursor";
18543
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18544
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18545
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18546
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18547
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18548
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18549
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18550
+ const JSON_INDENT_SPACES$1 = 2;
18551
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18552
+ const readJsonFile = (filePath, fallback) => {
18553
+ if (!fs$1.existsSync(filePath)) return fallback;
18554
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18555
+ if (content.length === 0) return fallback;
18556
+ return JSON.parse(content);
18755
18557
  };
18756
- const execFileAsync$1 = promisify(execFile);
18757
- const defaultInstallDependencyRunner = async (input) => {
18758
- await execFileAsync$1(input.command, [...input.args], {
18759
- cwd: input.cwd,
18760
- env: {
18761
- ...process.env,
18762
- REACT_DOCTOR_INSTALL: "1"
18763
- },
18764
- shell: process.platform === "win32"
18558
+ const writeJsonFile = (filePath, value) => {
18559
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18560
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18561
+ };
18562
+ const writeHookScript = (filePath) => {
18563
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18564
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18565
+ fs$1.chmodSync(filePath, 493);
18566
+ };
18567
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18568
+ const installClaudeHook = (projectRoot) => {
18569
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18570
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18571
+ const settings = readJsonFile(settingsPath, {});
18572
+ const hooks = { ...settings.hooks ?? {} };
18573
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18574
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18575
+ type: "command",
18576
+ command: CLAUDE_HOOK_COMMAND
18577
+ }] });
18578
+ hooks.PostToolBatch = postToolBatchHooks;
18579
+ writeJsonFile(settingsPath, {
18580
+ ...settings,
18581
+ hooks
18765
18582
  });
18583
+ writeHookScript(hookPath);
18584
+ return [settingsPath, hookPath];
18766
18585
  };
18767
- const isSupplyChainTrustError = (error) => {
18768
- const candidate = error;
18769
- const haystack = [
18770
- candidate?.stderr,
18771
- candidate?.stdout,
18772
- candidate?.message
18773
- ].map((part) => String(part ?? "")).join("\n");
18774
- return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
18586
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18587
+ const installCursorHook = (projectRoot) => {
18588
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18589
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18590
+ const config = readJsonFile(configPath, {});
18591
+ const hooks = { ...config.hooks ?? {} };
18592
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18593
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18594
+ command: CURSOR_HOOK_RELATIVE_PATH,
18595
+ matcher: CURSOR_HOOK_MATCHER,
18596
+ timeout: 120
18597
+ });
18598
+ hooks.postToolUse = postToolUseHooks;
18599
+ writeJsonFile(configPath, {
18600
+ ...config,
18601
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18602
+ hooks
18603
+ });
18604
+ writeHookScript(hookPath);
18605
+ return [configPath, hookPath];
18775
18606
  };
18776
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18777
- const installReactDoctorDependency = async (options) => {
18778
- const packageJson = readPackageJson(options.projectRoot);
18779
- if (!isRecord(packageJson)) return {
18780
- dependencyStatus: "skipped",
18781
- dependencyReason: "missing-or-invalid-package-json"
18782
- };
18783
- if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
18784
- if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
18785
- dependencyStatus: "skipped",
18786
- dependencyReason: "invalid-dev-dependencies"
18787
- };
18788
- const runnerInput = buildInstallCommand(options.projectRoot);
18789
- try {
18790
- await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
18791
- } catch (error) {
18792
- return {
18793
- dependencyStatus: "skipped",
18794
- dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
18795
- installCommand: formatInstallCommand(runnerInput)
18796
- };
18607
+ const buildAgentHookScript = () => [
18608
+ "#!/bin/sh",
18609
+ "set -u",
18610
+ "",
18611
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18612
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18613
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18614
+ "cat > \"$input_file\"",
18615
+ "",
18616
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18617
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18618
+ "if [ -z \"$project_root\" ]; then",
18619
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18620
+ "fi",
18621
+ "if ! cd \"$project_root\"; then",
18622
+ " exit 0",
18623
+ "fi",
18624
+ "",
18625
+ "should_scan() {",
18626
+ " if ! command -v node >/dev/null 2>&1; then",
18627
+ " return 0",
18628
+ " fi",
18629
+ "",
18630
+ " node - \"$input_file\" <<'NODE'",
18631
+ "const fs = require('node:fs');",
18632
+ "const inputPath = process.argv[2];",
18633
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18634
+ "try {",
18635
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18636
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18637
+ " if (eventName === 'PostToolBatch') {",
18638
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18639
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18640
+ " }",
18641
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18642
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18643
+ "} catch {",
18644
+ " process.exit(0);",
18645
+ "}",
18646
+ "NODE",
18647
+ "}",
18648
+ "",
18649
+ "run_react_doctor() {",
18650
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18651
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18652
+ " return",
18653
+ " fi",
18654
+ "",
18655
+ " if command -v react-doctor >/dev/null 2>&1; then",
18656
+ " react-doctor --verbose --diff --blocking warning --no-score",
18657
+ " return",
18658
+ " fi",
18659
+ "",
18660
+ " if command -v pnpm >/dev/null 2>&1; then",
18661
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18662
+ " return",
18663
+ " fi",
18664
+ "",
18665
+ " if command -v npx >/dev/null 2>&1; then",
18666
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18667
+ " return",
18668
+ " fi",
18669
+ "",
18670
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18671
+ " return 0",
18672
+ "}",
18673
+ "",
18674
+ "if ! should_scan; then",
18675
+ " exit 0",
18676
+ "fi",
18677
+ "",
18678
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18679
+ " exit 0",
18680
+ "fi",
18681
+ "",
18682
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
18683
+ "const fs = require('node:fs');",
18684
+ "const inputPath = process.argv[2];",
18685
+ "const outputPath = process.argv[3];",
18686
+ "const readInput = () => {",
18687
+ " try {",
18688
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18689
+ " } catch {",
18690
+ " return {};",
18691
+ " }",
18692
+ "};",
18693
+ "const input = readInput();",
18694
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18695
+ "if (!scanOutput) process.exit(0);",
18696
+ "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}`;",
18697
+ "if (input.hook_event_name === 'PostToolBatch') {",
18698
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18699
+ "} else {",
18700
+ " console.log(JSON.stringify({ additional_context: message }));",
18701
+ "}",
18702
+ "NODE",
18703
+ ""
18704
+ ].join("\n");
18705
+ const installReactDoctorAgentHooks = (options) => {
18706
+ const installedAgents = [];
18707
+ const files = [];
18708
+ const requestedAgents = options.agents.filter(isSupportedAgent);
18709
+ for (const agent of requestedAgents) {
18710
+ if (agent === CLAUDE_AGENT) {
18711
+ files.push(...installClaudeHook(options.projectRoot));
18712
+ installedAgents.push(agent);
18713
+ }
18714
+ if (agent === CURSOR_AGENT) {
18715
+ files.push(...installCursorHook(options.projectRoot));
18716
+ installedAgents.push(agent);
18717
+ }
18797
18718
  }
18798
- return { dependencyStatus: "created" };
18719
+ return {
18720
+ installedAgents,
18721
+ files
18722
+ };
18799
18723
  };
18800
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18801
- hookPath,
18802
- runnerRoot: projectRoot,
18803
- kind: "git"
18804
- });
18805
- const formatGitHookInstallMessage = (hookResult) => {
18806
- 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.`;
18807
- return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
18724
+ //#endregion
18725
+ //#region src/cli/utils/install-git-hook-file.ts
18726
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18727
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18728
+ 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?)`);
18729
+ const SHEBANG = "#!/bin/sh";
18730
+ const SHEBANG_PREFIX = "#!";
18731
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18732
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18733
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18734
+ const buildReactDoctorHookBlock = () => [
18735
+ REACT_DOCTOR_BLOCK_START,
18736
+ "react_doctor_scan_staged_files() {",
18737
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18738
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18739
+ " return",
18740
+ " fi",
18741
+ "",
18742
+ " if command -v react-doctor >/dev/null 2>&1; then",
18743
+ ` ${REACT_DOCTOR_COMMAND}`,
18744
+ " return",
18745
+ " fi",
18746
+ "",
18747
+ " if command -v pnpm >/dev/null 2>&1; then",
18748
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18749
+ " return",
18750
+ " fi",
18751
+ "",
18752
+ " if command -v npx >/dev/null 2>&1; then",
18753
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
18754
+ " return",
18755
+ " fi",
18756
+ "",
18757
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18758
+ "}",
18759
+ "",
18760
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18761
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18762
+ " rm -f \"$react_doctor_output\"",
18763
+ "else",
18764
+ " rm -f \"$react_doctor_output\"",
18765
+ ` 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`,
18766
+ "fi",
18767
+ REACT_DOCTOR_BLOCK_END
18768
+ ].join("\n");
18769
+ const mergeHookContent = (existingContent) => {
18770
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18771
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18772
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18773
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
18774
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18775
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18776
+ return [
18777
+ shebangLine,
18778
+ "",
18779
+ hookBlock.trimEnd(),
18780
+ ...remainingLines
18781
+ ].join("\n");
18782
+ }
18783
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18808
18784
  };
18809
- const formatDoctorScriptInstallMessage = (scriptResult) => {
18810
- const messages = [];
18811
- const scriptName = scriptResult.scriptName ?? "doctor";
18812
- if (scriptResult.scriptStatus === "created") messages.push(`Added package script: ${scriptName}.`);
18813
- else if (scriptResult.scriptStatus === "existing") messages.push(`Package script already exists: ${scriptName}.`);
18814
- else if (scriptResult.scriptReason === "script-names-taken") messages.push("Skipped package script: doctor and react-doctor are already taken.");
18815
- else if (scriptResult.scriptReason === "doctor-script-taken") messages.push("Skipped package script: doctor and react-doctor scripts already exist.");
18816
- else if (scriptResult.scriptReason === "invalid-scripts") messages.push(`Skipped package script: scripts field is not an object.`);
18817
- else messages.push("Skipped package script: package.json missing or invalid.");
18818
- return messages.join(" ");
18785
+ const removeLegacyManagedRunner = (projectRoot) => {
18786
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18787
+ fs$1.rmSync(runnerPath, { force: true });
18788
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18789
+ fs$1.rmdirSync(directory);
18790
+ } catch {}
18819
18791
  };
18820
- const formatDependencyInstallMessage = (result) => {
18821
- if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
18822
- if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
18823
- if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
18824
- 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).";
18825
- if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
18826
- return "Skipped dev dependency install: package.json missing or invalid.";
18792
+ const installDirectGitHook = (options) => {
18793
+ const didHookExist = fs$1.existsSync(options.hookPath);
18794
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18795
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18796
+ "config",
18797
+ "core.hooksPath",
18798
+ options.hooksPathConfig
18799
+ ]);
18800
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18801
+ fs$1.writeFileSync(options.hookPath, nextContent);
18802
+ fs$1.chmodSync(options.hookPath, 493);
18803
+ removeLegacyManagedRunner(options.projectRoot);
18804
+ return {
18805
+ hookPath: options.hookPath,
18806
+ kind: options.kind ?? "git",
18807
+ status: didHookExist ? "updated" : "created"
18808
+ };
18827
18809
  };
18828
- const buildDependencyFollowUp = (result) => {
18829
- if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
18830
- return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
18810
+ //#endregion
18811
+ //#region src/cli/utils/install-git-hook-config-managers.ts
18812
+ const appendStringCommand = (existingCommand) => {
18813
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18814
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18831
18815
  };
18832
- const installReactDoctorScriptStep = (projectRoot) => {
18833
- const scriptSpinner = spinner("Installing React Doctor package script...").start();
18834
- try {
18835
- const scriptResult = installDoctorScript({ projectRoot });
18836
- scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18837
- } catch (error) {
18838
- scriptSpinner.fail("Failed to install React Doctor package script.");
18839
- throw error;
18840
- }
18816
+ const appendArrayCommand = (existingCommands) => {
18817
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18818
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18841
18819
  };
18842
- const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
18843
- installReactDoctorScriptStep(projectRoot);
18844
- const dependencySpinner = spinner("Installing React Doctor package...").start();
18845
- try {
18846
- const dependencyResult = await installReactDoctorDependency({
18847
- projectRoot,
18848
- runner: dependencyRunner
18849
- });
18850
- recordCount(METRIC.installDependency, 1, {
18851
- status: dependencyResult.dependencyStatus,
18852
- reason: dependencyResult.dependencyReason ?? null,
18853
- packageManager: detectPackageManager(projectRoot)
18854
- });
18855
- if (dependencyResult.dependencyStatus === "skipped") {
18856
- const message = formatDependencyInstallMessage(dependencyResult);
18857
- if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
18858
- else dependencySpinner.fail(message);
18859
- const followUp = buildDependencyFollowUp(dependencyResult);
18860
- if (followUp !== void 0) cliLogger.dim(followUp);
18861
- return dependencyResult;
18862
- }
18863
- dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
18864
- return dependencyResult;
18865
- } catch (error) {
18866
- dependencySpinner.fail("Failed to install React Doctor package.");
18867
- throw error;
18820
+ const installPackageJsonHook = (options, strategy) => {
18821
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
18822
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18823
+ const packageJson = readPackageJson(options.projectRoot);
18824
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18825
+ const parentKeys = strategy.path.slice(0, -1);
18826
+ const leafKey = strategy.path[strategy.path.length - 1];
18827
+ let parent = nextPackageJson;
18828
+ for (const key of parentKeys) {
18829
+ const existing = parent[key];
18830
+ const cloned = isRecord(existing) ? { ...existing } : {};
18831
+ parent[key] = cloned;
18832
+ parent = cloned;
18868
18833
  }
18834
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18835
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
18836
+ removeLegacyManagedRunner(options.projectRoot);
18837
+ return {
18838
+ hookPath: packageJsonPath,
18839
+ kind: strategy.kind,
18840
+ status: didHookExist ? "updated" : "created"
18841
+ };
18869
18842
  };
18870
- const getSkillSourceDirectory = () => {
18871
- const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18872
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18843
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18844
+ kind: "simple-git-hooks",
18845
+ path: ["simple-git-hooks", "pre-commit"],
18846
+ leafShape: "string"
18847
+ });
18848
+ const installGhooks = (options) => installPackageJsonHook(options, {
18849
+ kind: "ghooks",
18850
+ path: [
18851
+ "config",
18852
+ "ghooks",
18853
+ "pre-commit"
18854
+ ],
18855
+ leafShape: "string"
18856
+ });
18857
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18858
+ kind: "pre-commit-npm",
18859
+ path: ["pre-commit"],
18860
+ leafShape: "array"
18861
+ });
18862
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
18863
+ kind: "pretty-quick",
18864
+ path: ["gitHooks", "pre-commit"],
18865
+ leafShape: "string"
18866
+ });
18867
+ const installYorkie = (options) => installPackageJsonHook(options, {
18868
+ kind: "yorkie",
18869
+ path: ["gitHooks", "pre-commit"],
18870
+ leafShape: "string"
18871
+ });
18872
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
18873
+ kind: "git-hooks-js",
18874
+ path: ["git-hooks", "pre-commit"],
18875
+ leafShape: "string"
18876
+ });
18877
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18878
+ const normalizedContent = ensureTrailingNewline(content);
18879
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18880
+ if (match === null) return ensureTrailingNewline([
18881
+ normalizedContent.trimEnd(),
18882
+ "",
18883
+ `${sectionName}:`,
18884
+ ...block,
18885
+ ""
18886
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18887
+ const sectionStartIndex = match.index;
18888
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18889
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18890
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18891
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18892
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18893
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18894
+ const suffix = normalizedContent.slice(insertIndex);
18895
+ return ensureTrailingNewline([
18896
+ prefix,
18897
+ ...block,
18898
+ suffix.trimStart()
18899
+ ].join("\n"));
18873
18900
  };
18874
- const findBundledSiblingSkills = (primarySkillDir) => {
18875
- const skillsParent = path$1.dirname(primarySkillDir);
18876
- if (!fs$1.existsSync(skillsParent)) return [];
18877
- const resolvedPrimary = path$1.resolve(primarySkillDir);
18878
- return fs$1.readdirSync(skillsParent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => ({
18879
- name: entry.name,
18880
- source: path$1.join(skillsParent, entry.name)
18881
- })).filter((sibling) => path$1.resolve(sibling.source) !== resolvedPrimary && fs$1.existsSync(path$1.join(sibling.source, SKILL_MANIFEST_FILE)));
18882
- };
18883
- const installBundledSiblingSkills = async (primarySkillDir, agents, projectRoot) => {
18884
- const installedSkillNames = [];
18885
- for (const sibling of findBundledSiblingSkills(primarySkillDir)) {
18886
- const result = await installSkillsFromSource({
18887
- source: sibling.source,
18888
- agents: [...agents],
18889
- cwd: projectRoot,
18890
- mode: "copy"
18891
- });
18892
- if (result.failed.length > 0) throw new Error(result.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
18893
- if (result.skills.length > 0) installedSkillNames.push(sibling.name);
18894
- }
18895
- return installedSkillNames;
18901
+ const findTopLevelSectionRange = (content, sectionName) => {
18902
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18903
+ if (match === null) return null;
18904
+ const headerLineEndIndex = content.indexOf("\n", match.index);
18905
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18906
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18907
+ nextSectionPattern.lastIndex = headerEndIndex;
18908
+ return {
18909
+ headerEndIndex,
18910
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18911
+ };
18896
18912
  };
18897
- const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
18898
- const runInstallReactDoctor = async (options = {}) => {
18899
- const requestedProjectRoot = options.projectRoot ?? process.cwd();
18900
- const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
18901
- const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
18902
- if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
18903
- cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
18904
- process.exitCode = 1;
18905
- return;
18906
- }
18907
- const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
18908
- if (detectedAgents.length === 0) {
18909
- cliLogger.error("No supported coding agents detected.");
18910
- cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
18911
- cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
18912
- process.exitCode = 1;
18913
- return;
18914
- }
18915
- const skipPrompts = shouldSkipPrompts({ yes: options.yes });
18916
- const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
18917
- const gitHookPath = gitHookTarget?.hookPath;
18918
- const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
18919
- const prompt = options.prompt ?? prompts;
18920
- const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
18921
- type: "multiselect",
18922
- name: "agents",
18923
- message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
18924
- choices: detectedAgents.map((agent) => ({
18925
- title: getSkillAgentConfig(agent).displayName,
18926
- value: agent,
18927
- selected: true
18928
- })),
18929
- instructions: false,
18930
- min: 1
18931
- }, promptOptions)).agents ?? [];
18932
- if (selectedAgents.length === 0) return;
18933
- const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
18934
- const canInstallWorkflow = !isReactDoctorWorkflowInstalled(projectRoot);
18935
- const setupActionChoices = [
18936
- ...gitHookPath === null || gitHookPath === void 0 ? [] : [{
18937
- title: "Pre-commit hook",
18938
- description: "Check staged changes before each commit",
18939
- value: SETUP_OPTION_GIT_HOOK,
18940
- selected: true
18941
- }],
18942
- ...canInstallNativeAgentHooks(selectedAgents) ? [{
18943
- title: "Agent hooks",
18944
- description: "Ask Claude Code or Cursor to scan after code edits",
18945
- value: SETUP_OPTION_AGENT_HOOKS,
18946
- selected: Boolean(options.agentHooks)
18947
- }] : [],
18948
- ...canInstallWorkflow ? [{
18949
- title: "GitHub Actions workflow",
18950
- description: "Scan pull requests in CI",
18951
- value: SETUP_OPTION_WORKFLOW,
18952
- selected: true
18953
- }] : []
18913
+ const appendLefthookCommand = (content) => {
18914
+ const normalizedContent = ensureTrailingNewline(content);
18915
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18916
+ const reactDoctorCommandBlock = [
18917
+ " react-doctor:",
18918
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18919
+ ""
18954
18920
  ];
18955
- const setupChoices = setupActionChoices.length === 0 ? [] : [{
18956
- title: "Skip optional setup",
18957
- description: "Install only the agent skill and package setup",
18958
- value: SETUP_OPTION_SKIP,
18959
- selected: false
18960
- }, ...setupActionChoices];
18961
- const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
18962
- type: "multiselect",
18963
- name: "setupOptions",
18964
- message: "Select additional React Doctor setup:",
18965
- choices: setupChoices,
18966
- instructions: false
18967
- }, promptOptions)).setupOptions ?? [];
18968
- const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
18969
- const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
18970
- const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
18971
- const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
18972
- const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_WORKFLOW));
18973
- if (options.dryRun) {
18974
- cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
18975
- for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
18976
- cliLogger.dim(` Source: ${sourceDir}`);
18977
- for (const sibling of findBundledSiblingSkills(sourceDir)) cliLogger.dim(` Also installs skill: ${sibling.name}`);
18978
- cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
18979
- cliLogger.dim(" Dev dependency: react-doctor");
18980
- if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
18981
- if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
18982
- if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
18983
- return;
18984
- }
18985
- const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
18986
- try {
18987
- const installResult = await installSkillsFromSource({
18988
- source: sourceDir,
18989
- agents: selectedAgents,
18990
- cwd: projectRoot,
18991
- mode: "copy"
18992
- });
18993
- if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
18994
- if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
18995
- installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
18996
- } catch (error) {
18997
- installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
18998
- throw error;
18999
- }
19000
- try {
19001
- const installedSiblingSkills = await installBundledSiblingSkills(sourceDir, selectedAgents, projectRoot);
19002
- if (installedSiblingSkills.length > 0) cliLogger.dim(` Also installed the ${installedSiblingSkills.join(", ")} skill.`);
19003
- } catch {
19004
- cliLogger.dim(" Skipped bundled sibling skills (install error).");
18921
+ if (sectionRange === null) return ensureTrailingNewline([
18922
+ normalizedContent.trimEnd(),
18923
+ "",
18924
+ "pre-commit:",
18925
+ " commands:",
18926
+ ...reactDoctorCommandBlock
18927
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18928
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18929
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18930
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18931
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18932
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18933
+ };
18934
+ const installLefthook = (options) => {
18935
+ const didHookExist = fs$1.existsSync(options.hookPath);
18936
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18937
+ if (!existingContent.includes("react-doctor")) {
18938
+ const nextContent = appendLefthookCommand(existingContent);
18939
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18940
+ fs$1.writeFileSync(options.hookPath, nextContent);
19005
18941
  }
19006
- const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19007
- if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
19008
- const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19009
- try {
19010
- const hookResult = installReactDoctorGitHook({
19011
- hookPath: gitHookTarget.hookPath,
19012
- projectRoot: gitHookTarget.runnerRoot,
19013
- kind: gitHookTarget.kind,
19014
- hooksPathConfig: gitHookTarget.hooksPathConfig
19015
- });
19016
- hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19017
- recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19018
- } catch (error) {
19019
- hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19020
- throw error;
19021
- }
18942
+ removeLegacyManagedRunner(options.projectRoot);
18943
+ return {
18944
+ hookPath: options.hookPath,
18945
+ kind: "lefthook",
18946
+ status: didHookExist ? "updated" : "created"
18947
+ };
18948
+ };
18949
+ const installPreCommit = (options) => {
18950
+ const didHookExist = fs$1.existsSync(options.hookPath);
18951
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18952
+ if (!existingContent.includes("id: react-doctor")) {
18953
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
18954
+ const localHookBlock = [
18955
+ " - repo: local",
18956
+ " hooks:",
18957
+ " - id: react-doctor",
18958
+ " name: react-doctor",
18959
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18960
+ " language: system",
18961
+ " pass_filenames: false",
18962
+ ""
18963
+ ].join("\n");
18964
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18965
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18966
+ fs$1.writeFileSync(options.hookPath, nextContent);
19022
18967
  }
19023
- if (shouldInstallAgentHooks) {
19024
- const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19025
- try {
19026
- const hookResult = installReactDoctorAgentHooks({
19027
- projectRoot,
19028
- agents: selectedAgents
19029
- });
19030
- if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19031
- else {
19032
- hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19033
- recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19034
- }
19035
- } catch (error) {
19036
- hookSpinner.fail("Failed to install React Doctor agent hooks.");
19037
- throw error;
19038
- }
18968
+ removeLegacyManagedRunner(options.projectRoot);
18969
+ return {
18970
+ hookPath: options.hookPath,
18971
+ kind: "pre-commit",
18972
+ status: didHookExist ? "updated" : "created"
18973
+ };
18974
+ };
18975
+ const installOvercommit = (options) => {
18976
+ const didHookExist = fs$1.existsSync(options.hookPath);
18977
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18978
+ if (!existingContent.includes("ReactDoctor")) {
18979
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18980
+ " ReactDoctor:",
18981
+ " enabled: true",
18982
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18983
+ ""
18984
+ ]);
18985
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18986
+ fs$1.writeFileSync(options.hookPath, nextContent);
19039
18987
  }
19040
- let didInstallWorkflow = false;
19041
- if (shouldInstallWorkflow) didInstallWorkflow = reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19042
- recordCount(METRIC.installCompleted, 1, {
19043
- agentsCount: selectedAgents.length,
19044
- gitHook: shouldInstallGitHook,
19045
- agentHooks: shouldInstallAgentHooks,
19046
- workflow: didInstallWorkflow,
19047
- dependencyStatus: dependencyResult.dependencyStatus,
19048
- packageManager: detectPackageManager(projectRoot)
19049
- });
19050
- for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
18988
+ removeLegacyManagedRunner(options.projectRoot);
18989
+ return {
18990
+ hookPath: options.hookPath,
18991
+ kind: "overcommit",
18992
+ status: didHookExist ? "updated" : "created"
18993
+ };
19051
18994
  };
19052
18995
  //#endregion
19053
- //#region src/cli/utils/hash-project-root.ts
19054
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19055
- //#endregion
19056
- //#region src/cli/utils/action-upgrade-prompt.ts
19057
- const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
19058
- const getActionUpgradeStore = (options = {}) => new Conf({
19059
- projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
19060
- cwd: options.cwd
19061
- });
19062
- const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
19063
- try {
19064
- const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
19065
- return Boolean(upgrades[hashProjectRoot(projectRoot)]);
19066
- } catch {
19067
- return true;
19068
- }
18996
+ //#region src/cli/utils/install-git-hook.ts
18997
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18998
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18999
+ const isSimpleGitHooksProject = (projectRoot) => {
19000
+ const packageJson = readPackageJson(projectRoot);
19001
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19069
19002
  };
19070
- const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
19071
- try {
19072
- const store = getActionUpgradeStore(storeOptions);
19073
- const upgrades = store.get("actionUpgrades", {});
19074
- store.set("actionUpgrades", {
19075
- ...upgrades,
19076
- [hashProjectRoot(projectRoot)]: {
19077
- rootDirectory: path$1.resolve(projectRoot),
19078
- outcome,
19079
- at: (/* @__PURE__ */ new Date()).toISOString()
19080
- }
19081
- });
19082
- return true;
19083
- } catch {
19084
- return false;
19003
+ const getLefthookConfigPath = (projectRoot) => {
19004
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
19005
+ const filePath = path$1.join(projectRoot, fileName);
19006
+ if (fs$1.existsSync(filePath)) return filePath;
19085
19007
  }
19008
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19086
19009
  };
19087
- //#endregion
19088
- //#region src/cli/utils/install-skill-for-agent.ts
19089
- const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19090
- const source = getSkillSourceDirectory();
19091
- if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19092
- const result = await installSkillsFromSource({
19093
- source,
19094
- agents: [agent],
19095
- cwd: projectRoot,
19096
- mode: "copy"
19097
- });
19098
- return result.skills.length > 0 && result.failed.length === 0;
19010
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
19011
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
19012
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
19013
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
19014
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
19015
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
19016
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
19017
+ const detectGitHookTarget = (projectRoot) => {
19018
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
19019
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
19020
+ const configuredHooksPath = runGit(projectRoot, [
19021
+ "config",
19022
+ "--path",
19023
+ "--get",
19024
+ "core.hooksPath"
19025
+ ]);
19026
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
19027
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
19028
+ runnerRoot: topLevel,
19029
+ kind: "configured"
19030
+ };
19031
+ if (isHuskyProject(topLevel)) return {
19032
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19033
+ runnerRoot: topLevel,
19034
+ kind: "husky",
19035
+ hooksPathConfig: HUSKY_HOOKS_PATH
19036
+ };
19037
+ if (isVitePlusProject(topLevel)) return {
19038
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19039
+ runnerRoot: topLevel,
19040
+ kind: "vite-plus",
19041
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19042
+ };
19043
+ if (isSimpleGitHooksProject(topLevel)) return {
19044
+ hookPath: path$1.join(topLevel, "package.json"),
19045
+ runnerRoot: topLevel,
19046
+ kind: "simple-git-hooks"
19047
+ };
19048
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19049
+ if (lefthookConfigPath !== null) return {
19050
+ hookPath: lefthookConfigPath,
19051
+ runnerRoot: topLevel,
19052
+ kind: "lefthook"
19053
+ };
19054
+ if (isPreCommitProject(topLevel)) return {
19055
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19056
+ runnerRoot: topLevel,
19057
+ kind: "pre-commit"
19058
+ };
19059
+ if (isOvercommitProject(topLevel)) return {
19060
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19061
+ runnerRoot: topLevel,
19062
+ kind: "overcommit"
19063
+ };
19064
+ if (isYorkieProject(topLevel)) return {
19065
+ hookPath: getPackageJsonPath(topLevel),
19066
+ runnerRoot: topLevel,
19067
+ kind: "yorkie"
19068
+ };
19069
+ if (isGhooksProject(topLevel)) return {
19070
+ hookPath: getPackageJsonPath(topLevel),
19071
+ runnerRoot: topLevel,
19072
+ kind: "ghooks"
19073
+ };
19074
+ if (isGitHooksJsProject(topLevel)) return {
19075
+ hookPath: getPackageJsonPath(topLevel),
19076
+ runnerRoot: topLevel,
19077
+ kind: "git-hooks-js"
19078
+ };
19079
+ if (isPreCommitNpmProject(topLevel)) return {
19080
+ hookPath: getPackageJsonPath(topLevel),
19081
+ runnerRoot: topLevel,
19082
+ kind: "pre-commit-npm"
19083
+ };
19084
+ if (isPrettyQuickProject(topLevel)) return {
19085
+ hookPath: getPackageJsonPath(topLevel),
19086
+ runnerRoot: topLevel,
19087
+ kind: "pretty-quick"
19088
+ };
19089
+ const hookPath = runGit(projectRoot, [
19090
+ "rev-parse",
19091
+ "--git-path",
19092
+ HOOK_RELATIVE_PATH
19093
+ ]);
19094
+ if (hookPath === null || hookPath.length === 0) return null;
19095
+ return {
19096
+ hookPath: resolveGitPath(projectRoot, hookPath),
19097
+ runnerRoot: topLevel,
19098
+ kind: "git"
19099
+ };
19100
+ };
19101
+ const installReactDoctorGitHook = (options) => {
19102
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19103
+ if (options.kind === "lefthook") return installLefthook(options);
19104
+ if (options.kind === "pre-commit") return installPreCommit(options);
19105
+ if (options.kind === "overcommit") return installOvercommit(options);
19106
+ if (options.kind === "yorkie") return installYorkie(options);
19107
+ if (options.kind === "ghooks") return installGhooks(options);
19108
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19109
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19110
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19111
+ return installDirectGitHook(options);
19099
19112
  };
19100
19113
  //#endregion
19101
- //#region src/cli/utils/open-url.ts
19102
- const resolveOpenCommand = (url) => {
19103
- if (process$1.platform === "darwin") return {
19104
- command: "open",
19105
- args: [url]
19114
+ //#region src/cli/utils/should-skip-prompts.ts
19115
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19116
+ //#endregion
19117
+ //#region src/cli/utils/install-react-doctor.ts
19118
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19119
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19120
+ const SETUP_OPTION_SKIP = "skip";
19121
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19122
+ "ghooks",
19123
+ "git-hooks-js",
19124
+ "lefthook",
19125
+ "overcommit",
19126
+ "pre-commit",
19127
+ "pre-commit-npm",
19128
+ "pretty-quick",
19129
+ "simple-git-hooks",
19130
+ "yorkie"
19131
+ ]);
19132
+ const PACKAGE_MANAGER_LOCKFILES = [
19133
+ {
19134
+ packageManager: "pnpm",
19135
+ fileName: "pnpm-lock.yaml"
19136
+ },
19137
+ {
19138
+ packageManager: "yarn",
19139
+ fileName: "yarn.lock"
19140
+ },
19141
+ {
19142
+ packageManager: "bun",
19143
+ fileName: "bun.lockb"
19144
+ },
19145
+ {
19146
+ packageManager: "bun",
19147
+ fileName: "bun.lock"
19148
+ },
19149
+ {
19150
+ packageManager: "npm",
19151
+ fileName: "package-lock.json"
19152
+ }
19153
+ ];
19154
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19155
+ let currentDirectory = path$1.resolve(startDirectory);
19156
+ while (true) {
19157
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19158
+ const parentDirectory = path$1.dirname(currentDirectory);
19159
+ if (parentDirectory === currentDirectory) return null;
19160
+ currentDirectory = parentDirectory;
19161
+ }
19162
+ };
19163
+ const detectPackageManager = (projectRoot) => {
19164
+ let currentDirectory = path$1.resolve(projectRoot);
19165
+ while (true) {
19166
+ const packageJson = readPackageJson(currentDirectory);
19167
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19168
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19169
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19170
+ }
19171
+ const parentDirectory = path$1.dirname(currentDirectory);
19172
+ if (parentDirectory === currentDirectory) break;
19173
+ currentDirectory = parentDirectory;
19174
+ }
19175
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19176
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19177
+ };
19178
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19179
+ const buildInstallCommand = (projectRoot) => {
19180
+ const packageManager = detectPackageManager(projectRoot);
19181
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19182
+ if (packageManager === "npm") return {
19183
+ command: "npm",
19184
+ args: [
19185
+ "install",
19186
+ "--save-dev",
19187
+ packageSpecifier
19188
+ ],
19189
+ cwd: projectRoot
19190
+ };
19191
+ if (packageManager === "yarn") return {
19192
+ command: "yarn",
19193
+ args: [
19194
+ "add",
19195
+ "--dev",
19196
+ packageSpecifier
19197
+ ],
19198
+ cwd: projectRoot
19106
19199
  };
19107
- if (process$1.platform === "win32") return {
19108
- command: "cmd",
19200
+ if (packageManager === "bun") return {
19201
+ command: "bun",
19109
19202
  args: [
19110
- "/c",
19111
- "start",
19112
- "",
19113
- url
19114
- ]
19203
+ "add",
19204
+ "--dev",
19205
+ packageSpecifier
19206
+ ],
19207
+ cwd: projectRoot
19115
19208
  };
19116
19209
  return {
19117
- command: "xdg-open",
19118
- args: [url]
19210
+ command: "pnpm",
19211
+ args: [
19212
+ "add",
19213
+ "--save-dev",
19214
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19215
+ packageSpecifier
19216
+ ],
19217
+ cwd: projectRoot
19119
19218
  };
19120
19219
  };
19121
- const openUrl = (url) => {
19122
- try {
19123
- const { command, args } = resolveOpenCommand(url);
19124
- const child = spawn(command, args, {
19125
- detached: true,
19126
- stdio: "ignore"
19127
- });
19128
- child.on("error", () => {});
19129
- child.unref();
19130
- return true;
19131
- } catch {
19132
- return false;
19133
- }
19134
- };
19135
- //#endregion
19136
- //#region src/cli/utils/open-workflow-pull-request.ts
19137
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
19138
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
19139
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
19140
- 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.
19141
-
19142
- Docs: https://www.react.doctor/ci`;
19143
19220
  const execFileAsync = promisify(execFile);
19144
- const run = async (command, args, cwd) => {
19221
+ const defaultInstallDependencyRunner = async (input) => {
19222
+ await execFileAsync(input.command, [...input.args], {
19223
+ cwd: input.cwd,
19224
+ env: {
19225
+ ...process.env,
19226
+ REACT_DOCTOR_INSTALL: "1"
19227
+ },
19228
+ shell: process.platform === "win32"
19229
+ });
19230
+ };
19231
+ const isSupplyChainTrustError = (error) => {
19232
+ const candidate = error;
19233
+ const haystack = [
19234
+ candidate?.stderr,
19235
+ candidate?.stdout,
19236
+ candidate?.message
19237
+ ].map((part) => String(part ?? "")).join("\n");
19238
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19239
+ };
19240
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19241
+ const installReactDoctorDependency = async (options) => {
19242
+ const packageJson = readPackageJson(options.projectRoot);
19243
+ if (!isRecord(packageJson)) return {
19244
+ dependencyStatus: "skipped",
19245
+ dependencyReason: "missing-or-invalid-package-json"
19246
+ };
19247
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19248
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19249
+ dependencyStatus: "skipped",
19250
+ dependencyReason: "invalid-dev-dependencies"
19251
+ };
19252
+ const runnerInput = buildInstallCommand(options.projectRoot);
19145
19253
  try {
19146
- const { stdout, stderr } = await execFileAsync(command, [...args], {
19147
- cwd,
19148
- encoding: "utf8"
19149
- });
19150
- return {
19151
- success: true,
19152
- stdout: stdout.trim(),
19153
- stderr: stderr.trim()
19154
- };
19254
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19155
19255
  } catch (error) {
19156
- const failure = error;
19157
19256
  return {
19158
- success: false,
19159
- stdout: (failure.stdout ?? "").trim(),
19160
- stderr: (failure.stderr ?? "").trim()
19257
+ dependencyStatus: "skipped",
19258
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19259
+ installCommand: formatInstallCommand(runnerInput)
19161
19260
  };
19162
19261
  }
19262
+ return { dependencyStatus: "created" };
19163
19263
  };
19164
- const detectDefaultBranch = async (cwd) => {
19165
- const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
19166
- if (symRef.success) {
19167
- const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
19168
- if (branchMatch) return branchMatch[1];
19264
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19265
+ hookPath,
19266
+ runnerRoot: projectRoot,
19267
+ kind: "git"
19268
+ });
19269
+ const formatGitHookInstallMessage = (hookResult) => {
19270
+ 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.`;
19271
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19272
+ };
19273
+ const formatDependencyInstallMessage = (result) => {
19274
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19275
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19276
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19277
+ 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).";
19278
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19279
+ return "Skipped dev dependency install: package.json missing or invalid.";
19280
+ };
19281
+ const buildDependencyFollowUp = (result) => {
19282
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19283
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19284
+ };
19285
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19286
+ installReactDoctorScriptStep(projectRoot);
19287
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19288
+ try {
19289
+ const dependencyResult = await installReactDoctorDependency({
19290
+ projectRoot,
19291
+ runner: dependencyRunner
19292
+ });
19293
+ recordCount(METRIC.installDependency, 1, {
19294
+ status: dependencyResult.dependencyStatus,
19295
+ reason: dependencyResult.dependencyReason ?? null,
19296
+ packageManager: detectPackageManager(projectRoot)
19297
+ });
19298
+ if (dependencyResult.dependencyStatus === "skipped") {
19299
+ const message = formatDependencyInstallMessage(dependencyResult);
19300
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19301
+ else dependencySpinner.fail(message);
19302
+ const followUp = buildDependencyFollowUp(dependencyResult);
19303
+ if (followUp !== void 0) cliLogger.dim(followUp);
19304
+ return dependencyResult;
19305
+ }
19306
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19307
+ return dependencyResult;
19308
+ } catch (error) {
19309
+ dependencySpinner.fail("Failed to install React Doctor package.");
19310
+ throw error;
19169
19311
  }
19170
- if ((await run("git", [
19171
- "rev-parse",
19172
- "--verify",
19173
- "origin/main"
19174
- ], cwd)).success) return "main";
19175
- if ((await run("git", [
19176
- "rev-parse",
19177
- "--verify",
19178
- "origin/master"
19179
- ], cwd)).success) return "master";
19180
- return null;
19181
19312
  };
19182
- const findUniqueBranchName = async (cwd) => {
19183
- if (!(await run("git", [
19184
- "rev-parse",
19185
- "--verify",
19186
- NEW_BRANCH_PREFIX
19187
- ], cwd)).success) return NEW_BRANCH_PREFIX;
19188
- return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
19313
+ const getSkillSourceDirectory = () => {
19314
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19315
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19189
19316
  };
19190
- const openWorkflowPullRequest = async (params) => {
19191
- const workflowPath = path$1.resolve(params.workflowPath);
19192
- const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
19193
- const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
19194
- const prBody = params.prBody ?? DEFAULT_PR_BODY;
19195
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19196
- if (!repoRootProbe.success) return {
19197
- status: "not-attempted",
19198
- reason: "not-a-git-repo"
19199
- };
19200
- const cwd = repoRootProbe.stdout;
19201
- if (!isCommandAvailable("gh")) return {
19202
- status: "not-attempted",
19203
- reason: "gh-not-installed"
19204
- };
19205
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
19206
- status: "not-attempted",
19207
- reason: "gh-not-authenticated"
19208
- };
19209
- const defaultBranch = await detectDefaultBranch(cwd);
19210
- if (!defaultBranch) return {
19211
- status: "not-attempted",
19212
- reason: "no-default-branch"
19213
- };
19214
- const previousBranchProbe = await run("git", [
19215
- "rev-parse",
19216
- "--abbrev-ref",
19217
- "HEAD"
19218
- ], cwd);
19219
- if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
19220
- status: "not-attempted",
19221
- reason: "detached-head"
19222
- };
19223
- const previousBranch = previousBranchProbe.stdout;
19224
- await run("git", [
19225
- "fetch",
19226
- "origin",
19227
- defaultBranch
19228
- ], cwd);
19229
- const newBranch = await findUniqueBranchName(cwd);
19230
- if (!(await run("git", [
19231
- "checkout",
19232
- "-b",
19233
- newBranch,
19234
- `origin/${defaultBranch}`
19235
- ], cwd)).success) return {
19236
- status: "not-attempted",
19237
- reason: "checkout-failed"
19238
- };
19239
- const restoreToPreviousBranch = async (deleteNewBranch) => {
19240
- await run("git", ["checkout", previousBranch], cwd);
19241
- if (deleteNewBranch) await run("git", [
19242
- "branch",
19243
- "-D",
19244
- newBranch
19245
- ], cwd);
19246
- };
19247
- if (!(await run("git", [
19248
- "add",
19249
- "--",
19250
- path$1.relative(cwd, workflowPath)
19251
- ], cwd)).success) {
19252
- await restoreToPreviousBranch(true);
19253
- return {
19254
- status: "not-attempted",
19255
- reason: "git-add-failed"
19256
- };
19317
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19318
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19319
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19320
+ try {
19321
+ const installResult = await installSkillsFromSource({
19322
+ source: sourceDir,
19323
+ agents: selectedAgents,
19324
+ cwd: projectRoot,
19325
+ mode: "copy"
19326
+ });
19327
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19328
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19329
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19330
+ } catch (error) {
19331
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19332
+ throw error;
19257
19333
  }
19258
- if (!(await run("git", [
19259
- "commit",
19260
- "-m",
19261
- commitMessage
19262
- ], cwd)).success) {
19263
- await restoreToPreviousBranch(true);
19264
- return {
19265
- status: "not-attempted",
19266
- reason: "git-commit-failed"
19267
- };
19334
+ };
19335
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19336
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19337
+ try {
19338
+ const hookResult = installReactDoctorGitHook({
19339
+ hookPath: gitHookTarget.hookPath,
19340
+ projectRoot: gitHookTarget.runnerRoot,
19341
+ kind: gitHookTarget.kind,
19342
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19343
+ });
19344
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19345
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19346
+ } catch (error) {
19347
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19348
+ throw error;
19268
19349
  }
19269
- if (!(await run("git", [
19270
- "push",
19271
- "-u",
19272
- "origin",
19273
- newBranch
19274
- ], cwd)).success) {
19275
- await restoreToPreviousBranch(true);
19276
- return {
19277
- status: "not-attempted",
19278
- reason: "git-push-failed"
19279
- };
19350
+ };
19351
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19352
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19353
+ try {
19354
+ const hookResult = installReactDoctorAgentHooks({
19355
+ projectRoot,
19356
+ agents: selectedAgents
19357
+ });
19358
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19359
+ else {
19360
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19361
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19362
+ }
19363
+ } catch (error) {
19364
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19365
+ throw error;
19280
19366
  }
19281
- const prCreate = await run("gh", [
19282
- "pr",
19283
- "create",
19284
- "--title",
19285
- prTitle,
19286
- "--body",
19287
- prBody,
19288
- "--base",
19289
- defaultBranch,
19290
- "--head",
19291
- newBranch
19292
- ], cwd);
19293
- await restoreToPreviousBranch(false);
19294
- if (!prCreate.success) return {
19295
- status: "branch-pushed",
19296
- branch: newBranch
19297
- };
19298
- return {
19299
- status: "pr-opened",
19300
- url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
19301
- };
19302
19367
  };
19303
- const stageWorkflowFile = async (params) => {
19304
- const workflowPath = path$1.resolve(params.workflowPath);
19305
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19306
- if (!repoRootProbe.success) return false;
19307
- return (await run("git", [
19308
- "add",
19309
- "--",
19310
- path$1.relative(repoRootProbe.stdout, workflowPath)
19311
- ], repoRootProbe.stdout)).success;
19368
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19369
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19370
+ };
19371
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19372
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19373
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19374
+ if (upgradeResult.status === "failed") {
19375
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19376
+ return false;
19377
+ }
19378
+ if (upgradeResult.status === "not-needed") {
19379
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19380
+ return false;
19381
+ }
19382
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19383
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19384
+ return true;
19385
+ };
19386
+ const runInstallReactDoctor = async (options = {}) => {
19387
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19388
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19389
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19390
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19391
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19392
+ process.exitCode = 1;
19393
+ return;
19394
+ }
19395
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19396
+ if (detectedAgents.length === 0) {
19397
+ cliLogger.error("No supported coding agents detected.");
19398
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19399
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19400
+ process.exitCode = 1;
19401
+ return;
19402
+ }
19403
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19404
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19405
+ const gitHookPath = gitHookTarget?.hookPath;
19406
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19407
+ const prompt = options.prompt ?? prompts;
19408
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19409
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19410
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19411
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19412
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19413
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19414
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19415
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19416
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19417
+ type: "multiselect",
19418
+ name: "agents",
19419
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19420
+ choices: detectedAgents.map((agent) => ({
19421
+ title: getSkillAgentConfig(agent).displayName,
19422
+ value: agent,
19423
+ selected: true
19424
+ })),
19425
+ instructions: false,
19426
+ min: 1
19427
+ }, promptOptions)).agents ?? [];
19428
+ if (selectedAgents.length === 0) return;
19429
+ let dependencyResult;
19430
+ if (!options.dryRun) {
19431
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19432
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19433
+ }
19434
+ let didInstallWorkflow = false;
19435
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19436
+ cliLogger.break();
19437
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19438
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19439
+ }
19440
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19441
+ title: "Pre-commit hook",
19442
+ description: "Check staged changes before each commit",
19443
+ value: SETUP_OPTION_GIT_HOOK,
19444
+ selected: true
19445
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19446
+ title: "Agent hooks",
19447
+ description: "Ask Claude Code or Cursor to scan after code edits",
19448
+ value: SETUP_OPTION_AGENT_HOOKS,
19449
+ selected: Boolean(options.agentHooks)
19450
+ }] : []];
19451
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19452
+ title: "Skip optional setup",
19453
+ description: "Install only the agent skill and package setup",
19454
+ value: SETUP_OPTION_SKIP,
19455
+ selected: false
19456
+ }, ...setupActionChoices];
19457
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19458
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19459
+ type: "multiselect",
19460
+ name: "setupOptions",
19461
+ message: "Select additional React Doctor setup:",
19462
+ choices: setupChoices,
19463
+ instructions: false
19464
+ }, promptOptions)).setupOptions ?? [];
19465
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19466
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19467
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19468
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19469
+ if (!options.dryRun) {
19470
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19471
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19472
+ }
19473
+ if (options.dryRun) {
19474
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19475
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19476
+ cliLogger.dim(` Source: ${sourceDir}`);
19477
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19478
+ cliLogger.dim(" Dev dependency: react-doctor");
19479
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19480
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19481
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19482
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19483
+ return;
19484
+ }
19485
+ recordCount(METRIC.installCompleted, 1, {
19486
+ agentsCount: selectedAgents.length,
19487
+ gitHook: shouldInstallGitHook,
19488
+ agentHooks: shouldInstallAgentHooks,
19489
+ workflow: didInstallWorkflow,
19490
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19491
+ packageManager: detectPackageManager(projectRoot)
19492
+ });
19493
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19494
+ };
19495
+ //#endregion
19496
+ //#region src/cli/utils/install-skill-for-agent.ts
19497
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19498
+ const source = getSkillSourceDirectory();
19499
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19500
+ const result = await installSkillsFromSource({
19501
+ source,
19502
+ agents: [agent],
19503
+ cwd: projectRoot,
19504
+ mode: "copy"
19505
+ });
19506
+ return result.skills.length > 0 && result.failed.length === 0;
19312
19507
  };
19313
19508
  //#endregion
19314
19509
  //#region src/cli/utils/launch-agent.ts
@@ -19399,9 +19594,6 @@ const copyToClipboard = (text) => {
19399
19594
  };
19400
19595
  //#endregion
19401
19596
  //#region src/cli/utils/handoff-to-agent.ts
19402
- const CI_YES_CHOICE = "ci-yes";
19403
- const CI_LEARN_MORE_CHOICE = "ci-learn-more";
19404
- const CI_NO_CHOICE = "ci-no";
19405
19597
  const CLIPBOARD_CHOICE = "clipboard";
19406
19598
  const SKIP_CHOICE = "skip";
19407
19599
  const printPayload = (payload) => {
@@ -19410,59 +19602,11 @@ const printPayload = (payload) => {
19410
19602
  cliLogger.log(payload);
19411
19603
  cliLogger.log(highlighter.dim("──────────────────────"));
19412
19604
  };
19413
- const setUpGitHubActions = async (rootDirectory) => {
19414
- const projectRoot = findNearestPackageDirectory(rootDirectory) ?? rootDirectory;
19415
- try {
19416
- installReactDoctorScriptStep(projectRoot);
19417
- } catch {}
19418
- const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
19419
- const workflowResult = installReactDoctorWorkflow(projectRoot);
19420
- reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
19421
- cliLogger.break();
19422
- if (workflowResult.status === "failed") {
19423
- cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
19424
- return;
19425
- }
19426
- if (workflowResult.status === "created") {
19427
- const pullRequestSpinner = spinner("Opening a pull request for review...").start();
19428
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
19429
- if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
19430
- 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}`);
19431
- else {
19432
- pullRequestSpinner.stop();
19433
- if (await stageWorkflowFile({ workflowPath: workflowResult.workflowPath })) cliLogger.log(` Staged the workflow file. Commit it to start scanning every pull request.`);
19434
- else cliLogger.log(" React Doctor will now scan every new pull request automatically.");
19435
- }
19436
- }
19437
- cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
19438
- };
19439
- const UPGRADE_YES_CHOICE = "upgrade-yes";
19440
- const UPGRADE_NO_CHOICE = "upgrade-no";
19441
19605
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19442
19606
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19443
19607
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19444
19608
 
19445
19609
  Docs: https://www.react.doctor/ci`;
19446
- const askUpgradeActionVersion = async () => {
19447
- const { upgradeChoice } = await prompts({
19448
- type: "select",
19449
- name: "upgradeChoice",
19450
- message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
19451
- hint: " ",
19452
- choices: [{
19453
- title: "Yes (recommended)",
19454
- description: "Open a PR bumping the workflow to millionco/react-doctor@v2",
19455
- value: UPGRADE_YES_CHOICE
19456
- }, {
19457
- title: "No, thanks",
19458
- description: "Keep @v1 — won't ask again for this repo",
19459
- value: UPGRADE_NO_CHOICE
19460
- }],
19461
- initial: 0
19462
- }, { onCancel: () => true });
19463
- if (upgradeChoice === void 0) return "cancel";
19464
- return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
19465
- };
19466
19610
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19467
19611
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19468
19612
  if (!changed) return false;
@@ -19507,46 +19651,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19507
19651
  }
19508
19652
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19509
19653
  };
19510
- const SGR_BOLD_OFF = "\x1B[22m";
19511
- const ciQuestionMessage = [
19512
- "Add React Doctor to GitHub Actions?",
19513
- `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
19514
- `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
19515
- ].join("\n");
19516
- const askAddToGitHubActions = async () => {
19517
- while (true) {
19518
- const { ciChoice } = await prompts({
19519
- type: "select",
19520
- name: "ciChoice",
19521
- message: ciQuestionMessage,
19522
- hint: " ",
19523
- choices: [
19524
- {
19525
- title: "Yes (recommended)",
19526
- description: "Adds the workflow file and a doctor package script",
19527
- value: CI_YES_CHOICE
19528
- },
19529
- {
19530
- title: "Learn more",
19531
- description: highlighter.info(CI_URL),
19532
- value: CI_LEARN_MORE_CHOICE
19533
- },
19534
- {
19535
- title: "No, thanks",
19536
- description: "Continue to the agent handoff",
19537
- value: CI_NO_CHOICE
19538
- }
19539
- ],
19540
- initial: 0
19541
- }, { onCancel: () => true });
19542
- if (ciChoice === void 0) return "cancel";
19543
- if (ciChoice === CI_YES_CHOICE) return "yes";
19544
- if (ciChoice === CI_NO_CHOICE) return "no";
19545
- const opened = openUrl(CI_URL);
19546
- cliLogger.log(opened ? `Opened ${highlighter.info(CI_URL)} in your browser.` : `Visit ${highlighter.info(CI_URL)} to learn more.`);
19547
- cliLogger.break();
19548
- }
19549
- };
19550
19654
  const detectLaunchableAgents = async () => {
19551
19655
  const detected = new Set(await detectAvailableAgents());
19552
19656
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19563,7 +19667,7 @@ const handoffToAgent = async (input) => {
19563
19667
  });
19564
19668
  if (ciOutcome === "cancel") return;
19565
19669
  if (ciOutcome === "yes") {
19566
- await setUpGitHubActions(input.rootDirectory);
19670
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19567
19671
  cliLogger.break();
19568
19672
  }
19569
19673
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19714,6 +19818,14 @@ const HAPPY_FACE_LINES = [
19714
19818
  "│ ▽ │",
19715
19819
  "└─────┘"
19716
19820
  ];
19821
+ const FACE_INDENT = " ";
19822
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
19823
+ const clampToColumns = (text, maxColumns) => {
19824
+ if (maxColumns <= 0) return "";
19825
+ if (text.length <= maxColumns) return text;
19826
+ if (maxColumns === 1) return "…";
19827
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
19828
+ };
19717
19829
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19718
19830
  const characters = [...text];
19719
19831
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19727,13 +19839,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19727
19839
  const interLineDelayMs = 250 / speedMultiplier;
19728
19840
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19729
19841
  const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
19730
- const mouthPrefix = ` ${face[2] ?? ""} `;
19731
- yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
19842
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
19843
+ const terminalColumns = process.stdout.columns;
19844
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
19845
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
19846
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
19847
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19732
19848
  yield* writeStdout("\x1B[3A");
19733
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
19849
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19734
19850
  yield* Effect.sleep(interLineDelayMs);
19735
19851
  yield* writeStdout("\x1B[1B");
19736
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
19852
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19737
19853
  yield* Effect.sleep(explanationHoldMs);
19738
19854
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19739
19855
  });
@@ -19842,8 +19958,9 @@ const findLowestScoredScan = (completedScans) => {
19842
19958
  };
19843
19959
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
19844
19960
  const { completedScans, userConfig, verbose, isOffline, projectName } = input;
19961
+ const categoryFilters = input.categoryFilters ?? /* @__PURE__ */ new Set();
19845
19962
  const animateRender = !verbose && canAnimateOnboarding(process.stdout);
19846
- const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
19963
+ const displayDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig), categoryFilters);
19847
19964
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
19848
19965
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
19849
19966
  const resolveDiagnosticSourceRoot = (diagnostic) => projectRootByDiagnostic.get(diagnostic) ?? "";
@@ -19857,29 +19974,30 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19857
19974
  const totalScannedFileCount = uniqueScannedFilePaths.size + fileCountFromScansWithoutPaths;
19858
19975
  const totalScanElapsedMilliseconds = completedScans.reduce((sum, scan) => sum + (scan.result.scanElapsedMilliseconds ?? scan.result.elapsedMilliseconds), 0);
19859
19976
  yield* Console.log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
19860
- if (surfaceDiagnostics.length > 0) {
19977
+ if (displayDiagnostics.length > 0) {
19861
19978
  yield* Console.log("");
19862
- yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19979
+ yield* printDiagnostics(displayDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
19863
19980
  }
19864
19981
  const lowestScoredScan = findLowestScoredScan(completedScans);
19865
19982
  const aggregateScore = lowestScoredScan?.result.score ?? null;
19866
19983
  const totalSourceFileCount = completedScans.reduce((sum, scan) => sum + scan.result.project.sourceFileCount, 0);
19867
19984
  yield* printSummary({
19868
- diagnostics: surfaceDiagnostics,
19985
+ diagnostics: displayDiagnostics,
19869
19986
  elapsedMilliseconds: completedScans.reduce((sum, scan) => sum + scan.result.elapsedMilliseconds, 0),
19870
19987
  scoreResult: aggregateScore,
19871
- potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
19988
+ potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(displayDiagnostics, filterDiagnosticsForSurface(lowestScoredScan.result.diagnostics, "cli", userConfig), lowestScoredScan.result.score)) : null,
19872
19989
  totalSourceFileCount,
19873
19990
  noScoreMessage: "Score unavailable.",
19874
19991
  verbose,
19875
19992
  animateProjection: animateRender
19876
19993
  });
19877
19994
  const entries = completedScans.map((scan) => {
19878
- const errorCount = scan.result.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19995
+ const projectDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface([...scan.result.diagnostics], "cli", userConfig), categoryFilters);
19996
+ const errorCount = projectDiagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
19879
19997
  return {
19880
19998
  projectName: scan.result.project.projectName,
19881
19999
  score: scan.result.score?.score ?? null,
19882
- issueCount: scan.result.diagnostics.length,
20000
+ issueCount: projectDiagnostics.length,
19883
20001
  errorCount
19884
20002
  };
19885
20003
  });
@@ -19887,7 +20005,7 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
19887
20005
  yield* Console.log("");
19888
20006
  for (const entry of entries) yield* Console.log(buildSummaryLine(entry, longestProjectNameLength));
19889
20007
  yield* printFooter({
19890
- diagnostics: surfaceDiagnostics,
20008
+ diagnostics: displayDiagnostics,
19891
20009
  scoreResult: aggregateScore,
19892
20010
  projectName,
19893
20011
  isOffline
@@ -19977,7 +20095,8 @@ const resolveCliInspectOptions = (flags, userConfig) => {
19977
20095
  noScore: flags.score === false || flags.telemetry === false || (userConfig?.noScore ?? false),
19978
20096
  isCi: isCiEnvironment(),
19979
20097
  silent: Boolean(flags.json),
19980
- concurrency: resolveParallelFlag(flags.parallel)
20098
+ concurrency: resolveParallelFlag(flags.parallel),
20099
+ categoryFilters: resolveCliCategories(flags.category)
19981
20100
  };
19982
20101
  };
19983
20102
  //#endregion
@@ -20230,6 +20349,16 @@ const validateModeFlags = (flags) => {
20230
20349
  };
20231
20350
  //#endregion
20232
20351
  //#region src/cli/commands/inspect.ts
20352
+ const filterCompletedScansByCategories = (completedScans, categoryFilters) => {
20353
+ if (categoryFilters.size === 0) return [...completedScans];
20354
+ return completedScans.map((scan) => ({
20355
+ ...scan,
20356
+ result: {
20357
+ ...scan.result,
20358
+ diagnostics: filterDiagnosticsByCategories(scan.result.diagnostics, categoryFilters)
20359
+ }
20360
+ }));
20361
+ };
20233
20362
  /**
20234
20363
  * Post-scan finalization shared by the staged-arm and project-loop
20235
20364
  * paths of `inspectAction`: emit the JSON report (when in JSON mode)
@@ -20242,6 +20371,7 @@ const finalizeScans = (input) => {
20242
20371
  const baselineComputed = input.completedScans.length > 0 && input.completedScans.every((scan) => scan.result.baselineDelta !== void 0);
20243
20372
  const baselineDegraded = input.baselineIntended && !baselineComputed;
20244
20373
  const mode = baselineDegraded ? "diff" : input.mode;
20374
+ const jsonCompletedScans = filterCompletedScansByCategories(input.completedScans, input.categoryFilters);
20245
20375
  if (input.isJsonMode) {
20246
20376
  const baseline = baselineComputed && baselineDeltas.length > 0 ? {
20247
20377
  baseRef: baselineDeltas[0].baseRef,
@@ -20253,7 +20383,7 @@ const finalizeScans = (input) => {
20253
20383
  directory: input.resolvedDirectory,
20254
20384
  mode,
20255
20385
  diff: input.diff,
20256
- scans: input.completedScans,
20386
+ scans: jsonCompletedScans,
20257
20387
  totalElapsedMilliseconds: performance.now() - input.startTime,
20258
20388
  baseline
20259
20389
  }));
@@ -20273,8 +20403,8 @@ const buildChangedFilesDiffInfo = (changedFiles) => ({
20273
20403
  * `react-doctor.config.json` to `doctor.config.ts` before config is loaded,
20274
20404
  * so the scan reads the renamed file and the user is told once. CI, coding
20275
20405
  * agents, JSON/score output, pre-commit (`--staged`) hooks, and non-TTY runs
20276
- * are left untouched — the loader's warning still nudges them — so a scan
20277
- * never mutates the repo unattended.
20406
+ * are left untouched — the loader still reads the legacy file as a deprecated
20407
+ * fallback and warns — so a scan never mutates the repo unattended.
20278
20408
  */
20279
20409
  const maybeMigrateLegacyConfig = (requestedDirectory, { isQuiet, isStaged }) => {
20280
20410
  if (!(!isQuiet && !isStaged && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment())) return;
@@ -20327,6 +20457,7 @@ const inspectAction = async (directory, flags) => {
20327
20457
  await Effect.runPromise(playWelcomeScene({ speedMultiplier: isReturningUser ? 2 : 1 }));
20328
20458
  } else Effect.runSync(printBrandedHeader);
20329
20459
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
20460
+ const categoryFilters = new Set(scanOptions.categoryFilters ?? []);
20330
20461
  const skipPrompts = shouldSkipPrompts({
20331
20462
  yes: flags.yes,
20332
20463
  json: flags.json
@@ -20387,6 +20518,7 @@ const inspectAction = async (directory, flags) => {
20387
20518
  isJsonMode,
20388
20519
  isScoreOnly,
20389
20520
  flags,
20521
+ categoryFilters,
20390
20522
  userConfig,
20391
20523
  resolvedDirectory,
20392
20524
  startTime
@@ -20446,6 +20578,7 @@ const inspectAction = async (directory, flags) => {
20446
20578
  const shouldShowShareLink = !scanOptions.noScore && (userConfig?.share ?? true) && !scanOptions.isCi;
20447
20579
  await Effect.runPromise(printMultiProjectSummary({
20448
20580
  completedScans,
20581
+ categoryFilters,
20449
20582
  userConfig,
20450
20583
  verbose: Boolean(flags.verbose),
20451
20584
  isOffline: !shouldShowShareLink,
@@ -20461,14 +20594,15 @@ const inspectAction = async (directory, flags) => {
20461
20594
  isJsonMode,
20462
20595
  isScoreOnly,
20463
20596
  flags,
20597
+ categoryFilters,
20464
20598
  userConfig,
20465
20599
  resolvedDirectory,
20466
20600
  startTime
20467
20601
  });
20468
- const surfaceDiagnostics = filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig);
20469
- if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && surfaceDiagnostics.length > 0) {
20602
+ const selectedSurfaceDiagnostics = filterDiagnosticsByCategories(filterDiagnosticsForSurface(allDiagnostics, scanOptions.outputSurface ?? "cli", userConfig), categoryFilters);
20603
+ if (!isQuiet && !skipPrompts && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment() && selectedSurfaceDiagnostics.length > 0) {
20470
20604
  await handoffToAgent({
20471
- diagnostics: surfaceDiagnostics,
20605
+ diagnostics: selectedSurfaceDiagnostics,
20472
20606
  projectName: path$1.basename(resolvedDirectory),
20473
20607
  rootDirectory: resolvedDirectory,
20474
20608
  interactive: true
@@ -20636,13 +20770,27 @@ const resolveRuleConfigTarget = async (projectRoot) => {
20636
20770
  config: isPlainObject(embedded) ? embedded : {}
20637
20771
  };
20638
20772
  }
20639
- if (loaded.format === "json") return {
20640
- format: "json",
20641
- filePath: loaded.configFilePath,
20642
- directory: loaded.sourceDirectory,
20643
- exists: true,
20644
- config: readObjectFile(loaded.configFilePath) ?? {}
20645
- };
20773
+ if (loaded.format === "json") {
20774
+ if (path$1.basename(loaded.configFilePath) === "react-doctor.config.json") {
20775
+ const legacyConfig = readObjectFile(loaded.configFilePath) ?? {};
20776
+ delete legacyConfig.$schema;
20777
+ return {
20778
+ format: "json",
20779
+ filePath: path$1.join(loaded.sourceDirectory, NEW_CONFIG_FILENAME),
20780
+ directory: loaded.sourceDirectory,
20781
+ exists: false,
20782
+ config: legacyConfig,
20783
+ migratedFromFilePath: loaded.configFilePath
20784
+ };
20785
+ }
20786
+ return {
20787
+ format: "json",
20788
+ filePath: loaded.configFilePath,
20789
+ directory: loaded.sourceDirectory,
20790
+ exists: true,
20791
+ config: readObjectFile(loaded.configFilePath) ?? {}
20792
+ };
20793
+ }
20646
20794
  return {
20647
20795
  format: "module",
20648
20796
  filePath: loaded.configFilePath,
@@ -20721,7 +20869,10 @@ const writeRuleConfig = async (target, nextConfig) => {
20721
20869
  return { written };
20722
20870
  }
20723
20871
  if (target.format === "package-json") writePackageJsonConfig(target.filePath, nextConfig);
20724
- else writeJsonConfig(target.filePath, nextConfig);
20872
+ else {
20873
+ writeJsonConfig(target.filePath, nextConfig);
20874
+ if (target.migratedFromFilePath) fs$1.rmSync(target.migratedFromFilePath, { force: true });
20875
+ }
20725
20876
  clearConfigCache();
20726
20877
  return { written: true };
20727
20878
  };
@@ -20882,7 +21033,7 @@ const rulesListAction = async (options) => {
20882
21033
  });
20883
21034
  const catalog = buildRuleCatalog();
20884
21035
  const config = validateConfigTypes((await resolveRuleConfigTarget(resolveProjectRoot(options))).config);
20885
- const categoryFilter = options.category?.toLowerCase();
21036
+ const categoryFilter = typeof options.category === "string" ? options.category.toLowerCase() : void 0;
20886
21037
  const frameworkFilter = options.framework?.toLowerCase();
20887
21038
  const rows = catalog.filter((entry) => {
20888
21039
  if (categoryFilter && entry.category.toLowerCase() !== categoryFilter) return false;
@@ -21245,6 +21396,7 @@ const ROOT_FLAG_SPEC = {
21245
21396
  "--yes"
21246
21397
  ]),
21247
21398
  longOptionsWithRequiredValues: new Set([
21399
+ "--category",
21248
21400
  "--changed-files-from",
21249
21401
  "--blocking",
21250
21402
  "--fail-on",
@@ -21401,6 +21553,7 @@ ${formatExampleLines([
21401
21553
  ["react-doctor ./apps/web", "scan a specific directory"],
21402
21554
  ["react-doctor --diff main", "scan only files changed vs. main"],
21403
21555
  ["react-doctor --staged", "scan staged files (pre-commit hook)"],
21556
+ ["react-doctor --category Security", "show only one diagnostic category"],
21404
21557
  ["react-doctor --blocking warning", "fail CI on warnings too (default: error)"],
21405
21558
  ["react-doctor --json > report.json", "write a machine-readable report"],
21406
21559
  ["react-doctor why src/App.tsx:42", "explain why a rule fired there"],
@@ -21429,7 +21582,8 @@ ${formatExampleLines([
21429
21582
  ${highlighter.dim("Learn more:")}
21430
21583
  ${highlighter.info(CANONICAL_GITHUB_URL)}
21431
21584
  `;
21432
- 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);
21585
+ const collectCategoryOption = (value, previousValues) => [...previousValues ?? [], value];
21586
+ 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);
21433
21587
  program.action(inspectAction);
21434
21588
  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));
21435
21589
  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);
@@ -21472,4 +21626,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21472
21626
  export {};
21473
21627
 
21474
21628
  //# sourceMappingURL=cli.js.map
21475
- //# debugId=30809678-4fe4-55cc-938c-ee6301ab7888
21629
+ //# debugId=d1b95aab-fa59-5a23-83a0-37e1ff08b002