react-doctor 0.4.1 → 0.4.2-dev.42c339f

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]="92822f58-92ef-58d5-8850-2746c0b48fc0")}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";
@@ -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;
@@ -7629,6 +7630,35 @@ const loadPackageJsonConfig = (directory) => {
7629
7630
  format: "package-json"
7630
7631
  };
7631
7632
  };
7633
+ const loadLegacyConfig = (directory) => {
7634
+ const legacyFilePath = path$1.join(directory, LEGACY_CONFIG_FILENAME);
7635
+ if (!isFile(legacyFilePath)) return {
7636
+ status: "absent",
7637
+ loaded: null
7638
+ };
7639
+ try {
7640
+ const parsed = readDataConfig(legacyFilePath);
7641
+ if (isPlainObject(parsed)) {
7642
+ warn(`${LEGACY_CONFIG_FILENAME} is deprecated — rename it to ${CONFIG_BASENAME}.json (or author a ${CONFIG_BASENAME}.ts). It is still read for now.`);
7643
+ return {
7644
+ status: "found",
7645
+ loaded: {
7646
+ config: validateConfigTypes(parsed),
7647
+ sourceDirectory: directory,
7648
+ configFilePath: legacyFilePath,
7649
+ format: "json"
7650
+ }
7651
+ };
7652
+ }
7653
+ warn(`${LEGACY_CONFIG_FILENAME} must contain an object, ignoring.`);
7654
+ } catch (error) {
7655
+ warn(`Failed to load ${LEGACY_CONFIG_FILENAME}: ${formatError(error)}`);
7656
+ }
7657
+ return {
7658
+ status: "invalid",
7659
+ loaded: null
7660
+ };
7661
+ };
7632
7662
  const loadConfigFromDirectory = async (directory) => {
7633
7663
  let sawBrokenConfigFile = false;
7634
7664
  for (const extension of CONFIG_EXTENSIONS) {
@@ -7658,7 +7688,8 @@ const loadConfigFromDirectory = async (directory) => {
7658
7688
  status: "found",
7659
7689
  loaded: packageJsonConfig
7660
7690
  };
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).`);
7691
+ const legacyResult = loadLegacyConfig(directory);
7692
+ if (legacyResult.status !== "absent") return legacyResult;
7662
7693
  return {
7663
7694
  status: sawBrokenConfigFile ? "invalid" : "absent",
7664
7695
  loaded: null
@@ -7695,7 +7726,9 @@ const directoryHasCurrentConfig = (directory) => {
7695
7726
  /**
7696
7727
  * Walks up from `rootDirectory` (same boundary semantics as
7697
7728
  * `loadConfigWithSource`) looking for a pre-migration
7698
- * `react-doctor.config.json` that is no longer read. Returns the first one
7729
+ * `react-doctor.config.json`. The loader still reads this file as a deprecated
7730
+ * fallback (see `loadLegacyConfig`); this detector is what lets the interactive
7731
+ * CLI offer to rename it to a current-format config. Returns the first one
7699
7732
  * found, or `null` when a current-format config supersedes it or none exists
7700
7733
  * before a project boundary. Detection only — the CLI performs the rename.
7701
7734
  */
@@ -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.42c339f";
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.42c339f`;
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.42c339f") ? "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
@@ -16441,8 +16474,22 @@ const buildCodeFrame = (input) => {
16441
16474
  });
16442
16475
  };
16443
16476
  //#endregion
16477
+ //#region src/cli/utils/resolve-measure-width.ts
16478
+ const resolveClampedWidth = (input) => {
16479
+ const terminalColumns = process.stdout.columns;
16480
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16481
+ const availableColumns = terminalColumns - input.reservedColumns;
16482
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16483
+ };
16484
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16485
+ reservedColumns,
16486
+ fullWidth: 60,
16487
+ minWidth: 24
16488
+ });
16489
+ //#endregion
16444
16490
  //#region src/cli/utils/build-section-divider.ts
16445
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16491
+ const DIVIDER_INDENT = " ";
16492
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16446
16493
  //#endregion
16447
16494
  //#region src/cli/utils/indent-multiline-text.ts
16448
16495
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16602,7 +16649,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16602
16649
  endLine: isMultiSite ? cluster.endLine : void 0,
16603
16650
  rootDirectory: resolveSourceRoot(lead)
16604
16651
  }) : null;
16605
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16652
+ if (codeFrame) {
16653
+ const boxInnerWidth = resolveMeasureWidth(8);
16654
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16655
+ }
16606
16656
  const seenHints = /* @__PURE__ */ new Set();
16607
16657
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16608
16658
  seenHints.add(diagnostic.suppressionHint);
@@ -16620,8 +16670,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16620
16670
  const learnMoreLine = formatLearnMoreLine(representative);
