react-doctor 0.4.2-dev.7cf52d8 → 0.4.2-dev.af98f83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1486eaee-ed07-5eef-a9d7-51293140e237")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="de2dd8ab-0280-54a5-852a-2a7dca2192fe")}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;
@@ -6724,7 +6725,6 @@ const LEGACY_RULE_KEY_TO_NATIVE_RULE_KEY = {
6724
6725
  "react/jsx-no-new-function-as-prop": "react-doctor/jsx-no-new-function-as-prop",
6725
6726
  "react/jsx-no-new-object-as-prop": "react-doctor/jsx-no-new-object-as-prop",
6726
6727
  "react/jsx-no-script-url": "react-doctor/jsx-no-script-url",
6727
- "react/jsx-no-target-blank": "react-doctor/jsx-no-target-blank",
6728
6728
  "react/jsx-no-undef": "react-doctor/jsx-no-undef",
6729
6729
  "react/jsx-no-useless-fragment": "react-doctor/jsx-no-useless-fragment",
6730
6730
  "react/jsx-pascal-case": "react-doctor/jsx-pascal-case",
@@ -12247,7 +12247,7 @@ const makeNoopConsole = () => ({
12247
12247
  });
12248
12248
  //#endregion
12249
12249
  //#region src/cli/utils/version.ts
12250
- const VERSION = "0.4.2-dev.7cf52d8";
12250
+ const VERSION = "0.4.2-dev.af98f83";
12251
12251
  //#endregion
12252
12252
  //#region src/cli/utils/json-mode.ts
12253
12253
  let context = null;
@@ -12605,13 +12605,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12605
12605
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12606
12606
  * standard `SENTRY_RELEASE` override.
12607
12607
  */
12608
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.7cf52d8`;
12608
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.4.2-dev.af98f83`;
12609
12609
  /**
12610
12610
  * Deployment environment shown in Sentry's environment filter. Defaults to
12611
12611
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12612
12612
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12613
12613
  */
12614
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.7cf52d8") ? "development" : "production");
12614
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.4.2-dev.af98f83") ? "development" : "production");
12615
12615
  /**
12616
12616
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12617
12617
  * (set to `0` to disable tracing) and falls back to
@@ -16473,8 +16473,22 @@ const buildCodeFrame = (input) => {
16473
16473
  });
16474
16474
  };
16475
16475
  //#endregion
16476
+ //#region src/cli/utils/resolve-measure-width.ts
16477
+ const resolveClampedWidth = (input) => {
16478
+ const terminalColumns = process.stdout.columns;
16479
+ if (!terminalColumns || terminalColumns <= 0) return input.fullWidth;
16480
+ const availableColumns = terminalColumns - input.reservedColumns;
16481
+ return Math.max(input.minWidth, Math.min(input.fullWidth, availableColumns));
16482
+ };
16483
+ const resolveMeasureWidth = (reservedColumns = 0) => resolveClampedWidth({
16484
+ reservedColumns,
16485
+ fullWidth: 60,
16486
+ minWidth: 24
16487
+ });
16488
+ //#endregion
16476
16489
  //#region src/cli/utils/build-section-divider.ts
16477
- const buildSectionDivider = () => highlighter.dim(` ${"─".repeat(60)}`);
16490
+ const DIVIDER_INDENT = " ";
16491
+ const buildSectionDivider = () => highlighter.dim(`${DIVIDER_INDENT}${"─".repeat(resolveMeasureWidth(2))}`);
16478
16492
  //#endregion
16479
16493
  //#region src/cli/utils/indent-multiline-text.ts
16480
16494
  const indentMultilineText = (text, linePrefix) => text.split("\n").map((lineText) => `${linePrefix}${lineText}`).join("\n");
@@ -16634,7 +16648,10 @@ const buildDiagnosticClusterLines = (cluster, resolveSourceRoot, renderCodeFrame
16634
16648
  endLine: isMultiSite ? cluster.endLine : void 0,
16635
16649
  rootDirectory: resolveSourceRoot(lead)
16636
16650
  }) : null;
16637
- if (codeFrame) lines.push(indentMultilineText(boxText(codeFrame, 60), TOP_ERROR_DETAIL_INDENT));
16651
+ if (codeFrame) {
16652
+ const boxInnerWidth = resolveMeasureWidth(8);
16653
+ lines.push(indentMultilineText(boxText(codeFrame, boxInnerWidth), TOP_ERROR_DETAIL_INDENT));
16654
+ }
16638
16655
  const seenHints = /* @__PURE__ */ new Set();
16639
16656
  for (const diagnostic of cluster.diagnostics) if (diagnostic.suppressionHint && !seenHints.has(diagnostic.suppressionHint)) {
16640
16657
  seenHints.add(diagnostic.suppressionHint);
@@ -16652,8 +16669,8 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16652
16669
  const learnMoreLine = formatLearnMoreLine(representative);
16653
16670
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
16654
16671
  }
16655
- if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, 60, { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16656
- if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, 60, { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16672
+ if (!renderEverySite) for (const explanationLine of wrapTextToWidth(representative.message, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(`${TOP_ERROR_DETAIL_INDENT}${explanationLine}`);
16673
+ if (representative.help) for (const fixLine of wrapTextToWidth(`→ ${representative.help}`, resolveMeasureWidth(4), { breakLongWords: false })) lines.push(highlighter.dim(`${TOP_ERROR_DETAIL_INDENT}${fixLine}`));
16657
16674
  if (renderEverySite && isAgentEnvironment) {
16658
16675
  const fixRecipeLine = formatFixRecipeLine(representative);
16659
16676
  if (fixRecipeLine) lines.push(highlighter.gray(`${TOP_ERROR_DETAIL_INDENT}${fixRecipeLine}`));
@@ -16847,14 +16864,21 @@ const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16847
16864
  const RAINBOW_GRADIENT_WIDTH = 80;
16848
16865
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16849
16866
  const RAINBOW_OKLCH_CHROMA = .129;
16867
+ const FACE_BOX_TOP_BORDER = "┌─────┐";
16868
+ const SCORE_RIGHT_COLUMN_OFFSET = 11;
16869
+ const getScoreBarWidth = () => resolveClampedWidth({
16870
+ reservedColumns: SCORE_RIGHT_COLUMN_OFFSET + 1,
16871
+ fullWidth: 50,
16872
+ minWidth: 10
16873
+ });
16850
16874
  const buildScoreBarSegments = (filledCount) => {
16851
- const emptyCount = 50 - filledCount;
16875
+ const emptyCount = Math.max(0, getScoreBarWidth() - filledCount);
16852
16876
  return {
16853
16877
  filledSegment: "█".repeat(filledCount),
16854
16878
  emptySegment: "░".repeat(emptyCount)
16855
16879
  };
16856
16880
  };
16857
- const getFilledCount = (score) => Math.round(score / 100 * 50);
16881
+ const getFilledCount = (score) => Math.round(score / 100 * getScoreBarWidth());
16858
16882
  const joinScoreHeaderFrame = (lines) => `${lines[0]}\n\r${lines[1]}\n\r${lines[2]}\n\r${lines[3]}\n`;
16859
16883
  const buildRawScoreBar = (displayScore) => {
16860
16884
  const { filledSegment, emptySegment } = buildScoreBarSegments(getFilledCount(displayScore));
@@ -16890,10 +16914,11 @@ const buildScoreBar = (displayScore, colorScore = displayScore) => {
16890
16914
  return colorizeByScore(filledSegment, colorScore) + highlighter.dim(emptySegment);
16891
16915
  };
16892
16916
  const buildProjectedScoreBar = (currentScore, potentialScore) => {
16917
+ const barWidth = getScoreBarWidth();
16893
16918
  const currentFill = getFilledCount(currentScore);
16894
- const potentialFill = Math.min(getFilledCount(potentialScore), 50);
16919
+ const potentialFill = Math.min(getFilledCount(potentialScore), barWidth);
16895
16920
  const gainCount = Math.max(0, potentialFill - currentFill);
16896
- const emptyCount = Math.max(0, 50 - currentFill - gainCount);
16921
+ const emptyCount = Math.max(0, barWidth - currentFill - gainCount);
16897
16922
  return colorizeByScore("█".repeat(currentFill), currentScore) + highlighter.dim(colorizeByScore("▓".repeat(gainCount), currentScore)) + highlighter.dim("░".repeat(emptyCount));
16898
16923
  };
16899
16924
  const getDoctorFace = (score) => {
@@ -16906,7 +16931,7 @@ const RAW_BRANDING_LINE = "React Doctor (https://react.doctor)";
16906
16931
  const buildRawFaceLines = (score) => {
16907
16932
  const [eyes, mouth] = getDoctorFace(score);
16908
16933
  return [
16909
- "┌─────┐",
16934
+ FACE_BOX_TOP_BORDER,
16910
16935
  `│ ${eyes} │`,
16911
16936
  `│ ${mouth} │`,
16912
16937
  "└─────┘"
@@ -17048,6 +17073,11 @@ const writeDiagnosticsDirectory = (diagnostics) => {
17048
17073
  };
17049
17074
  //#endregion
17050
17075
  //#region src/cli/utils/render-summary.ts
17076
+ const FOOTER_DESCRIPTION_INDENT = " ";
17077
+ const printFooterDescription = (description) => Effect.gen(function* () {
17078
+ const wrapWidth = resolveMeasureWidth(2);
17079
+ for (const line of wrapTextToWidth(description, wrapWidth)) yield* Console.log(highlighter.dim(`${FOOTER_DESCRIPTION_INDENT}${line}`));
17080
+ });
17051
17081
  const buildShareUrl = (diagnostics, scoreResult, projectName) => {
17052
17082
  const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
17053
17083
  const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
@@ -17067,14 +17097,14 @@ const printFooter = (input) => Effect.gen(function* () {
17067
17097
  if (!input.isOffline) {
17068
17098
  const shareUrl = buildShareUrl(input.diagnostics, input.scoreResult, input.projectName);
17069
17099
  yield* Console.log(` ${highlighter.bold("Share:")} ${highlighter.info(shareUrl)}`);
17070
- yield* Console.log(highlighter.dim(" Tell others how you did on socials"));
17100
+ yield* printFooterDescription("Tell others how you did on socials");
17071
17101
  yield* Console.log("");
17072
17102
  }
17073
17103
  yield* Console.log(` ${highlighter.bold("Docs:")} ${highlighter.info(DOCS_URL)}`);
17074
- yield* Console.log(highlighter.dim(" Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file"));
17104
+ yield* printFooterDescription("Learn more about fixing issues, setting up CI/CD, and configuring rules with a config file");
17075
17105
  yield* Console.log("");
17076
17106
  yield* Console.log(` ${highlighter.bold("GitHub:")} ${highlighter.info(CANONICAL_GITHUB_URL)}`);
17077
- yield* Console.log(highlighter.dim(" Report issues and star the repository!"));
17107
+ yield* printFooterDescription("Report issues and star the repository!");
17078
17108
  });
17079
17109
  const printSummary = (input) => Effect.gen(function* () {
17080
17110
  if (input.scoreResult) {
@@ -17980,190 +18010,24 @@ const installDoctorScript = (options) => {
17980
18010
  ...scriptTarget.reason !== void 0 ? { scriptReason: scriptTarget.reason } : {}
17981
18011
  };
17982
18012
  };
17983
- //#endregion
17984
- //#region src/cli/utils/install-agent-hooks.ts
17985
- const CLAUDE_AGENT = "claude-code";
17986
- const CURSOR_AGENT = "cursor";
17987
- const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
17988
- const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
17989
- const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
17990
- const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
17991
- const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
17992
- const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
17993
- const CURSOR_HOOKS_SCHEMA_VERSION = 1;
17994
- const JSON_INDENT_SPACES$1 = 2;
17995
- const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
17996
- const readJsonFile = (filePath, fallback) => {
17997
- if (!fs$1.existsSync(filePath)) return fallback;
17998
- const content = fs$1.readFileSync(filePath, "utf8").trim();
17999
- if (content.length === 0) return fallback;
18000
- return JSON.parse(content);
18001
- };
18002
- const writeJsonFile = (filePath, value) => {
18003
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18004
- fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18005
- };
18006
- const writeHookScript = (filePath) => {
18007
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18008
- fs$1.writeFileSync(filePath, buildAgentHookScript());
18009
- fs$1.chmodSync(filePath, 493);
18010
- };
18011
- const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18012
- const installClaudeHook = (projectRoot) => {
18013
- const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18014
- const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18015
- const settings = readJsonFile(settingsPath, {});
18016
- const hooks = { ...settings.hooks ?? {} };
18017
- const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18018
- if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18019
- type: "command",
18020
- command: CLAUDE_HOOK_COMMAND
18021
- }] });
18022
- hooks.PostToolBatch = postToolBatchHooks;
18023
- writeJsonFile(settingsPath, {
18024
- ...settings,
18025
- hooks
18026
- });
18027
- writeHookScript(hookPath);
18028
- return [settingsPath, hookPath];
18029
- };
18030
- const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18031
- const installCursorHook = (projectRoot) => {
18032
- const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18033
- const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18034
- const config = readJsonFile(configPath, {});
18035
- const hooks = { ...config.hooks ?? {} };
18036
- const postToolUseHooks = [...hooks.postToolUse ?? []];
18037
- if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18038
- command: CURSOR_HOOK_RELATIVE_PATH,
18039
- matcher: CURSOR_HOOK_MATCHER,
18040
- timeout: 120
18041
- });
18042
- hooks.postToolUse = postToolUseHooks;
18043
- writeJsonFile(configPath, {
18044
- ...config,
18045
- version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18046
- hooks
18047
- });
18048
- writeHookScript(hookPath);
18049
- return [configPath, hookPath];
18013
+ const formatDoctorScriptInstallMessage = (scriptResult) => {
18014
+ const scriptName = scriptResult.scriptName ?? "doctor";
18015
+ if (scriptResult.scriptStatus === "created") return `Added package script: ${scriptName}.`;
18016
+ if (scriptResult.scriptStatus === "existing") return `Package script already exists: ${scriptName}.`;
18017
+ if (scriptResult.scriptReason === "script-names-taken") return "Skipped package script: doctor and react-doctor are already taken.";
18018
+ if (scriptResult.scriptReason === "doctor-script-taken") return "Skipped package script: doctor and react-doctor scripts already exist.";
18019
+ if (scriptResult.scriptReason === "invalid-scripts") return "Skipped package script: scripts field is not an object.";
18020
+ return "Skipped package script: package.json missing or invalid.";
18050
18021
  };
18051
- const buildAgentHookScript = () => [
18052
- "#!/bin/sh",
18053
- "set -u",
18054
- "",
18055
- "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18056
- "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18057
- "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18058
- "cat > \"$input_file\"",
18059
- "",
18060
- "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18061
- "project_root=${CLAUDE_PROJECT_DIR:-}",
18062
- "if [ -z \"$project_root\" ]; then",
18063
- " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18064
- "fi",
18065
- "if ! cd \"$project_root\"; then",
18066
- " exit 0",
18067
- "fi",
18068
- "",
18069
- "should_scan() {",
18070
- " if ! command -v node >/dev/null 2>&1; then",
18071
- " return 0",
18072
- " fi",
18073
- "",
18074
- " node - \"$input_file\" <<'NODE'",
18075
- "const fs = require('node:fs');",
18076
- "const inputPath = process.argv[2];",
18077
- "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18078
- "try {",
18079
- " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18080
- " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18081
- " if (eventName === 'PostToolBatch') {",
18082
- " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18083
- " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18084
- " }",
18085
- " const toolName = input.tool_name || input.toolName || input.tool;",
18086
- " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18087
- "} catch {",
18088
- " process.exit(0);",
18089
- "}",
18090
- "NODE",
18091
- "}",
18092
- "",
18093
- "run_react_doctor() {",
18094
- " if [ -x ./node_modules/.bin/react-doctor ]; then",
18095
- " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18096
- " return",
18097
- " fi",
18098
- "",
18099
- " if command -v react-doctor >/dev/null 2>&1; then",
18100
- " react-doctor --verbose --diff --blocking warning --no-score",
18101
- " return",
18102
- " fi",
18103
- "",
18104
- " if command -v pnpm >/dev/null 2>&1; then",
18105
- " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18106
- " return",
18107
- " fi",
18108
- "",
18109
- " if command -v npx >/dev/null 2>&1; then",
18110
- " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18111
- " return",
18112
- " fi",
18113
- "",
18114
- " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18115
- " return 0",
18116
- "}",
18117
- "",
18118
- "if ! should_scan; then",
18119
- " exit 0",
18120
- "fi",
18121
- "",
18122
- "if run_react_doctor > \"$output_file\" 2>&1; then",
18123
- " exit 0",
18124
- "fi",
18125
- "",
18126
- "node - \"$input_file\" \"$output_file\" <<'NODE'",
18127
- "const fs = require('node:fs');",
18128
- "const inputPath = process.argv[2];",
18129
- "const outputPath = process.argv[3];",
18130
- "const readInput = () => {",
18131
- " try {",
18132
- " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18133
- " } catch {",
18134
- " return {};",
18135
- " }",
18136
- "};",
18137
- "const input = readInput();",
18138
- "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18139
- "if (!scanOutput) process.exit(0);",
18140
- "const message = `React Doctor found issues in the changed files. Review this output and fix the regressions before finishing. For confirmed issues that cannot be fixed now, create GitHub issues with the rule, file/line, confidence, impact, and proposed fix.\\n\\n${scanOutput}`;",
18141
- "if (input.hook_event_name === 'PostToolBatch') {",
18142
- " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18143
- "} else {",
18144
- " console.log(JSON.stringify({ additional_context: message }));",
18145
- "}",
18146
- "NODE",
18147
- ""
18148
- ].join("\n");
18149
- const installReactDoctorAgentHooks = (options) => {
18150
- const installedAgents = [];
18151
- const files = [];
18152
- const requestedAgents = options.agents.filter(isSupportedAgent);
18153
- for (const agent of requestedAgents) {
18154
- if (agent === CLAUDE_AGENT) {
18155
- files.push(...installClaudeHook(options.projectRoot));
18156
- installedAgents.push(agent);
18157
- }
18158
- if (agent === CURSOR_AGENT) {
18159
- files.push(...installCursorHook(options.projectRoot));
18160
- installedAgents.push(agent);
18161
- }
18022
+ const installReactDoctorScriptStep = (projectRoot) => {
18023
+ const scriptSpinner = spinner("Installing React Doctor package script...").start();
18024
+ try {
18025
+ const scriptResult = installDoctorScript({ projectRoot });
18026
+ scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18027
+ } catch (error) {
18028
+ scriptSpinner.fail("Failed to install React Doctor package script.");
18029
+ throw error;
18162
18030
  }
18163
- return {
18164
- installedAgents,
18165
- files
18166
- };
18167
18031
  };
18168
18032
  //#endregion
18169
18033
  //#region src/cli/utils/install-github-workflow.ts
@@ -18273,1074 +18137,1359 @@ const installReactDoctorWorkflow = (projectRoot) => {
18273
18137
  };
18274
18138
  }
18275
18139
  };
18140
+ const upgradeReactDoctorWorkflowInPlace = (projectRoot) => {
18141
+ const workflow = readReactDoctorWorkflow(projectRoot);
18142
+ if (!workflow) return {
18143
+ status: "not-needed",
18144
+ workflowPath: getReactDoctorWorkflowPath(projectRoot)
18145
+ };
18146
+ const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
18147
+ if (!changed) return {
18148
+ status: "not-needed",
18149
+ workflowPath: workflow.workflowPath
18150
+ };
18151
+ try {
18152
+ fs$1.writeFileSync(workflow.workflowPath, content);
18153
+ return {
18154
+ status: "upgraded",
18155
+ workflowPath: workflow.workflowPath
18156
+ };
18157
+ } catch {
18158
+ return {
18159
+ status: "failed",
18160
+ workflowPath: workflow.workflowPath
18161
+ };
18162
+ }
18163
+ };
18276
18164
  //#endregion
18277
- //#region src/cli/utils/report-workflow-result.ts
18278
- const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18279
- if (result.status === "failed") {
18280
- workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18281
- return false;
18165
+ //#region src/cli/utils/hash-project-root.ts
18166
+ const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
18167
+ //#endregion
18168
+ //#region src/cli/utils/action-upgrade-prompt.ts
18169
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
18170
+ const getActionUpgradeStore = (options = {}) => new Conf({
18171
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
18172
+ cwd: options.cwd
18173
+ });
18174
+ const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
18175
+ try {
18176
+ const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
18177
+ return Boolean(upgrades[hashProjectRoot(projectRoot)]);
18178
+ } catch {
18179
+ return true;
18282
18180
  }
18283
- if (result.status === "exists") {
18284
- workflowSpinner.succeed("GitHub Actions workflow already configured.");
18181
+ };
18182
+ const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
18183
+ try {
18184
+ const store = getActionUpgradeStore(storeOptions);
18185
+ const upgrades = store.get("actionUpgrades", {});
18186
+ store.set("actionUpgrades", {
18187
+ ...upgrades,
18188
+ [hashProjectRoot(projectRoot)]: {
18189
+ rootDirectory: path$1.resolve(projectRoot),
18190
+ outcome,
18191
+ at: (/* @__PURE__ */ new Date()).toISOString()
18192
+ }
18193
+ });
18194
+ return true;
18195
+ } catch {
18285
18196
  return false;
18286
18197
  }
18287
- workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18288
- recordCount(METRIC.installWorkflow, 1);
18289
- return true;
18290
18198
  };
18291
18199
  //#endregion
18292
- //#region src/cli/utils/install-git-hook-file.ts
18293
- const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18294
- const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18295
- const REACT_DOCTOR_BLOCK_PATTERN = new RegExp(`(?:${REACT_DOCTOR_BLOCK_START}[\\s\\S]*?${REACT_DOCTOR_BLOCK_END}\\n?|# react-doctor hook launcher start[\\s\\S]*?# react-doctor hook launcher end\\n?)`);
18296
- const SHEBANG = "#!/bin/sh";
18297
- const SHEBANG_PREFIX = "#!";
18298
- const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18299
- const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18300
- const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18301
- const buildReactDoctorHookBlock = () => [
18302
- REACT_DOCTOR_BLOCK_START,
18303
- "react_doctor_scan_staged_files() {",
18304
- ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18305
- ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18306
- " return",
18307
- " fi",
18308
- "",
18309
- " if command -v react-doctor >/dev/null 2>&1; then",
18310
- ` ${REACT_DOCTOR_COMMAND}`,
18311
- " return",
18312
- " fi",
18313
- "",
18314
- " if command -v pnpm >/dev/null 2>&1; then",
18315
- ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18316
- " return",
18317
- " fi",
18318
- "",
18319
- " if command -v npx >/dev/null 2>&1; then",
18320
- ` ${NPX_REACT_DOCTOR_COMMAND}`,
18321
- " return",
18322
- " fi",
18323
- "",
18324
- " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18325
- "}",
18326
- "",
18327
- "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18328
- "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18329
- " rm -f \"$react_doctor_output\"",
18330
- "else",
18331
- " rm -f \"$react_doctor_output\"",
18332
- ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
18333
- "fi",
18334
- REACT_DOCTOR_BLOCK_END
18335
- ].join("\n");
18336
- const mergeHookContent = (existingContent) => {
18337
- const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18338
- if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18339
- if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18340
- const normalizedExistingContent = ensureTrailingNewline(existingContent);
18341
- if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18342
- const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18343
- return [
18344
- shebangLine,
18200
+ //#region src/cli/utils/open-url.ts
18201
+ const resolveOpenCommand = (url) => {
18202
+ if (process$1.platform === "darwin") return {
18203
+ command: "open",
18204
+ args: [url]
18205
+ };
18206
+ if (process$1.platform === "win32") return {
18207
+ command: "cmd",
18208
+ args: [
18209
+ "/c",
18210
+ "start",
18345
18211
  "",
18346
- hookBlock.trimEnd(),
18347
- ...remainingLines
18348
- ].join("\n");
18349
- }
18350
- return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18351
- };
18352
- const removeLegacyManagedRunner = (projectRoot) => {
18353
- const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18354
- fs$1.rmSync(runnerPath, { force: true });
18355
- for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18356
- fs$1.rmdirSync(directory);
18357
- } catch {}
18358
- };
18359
- const installDirectGitHook = (options) => {
18360
- const didHookExist = fs$1.existsSync(options.hookPath);
18361
- const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18362
- if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18363
- "config",
18364
- "core.hooksPath",
18365
- options.hooksPathConfig
18366
- ]);
18367
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18368
- fs$1.writeFileSync(options.hookPath, nextContent);
18369
- fs$1.chmodSync(options.hookPath, 493);
18370
- removeLegacyManagedRunner(options.projectRoot);
18212
+ url
18213
+ ]
18214
+ };
18371
18215
  return {
18372
- hookPath: options.hookPath,
18373
- kind: options.kind ?? "git",
18374
- status: didHookExist ? "updated" : "created"
18216
+ command: "xdg-open",
18217
+ args: [url]
18375
18218
  };
18376
18219
  };
18220
+ const openUrl = (url) => {
18221
+ try {
18222
+ const { command, args } = resolveOpenCommand(url);
18223
+ const child = spawn(command, args, {
18224
+ detached: true,
18225
+ stdio: "ignore"
18226
+ });
18227
+ child.on("error", () => {});
18228
+ child.unref();
18229
+ return true;
18230
+ } catch {
18231
+ return false;
18232
+ }
18233
+ };
18377
18234
  //#endregion
18378
- //#region src/cli/utils/install-git-hook-config-managers.ts
18379
- const appendStringCommand = (existingCommand) => {
18380
- const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18381
- return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18235
+ //#region src/cli/utils/ask-add-to-github-actions.ts
18236
+ const CI_YES_CHOICE = "ci-yes";
18237
+ const CI_LEARN_MORE_CHOICE = "ci-learn-more";
18238
+ const CI_NO_CHOICE = "ci-no";
18239
+ const SGR_BOLD_OFF = "\x1B[22m";
18240
+ const ciQuestionMessage = [
18241
+ "Add React Doctor to GitHub Actions?",
18242
+ `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
18243
+ `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
18244
+ ].join("\n");
18245
+ const askAddToGitHubActions = async (prompt = prompts) => {
18246
+ while (true) {
18247
+ const { ciChoice } = await prompt({
18248
+ type: "select",
18249
+ name: "ciChoice",
18250
+ message: ciQuestionMessage,
18251
+ hint: " ",
18252
+ choices: [
18253
+ {
18254
+ title: "Yes",
18255
+ description: "Adds the workflow file and a doctor package script",
18256
+ value: CI_YES_CHOICE
18257
+ },
18258
+ {
18259
+ title: "Learn more",
18260
+ description: "Opens the docs page in your browser",
18261
+ value: CI_LEARN_MORE_CHOICE
18262
+ },
18263
+ {
18264
+ title: "No",
18265
+ description: "Skip for now",
18266
+ value: CI_NO_CHOICE
18267
+ }
18268
+ ],
18269
+ initial: 0
18270
+ }, { onCancel: () => true });
18271
+ if (ciChoice === void 0) return "cancel";
18272
+ if (ciChoice === CI_YES_CHOICE) return "yes";
18273
+ if (ciChoice === CI_NO_CHOICE) return "no";
18274
+ const opened = openUrl(GITHUB_ACTIONS_SETUP_URL);
18275
+ cliLogger.log(opened ? `Opened ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} in your browser.` : `Visit ${highlighter.info(GITHUB_ACTIONS_SETUP_URL)} to learn more.`);
18276
+ cliLogger.break();
18277
+ }
18382
18278
  };
18383
- const appendArrayCommand = (existingCommands) => {
18384
- const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18385
- return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18279
+ //#endregion
18280
+ //#region src/cli/utils/ask-upgrade-action-version.ts
18281
+ const UPGRADE_YES_CHOICE = "upgrade-yes";
18282
+ const UPGRADE_NO_CHOICE = "upgrade-no";
18283
+ const askUpgradeActionVersion = async (prompt = prompts) => {
18284
+ const { upgradeChoice } = await prompt({
18285
+ type: "select",
18286
+ name: "upgradeChoice",
18287
+ message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
18288
+ hint: " ",
18289
+ choices: [{
18290
+ title: "Yes (recommended)",
18291
+ description: "Bump the workflow to millionco/react-doctor@v2",
18292
+ value: UPGRADE_YES_CHOICE
18293
+ }, {
18294
+ title: "No, thanks",
18295
+ description: "Keep @v1 — won't ask again for this repo",
18296
+ value: UPGRADE_NO_CHOICE
18297
+ }],
18298
+ initial: 0
18299
+ }, { onCancel: () => true });
18300
+ if (upgradeChoice === void 0) return "cancel";
18301
+ return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
18386
18302
  };
18387
- const installPackageJsonHook = (options, strategy) => {
18388
- const packageJsonPath = getPackageJsonPath(options.projectRoot);
18389
- const didHookExist = fs$1.existsSync(packageJsonPath);
18390
- const packageJson = readPackageJson(options.projectRoot);
18391
- const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18392
- const parentKeys = strategy.path.slice(0, -1);
18393
- const leafKey = strategy.path[strategy.path.length - 1];
18394
- let parent = nextPackageJson;
18395
- for (const key of parentKeys) {
18396
- const existing = parent[key];
18397
- const cloned = isRecord(existing) ? { ...existing } : {};
18398
- parent[key] = cloned;
18399
- parent = cloned;
18303
+ //#endregion
18304
+ //#region src/cli/utils/open-workflow-pull-request.ts
18305
+ const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
18306
+ const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
18307
+ const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
18308
+ 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.
18309
+
18310
+ Docs: https://www.react.doctor/ci`;
18311
+ const execFileAsync$1 = promisify(execFile);
18312
+ const run = async (command, args, cwd) => {
18313
+ try {
18314
+ const { stdout, stderr } = await execFileAsync$1(command, [...args], {
18315
+ cwd,
18316
+ encoding: "utf8"
18317
+ });
18318
+ return {
18319
+ success: true,
18320
+ stdout: stdout.trim(),
18321
+ stderr: stderr.trim()
18322
+ };
18323
+ } catch (error) {
18324
+ const failure = error;
18325
+ return {
18326
+ success: false,
18327
+ stdout: (failure.stdout ?? "").trim(),
18328
+ stderr: (failure.stderr ?? "").trim()
18329
+ };
18400
18330
  }
18401
- parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18402
- writeJsonFile$1(packageJsonPath, nextPackageJson);
18403
- removeLegacyManagedRunner(options.projectRoot);
18404
- return {
18405
- hookPath: packageJsonPath,
18406
- kind: strategy.kind,
18407
- status: didHookExist ? "updated" : "created"
18408
- };
18409
18331
  };
18410
- const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18411
- kind: "simple-git-hooks",
18412
- path: ["simple-git-hooks", "pre-commit"],
18413
- leafShape: "string"
18414
- });
18415
- const installGhooks = (options) => installPackageJsonHook(options, {
18416
- kind: "ghooks",
18417
- path: [
18418
- "config",
18419
- "ghooks",
18420
- "pre-commit"
18421
- ],
18422
- leafShape: "string"
18423
- });
18424
- const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18425
- kind: "pre-commit-npm",
18426
- path: ["pre-commit"],
18427
- leafShape: "array"
18428
- });
18429
- const installPrettyQuick = (options) => installPackageJsonHook(options, {
18430
- kind: "pretty-quick",
18431
- path: ["gitHooks", "pre-commit"],
18432
- leafShape: "string"
18433
- });
18434
- const installYorkie = (options) => installPackageJsonHook(options, {
18435
- kind: "yorkie",
18436
- path: ["gitHooks", "pre-commit"],
18437
- leafShape: "string"
18438
- });
18439
- const installGitHooksJs = (options) => installPackageJsonHook(options, {
18440
- kind: "git-hooks-js",
18441
- path: ["git-hooks", "pre-commit"],
18442
- leafShape: "string"
18443
- });
18444
- const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18445
- const normalizedContent = ensureTrailingNewline(content);
18446
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18447
- if (match === null) return ensureTrailingNewline([
18448
- normalizedContent.trimEnd(),
18449
- "",
18450
- `${sectionName}:`,
18451
- ...block,
18452
- ""
18453
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18454
- const sectionStartIndex = match.index;
18455
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18456
- nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18457
- let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18458
- while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18459
- const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18460
- const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18461
- const suffix = normalizedContent.slice(insertIndex);
18462
- return ensureTrailingNewline([
18463
- prefix,
18464
- ...block,
18465
- suffix.trimStart()
18466
- ].join("\n"));
18467
- };
18468
- const findTopLevelSectionRange = (content, sectionName) => {
18469
- const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18470
- if (match === null) return null;
18471
- const headerLineEndIndex = content.indexOf("\n", match.index);
18472
- const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18473
- const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18474
- nextSectionPattern.lastIndex = headerEndIndex;
18475
- return {
18476
- headerEndIndex,
18477
- contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18478
- };
18479
- };
18480
- const appendLefthookCommand = (content) => {
18481
- const normalizedContent = ensureTrailingNewline(content);
18482
- const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18483
- const reactDoctorCommandBlock = [
18484
- " react-doctor:",
18485
- ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18486
- ""
18487
- ];
18488
- if (sectionRange === null) return ensureTrailingNewline([
18489
- normalizedContent.trimEnd(),
18490
- "",
18491
- "pre-commit:",
18492
- " commands:",
18493
- ...reactDoctorCommandBlock
18494
- ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18495
- const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18496
- const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18497
- const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18498
- const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18499
- return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18500
- };
18501
- const installLefthook = (options) => {
18502
- const didHookExist = fs$1.existsSync(options.hookPath);
18503
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18504
- if (!existingContent.includes("react-doctor")) {
18505
- const nextContent = appendLefthookCommand(existingContent);
18506
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18507
- fs$1.writeFileSync(options.hookPath, nextContent);
18508
- }
18509
- removeLegacyManagedRunner(options.projectRoot);
18510
- return {
18511
- hookPath: options.hookPath,
18512
- kind: "lefthook",
18513
- status: didHookExist ? "updated" : "created"
18514
- };
18515
- };
18516
- const installPreCommit = (options) => {
18517
- const didHookExist = fs$1.existsSync(options.hookPath);
18518
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18519
- if (!existingContent.includes("id: react-doctor")) {
18520
- const hasReposKey = /^repos:\s*$/m.test(existingContent);
18521
- const localHookBlock = [
18522
- " - repo: local",
18523
- " hooks:",
18524
- " - id: react-doctor",
18525
- " name: react-doctor",
18526
- ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18527
- " language: system",
18528
- " pass_filenames: false",
18529
- ""
18530
- ].join("\n");
18531
- const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18532
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18533
- fs$1.writeFileSync(options.hookPath, nextContent);
18534
- }
18535
- removeLegacyManagedRunner(options.projectRoot);
18536
- return {
18537
- hookPath: options.hookPath,
18538
- kind: "pre-commit",
18539
- status: didHookExist ? "updated" : "created"
18540
- };
18541
- };
18542
- const installOvercommit = (options) => {
18543
- const didHookExist = fs$1.existsSync(options.hookPath);
18544
- const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18545
- if (!existingContent.includes("ReactDoctor")) {
18546
- const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18547
- " ReactDoctor:",
18548
- " enabled: true",
18549
- ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18550
- ""
18551
- ]);
18552
- fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18553
- fs$1.writeFileSync(options.hookPath, nextContent);
18332
+ const detectDefaultBranch = async (cwd) => {
18333
+ const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
18334
+ if (symRef.success) {
18335
+ const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
18336
+ if (branchMatch) return branchMatch[1];
18554
18337
  }
18555
- removeLegacyManagedRunner(options.projectRoot);
18556
- return {
18557
- hookPath: options.hookPath,
18558
- kind: "overcommit",
18559
- status: didHookExist ? "updated" : "created"
18560
- };
18561
- };
18562
- //#endregion
18563
- //#region src/cli/utils/install-git-hook.ts
18564
- const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18565
- const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18566
- const isSimpleGitHooksProject = (projectRoot) => {
18567
- const packageJson = readPackageJson(projectRoot);
18568
- return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
18338
+ if ((await run("git", [
18339
+ "rev-parse",
18340
+ "--verify",
18341
+ "origin/main"
18342
+ ], cwd)).success) return "main";
18343
+ if ((await run("git", [
18344
+ "rev-parse",
18345
+ "--verify",
18346
+ "origin/master"
18347
+ ], cwd)).success) return "master";
18348
+ return null;
18569
18349
  };
18570
- const getLefthookConfigPath = (projectRoot) => {
18571
- for (const fileName of LEFTHOOK_CONFIG_FILES) {
18572
- const filePath = path$1.join(projectRoot, fileName);
18573
- if (fs$1.existsSync(filePath)) return filePath;
18574
- }
18575
- return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
18350
+ const findUniqueBranchName = async (cwd) => {
18351
+ if (!(await run("git", [
18352
+ "rev-parse",
18353
+ "--verify",
18354
+ NEW_BRANCH_PREFIX
18355
+ ], cwd)).success) return NEW_BRANCH_PREFIX;
18356
+ return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
18576
18357
  };
18577
- const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18578
- const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18579
- const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18580
- const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
18581
- const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
18582
- const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
18583
- const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
18584
- const detectGitHookTarget = (projectRoot) => {
18585
- if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
18586
- const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
18587
- const configuredHooksPath = runGit(projectRoot, [
18588
- "config",
18589
- "--path",
18590
- "--get",
18591
- "core.hooksPath"
18592
- ]);
18593
- if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
18594
- hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
18595
- runnerRoot: topLevel,
18596
- kind: "configured"
18597
- };
18598
- if (isHuskyProject(topLevel)) return {
18599
- hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
18600
- runnerRoot: topLevel,
18601
- kind: "husky",
18602
- hooksPathConfig: HUSKY_HOOKS_PATH
18603
- };
18604
- if (isVitePlusProject(topLevel)) return {
18605
- hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
18606
- runnerRoot: topLevel,
18607
- kind: "vite-plus",
18608
- hooksPathConfig: VITE_PLUS_HOOKS_PATH
18609
- };
18610
- if (isSimpleGitHooksProject(topLevel)) return {
18611
- hookPath: path$1.join(topLevel, "package.json"),
18612
- runnerRoot: topLevel,
18613
- kind: "simple-git-hooks"
18358
+ const openWorkflowPullRequest = async (params) => {
18359
+ const workflowPath = path$1.resolve(params.workflowPath);
18360
+ const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
18361
+ const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
18362
+ const prBody = params.prBody ?? DEFAULT_PR_BODY;
18363
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18364
+ if (!repoRootProbe.success) return {
18365
+ status: "not-attempted",
18366
+ reason: "not-a-git-repo"
18614
18367
  };
18615
- const lefthookConfigPath = getLefthookConfigPath(topLevel);
18616
- if (lefthookConfigPath !== null) return {
18617
- hookPath: lefthookConfigPath,
18618
- runnerRoot: topLevel,
18619
- kind: "lefthook"
18368
+ const cwd = repoRootProbe.stdout;
18369
+ if (!isCommandAvailable("gh")) return {
18370
+ status: "not-attempted",
18371
+ reason: "gh-not-installed"
18620
18372
  };
18621
- if (isPreCommitProject(topLevel)) return {
18622
- hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
18623
- runnerRoot: topLevel,
18624
- kind: "pre-commit"
18373
+ if (!(await run("gh", ["auth", "status"], cwd)).success) return {
18374
+ status: "not-attempted",
18375
+ reason: "gh-not-authenticated"
18625
18376
  };
18626
- if (isOvercommitProject(topLevel)) return {
18627
- hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
18628
- runnerRoot: topLevel,
18629
- kind: "overcommit"
18377
+ const defaultBranch = await detectDefaultBranch(cwd);
18378
+ if (!defaultBranch) return {
18379
+ status: "not-attempted",
18380
+ reason: "no-default-branch"
18630
18381
  };
18631
- if (isYorkieProject(topLevel)) return {
18632
- hookPath: getPackageJsonPath(topLevel),
18633
- runnerRoot: topLevel,
18634
- kind: "yorkie"
18382
+ const previousBranchProbe = await run("git", [
18383
+ "rev-parse",
18384
+ "--abbrev-ref",
18385
+ "HEAD"
18386
+ ], cwd);
18387
+ if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
18388
+ status: "not-attempted",
18389
+ reason: "detached-head"
18635
18390
  };
18636
- if (isGhooksProject(topLevel)) return {
18637
- hookPath: getPackageJsonPath(topLevel),
18638
- runnerRoot: topLevel,
18639
- kind: "ghooks"
18391
+ const previousBranch = previousBranchProbe.stdout;
18392
+ await run("git", [
18393
+ "fetch",
18394
+ "origin",
18395
+ defaultBranch
18396
+ ], cwd);
18397
+ const newBranch = await findUniqueBranchName(cwd);
18398
+ if (!(await run("git", [
18399
+ "checkout",
18400
+ "-b",
18401
+ newBranch,
18402
+ `origin/${defaultBranch}`
18403
+ ], cwd)).success) return {
18404
+ status: "not-attempted",
18405
+ reason: "checkout-failed"
18640
18406
  };
18641
- if (isGitHooksJsProject(topLevel)) return {
18642
- hookPath: getPackageJsonPath(topLevel),
18643
- runnerRoot: topLevel,
18644
- kind: "git-hooks-js"
18407
+ const restoreToPreviousBranch = async (deleteNewBranch) => {
18408
+ await run("git", ["checkout", previousBranch], cwd);
18409
+ if (deleteNewBranch) await run("git", [
18410
+ "branch",
18411
+ "-D",
18412
+ newBranch
18413
+ ], cwd);
18645
18414
  };
18646
- if (isPreCommitNpmProject(topLevel)) return {
18647
- hookPath: getPackageJsonPath(topLevel),
18648
- runnerRoot: topLevel,
18649
- kind: "pre-commit-npm"
18650
- };
18651
- if (isPrettyQuickProject(topLevel)) return {
18652
- hookPath: getPackageJsonPath(topLevel),
18653
- runnerRoot: topLevel,
18654
- kind: "pretty-quick"
18415
+ if (!(await run("git", [
18416
+ "add",
18417
+ "--",
18418
+ path$1.relative(cwd, workflowPath)
18419
+ ], cwd)).success) {
18420
+ await restoreToPreviousBranch(true);
18421
+ return {
18422
+ status: "not-attempted",
18423
+ reason: "git-add-failed"
18424
+ };
18425
+ }
18426
+ if (!(await run("git", [
18427
+ "commit",
18428
+ "-m",
18429
+ commitMessage
18430
+ ], cwd)).success) {
18431
+ await restoreToPreviousBranch(true);
18432
+ return {
18433
+ status: "not-attempted",
18434
+ reason: "git-commit-failed"
18435
+ };
18436
+ }
18437
+ if (!(await run("git", [
18438
+ "push",
18439
+ "-u",
18440
+ "origin",
18441
+ newBranch
18442
+ ], cwd)).success) {
18443
+ await restoreToPreviousBranch(true);
18444
+ return {
18445
+ status: "not-attempted",
18446
+ reason: "git-push-failed"
18447
+ };
18448
+ }
18449
+ const prCreate = await run("gh", [
18450
+ "pr",
18451
+ "create",
18452
+ "--title",
18453
+ prTitle,
18454
+ "--body",
18455
+ prBody,
18456
+ "--base",
18457
+ defaultBranch,
18458
+ "--head",
18459
+ newBranch
18460
+ ], cwd);
18461
+ await restoreToPreviousBranch(false);
18462
+ if (!prCreate.success) return {
18463
+ status: "branch-pushed",
18464
+ branch: newBranch
18655
18465
  };
18656
- const hookPath = runGit(projectRoot, [
18657
- "rev-parse",
18658
- "--git-path",
18659
- HOOK_RELATIVE_PATH
18660
- ]);
18661
- if (hookPath === null || hookPath.length === 0) return null;
18662
18466
  return {
18663
- hookPath: resolveGitPath(projectRoot, hookPath),
18664
- runnerRoot: topLevel,
18665
- kind: "git"
18467
+ status: "pr-opened",
18468
+ url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
18666
18469
  };
18667
18470
  };
18668
- const installReactDoctorGitHook = (options) => {
18669
- if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
18670
- if (options.kind === "lefthook") return installLefthook(options);
18671
- if (options.kind === "pre-commit") return installPreCommit(options);
18672
- if (options.kind === "overcommit") return installOvercommit(options);
18673
- if (options.kind === "yorkie") return installYorkie(options);
18674
- if (options.kind === "ghooks") return installGhooks(options);
18675
- if (options.kind === "git-hooks-js") return installGitHooksJs(options);
18676
- if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
18677
- if (options.kind === "pretty-quick") return installPrettyQuick(options);
18678
- return installDirectGitHook(options);
18471
+ const stageWorkflowFile = async (params) => {
18472
+ const workflowPath = path$1.resolve(params.workflowPath);
18473
+ const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
18474
+ if (!repoRootProbe.success) return false;
18475
+ return (await run("git", [
18476
+ "add",
18477
+ "--",
18478
+ path$1.relative(repoRootProbe.stdout, workflowPath)
18479
+ ], repoRootProbe.stdout)).success;
18679
18480
  };
18680
18481
  //#endregion
18681
- //#region src/cli/utils/should-skip-prompts.ts
18682
- const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
18683
- //#endregion
18684
- //#region src/cli/utils/install-react-doctor.ts
18685
- const SETUP_OPTION_GIT_HOOK = "git-hook";
18686
- const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
18687
- const SETUP_OPTION_WORKFLOW = "workflow";
18688
- const SETUP_OPTION_SKIP = "skip";
18689
- const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
18690
- "ghooks",
18691
- "git-hooks-js",
18692
- "lefthook",
18693
- "overcommit",
18694
- "pre-commit",
18695
- "pre-commit-npm",
18696
- "pretty-quick",
18697
- "simple-git-hooks",
18698
- "yorkie"
18699
- ]);
18700
- const PACKAGE_MANAGER_LOCKFILES = [
18701
- {
18702
- packageManager: "pnpm",
18703
- fileName: "pnpm-lock.yaml"
18704
- },
18705
- {
18706
- packageManager: "yarn",
18707
- fileName: "yarn.lock"
18708
- },
18709
- {
18710
- packageManager: "bun",
18711
- fileName: "bun.lockb"
18712
- },
18713
- {
18714
- packageManager: "bun",
18715
- fileName: "bun.lock"
18716
- },
18717
- {
18718
- packageManager: "npm",
18719
- fileName: "package-lock.json"
18482
+ //#region src/cli/utils/report-workflow-result.ts
18483
+ const reportWorkflowResult = (workflowSpinner, result, projectRoot) => {
18484
+ if (result.status === "failed") {
18485
+ workflowSpinner.fail("Couldn't write the GitHub Actions workflow.");
18486
+ return false;
18720
18487
  }
18721
- ];
18722
- const findNearestFileDirectory = (startDirectory, fileNames) => {
18723
- let currentDirectory = path$1.resolve(startDirectory);
18724
- while (true) {
18725
- if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
18726
- const parentDirectory = path$1.dirname(currentDirectory);
18727
- if (parentDirectory === currentDirectory) return null;
18728
- currentDirectory = parentDirectory;
18488
+ if (result.status === "exists") {
18489
+ workflowSpinner.succeed("GitHub Actions workflow already configured.");
18490
+ return false;
18729
18491
  }
18492
+ workflowSpinner.succeed(`GitHub Actions workflow added at ${path$1.relative(projectRoot, result.workflowPath)}.`);
18493
+ recordCount(METRIC.installWorkflow, 1);
18494
+ return true;
18730
18495
  };
18731
- const detectPackageManager = (projectRoot) => {
18732
- let currentDirectory = path$1.resolve(projectRoot);
18733
- while (true) {
18734
- const packageJson = readPackageJson(currentDirectory);
18735
- if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
18736
- const packageManagerName = packageJson.packageManager.split("@")[0];
18737
- if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
18496
+ //#endregion
18497
+ //#region src/cli/utils/set-up-github-actions.ts
18498
+ const setUpGitHubActions = async (options) => {
18499
+ const projectRoot = findNearestPackageDirectory(options.rootDirectory) ?? options.rootDirectory;
18500
+ try {
18501
+ installReactDoctorScriptStep(projectRoot);
18502
+ } catch {}
18503
+ const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
18504
+ const workflowResult = installReactDoctorWorkflow(projectRoot);
18505
+ const didCreateWorkflow = reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
18506
+ cliLogger.break();
18507
+ if (workflowResult.status === "failed") {
18508
+ cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
18509
+ return false;
18510
+ }
18511
+ if (workflowResult.status === "created") {
18512
+ const pullRequestSpinner = spinner("Opening a pull request for review...").start();
18513
+ const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
18514
+ if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
18515
+ 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}`);
18516
+ else {
18517
+ pullRequestSpinner.stop();
18518
+ const didStage = await stageWorkflowFile({ workflowPath: workflowResult.workflowPath });
18519
+ 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.");
18738
18520
  }
18739
- const parentDirectory = path$1.dirname(currentDirectory);
18740
- if (parentDirectory === currentDirectory) break;
18741
- currentDirectory = parentDirectory;
18742
18521
  }
18743
- const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
18744
- return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
18522
+ cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
18523
+ return didCreateWorkflow;
18745
18524
  };
18746
- const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
18747
- const buildInstallCommand = (projectRoot) => {
18748
- const packageManager = detectPackageManager(projectRoot);
18749
- const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
18750
- if (packageManager === "npm") return {
18751
- command: "npm",
18752
- args: [
18753
- "install",
18754
- "--save-dev",
18755
- packageSpecifier
18756
- ],
18757
- cwd: projectRoot
18758
- };
18759
- if (packageManager === "yarn") return {
18760
- command: "yarn",
18761
- args: [
18762
- "add",
18763
- "--dev",
18764
- packageSpecifier
18765
- ],
18766
- cwd: projectRoot
18767
- };
18768
- if (packageManager === "bun") return {
18769
- command: "bun",
18770
- args: [
18771
- "add",
18772
- "--dev",
18773
- packageSpecifier
18774
- ],
18775
- cwd: projectRoot
18776
- };
18777
- return {
18778
- command: "pnpm",
18779
- args: [
18780
- "add",
18781
- "--save-dev",
18782
- ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
18783
- packageSpecifier
18784
- ],
18785
- cwd: projectRoot
18786
- };
18525
+ //#endregion
18526
+ //#region src/cli/utils/install-agent-hooks.ts
18527
+ const CLAUDE_AGENT = "claude-code";
18528
+ const CURSOR_AGENT = "cursor";
18529
+ const CLAUDE_SETTINGS_RELATIVE_PATH = ".claude/settings.json";
18530
+ const CLAUDE_HOOK_RELATIVE_PATH = ".claude/hooks/react-doctor.sh";
18531
+ const CLAUDE_HOOK_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/hooks/react-doctor.sh\"";
18532
+ const CURSOR_HOOKS_RELATIVE_PATH = ".cursor/hooks.json";
18533
+ const CURSOR_HOOK_RELATIVE_PATH = ".cursor/hooks/react-doctor.sh";
18534
+ const CURSOR_HOOK_MATCHER = "Write|Edit|MultiEdit|ApplyPatch";
18535
+ const CURSOR_HOOKS_SCHEMA_VERSION = 1;
18536
+ const JSON_INDENT_SPACES$1 = 2;
18537
+ const isSupportedAgent = (agent) => agent === CLAUDE_AGENT || agent === CURSOR_AGENT;
18538
+ const readJsonFile = (filePath, fallback) => {
18539
+ if (!fs$1.existsSync(filePath)) return fallback;
18540
+ const content = fs$1.readFileSync(filePath, "utf8").trim();
18541
+ if (content.length === 0) return fallback;
18542
+ return JSON.parse(content);
18787
18543
  };
18788
- const execFileAsync$1 = promisify(execFile);
18789
- const defaultInstallDependencyRunner = async (input) => {
18790
- await execFileAsync$1(input.command, [...input.args], {
18791
- cwd: input.cwd,
18792
- env: {
18793
- ...process.env,
18794
- REACT_DOCTOR_INSTALL: "1"
18795
- },
18796
- shell: process.platform === "win32"
18797
- });
18544
+ const writeJsonFile = (filePath, value) => {
18545
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18546
+ fs$1.writeFileSync(filePath, `${JSON.stringify(value, null, JSON_INDENT_SPACES$1)}\n`);
18798
18547
  };
18799
- const isSupplyChainTrustError = (error) => {
18800
- const candidate = error;
18801
- const haystack = [
18802
- candidate?.stderr,
18803
- candidate?.stdout,
18804
- candidate?.message
18805
- ].map((part) => String(part ?? "")).join("\n");
18806
- return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
18807
- };
18808
- const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
18809
- const installReactDoctorDependency = async (options) => {
18810
- const packageJson = readPackageJson(options.projectRoot);
18811
- if (!isRecord(packageJson)) return {
18812
- dependencyStatus: "skipped",
18813
- dependencyReason: "missing-or-invalid-package-json"
18814
- };
18815
- if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
18816
- if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
18817
- dependencyStatus: "skipped",
18818
- dependencyReason: "invalid-dev-dependencies"
18819
- };
18820
- const runnerInput = buildInstallCommand(options.projectRoot);
18821
- try {
18822
- await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
18823
- } catch (error) {
18824
- return {
18825
- dependencyStatus: "skipped",
18826
- dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
18827
- installCommand: formatInstallCommand(runnerInput)
18828
- };
18829
- }
18830
- return { dependencyStatus: "created" };
18831
- };
18832
- const buildManualGitHookTarget = (hookPath, projectRoot) => ({
18833
- hookPath,
18834
- runnerRoot: projectRoot,
18835
- kind: "git"
18836
- });
18837
- const formatGitHookInstallMessage = (hookResult) => {
18838
- if (CONFIG_ONLY_GIT_HOOK_KINDS.has(hookResult.kind)) return `React Doctor pre-commit config ${hookResult.status} at ${hookResult.hookPath}. Run your hook manager's install command if hooks are not already installed.`;
18839
- return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
18840
- };
18841
- const formatDoctorScriptInstallMessage = (scriptResult) => {
18842
- const messages = [];
18843
- const scriptName = scriptResult.scriptName ?? "doctor";
18844
- if (scriptResult.scriptStatus === "created") messages.push(`Added package script: ${scriptName}.`);
18845
- else if (scriptResult.scriptStatus === "existing") messages.push(`Package script already exists: ${scriptName}.`);
18846
- else if (scriptResult.scriptReason === "script-names-taken") messages.push("Skipped package script: doctor and react-doctor are already taken.");
18847
- else if (scriptResult.scriptReason === "doctor-script-taken") messages.push("Skipped package script: doctor and react-doctor scripts already exist.");
18848
- else if (scriptResult.scriptReason === "invalid-scripts") messages.push(`Skipped package script: scripts field is not an object.`);
18849
- else messages.push("Skipped package script: package.json missing or invalid.");
18850
- return messages.join(" ");
18548
+ const writeHookScript = (filePath) => {
18549
+ fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
18550
+ fs$1.writeFileSync(filePath, buildAgentHookScript());
18551
+ fs$1.chmodSync(filePath, 493);
18851
18552
  };
18852
- const formatDependencyInstallMessage = (result) => {
18853
- if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
18854
- if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
18855
- if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
18856
- if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
18857
- if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
18858
- return "Skipped dev dependency install: package.json missing or invalid.";
18553
+ const hasClaudeHookCommand = (groups) => groups.some((group) => (group.hooks ?? []).some((hook) => hook.command === CLAUDE_HOOK_COMMAND));
18554
+ const installClaudeHook = (projectRoot) => {
18555
+ const settingsPath = path$1.join(projectRoot, CLAUDE_SETTINGS_RELATIVE_PATH);
18556
+ const hookPath = path$1.join(projectRoot, CLAUDE_HOOK_RELATIVE_PATH);
18557
+ const settings = readJsonFile(settingsPath, {});
18558
+ const hooks = { ...settings.hooks ?? {} };
18559
+ const postToolBatchHooks = [...hooks.PostToolBatch ?? []];
18560
+ if (!hasClaudeHookCommand(postToolBatchHooks)) postToolBatchHooks.push({ hooks: [{
18561
+ type: "command",
18562
+ command: CLAUDE_HOOK_COMMAND
18563
+ }] });
18564
+ hooks.PostToolBatch = postToolBatchHooks;
18565
+ writeJsonFile(settingsPath, {
18566
+ ...settings,
18567
+ hooks
18568
+ });
18569
+ writeHookScript(hookPath);
18570
+ return [settingsPath, hookPath];
18859
18571
  };
18860
- const buildDependencyFollowUp = (result) => {
18861
- if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
18862
- return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
18572
+ const hasCursorHookCommand = (handlers) => handlers.some((handler) => handler.command === CURSOR_HOOK_RELATIVE_PATH);
18573
+ const installCursorHook = (projectRoot) => {
18574
+ const configPath = path$1.join(projectRoot, CURSOR_HOOKS_RELATIVE_PATH);
18575
+ const hookPath = path$1.join(projectRoot, CURSOR_HOOK_RELATIVE_PATH);
18576
+ const config = readJsonFile(configPath, {});
18577
+ const hooks = { ...config.hooks ?? {} };
18578
+ const postToolUseHooks = [...hooks.postToolUse ?? []];
18579
+ if (!hasCursorHookCommand(postToolUseHooks)) postToolUseHooks.push({
18580
+ command: CURSOR_HOOK_RELATIVE_PATH,
18581
+ matcher: CURSOR_HOOK_MATCHER,
18582
+ timeout: 120
18583
+ });
18584
+ hooks.postToolUse = postToolUseHooks;
18585
+ writeJsonFile(configPath, {
18586
+ ...config,
18587
+ version: config.version ?? CURSOR_HOOKS_SCHEMA_VERSION,
18588
+ hooks
18589
+ });
18590
+ writeHookScript(hookPath);
18591
+ return [configPath, hookPath];
18863
18592
  };
18864
- const installReactDoctorScriptStep = (projectRoot) => {
18865
- const scriptSpinner = spinner("Installing React Doctor package script...").start();
18866
- try {
18867
- const scriptResult = installDoctorScript({ projectRoot });
18868
- scriptSpinner.succeed(formatDoctorScriptInstallMessage(scriptResult));
18869
- } catch (error) {
18870
- scriptSpinner.fail("Failed to install React Doctor package script.");
18871
- throw error;
18593
+ const buildAgentHookScript = () => [
18594
+ "#!/bin/sh",
18595
+ "set -u",
18596
+ "",
18597
+ "input_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook.XXXXXX\")",
18598
+ "output_file=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-agent-hook-output.XXXXXX\")",
18599
+ "trap 'rm -f \"$input_file\" \"$output_file\"' EXIT",
18600
+ "cat > \"$input_file\"",
18601
+ "",
18602
+ "script_dir=$(CDPATH= cd \"$(dirname \"$0\")\" && pwd)",
18603
+ "project_root=${CLAUDE_PROJECT_DIR:-}",
18604
+ "if [ -z \"$project_root\" ]; then",
18605
+ " project_root=$(CDPATH= cd \"$script_dir/../..\" && pwd)",
18606
+ "fi",
18607
+ "if ! cd \"$project_root\"; then",
18608
+ " exit 0",
18609
+ "fi",
18610
+ "",
18611
+ "should_scan() {",
18612
+ " if ! command -v node >/dev/null 2>&1; then",
18613
+ " return 0",
18614
+ " fi",
18615
+ "",
18616
+ " node - \"$input_file\" <<'NODE'",
18617
+ "const fs = require('node:fs');",
18618
+ "const inputPath = process.argv[2];",
18619
+ "const editToolNames = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ApplyPatch']);",
18620
+ "try {",
18621
+ " const input = JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18622
+ " const eventName = input.hook_event_name || input.eventName || input.event_name;",
18623
+ " if (eventName === 'PostToolBatch') {",
18624
+ " const toolCalls = Array.isArray(input.tool_calls) ? input.tool_calls : [];",
18625
+ " process.exit(toolCalls.some((toolCall) => editToolNames.has(toolCall.tool_name)) ? 0 : 10);",
18626
+ " }",
18627
+ " const toolName = input.tool_name || input.toolName || input.tool;",
18628
+ " process.exit(!toolName || editToolNames.has(toolName) ? 0 : 10);",
18629
+ "} catch {",
18630
+ " process.exit(0);",
18631
+ "}",
18632
+ "NODE",
18633
+ "}",
18634
+ "",
18635
+ "run_react_doctor() {",
18636
+ " if [ -x ./node_modules/.bin/react-doctor ]; then",
18637
+ " ./node_modules/.bin/react-doctor --verbose --diff --blocking warning --no-score",
18638
+ " return",
18639
+ " fi",
18640
+ "",
18641
+ " if command -v react-doctor >/dev/null 2>&1; then",
18642
+ " react-doctor --verbose --diff --blocking warning --no-score",
18643
+ " return",
18644
+ " fi",
18645
+ "",
18646
+ " if command -v pnpm >/dev/null 2>&1; then",
18647
+ " pnpm dlx react-doctor@latest --verbose --diff --blocking warning --no-score",
18648
+ " return",
18649
+ " fi",
18650
+ "",
18651
+ " if command -v npx >/dev/null 2>&1; then",
18652
+ " npx --yes react-doctor@latest --verbose --diff --blocking warning --no-score",
18653
+ " return",
18654
+ " fi",
18655
+ "",
18656
+ " printf '%s\\n' 'react-doctor: command not found; skipping agent hook scan.'",
18657
+ " return 0",
18658
+ "}",
18659
+ "",
18660
+ "if ! should_scan; then",
18661
+ " exit 0",
18662
+ "fi",
18663
+ "",
18664
+ "if run_react_doctor > \"$output_file\" 2>&1; then",
18665
+ " exit 0",
18666
+ "fi",
18667
+ "",
18668
+ "node - \"$input_file\" \"$output_file\" <<'NODE'",
18669
+ "const fs = require('node:fs');",
18670
+ "const inputPath = process.argv[2];",
18671
+ "const outputPath = process.argv[3];",
18672
+ "const readInput = () => {",
18673
+ " try {",
18674
+ " return JSON.parse(fs.readFileSync(inputPath, 'utf8') || '{}');",
18675
+ " } catch {",
18676
+ " return {};",
18677
+ " }",
18678
+ "};",
18679
+ "const input = readInput();",
18680
+ "const scanOutput = fs.readFileSync(outputPath, 'utf8').trim();",
18681
+ "if (!scanOutput) process.exit(0);",
18682
+ "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}`;",
18683
+ "if (input.hook_event_name === 'PostToolBatch') {",
18684
+ " console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolBatch', additionalContext: message } }));",
18685
+ "} else {",
18686
+ " console.log(JSON.stringify({ additional_context: message }));",
18687
+ "}",
18688
+ "NODE",
18689
+ ""
18690
+ ].join("\n");
18691
+ const installReactDoctorAgentHooks = (options) => {
18692
+ const installedAgents = [];
18693
+ const files = [];
18694
+ const requestedAgents = options.agents.filter(isSupportedAgent);
18695
+ for (const agent of requestedAgents) {
18696
+ if (agent === CLAUDE_AGENT) {
18697
+ files.push(...installClaudeHook(options.projectRoot));
18698
+ installedAgents.push(agent);
18699
+ }
18700
+ if (agent === CURSOR_AGENT) {
18701
+ files.push(...installCursorHook(options.projectRoot));
18702
+ installedAgents.push(agent);
18703
+ }
18872
18704
  }
18705
+ return {
18706
+ installedAgents,
18707
+ files
18708
+ };
18873
18709
  };
18874
- const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
18875
- installReactDoctorScriptStep(projectRoot);
18876
- const dependencySpinner = spinner("Installing React Doctor package...").start();
18877
- try {
18878
- const dependencyResult = await installReactDoctorDependency({
18879
- projectRoot,
18880
- runner: dependencyRunner
18881
- });
18882
- recordCount(METRIC.installDependency, 1, {
18883
- status: dependencyResult.dependencyStatus,
18884
- reason: dependencyResult.dependencyReason ?? null,
18885
- packageManager: detectPackageManager(projectRoot)
18886
- });
18887
- if (dependencyResult.dependencyStatus === "skipped") {
18888
- const message = formatDependencyInstallMessage(dependencyResult);
18889
- if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
18890
- else dependencySpinner.fail(message);
18891
- const followUp = buildDependencyFollowUp(dependencyResult);
18892
- if (followUp !== void 0) cliLogger.dim(followUp);
18893
- return dependencyResult;
18894
- }
18895
- dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
18896
- return dependencyResult;
18897
- } catch (error) {
18898
- dependencySpinner.fail("Failed to install React Doctor package.");
18899
- throw error;
18710
+ //#endregion
18711
+ //#region src/cli/utils/install-git-hook-file.ts
18712
+ const REACT_DOCTOR_BLOCK_START = "# react-doctor hook start";
18713
+ const REACT_DOCTOR_BLOCK_END = "# react-doctor hook end";
18714
+ 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?)`);
18715
+ const SHEBANG = "#!/bin/sh";
18716
+ const SHEBANG_PREFIX = "#!";
18717
+ const LOCAL_REACT_DOCTOR_BIN = "./node_modules/.bin/react-doctor";
18718
+ const PNPM_REACT_DOCTOR_COMMAND = "pnpm dlx react-doctor@latest --staged --blocking warning";
18719
+ const NPX_REACT_DOCTOR_COMMAND = "npx --yes react-doctor@latest --staged --blocking warning";
18720
+ const buildReactDoctorHookBlock = () => [
18721
+ REACT_DOCTOR_BLOCK_START,
18722
+ "react_doctor_scan_staged_files() {",
18723
+ ` if [ -x "${LOCAL_REACT_DOCTOR_BIN}" ]; then`,
18724
+ ` "${LOCAL_REACT_DOCTOR_BIN}" ${REACT_DOCTOR_COMMAND.replace("react-doctor ", "")}`,
18725
+ " return",
18726
+ " fi",
18727
+ "",
18728
+ " if command -v react-doctor >/dev/null 2>&1; then",
18729
+ ` ${REACT_DOCTOR_COMMAND}`,
18730
+ " return",
18731
+ " fi",
18732
+ "",
18733
+ " if command -v pnpm >/dev/null 2>&1; then",
18734
+ ` ${PNPM_REACT_DOCTOR_COMMAND}`,
18735
+ " return",
18736
+ " fi",
18737
+ "",
18738
+ " if command -v npx >/dev/null 2>&1; then",
18739
+ ` ${NPX_REACT_DOCTOR_COMMAND}`,
18740
+ " return",
18741
+ " fi",
18742
+ "",
18743
+ " printf '%s\\n' \"react-doctor: command not found; skipping staged scan.\"",
18744
+ "}",
18745
+ "",
18746
+ "react_doctor_output=$(mktemp \"${TMPDIR:-/tmp}/react-doctor-hook.XXXXXX\")",
18747
+ "if react_doctor_scan_staged_files > \"$react_doctor_output\" 2>&1; then",
18748
+ " rm -f \"$react_doctor_output\"",
18749
+ "else",
18750
+ " rm -f \"$react_doctor_output\"",
18751
+ ` printf '%s\\n' "React Doctor found staged regressions." "Run ${REACT_DOCTOR_COMMAND} to inspect." "Want them fixed? Ask your agent to run that command and resolve the findings." >&2`,
18752
+ "fi",
18753
+ REACT_DOCTOR_BLOCK_END
18754
+ ].join("\n");
18755
+ const mergeHookContent = (existingContent) => {
18756
+ const hookBlock = `${buildReactDoctorHookBlock()}\n`;
18757
+ if (REACT_DOCTOR_BLOCK_PATTERN.test(existingContent)) return ensureTrailingNewline(existingContent.replace(REACT_DOCTOR_BLOCK_PATTERN, hookBlock));
18758
+ if (existingContent.length === 0) return `${SHEBANG}\n\n${hookBlock}`;
18759
+ const normalizedExistingContent = ensureTrailingNewline(existingContent);
18760
+ if (normalizedExistingContent.startsWith(SHEBANG_PREFIX)) {
18761
+ const [shebangLine, ...remainingLines] = normalizedExistingContent.split("\n");
18762
+ return [
18763
+ shebangLine,
18764
+ "",
18765
+ hookBlock.trimEnd(),
18766
+ ...remainingLines
18767
+ ].join("\n");
18900
18768
  }
18769
+ return `${SHEBANG}\n\n${hookBlock}${normalizedExistingContent}`;
18770
+ };
18771
+ const removeLegacyManagedRunner = (projectRoot) => {
18772
+ const runnerPath = path$1.join(projectRoot, LEGACY_HOOK_RUNNER_RELATIVE_PATH);
18773
+ fs$1.rmSync(runnerPath, { force: true });
18774
+ for (const directory of [path$1.dirname(runnerPath), path$1.join(projectRoot, ".react-doctor")]) try {
18775
+ fs$1.rmdirSync(directory);
18776
+ } catch {}
18777
+ };
18778
+ const installDirectGitHook = (options) => {
18779
+ const didHookExist = fs$1.existsSync(options.hookPath);
18780
+ const nextContent = mergeHookContent(didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "");
18781
+ if (options.hooksPathConfig !== void 0) runGit(options.projectRoot, [
18782
+ "config",
18783
+ "core.hooksPath",
18784
+ options.hooksPathConfig
18785
+ ]);
18786
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18787
+ fs$1.writeFileSync(options.hookPath, nextContent);
18788
+ fs$1.chmodSync(options.hookPath, 493);
18789
+ removeLegacyManagedRunner(options.projectRoot);
18790
+ return {
18791
+ hookPath: options.hookPath,
18792
+ kind: options.kind ?? "git",
18793
+ status: didHookExist ? "updated" : "created"
18794
+ };
18901
18795
  };
18902
- const getSkillSourceDirectory = () => {
18903
- const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
18904
- return path$1.join(distDirectory, "skills", SKILL_NAME);
18796
+ //#endregion
18797
+ //#region src/cli/utils/install-git-hook-config-managers.ts
18798
+ const appendStringCommand = (existingCommand) => {
18799
+ const existingCommandText = typeof existingCommand === "string" ? existingCommand : Array.isArray(existingCommand) ? existingCommand.filter((entry) => typeof entry === "string").join("\n") : "";
18800
+ return existingCommandText.includes("react-doctor --staged --blocking warning") ? existingCommandText : [existingCommandText, NON_BLOCKING_REACT_DOCTOR_COMMAND].filter(Boolean).join("\n");
18905
18801
  };
18906
- const findBundledSiblingSkills = (primarySkillDir) => {
18907
- const skillsParent = path$1.dirname(primarySkillDir);
18908
- if (!fs$1.existsSync(skillsParent)) return [];
18909
- const resolvedPrimary = path$1.resolve(primarySkillDir);
18910
- return fs$1.readdirSync(skillsParent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => ({
18911
- name: entry.name,
18912
- source: path$1.join(skillsParent, entry.name)
18913
- })).filter((sibling) => path$1.resolve(sibling.source) !== resolvedPrimary && fs$1.existsSync(path$1.join(sibling.source, SKILL_MANIFEST_FILE)));
18914
- };
18915
- const installBundledSiblingSkills = async (primarySkillDir, agents, projectRoot) => {
18916
- const installedSkillNames = [];
18917
- for (const sibling of findBundledSiblingSkills(primarySkillDir)) {
18918
- const result = await installSkillsFromSource({
18919
- source: sibling.source,
18920
- agents: [...agents],
18921
- cwd: projectRoot,
18922
- mode: "copy"
18923
- });
18924
- if (result.failed.length > 0) throw new Error(result.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
18925
- if (result.skills.length > 0) installedSkillNames.push(sibling.name);
18926
- }
18927
- return installedSkillNames;
18802
+ const appendArrayCommand = (existingCommands) => {
18803
+ const commands = Array.isArray(existingCommands) ? existingCommands.filter((entry) => typeof entry === "string") : typeof existingCommands === "string" ? [existingCommands] : [];
18804
+ return commands.some((command) => command.includes("react-doctor --staged --blocking warning")) ? commands : [...commands, NON_BLOCKING_REACT_DOCTOR_COMMAND];
18928
18805
  };
18929
- const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
18930
- const runInstallReactDoctor = async (options = {}) => {
18931
- const requestedProjectRoot = options.projectRoot ?? process.cwd();
18932
- const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
18933
- const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
18934
- if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
18935
- cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
18936
- process.exitCode = 1;
18937
- return;
18938
- }
18939
- const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
18940
- if (detectedAgents.length === 0) {
18941
- cliLogger.error("No supported coding agents detected.");
18942
- cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
18943
- cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
18944
- process.exitCode = 1;
18945
- return;
18806
+ const installPackageJsonHook = (options, strategy) => {
18807
+ const packageJsonPath = getPackageJsonPath(options.projectRoot);
18808
+ const didHookExist = fs$1.existsSync(packageJsonPath);
18809
+ const packageJson = readPackageJson(options.projectRoot);
18810
+ const nextPackageJson = isRecord(packageJson) ? { ...packageJson } : {};
18811
+ const parentKeys = strategy.path.slice(0, -1);
18812
+ const leafKey = strategy.path[strategy.path.length - 1];
18813
+ let parent = nextPackageJson;
18814
+ for (const key of parentKeys) {
18815
+ const existing = parent[key];
18816
+ const cloned = isRecord(existing) ? { ...existing } : {};
18817
+ parent[key] = cloned;
18818
+ parent = cloned;
18946
18819
  }
18947
- const skipPrompts = shouldSkipPrompts({ yes: options.yes });
18948
- const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
18949
- const gitHookPath = gitHookTarget?.hookPath;
18950
- const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
18951
- const prompt = options.prompt ?? prompts;
18952
- const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
18953
- type: "multiselect",
18954
- name: "agents",
18955
- message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
18956
- choices: detectedAgents.map((agent) => ({
18957
- title: getSkillAgentConfig(agent).displayName,
18958
- value: agent,
18959
- selected: true
18960
- })),
18961
- instructions: false,
18962
- min: 1
18963
- }, promptOptions)).agents ?? [];
18964
- if (selectedAgents.length === 0) return;
18965
- const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
18966
- const canInstallWorkflow = !isReactDoctorWorkflowInstalled(projectRoot);
18967
- const setupActionChoices = [
18968
- ...gitHookPath === null || gitHookPath === void 0 ? [] : [{
18969
- title: "Pre-commit hook",
18970
- description: "Check staged changes before each commit",
18971
- value: SETUP_OPTION_GIT_HOOK,
18972
- selected: true
18973
- }],
18974
- ...canInstallNativeAgentHooks(selectedAgents) ? [{
18975
- title: "Agent hooks",
18976
- description: "Ask Claude Code or Cursor to scan after code edits",
18977
- value: SETUP_OPTION_AGENT_HOOKS,
18978
- selected: Boolean(options.agentHooks)
18979
- }] : [],
18980
- ...canInstallWorkflow ? [{
18981
- title: "GitHub Actions workflow",
18982
- description: "Scan pull requests in CI",
18983
- value: SETUP_OPTION_WORKFLOW,
18984
- selected: true
18985
- }] : []
18820
+ parent[leafKey] = strategy.leafShape === "array" ? appendArrayCommand(parent[leafKey]) : appendStringCommand(parent[leafKey]);
18821
+ writeJsonFile$1(packageJsonPath, nextPackageJson);
18822
+ removeLegacyManagedRunner(options.projectRoot);
18823
+ return {
18824
+ hookPath: packageJsonPath,
18825
+ kind: strategy.kind,
18826
+ status: didHookExist ? "updated" : "created"
18827
+ };
18828
+ };
18829
+ const installSimpleGitHooks = (options) => installPackageJsonHook(options, {
18830
+ kind: "simple-git-hooks",
18831
+ path: ["simple-git-hooks", "pre-commit"],
18832
+ leafShape: "string"
18833
+ });
18834
+ const installGhooks = (options) => installPackageJsonHook(options, {
18835
+ kind: "ghooks",
18836
+ path: [
18837
+ "config",
18838
+ "ghooks",
18839
+ "pre-commit"
18840
+ ],
18841
+ leafShape: "string"
18842
+ });
18843
+ const installPreCommitNpm = (options) => installPackageJsonHook(options, {
18844
+ kind: "pre-commit-npm",
18845
+ path: ["pre-commit"],
18846
+ leafShape: "array"
18847
+ });
18848
+ const installPrettyQuick = (options) => installPackageJsonHook(options, {
18849
+ kind: "pretty-quick",
18850
+ path: ["gitHooks", "pre-commit"],
18851
+ leafShape: "string"
18852
+ });
18853
+ const installYorkie = (options) => installPackageJsonHook(options, {
18854
+ kind: "yorkie",
18855
+ path: ["gitHooks", "pre-commit"],
18856
+ leafShape: "string"
18857
+ });
18858
+ const installGitHooksJs = (options) => installPackageJsonHook(options, {
18859
+ kind: "git-hooks-js",
18860
+ path: ["git-hooks", "pre-commit"],
18861
+ leafShape: "string"
18862
+ });
18863
+ const appendIndentedBlockToTopLevelSection = (content, sectionName, block) => {
18864
+ const normalizedContent = ensureTrailingNewline(content);
18865
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(normalizedContent);
18866
+ if (match === null) return ensureTrailingNewline([
18867
+ normalizedContent.trimEnd(),
18868
+ "",
18869
+ `${sectionName}:`,
18870
+ ...block,
18871
+ ""
18872
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18873
+ const sectionStartIndex = match.index;
18874
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18875
+ nextSectionPattern.lastIndex = sectionStartIndex + match[0].length;
18876
+ let nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18877
+ while (nextSectionMatch !== null && nextSectionMatch.index === sectionStartIndex) nextSectionMatch = nextSectionPattern.exec(normalizedContent);
18878
+ const insertIndex = nextSectionMatch?.index ?? normalizedContent.length;
18879
+ const prefix = normalizedContent.slice(0, insertIndex).trimEnd();
18880
+ const suffix = normalizedContent.slice(insertIndex);
18881
+ return ensureTrailingNewline([
18882
+ prefix,
18883
+ ...block,
18884
+ suffix.trimStart()
18885
+ ].join("\n"));
18886
+ };
18887
+ const findTopLevelSectionRange = (content, sectionName) => {
18888
+ const match = new RegExp(`^${sectionName}:\\s*$`, "m").exec(content);
18889
+ if (match === null) return null;
18890
+ const headerLineEndIndex = content.indexOf("\n", match.index);
18891
+ const headerEndIndex = headerLineEndIndex === -1 ? match.index + match[0].length : headerLineEndIndex + 1;
18892
+ const nextSectionPattern = /^[A-Za-z0-9_-]+:\s*$/gm;
18893
+ nextSectionPattern.lastIndex = headerEndIndex;
18894
+ return {
18895
+ headerEndIndex,
18896
+ contentEndIndex: nextSectionPattern.exec(content)?.index ?? content.length
18897
+ };
18898
+ };
18899
+ const appendLefthookCommand = (content) => {
18900
+ const normalizedContent = ensureTrailingNewline(content);
18901
+ const sectionRange = findTopLevelSectionRange(normalizedContent, "pre-commit");
18902
+ const reactDoctorCommandBlock = [
18903
+ " react-doctor:",
18904
+ ` run: ${NON_BLOCKING_REACT_DOCTOR_COMMAND}`,
18905
+ ""
18986
18906
  ];
18987
- const setupChoices = setupActionChoices.length === 0 ? [] : [{
18988
- title: "Skip optional setup",
18989
- description: "Install only the agent skill and package setup",
18990
- value: SETUP_OPTION_SKIP,
18991
- selected: false
18992
- }, ...setupActionChoices];
18993
- const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
18994
- type: "multiselect",
18995
- name: "setupOptions",
18996
- message: "Select additional React Doctor setup:",
18997
- choices: setupChoices,
18998
- instructions: false
18999
- }, promptOptions)).setupOptions ?? [];
19000
- const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19001
- const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19002
- const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19003
- const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19004
- const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_WORKFLOW));
19005
- if (options.dryRun) {
19006
- cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19007
- for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19008
- cliLogger.dim(` Source: ${sourceDir}`);
19009
- for (const sibling of findBundledSiblingSkills(sourceDir)) cliLogger.dim(` Also installs skill: ${sibling.name}`);
19010
- cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19011
- cliLogger.dim(" Dev dependency: react-doctor");
19012
- if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19013
- if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19014
- if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19015
- return;
19016
- }
19017
- const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19018
- try {
19019
- const installResult = await installSkillsFromSource({
19020
- source: sourceDir,
19021
- agents: selectedAgents,
19022
- cwd: projectRoot,
19023
- mode: "copy"
19024
- });
19025
- if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19026
- if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19027
- installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19028
- } catch (error) {
19029
- installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19030
- throw error;
19031
- }
19032
- try {
19033
- const installedSiblingSkills = await installBundledSiblingSkills(sourceDir, selectedAgents, projectRoot);
19034
- if (installedSiblingSkills.length > 0) cliLogger.dim(` Also installed the ${installedSiblingSkills.join(", ")} skill.`);
19035
- } catch {
19036
- cliLogger.dim(" Skipped bundled sibling skills (install error).");
18907
+ if (sectionRange === null) return ensureTrailingNewline([
18908
+ normalizedContent.trimEnd(),
18909
+ "",
18910
+ "pre-commit:",
18911
+ " commands:",
18912
+ ...reactDoctorCommandBlock
18913
+ ].filter((line, index) => index > 0 || line.length > 0).join("\n"));
18914
+ const sectionContent = normalizedContent.slice(sectionRange.headerEndIndex, sectionRange.contentEndIndex);
18915
+ const commandsMatch = /^ commands:\s*$/m.exec(sectionContent);
18916
+ const insertIndex = commandsMatch === null ? sectionRange.headerEndIndex : sectionRange.headerEndIndex + sectionContent.indexOf(commandsMatch[0]) + commandsMatch[0].length + 1;
18917
+ const insertBlock = commandsMatch === null ? [" commands:", ...reactDoctorCommandBlock].join("\n") : reactDoctorCommandBlock.join("\n");
18918
+ return ensureTrailingNewline(`${normalizedContent.slice(0, insertIndex)}${insertBlock}${normalizedContent.slice(insertIndex)}`);
18919
+ };
18920
+ const installLefthook = (options) => {
18921
+ const didHookExist = fs$1.existsSync(options.hookPath);
18922
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18923
+ if (!existingContent.includes("react-doctor")) {
18924
+ const nextContent = appendLefthookCommand(existingContent);
18925
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18926
+ fs$1.writeFileSync(options.hookPath, nextContent);
19037
18927
  }
19038
- const dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19039
- if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) {
19040
- const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19041
- try {
19042
- const hookResult = installReactDoctorGitHook({
19043
- hookPath: gitHookTarget.hookPath,
19044
- projectRoot: gitHookTarget.runnerRoot,
19045
- kind: gitHookTarget.kind,
19046
- hooksPathConfig: gitHookTarget.hooksPathConfig
19047
- });
19048
- hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19049
- recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19050
- } catch (error) {
19051
- hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19052
- throw error;
19053
- }
18928
+ removeLegacyManagedRunner(options.projectRoot);
18929
+ return {
18930
+ hookPath: options.hookPath,
18931
+ kind: "lefthook",
18932
+ status: didHookExist ? "updated" : "created"
18933
+ };
18934
+ };
18935
+ const installPreCommit = (options) => {
18936
+ const didHookExist = fs$1.existsSync(options.hookPath);
18937
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18938
+ if (!existingContent.includes("id: react-doctor")) {
18939
+ const hasReposKey = /^repos:\s*$/m.test(existingContent);
18940
+ const localHookBlock = [
18941
+ " - repo: local",
18942
+ " hooks:",
18943
+ " - id: react-doctor",
18944
+ " name: react-doctor",
18945
+ ` entry: sh -c '${NON_BLOCKING_REACT_DOCTOR_COMMAND}'`,
18946
+ " language: system",
18947
+ " pass_filenames: false",
18948
+ ""
18949
+ ].join("\n");
18950
+ const nextContent = hasReposKey ? `${ensureTrailingNewline(existingContent)}${localHookBlock}` : `repos:\n${localHookBlock}`;
18951
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18952
+ fs$1.writeFileSync(options.hookPath, nextContent);
19054
18953
  }
19055
- if (shouldInstallAgentHooks) {
19056
- const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19057
- try {
19058
- const hookResult = installReactDoctorAgentHooks({
19059
- projectRoot,
19060
- agents: selectedAgents
19061
- });
19062
- if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19063
- else {
19064
- hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19065
- recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19066
- }
19067
- } catch (error) {
19068
- hookSpinner.fail("Failed to install React Doctor agent hooks.");
19069
- throw error;
19070
- }
18954
+ removeLegacyManagedRunner(options.projectRoot);
18955
+ return {
18956
+ hookPath: options.hookPath,
18957
+ kind: "pre-commit",
18958
+ status: didHookExist ? "updated" : "created"
18959
+ };
18960
+ };
18961
+ const installOvercommit = (options) => {
18962
+ const didHookExist = fs$1.existsSync(options.hookPath);
18963
+ const existingContent = didHookExist ? fs$1.readFileSync(options.hookPath, "utf8") : "";
18964
+ if (!existingContent.includes("ReactDoctor")) {
18965
+ const nextContent = appendIndentedBlockToTopLevelSection(existingContent, "PreCommit", [
18966
+ " ReactDoctor:",
18967
+ " enabled: true",
18968
+ ` command: ['sh', '-c', '${NON_BLOCKING_REACT_DOCTOR_COMMAND}']`,
18969
+ ""
18970
+ ]);
18971
+ fs$1.mkdirSync(path$1.dirname(options.hookPath), { recursive: true });
18972
+ fs$1.writeFileSync(options.hookPath, nextContent);
19071
18973
  }
19072
- let didInstallWorkflow = false;
19073
- if (shouldInstallWorkflow) didInstallWorkflow = reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19074
- recordCount(METRIC.installCompleted, 1, {
19075
- agentsCount: selectedAgents.length,
19076
- gitHook: shouldInstallGitHook,
19077
- agentHooks: shouldInstallAgentHooks,
19078
- workflow: didInstallWorkflow,
19079
- dependencyStatus: dependencyResult.dependencyStatus,
19080
- packageManager: detectPackageManager(projectRoot)
19081
- });
19082
- for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
18974
+ removeLegacyManagedRunner(options.projectRoot);
18975
+ return {
18976
+ hookPath: options.hookPath,
18977
+ kind: "overcommit",
18978
+ status: didHookExist ? "updated" : "created"
18979
+ };
19083
18980
  };
19084
18981
  //#endregion
19085
- //#region src/cli/utils/hash-project-root.ts
19086
- const hashProjectRoot = (projectRoot) => createHash("sha256").update(path$1.resolve(projectRoot)).digest("hex");
19087
- //#endregion
19088
- //#region src/cli/utils/action-upgrade-prompt.ts
19089
- const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
19090
- const getActionUpgradeStore = (options = {}) => new Conf({
19091
- projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
19092
- cwd: options.cwd
19093
- });
19094
- const hasHandledActionUpgrade = (projectRoot, storeOptions = {}) => {
19095
- try {
19096
- const upgrades = getActionUpgradeStore(storeOptions).get("actionUpgrades", {});
19097
- return Boolean(upgrades[hashProjectRoot(projectRoot)]);
19098
- } catch {
19099
- return true;
19100
- }
18982
+ //#region src/cli/utils/install-git-hook.ts
18983
+ const isHuskyProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".husky")) || packageHasDependency(projectRoot, "husky");
18984
+ const isVitePlusProject = (projectRoot) => packageHasDependency(projectRoot, "vite-plus");
18985
+ const isSimpleGitHooksProject = (projectRoot) => {
18986
+ const packageJson = readPackageJson(projectRoot);
18987
+ return isRecord(packageJson) && isRecord(packageJson["simple-git-hooks"]) || packageHasDependency(projectRoot, "simple-git-hooks") || fs$1.existsSync(path$1.join(projectRoot, ".simple-git-hooks.cjs"));
19101
18988
  };
19102
- const recordActionUpgradeDecision = (projectRoot, outcome, storeOptions = {}) => {
19103
- try {
19104
- const store = getActionUpgradeStore(storeOptions);
19105
- const upgrades = store.get("actionUpgrades", {});
19106
- store.set("actionUpgrades", {
19107
- ...upgrades,
19108
- [hashProjectRoot(projectRoot)]: {
19109
- rootDirectory: path$1.resolve(projectRoot),
19110
- outcome,
19111
- at: (/* @__PURE__ */ new Date()).toISOString()
19112
- }
19113
- });
19114
- return true;
19115
- } catch {
19116
- return false;
18989
+ const getLefthookConfigPath = (projectRoot) => {
18990
+ for (const fileName of LEFTHOOK_CONFIG_FILES) {
18991
+ const filePath = path$1.join(projectRoot, fileName);
18992
+ if (fs$1.existsSync(filePath)) return filePath;
19117
18993
  }
18994
+ return packageHasDependency(projectRoot, "lefthook") ? path$1.join(projectRoot, LEFTHOOK_CONFIG_FILES[0] ?? "lefthook.yml") : null;
19118
18995
  };
19119
- //#endregion
19120
- //#region src/cli/utils/install-skill-for-agent.ts
19121
- const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19122
- const source = getSkillSourceDirectory();
19123
- if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19124
- const result = await installSkillsFromSource({
19125
- source,
19126
- agents: [agent],
19127
- cwd: projectRoot,
19128
- mode: "copy"
19129
- });
19130
- return result.skills.length > 0 && result.failed.length === 0;
18996
+ const isPreCommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, PRE_COMMIT_CONFIG_FILE));
18997
+ const isOvercommitProject = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, ".overcommit.yml")) || packageHasDependency(projectRoot, "overcommit");
18998
+ const isYorkieProject = (projectRoot) => packageHasRecordKey(projectRoot, "gitHooks") || packageHasDependency(projectRoot, "yorkie");
18999
+ const isGhooksProject = (projectRoot) => packageHasDependency(projectRoot, "ghooks") || packageHasNestedRecordKey(projectRoot, "config", "ghooks");
19000
+ const isGitHooksJsProject = (projectRoot) => packageHasRecordKey(projectRoot, "git-hooks") || packageHasDependency(projectRoot, "git-hooks-js");
19001
+ const isPreCommitNpmProject = (projectRoot) => packageHasDependency(projectRoot, "pre-commit");
19002
+ const isPrettyQuickProject = (projectRoot) => packageHasDependency(projectRoot, "pretty-quick");
19003
+ const detectGitHookTarget = (projectRoot) => {
19004
+ if (runGit(projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== "true") return null;
19005
+ const topLevel = runGit(projectRoot, ["rev-parse", "--show-toplevel"]) ?? projectRoot;
19006
+ const configuredHooksPath = runGit(projectRoot, [
19007
+ "config",
19008
+ "--path",
19009
+ "--get",
19010
+ "core.hooksPath"
19011
+ ]);
19012
+ if (configuredHooksPath !== null && configuredHooksPath.length > 0) return {
19013
+ hookPath: path$1.join(resolveGitPath(topLevel, configuredHooksPath), HOOK_FILE_NAME),
19014
+ runnerRoot: topLevel,
19015
+ kind: "configured"
19016
+ };
19017
+ if (isHuskyProject(topLevel)) return {
19018
+ hookPath: path$1.join(topLevel, HUSKY_HOOKS_PATH, HOOK_FILE_NAME),
19019
+ runnerRoot: topLevel,
19020
+ kind: "husky",
19021
+ hooksPathConfig: HUSKY_HOOKS_PATH
19022
+ };
19023
+ if (isVitePlusProject(topLevel)) return {
19024
+ hookPath: path$1.join(topLevel, VITE_PLUS_HOOKS_PATH, HOOK_FILE_NAME),
19025
+ runnerRoot: topLevel,
19026
+ kind: "vite-plus",
19027
+ hooksPathConfig: VITE_PLUS_HOOKS_PATH
19028
+ };
19029
+ if (isSimpleGitHooksProject(topLevel)) return {
19030
+ hookPath: path$1.join(topLevel, "package.json"),
19031
+ runnerRoot: topLevel,
19032
+ kind: "simple-git-hooks"
19033
+ };
19034
+ const lefthookConfigPath = getLefthookConfigPath(topLevel);
19035
+ if (lefthookConfigPath !== null) return {
19036
+ hookPath: lefthookConfigPath,
19037
+ runnerRoot: topLevel,
19038
+ kind: "lefthook"
19039
+ };
19040
+ if (isPreCommitProject(topLevel)) return {
19041
+ hookPath: path$1.join(topLevel, PRE_COMMIT_CONFIG_FILE),
19042
+ runnerRoot: topLevel,
19043
+ kind: "pre-commit"
19044
+ };
19045
+ if (isOvercommitProject(topLevel)) return {
19046
+ hookPath: path$1.join(topLevel, OVERCOMMIT_CONFIG_FILE),
19047
+ runnerRoot: topLevel,
19048
+ kind: "overcommit"
19049
+ };
19050
+ if (isYorkieProject(topLevel)) return {
19051
+ hookPath: getPackageJsonPath(topLevel),
19052
+ runnerRoot: topLevel,
19053
+ kind: "yorkie"
19054
+ };
19055
+ if (isGhooksProject(topLevel)) return {
19056
+ hookPath: getPackageJsonPath(topLevel),
19057
+ runnerRoot: topLevel,
19058
+ kind: "ghooks"
19059
+ };
19060
+ if (isGitHooksJsProject(topLevel)) return {
19061
+ hookPath: getPackageJsonPath(topLevel),
19062
+ runnerRoot: topLevel,
19063
+ kind: "git-hooks-js"
19064
+ };
19065
+ if (isPreCommitNpmProject(topLevel)) return {
19066
+ hookPath: getPackageJsonPath(topLevel),
19067
+ runnerRoot: topLevel,
19068
+ kind: "pre-commit-npm"
19069
+ };
19070
+ if (isPrettyQuickProject(topLevel)) return {
19071
+ hookPath: getPackageJsonPath(topLevel),
19072
+ runnerRoot: topLevel,
19073
+ kind: "pretty-quick"
19074
+ };
19075
+ const hookPath = runGit(projectRoot, [
19076
+ "rev-parse",
19077
+ "--git-path",
19078
+ HOOK_RELATIVE_PATH
19079
+ ]);
19080
+ if (hookPath === null || hookPath.length === 0) return null;
19081
+ return {
19082
+ hookPath: resolveGitPath(projectRoot, hookPath),
19083
+ runnerRoot: topLevel,
19084
+ kind: "git"
19085
+ };
19086
+ };
19087
+ const installReactDoctorGitHook = (options) => {
19088
+ if (options.kind === "simple-git-hooks") return installSimpleGitHooks(options);
19089
+ if (options.kind === "lefthook") return installLefthook(options);
19090
+ if (options.kind === "pre-commit") return installPreCommit(options);
19091
+ if (options.kind === "overcommit") return installOvercommit(options);
19092
+ if (options.kind === "yorkie") return installYorkie(options);
19093
+ if (options.kind === "ghooks") return installGhooks(options);
19094
+ if (options.kind === "git-hooks-js") return installGitHooksJs(options);
19095
+ if (options.kind === "pre-commit-npm") return installPreCommitNpm(options);
19096
+ if (options.kind === "pretty-quick") return installPrettyQuick(options);
19097
+ return installDirectGitHook(options);
19131
19098
  };
19132
19099
  //#endregion
19133
- //#region src/cli/utils/open-url.ts
19134
- const resolveOpenCommand = (url) => {
19135
- if (process$1.platform === "darwin") return {
19136
- command: "open",
19137
- args: [url]
19100
+ //#region src/cli/utils/should-skip-prompts.ts
19101
+ const shouldSkipPrompts = (input = {}) => Boolean(input.yes) || Boolean(input.json) || isNonInteractiveEnvironment() || !process.stdin.isTTY;
19102
+ //#endregion
19103
+ //#region src/cli/utils/install-react-doctor.ts
19104
+ const SETUP_OPTION_GIT_HOOK = "git-hook";
19105
+ const SETUP_OPTION_AGENT_HOOKS = "agent-hooks";
19106
+ const SETUP_OPTION_SKIP = "skip";
19107
+ const CONFIG_ONLY_GIT_HOOK_KINDS = new Set([
19108
+ "ghooks",
19109
+ "git-hooks-js",
19110
+ "lefthook",
19111
+ "overcommit",
19112
+ "pre-commit",
19113
+ "pre-commit-npm",
19114
+ "pretty-quick",
19115
+ "simple-git-hooks",
19116
+ "yorkie"
19117
+ ]);
19118
+ const PACKAGE_MANAGER_LOCKFILES = [
19119
+ {
19120
+ packageManager: "pnpm",
19121
+ fileName: "pnpm-lock.yaml"
19122
+ },
19123
+ {
19124
+ packageManager: "yarn",
19125
+ fileName: "yarn.lock"
19126
+ },
19127
+ {
19128
+ packageManager: "bun",
19129
+ fileName: "bun.lockb"
19130
+ },
19131
+ {
19132
+ packageManager: "bun",
19133
+ fileName: "bun.lock"
19134
+ },
19135
+ {
19136
+ packageManager: "npm",
19137
+ fileName: "package-lock.json"
19138
+ }
19139
+ ];
19140
+ const findNearestFileDirectory = (startDirectory, fileNames) => {
19141
+ let currentDirectory = path$1.resolve(startDirectory);
19142
+ while (true) {
19143
+ if (fileNames.some((fileName) => fs$1.existsSync(path$1.join(currentDirectory, fileName)))) return currentDirectory;
19144
+ const parentDirectory = path$1.dirname(currentDirectory);
19145
+ if (parentDirectory === currentDirectory) return null;
19146
+ currentDirectory = parentDirectory;
19147
+ }
19148
+ };
19149
+ const detectPackageManager = (projectRoot) => {
19150
+ let currentDirectory = path$1.resolve(projectRoot);
19151
+ while (true) {
19152
+ const packageJson = readPackageJson(currentDirectory);
19153
+ if (isRecord(packageJson) && typeof packageJson.packageManager === "string") {
19154
+ const packageManagerName = packageJson.packageManager.split("@")[0];
19155
+ if (packageManagerName === "pnpm" || packageManagerName === "yarn" || packageManagerName === "bun" || packageManagerName === "npm") return packageManagerName;
19156
+ }
19157
+ const parentDirectory = path$1.dirname(currentDirectory);
19158
+ if (parentDirectory === currentDirectory) break;
19159
+ currentDirectory = parentDirectory;
19160
+ }
19161
+ const lockfileDirectory = findNearestFileDirectory(projectRoot, PACKAGE_MANAGER_LOCKFILES.map((lockfile) => lockfile.fileName));
19162
+ return PACKAGE_MANAGER_LOCKFILES.find((lockfile) => lockfileDirectory !== null && fs$1.existsSync(path$1.join(lockfileDirectory, lockfile.fileName)))?.packageManager ?? "npm";
19163
+ };
19164
+ const packageManagerNeedsWorkspaceFlag = (projectRoot) => fs$1.existsSync(path$1.join(projectRoot, "pnpm-workspace.yaml")) || findNearestFileDirectory(projectRoot, ["pnpm-workspace.yaml"]) !== null;
19165
+ const buildInstallCommand = (projectRoot) => {
19166
+ const packageManager = detectPackageManager(projectRoot);
19167
+ const packageSpecifier = `${DOCTOR_PACKAGE_NAME}@latest`;
19168
+ if (packageManager === "npm") return {
19169
+ command: "npm",
19170
+ args: [
19171
+ "install",
19172
+ "--save-dev",
19173
+ packageSpecifier
19174
+ ],
19175
+ cwd: projectRoot
19138
19176
  };
19139
- if (process$1.platform === "win32") return {
19140
- command: "cmd",
19177
+ if (packageManager === "yarn") return {
19178
+ command: "yarn",
19141
19179
  args: [
19142
- "/c",
19143
- "start",
19144
- "",
19145
- url
19146
- ]
19180
+ "add",
19181
+ "--dev",
19182
+ packageSpecifier
19183
+ ],
19184
+ cwd: projectRoot
19185
+ };
19186
+ if (packageManager === "bun") return {
19187
+ command: "bun",
19188
+ args: [
19189
+ "add",
19190
+ "--dev",
19191
+ packageSpecifier
19192
+ ],
19193
+ cwd: projectRoot
19147
19194
  };
19148
19195
  return {
19149
- command: "xdg-open",
19150
- args: [url]
19196
+ command: "pnpm",
19197
+ args: [
19198
+ "add",
19199
+ "--save-dev",
19200
+ ...packageManagerNeedsWorkspaceFlag(projectRoot) ? ["-w"] : [],
19201
+ packageSpecifier
19202
+ ],
19203
+ cwd: projectRoot
19151
19204
  };
19152
19205
  };
19153
- const openUrl = (url) => {
19154
- try {
19155
- const { command, args } = resolveOpenCommand(url);
19156
- const child = spawn(command, args, {
19157
- detached: true,
19158
- stdio: "ignore"
19159
- });
19160
- child.on("error", () => {});
19161
- child.unref();
19162
- return true;
19163
- } catch {
19164
- return false;
19165
- }
19166
- };
19167
- //#endregion
19168
- //#region src/cli/utils/open-workflow-pull-request.ts
19169
- const NEW_BRANCH_PREFIX = "react-doctor/add-github-actions";
19170
- const DEFAULT_COMMIT_MESSAGE = "ci: add React Doctor GitHub Actions workflow";
19171
- const DEFAULT_PR_TITLE = "Add React Doctor to GitHub Actions";
19172
- const DEFAULT_PR_BODY = `Adds a [React Doctor](https://www.react.doctor) scan to every pull request and every push to the default branch. The workflow file is documented inline.
19173
-
19174
- Docs: https://www.react.doctor/ci`;
19175
19206
  const execFileAsync = promisify(execFile);
19176
- const run = async (command, args, cwd) => {
19207
+ const defaultInstallDependencyRunner = async (input) => {
19208
+ await execFileAsync(input.command, [...input.args], {
19209
+ cwd: input.cwd,
19210
+ env: {
19211
+ ...process.env,
19212
+ REACT_DOCTOR_INSTALL: "1"
19213
+ },
19214
+ shell: process.platform === "win32"
19215
+ });
19216
+ };
19217
+ const isSupplyChainTrustError = (error) => {
19218
+ const candidate = error;
19219
+ const haystack = [
19220
+ candidate?.stderr,
19221
+ candidate?.stdout,
19222
+ candidate?.message
19223
+ ].map((part) => String(part ?? "")).join("\n");
19224
+ return /ERR_PNPM_TRUST_DOWNGRADE|trust downgrade/i.test(haystack);
19225
+ };
19226
+ const formatInstallCommand = (input) => [input.command, ...input.args].join(" ");
19227
+ const installReactDoctorDependency = async (options) => {
19228
+ const packageJson = readPackageJson(options.projectRoot);
19229
+ if (!isRecord(packageJson)) return {
19230
+ dependencyStatus: "skipped",
19231
+ dependencyReason: "missing-or-invalid-package-json"
19232
+ };
19233
+ if (hasDoctorDependency(packageJson)) return { dependencyStatus: "existing" };
19234
+ if (packageJson.devDependencies !== void 0 && !isRecord(packageJson.devDependencies)) return {
19235
+ dependencyStatus: "skipped",
19236
+ dependencyReason: "invalid-dev-dependencies"
19237
+ };
19238
+ const runnerInput = buildInstallCommand(options.projectRoot);
19177
19239
  try {
19178
- const { stdout, stderr } = await execFileAsync(command, [...args], {
19179
- cwd,
19180
- encoding: "utf8"
19181
- });
19182
- return {
19183
- success: true,
19184
- stdout: stdout.trim(),
19185
- stderr: stderr.trim()
19186
- };
19240
+ await (options.runner ?? defaultInstallDependencyRunner)(runnerInput);
19187
19241
  } catch (error) {
19188
- const failure = error;
19189
19242
  return {
19190
- success: false,
19191
- stdout: (failure.stdout ?? "").trim(),
19192
- stderr: (failure.stderr ?? "").trim()
19243
+ dependencyStatus: "skipped",
19244
+ dependencyReason: isSupplyChainTrustError(error) ? "trust-policy-blocked" : "install-command-failed",
19245
+ installCommand: formatInstallCommand(runnerInput)
19193
19246
  };
19194
19247
  }
19248
+ return { dependencyStatus: "created" };
19195
19249
  };
19196
- const detectDefaultBranch = async (cwd) => {
19197
- const symRef = await run("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
19198
- if (symRef.success) {
19199
- const branchMatch = symRef.stdout.match(/refs\/remotes\/origin\/(.+)$/);
19200
- if (branchMatch) return branchMatch[1];
19201
- }
19202
- if ((await run("git", [
19203
- "rev-parse",
19204
- "--verify",
19205
- "origin/main"
19206
- ], cwd)).success) return "main";
19207
- if ((await run("git", [
19208
- "rev-parse",
19209
- "--verify",
19210
- "origin/master"
19211
- ], cwd)).success) return "master";
19212
- return null;
19250
+ const buildManualGitHookTarget = (hookPath, projectRoot) => ({
19251
+ hookPath,
19252
+ runnerRoot: projectRoot,
19253
+ kind: "git"
19254
+ });
19255
+ const formatGitHookInstallMessage = (hookResult) => {
19256
+ 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.`;
19257
+ return `React Doctor pre-commit hook ${hookResult.status} at ${hookResult.hookPath}.`;
19213
19258
  };
19214
- const findUniqueBranchName = async (cwd) => {
19215
- if (!(await run("git", [
19216
- "rev-parse",
19217
- "--verify",
19218
- NEW_BRANCH_PREFIX
19219
- ], cwd)).success) return NEW_BRANCH_PREFIX;
19220
- return `${NEW_BRANCH_PREFIX}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[-:T]/g, "")}`;
19259
+ const formatDependencyInstallMessage = (result) => {
19260
+ if (result.dependencyStatus === "created") return "Installed dev dependency: react-doctor.";
19261
+ if (result.dependencyStatus === "existing") return "React Doctor dependency already exists.";
19262
+ if (result.dependencyReason === "invalid-dev-dependencies") return "Skipped dev dependency install: devDependencies field is not an object.";
19263
+ if (result.dependencyReason === "trust-policy-blocked") return "Local install skipped by your package manager's supply-chain trust policy (safe to ignore for pre-release packages).";
19264
+ if (result.dependencyReason === "install-command-failed") return "Local install failed: your package manager rejected the command.";
19265
+ return "Skipped dev dependency install: package.json missing or invalid.";
19221
19266
  };
19222
- const openWorkflowPullRequest = async (params) => {
19223
- const workflowPath = path$1.resolve(params.workflowPath);
19224
- const commitMessage = params.commitMessage ?? DEFAULT_COMMIT_MESSAGE;
19225
- const prTitle = params.prTitle ?? DEFAULT_PR_TITLE;
19226
- const prBody = params.prBody ?? DEFAULT_PR_BODY;
19227
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19228
- if (!repoRootProbe.success) return {
19229
- status: "not-attempted",
19230
- reason: "not-a-git-repo"
19231
- };
19232
- const cwd = repoRootProbe.stdout;
19233
- if (!isCommandAvailable("gh")) return {
19234
- status: "not-attempted",
19235
- reason: "gh-not-installed"
19236
- };
19237
- if (!(await run("gh", ["auth", "status"], cwd)).success) return {
19238
- status: "not-attempted",
19239
- reason: "gh-not-authenticated"
19240
- };
19241
- const defaultBranch = await detectDefaultBranch(cwd);
19242
- if (!defaultBranch) return {
19243
- status: "not-attempted",
19244
- reason: "no-default-branch"
19245
- };
19246
- const previousBranchProbe = await run("git", [
19247
- "rev-parse",
19248
- "--abbrev-ref",
19249
- "HEAD"
19250
- ], cwd);
19251
- if (!previousBranchProbe.success || previousBranchProbe.stdout === "HEAD") return {
19252
- status: "not-attempted",
19253
- reason: "detached-head"
19254
- };
19255
- const previousBranch = previousBranchProbe.stdout;
19256
- await run("git", [
19257
- "fetch",
19258
- "origin",
19259
- defaultBranch
19260
- ], cwd);
19261
- const newBranch = await findUniqueBranchName(cwd);
19262
- if (!(await run("git", [
19263
- "checkout",
19264
- "-b",
19265
- newBranch,
19266
- `origin/${defaultBranch}`
19267
- ], cwd)).success) return {
19268
- status: "not-attempted",
19269
- reason: "checkout-failed"
19270
- };
19271
- const restoreToPreviousBranch = async (deleteNewBranch) => {
19272
- await run("git", ["checkout", previousBranch], cwd);
19273
- if (deleteNewBranch) await run("git", [
19274
- "branch",
19275
- "-D",
19276
- newBranch
19277
- ], cwd);
19278
- };
19279
- if (!(await run("git", [
19280
- "add",
19281
- "--",
19282
- path$1.relative(cwd, workflowPath)
19283
- ], cwd)).success) {
19284
- await restoreToPreviousBranch(true);
19285
- return {
19286
- status: "not-attempted",
19287
- reason: "git-add-failed"
19288
- };
19267
+ const buildDependencyFollowUp = (result) => {
19268
+ if (result.dependencyReason !== "trust-policy-blocked" && result.dependencyReason !== "install-command-failed") return;
19269
+ return ` React Doctor still works via \`npx react-doctor\`. To install locally: ${result.installCommand ?? `npm install --save-dev react-doctor@latest`}`;
19270
+ };
19271
+ const installReactDoctorPackageSetup = async (projectRoot, dependencyRunner) => {
19272
+ installReactDoctorScriptStep(projectRoot);
19273
+ const dependencySpinner = spinner("Installing React Doctor package...").start();
19274
+ try {
19275
+ const dependencyResult = await installReactDoctorDependency({
19276
+ projectRoot,
19277
+ runner: dependencyRunner
19278
+ });
19279
+ recordCount(METRIC.installDependency, 1, {
19280
+ status: dependencyResult.dependencyStatus,
19281
+ reason: dependencyResult.dependencyReason ?? null,
19282
+ packageManager: detectPackageManager(projectRoot)
19283
+ });
19284
+ if (dependencyResult.dependencyStatus === "skipped") {
19285
+ const message = formatDependencyInstallMessage(dependencyResult);
19286
+ if (dependencyResult.dependencyReason === "trust-policy-blocked") dependencySpinner.warn(message);
19287
+ else dependencySpinner.fail(message);
19288
+ const followUp = buildDependencyFollowUp(dependencyResult);
19289
+ if (followUp !== void 0) cliLogger.dim(followUp);
19290
+ return dependencyResult;
19291
+ }
19292
+ dependencySpinner.succeed(formatDependencyInstallMessage(dependencyResult));
19293
+ return dependencyResult;
19294
+ } catch (error) {
19295
+ dependencySpinner.fail("Failed to install React Doctor package.");
19296
+ throw error;
19297
+ }
19298
+ };
19299
+ const getSkillSourceDirectory = () => {
19300
+ const distDirectory = path$1.dirname(fileURLToPath(import.meta.url));
19301
+ return path$1.join(distDirectory, "skills", SKILL_NAME);
19302
+ };
19303
+ const canInstallNativeAgentHooks = (agents) => agents.some((agent) => agent === "claude-code" || agent === "cursor");
19304
+ const installReactDoctorSkillStep = async (sourceDir, selectedAgents, projectRoot) => {
19305
+ const installSpinner = spinner(`Installing ${SKILL_NAME} skill...`).start();
19306
+ try {
19307
+ const installResult = await installSkillsFromSource({
19308
+ source: sourceDir,
19309
+ agents: selectedAgents,
19310
+ cwd: projectRoot,
19311
+ mode: "copy"
19312
+ });
19313
+ if (installResult.skills.length === 0) throw new Error(`Could not parse ${SKILL_MANIFEST_FILE} for ${SKILL_NAME} (missing or invalid frontmatter).`);
19314
+ if (installResult.failed.length > 0) throw new Error(installResult.failed.map((failure) => `${getSkillAgentConfig(failure.agent).displayName}: ${failure.error}`).join("\n"));
19315
+ installSpinner.succeed(`${SKILL_NAME} skill installed for ${selectedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19316
+ } catch (error) {
19317
+ installSpinner.fail(`Failed to install ${SKILL_NAME} skill.`);
19318
+ throw error;
19289
19319
  }
19290
- if (!(await run("git", [
19291
- "commit",
19292
- "-m",
19293
- commitMessage
19294
- ], cwd)).success) {
19295
- await restoreToPreviousBranch(true);
19296
- return {
19297
- status: "not-attempted",
19298
- reason: "git-commit-failed"
19299
- };
19320
+ };
19321
+ const installReactDoctorGitHookStep = (gitHookTarget) => {
19322
+ const hookSpinner = spinner("Installing React Doctor pre-commit hook...").start();
19323
+ try {
19324
+ const hookResult = installReactDoctorGitHook({
19325
+ hookPath: gitHookTarget.hookPath,
19326
+ projectRoot: gitHookTarget.runnerRoot,
19327
+ kind: gitHookTarget.kind,
19328
+ hooksPathConfig: gitHookTarget.hooksPathConfig
19329
+ });
19330
+ hookSpinner.succeed(formatGitHookInstallMessage(hookResult));
19331
+ recordCount(METRIC.installGitHook, 1, { kind: hookResult.kind });
19332
+ } catch (error) {
19333
+ hookSpinner.fail("Failed to install React Doctor pre-commit hook.");
19334
+ throw error;
19300
19335
  }
19301
- if (!(await run("git", [
19302
- "push",
19303
- "-u",
19304
- "origin",
19305
- newBranch
19306
- ], cwd)).success) {
19307
- await restoreToPreviousBranch(true);
19308
- return {
19309
- status: "not-attempted",
19310
- reason: "git-push-failed"
19311
- };
19336
+ };
19337
+ const installReactDoctorAgentHooksStep = (projectRoot, selectedAgents) => {
19338
+ const hookSpinner = spinner("Installing React Doctor agent hooks...").start();
19339
+ try {
19340
+ const hookResult = installReactDoctorAgentHooks({
19341
+ projectRoot,
19342
+ agents: selectedAgents
19343
+ });
19344
+ if (hookResult.installedAgents.length === 0) hookSpinner.succeed("No supported native agent hook targets selected.");
19345
+ else {
19346
+ hookSpinner.succeed(`React Doctor agent hooks installed for ${hookResult.installedAgents.map((agent) => getSkillAgentConfig(agent).displayName).join(", ")}.`);
19347
+ recordCount(METRIC.installAgentHooks, 1, { agentsCount: hookResult.installedAgents.length });
19348
+ }
19349
+ } catch (error) {
19350
+ hookSpinner.fail("Failed to install React Doctor agent hooks.");
19351
+ throw error;
19312
19352
  }
19313
- const prCreate = await run("gh", [
19314
- "pr",
19315
- "create",
19316
- "--title",
19317
- prTitle,
19318
- "--body",
19319
- prBody,
19320
- "--base",
19321
- defaultBranch,
19322
- "--head",
19323
- newBranch
19324
- ], cwd);
19325
- await restoreToPreviousBranch(false);
19326
- if (!prCreate.success) return {
19327
- status: "branch-pushed",
19328
- branch: newBranch
19329
- };
19330
- return {
19331
- status: "pr-opened",
19332
- url: prCreate.stdout.split(/\r?\n/).filter(Boolean).pop() ?? ""
19333
- };
19334
19353
  };
19335
- const stageWorkflowFile = async (params) => {
19336
- const workflowPath = path$1.resolve(params.workflowPath);
19337
- const repoRootProbe = await run("git", ["rev-parse", "--show-toplevel"], path$1.dirname(workflowPath));
19338
- if (!repoRootProbe.success) return false;
19339
- return (await run("git", [
19340
- "add",
19341
- "--",
19342
- path$1.relative(repoRootProbe.stdout, workflowPath)
19343
- ], repoRootProbe.stdout)).success;
19354
+ const installReactDoctorWorkflowStep = (projectRoot) => {
19355
+ return reportWorkflowResult(spinner("Adding GitHub Actions workflow...").start(), installReactDoctorWorkflow(projectRoot), projectRoot);
19356
+ };
19357
+ const upgradeReactDoctorWorkflowStep = (projectRoot) => {
19358
+ const workflowSpinner = spinner("Upgrading GitHub Actions workflow to v2...").start();
19359
+ const upgradeResult = upgradeReactDoctorWorkflowInPlace(projectRoot);
19360
+ if (upgradeResult.status === "failed") {
19361
+ workflowSpinner.fail("Couldn't update the GitHub Actions workflow.");
19362
+ return false;
19363
+ }
19364
+ if (upgradeResult.status === "not-needed") {
19365
+ workflowSpinner.succeed("GitHub Actions workflow already up to date.");
19366
+ return false;
19367
+ }
19368
+ workflowSpinner.succeed(`Upgraded the GitHub Actions workflow to v2 at ${path$1.relative(projectRoot, upgradeResult.workflowPath)}.`);
19369
+ recordCount(METRIC.installWorkflow, 1, { kind: "upgrade" });
19370
+ return true;
19371
+ };
19372
+ const runInstallReactDoctor = async (options = {}) => {
19373
+ const requestedProjectRoot = options.projectRoot ?? process.cwd();
19374
+ const projectRoot = findNearestPackageDirectory(requestedProjectRoot) ?? requestedProjectRoot;
19375
+ const sourceDir = options.sourceDir ?? getSkillSourceDirectory();
19376
+ if (!fs$1.existsSync(path$1.join(sourceDir, SKILL_MANIFEST_FILE))) {
19377
+ cliLogger.error(`Could not locate the ${SKILL_NAME} skill bundled with this package.`);
19378
+ process.exitCode = 1;
19379
+ return;
19380
+ }
19381
+ const detectedAgents = options.detectedAgents ?? await detectAvailableAgents();
19382
+ if (detectedAgents.length === 0) {
19383
+ cliLogger.error("No supported coding agents detected.");
19384
+ cliLogger.dim(" Looked for binaries on PATH (claude, codex, cursor, droid, gemini, copilot, opencode, pi)");
19385
+ cliLogger.dim(" and config dirs in $HOME (~/.claude, ~/.cursor, ~/.codex, ~/.gemini, ...).");
19386
+ process.exitCode = 1;
19387
+ return;
19388
+ }
19389
+ const skipPrompts = shouldSkipPrompts({ yes: options.yes });
19390
+ const gitHookTarget = options.gitHookPath === void 0 ? detectGitHookTarget(projectRoot) : options.gitHookPath === null ? null : buildManualGitHookTarget(options.gitHookPath, projectRoot);
19391
+ const gitHookPath = gitHookTarget?.hookPath;
19392
+ const promptOptions = options.onPromptCancel === void 0 ? {} : { onCancel: options.onPromptCancel };
19393
+ const prompt = options.prompt ?? prompts;
19394
+ const workflowTargetPath = getReactDoctorWorkflowPath(projectRoot);
19395
+ const existingWorkflow = readReactDoctorWorkflow(projectRoot);
19396
+ const canInstallWorkflow = !fs$1.existsSync(workflowTargetPath);
19397
+ const canUpgradeWorkflow = existingWorkflow !== null && workflowUsesV1Action(existingWorkflow.content) && !hasHandledActionUpgrade(projectRoot);
19398
+ const shouldInstallWorkflow = canInstallWorkflow && (Boolean(options.yes) || !skipPrompts && await askAddToGitHubActions(prompt) === "yes");
19399
+ const upgradePromptOutcome = canUpgradeWorkflow && !options.yes && !skipPrompts ? await askUpgradeActionVersion(prompt) : null;
19400
+ const shouldUpgradeWorkflow = canUpgradeWorkflow && (Boolean(options.yes) || upgradePromptOutcome === "yes");
19401
+ if (upgradePromptOutcome === "no" && !options.dryRun) recordActionUpgradeDecision(projectRoot, "declined");
19402
+ const selectedAgents = skipPrompts ? detectedAgents : (await prompt({
19403
+ type: "multiselect",
19404
+ name: "agents",
19405
+ message: `Install the ${highlighter.info(`/react-doctor`)} skill for:`,
19406
+ choices: detectedAgents.map((agent) => ({
19407
+ title: getSkillAgentConfig(agent).displayName,
19408
+ value: agent,
19409
+ selected: true
19410
+ })),
19411
+ instructions: false,
19412
+ min: 1
19413
+ }, promptOptions)).agents ?? [];
19414
+ if (selectedAgents.length === 0) return;
19415
+ let dependencyResult;
19416
+ if (!options.dryRun) {
19417
+ await installReactDoctorSkillStep(sourceDir, selectedAgents, projectRoot);
19418
+ dependencyResult = await installReactDoctorPackageSetup(projectRoot, options.installDependencyRunner);
19419
+ }
19420
+ let didInstallWorkflow = false;
19421
+ if (!options.dryRun && (shouldInstallWorkflow || shouldUpgradeWorkflow)) {
19422
+ cliLogger.break();
19423
+ if (shouldInstallWorkflow) didInstallWorkflow = installReactDoctorWorkflowStep(projectRoot);
19424
+ else if (upgradeReactDoctorWorkflowStep(projectRoot)) recordActionUpgradeDecision(projectRoot, "accepted");
19425
+ }
19426
+ const setupActionChoices = [...gitHookPath === null || gitHookPath === void 0 ? [] : [{
19427
+ title: "Pre-commit hook",
19428
+ description: "Check staged changes before each commit",
19429
+ value: SETUP_OPTION_GIT_HOOK,
19430
+ selected: true
19431
+ }], ...canInstallNativeAgentHooks(selectedAgents) ? [{
19432
+ title: "Agent hooks",
19433
+ description: "Ask Claude Code or Cursor to scan after code edits",
19434
+ value: SETUP_OPTION_AGENT_HOOKS,
19435
+ selected: Boolean(options.agentHooks)
19436
+ }] : []];
19437
+ const setupChoices = setupActionChoices.length === 0 ? [] : [{
19438
+ title: "Skip optional setup",
19439
+ description: "Install only the agent skill and package setup",
19440
+ value: SETUP_OPTION_SKIP,
19441
+ selected: false
19442
+ }, ...setupActionChoices];
19443
+ if (setupChoices.length > 0 && !options.dryRun) cliLogger.break();
19444
+ const selectedSetupOptions = skipPrompts || setupChoices.length === 0 ? [] : (await prompt({
19445
+ type: "multiselect",
19446
+ name: "setupOptions",
19447
+ message: "Select additional React Doctor setup:",
19448
+ choices: setupChoices,
19449
+ instructions: false
19450
+ }, promptOptions)).setupOptions ?? [];
19451
+ const selectedSetupActions = selectedSetupOptions.filter((setupOption) => setupOption !== SETUP_OPTION_SKIP);
19452
+ const didSkipOptionalSetup = selectedSetupActions.length === 0 && selectedSetupOptions.includes(SETUP_OPTION_SKIP);
19453
+ const shouldInstallGitHook = gitHookPath != null && (Boolean(options.yes) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_GIT_HOOK));
19454
+ const shouldInstallAgentHooks = Boolean(options.agentHooks) || !didSkipOptionalSetup && selectedSetupActions.includes(SETUP_OPTION_AGENT_HOOKS);
19455
+ if (!options.dryRun) {
19456
+ if (shouldInstallGitHook && gitHookTarget !== null && gitHookTarget !== void 0) installReactDoctorGitHookStep(gitHookTarget);
19457
+ if (shouldInstallAgentHooks) installReactDoctorAgentHooksStep(projectRoot, selectedAgents);
19458
+ }
19459
+ if (options.dryRun) {
19460
+ cliLogger.log(`Dry run — would install ${SKILL_NAME} skill for:`);
19461
+ for (const agent of selectedAgents) cliLogger.dim(` - ${getSkillAgentConfig(agent).displayName}`);
19462
+ cliLogger.dim(` Source: ${sourceDir}`);
19463
+ cliLogger.dim(" Package script: doctor (or react-doctor if doctor exists)");
19464
+ cliLogger.dim(" Dev dependency: react-doctor");
19465
+ if (shouldInstallGitHook) cliLogger.dim(` Git hook: ${gitHookPath}`);
19466
+ if (shouldInstallAgentHooks) cliLogger.dim(" Agent hooks: Claude Code / Cursor when selected");
19467
+ if (shouldInstallWorkflow) cliLogger.dim(` GitHub Actions workflow: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19468
+ if (shouldUpgradeWorkflow) cliLogger.dim(` Upgrade GitHub Actions workflow to v2: ${path$1.relative(projectRoot, workflowTargetPath)}`);
19469
+ return;
19470
+ }
19471
+ recordCount(METRIC.installCompleted, 1, {
19472
+ agentsCount: selectedAgents.length,
19473
+ gitHook: shouldInstallGitHook,
19474
+ agentHooks: shouldInstallAgentHooks,
19475
+ workflow: didInstallWorkflow,
19476
+ dependencyStatus: dependencyResult?.dependencyStatus ?? "skipped",
19477
+ packageManager: detectPackageManager(projectRoot)
19478
+ });
19479
+ for (const agent of selectedAgents) recordCount(METRIC.installAgent, 1, { agent });
19480
+ };
19481
+ //#endregion
19482
+ //#region src/cli/utils/install-skill-for-agent.ts
19483
+ const installReactDoctorSkillForAgent = async (agent, projectRoot) => {
19484
+ const source = getSkillSourceDirectory();
19485
+ if (!fs$1.existsSync(path$1.join(source, SKILL_MANIFEST_FILE))) return false;
19486
+ const result = await installSkillsFromSource({
19487
+ source,
19488
+ agents: [agent],
19489
+ cwd: projectRoot,
19490
+ mode: "copy"
19491
+ });
19492
+ return result.skills.length > 0 && result.failed.length === 0;
19344
19493
  };
19345
19494
  //#endregion
19346
19495
  //#region src/cli/utils/launch-agent.ts
@@ -19431,9 +19580,6 @@ const copyToClipboard = (text) => {
19431
19580
  };
19432
19581
  //#endregion
19433
19582
  //#region src/cli/utils/handoff-to-agent.ts
19434
- const CI_YES_CHOICE = "ci-yes";
19435
- const CI_LEARN_MORE_CHOICE = "ci-learn-more";
19436
- const CI_NO_CHOICE = "ci-no";
19437
19583
  const CLIPBOARD_CHOICE = "clipboard";
19438
19584
  const SKIP_CHOICE = "skip";
19439
19585
  const printPayload = (payload) => {
@@ -19442,59 +19588,11 @@ const printPayload = (payload) => {
19442
19588
  cliLogger.log(payload);
19443
19589
  cliLogger.log(highlighter.dim("──────────────────────"));
19444
19590
  };
19445
- const setUpGitHubActions = async (rootDirectory) => {
19446
- const projectRoot = findNearestPackageDirectory(rootDirectory) ?? rootDirectory;
19447
- try {
19448
- installReactDoctorScriptStep(projectRoot);
19449
- } catch {}
19450
- const workflowSpinner = spinner("Adding GitHub Actions workflow...").start();
19451
- const workflowResult = installReactDoctorWorkflow(projectRoot);
19452
- reportWorkflowResult(workflowSpinner, workflowResult, projectRoot);
19453
- cliLogger.break();
19454
- if (workflowResult.status === "failed") {
19455
- cliLogger.log(` Couldn't set up GitHub Actions automatically. Follow the guide at ${highlighter.info(CI_URL)}`);
19456
- return;
19457
- }
19458
- if (workflowResult.status === "created") {
19459
- const pullRequestSpinner = spinner("Opening a pull request for review...").start();
19460
- const pullRequestResult = await openWorkflowPullRequest({ workflowPath: workflowResult.workflowPath });
19461
- if (pullRequestResult.status === "pr-opened") pullRequestSpinner.succeed(`Opened pull request for review: ${highlighter.info(pullRequestResult.url)}`);
19462
- else if (pullRequestResult.status === "branch-pushed") pullRequestSpinner.warn(`Pushed branch ${highlighter.bold(pullRequestResult.branch)} but couldn't open a PR. Open one with: gh pr create --head ${pullRequestResult.branch}`);
19463
- else {
19464
- pullRequestSpinner.stop();
19465
- if (await stageWorkflowFile({ workflowPath: workflowResult.workflowPath })) cliLogger.log(` Staged the workflow file. Commit it to start scanning every pull request.`);
19466
- else cliLogger.log(" React Doctor will now scan every new pull request automatically.");
19467
- }
19468
- }
19469
- cliLogger.log(` Learn more: ${highlighter.info(CI_URL)}`);
19470
- };
19471
- const UPGRADE_YES_CHOICE = "upgrade-yes";
19472
- const UPGRADE_NO_CHOICE = "upgrade-no";
19473
19591
  const UPGRADE_COMMIT_MESSAGE = "ci: upgrade React Doctor GitHub Action to v2";
19474
19592
  const UPGRADE_PR_TITLE = "Upgrade React Doctor Action to v2";
19475
19593
  const UPGRADE_PR_BODY = `Bumps the React Doctor GitHub Actions workflow to the action's latest major, \`millionco/react-doctor@v2\`.
19476
19594
 
19477
19595
  Docs: https://www.react.doctor/ci`;
19478
- const askUpgradeActionVersion = async () => {
19479
- const { upgradeChoice } = await prompts({
19480
- type: "select",
19481
- name: "upgradeChoice",
19482
- message: "A new major of the React Doctor Action (v2) is out. Upgrade this repo's workflow?",
19483
- hint: " ",
19484
- choices: [{
19485
- title: "Yes (recommended)",
19486
- description: "Open a PR bumping the workflow to millionco/react-doctor@v2",
19487
- value: UPGRADE_YES_CHOICE
19488
- }, {
19489
- title: "No, thanks",
19490
- description: "Keep @v1 — won't ask again for this repo",
19491
- value: UPGRADE_NO_CHOICE
19492
- }],
19493
- initial: 0
19494
- }, { onCancel: () => true });
19495
- if (upgradeChoice === void 0) return "cancel";
19496
- return upgradeChoice === UPGRADE_YES_CHOICE ? "yes" : "no";
19497
- };
19498
19596
  const upgradeGitHubActionsWorkflow = async (workflow) => {
19499
19597
  const { content, changed } = upgradeWorkflowActionToV2(workflow.content);
19500
19598
  if (!changed) return false;
@@ -19539,46 +19637,6 @@ const maybeOfferActionUpgrade = async (projectRoot) => {
19539
19637
  }
19540
19638
  if (await upgradeGitHubActionsWorkflow(workflow)) recordActionUpgradeDecision(projectRoot, "accepted");
19541
19639
  };
19542
- const SGR_BOLD_OFF = "\x1B[22m";
19543
- const ciQuestionMessage = [
19544
- "Add React Doctor to GitHub Actions?",
19545
- `${SGR_BOLD_OFF} ${highlighter.dim("Scan every pull request to prevent new React issues while you fix the backlog.")}`,
19546
- `${SGR_BOLD_OFF} ${highlighter.dim(`Used by teams at ${CI_TRUST_COMPANIES}.`)}`
19547
- ].join("\n");
19548
- const askAddToGitHubActions = async () => {
19549
- while (true) {
19550
- const { ciChoice } = await prompts({
19551
- type: "select",
19552
- name: "ciChoice",
19553
- message: ciQuestionMessage,
19554
- hint: " ",
19555
- choices: [
19556
- {
19557
- title: "Yes (recommended)",
19558
- description: "Adds the workflow file and a doctor package script",
19559
- value: CI_YES_CHOICE
19560
- },
19561
- {
19562
- title: "Learn more",
19563
- description: highlighter.info(CI_URL),
19564
- value: CI_LEARN_MORE_CHOICE
19565
- },
19566
- {
19567
- title: "No, thanks",
19568
- description: "Continue to the agent handoff",
19569
- value: CI_NO_CHOICE
19570
- }
19571
- ],
19572
- initial: 0
19573
- }, { onCancel: () => true });
19574
- if (ciChoice === void 0) return "cancel";
19575
- if (ciChoice === CI_YES_CHOICE) return "yes";
19576
- if (ciChoice === CI_NO_CHOICE) return "no";
19577
- const opened = openUrl(CI_URL);
19578
- cliLogger.log(opened ? `Opened ${highlighter.info(CI_URL)} in your browser.` : `Visit ${highlighter.info(CI_URL)} to learn more.`);
19579
- cliLogger.break();
19580
- }
19581
- };
19582
19640
  const detectLaunchableAgents = async () => {
19583
19641
  const detected = new Set(await detectAvailableAgents());
19584
19642
  return Object.keys(CLI_AGENT_BINARIES).filter((agentId) => detected.has(agentId) && isCommandAvailable(CLI_AGENT_BINARIES[agentId]));
@@ -19595,7 +19653,7 @@ const handoffToAgent = async (input) => {
19595
19653
  });
19596
19654
  if (ciOutcome === "cancel") return;
19597
19655
  if (ciOutcome === "yes") {
19598
- await setUpGitHubActions(input.rootDirectory);
19656
+ await setUpGitHubActions({ rootDirectory: input.rootDirectory });
19599
19657
  cliLogger.break();
19600
19658
  }
19601
19659
  } else await maybeOfferActionUpgrade(projectRootForCi);
@@ -19746,6 +19804,14 @@ const HAPPY_FACE_LINES = [
19746
19804
  "│ ▽ │",
19747
19805
  "└─────┘"
19748
19806
  ];
19807
+ const FACE_INDENT = " ";
19808
+ const FACE_PREFIX_WIDTH = 2 + (HAPPY_FACE_LINES[0]?.length ?? 0) + 2;
19809
+ const clampToColumns = (text, maxColumns) => {
19810
+ if (maxColumns <= 0) return "";
19811
+ if (text.length <= maxColumns) return text;
19812
+ if (maxColumns === 1) return "…";
19813
+ return `${text.slice(0, maxColumns - 1).trimEnd()}…`;
19814
+ };
19749
19815
  const typeLine = (linePrefix, text, style, charDelayMs) => Effect.gen(function* () {
19750
19816
  const characters = [...text];
19751
19817
  for (let length = 1; length <= characters.length; length += 1) {
@@ -19759,13 +19825,17 @@ const playWelcomeScene = (options = {}) => Effect.gen(function* () {
19759
19825
  const interLineDelayMs = 250 / speedMultiplier;
19760
19826
  const explanationHoldMs = WELCOME_EXPLANATION_HOLD_MS / speedMultiplier;
19761
19827
  const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
19762
- const mouthPrefix = ` ${face[2] ?? ""} `;
19763
- yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
19828
+ const mouthPrefix = `${FACE_INDENT}${face[2] ?? ""}${FACE_INDENT}`;
19829
+ const terminalColumns = process.stdout.columns;
19830
+ const availableTextColumns = terminalColumns && terminalColumns > 0 ? Math.max(0, terminalColumns - FACE_PREFIX_WIDTH - 1) : Number.POSITIVE_INFINITY;
19831
+ const greeting = clampToColumns("Welcome to React Doctor", availableTextColumns);
19832
+ const tagline = clampToColumns("I diagnose your React code for bugs, security & performance.", availableTextColumns);
19833
+ yield* writeStdout(`\n${face.map((line) => `${FACE_INDENT}${line}`).join("\n")}\n`);
19764
19834
  yield* writeStdout("\x1B[3A");
19765
- yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment), charDelayMs);
19835
+ yield* typeLine(`${FACE_INDENT}${face[1] ?? ""}${FACE_INDENT}`, greeting, (fragment) => highlighter.bold(fragment), charDelayMs);
19766
19836
  yield* Effect.sleep(interLineDelayMs);
19767
19837
  yield* writeStdout("\x1B[1B");
19768
- yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment), charDelayMs);
19838
+ yield* typeLine(mouthPrefix, tagline, (fragment) => highlighter.dim(fragment), charDelayMs);
19769
19839
  yield* Effect.sleep(explanationHoldMs);
19770
19840
  yield* writeStdout("\x1B[3A\r\x1B[0J");
19771
19841
  });
@@ -21521,4 +21591,4 @@ Promise.resolve().then(() => assertNoRemovedFlags(process.argv)).then(() => prog
21521
21591
  export {};
21522
21592
 
21523
21593
  //# sourceMappingURL=cli.js.map
21524
- //# debugId=1486eaee-ed07-5eef-a9d7-51293140e237
21594
+ //# debugId=de2dd8ab-0280-54a5-852a-2a7dca2192fe