react-doctor 0.2.16 → 0.2.17-dev.0c8b797

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]="7cd8f7c3-d243-5c1a-9ebb-98a50f4157a1")}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]="07713237-df07-5858-b7a4-7b12c0e7b293")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import * as Path from "node:path";
@@ -41,11 +41,11 @@ import * as Exit from "effect/Exit";
41
41
  import { stripVTControlCharacters } from "node:util";
42
42
  import tty from "node:tty";
43
43
  import { codeFrameColumns } from "@babel/code-frame";
44
+ import Conf from "conf";
44
45
  import { createHash, randomUUID } from "node:crypto";
45
46
  import basePrompts from "prompts";
46
47
  import { SKILL_MANIFEST_FILE, detectInstalledSkillAgents, getSkillAgentConfig, getSkillAgentTypes, installSkillsFromSource } from "agent-install";
47
48
  import { fileURLToPath } from "node:url";
48
- import Conf from "conf";
49
49
  import { generateCode, loadFile, writeFile } from "magicast";
50
50
  import { getConfigFromVariableDeclaration, getDefaultExportOptions } from "magicast/helpers";
51
51
  //#region \0rolldown/runtime.js
@@ -5054,33 +5054,15 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
5054
5054
  value: mod,
5055
5055
  enumerable: true
5056
5056
  }) : target, mod));
5057
- /**
5058
- * Narrow errors raised by the project-discovery helpers
5059
- * (`discoverProject` / `resolveDiagnoseTarget` / `readPackageJson`).
5060
- *
5061
- * These extend `Error` directly — they are NOT the tagged
5062
- * `ReactDoctorError` from `../errors.js` (that one wraps every
5063
- * runtime-pipeline failure as a `Schema.TaggedErrorClass` for
5064
- * `Effect.catchReasons` dispatch). The split is intentional:
5065
- *
5066
- * - Discovery happens BEFORE the Effect runtime takes over — at the
5067
- * `diagnose()` / CLI entry point — and throws plain JS exceptions
5068
- * so callers can `try/catch` without an Effect-layer-aware
5069
- * `instanceof` check.
5070
- * - The Project service (`services/project.ts → translateProjectInfoError`)
5071
- * translates each of these into the equivalent tagged-error
5072
- * `reason` before re-raising inside the Effect pipeline, so the
5073
- * runtime never sees a non-tagged failure.
5074
- *
5075
- * If you're inside the Effect runtime, use the tagged
5076
- * `ReactDoctorError` from `../errors.js` instead.
5077
- */
5078
5057
  var ProjectNotFoundError = class extends Error {
5079
5058
  name = "ProjectNotFoundError";
5080
5059
  directory;
5060
+ kind;
5081
5061
  constructor(directory, options) {
5082
- super(`No React project found in ${directory}. Expected a package.json at the directory root or a nested package.json with a React dependency.`, options);
5062
+ const kind = options?.kind ?? "no-project";
5063
+ super(kind === "missing-path" ? `Scan target "${directory}" does not exist. Check the path and try again.` : `No React project found in ${directory}. Expected a package.json at the directory root or a nested package.json with a React dependency.`, options);
5083
5064
  this.directory = directory;
5065
+ this.kind = kind;
5084
5066
  }
5085
5067
  };
5086
5068
  var NoReactDependencyError = class extends Error {
@@ -5117,6 +5099,7 @@ var AmbiguousProjectError = class extends Error {
5117
5099
  this.candidates = candidates;
5118
5100
  }
5119
5101
  };