16621
16671
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16622
16672
  }
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}`));
16673
+ if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16674
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16625
16675
  if (renderEverySite && isAgentEnvironment) {
16626
16676
  const fixRecipeLine = formatFixRecipeLine(representative);
16627
16677
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16815,14 +16865,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16815
16865
  const RAINBOW_GRADIENT_WIDTH = 80;
16816
16866
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16817
16867
  const RAINBOW_OKLCH_CHROMA = .129;
16868
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16869
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16870
+ const getScoreBarWidth = () => resolveClampedWidth({
16871
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16872
+ fullWidth: 50,
16873
+ minWidth: 10
16874
+ });
16818
16875
  const buildScoreBarSegments = (filledCount) => {
16819
- const emptyCount = 50 - filledCount;
16876
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16820
16877
  return {
16821
16878
  filledSegment: "█".repeat(filledCount),
16822
16879
  emptySegment: "░".repeat(emptyCount)
16823
16880
  };
16824
16881
  };
16825
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16882
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16826
16883
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16827
16884
  const buildRawScoreBar = (displayScore) => {
16828
16885
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16858,10 +16915,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16858
16915
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16859
16916
  };
16860
16917
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16918
+ const barWidth = getScoreBarWidth();
16861
16919
  const currentFill = getFilledCount(currentScore);
16862
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16920
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16863
16921
  const gainCount = Math.max(0, potentialFill - currentFill);
16864
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16922
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16865
16923
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16866
16924
  };
16867
16925
  const getDoctorFace = (score) => {
@@ -16874,7 +16932,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16874
16932
  const buildRawFaceLines = (score) => {
16875
16933
  const [eyes, mouth] = getDoctorFace(score);
16876
16934
  return [
16877
- "┌─────┐",
16935
+ FACE_BOX_TOP_BORDER,
16878
16936
  `│ ${eyes} │`,
16879
16937
  `│ ${mouth} │`,
16880
16938
  "└─────┘"
@@ -17016,6 +17074,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17016
17074
  };
17017
17075
  //#endregion
17018
17076
  //#region src/cli/utils/render-summary.ts
17077
+ const FOOTER_DESCRIPTION_INDENT = " ";
17078
+ const printFooterDescription = (description) => Effect.gen(function* () {
17079
+ const wrapWidth = resolveMeasureWidth(2);
17080
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17081
+ });
17019
17082
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17020
17083
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17021
17084
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17035,14 +17098,14 @@ const printFooter = (input) => Effect.gen(function* () {
17035
17098
  if (!input.isOffline) {
17036
17099
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17037
17100
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17038
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17101
+ yield* printFooterDescription("Tell others how you did on socials");
17039
17102
  yield* Console.log("");
17040
17103
  }
17041
17104
  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"));
17105
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17043
17106
  yield* Console.log("");
17044
17107
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17045
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17108
+ yield* printFooterDescription("Report issues and star the repository!");
17046
17109
  });
17047
17110
  const printSummary = (input) => Effect.gen(function* () {
17048
17111
  if (input.scoreResult) {
@@ -17948,190 +18011,24 @@ const installDoctorScript = (options) => {
17948
18011
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17949
18012
  };
17950
18013
  };
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];
18014
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18015
+ const scriptName = scriptResult.scriptName ?? "doctor";
18016
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18017
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18018
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18019
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18020
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18021
+ return "Skipped package script: package.json missing or invalid.";
18018
18022
  };
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
- }
18023
+ const installReactDoctorScriptStep = (projectRoot) => {
18024
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18025
+ try {
18026
+ const scriptResult = installDoctorScript({ projectRoot });
18027
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18028
+ } catch (error) {
18029
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18030
+ throw error;
18130
18031
  }
18131
- return {
18132
- installedAgents,
18133
- files
18134
- };
18135
18032
  };
18136
18033
  //#endregion
18137
18034
  //#region src/cli/utils/install-github-workflow.ts
@@ -18241,39 +18138,594 @@ const installReactDoctorWorkflow = (projectRoot) => {
18241
18138
  };
18242
18139
  }
18243
18140
  };
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;
18141
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18142
+ const workflow = readReactDoctorWorkflow(projectRoot);
18143
+ if (!workflow) return {
18144
+ status: "not-needed",
18145
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18146
+ };
18147
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18148
+ if (!changed) return {
18149
+ status: "not-needed",
18150
+ workflowPath: workflow.workflowPath
18151
+ };
18152
+ try {
18153
+ fs$1.writeFileSync(workflow.workflowPath, content);
18154
+ return {
18155
+ status: "upgraded",
18156
+ workflowPath: workflow.workflowPath
18157
+ };
18158
+ } catch {
18159
+ return {
18160
+ status: "failed",
18161
+ workflowPath: workflow.workflowPath
18162
+ };
18254
18163
  }
18255
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18256
- recordCount(METRIC.installWorkflow, 1);
18257
- return true;
18258
18164
  };
18259
18165
  //#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
- "",
18166
+ //#region src/cli/utils/hash-project-root.ts
18167
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18168
+ //#endregion
18169
+ //#region src/cli/utils/action-upgrade-prompt.ts
18170
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18171
+ const getActionUpgradeStore = (options = {}) => new Conf({
18172
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18173
+ cwd: options.cwd
18174
+ });
18175
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18176
+ try {
18177
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18178
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18179
+ } catch {
18180
+ return true;
18181
+ }
18182
+ };
18183
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18184
+ try {
18185
+ const store = getActionUpgradeStore(storeOptions);
18186
+ const upgrades = store.get("actionUpgrades", {});
18187
+ store.set("actionUpgrades", {
18188
+ ...upgrades,
18189
+ [hashProjectRoot(projectRoot)]: {
18190
+ rootDirectory: path$1.resolve(projectRoot),
18191
+ outcome,
18192
+ at: (/* @__PURE__ */ new Date()).toISOString()
18193
+ }
18194
+ });
18195
+ return true;
18196
+ } catch {
18197
+ return false;
18198
+ }
18199
+ };
18200
+ //#endregion
18201
+ //#region src/cli/utils/open-url.ts
18202
+ const resolveOpenCommand = (url) => {
18203
+ if (process$1.platform === "darwin") return {
18204
+ command: "open",
18205
+ args: [url]
18206
+ };
18207
+ if (process$1.platform === "win32") return {
18208
+ command: "cmd",
18209
+ args: [
18210
+ "/c",
18211
+ "start",
18212
+ "",
18213
+ url
18214
+ ]
18215
+ };
18216
+ return {
18217
+ command: "xdg-open",
18218
+ args: [url]
18219
+ };
18220
+ };
18221
+ const openUrl = (url) => {
18222
+ try {
18223
+ const { command, args } = resolveOpenCommand(url);
18224
+ const child = spawn(command, args, {
18225
+ detached: true,
18226
+ stdio: "ignore"
18227
+ });
18228
+ child.on("error", () => {});
18229
+ child.unref();
18230
+ return true;
18231
+ } catch {
18232
+ return false;
18233
+ }
18234
+ };
18235
+ //#endregion
18236
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18237
+ const CI_YES_CHOICE = "ci-yes";
18238
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18239
+ const CI_NO_CHOICE = "ci-no";
18240
+ const SGR_BOLD_OFF = "\x1B[22m";
18241
+ const ciQuestionMessage = [
18242
+ "Add React Doctor to GitHub Actions?",
18243
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18244
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18245
+ ].join("\n");
18246
+ const askAddToGitHubActions = async (prompt = prompts) => {
18247
+ while (true) {
18248
+ const { ciChoice } = await prompt({
18249
+ type: "select",
18250
+ name: "ciChoice",
18251
+ message: ciQuestionMessage,
18252
+ hint: " ",
18253
+ choices: [
18254
+ {
18255
+ title: "Yes",
18256
+ description: "Adds the workflow file and a doctor package script",
18257
+ value: CI_YES_CHOICE
18258
+ },
18259
+ {
18260
+ title: "Learn more",
18261
+ description: "Opens the docs page in your browser",
18262
+ value: CI_LEARN_MORE_CHOICE
18263
+ },
18264
+ {
18265
+ title: "No",
18266
+ description: "Skip for now",
18267
+ value: CI_NO_CHOICE
18268
+ }
18269
+ ],
18270
+ initial: 0
18271
+ }, { onCancel: () => true });
18272
+ if (ciChoice === void 0) return "cancel";
18273
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18274
+ if (ciChoice === CI_NO_CHOICE) return "no";
18275
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18276
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18277
+ cliLogger.break();
18278
+ }
18279
+ };
18280
+ //#endregion
18281
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18282
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18283
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18284
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18285
+ const { upgradeChoice } = await prompt({
18286
+ type: "select",
18287
+ name: "upgradeChoice",
18288
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18289
+ hint: " ",
18290
+ choices: [{
18291
+ title: "Yes (recommended)",
18292
+ description: "Bump the workflow to millionco/react-doctor@v2",
18293
+ value: UPGRADE_YES_CHOICE
18294
+ }, {
18295
+ title: "No, thanks",
18296
+ description: "Keep @v1 — won't ask again for this repo",
18297
+ value: UPGRADE_NO_CHOICE
18298
+ }],
18299
+ initial: 0
18300
+ }, { onCancel: () => true });
18301
+ if (upgradeChoice === void 0) return "cancel";
18302
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18303
+ };
18304
+ //#endregion
18305
+ //#region src/cli/utils/open-workflow-pull-request.ts
18306
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18307
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18308
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18309
+ 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.
18310
+
18311
+ Docs: https://www.react.doctor/ci`;
18312
+ const execFileAsync$1 = promisify(execFile);
18313
+ const run = async (command, args, cwd) => {
18314
+ try {
18315
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18316
+ cwd,
18317
+ encoding: "utf8"
18318
+ });
18319
+ return {
18320
+ success: true,
18321
+ stdout: stdout.trim(),
18322
+ stderr: stderr.trim()
18323
+ };
18324
+ } catch (error) {
18325
+ const failure = error;
18326
+ return {
18327
+ success: false,
18328
+ stdout: (failure.stdout ?? "").trim(),
18329
+ stderr: (failure.stderr ?? "").trim()
18330
+ };
18331
+ }
18332
+ };
18333
+ const detectDefaultBranch = async (cwd) => {
18334
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18335
+ if (symRef.success) {
18336
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18337
+ if (branchMatch) return branchMatch[1];
18338
+ }
18339
+ if ((await run("git", [
18340
+ "rev-parse",
18341
+ "--verify",
18342
+ "origin/main"
18343
+ ], cwd)).success) return "main";
18344
+ if ((await run("git", [
18345
+ "rev-parse",
18346
+ "--verify",
18347
+ "origin/master"
18348
+ ], cwd)).success) return "master";
18349
+ return null;
18350
+ };
18351
+ const findUniqueBranchName = async (cwd) => {
18352
+ if (!(await run("git", [
18353
+ "rev-parse",
18354
+ "--verify",
18355
+ NEW_BRANCH_PREFIX
18356
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18357
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18358
+ };
18359
+ const openWorkflowPullRequest = async (params) => {
18360
+ const workflowPath = path$1.resolve(params.workflowPath);
18361
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18362
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18363
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18364
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18365
+ if (!repoRootProbe.success) return {
18366
+ status: "not-attempted",
18367
+ reason: "not-a-git-repo"
18368
+ };
18369
+ const cwd = repoRootProbe.stdout;
18370
+ if (!isCommandAvailable("gh")) return {
18371
+ status: "not-attempted",
18372
+ reason: "gh-not-installed"
18373
+ };
18374
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18375
+ status: "not-attempted",
18376
+ reason: "gh-not-authenticated"
18377
+ };
18378
+ const defaultBranch = await detectDefaultBranch(cwd);
18379
+ if (!defaultBranch) return {
18380
+ status: "not-attempted",
18381
+ reason: "no-default-branch"
18382
+ };
18383
+ const previousBranchProbe = await run("git", [
18384
+ "rev-parse",
18385
+ "--abbrev-ref",
18386
+ "HEAD"
18387
+ ], cwd);
18388
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18389
+ status: "not-attempted",
18390
+ reason: "detached-head"
18391
+ };
18392
+ const previousBranch = previousBranchProbe.stdout;
18393
+ await run("git", [
18394
+ "fetch",
18395
+ "origin",
18396
+ defaultBranch
18397
+ ], cwd);
18398
+ const newBranch = await findUniqueBranchName(cwd);
18399
+ if (!(await run("git", [
18400
+ "checkout",
18401
+ "-b",
18402
+ newBranch,
18403
+ `origin/${defaultBranch}`
18404
+ ], cwd)).success) return {
18405
+ status: "not-attempted",
18406
+ reason: "checkout-failed"
18407
+ };
18408
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18409
+ await run("git", ["checkout", previousBranch], cwd);
18410
+ if (deleteNewBranch) await run("git", [
18411
+ "branch",
18412
+ "-D",
18413
+ newBranch
18414
+ ], cwd);
18415
+ };
18416
+ if (!(await run("git", [
18417
+ "add",
18418
+ "--",
18419
+ path$1.relative(cwd, workflowPath)
18420
+ ], cwd)).success) {
18421
+ await restoreToPreviousBranch(true);
18422
+ return {
18423
+ status: "not-attempted",
18424
+ reason: "git-add-failed"
18425
+ };
18426
+ }
18427
+ if (!(await run("git", [
18428
+ "commit",
18429
+ "-m",
18430
+ commitMessage
18431
+ ], cwd)).success) {
18432
+ await restoreToPreviousBranch(true);
18433
+ return {
18434
+ status: "not-attempted",
18435
+ reason: "git-commit-failed"
18436
+ };
18437
+ }
18438
+ if (!(await run("git", [
18439
+ "push",
18440
+ "-u",
18441
+ "origin",
18442
+ newBranch
18443
+ ], cwd)).success) {
18444
+ await restoreToPreviousBranch(true);
18445
+ return {
18446
+ status: "not-attempted",
18447
+ reason: "git-push-failed"
18448
+ };
18449
+ }
18450
+ const prCreate = await run("gh", [
18451
+ "pr",
18452
+ "create",
18453
+ "--title",
18454
+ prTitle,
18455
+ "--body",
18456
+ prBody,
18457
+ "--base",
18458
+ defaultBranch,
18459
+ "--head",
18460
+ newBranch
18461
+ ], cwd);
18462
+ await restoreToPreviousBranch(false);
18463
+ if (!prCreate.success) return {
18464
+ status: "branch-pushed",
18465
+ branch: newBranch
18466
+ };
18467
+ return {
18468
+ status: "pr-opened",
18469
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18470
+ };
18471
+ };
18472
+ const stageWorkflowFile = async (params) => {
18473
+ const workflowPath = path$1.resolve(params.workflowPath);
18474
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18475
+ if (!repoRootProbe.success) return false;
18476
+ return (await run("git", [
18477
+ "add",
18478
+ "--",
18479
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18480
+ ], repoRootProbe.stdout)).success;
18481
+ };
18482
+ //#endregion
18483
+ //#region src/cli/utils/report-workflow-result.ts
18484
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18485
+ if (result.status === "failed") {
18486
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18487
+ return false;
18488
+ }
18489
+ if (result.status === "exists") {
18490
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18491
+ return false;
18492
+ }
18493
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18494
+ recordCount(METRIC.installWorkflow, 1);
18495
+ return true;
18496
+ };
18497
+ //#endregion
18498
+ //#region src/cli/utils/set-up-github-actions.ts
18499
+ const setUpGitHubActions = async (options) => {
18500
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18501
+ try {
18502
+ installReactDoctorScriptStep(projectRoot);
18503
+ } catch {}
18504
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18505
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18506
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18507
+ cliLogger.break();
18508
+ if (workflowResult.status === "failed") {
18509
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18510
+ return false;
18511
+ }
18512
+ if (workflowResult.status === "created") {
18513
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18514
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18515
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18516
+ 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}`);
18517
+ else {
18518
+ pullRequestSpinner.stop();
18519
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18520
+ 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.");
18521
+ }
18522
+ }
18523
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18524
+ return didCreateWorkflow;
18525
+ };
18526
+ //#endregion
18527
+ //#region src/cli/utils/install-agent-hooks.ts
18528
+ const CLAUDE_AGENT = "claude-code";
18529
+ const CURSOR_AGENT = "cursor";
18530
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18531
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18532
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18533
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18534
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18535
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18536
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18537
+ const JSON_INDENT_SPACES$1 = 2;
18538
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18539
+ const readJsonFile = (filePath, fallback) => {
18540
+ if (!fs$1.existsSync(filePath)) return fallback;
18541
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18542
+ if (content.length === 0) return fallback;
18543
+ return JSON.parse(content);
18544
+ };
18545
+ const writeJsonFile = (filePath, value) => {
18546
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18547
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18548
+ };
18549
+ const writeHookScript = (filePath) => {
18550
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18551
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18552
+ fs$1.chmodSync(filePath, 493);
18553
+ };
18554
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18555
+ const installClaudeHook = (projectRoot) => {
18556
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18557
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18558
+ const settings = readJsonFile(settingsPath, {});
18559
+ const hooks = { ...settings.hooks ?? {} };
18560
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18561
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18562
+ type: "command",
18563
+ command: CLAUDE_HOOK_COMMAND
18564
+ }] });
18565
+ hooks.PostToolBatch = postToolBatchHooks;
18566
+ writeJsonFile(settingsPath, {
18567
+ ...settings,
18568
+ hooks
18569
+ });
18570
+ writeHookScript(hookPath);
18571
+ return [settingsPath, hookPath];
18572
+ };
18573
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18574
+ const installCursorHook = (projectRoot) => {
18575
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18576
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18577
+ const config = readJsonFile(configPath, {});
18578
+ const hooks = { ...config.hooks ?? {} };
18579
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18580
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18581
+ command: CURSOR_HOOK_RELATIVE_PATH,
18582
+ matcher: CURSOR_HOOK_MATCHER,
18583
+ timeout: 120
18584
+ });
18585
+ hooks.postToolUse = postToolUseHooks;
18586
+ writeJsonFile(configPath, {
18587
+ ...config,
18588
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18589
+ hooks
18590
+ });
18591
+ writeHookScript(hookPath);
18592
+ return [configPath, hookPath];
18593
+ };
18594
+ const buildAgentHookScript = () => [
18595
+ "#!/bin/sh",
18596
+ "set -u",
18597
+ "",
18598
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18599
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18600
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18601
+ "cat > \"$input_file\"",
18602
+ "",
18603
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18604
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18605
+ "if [ -z \"$project_root\" ]; then",
18606
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18607
+ "fi",
18608
+ "if ! cd \"$project_root\"; then",
18609
+ " exit 0",
18610
+ "fi",
18611
+ "",
18612
+ "should_scan() {",
18613
+ " if ! command -v node >/dev/null 2>&1; then",
18614
+ " return 0",
18615
+ " fi",
18616
+ "",
18617
+ " node - \"$input_file\" <<'NODE'",
18618
+ "const fs = require('node:fs');",
18619
+ "const inputPath = process.argv[2];",
18620
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18621
+ "try {",
18622
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18623
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18624
+ " if (eventName === 'PostToolBatch') {",
18625
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18626
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18627
+ " }",
18628
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18629
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18630
+ "} catch {",
18631
+ " process.exit(0);",
18632
+ "}",
18633
+ "NODE",
18634
+ "}",
18635
+ "",
18636
+ "run_react_doctor() {",
18637
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18638
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18639
+ " return",
18640
+ " fi",
18641
+ "",
18642
+ " if command -v react-doctor >/dev/null 2>&1; then",
18643
+ " react-doctor --verbose --diff --blocking warning --no-score",
18644
+ " return",
18645
+ " fi",
18646
+ "",
18647
+ " if command -v pnpm >/dev/null 2>&1; then",
18648
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18649
+ " return",
18650
+ " fi",
18651
+ "",
18652
+ " if command -v npx >/dev/null 2>&1; then",
18653
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18654
+ " return",
18655
+ " fi",
18656
+ "",
18657
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18658
+ " return 0",
18659
+ "}",
18660
+ "",
18661
+ "if ! should_scan; then",
18662
+ " exit 0",
18663
+ "fi",
18664
+ "",
18665
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18666
+ " exit 0",
18667
+ "fi",
18668
+ "",
18669
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
18670
+ "const fs = require('node:fs');",
18671
+ "const inputPath = process.argv[2];",
18672
+ "const outputPath = process.argv[3];",
18673
+ "const readInput = () => {",
18674
+ " try {",
18675
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18676
+ " } catch {",
18677
+ " return {};",
18678
+ " }",
18679
+ "};",
18680
+ "const input = readInput();",
18681
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18682
+ "if (!scanOutput) process.exit(0);",
18683
+ "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}`;",
18684
+ "if (input.hook_event_name === 'PostToolBatch') {",
18685
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18686
+ "} else {",
18687
+ " console.log(JSON.stringify({ additional_context: message }));",
18688
+ "}",
18689
+ "NODE",
18690
+ ""
18691
+ ].join("\n");
18692
+ const installReactDoctorAgentHooks = (options) => {
18693
+ const installedAgents = [];
18694
+ const files = [];
18695
+ const requestedAgents = options.agents.filter(isSupportedAgent);
18696
+ for (const agent of requestedAgents) {
18697
+ if (agent === CLAUDE_AGENT) {
18698
+ files.push(...installClaudeHook(options.projectRoot));
18699
+ installedAgents.push(agent);
18700
+ }
18701
+ if (agent === CURSOR_AGENT) {
18702
+ files.push(...installCursorHook(options.projectRoot));
18703
+ installedAgents.push(agent);
18704
+ }
18705
+ }
18706
+ return {
18707
+ installedAgents,
18708
+ files
18709
+ };
18710
+ };
18711
+ //#endregion
18712
+ //#region src/cli/utils/install-git-hook-file.ts
18713
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18714
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18715
+ 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?)`);
18716
+ const SHEBANG = "#!/bin/sh";
18717
+ const SHEBANG_PREFIX = "#!";
18718
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18719
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18720
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18721
+ const buildReactDoctorHookBlock = () => [
18722
+ REACT_DOCTOR_BLOCK_START,
18723
+ "react_doctor_scan_staged_files() {",
18724
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18725
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18726
+ " return",
18727
+ " fi",
18728
+ "",
18277
18729
  " if command -v react-doctor >/dev/null 2>&1; then",
18278
18730
  ` ${REACT_DOCTOR_COMMAND}`,
18279
18731
  " return",
@@ -18652,7 +19104,6 @@ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.js
18652
19104
  //#region src/cli/utils/install-react-doctor.ts
18653
19105
  const SETUP_OPTION_GIT_HOOK = "git-hook";
18654
19106
  const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
18655
- const SETUP_OPTION_WORKFLOW = "workflow";
18656
19107
  const SETUP_OPTION_SKIP = "skip";
18657
19108
  const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
18658
19109
  "ghooks",
@@ -18753,9 +19204,9 @@ const buildInstallCommand = (projectRoot) => {
18753
19204
  cwd: projectRoot
18754
19205
  };
18755
19206
  };
18756
- const execFileAsync$1 = promisify(execFile);
19207
+ const execFileAsync = promisify(execFile);
18757
19208
  const defaultInstallDependencyRunner = async (input) => {
18758
- await execFileAsync$1(input.command, [...input.args], {
19209
+ await execFileAsync(input.command, [...input.args], {
18759
19210
  cwd: input.cwd,
18760
19211
  env: {
18761
19212
  ...process.env,
@@ -18806,17 +19257,6 @@ const formatGitHookInstallMessage = (hookResult) => {
18806
19257
  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
19258
  return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
18808
19259
  };
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(" ");
18819
- };
18820
19260
  const formatDependencyInstallMessage = (result) => {
18821
19261
  if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
18822
19262
  if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
@@ -18829,16 +19269,6 @@ const buildDependencyFollowUp = (result) => {
18829
19269
  if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
18830
19270
  return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
18831
19271
  };
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
- }
18841
- };
18842
19272
  const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
18843
19273
  installReactDoctorScriptStep(projectRoot);
18844
19274
  const dependencySpinner = spinner("Installing React Doctor package...").start();
@@ -18869,119 +19299,33 @@ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) =>
18869
19299
  };
18870
19300
  const getSkillSourceDirectory = () => {
18871
19301
  const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18872
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18873
- };
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;
18896
- };
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
- }] : []
18954
- ];
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;
19302
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19303
+ };
19304
+ const findBundledSiblingSkills = (primarySkillDir) => {
19305
+ const skillsParent = path$1.dirname(primarySkillDir);
19306
+ if (!fs$1.existsSync(skillsParent)) return [];
19307
+ const resolvedPrimary = path$1.resolve(primarySkillDir);
19308
+ return fs$1.readdirSync(skillsParent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => ({
19309
+ name: entry.name,
19310
+ source: path$1.join(skillsParent, entry.name)
19311
+ })).filter((sibling) => path$1.resolve(sibling.source) !== resolvedPrimary && fs$1.existsSync(path$1.join(sibling.source, SKILL_MANIFEST_FILE)));
19312
+ };
19313
+ const installBundledSiblingSkills = async (primarySkillDir, agents, projectRoot) => {
19314
+ const installedSkillNames = [];
19315
+ for (const sibling of findBundledSiblingSkills(primarySkillDir)) {
19316
+ const result = await installSkillsFromSource({
19317
+ source: sibling.source,
19318
+ agents: [...agents],
19319
+ cwd: projectRoot,
19320
+ mode: "copy"
19321
+ });
19322
+ if (result.failed.length > 0) throw new Error(result.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19323
+ if (result.skills.length > 0) installedSkillNames.push(sibling.name);
18984
19324
  }
19325
+ return installedSkillNames;
19326
+ };
19327
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19328
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
18985
19329
  const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
18986
19330
  try {
18987
19331
  const installResult = await installSkillsFromSource({
@@ -18998,317 +19342,185 @@ const runInstallReactDoctor = async (options = {}) => {
18998
19342
  throw error;
18999
19343
  }
19000
19344
  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).");
19005
- }
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
- }
19022
- }
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
- }
19039
- }
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 });
19051
- };
19052
- //#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
- }
19069
- };
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;
19085
- }
19086
- };
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;
19099
- };
19100
- //#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]
19106
- };
19107
- if (process$1.platform === "win32") return {
19108
- command: "cmd",
19109
- args: [
19110
- "/c",
19111
- "start",
19112
- "",
19113
- url
19114
- ]
19115
- };
19116
- return {
19117
- command: "xdg-open",
19118
- args: [url]
19119
- };
19120
- };
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
- const execFileAsync = promisify(execFile);
19144
- const run = async (command, args, cwd) => {
19145
- 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
- };
19155
- } catch (error) {
19156
- const failure = error;
19157
- return {
19158
- success: false,
19159
- stdout: (failure.stdout ?? "").trim(),
19160
- stderr: (failure.stderr ?? "").trim()
19161
- };
19162
- }
19163
- };
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];
19169
- }
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
- };
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, "")}`;
19189
- };
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
- };
19345
+ const installedSiblingSkills = await installBundledSiblingSkills(sourceDir, selectedAgents, projectRoot);
19346
+ if (installedSiblingSkills.length > 0) cliLogger.dim(` Also installed the ${installedSiblingSkills.join(", ")} skill.`);
19347
+ } catch {
19348
+ cliLogger.dim(" Skipped bundled sibling skills (install error).");
19257
19349
  }
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
- };
19350
+ };
19351
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19352
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19353
+ try {
19354
+ const hookResult = installReactDoctorGitHook({
19355
+ hookPath: gitHookTarget.hookPath,
19356
+ projectRoot: gitHookTarget.runnerRoot,
19357
+ kind: gitHookTarget.kind,
19358
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19359
+ });
19360
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19361
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19362
+ } catch (error) {
19363
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19364
+ throw error;
19268
19365
  }
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
- };
19366
+ };
19367
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19368
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19369
+ try {
19370
+ const hookResult = installReactDoctorAgentHooks({
19371
+ projectRoot,
19372
+ agents: selectedAgents
19373
+ });
19374
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19375
+ else {
19376
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19377
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19378
+ }
19379
+ } catch (error) {
19380
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19381
+ throw error;
19280
19382
  }
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
19383
  };
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;
19384
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19385
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19386
+ };
19387
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19388
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19389
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19390
+ if (upgradeResult.status === "failed") {
19391
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19392
+ return false;
19393
+ }
19394
+ if (upgradeResult.status === "not-needed") {
19395
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19396
+ return false;
19397
+ }
19398
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19399
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19400
+ return true;
19401
+ };
19402
+ const runInstallReactDoctor = async (options = {}) => {
19403
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19404
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19405
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19406
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19407
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19408
+ process.exitCode = 1;
19409
+ return;
19410
+ }
19411
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19412
+ if (detectedAgents.length === 0) {
19413
+ cliLogger.error("No supported coding agents detected.");
19414
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19415
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19416
+ process.exitCode = 1;
19417
+ return;
19418
+ }
19419
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19420
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19421
+ const gitHookPath = gitHookTarget?.hookPath;
19422
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19423
+ const prompt = options.prompt ?? prompts;
19424
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19425
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19426
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19427
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19428
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19429
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19430
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19431
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19432
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19433
+ type: "multiselect",
19434
+ name: "agents",
19435
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19436
+ choices: detectedAgents.map((agent) => ({
19437
+ title: getSkillAgentConfig(agent).displayName,
19438
+ value: agent,
19439
+ selected: true
19440
+ })),
19441
+ instructions: false,
19442
+ min: 1
19443
+ }, promptOptions)).agents ?? [];
19444
+ if (selectedAgents.length === 0) return;
19445
+ let dependencyResult;
19446
+ if (!options.dryRun) {
19447
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19448
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19449
+ }
19450
+ let didInstallWorkflow = false;
19451
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19452
+ cliLogger.break();
19453
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19454
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19455
+ }
19456
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19457
+ title: "Pre-commit hook",
19458
+ description: "Check staged changes before each commit",
19459
+ value: SETUP_OPTION_GIT_HOOK,
19460
+ selected: true
19461
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19462
+ title: "Agent hooks",
19463
+ description: "Ask Claude Code or Cursor to scan after code edits",
19464
+ value: SETUP_OPTION_AGENT_HOOKS,
19465
+ selected: Boolean(options.agentHooks)
19466
+ }] : []];
19467
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19468
+ title: "Skip optional setup",
19469
+ description: "Install only the agent skill and package setup",
19470
+ value: SETUP_OPTION_SKIP,
19471
+ selected: false
19472
+ }, ...setupActionChoices];
19473
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19474
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19475
+ type: "multiselect",
19476
+ name: "setupOptions",
19477
+ message: "Select additional React Doctor setup:",
19478
+ choices: setupChoices,
19479
+ instructions: false
19480
+ }, promptOptions)).setupOptions ?? [];
19481
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19482
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19483
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19484
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19485
+ if (!options.dryRun) {
19486
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19487
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19488
+ }
19489
+ if (options.dryRun) {
19490
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19491
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19492
+ cliLogger.dim(` Source: ${sourceDir}`);
19493
+ for (const sibling of findBundledSiblingSkills(sourceDir)) cliLogger.dim(` Also installs skill: ${sibling.name}`);
19494
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19495
+ cliLogger.dim(" Dev dependency: react-doctor");
19496
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19497
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19498
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19499
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19500
+ return;
19501
+ }
19502
+ recordCount(METRIC.installCompleted, 1, {
19503
+ agentsCount: selectedAgents.length,
19504
+ gitHook: shouldInstallGitHook,
19505
+ agentHooks: shouldInstallAgentHooks,
19506
+ workflow: didInstallWorkflow,
19507
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19508
+ packageManager: detectPackageManager(projectRoot)
19509
+ });
19510
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19511
+ };
19512
+ //#endregion
19513
+ //#region src/cli/utils/install-skill-for-agent.ts
19514
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19515
+ const source = getSkillSourceDirectory();
19516
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19517
+ const result = await installSkillsFromSource({
19518
+ source,
19519
+ agents: [agent],
19520
+ cwd: projectRoot,
19521
+ mode: "copy"
19522
+ });
19523
+ return result.skills.length > 0 && result.failed.length === 0;
19312
19524
  };
