Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): consistent exit codes across all error paths (#2520)

Joey8d4c28bee2d9
diff --git a/.changeset/cli-exit-code-policy.md b/.changeset/cli-exit-code-policy.md
new file mode 100644
index 0000000000..a66b28b9b7
--- /dev/null
+++ b/.changeset/cli-exit-code-policy.md
@@ -0,0 +1,9 @@
+---
+'@xds/cli': patch
+---
+
+**CLI exit-code policy**: every user-visible error now exits with code 1 in both human and `--json` modes. Previously several command-layer errors printed a message but exited 0 — invisible to CI scripts and AI agents that gate on the exit code.
+
+Affected paths now exit 1: `xds bogus-cmd`, `xds theme bogus-subcommand`, the bare `theme` parent group when given an unknown subcommand, and any "command not found"/"did you mean…" suggestion path. `--json` and non-`--json` invocations of the same error case now agree on the exit code.
+
+Help, version, and bare-list invocations still exit 0. Introduces `lib/cli-error.mjs` as the single helper for emitting CLI errors — its doc-block is the canonical exit-code policy.
diff --git a/packages/cli/src/cli-exit-codes.test.mjs b/packages/cli/src/cli-exit-codes.test.mjs
new file mode 100644
index 0000000000..595056b969
--- /dev/null
+++ b/packages/cli/src/cli-exit-codes.test.mjs
@@ -0,0 +1,177 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file End-to-end exit-code policy tests.
+ *
+ * Spawns the CLI as a subprocess and asserts the exit code (and JSON
+ * envelope shape, where applicable) for every error path the policy
+ * covers. This is the test that catches CI-script-breaking regressions:
+ * if a future change accidentally restores `exit 0` on a user-visible
+ * error, this file fires.
+ *
+ * Policy under test (see lib/cli-error.mjs for full doc-block):
+ * - Any user-visible error → exit 1 (both modes).
+ * - Help/version/empty → exit 0.
+ * - --json and non-JSON exit with the same code for the same case.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI = path.resolve(__dirname, '..', 'bin', 'xds.mjs');
+
+function runCli(args) {
+ return spawnSync(process.execPath, [CLI, ...args], {
+ encoding: 'utf8',
+ timeout: 20_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
+ });
+}
+
+/** Shorthand for asserting the exit code. */
+function expectExit(args, code) {
+ const r = runCli(args);
+ expect(
+ r.status,
+ `xds ${args.join(' ')} should exit ${code}, got ${r.status}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`,
+ ).toBe(code);
+ return r;
+}
+
+/** Parse the stdout of a --json invocation as a JSON envelope. */
+function parseEnvelope(r) {
+ try {
+ return JSON.parse(r.stdout);
+ } catch {
+ throw new Error(`stdout was not JSON:\n${r.stdout}\n--- stderr ---\n${r.stderr}`);
+ }
+}
+
+// ─── Error paths: must exit 1 ────────────────────────────────────────────────
+
+describe('exit codes — error paths (human mode → exit 1)', () => {
+ it('xds bogus-cmd → exit 1', () => {
+ const r = expectExit(['bogus-cmd'], 1);
+ expect(r.stderr).toMatch(/unknown command/i);
+ });
+
+ it('xds theme bogus → exit 1', () => {
+ const r = expectExit(['theme', 'bogus'], 1);
+ expect(r.stderr).toMatch(/unknown subcommand/i);
+ });
+
+ it('xds component bogus → exit 1', () => {
+ const r = expectExit(['component', 'bogus'], 1);
+ expect(r.stderr).toMatch(/no component named/i);
+ });
+
+ it('xds hook bogus → exit 1', () => {
+ const r = expectExit(['hook', 'bogus'], 1);
+ expect(r.stderr).toMatch(/no hook named/i);
+ });
+
+ it('xds docs bogus → exit 1', () => {
+ const r = expectExit(['docs', 'bogus'], 1);
+ expect(r.stderr).toMatch(/unknown topic/i);
+ });
+
+ it('xds --bogus-flag → exit 1', () => {
+ const r = expectExit(['--bogus-flag'], 1);
+ // Commander's unknown-option message goes to stderr.
+ expect(r.stderr).toMatch(/unknown option/i);
+ });
+});
+
+describe('exit codes — error paths (--json → exit 1, valid envelope)', () => {
+ it('xds bogus-cmd --json → exit 1, error envelope', () => {
+ const r = expectExit(['bogus-cmd', '--json'], 1);
+ const env = parseEnvelope(r);
+ expect(env.apiVersion).toBe(1);
+ expect(env.error).toMatch(/unknown command/i);
+ });
+
+ it('xds component bogus --json → exit 1, error envelope', () => {
+ const r = expectExit(['component', 'bogus', '--json'], 1);
+ const env = parseEnvelope(r);
+ expect(env.apiVersion).toBe(1);
+ expect(env.error).toMatch(/no component named/i);
+ });
+
+ it('xds hook bogus --json → exit 1, error envelope', () => {
+ const r = expectExit(['hook', 'bogus', '--json'], 1);
+ const env = parseEnvelope(r);
+ expect(env.apiVersion).toBe(1);
+ expect(env.error).toMatch(/no hook named/i);
+ });
+
+ it('xds docs bogus --json → exit 1, error envelope', () => {
+ const r = expectExit(['docs', 'bogus', '--json'], 1);
+ const env = parseEnvelope(r);
+ expect(env.apiVersion).toBe(1);
+ expect(env.error).toMatch(/unknown topic/i);
+ });
+});
+
+// ─── Success paths: must exit 0 (positive controls) ──────────────────────────
+
+describe('exit codes — success paths (exit 0)', () => {
+ it('xds (no args) → exit 0, prints help', () => {
+ const r = expectExit([], 0);
+ // Help should land on stdout (Commander default for help()).
+ expect(r.stdout + r.stderr).toMatch(/Usage:/);
+ });
+
+ it('xds --help → exit 0', () => {
+ expectExit(['--help'], 0);
+ });
+
+ it('xds --version → exit 0, prints a version', () => {
+ const r = expectExit(['--version'], 0);
+ expect(r.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/);
+ });
+
+ it('xds component (list mode) → exit 0', () => {
+ expectExit(['component'], 0);
+ });
+
+ it('xds component Button → exit 0', () => {
+ expectExit(['component', 'Button'], 0);
+ });
+
+ it('xds docs (list mode) → exit 0', () => {
+ expectExit(['docs'], 0);
+ });
+
+ it('xds theme (no subcommand) → exit 0, shows help', () => {
+ // Bare theme without a subcommand is a help-display case → exit 0.
+ expectExit(['theme'], 0);
+ });
+
+ it('xds hook (list mode) → exit 0', () => {
+ expectExit(['hook'], 0);
+ });
+});
+
+// ─── Mode parity: same case must exit the same in both modes ────────────────
+
+describe('exit codes — JSON / non-JSON parity', () => {
+ const cases = [
+ ['bogus-cmd'],
+ ['component', 'bogus'],
+ ['hook', 'bogus'],
+ ['docs', 'bogus'],
+ ];
+
+ for (const args of cases) {
+ it(`xds ${args.join(' ')} — exit code matches with and without --json`, () => {
+ const human = runCli(args);
+ const jsonRun = runCli([...args, '--json']);
+ expect(jsonRun.status).toBe(human.status);
+ expect(jsonRun.status).toBe(1);
+ });
+ }
+});
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index 345f787547..65fe73456b 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -25,6 +25,7 @@ import {getRunPrefix} from '../utils/package-manager.mjs';
import {discoverComponents} from '../lib/component-discovery.mjs';
import {discoverHooks} from '../lib/hook-discovery.mjs';
import {humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
const AGENTS_MD = 'AGENTS.md';
const CLAUDE_MD = 'CLAUDE.md';
@@ -431,8 +432,7 @@ export function registerAgentDocs(program) {
// Validate --agent
if (options.agent && !VALID_AGENTS.includes(options.agent)) {
- console.error(`Error: Unknown agent "${options.agent}". Valid: ${VALID_AGENTS.join(', ')}`);
- process.exitCode = 1;
+ cliError(`Unknown agent "${options.agent}". Valid: ${VALID_AGENTS.join(', ')}`);
return;
}
@@ -455,8 +455,7 @@ export function registerAgentDocs(program) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- console.error(`Error: ${err.message}`);
- process.exitCode = 1;
+ cliError(err.message);
return;
}
throw err;
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index af3b458a66..e26d3ecb4f 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -19,6 +19,7 @@ import {createJiti} from 'jiti';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {sanitizeName, PathSafetyError} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
// Import shared theme processing from core — ensures build and runtime
// use the same logic for typography.scale expansion, prose, and component rules.
@@ -973,11 +974,19 @@ export function registerTheme(program) {
const theme = program
.command('theme')
.description('Theme tools — build, export, and manage XDS themes')
- .action(() => {
- // Parent group has no default behaviour. When invoked without a
- // subcommand, the preAction hook (in index.mjs) will reject --json
- // because 'theme' (parent) is not on the JSON_SUPPORTED allowlist —
- // only 'theme build' is. For the human path, fall through to help.
+ .action((options, cmd) => {
+ // Parent group has no default behaviour. If the user passed an
+ // unknown subcommand (e.g. `xds theme bogus`), Commander hands it to
+ // us as a positional in cmd.args — exit 1 with a clear error.
+ const extras = (cmd && cmd.args) || [];
+ if (extras.length > 0) {
+ const unknown = String(extras[0]);
+ const known = (theme.commands || []).map((c) => c.name());
+ const suggestions = known.map((name) => ({name, reason: 'available subcommand'}));
+ cliError(`unknown subcommand 'theme ${unknown}'`, {suggestions});
+ return;
+ }
+ // Bare `xds theme` — show the subcommand list. Exit 0 (help is success).
theme.help();
});
@@ -991,9 +1000,8 @@ export function registerTheme(program) {
const json = program.opts().json || false;
if (!fs.existsSync(filePath)) {
- if (json) return jsonError('File not found: ' + filePath);
- console.error(`Error: File not found: ${filePath}`);
- process.exit(1);
+ cliError(`File not found: ${filePath}`);
+ return;
}
if (!json) humanLog(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
@@ -1003,15 +1011,13 @@ export function registerTheme(program) {
try {
themeDef = await extractThemeDefinition(filePath);
} catch (e) {
- if (json) return jsonError(e.message);
- console.error(`Error: ${e.message}`);
- process.exit(1);
+ cliError(e.message);
+ return;
}
if (!themeDef.name) {
- if (json) return jsonError('Theme must have a name property.');
- console.error('Error: Theme must have a name property.');
- process.exit(1);
+ cliError('Theme must have a name property.');
+ return;
}
// Path-safety: the theme name is used to derive output filenames
@@ -1022,9 +1028,8 @@ export function registerTheme(program) {
sanitizeName(themeDef.name, {label: 'theme name'});
} catch (err) {
if (err instanceof PathSafetyError) {
- if (json) return jsonError(err.message);
- console.error(`Error: ${err.message}`);
- process.exit(1);
+ cliError(err.message);
+ return;
}
throw err;
}
@@ -1199,9 +1204,8 @@ export function registerTheme(program) {
try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }
}
const msg = `Failed to write theme outputs: ${err.message}`;
- if (json) return jsonError(msg);
- console.error(`Error: ${msg}`);
- process.exit(1);
+ cliError(msg);
+ return;
}
if (!json) {
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index e4cb0c1bea..1dfa6200cc 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -24,6 +24,7 @@ import {
import {resolveTheme} from '../../lib/resolve-theme.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
+import {cliError} from '../../lib/cli-error.mjs';
import {component as componentApi} from '../../api/component.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -48,10 +49,8 @@ export function registerComponent(program) {
const validDetails = ['full', 'compact', 'brief'];
if (!validDetails.includes(detail)) {
- if (json) return jsonError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
- console.error(`Error: Invalid --detail value "${detail}".`);
- console.error(`Valid levels: ${validDetails.join(', ')}`);
- process.exit(1);
+ cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
+ return;
}
let result;
@@ -69,15 +68,8 @@ export function registerComponent(program) {
lang, zh, dense,
});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- if (e.suggestions?.length) {
- console.error('');
- for (const s of e.suggestions) {
- console.error(` ${s.name} (${s.reason})`);
- }
- }
- process.exit(1);
+ cliError(e.message, {suggestions: e.suggestions});
+ return;
}
if (json) return jsonOut(result.type, result.data);
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index ebdb8d551d..ba14c6dabc 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -14,6 +14,7 @@ import {loadConfig} from '../lib/config.mjs';
import {scanAllPackages} from '../lib/package-scanner.mjs';
import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
import {discover as discoverApi} from '../api/discover.mjs';
export function registerDiscover(program) {
@@ -31,15 +32,8 @@ export function registerDiscover(program) {
try {
result = await discoverApi(query, {components: options.components, lang, zh});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- if (e.suggestions?.length) {
- console.error('');
- for (const s of e.suggestions) {
- console.error(` ${s.name} (${s.reason})`);
- }
- }
- process.exit(1);
+ cliError(e.message, {suggestions: e.suggestions});
+ return;
}
if (json) {
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index 476d034569..d89f570170 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -14,6 +14,7 @@
import {getRunPrefix} from '../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
import {docs as docsApi} from '../api/docs.mjs';
// ─── Formatting ──────────────────────────────────────────────────────────────
@@ -113,12 +114,10 @@ export function registerDocs(program) {
try {
result = await docsApi(topic, section, {lang, zh, dense});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- if (e.suggestions?.length) {
- console.error(`Available: ${e.suggestions.map(s => s.name).join(', ')}`);
- }
- process.exit(1);
+ // docs API throws structured errors with {name, reason} suggestions —
+ // pass them through untouched so the CLI envelope matches the API.
+ cliError(e.message, {suggestions: e.suggestions || []});
+ return;
}
if (json) return jsonOut(result.type, result.data);
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index d47c4c1a87..8758b8a2d2 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -21,6 +21,7 @@ import {
} from '../utils/github.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
/**
* Decide whether we're in a context safe to actually file a report.
@@ -270,12 +271,11 @@ export function registerGapReport(program) {
if (willFile && !config.command && !checkGhCli()) {
const msg =
- 'GitHub CLI (gh) is not installed or not authenticated.\n' +
- 'Install it from https://cli.github.com and run `gh auth login`.\n\n' +
+ 'GitHub CLI (gh) is not installed or not authenticated. ' +
+ 'Install it from https://cli.github.com and run `gh auth login`. ' +
`Or run \`${getRunPrefix()} xds gap-report setup\` to configure a custom command.`;
- if (json) return jsonError(msg);
- console.error(`Error: ${msg}`);
- process.exit(1);
+ cliError(msg);
+ return;
}
const isNonInteractive =
@@ -287,15 +287,10 @@ export function registerGapReport(program) {
c => c.value === options.category,
);
if (!validCategory) {
- if (json)
- return jsonError(
- `Invalid category "${options.category}". Valid: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
- );
- console.error(
- `Error: Invalid category "${options.category}".\n` +
- `Valid categories: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
+ cliError(
+ `Invalid category "${options.category}". Valid: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
);
- process.exit(1);
+ return;
}
const preview = buildGapReportPreview({
@@ -346,9 +341,8 @@ export function registerGapReport(program) {
humanLog('\nGap reporting is disabled via configuration.\n');
}
} catch (err) {
- if (json) return jsonError(err.message);
- console.error(`Error filing gap report: ${err.message}`);
- process.exit(1);
+ cliError(`Filing gap report failed: ${err.message}`);
+ return;
}
return;
}
diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjs
index 870597389d..b3e0172e9b 100644
--- a/packages/cli/src/commands/hook/index.mjs
+++ b/packages/cli/src/commands/hook/index.mjs
@@ -18,6 +18,7 @@ import {
} from '../../lib/hook-format.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
+import {cliError} from '../../lib/cli-error.mjs';
import {hook as hookApi} from '../../api/hook.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -37,10 +38,8 @@ export function registerHook(program) {
const validDetails = ['full', 'compact', 'brief'];
if (!validDetails.includes(detail)) {
- if (json) return jsonError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
- console.error(`Error: Invalid --detail value "${detail}".`);
- console.error(`Valid levels: ${validDetails.join(', ')}`);
- process.exit(1);
+ cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
+ return;
}
let result;
@@ -54,15 +53,8 @@ export function registerHook(program) {
lang, zh,
});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- if (e.suggestions?.length) {
- console.error('');
- for (const s of e.suggestions) {
- console.error(` ${s.name} (${s.reason})`);
- }
- }
- process.exit(1);
+ cliError(e.message, {suggestions: e.suggestions});
+ return;
}
if (json) return jsonOut(result.type, result.data);
diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjs
index 9468cc8be8..c5414ac253 100644
--- a/packages/cli/src/commands/init.mjs
+++ b/packages/cli/src/commands/init.mjs
@@ -22,6 +22,7 @@ import {getRunPrefix} from '../utils/package-manager.mjs';
import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';
import {listTemplates} from './template.mjs';
import {humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
import {requireInteractive} from '../utils/interactive.mjs';
const VALID_FEATURES = ['agents', 'theme', 'template'];
@@ -103,7 +104,7 @@ async function runTemplate(targetDir, {interactive = true, templateName} = {}) {
}
if (!templates.includes(templateName)) {
- console.error(`Error: Unknown template "${templateName}". Available: ${templates.join(', ')}`);
+ cliError(`Unknown template "${templateName}". Available: ${templates.join(', ')}`);
return;
}
@@ -177,9 +178,8 @@ export function registerInit(program) {
const invalid = features.filter(f => !VALID_FEATURES.includes(f));
if (invalid.length > 0) {
- console.error(`Error: Unknown features: ${invalid.join(', ')}`);
- console.error(`Valid features: ${VALID_FEATURES.join(', ')}`);
- process.exit(1);
+ cliError(`Unknown features: ${invalid.join(', ')}. Valid features: ${VALID_FEATURES.join(', ')}`);
+ return;
}
for (const feature of features) {
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 71c45d520e..6aa24d49dc 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -18,6 +18,7 @@ import {findCoreDir, listComponents} from '../utils/paths.mjs';
import {assertWithin, PathSafetyError, isNonInteractive} from '../utils/path-safety.mjs';
import {isInteractive} from '../utils/interactive.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
import {
buildGapReportPreview,
checkGhCli,
@@ -85,12 +86,10 @@ export function registerSwizzle(program) {
const json = program.opts().json || false;
if (!coreDir) {
- if (json) return jsonError('Could not find @xds/core package');
- console.error(
- 'Error: Could not find @xds/core package.\n' +
- 'Make sure you are inside the XDS monorepo or have @xds/core installed.',
+ cliError(
+ 'Could not find @xds/core package. Make sure you are inside the XDS monorepo or have @xds/core installed.',
);
- process.exit(1);
+ return;
}
const components = listComponents(coreDir);
@@ -111,10 +110,11 @@ export function registerSwizzle(program) {
const componentDir = path.join(coreDir, 'src', dirName);
if (!fs.existsSync(componentDir)) {
- if (json) return jsonError(`Component "${component}" not found`, components.slice(0, 5).map(n => ({name: n, reason: 'available component'})));
- console.error(`Error: Component "${component}" not found.`);
- console.error(`Available: ${components.join(', ')}`);
- process.exit(1);
+ cliError(
+ `Component "${component}" not found.`,
+ {suggestions: components.slice(0, 10).map((n) => ({name: n}))},
+ );
+ return;
}
// Path-safety: --output must resolve inside cwd. Reject absolute
@@ -126,9 +126,8 @@ export function registerSwizzle(program) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- if (json) return jsonError(err.message);
- console.error(`Error: ${err.message}`);
- process.exit(1);
+ cliError(err.message);
+ return;
}
throw err;
}
@@ -152,9 +151,8 @@ export function registerSwizzle(program) {
const msg =
`Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
`Re-run with --overwrite (or -f) to replace them.`;
- if (json) return jsonError(msg);
- console.error(`Error: ${msg}`);
- process.exit(1);
+ cliError(msg);
+ return;
}
const confirmed = isCancel(
await p.confirm({
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 2d43109ec9..15f35523d4 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -10,6 +10,7 @@ import * as p from '@clack/prompts';
import {CLI_ROOT} from '../utils/paths.mjs';
import {isNonInteractive} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {cliError} from '../lib/cli-error.mjs';
import {template as templateApi, getTemplateById} from '../api/template.mjs';
export {discoverTemplates, listTemplates, getTemplateById} from '../api/template.mjs';
@@ -49,9 +50,8 @@ export function registerTemplate(program) {
const msg =
`Refusing to overwrite existing file ${rel}. ` +
`Re-run with --overwrite (or -f) to replace it.`;
- if (json) return jsonError(msg);
- console.error(`Error: ${msg}`);
- process.exit(1);
+ cliError(msg);
+ return;
}
const confirmed = isCancel(
await p.confirm({
@@ -76,12 +76,10 @@ export function registerTemplate(program) {
cwd: process.cwd(),
});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- if (e.suggestions?.length) {
- console.error(`Available: ${e.suggestions.map(s => s.name).join(', ')}`);
- }
- process.exit(1);
+ // template API throws structured errors with {name, reason} suggestions —
+ // pass them through untouched so the CLI envelope matches the API.
+ cliError(e.message, {suggestions: e.suggestions || []});
+ return;
}
if (json) return jsonOut(result.type, result.data);
@@ -145,9 +143,8 @@ export function registerTemplate(program) {
try {
result = await getTemplateById(options.id, {cwd: process.cwd()});
} catch (e) {
- if (json) return jsonError(e.message, e.suggestions);
- console.error(`Error: ${e.message}`);
- process.exit(1);
+ cliError(e.message, {suggestions: e.suggestions});
+ return;
}
if (json) return jsonOut(result.type, result.data);
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index ef4c04037c..19376edacf 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -14,6 +14,8 @@ import * as path from 'node:path';
import {checkForUpdate} from './utils/update-check.mjs';
import {getRunPrefix} from './utils/package-manager.mjs';
import {API_VERSION, setJsonMode} from './lib/json.mjs';
+import {cliError} from './lib/cli-error.mjs';
+import {levenshteinDistance} from './lib/string-utils.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -70,7 +72,25 @@ program
'Output as typed JSON. Success envelope: { type, data }. Error envelope: { error, suggestions? }.',
)
.addHelpCommand('help', 'Show all commands')
- .action(() => {
+ .action((options, cmd) => {
+ // If Commander handed us a positional that didn't match any subcommand,
+ // treat it as "unknown command" — exit 1 with a helpful suggestion.
+ // This is the bare-invocation handler; if cmd.args has content here,
+ // none of the registered subcommands matched.
+ const extras = (cmd && cmd.args) || [];
+ if (extras.length > 0) {
+ const unknown = String(extras[0]);
+ const known = (program.commands || []).map((c) => c.name());
+ const suggestions = known
+ .map((name) => ({name, distance: levenshteinDistance(unknown.toLowerCase(), name.toLowerCase())}))
+ .filter((s) => s.distance <= 3)
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, 3)
+ .map((s) => ({name: s.name, reason: 'did you mean this?'}));
+ cliError(`unknown command '${unknown}'`, {suggestions});
+ return;
+ }
+
// `xds` (no subcommand) — print help, or emit a JSON envelope when --json.
if (program.opts().json) {
// Emit a JSON help envelope. Treat the bare invocation as supported.
diff --git a/packages/cli/src/lib/cli-error.mjs b/packages/cli/src/lib/cli-error.mjs
new file mode 100644
index 0000000000..3817d14eb9
--- /dev/null
+++ b/packages/cli/src/lib/cli-error.mjs
@@ -0,0 +1,147 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDS CLI — central error handling helper.
+ *
+ * ## Exit-code policy
+ *
+ * The XDS CLI follows one rule above all: **exit code is the contract**. CI
+ * scripts and AI agents read it before they read any text. Every error path
+ * across every command must agree on the exit code so that callers can
+ * detect failure without parsing stdout/stderr.
+ *
+ * Specifically:
+ *
+ * 1. **Any user-visible error → exit 1.** This includes "command not
+ * found", "unknown subcommand", "invalid argument", "file missing",
+ * "validation failed", and every `Error: ...` line we ever print.
+ *
+ * 2. **"Did you mean…" suggestions are still errors.** Suggestion lists
+ * help the user recover, but the CLI still exits 1. The user asked for
+ * something we couldn't deliver.
+ *
+ * 3. **Help-display is success.** `xds`, `xds --help`, `xds <cmd> --help`,
+ * and `xds --version` all exit 0. The user got what they asked for.
+ *
+ * 4. **Empty / no-args invocations:** if the command has a sensible
+ * default (e.g. `xds component` lists all components, `xds docs` lists
+ * all topics), exit 0. If the command requires arguments (e.g. `xds
+ * theme build`), Commander rejects it with exit 1.
+ *
+ * 5. **`--json` and non-`--json` agree on exit code.** The same error case
+ * MUST exit with the same code in both modes. The shape of the message
+ * differs (envelope vs. plain text); the exit code does not.
+ *
+ * 6. **Prefer `process.exitCode = 1; return` over `process.exit(1)`** when
+ * the action handler is the last thing on the call stack. This lets
+ * pending I/O (stderr buffers, postAction hooks) finish cleanly. Use
+ * `process.exit(1)` only when an immediate halt is required.
+ *
+ * The JSON envelope shape MUST match the contract from the json.mjs module:
+ *
+ * { apiVersion: 1, error: <string>, suggestions?: [{name, reason}, ...] }
+ *
+ * NEVER add ad-hoc fields. NEVER vary the shape. Consumers depend on it.
+ */
+
+import {isJsonMode, jsonError as _jsonError, humanWarn} from './json.mjs';
+
+/**
+ * Suggestion object — matches the shape used by API errors and the JSON
+ * envelope's `suggestions` field.
+ * @typedef {{name: string, reason?: string}} Suggestion
+ */
+
+/**
+ * Options for {@link cliError}.
+ * @typedef {object} CliErrorOptions
+ * @property {Suggestion[]} [suggestions] - Optional "did you mean…" list.
+ * Printed under the error message in human mode and serialized as the
+ * `suggestions` field in JSON mode.
+ * @property {number} [exitCode] - Override the exit code. Defaults to 1.
+ * Don't set this unless you have a specific reason — every error in the
+ * CLI should exit 1.
+ * @property {boolean} [hard] - When true, call `process.exit` immediately
+ * instead of setting `process.exitCode`. Default: true. We default to hard
+ * exits for commands because Commander's action handlers don't always
+ * propagate a `return` cleanly through nested awaits.
+ */
+
+/**
+ * Emit a user-visible error and stop the current command.
+ *
+ * Routes the error through the JSON envelope when `--json` is active, or to
+ * stderr otherwise. Always sets a non-zero exit code (default 1). Use this
+ * in place of every ad-hoc `console.error('Error: …'); process.exit(1)`
+ * pair across the CLI.
+ *
+ * @param {string} message - Human-readable error message. The leading
+ * "Error: " prefix is added automatically in human mode; in JSON mode the
+ * message is placed verbatim in the envelope's `error` field.
+ * @param {CliErrorOptions} [options]
+ * @returns {never} - Never returns; either exits the process or throws via
+ * `jsonError` (which itself exits).
+ */
+export function cliError(message, options = {}) {
+ const {suggestions, exitCode = 1, hard = true} = options;
+
+ if (isJsonMode()) {
+ // jsonError emits the envelope on stdout and calls process.exit(1).
+ // We don't honor a custom exitCode in JSON mode — the contract is exit 1.
+ _jsonError(message, suggestions);
+ // Unreachable, but keeps the type-checker honest.
+ return /** @type {never} */ (undefined);
+ }
+
+ // Human mode: prefix "Error:" and print suggestions on subsequent lines.
+ // Use console.error directly — we always want stderr for errors regardless
+ // of the JSON-mode flag (we already handled JSON above).
+ console.error(`Error: ${message}`);
+ if (suggestions?.length) {
+ console.error('');
+ for (const s of suggestions) {
+ const tag = s.reason ? ` ${s.name} (${s.reason})` : ` ${s.name}`;
+ console.error(tag);
+ }
+ }
+
+ if (hard) {
+ process.exit(exitCode);
+ } else {
+ process.exitCode = exitCode;
+ }
+ return /** @type {never} */ (undefined);
+}
+
+/**
+ * Clean exit. Mostly a marker for intent — `process.exit(0)` works fine,
+ * but using cliExit at success boundaries makes greps for "exit policy"
+ * sites unambiguous.
+ * @param {number} [code]
+ * @returns {never}
+ */
+export function cliExit(code = 0) {
+ process.exit(code);
+}
+
+/**
+ * Assert a condition; on failure, emit a CLI error.
+ *
+ * Convenience wrapper for the common pattern:
+ *
+ * if (!something) { cliError('something is required'); }
+ *
+ * @param {unknown} condition - Truthy → no-op. Falsy → cliError.
+ * @param {string} message
+ * @param {CliErrorOptions} [options]
+ * @returns {asserts condition}
+ */
+export function assertOrExit(condition, message, options) {
+ if (!condition) {
+ cliError(message, options);
+ }
+}
+
+// Re-export humanWarn for callers that want a non-fatal warning channel.
+// Warnings should NOT change the exit code.
+export {humanWarn};
diff --git a/packages/cli/src/lib/cli-error.test.mjs b/packages/cli/src/lib/cli-error.test.mjs
new file mode 100644
index 0000000000..72a4ff4e16
--- /dev/null
+++ b/packages/cli/src/lib/cli-error.test.mjs
@@ -0,0 +1,199 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the central CLI error helper (`cli-error.mjs`).
+ *
+ * What we lock in here:
+ * - cliError prints "Error: <msg>" to stderr in human mode and never
+ * touches stdout (preserves stdout discipline).
+ * - cliError emits the JSON envelope shape from json.mjs in JSON mode.
+ * - assertOrExit short-circuits on falsy conditions and returns silently
+ * on truthy ones (no side effects).
+ * - The exit code is 1 in both modes, matching the policy.
+ *
+ * E2E exit codes for actual subcommand invocations are tested in
+ * cli-exit-codes.test.mjs.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {cliError, assertOrExit, cliExit} from './cli-error.mjs';
+import {setJsonMode, API_VERSION} from './json.mjs';
+
+describe('cliError — human mode', () => {
+ let stderr;
+ let stdout;
+ let exitCode;
+ let exitSpy;
+
+ beforeEach(() => {
+ setJsonMode(false);
+ stderr = [];
+ stdout = [];
+ exitCode = null;
+ vi.spyOn(console, 'error').mockImplementation((...a) => stderr.push(a.join(' ')));
+ vi.spyOn(console, 'log').mockImplementation((...a) => stdout.push(a.join(' ')));
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
+ exitCode = code ?? 0;
+ throw new Error(`__exit_${exitCode}__`);
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('prints "Error: <msg>" to stderr and exits 1', () => {
+ expect(() => cliError('something broke')).toThrow('__exit_1__');
+ expect(stderr).toContain('Error: something broke');
+ expect(stdout).toEqual([]);
+ expect(exitCode).toBe(1);
+ });
+
+ it('prints suggestions on subsequent stderr lines', () => {
+ expect(() =>
+ cliError('No component named "Buton"', {
+ suggestions: [
+ {name: 'Button', reason: 'closest match'},
+ {name: 'ButtonGroup', reason: 'related'},
+ ],
+ }),
+ ).toThrow('__exit_1__');
+ expect(stderr[0]).toBe('Error: No component named "Buton"');
+ expect(stderr).toContain(' Button (closest match)');
+ expect(stderr).toContain(' ButtonGroup (related)');
+ });
+
+ it('omits "(reason)" when suggestion has no reason field', () => {
+ expect(() =>
+ cliError('Unknown topic', {suggestions: [{name: 'color'}, {name: 'spacing'}]}),
+ ).toThrow('__exit_1__');
+ expect(stderr).toContain(' color');
+ expect(stderr).toContain(' spacing');
+ });
+
+ it('respects custom exitCode', () => {
+ expect(() => cliError('msg', {exitCode: 2})).toThrow('__exit_2__');
+ expect(exitCode).toBe(2);
+ });
+
+ it('uses process.exitCode when hard:false', () => {
+ const original = process.exitCode;
+ try {
+ // Should NOT throw — sets process.exitCode and returns.
+ cliError('soft', {hard: false});
+ expect(process.exitCode).toBe(1);
+ expect(exitSpy).not.toHaveBeenCalled();
+ } finally {
+ process.exitCode = original;
+ }
+ });
+});
+
+describe('cliError — JSON mode', () => {
+ let stderr;
+ let stdout;
+ let exitCode;
+
+ beforeEach(() => {
+ setJsonMode(true);
+ stderr = [];
+ stdout = [];
+ exitCode = null;
+ vi.spyOn(console, 'error').mockImplementation((...a) => stderr.push(a.join(' ')));
+ vi.spyOn(console, 'log').mockImplementation((...a) => stdout.push(a.join(' ')));
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
+ exitCode = code ?? 0;
+ throw new Error(`__exit_${exitCode}__`);
+ });
+ });
+
+ afterEach(() => {
+ setJsonMode(false);
+ vi.restoreAllMocks();
+ });
+
+ it('emits a JSON envelope on stdout, nothing on stderr, and exits 1', () => {
+ expect(() => cliError('json mode error')).toThrow('__exit_1__');
+ expect(stderr).toEqual([]);
+ expect(stdout.length).toBe(1);
+ const env = JSON.parse(stdout[0]);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.error).toBe('json mode error');
+ expect(env.suggestions).toBeUndefined();
+ expect(exitCode).toBe(1);
+ });
+
+ it('serializes suggestions in the envelope', () => {
+ expect(() =>
+ cliError('No component named "Buton"', {
+ suggestions: [{name: 'Button', reason: 'closest match'}],
+ }),
+ ).toThrow('__exit_1__');
+ const env = JSON.parse(stdout[0]);
+ expect(env.suggestions).toEqual([{name: 'Button', reason: 'closest match'}]);
+ });
+
+ it('always exits 1 in JSON mode (custom exitCode is ignored — contract)', () => {
+ expect(() => cliError('msg', {exitCode: 2})).toThrow('__exit_1__');
+ expect(exitCode).toBe(1);
+ });
+});
+
+describe('assertOrExit', () => {
+ let exitCalled;
+
+ beforeEach(() => {
+ setJsonMode(false);
+ exitCalled = false;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(process, 'exit').mockImplementation(() => {
+ exitCalled = true;
+ throw new Error('__exit__');
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('is a no-op for truthy conditions', () => {
+ expect(() => assertOrExit(true, 'should not fire')).not.toThrow();
+ expect(() => assertOrExit('non-empty', 'should not fire')).not.toThrow();
+ expect(() => assertOrExit(1, 'should not fire')).not.toThrow();
+ expect(exitCalled).toBe(false);
+ });
+
+ it('triggers cliError for falsy conditions', () => {
+ expect(() => assertOrExit(false, 'must be true')).toThrow('__exit__');
+ expect(exitCalled).toBe(true);
+ });
+
+ it('triggers cliError for null/undefined', () => {
+ expect(() => assertOrExit(null, 'nope')).toThrow('__exit__');
+ expect(exitCalled).toBe(true);
+ });
+});
+
+describe('cliExit', () => {
+ it('calls process.exit with given code', () => {
+ let called = null;
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
+ called = code;
+ throw new Error('__exit__');
+ });
+ expect(() => cliExit(0)).toThrow('__exit__');
+ expect(called).toBe(0);
+ vi.restoreAllMocks();
+ });
+
+ it('defaults to exit code 0', () => {
+ let called = null;
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
+ called = code;
+ throw new Error('__exit__');
+ });
+ expect(() => cliExit()).toThrow('__exit__');
+ expect(called).toBe(0);
+ vi.restoreAllMocks();
+ });
+});