5102
+ const isProjectDiscoveryError = (value) => value instanceof ProjectNotFoundError || value instanceof NoReactDependencyError || value instanceof PackageJsonNotFoundError || value instanceof NotADirectoryError || value instanceof AmbiguousProjectError;
5120
5103
  const isFile = (filePath) => {
5121
5104
  try {
5122
5105
  return fs.statSync(filePath).isFile();
@@ -6299,7 +6282,7 @@ const MILLISECONDS_PER_SECOND = 1e3;
6299
6282
  const SCORE_API_URL = "https://www.react.doctor/api/score";
6300
6283
  const ENTERPRISE_CONTACT_URL = "https://react.doctor/enterprise";
6301
6284
  const SHARE_BASE_URL = "https://react.doctor/share";
6302
- const DOCS_URL = "https://www.react.doctor/docs";
6285
+ const DOCS_URL = "https://react.doctor/docs";
6303
6286
  const DOCS_RULES_BASE_URL = `${DOCS_URL}/rules`;
6304
6287
  const FETCH_TIMEOUT_MS = 1e4;
6305
6288
  const GITHUB_VIEWER_PERMISSION_TIMEOUT_MS = 2e3;
@@ -7701,7 +7684,7 @@ const resolveScanTarget = async (requestedDirectory, options = {}) => {
7701
7684
  const redirectedDirectory = resolveConfigRootDir(userConfig, configSourceDirectory);
7702
7685
  const directoryAfterRedirect = redirectedDirectory ?? absoluteRequested;
7703
7686
  const resolvedDirectory = resolveDiagnoseTarget(directoryAfterRedirect, options) ?? directoryAfterRedirect;
7704
- if (!isDirectory(resolvedDirectory)) throw existsSync(resolvedDirectory) ? new NotADirectoryError(resolvedDirectory) : new ProjectNotFoundError(resolvedDirectory);
7687
+ if (!isDirectory(resolvedDirectory)) throw existsSync(resolvedDirectory) ? new NotADirectoryError(resolvedDirectory) : new ProjectNotFoundError(resolvedDirectory, { kind: "missing-path" });
7705
7688
  return {
7706
7689
  resolvedDirectory,
7707
7690
  requestedDirectory: absoluteRequested,
@@ -9203,7 +9186,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
9203
9186
  if (result.status !== 0) return null;
9204
9187
  const branch = trimOrNull(result.stdout);
9205
9188
  return branch === "HEAD" ? null : branch;
9206
- }));
9189
+ }), Effect.orElseSucceed(() => null));
9207
9190
  const defaultBranch = (directory) => Effect.gen(function* () {
9208
9191
  const symref = yield* runGit(directory, ["symbolic-ref", "refs/remotes/origin/HEAD"]);
9209
9192
  if (symref.status === 0) {
@@ -11759,7 +11742,7 @@ const filterSourceFiles = (filePaths) => filePaths.filter(isLintableSourceFile);
11759
11742
  /**
11760
11743
  * Canonical URL for a rule's documentation page — its reviewer-tested fix
11761
11744
  * recipe rendered for humans — served at
11762
- * `https://www.react.doctor/docs/rules/<plugin>/<rule>`. The CLI links here
11745
+ * `https://react.doctor/docs/rules/<plugin>/<rule>`. The CLI links here
11763
11746
  * from its fix-recipe directive so each fix follows the canonical recipe
11764
11747
  * instead of being improvised per diagnostic.
11765
11748
  */
@@ -11851,6 +11834,9 @@ const detectCodingAgent = () => {
11851
11834
  const isCodingAgentEnvironment = () => detectCodingAgent() !== null;
11852
11835
  const isCiOrCodingAgentEnvironment = () => isCiEnvironment() || isCodingAgentEnvironment();
11853
11836
  //#endregion
11837
+ //#region src/cli/utils/is-git-hook-environment.ts
11838
+ const isGitHookEnvironment = () => Boolean(process.env.GIT_DIR);
11839
+ //#endregion
11854
11840
  //#region src/cli/utils/is-non-interactive-environment.ts
11855
11841
  const NON_INTERACTIVE_ENVIRONMENT_VARIABLES = [
11856
11842
  "CI",
@@ -11871,6 +11857,9 @@ const isNonInteractiveEnvironment = () => NON_INTERACTIVE_ENVIRONMENT_VARIABLES.
11871
11857
  //#endregion
11872
11858
  //#region src/cli/utils/constants.ts
11873
11859
  const STAGED_FILES_TEMP_DIR_PREFIX = "react-doctor-staged-";
11860
+ const WELCOME_EXPLANATION_HOLD_MS = 2e3;
11861
+ const WELCOME_HOLD_MS = 1e3;
11862
+ const CATEGORY_COUNTUP_SETTLE_HOLD_MS = 1e3;
11874
11863
  const INTERNAL_ERROR_JSON_FALLBACK = "{\"schemaVersion\":1,\"ok\":false,\"error\":{\"message\":\"Internal error\",\"name\":\"Error\",\"chain\":[]}}\n";
11875
11864
  const SENTRY_FLUSH_TIMEOUT_MS = 2e3;
11876
11865
  const NANOSECONDS_PER_SECOND = 1000000000n;
@@ -11942,7 +11931,7 @@ const makeNoopConsole = () => ({
11942
11931
  });
11943
11932
  //#endregion
11944
11933
  //#region src/cli/utils/version.ts
11945
- const VERSION = "0.2.16";
11934
+ const VERSION = "0.2.17-dev.0c8b797";
11946
11935
  //#endregion
11947
11936
  //#region src/cli/utils/json-mode.ts
11948
11937
  let context = null;
@@ -12044,7 +12033,7 @@ const detectNodeMajor = () => {
12044
12033
  return Number.isNaN(major) ? 0 : major;
12045
12034
  };
12046
12035
  const detectOrigin = () => {
12047
- if (process.env.GIT_DIR) return "git-hook";
12036
+ if (isGitHookEnvironment()) return "git-hook";
12048
12037
  if (isCodingAgentEnvironment()) return "agent";
12049
12038
  if (isCiEnvironment()) return "ci";
12050
12039
  return "cli";
@@ -12288,13 +12277,13 @@ const isDevVersion = (version) => version === "0.0.0" || version.includes("-");
12288
12277
  * uploads source-map artifacts under, so stack frames symbolicate. Honors the
12289
12278
  * standard `SENTRY_RELEASE` override.
12290
12279
  */
12291
- const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.16`;
12280
+ const resolveSentryRelease = () => process.env.SENTRY_RELEASE || `react-doctor@0.2.17-dev.0c8b797`;
12292
12281
  /**
12293
12282
  * Deployment environment shown in Sentry's environment filter. Defaults to
12294
12283
  * `production` for tagged releases and `development` for dev/unbuilt versions,
12295
12284
  * overridable via the standard `SENTRY_ENVIRONMENT` env var.
12296
12285
  */
12297
- const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.16") ? "development" : "production");
12286
+ const resolveSentryEnvironment = () => process.env.SENTRY_ENVIRONMENT || (isDevVersion("0.2.17-dev.0c8b797") ? "development" : "production");
12298
12287
  /**
12299
12288
  * Performance-tracing sample rate in `[0, 1]`. Reads `SENTRY_TRACES_SAMPLE_RATE`
12300
12289
  * (set to `0` to disable tracing) and falls back to
@@ -15916,6 +15905,11 @@ const wrapTextToWidth = (text, width, options = {}) => {
15916
15905
  return text.split("\n").flatMap((lineText) => wrapLine(lineText, width, breakLongWords));
15917
15906
  };
15918
15907
  //#endregion
15908
+ //#region src/cli/utils/write-stdout.ts
15909
+ const writeStdout = (text) => Effect.sync(() => {
15910
+ process.stdout.write(text);
15911
+ });
15912
+ //#endregion
15919
15913
  //#region src/cli/utils/render-diagnostics.ts
15920
15914
  const POINTER = isUnicodeSupported() ? "›" : ">";
15921
15915
  const colorizeBySeverity = (text, severity) => severity === "error" ? highlighter.error(text) : highlighter.warn(text);
@@ -15949,14 +15943,39 @@ const buildCategoryDiagnosticGroups = (diagnostics, rulePriority) => {
15949
15943
  return categoryGroupA.category.localeCompare(categoryGroupB.category);
15950
15944
  });
15951
15945
  };
15952
- const buildCompactCategoryLine = (categoryGroup) => {
15953
- const errorCount = categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
15954
- const warningCount = categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
15946
+ const formatCategoryTallyLine = (tally, errorShown, warningShown) => {
15955
15947
  const parts = [];
15956
- if (errorCount > 0) parts.push(highlighter.error(`${errorCount} ${errorCount === 1 ? "error" : "errors"}`));
15957
- if (warningCount > 0) parts.push(highlighter.warn(highlighter.dim(`${warningCount} ${warningCount === 1 ? "warning" : "warnings"}`)));
15958
- return ` ${highlighter.bold(categoryGroup.category)} ${highlighter.dim(POINTER)} ${parts.join(highlighter.dim(", "))}`;
15948
+ if (tally.errorCount > 0) parts.push(highlighter.error(`${errorShown} ${errorShown === 1 ? "error" : "errors"}`));
15949
+ if (tally.warningCount > 0) parts.push(highlighter.warn(highlighter.dim(`${warningShown} ${warningShown === 1 ? "warning" : "warnings"}`)));
15950
+ return ` ${highlighter.bold(tally.category)} ${highlighter.dim(POINTER)} ${parts.join(highlighter.dim(", "))}`;
15951
+ };
15952
+ const buildCategoryTally = (categoryGroup) => ({
15953
+ category: categoryGroup.category,
15954
+ errorCount: categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length,
15955
+ warningCount: categoryGroup.diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length
15956
+ });
15957
+ const buildCategoryTallyLines = (tallies) => tallies.map((tally) => formatCategoryTallyLine(tally, tally.errorCount, tally.warningCount));
15958
+ const buildPartiallyRevealedTallyLines = (tallies, revealedUnitCount) => {
15959
+ let remainingToReveal = revealedUnitCount;
15960
+ return tallies.map((tally) => {
15961
+ const errorShown = Math.min(tally.errorCount, remainingToReveal);
15962
+ remainingToReveal -= errorShown;
15963
+ const warningShown = Math.min(tally.warningCount, remainingToReveal);
15964
+ remainingToReveal -= warningShown;
15965
+ return formatCategoryTallyLine(tally, errorShown, warningShown);
15966
+ });
15959
15967
  };
15968
+ const printCategoryCountUp = (tallies) => Effect.gen(function* () {
15969
+ const totalUnitCount = tallies.reduce((sum, tally) => sum + tally.errorCount + tally.warningCount, 0);
15970
+ const unitsPerStep = Math.max(1, Math.ceil(totalUnitCount / 24));
15971
+ for (let revealedUnitCount = 0; revealedUnitCount < totalUnitCount; revealedUnitCount += unitsPerStep) {
15972
+ const lines = buildPartiallyRevealedTallyLines(tallies, revealedUnitCount);
15973
+ yield* writeStdout(`${revealedUnitCount === 0 ? "" : `\x1b[${tallies.length}A`}\r${lines.join("\n\r")}\n`);
15974
+ yield* Effect.sleep(70);
15975
+ }
15976
+ yield* writeStdout(`${totalUnitCount === 0 ? "" : `\x1b[${tallies.length}A`}\r${buildCategoryTallyLines(tallies).join("\n\r")}\n`);
15977
+ yield* Effect.sleep(CATEGORY_COUNTUP_SETTLE_HOLD_MS);
15978
+ });
15960
15979
  const TOP_ERROR_DETAIL_INDENT = " ";
15961
15980
  const pickRepresentativeDiagnostic = (ruleDiagnostics) => ruleDiagnostics.find((diagnostic) => diagnostic.line > 0) ?? ruleDiagnostics[0];
15962
15981
  const FRAME_CONTEXT_REACH_LINES = 3;
@@ -16014,7 +16033,7 @@ const buildRuleDetailBlock = (ruleKey, ruleDiagnostics, resolveSourceRoot, rende
16014
16033
  const { severity } = representative;
16015
16034
  const trailingBadge = formatTrailingSiteBadge(ruleDiagnostics.length);
16016
16035
  const headline = colorizeBySeverity(`${representative.category}: ${representative.title ?? ruleKey}`, severity);
16017
- const lines = [` ${colorizeBySeverity(severity === "error" ? "✗" : "⚠", severity)} ${headline}${trailingBadge}`];
16036
+ const lines = [` ${colorizeBySeverity(severity === "error" ? "✖" : "⚠", severity)} ${headline}${trailingBadge}`];
16018
16037
  if (renderEverySite && !isAgentEnvironment) {
16019
16038
  const learnMoreLine = formatLearnMoreLine(representative);
16020
16039
  if (learnMoreLine) lines.push(`${TOP_ERROR_DETAIL_INDENT}${highlighter.info(learnMoreLine)}`);
@@ -16048,33 +16067,48 @@ const buildOverflowSummaryLine = (diagnostics, rulePriority) => {
16048
16067
  parts.push(highlighter.bold(highlighter.warn(`+${warningCount} optional ${warningNoun}`)));
16049
16068
  }
16050
16069
  const command = highlighter.bold(highlighter.info("npx react-doctor@latest --verbose"));
16051
- return ` ${parts.length > 0 ? `${parts.join(highlighter.dim(" and "))} ${highlighter.dim("— run")}` : highlighter.dim("Run")} ${command} ${highlighter.dim("for details")}`;
16070
+ return ` ${parts.length > 0 ? `${parts.join(highlighter.dim(" and "))} ${highlighter.dim("- run")}` : highlighter.dim("Run")} ${command} ${highlighter.dim("for details")}`;
16052
16071
  };
16053
16072
  const getTopErrorRuleKeys = (diagnostics, limit, rulePriority) => new Set(selectTopErrorRuleGroups(diagnostics, limit, rulePriority).map(([ruleKey]) => ruleKey));
16054
- const buildTopErrorsLines = (diagnostics, resolveSourceRoot, rulePriority) => {
16073
+ const buildTopErrorsSection = (diagnostics, resolveSourceRoot, rulePriority) => {
16055
16074
  const topRuleGroups = selectErrorRuleGroups(diagnostics, rulePriority).slice(0, 3);
16056
- if (topRuleGroups.length === 0) return [];
16075
+ if (topRuleGroups.length === 0) return {
16076
+ lines: [],
16077
+ blockOffsets: []
16078
+ };
16057
16079
  const lines = [
16058
16080
  buildSectionDivider(),
16059
16081
  ` ${highlighter.bold(`Top ${topRuleGroups.length} ${topRuleGroups.length === 1 ? "error" : "errors"} you should fix`)}`,
16060
16082
  ""
16061
16083
  ];
16084
+ const blockOffsets = [];
16062
16085
  for (const [ruleKey, ruleDiagnostics] of topRuleGroups) {
16086
+ blockOffsets.push(lines.length);
16063
16087
  lines.push(...buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, false, false));
16064
16088
  lines.push("");
16065
16089
  }
16066
- return lines;
16090
+ return {
16091
+ lines,
16092
+ blockOffsets
16093
+ };
16067
16094
  };
16068
- const buildCategoryBreakdownLines = (diagnostics, rulePriority) => buildCategoryDiagnosticGroups(diagnostics, rulePriority).map(buildCompactCategoryLine);
16069
16095
  const joinSections = (...sections) => {
16070
16096
  const lines = [];
16097
+ const sectionStarts = [];
16071
16098
  for (const section of sections) {
16072
- if (section.length === 0) continue;
16099
+ if (section.length === 0) {
16100
+ sectionStarts.push(null);
16101
+ continue;
16102
+ }
16073
16103
  if (lines.length > 0) lines.push("");
16104
+ sectionStarts.push(lines.length);
16074
16105
  lines.push(...section);
16075
16106
  }
16076
16107
  if (lines.length > 0 && lines[lines.length - 1] !== "") lines.push("");
16077
- return lines;
16108
+ return {
16109
+ lines,
16110
+ sectionStarts
16111
+ };
16078
16112
  };
16079
16113
  const buildCountsSummaryLines = (diagnostics) => {
16080
16114
  const totalIssueCount = diagnostics.length;
@@ -16089,16 +16123,36 @@ const buildCountsSummaryLines = (diagnostics) => {
16089
16123
  * single Effect.forEach over Console.log so failures or fiber
16090
16124
  * interruption produce predictable partial output.
16091
16125
  */
16092
- const printDiagnostics = (diagnostics, isVerbose, sourceRoot, rulePriority, isAgentEnvironment = false) => Effect.gen(function* () {
16126
+ const printDiagnostics = (diagnostics, isVerbose, sourceRoot, rulePriority, isAgentEnvironment = false, onboarding = {}) => Effect.gen(function* () {
16127
+ const sectionPause = onboarding.sectionPause ?? Effect.void;
16128
+ const animateCountUp = onboarding.animateCountUp ?? false;
16093
16129
  const resolveSourceRoot = typeof sourceRoot === "function" ? sourceRoot : () => sourceRoot;
16094
16130
  let detailLines;
16095
- if (!isVerbose) detailLines = buildTopErrorsLines(diagnostics, resolveSourceRoot, rulePriority);
16096
- else detailLines = buildSortedRuleGroups(diagnostics, rulePriority).flatMap(([ruleKey, ruleDiagnostics]) => {
16131
+ let topErrorBlockOffsets = [];
16132
+ if (!isVerbose) {
16133
+ const topErrors = buildTopErrorsSection(diagnostics, resolveSourceRoot, rulePriority);
16134
+ detailLines = topErrors.lines;
16135
+ topErrorBlockOffsets = topErrors.blockOffsets;
16136
+ } else detailLines = buildSortedRuleGroups(diagnostics, rulePriority).flatMap(([ruleKey, ruleDiagnostics]) => {
16097
16137
  return [...buildRuleDetailBlock(ruleKey, ruleDiagnostics, resolveSourceRoot, true, isAgentEnvironment), ""];
16098
16138
  });
16099
16139
  const overflowLine = isVerbose ? void 0 : buildOverflowSummaryLine(diagnostics, rulePriority);
16100
- const lines = joinSections(buildCategoryBreakdownLines(diagnostics, rulePriority), buildCountsSummaryLines(diagnostics), detailLines, overflowLine ? [overflowLine] : []);
16101
- for (const line of lines) yield* Console.log(line);
16140
+ const categoryTallies = buildCategoryDiagnosticGroups(diagnostics, rulePriority).map(buildCategoryTally);
16141
+ const categoryLines = buildCategoryTallyLines(categoryTallies);
16142
+ const { lines, sectionStarts } = joinSections(categoryLines, buildCountsSummaryLines(diagnostics), detailLines, overflowLine ? [overflowLine] : []);
16143
+ const [categoryStart, , detailStart] = sectionStarts;
16144
+ const pauseBeforeLineIndices = detailStart == null ? /* @__PURE__ */ new Set() : new Set(topErrorBlockOffsets.map((offset) => detailStart + offset));
16145
+ let lineIndex = 0;
16146
+ while (lineIndex < lines.length) {
16147
+ if (animateCountUp && lineIndex === categoryStart && categoryLines.length > 0) {
16148
+ yield* printCategoryCountUp(categoryTallies);
16149
+ lineIndex += categoryLines.length;
16150
+ continue;
16151
+ }
16152
+ if (pauseBeforeLineIndices.has(lineIndex)) yield* sectionPause;
16153
+ yield* Console.log(lines[lineIndex]);
16154
+ lineIndex += 1;
16155
+ }
16102
16156
  });
16103
16157
  const formatElapsedTime = (elapsedMilliseconds) => {
16104
16158
  if (elapsedMilliseconds < 1e3) return `${Math.round(elapsedMilliseconds)}ms`;
@@ -16136,6 +16190,45 @@ const computeProjectedScore = async (topErrorSource, rescoreSource, currentScore
16136
16190
  if (!potentialScore || potentialScore.score <= currentScore.score) return null;
16137
16191
  return potentialScore.score;
16138
16192
  };
16193
+ const FORCE_ONBOARDING_ENV_VAR = "REACT_DOCTOR_FORCE_ONBOARDING";
16194
+ const FALSY_FLAG_VALUES = new Set([
16195
+ "",
16196
+ "0",
16197
+ "false"
16198
+ ]);
16199
+ const isOnboardingForced = (environment = process.env) => {
16200
+ const value = environment[FORCE_ONBOARDING_ENV_VAR];
16201
+ return value !== void 0 && !FALSY_FLAG_VALUES.has(value.toLowerCase());
16202
+ };
16203
+ const onboardingSectionPause = (shouldPace) => shouldPace ? Effect.sleep(850) : Effect.void;
16204
+ const shouldRecordOnboarding = (input) => input.paceOnboardingSections && !input.forceOnboarding && !input.verbose && !input.isNonInteractiveEnvironment;
16205
+ const canAnimateOnboarding = (stream = process.stdout) => {
16206
+ if (!(stream.isTTY === true && (stream.columns ?? 0) > 0 && process.env.TERM !== "dumb")) return false;
16207
+ if (isOnboardingForced()) return true;
16208
+ return !isGitHookEnvironment() && !isCiEnvironment();
16209
+ };
16210
+ //#endregion
16211
+ //#region src/cli/utils/onboarding-state.ts
16212
+ const GLOBAL_CONFIG_PROJECT_NAME$1 = "react-doctor";
16213
+ const ONBOARDED_AT_KEY = "onboardedAt";
16214
+ const getOnboardingStore = (options = {}) => new Conf({
16215
+ projectName: GLOBAL_CONFIG_PROJECT_NAME$1,
16216
+ cwd: options.cwd
16217
+ });
16218
+ const hasCompletedOnboarding = (options = {}) => {
16219
+ try {
16220
+ return typeof getOnboardingStore(options).get(ONBOARDED_AT_KEY) === "string";
16221
+ } catch {
16222
+ return true;
16223
+ }
16224
+ };
16225
+ const markOnboardingComplete = (options = {}) => {
16226
+ try {
16227
+ const store = getOnboardingStore(options);
16228
+ if (typeof store.get(ONBOARDED_AT_KEY) === "string") return;
16229
+ store.set(ONBOARDED_AT_KEY, (/* @__PURE__ */ new Date()).toISOString());
16230
+ } catch {}
16231
+ };
16139
16232
  //#endregion
16140
16233
  //#region src/cli/utils/render-project-detection.ts
16141
16234
  const printProjectDetection = (_input) => Effect.void;
@@ -16147,13 +16240,14 @@ const colorizeByScore = (text, score) => {
16147
16240
  return highlighter.error(text);
16148
16241
  };
16149
16242
  //#endregion
16243
+ //#region src/cli/utils/ease-out-cubic.ts
16244
+ const easeOutCubic = (progress) => 1 - (1 - progress) ** 3;
16245
+ //#endregion
16150
16246
  //#region src/cli/utils/render-score-header.ts
16151
16247
  const RAINBOW_HUE_SHIFT_PER_FRAME = 9;
16152
16248
  const RAINBOW_GRADIENT_WIDTH = 80;
16153
16249
  const RAINBOW_OKLCH_LIGHTNESS = .638;
16154
16250
  const RAINBOW_OKLCH_CHROMA = .129;
16155
- const easeOutCubic = (progress) => 1 - (1 - progress) ** 3;
16156
- const sleep = (milliseconds) => Effect.promise(() => new Promise((resolve) => setTimeout(resolve, milliseconds)));
16157
16251
  const buildScoreBarSegments = (filledCount) => {
16158
16252
  const emptyCount = 50 - filledCount;
16159
16253
  return {
@@ -16223,9 +16317,6 @@ const buildFaceRenderedLines = (score) => {
16223
16317
  const colorize = (text) => colorizeByScore(text, score);
16224
16318
  return buildRawFaceLines(score).map(colorize);
16225
16319
  };
16226
- const writeScoreHeaderLine = (line) => Effect.sync(() => {
16227
- process.stdout.write(line);
16228
- });
16229
16320
  const buildScoreLine = (displayScore, finalScore, label) => {
16230
16321
  const scoreNumber = colorizeByScore(`${displayScore}`, finalScore);
16231
16322
  const scoreLabel = colorizeByScore(label, finalScore);
@@ -16264,37 +16355,37 @@ const printAnimatedScore = (scoreFaceLine, barFaceLine, score, label, potentialS
16264
16355
  const progress = easeOutCubic(frame / 40);
16265
16356
  const animatedScore = Math.round(score * progress);
16266
16357
  if (isPerfectScore) {
16267
- yield* writeScoreHeaderLine(`${frame === 0 ? "" : "\x1B[4A"}\r${buildRainbowScoreHeaderFrame({
16358
+ yield* writeStdout(`${frame === 0 ? "" : "\x1B[4A"}\r${buildRainbowScoreHeaderFrame({
16268
16359
  score,
16269
16360
  displayScore: animatedScore,
16270
16361
  label,
16271
16362
  frame
16272
16363
  })}`);
16273
- if (frame < 40) yield* sleep(50);
16364
+ if (frame < 40) yield* Effect.sleep(50);
16274
16365
  continue;
16275
16366
  }
16276
16367
  const animatedScoreLine = buildScoreLine(animatedScore, score, label);
16277
16368
  const animatedBarLine = frame === 40 && potentialScore !== void 0 ? buildProjectedScoreBar(score, potentialScore) : buildScoreBar(animatedScore, score);
16278
- yield* writeScoreHeaderLine(`${frame === 0 ? "" : "\x1B[2A"}\r${buildScoreHeaderLine(scoreFaceLine, animatedScoreLine)}\n\r${buildScoreHeaderLine(barFaceLine, animatedBarLine)}\n`);
16279
- if (frame < 40) yield* sleep(50);
16369
+ yield* writeStdout(`${frame === 0 ? "" : "\x1B[2A"}\r${buildScoreHeaderLine(scoreFaceLine, animatedScoreLine)}\n\r${buildScoreHeaderLine(barFaceLine, animatedBarLine)}\n`);
16370
+ if (frame < 40) yield* Effect.sleep(50);
16280
16371
  }
16281
16372
  if (!isPerfectScore) return;
16282
16373
  for (let frame = 0; frame < 16; frame += 1) {
16283
- yield* writeScoreHeaderLine(`\x1b[4A\r${buildRainbowScoreHeaderFrame({
16374
+ yield* writeStdout(`\x1b[4A\r${buildRainbowScoreHeaderFrame({
16284
16375
  score,
16285
16376
  displayScore: score,
16286
16377
  label,
16287
16378
  frame
16288
16379
  })}`);
16289
- yield* sleep(50);
16380
+ yield* Effect.sleep(50);
16290
16381
  }
16291
- yield* writeScoreHeaderLine(`\x1b[4A\r${buildFinalPerfectScoreHeaderFrame(score, label, 16)}\x1b[2A`);
16382
+ yield* writeStdout(`\x1b[4A\r${buildFinalPerfectScoreHeaderFrame(score, label, 16)}\x1b[2A`);
16292
16383
  });
16293
16384
  const printScoreHeader = (scoreResult, potentialScore) => Effect.gen(function* () {
16294
16385
  const isPerfectScore = scoreResult.score === 100;
16295
16386
  const renderedFaceLines = buildFaceRenderedLines(scoreResult.score);
16296
16387
  const rawFaceLines = buildRawFaceLines(scoreResult.score);
16297
- const shouldAnimate = !isSpinnerSilent() && isSpinnerInteractive(process.stdout);
16388
+ const shouldAnimate = !isSpinnerSilent() && canAnimateOnboarding(process.stdout);
16298
16389
  const displayScore = shouldAnimate ? 0 : scoreResult.score;
16299
16390
  const rightColumnLines = [
16300
16391
  buildScoreLine(displayScore, scoreResult.score, scoreResult.label),
@@ -16320,9 +16411,19 @@ const printScoreHeader = (scoreResult, potentialScore) => Effect.gen(function* (
16320
16411
  }));
16321
16412
  yield* Console.log("");
16322
16413
  if (shouldAnimate) {
16323
- yield* writeScoreHeaderLine("\x1B[5A");
16414
+ yield* writeStdout("\x1B[5A");
16324
16415
  yield* printAnimatedScore(renderedFaceLines[0], renderedFaceLines[1], scoreResult.score, scoreResult.label, potentialScore);
16325
- yield* writeScoreHeaderLine("\x1B[3B");
16416
+ yield* writeStdout("\x1B[3B");
16417
+ }
16418
+ });
16419
+ const animateScoreProjection = (scoreResult, potentialScore, linesBelowBar) => Effect.gen(function* () {
16420
+ if (scoreResult.score === 100 || potentialScore <= scoreResult.score) return;
16421
+ const barFaceLine = buildFaceRenderedLines(scoreResult.score)[1] ?? "";
16422
+ for (let frame = 1; frame <= 16; frame += 1) {
16423
+ const progress = easeOutCubic(frame / 16);
16424
+ const displayedPotential = scoreResult.score + (potentialScore - scoreResult.score) * progress;
16425
+ yield* writeStdout(`\x1b[${linesBelowBar}A\r${buildScoreHeaderLine(barFaceLine, buildProjectedScoreBar(scoreResult.score, displayedPotential))}\x1b[${linesBelowBar}B\r`);
16426
+ if (frame < 16) yield* Effect.sleep(35);
16326
16427
  }
16327
16428
  });
16328
16429
  const printBrandingOnlyHeader = Effect.gen(function* () {
@@ -16375,10 +16476,12 @@ const printFooter = (input) => Effect.gen(function* () {
16375
16476
  });
16376
16477
  const printSummary = (input) => Effect.gen(function* () {
16377
16478
  if (input.scoreResult) {
16378
- yield* printScoreHeader(input.scoreResult, input.potentialScore ?? void 0);
16479
+ const animateProjection = Boolean(input.animateProjection) && input.potentialScore != null && !input.verbose;
16480
+ yield* printScoreHeader(input.scoreResult, animateProjection ? void 0 : input.potentialScore ?? void 0);
16379
16481
  if (input.potentialScore != null) {
16380
16482
  const improvement = input.potentialScore - input.scoreResult.score;
16381
16483
  yield* Console.log(highlighter.gray(" You could improve ") + colorizeByScore(`+${improvement}%`, input.potentialScore) + highlighter.gray(` by fixing the top 3 issues`));
16484
+ if (animateProjection) yield* animateScoreProjection(input.scoreResult, input.potentialScore, 5);
16382
16485
  }
16383
16486
  } else yield* printNoScoreHeader(input.noScoreMessage);
16384
16487
  const diagnosticsDirectory = yield* Effect.try({
@@ -16646,9 +16749,12 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16646
16749
  else runConsole(Console.error(highlighter.error(lintFailureReason)));
16647
16750
  const inspectDiagnostics = output.diagnostics;
16648
16751
  const score = didLintFail ? null : output.score;
16752
+ const elapsedMilliseconds = performance.now() - startTime;
16753
+ const forceOnboarding = isOnboardingForced();
16754
+ const paceOnboardingSections = !options.silent && !options.scoreOnly && !options.suppressRendering && !options.verbose && canAnimateOnboarding(process.stdout) && (forceOnboarding || !hasCompletedOnboarding());
16649
16755
  const finalizeInput = {
16650
16756
  options,
16651
- elapsedMilliseconds: performance.now() - startTime,
16757
+ elapsedMilliseconds,
16652
16758
  diagnostics: inspectDiagnostics,
16653
16759
  score,
16654
16760
  project: output.project,
@@ -16664,6 +16770,12 @@ const runInspectWithRuntime = async (directory, options, userConfig, hasConfigOv
16664
16770
  scanElapsedMilliseconds: output.scanElapsedMilliseconds
16665
16771
  };
16666
16772
  const result = await Effect.runPromise(finalizeAndRender(finalizeInput).pipe(options.silent ? Effect.provideService(Console.Console, silentConsole) : (program) => program));
16773
+ if (shouldRecordOnboarding({
16774
+ paceOnboardingSections,
16775
+ forceOnboarding,
16776
+ verbose: options.verbose,
16777
+ isNonInteractiveEnvironment: options.isNonInteractiveEnvironment
16778
+ })) markOnboardingComplete();
16667
16779
  recordScanMetrics({
16668
16780
  result,
16669
16781
  mode: isDiffMode ? "diff" : "full",
@@ -16707,16 +16819,20 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16707
16819
  else yield* Console.log(highlighter.gray(noScoreMessage));
16708
16820
  return buildResult();
16709
16821
  }
16822
+ const animateRender = !options.silent && !options.verbose && canAnimateOnboarding(process.stdout);
16823
+ const pause = onboardingSectionPause(animateRender);
16710
16824
  const surfaceDiagnostics = filterDiagnosticsForSurface([...diagnostics], options.outputSurface, userConfig);
16711
16825
  const demotedDiagnosticCount = diagnostics.length - surfaceDiagnostics.length;
16712
16826
  const lintSourceFileCount = options.includePaths.length > 0 ? options.includePaths.length : project.sourceFileCount;
16713
16827
  if (surfaceDiagnostics.length === 0) {
16828
+ yield* pause;
16714
16829
  if (hasSkippedChecks) {
16715
16830
  const skippedLabel = skippedChecks.join(" and ");
16716
16831
  yield* Console.warn(highlighter.warn(`No issues detected, but ${skippedLabel} checks failed — results are incomplete.`));
16717
16832
  } else if (demotedDiagnosticCount > 0) yield* Console.log(highlighter.success(`No issues found! (${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface — see config.surfaces.)`));
16718
16833
  else yield* Console.log(highlighter.success("No issues found!"));
16719
16834
  yield* Console.log("");
16835
+ yield* pause;
16720
16836
  if (hasSkippedChecks) {
16721
16837
  yield* printBrandingOnlyHeader;
16722
16838
  yield* Console.log(highlighter.gray(" Score not shown — some checks could not complete."));
@@ -16724,8 +16840,12 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16724
16840
  else yield* printNoScoreHeader(noScoreMessage);
16725
16841
  return buildResult();
16726
16842
  }
16843
+ yield* pause;
16727
16844
  yield* Console.log("");
16728
- yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment());
16845
+ yield* printDiagnostics([...surfaceDiagnostics], options.verbose, directory, buildRulePriorityMap([score]), isCodingAgentEnvironment(), {
16846
+ sectionPause: pause,
16847
+ animateCountUp: animateRender
16848
+ });
16729
16849
  if (options.isNonInteractiveEnvironment && options.outputSurface !== "prComment") yield* printAgentGuidance();
16730
16850
  if (demotedDiagnosticCount > 0) {
16731
16851
  yield* Console.log(highlighter.gray(` ${demotedDiagnosticCount} demoted from the ${options.outputSurface} surface (e.g. design cleanup) — run \`npx react-doctor@latest .\` locally for the full list.`));
@@ -16733,6 +16853,7 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16733
16853
  }
16734
16854
  const potentialScore = score ? yield* Effect.promise(() => computeProjectedScore([...surfaceDiagnostics], [...surfaceDiagnostics], score)) : null;
16735
16855
  const shouldShowShareLink = !options.noScore && options.share && !options.isCi;
16856
+ yield* pause;
16736
16857
  yield* printSummary({
16737
16858
  diagnostics: [...surfaceDiagnostics],
16738
16859
  elapsedMilliseconds,
@@ -16740,13 +16861,15 @@ const finalizeAndRender = (input) => Effect.gen(function* () {
16740
16861
  potentialScore,
16741
16862
  totalSourceFileCount: lintSourceFileCount,
16742
16863
  noScoreMessage,
16743
- verbose: options.verbose
16864
+ verbose: options.verbose,
16865
+ animateProjection: animateRender
16744
16866
  });
16745
16867
  if (hasSkippedChecks) {
16746
16868
  const skippedLabel = skippedChecks.join(" and ");
16747
16869
  yield* Console.log("");
16748
16870
  yield* Console.warn(highlighter.warn(` Note: ${skippedLabel} checks failed — score may be incomplete.`));
16749
16871
  }
16872
+ yield* pause;
16750
16873
  yield* printFooter({
16751
16874
  diagnostics: [...surfaceDiagnostics],
16752
16875
  scoreResult: score,
@@ -16879,6 +17002,49 @@ const handleUserError = (error, options = {}) => {
16879
17002
  process.exitCode = 1;
16880
17003
  };
16881
17004
  //#endregion
17005
+ //#region src/cli/utils/cli-input-error.ts
17006
+ /**
17007
+ * A mistake in *how the CLI was invoked* — a malformed `<file>:<line>`
17008
+ * argument, mutually exclusive flags, or an unknown `--project` name. This is
17009
+ * user input, not a react-doctor bug, so `isExpectedUserError` routes it
17010
+ * through `handleUserError`: a clean, single-line message with no Sentry
17011
+ * report and no "Something went wrong, open a prefilled issue" block.
17012
+ *
17013
+ * The `message` is rendered verbatim, so it must read as a complete,
17014
+ * human-readable sentence that tells the user how to fix their invocation.
17015
+ */
17016
+ var CliInputError = class extends Error {
17017
+ name = "CliInputError";
17018
+ };
17019
+ //#endregion
17020
+ //#region src/cli/utils/is-expected-user-error.ts
17021
+ /**
17022
+ * Whether `error` is an expected, user-actionable failure — the user's project
17023
+ * or input, not a react-doctor bug. Such failures must be kept out of crash
17024
+ * reporting (Sentry + the alertable error-rate metric) and rendered via
17025
+ * `handleUserError` (a plain message — no "Something went wrong", prefilled
17026
+ * issue, Discord link, or Sentry reference), since there is no bug to report.
17027
+ *
17028
+ * Three distinct shapes reach the CLI's catch blocks:
17029
+ *
17030
+ * - **Project-discovery failures** (`NoReactDependencyError`,
17031
+ * `ProjectNotFoundError`, `PackageJsonNotFoundError`, `NotADirectoryError`,
17032
+ * `AmbiguousProjectError`) arrive as their plain legacy classes (so
17033
+ * `isReactDoctorError` is `false` for them) — narrow with
17034
+ * `isProjectDiscoveryError`. Running react-doctor against a directory that
17035
+ * has no React, or a path that doesn't exist, is the canonical example.
17036
+ * - **CLI invocation mistakes** (`CliInputError`): a malformed
17037
+ * `<file>:<line>` argument, mutually exclusive flags, or an unknown
17038
+ * `--project` name.
17039
+ * - **Bad `--diff` input** (`GitBaseBranchInvalid` / `GitBaseBranchMissing`)
17040
+ * stays the tagged `ReactDoctorError`, so dispatch on the reason `_tag`.
17041
+ *
17042
+ * This composes the existing core narrowers rather than introducing a new
17043
+ * error-shape helper (AGENTS.md): it encodes CLI-layer reporting policy, not
17044
+ * knowledge of the `ReactDoctorError` shape.
17045
+ */
17046
+ const isExpectedUserError = (error) => error instanceof CliInputError || isProjectDiscoveryError(error) || isReactDoctorError(error) && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
17047
+ //#endregion
16882
17048
  //#region src/cli/utils/build-handoff-payload.ts
16883
17049
  const buildHandoffPayload = (input) => {
16884
17050
  const topGroups = buildSortedRuleGroups(input.diagnostics).slice(0, 3);
@@ -18189,7 +18355,6 @@ const copyToClipboard = (text) => {
18189
18355
  //#endregion
18190
18356
  //#region src/cli/utils/handoff-to-agent.ts
18191
18357
  const CLIPBOARD_CHOICE = "clipboard";
18192
- const PRINT_CHOICE = "print";
18193
18358
  const SKIP_CHOICE = "skip";
18194
18359
  const printPayload = (payload) => {
18195
18360
  cliLogger.break();
@@ -18207,7 +18372,7 @@ const handoffToAgent = async (input) => {
18207
18372
  const { handoffTarget } = await prompts({
18208
18373
  type: "select",
18209
18374
  name: "handoffTarget",
18210
- message: "Hand these issues to an agent?",
18375
+ message: "Would you like to spawn an agent to fix these issues?",
18211
18376
  choices: [
18212
18377
  ...(await detectLaunchableAgents()).map((agentId) => ({
18213
18378
  title: getSkillAgentConfig(agentId).displayName,
@@ -18219,11 +18384,6 @@ const handoffToAgent = async (input) => {
18219
18384
  description: "Paste into any agent or chat",
18220
18385
  value: CLIPBOARD_CHOICE
18221
18386
  },
18222
- {
18223
- title: "Print prompt",
18224
- description: "Show the prompt below",
18225
- value: PRINT_CHOICE
18226
- },
18227
18387
  {
18228
18388
  title: "Skip",
18229
18389
  description: "Don't hand off",
@@ -18235,7 +18395,6 @@ const handoffToAgent = async (input) => {
18235
18395
  let handoffOutcome = "launch";
18236
18396
  if (handoffTarget === void 0) handoffOutcome = "cancel";
18237
18397
  else if (handoffTarget === SKIP_CHOICE) handoffOutcome = "skip";
18238
- else if (handoffTarget === PRINT_CHOICE) handoffOutcome = "print";
18239
18398
  else if (handoffTarget === CLIPBOARD_CHOICE) handoffOutcome = "clipboard";
18240
18399
  recordCount(METRIC.agentHandoff, 1, {
18241
18400
  outcome: handoffOutcome,
@@ -18247,10 +18406,6 @@ const handoffToAgent = async (input) => {
18247
18406
  diagnostics: input.diagnostics,
18248
18407
  projectName: input.projectName
18249
18408
  });
18250
- if (handoffTarget === PRINT_CHOICE) {
18251
- printPayload(payload);
18252
- return;
18253
- }
18254
18409
  if (handoffTarget === CLIPBOARD_CHOICE) {
18255
18410
  if (await copyToClipboard(payload)) cliLogger.log("Copied the prompt to your clipboard.");
18256
18411
  else printPayload(payload);
@@ -18367,6 +18522,35 @@ const printBrandedHeader = Effect.gen(function* () {
18367
18522
  yield* Console.log("");
18368
18523
  });
18369
18524
  //#endregion
18525
+ //#region src/cli/utils/render-welcome.ts
18526
+ const HAPPY_FACE_LINES = [
18527
+ "┌─────┐",
18528
+ "│ ◠ ◠ │",
18529
+ "│ ▽ │",
18530
+ "└─────┘"
18531
+ ];
18532
+ const typeLine = (linePrefix, text, style) => Effect.gen(function* () {
18533
+ const characters = [...text];
18534
+ for (let length = 1; length <= characters.length; length += 1) {
18535
+ yield* writeStdout(`\r${linePrefix}${style(characters.slice(0, length).join(""))}\x1b[K`);
18536
+ yield* Effect.sleep(32);
18537
+ }
18538
+ });
18539
+ const playWelcomeScene = () => Effect.gen(function* () {
18540
+ const face = HAPPY_FACE_LINES.map((line) => highlighter.success(line));
18541
+ const mouthPrefix = ` ${face[2] ?? ""} `;
18542
+ yield* writeStdout(`\n${face.map((line) => ` ${line}`).join("\n")}\n`);
18543
+ yield* writeStdout("\x1B[3A");
18544
+ yield* typeLine(` ${face[1] ?? ""} `, "Welcome to React Doctor", (fragment) => highlighter.bold(fragment));
18545
+ yield* Effect.sleep(500);
18546
+ yield* writeStdout("\x1B[1B");
18547
+ yield* typeLine(mouthPrefix, "I diagnose your React code for bugs, security & performance.", (fragment) => highlighter.dim(fragment));
18548
+ yield* Effect.sleep(WELCOME_EXPLANATION_HOLD_MS);
18549
+ yield* typeLine(mouthPrefix, "Let's scan your codebase...", (fragment) => highlighter.dim(fragment));
18550
+ yield* Effect.sleep(WELCOME_HOLD_MS);
18551
+ yield* writeStdout("\x1B[3A\r\x1B[0J");
18552
+ });
18553
+ //#endregion
18370
18554
  //#region src/cli/utils/report-error.ts
18371
18555
  /**
18372
18556
  * Sends an error to Sentry — enriched with a fresh snapshot of the current run
@@ -18385,6 +18569,7 @@ const printBrandedHeader = Effect.gen(function* () {
18385
18569
  */
18386
18570
  const reportErrorToSentry = async (error) => {
18387
18571
  if (!Sentry.isInitialized()) return void 0;
18572
+ if (isExpectedUserError(error)) return void 0;
18388
18573
  try {
18389
18574
  const { tags, contexts } = buildSentryScope();
18390
18575
  let reason = "unknown";
@@ -18464,6 +18649,7 @@ const findLowestScoredScan = (completedScans) => {
18464
18649
  };
18465
18650
  const printMultiProjectSummary = (input) => Effect.gen(function* () {
18466
18651
  const { completedScans, userConfig, verbose, isOffline, projectName } = input;
18652
+ const animateRender = !verbose && canAnimateOnboarding(process.stdout);
18467
18653
  const surfaceDiagnostics = filterDiagnosticsForSurface(completedScans.flatMap((scan) => scan.result.diagnostics), "cli", userConfig);
18468
18654
  const projectRootByDiagnostic = /* @__PURE__ */ new WeakMap();
18469
18655
  for (const scan of completedScans) for (const diagnostic of scan.result.diagnostics) projectRootByDiagnostic.set(diagnostic, scan.result.project.rootDirectory);
@@ -18480,7 +18666,7 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
18480
18666
  yield* Console.log(`${highlighter.success("✔")} Scanned ${totalScannedFileCount} ${totalScannedFileCount === 1 ? "file" : "files"} in ${formatElapsedTime(totalScanElapsedMilliseconds)}`);
18481
18667
  if (surfaceDiagnostics.length > 0) {
18482
18668
  yield* Console.log("");
18483
- yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment());
18669
+ yield* printDiagnostics(surfaceDiagnostics, verbose, resolveDiagnosticSourceRoot, buildRulePriorityMap(completedScans.map((scan) => scan.result.score)), isCodingAgentEnvironment(), { animateCountUp: animateRender });
18484
18670
  }
18485
18671
  const lowestScoredScan = findLowestScoredScan(completedScans);
18486
18672
  const aggregateScore = lowestScoredScan?.result.score ?? null;
@@ -18492,7 +18678,8 @@ const printMultiProjectSummary = (input) => Effect.gen(function* () {
18492
18678
  potentialScore: lowestScoredScan ? yield* Effect.promise(() => computeProjectedScore(surfaceDiagnostics, lowestScoredScan.result.diagnostics, lowestScoredScan.result.score)) : null,
18493
18679
  totalSourceFileCount,
18494
18680
  noScoreMessage: "Score unavailable.",
18495
- verbose
18681
+ verbose,
18682
+ animateProjection: animateRender
18496
18683
  });
18497
18684
  const entries = completedScans.map((scan) => {
18498
18685
  const errorCount = scan.result.diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
@@ -18522,7 +18709,11 @@ const getSetupPromptStore = (options = {}) => new Conf({
18522
18709
  });
18523
18710
  const getSetupPromptProjectKey = (projectRoot) => createHash("sha256").update(path.resolve(projectRoot)).digest("hex");
18524
18711
  const hasDisabledSetupPrompt = (projectRoot, storeOptions = {}) => {
18525
- return getSetupPromptStore(storeOptions).get("projects", {})[getSetupPromptProjectKey(projectRoot)]?.setupPrompt === false;
18712
+ try {
18713
+ return getSetupPromptStore(storeOptions).get("projects", {})[getSetupPromptProjectKey(projectRoot)]?.setupPrompt === false;
18714
+ } catch {
18715
+ return false;
18716
+ }
18526
18717
  };
18527
18718
  const resolveInstallSetupProjectRoot = (options) => {
18528
18719
  if (options.scanDirectories.length === 0) return findNearestPackageDirectory(options.scanRoot) ?? options.scanRoot;
@@ -18740,12 +18931,12 @@ const findOwningProjectDirectory = (rootDirectory, filePath) => {
18740
18931
  //#region src/cli/utils/parse-file-line-argument.ts
18741
18932
  const parseFileLineArgument = (rawArgument) => {
18742
18933
  const lastColonIndex = rawArgument.lastIndexOf(":");
18743
- if (lastColonIndex < 0) throw new Error(`Expected "<file>:<line>" (e.g. "src/foo.tsx:42"), got "${rawArgument}".`);
18934
+ if (lastColonIndex < 0) throw new CliInputError(`Expected "<file>:<line>" (e.g. "src/foo.tsx:42"), got "${rawArgument}".`);
18744
18935
  const filePath = rawArgument.slice(0, lastColonIndex);
18745
18936
  const lineText = rawArgument.slice(lastColonIndex + 1);
18746
- if (filePath.length === 0) throw new Error(`Missing file path in "${rawArgument}".`);
18937
+ if (filePath.length === 0) throw new CliInputError(`Missing file path in "${rawArgument}".`);
18747
18938
  const line = Number.parseInt(lineText, 10);
18748
- if (!Number.isFinite(line) || line <= 0 || String(line) !== lineText.trim()) throw new Error(`Expected a positive line number in "${rawArgument}".`);
18939
+ if (!Number.isFinite(line) || line <= 0 || String(line) !== lineText.trim()) throw new CliInputError(`Expected a positive line number in "${rawArgument}".`);
18749
18940
  return {
18750
18941
  filePath,
18751
18942
  line
@@ -18774,10 +18965,7 @@ const resolveProjectFlag = (projectFlag, workspacePackages) => {
18774
18965
  const resolvedDirectories = [];
18775
18966
  for (const requestedName of requestedNames) {
18776
18967
  const matched = workspacePackages.find((workspacePackage) => workspacePackage.name === requestedName || path.basename(workspacePackage.directory) === requestedName);
18777
- if (!matched) {
18778
- const availableNames = workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ");
18779
- throw new Error(`Project "${requestedName}" not found. Available: ${availableNames}`);
18780
- }
18968
+ if (!matched) throw new CliInputError(`Project "${requestedName}" not found. Available: ${workspacePackages.map((workspacePackage) => workspacePackage.name).join(", ")}`);
18781
18969
  resolvedDirectories.push(matched.directory);
18782
18970
  }
18783
18971
  return resolvedDirectories;
@@ -18828,7 +19016,7 @@ const runExplain = async (fileLineArgument, context) => {
18828
19016
  }
18829
19017
  for (const diagnostic of matchingDiagnostics) {
18830
19018
  const ruleIdentifier = `${diagnostic.plugin}/${diagnostic.rule}`;
18831
- const severitySymbol = diagnostic.severity === "error" ? "✗" : "⚠";
19019
+ const severitySymbol = diagnostic.severity === "error" ? "✖" : "⚠";
18832
19020
  const colorizedRule = colorizeRuleByDiagnostic(ruleIdentifier, diagnostic.severity);
18833
19021
  const severityLabel = colorizeRuleByDiagnostic(diagnostic.severity, diagnostic.severity);
18834
19022
  cliLogger.log(`${severitySymbol} ${colorizedRule} ${highlighter.dim(`(${severityLabel})`)} — ${diagnostic.message}`);
@@ -18857,14 +19045,14 @@ const shouldFailForDiagnostics = (diagnostics, failOnLevel) => {
18857
19045
  const validateModeFlags = (flags) => {
18858
19046
  const coercedDiff = coerceDiffValue(flags.diff);
18859
19047
  const exclusiveModes = [flags.staged ? "--staged" : null, coercedDiff !== void 0 && coercedDiff !== false ? "--diff" : null].filter((modeName) => modeName !== null);
18860
- if (exclusiveModes.length > 1) throw new Error(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
18861
- if (flags.yes && flags.full) throw new Error("Cannot combine --yes and --full; pick one.");
18862
- if (flags.score && flags.json) throw new Error("Cannot combine --score and --json; pick one output mode.");
18863
- if (flags.score && flags.telemetry === false) throw new Error("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
18864
- if (flags.prComment && (flags.json || flags.score)) throw new Error("--pr-comment cannot be combined with --json or --score.");
18865
- if (flags.annotations && flags.score) throw new Error("--annotations cannot be combined with --score.");
18866
- if (flags.explain !== void 0 && flags.why !== void 0) throw new Error("Use --explain or --why, not both — they're aliases of the same flag.");
18867
- if ((flags.explain ?? flags.why) !== void 0 && (flags.json || flags.score || flags.annotations || flags.staged)) throw new Error("--explain cannot be combined with --json, --score, --annotations, or --staged.");
19048
+ if (exclusiveModes.length > 1) throw new CliInputError(`Cannot combine ${exclusiveModes.join(" and ")}; pick one mode.`);
19049
+ if (flags.yes && flags.full) throw new CliInputError("Cannot combine --yes and --full; pick one.");
19050
+ if (flags.score && flags.json) throw new CliInputError("Cannot combine --score and --json; pick one output mode.");
19051
+ if (flags.score && flags.telemetry === false) throw new CliInputError("Cannot combine --score with --no-telemetry; --score prints the score that --no-telemetry disables.");
19052
+ if (flags.prComment && (flags.json || flags.score)) throw new CliInputError("--pr-comment cannot be combined with --json or --score.");
19053
+ if (flags.annotations && flags.score) throw new CliInputError("--annotations cannot be combined with --score.");
19054
+ if (flags.explain !== void 0 && flags.why !== void 0) throw new CliInputError("Use --explain or --why, not both — they're aliases of the same flag.");
19055
+ if ((flags.explain ?? flags.why) !== void 0 && (flags.json || flags.score || flags.annotations || flags.staged)) throw new CliInputError("--explain cannot be combined with --json, --score, --annotations, or --staged.");
18868
19056
  };
18869
19057
  //#endregion
18870
19058
  //#region src/cli/commands/inspect.ts
@@ -18947,7 +19135,8 @@ const inspectAction = async (directory, flags) => {
18947
19135
  });
18948
19136
  return;
18949
19137
  }
18950
- if (!isQuiet) Effect.runSync(printBrandedHeader);
19138
+ if (!isQuiet) if ((isOnboardingForced() || !hasCompletedOnboarding()) && canAnimateOnboarding(process.stdout)) await Effect.runPromise(playWelcomeScene());
19139
+ else Effect.runSync(printBrandedHeader);
18951
19140
  const scanOptions = resolveCliInspectOptions(flags, userConfig);
18952
19141
  const skipPrompts = shouldSkipPrompts({
18953
19142
  yes: flags.yes,
@@ -19111,7 +19300,7 @@ const inspectAction = async (directory, flags) => {
19111
19300
  }
19112
19301
  }
19113
19302
  } catch (error) {
19114
- const isUserError = isReactDoctorError(error) && (error.reason._tag === "GitBaseBranchInvalid" || error.reason._tag === "GitBaseBranchMissing");
19303
+ const isUserError = isExpectedUserError(error);
19115
19304
  const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
19116
19305
  if (isJsonMode) {
19117
19306
  writeJsonErrorReport(error);
@@ -20005,15 +20194,20 @@ if (process.argv.includes("-V") && !strippedArgv.includes("-V")) {
20005
20194
  applyColorPreference(strippedArgv);
20006
20195
  const argv = normalizeHelpInvocation(strippedArgv, knownCommands);
20007
20196
  program.parseAsync(argv).then(() => flushSentry()).catch(async (error) => {
20008
- const sentryEventId = await reportErrorToSentry(error);
20197
+ const isUserError = isExpectedUserError(error);
20198
+ const sentryEventId = isUserError ? void 0 : await reportErrorToSentry(error);
20009
20199
  if (isJsonModeActive()) {
20010
20200
  writeJsonErrorReport(error);
20011
20201
  process.exit(1);
20012
20202
  }
20203
+ if (isUserError) {
20204
+ handleUserError(error);
20205
+ return;
20206
+ }
20013
20207
  handleError(error, { sentryEventId });
20014
20208
  });
20015
20209
  //#endregion
20016
20210
  export {};
20017
20211
 
20018
20212
  //# sourceMappingURL=cli.js.map
20019
- //# debugId=7cd8f7c3-d243-5c1a-9ebb-98a50f4157a1
20213
+ //# debugId=07713237-df07-5858-b7a4-7b12c0e7b293
package/dist/index.d.ts CHANGED
@@ -610,10 +610,25 @@ interface JsonReport {
610
610
  * If you're inside the Effect runtime, use the tagged
611
611
  * `ReactDoctorError` from `../errors.js` instead.
612
612
  */
613
+ /**
614
+ * Distinguishes the two situations that both surface as "no project here", so
615
+ * the rendered message matches reality:
616
+ *
617
+ * - `no-project` (default): the path exists but has no React project — no
618
+ * `package.json` at the root and no discoverable nested React subproject.
619
+ * - `missing-path`: the resolved scan target does not exist on disk at all
620
+ * (a typo, a stale temp path, a monorepo subdir that isn't present). The
621
+ * generic "expected a package.json" guidance is misleading here, so point
622
+ * at the missing path instead.
623
+ */
624
+ interface ProjectNotFoundOptions extends ErrorOptions {
625
+ readonly kind?: "no-project" | "missing-path";
626
+ }
613
627
  declare class ProjectNotFoundError extends Error {
614
628
  readonly name = "ProjectNotFoundError";
615
629
  readonly directory: string;
616
- constructor(directory: string, options?: ErrorOptions);
630
+ readonly kind: "no-project" | "missing-path";
631
+ constructor(directory: string, options?: ProjectNotFoundOptions);
617
632
  }
618
633
  declare class NoReactDependencyError extends Error {
619
634
  readonly name = "NoReactDependencyError";
package/dist/index.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]="a56b86f0-1c28-52ae-9677-12f5e67df34f")}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]="9b91fa51-6642-5351-a848-af91945dec6f")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as fs$1 from "node:fs";
@@ -2027,33 +2027,15 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
2027
2027
  value: mod,
2028
2028
  enumerable: true
2029
2029
  }) : target, mod));
2030
- /**
2031
- * Narrow errors raised by the project-discovery helpers
2032
- * (`discoverProject` / `resolveDiagnoseTarget` / `readPackageJson`).
2033
- *
2034
- * These extend `Error` directly — they are NOT the tagged
2035
- * `ReactDoctorError` from `../errors.js` (that one wraps every
2036
- * runtime-pipeline failure as a `Schema.TaggedErrorClass` for
2037
- * `Effect.catchReasons` dispatch). The split is intentional:
2038
- *
2039
- * - Discovery happens BEFORE the Effect runtime takes over — at the
2040
- * `diagnose()` / CLI entry point — and throws plain JS exceptions
2041
- * so callers can `try/catch` without an Effect-layer-aware
2042
- * `instanceof` check.
2043
- * - The Project service (`services/project.ts → translateProjectInfoError`)
2044
- * translates each of these into the equivalent tagged-error
2045
- * `reason` before re-raising inside the Effect pipeline, so the
2046
- * runtime never sees a non-tagged failure.
2047
- *
2048
- * If you're inside the Effect runtime, use the tagged
2049
- * `ReactDoctorError` from `../errors.js` instead.
2050
- */
2051
2030
  var ProjectNotFoundError = class extends Error {
2052
2031
  name = "ProjectNotFoundError";
2053
2032
  directory;
2033
+ kind;
2054
2034
  constructor(directory, options) {
2055
- super(`No React project found in ${directory}. Expected a package.json at the directory root or a nested package.json with a React dependency.`, options);
2035
+ const kind = options?.kind ?? "no-project";
2036
+ super(kind === "missing-path" ? `Scan target "${directory}" does not exist. Check the path and try again.` : `No React project found in ${directory}. Expected a package.json at the directory root or a nested package.json with a React dependency.`, options);
2056
2037
  this.directory = directory;
2038
+ this.kind = kind;
2057
2039
  }
2058
2040
  };
2059
2041
  var NoReactDependencyError = class extends Error {
@@ -4651,7 +4633,7 @@ const resolveScanTarget = async (requestedDirectory, options = {}) => {
4651
4633
  const redirectedDirectory = resolveConfigRootDir(userConfig, configSourceDirectory);
4652
4634
  const directoryAfterRedirect = redirectedDirectory ?? absoluteRequested;
4653
4635
  const resolvedDirectory = resolveDiagnoseTarget(directoryAfterRedirect, options) ?? directoryAfterRedirect;
4654
- if (!isDirectory(resolvedDirectory)) throw existsSync(resolvedDirectory) ? new NotADirectoryError(resolvedDirectory) : new ProjectNotFoundError(resolvedDirectory);
4636
+ if (!isDirectory(resolvedDirectory)) throw existsSync(resolvedDirectory) ? new NotADirectoryError(resolvedDirectory) : new ProjectNotFoundError(resolvedDirectory, { kind: "missing-path" });
4655
4637
  return {
4656
4638
  resolvedDirectory,
4657
4639
  requestedDirectory: absoluteRequested,
@@ -6137,7 +6119,7 @@ var Git = class Git extends Context.Service()("react-doctor/Git") {
6137
6119
  if (result.status !== 0) return null;
6138
6120
  const branch = trimOrNull(result.stdout);
6139
6121
  return branch === "HEAD" ? null : branch;
6140
- }));
6122
+ }), Effect.orElseSucceed(() => null));
6141
6123
  const defaultBranch = (directory) => Effect.gen(function* () {
6142
6124
  const symref = yield* runGit(directory, ["symbolic-ref", "refs/remotes/origin/HEAD"]);
6143
6125
  if (symref.status === 0) {
@@ -8742,4 +8724,4 @@ const toJsonReport = (result, options) => buildJsonReport({
8742
8724
  export { AmbiguousProjectError, NoReactDependencyError, NotADirectoryError, PackageJsonNotFoundError, ProjectNotFoundError, ReactDoctorError, buildJsonReport, buildJsonReportError, clearCaches, diagnose, filterSourceFiles, getDiffInfo, isProjectDiscoveryError, isReactDoctorError, summarizeDiagnostics, toJsonReport };
8743
8725
 
8744
8726
  //# sourceMappingURL=index.js.map
8745
- //# debugId=a56b86f0-1c28-52ae-9677-12f5e67df34f
8727
+ //# debugId=9b91fa51-6642-5351-a848-af91945dec6f
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-doctor",
3
- "version": "0.2.16",
3
+ "version": "0.2.17-dev.0c8b797",
4
4
  "description": "Diagnose and fix React codebases for security, performance, correctness, accessibility, bundle-size, and architecture issues",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -63,7 +63,7 @@
63
63
  "oxlint": "^1.66.0",
64
64
  "prompts": "^2.4.2",
65
65
  "typescript": ">=5.0.4 <7",
66
- "oxlint-plugin-react-doctor": "0.2.16"
66
+ "oxlint-plugin-react-doctor": "0.2.17-dev.0c8b797"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/babel__code-frame": "^7.27.0",
@@ -71,8 +71,8 @@
71
71
  "@xterm/headless": "^6.0.0",
72
72
  "commander": "^14.0.3",
73
73
  "ora": "^9.4.0",
74
- "@react-doctor/api": "0.2.16",
75
- "@react-doctor/core": "0.2.16"
74
+ "@react-doctor/api": "0.2.17",
75
+ "@react-doctor/core": "0.2.17"
76
76
  },
77
77
  "engines": {
78
78
  "node": "^20.19.0 || >=22.12.0"