19313
19525
  //#endregion
19314
19526
  //#region src/cli/utils/launch-agent.ts
@@ -19399,9 +19611,6 @@ const copyToClipboard = (text) => {
19399
19611
  };
19400
19612
  //#endregion
19401
19613
  //#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
19614
  const CLIPBOARD_CHOICE = "clipboard";
19406
19615
  const SKIP_CHOICE = "skip";
19407
19616
  const printPayload = (payload) => {
@@ -19410,59 +19619,11 @@ const printPayload = (payload) => {
19410
19619
  cliLogger.log(payload);
19411
19620
  cliLogger.log(highlighter.dim("──────────────────────"));
19412
19621
  };
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
19622
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19442
19623
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19443
19624
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19444
19625
 
19445
19626
  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
19627
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19467
19628
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19468
19629
  if (!changed) return false;
@@ -19507,46 +19668,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19507
19668
  }
19508
19669
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19509
19670
  };
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
19671
  const detectLaunchableAgents = async () => {
19551
19672
  const detected = new Set(await detectAvailableAgents());
19552
19673
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19563,7 +19684,7 @@ const handoffToAgent = async (input) => {
19563
19684
  });
19564
19685
  if (ciOutcome === "cancel") return;
19565
19686
  if (ciOutcome === "yes") {
19566
- await setUpGitHubActions(input.rootDirectory);
19687
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19567
19688
  cliLogger.break();
19568
19689
  }
19569
19690
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19714,6 +19835,14 @@ const HAPPY_FACE_LINES = [
19714
19835
  "│ ▽ │",
19715
19836
  "└─────┘"
19716
19837
  ];
19838
+ const FACE_INDENT = " ";
19839
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
19840
+ const clampToColumns = (text, maxColumns) => {
19841
+ if (maxColumns <= 0) return "";
19842
+ if (text.length <= maxColumns) return text;
19843
+ if (maxColumns === 1) return "…";
19844
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
19845
+ };
19717
19846
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19718
19847
  const characters = [...text];
19719
19848
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19727,13 +19856,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19727
19856
  const interLineDelayMs = 250 / speedMultiplier;
19728
19857
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19729
19858
  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`);
19859
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
19860
+ const terminalColumns = process.stdout.columns;
19861
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
19862
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
19863
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
19864
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19732
19865
  yield* writeStdout("\x1B[3A");
19733
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
19866
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19734
19867
  yield* Effect.sleep(interLineDelayMs);
19735
19868
  yield* writeStdout("\x1B[1B");
19736
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
19869
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19737
19870
  yield* Effect.sleep(explanationHoldMs);
19738
19871
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19739
19872
  });
@@ -20273,8 +20406,8 @@ const buildChangedFilesDiffInfo = (changedFiles) => ({
20273
20406
  * `react-doctor.config.json` to `doctor.config.ts` before config is loaded,
20274
20407
  * so the scan reads the renamed file and the user is told once. CI, coding
20275
20408
  * 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.
20409
+ * are left untouched — the loader still reads the legacy file as a deprecated
20410
+ * fallback and warns — so a scan never mutates the repo unattended.
20278
20411
  */
20279
20412
  const maybeMigrateLegacyConfig = (requestedDirectory, { isQuiet, isStaged }) => {
20280
20413
  if (!(!isQuiet && !isStaged && process.stdout.isTTY === true && !isCiOrCodingAgentEnvironment())) return;
@@ -20636,13 +20769,27 @@ const resolveRuleConfigTarget = async (projectRoot) => {
20636
20769
  config: isPlainObject(embedded) ? embedded : {}
20637
20770
  };
20638
20771
  }
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
- };
20772
+ if (loaded.format === "json") {
20773
+ if (path$1.basename(loaded.configFilePath) === "react-doctor.config.json") {
20774
+ const legacyConfig = readObjectFile(loaded.configFilePath) ?? {};
20775
+ delete legacyConfig.$schema;
20776
+ return {
20777
+ format: "json",
20778
+ filePath: path$1.join(loaded.sourceDirectory, NEW_CONFIG_FILENAME),
20779
+ directory: loaded.sourceDirectory,
20780
+ exists: false,
20781
+ config: legacyConfig,
20782
+ migratedFromFilePath: loaded.configFilePath
20783
+ };
20784
+ }
20785
+ return {
20786
+ format: "json",
20787
+ filePath: loaded.configFilePath,
20788
+ directory: loaded.sourceDirectory,
20789
+ exists: true,
20790
+ config: readObjectFile(loaded.configFilePath) ?? {}
20791
+ };
20792
+ }
20646
20793
  return {
20647
20794
  format: "module",
20648
20795
  filePath: loaded.configFilePath,
@@ -20721,7 +20868,10 @@ const writeRuleConfig = async (target, nextConfig) => {
20721
20868
  return { written };
20722
20869
  }
20723
20870
  if (target.format === "package-json") writePackageJsonConfig(target.filePath, nextConfig);
20724
- else writeJsonConfig(target.filePath, nextConfig);
20871
+ else {
20872
+ writeJsonConfig(target.filePath, nextConfig);
20873
+ if (target.migratedFromFilePath) fs$1.rmSync(target.migratedFromFilePath, { force: true });
20874
+ }
20725
20875
  clearConfigCache();
20726
20876
  return { written: true };
20727
20877
  };
@@ -21472,4 +21622,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21472
21622
  export {};
21473
21623
 
21474
21624
  //# sourceMappingURL=cli.js.map
21475
- //# debugId=30809678-4fe4-55cc-938c-ee6301ab7888
21625
+ //# debugId=92822f58-92ef-58d5-8850-2746c0b48fc0