An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): honor --json on Commander parse errors and --help (#2519)
Joeya7b4f18eb945
diff --git a/.changeset/cli-json-commander-shim.md b/.changeset/cli-json-commander-shim.mdnew file mode 100644index 0000000000..5754a44a85--- /dev/null+++ b/.changeset/cli-json-commander-shim.md@@ -0,0 +1,9 @@+---+'@xds/cli': patch+---++**CLI:** honor `--json` on Commander parse errors and `--help`.++The `--json` contract from the previous release covered the normal command-execution path, but Commander's own short-circuits (parse errors, unknown options, `--help`, unknown subcommands) ran before the `preAction` gate could engage JSON mode. A `--json` consumer would get empty stdout + raw stderr instead of the contract envelope.++A new shim wires `exitOverride()` and a JSON-aware `configureOutput` onto every command (root + subcommands) and patches `outputHelp` to emit a structured `{apiVersion, type:'help', data}` envelope under `--json`. Parse errors now produce `{apiVersion, error}` on stdout with exit 1; unknown subcommands now error (instead of silently emitting help with exit 0); `--detail` is now choice-validated. Non-`--json` invocations are unchanged — Commander's "error: ..." line still goes to stderr.diff --git a/packages/cli/bin/xds.mjs b/packages/cli/bin/xds.mjsindex 977a198744..12fbbc12bd 100755--- a/packages/cli/bin/xds.mjs+++ b/packages/cli/bin/xds.mjs@@ -3,6 +3,7 @@import {program} from '../src/index.mjs';import {isJsonMode, toErrorEnvelope} from '../src/lib/json.mjs';+import {handleCommanderError} from '../src/lib/json-shim.mjs';/*** Top-level error boundary (contract guarantee #4): an uncaught throw must@@ -19,6 +20,12 @@ function inJsonMode() {}function handleFatal(err) {+ // CommanderError (parse errors, --help, unknown command) routes+ // through the JSON shim so that a --json consumer always gets a+ // valid envelope and the right exit code. handleCommanderError+ // calls process.exit when it owns the error.+ if (handleCommanderError(err)) return;+if (inJsonMode()) {// Only emit if a command didn't already produce an envelope.if (!process.__xdsJsonHandled) {diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjsindex e26d3ecb4f..3ca00fe25f 100644--- a/packages/cli/src/commands/build-theme.mjs+++ b/packages/cli/src/commands/build-theme.mjs@@ -33,8 +33,11 @@ try {_generateThemeRules = coreTheme.generateThemeRules;_generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;_generateOnMediaCSS = coreTheme.generateOnMediaCSS;-} catch (e) {- console.warn('Warning: could not load @xds/core/theme:', e.message);+} catch (_e) {+ // Silent fallback. The theme command surfaces a clear error if it's actually+ // invoked without core being available; emitting a stderr warning at module-+ // load time would leak into every other command's output and break the+ // clean-stderr contract under --json (and breaks tests that assert it).}/**diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex 19376edacf..4265727e6c 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -7,7 +7,7 @@* (bad import, syntax error), the other commands still work.*/-import {Command} from 'commander';+import {Command, Option} from 'commander';import {fileURLToPath} from 'node:url';import * as fs from 'node:fs';import * as path from 'node:path';@@ -16,6 +16,7 @@ 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';+import {installJsonShim} from './lib/json-shim.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -66,7 +67,11 @@ program.option('--zh', 'Output docs in Chinese Simplified').option('--dense', 'Output docs in compressed dense format (token-efficient)').option('--lang <locale>', 'Output docs in specified language/format (en, zh, dense)')- .option('--detail <level>', 'Output detail level (full, compact, brief)', 'full')+ .addOption(+ new Option('--detail <level>', 'Output detail level (full, compact, brief)')+ .choices(['full', 'compact', 'brief'])+ .default('full'),+ ).option('--json','Output as typed JSON. Success envelope: { type, data }. Error envelope: { error, suggestions? }.',@@ -80,13 +85,20 @@ programconst extras = (cmd && cmd.args) || [];if (extras.length > 0) {const unknown = String(extras[0]);- const known = (program.commands || []).map((c) => c.name());- const suggestions = known+ const known = (program.commands || [])+ .filter((c) => !c._hidden && c.name() !== 'help')+ .map((c) => c.name());+ const close = 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?'}));+ // If we have close matches, surface those. Otherwise list all known commands+ // so callers (including AI agents) can see what's available.+ const suggestions = close.length > 0+ ? close+ : known.map((name) => ({name, reason: 'available command'}));cliError(`unknown command '${unknown}'`, {suggestions});return;}@@ -259,3 +271,10 @@ ${line('')}╰${'─'.repeat(W + 2)}╯`);});++// Install the JSON shim AFTER all commands are registered so we can+// patch outputHelp on every command (root + subcommands). The shim+// extends the --json contract to cover Commander's parse-time short+// circuits (parse errors, unknown options, --help, unknown commands).+// See packages/cli/src/lib/json-shim.mjs for the rationale.+installJsonShim(program);diff --git a/packages/cli/src/lib/json-shim.mjs b/packages/cli/src/lib/json-shim.mjsnew file mode 100644index 0000000000..423300f4fe--- /dev/null+++ b/packages/cli/src/lib/json-shim.mjs@@ -0,0 +1,284 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Commander shim that extends the --json contract to cover+ * Commander's parse-time short-circuits (parse errors, unknown options,+ * --help display, unknown subcommands).+ *+ * Background: PR #2467 set up the --json envelope and a `preAction` gate.+ * That works for the normal command-execution path, but Commander's own+ * error and help paths run BEFORE preAction:+ *+ * - Missing required argument / unknown option → `_displayError`+ * writes "error: ..." to stderr and calls `_exit(1)` synchronously.+ * - `--help` → `outputHelp()` writes raw "Usage:" text to stdout+ * and calls `_exit(0)`.+ *+ * Neither path emits the JSON envelope, and neither throws (so the+ * try/catch in `bin/xds.mjs` never sees them). The result: a --json+ * consumer receives empty stdout + raw stderr, breaking the contract.+ *+ * The shim closes the gap by:+ * 1. Calling `exitOverride()` so Commander throws CommanderError+ * instead of calling `process.exit` synchronously.+ * 2. Routing those errors through a single handler that emits a+ * JSON error envelope when --json is in argv.+ * 3. Overriding each command's `outputHelp` so --help emits a+ * structured JSON help envelope (instead of raw text) when+ * --json is set.+ * 4. Routing unknown-subcommand attempts through the same error+ * envelope path (so `xds bogus-cmd --json` gets exit 1 + envelope+ * instead of exit 0 + help envelope).+ *+ * Non-JSON behavior is preserved exactly: every code path that printed+ * to stderr before still prints to stderr. Commander writes its+ * "error: ..." line via configureOutput.writeErr, which we pass+ * through verbatim outside of --json mode.+ */++import {API_VERSION, isJsonMode, toErrorEnvelope} from './json.mjs';++/**+ * Cheap argv check used before preAction has had a chance to engage+ * `setJsonMode`. We can't rely on `program.opts().json` here because+ * Commander throws during parse — opts may not be populated yet.+ * @returns {boolean}+ */+function argvHasJson() {+ return process.argv.slice(2).includes('--json');+}++/** @returns {boolean} */+function jsonActive() {+ return isJsonMode() || argvHasJson();+}++/**+ * Build a structured JSON help envelope for a given Commander command.+ * Mirrors the existing root help envelope shape, but works for any+ * subcommand (e.g. `xds component --help --json`).+ *+ * @param {import('commander').Command} cmd+ * @returns {{apiVersion: number, type: 'help', data: object}}+ */+export function buildHelpEnvelope(cmd) {+ // Reconstruct the fully-qualified command name (e.g. "xds theme build").+ const nameParts = [];+ let c = cmd;+ while (c) {+ nameParts.unshift(c.name());+ c = c.parent;+ }++ /** @type {Array<{flags: string, description: string, defaultValue?: unknown, choices?: string[]}>} */+ const options = cmd.options.map((o) => {+ /** @type {any} */+ const opt = {flags: o.flags, description: o.description || ''};+ if (o.defaultValue !== undefined) opt.defaultValue = o.defaultValue;+ if (Array.isArray(o.argChoices) && o.argChoices.length) opt.choices = o.argChoices;+ return opt;+ });++ const subcommands = cmd.commands+ .filter((s) => !s._hidden)+ .map((s) => ({name: s.name(), description: s.description() || ''}));++ return {+ apiVersion: API_VERSION,+ type: 'help',+ data: {+ command: nameParts.join(' '),+ description: cmd.description() || '',+ usage: `${nameParts.join(' ')} ${cmd.usage()}`.trim(),+ options,+ subcommands,+ },+ };+}++/**+ * Emit a JSON error envelope to stdout (the JSON contract uses stdout+ * for both success and error).+ *+ * @param {string} message+ * @param {Array<{name: string, reason: string}>} [suggestions]+ */+function emitJsonError(message, suggestions) {+ if (process.__xdsJsonHandled) return;+ process.__xdsJsonHandled = true;+ const env = toErrorEnvelope(message, suggestions);+ process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);+}++/**+ * Install the shim on a Commander program. Idempotent — safe to call+ * once at program-construction time.+ *+ * @param {import('commander').Command} program+ */+export function installJsonShim(program) {+ // exitOverride() and configureOutput() do NOT auto-cascade to+ // subcommands that were registered BEFORE the shim runs (Commander+ // copies these settings from parent at command-creation time, not+ // at parse time). So we walk the whole tree and apply them+ // explicitly to every node.+ applyShimRecursively(program);++ // Don't tack the help text onto error output. We render help+ // ourselves (or as JSON) and don't want Commander's stderr help dump+ // interleaving with our error envelope.+ program.showHelpAfterError(false);++ // Patch outputHelp on every command (root + subcommands) so+ // `--help` emits a JSON envelope when --json is active. Commander+ // creates subcommands lazily, so wrap recursively + patch any+ // new ones added later by walking after registration.+ patchHelpRecursively(program);+}++/**+ * Apply exitOverride and JSON-aware configureOutput to a command and+ * all of its descendants. We do this recursively because Commander+ * only copies these settings to children created AFTER the parent is+ * configured — and our subcommands were already registered by the+ * time installJsonShim runs.+ *+ * @param {import('commander').Command} cmd+ */+function applyShimRecursively(cmd) {+ cmd.exitOverride();+ cmd.configureOutput({+ writeOut: (str) => process.stdout.write(str),+ writeErr: (str) => {+ // Suppress Commander's "error: ..." stderr line when --json is+ // active, so a JSON consumer parsing both streams doesn't see+ // it alongside the envelope. Non-JSON callers are unaffected.+ if (jsonActive()) return;+ process.stderr.write(str);+ },+ });+ for (const sub of cmd.commands) {+ applyShimRecursively(sub);+ }+}++/**+ * Walk the command tree and override outputHelp on every command so that+ * `--help --json` emits a structured help envelope instead of raw text.+ *+ * @param {import('commander').Command} cmd+ */+function patchHelpRecursively(cmd) {+ patchOutputHelp(cmd);+ for (const sub of cmd.commands) {+ patchHelpRecursively(sub);+ }+ // If new subcommands are added later (via commands.push or+ // .command(...)), patch them on first .help()/--help. Commander+ // doesn't fire an event for command registration, so we hook into+ // Command.prototype here (one-time, idempotent).+ if (!Command_outputHelp_patched) {+ patchPrototype(cmd.constructor);+ Command_outputHelp_patched = true;+ }+}++let Command_outputHelp_patched = false;++/**+ * Replace outputHelp on a single Command instance.+ * @param {import('commander').Command} cmd+ */+function patchOutputHelp(cmd) {+ if (cmd.__xdsHelpPatched) return;+ cmd.__xdsHelpPatched = true;+ const original = cmd.outputHelp.bind(cmd);+ cmd.outputHelp = function patchedOutputHelp(contextOptions) {+ if (jsonActive()) {+ if (!process.__xdsJsonHandled) {+ process.__xdsJsonHandled = true;+ const env = buildHelpEnvelope(cmd);+ process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);+ }+ return;+ }+ return original(contextOptions);+ };+}++/**+ * Patch Command.prototype so that any subcommand created after install+ * also gets the JSON help override. Belt-and-suspenders for late-bound+ * commands.+ * @param {Function} CommandCtor+ */+function patchPrototype(CommandCtor) {+ const proto = CommandCtor.prototype;+ if (proto.__xdsHelpPatched) return;+ proto.__xdsHelpPatched = true;+ const original = proto.outputHelp;+ proto.outputHelp = function patchedProtoOutputHelp(contextOptions) {+ if (jsonActive()) {+ if (!process.__xdsJsonHandled) {+ process.__xdsJsonHandled = true;+ const env = buildHelpEnvelope(this);+ process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);+ }+ return;+ }+ return original.call(this, contextOptions);+ };+}++/**+ * Convert a CommanderError thrown during parse into either a JSON+ * envelope (under --json) or the legacy stderr behavior, then exit+ * with the right code.+ *+ * Codes we care about (Commander 14):+ * commander.helpDisplayed — `--help` was used (exit 0)+ * commander.help — same family (exit 0)+ * commander.version — `--version` was used (exit 0)+ * commander.unknownCommand — `xds bogus-cmd`+ * commander.unknownOption — `--bogus-flag`+ * commander.missingArgument — `xds theme build` (no <file>)+ * commander.invalidArgument — bad value for argParser+ * commander.invalidOptionArgument+ * commander.excessArguments+ *+ * @param {unknown} err+ * @returns {boolean} true if handled (caller should not re-throw)+ */+export function handleCommanderError(err) {+ if (!err || typeof err !== 'object' || !('code' in err)) return false;+ const code = /** @type {{code?: string, exitCode?: number, message?: string}} */ (err).code;+ if (typeof code !== 'string' || !code.startsWith('commander.')) return false;++ const exitCode = /** @type {{exitCode?: number}} */ (err).exitCode ?? 1;+ const message = /** @type {{message?: string}} */ (err).message ?? '';++ // Help / version success paths — Commander already wrote the output+ // (via our patched outputHelp for help; via its own writer for version,+ // which we handle separately in index.mjs argv preflight). Just exit+ // with the right code.+ if (+ code === 'commander.helpDisplayed' ||+ code === 'commander.help' ||+ code === 'commander.version'+ ) {+ process.exit(exitCode);+ }++ // Real error paths.+ if (jsonActive()) {+ // Strip Commander's "error: " prefix — the envelope key is `error`+ // already, doubled "error" is noise.+ const cleaned = message.replace(/^error:\s*/i, '');+ emitJsonError(cleaned);+ } else {+ // Non-JSON mode: Commander already wrote the "error: ..." line+ // to stderr via configureOutput.writeErr before throwing the+ // CommanderError. Nothing to do — exit with the original code.+ }+ process.exit(exitCode || 1);+}diff --git a/packages/cli/src/lib/json-shim.test.mjs b/packages/cli/src/lib/json-shim.test.mjsnew file mode 100644index 0000000000..985e76b0ba--- /dev/null+++ b/packages/cli/src/lib/json-shim.test.mjs@@ -0,0 +1,194 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Integration tests for the JSON shim — extends the --json+ * contract to cover Commander's parse-time short-circuits.+ *+ * Spawns the CLI as a real subprocess so Commander hooks, exitOverride,+ * and process.exit fire end-to-end. Asserts:+ *+ * 1. `--help --json` (root + subcommand) emits a JSON help envelope,+ * not raw "Usage:" text. Exit 0.+ * 2. Parse errors (missing required arg, unknown option) emit a+ * JSON error envelope on stdout. Exit 1.+ * 3. Unknown subcommand produces an error envelope (not a help+ * envelope with exit 0).+ * 4. Invalid `--detail` choice produces a single error envelope+ * (not error then help).+ * 5. Non-`--json` invocations still print to stderr and exit 1+ * exactly as before — no regression.+ */++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_BIN = path.resolve(__dirname, '../../bin/xds.mjs');++function runCli(args) {+ const res = spawnSync('node', [CLI_BIN, ...args], {+ encoding: 'utf-8',+ timeout: 20_000,+ });+ return {+ status: res.status,+ stdout: res.stdout || '',+ stderr: res.stderr || '',+ };+}++function parseJson(stdout) {+ return JSON.parse(stdout);+}++describe('--json shim: --help renders JSON envelope', () => {+ it('xds --help --json emits a help envelope (not raw text), exit 0', () => {+ const {status, stdout, stderr} = runCli(['--help', '--json']);+ expect(status).toBe(0);+ expect(stderr).toBe('');+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.type).toBe('help');+ expect(parsed.data).toBeDefined();+ expect(parsed.data.command).toBe('xds');+ // Should list known subcommands+ const subNames = parsed.data.subcommands.map((s) => s.name);+ expect(subNames).toContain('component');+ expect(subNames).toContain('theme');+ });++ it('xds component --help --json emits a subcommand help envelope', () => {+ const {status, stdout} = runCli(['component', '--help', '--json']);+ expect(status).toBe(0);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.type).toBe('help');+ expect(parsed.data.command).toBe('xds component');+ // Should expose its options+ const flags = parsed.data.options.map((o) => o.flags);+ expect(flags).toContain('--list');+ });++ it('xds theme build --help --json emits a nested subcommand help envelope', () => {+ const {status, stdout} = runCli(['theme', 'build', '--help', '--json']);+ expect(status).toBe(0);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.type).toBe('help');+ expect(parsed.data.command).toBe('xds theme build');+ expect(parsed.data.usage).toMatch(/<file>/);+ });+});++describe('--json shim: parse errors emit JSON error envelope', () => {+ it('xds theme build --json (missing required arg) emits error envelope, exit 1', () => {+ const {status, stdout} = runCli(['theme', 'build', '--json']);+ expect(status).toBe(1);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.error).toMatch(/missing required argument/i);+ expect(parsed.error).toMatch(/file/i);+ });++ it('xds --bogus-flag --json (unknown option) emits error envelope, exit 1', () => {+ const {status, stdout} = runCli(['--bogus-flag', '--json']);+ expect(status).toBe(1);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.error).toMatch(/unknown option/i);+ expect(parsed.error).toMatch(/--bogus-flag/);+ });++ it('xds component --json --bogus-flag (unknown option on subcmd) emits error envelope, exit 1', () => {+ const {status, stdout} = runCli(['component', '--json', '--bogus-flag']);+ expect(status).toBe(1);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.error).toMatch(/unknown option/i);+ });+});++describe('--json shim: unknown subcommand emits error envelope', () => {+ it('xds bogus-cmd --json emits error envelope, exit 1 (not exit 0 + help)', () => {+ const {status, stdout} = runCli(['bogus-cmd', '--json']);+ expect(status).toBe(1);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.error).toMatch(/unknown command/i);+ expect(parsed.error).toMatch(/bogus-cmd/);+ // Suggestions should list known commands+ expect(Array.isArray(parsed.suggestions)).toBe(true);+ const names = parsed.suggestions.map((s) => s.name);+ expect(names).toContain('component');+ });+});++describe('--json shim: invalid --detail choice', () => {+ it('xds --detail bogus --json emits a single error envelope, exit 1', () => {+ const {status, stdout} = runCli(['--detail', 'bogus', '--json']);+ expect(status).toBe(1);+ const parsed = parseJson(stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.error).toMatch(/--detail/);+ expect(parsed.error).toMatch(/invalid|allowed/i);+ // Single emission only — stdout must be exactly one JSON document.+ // (parseJson would have thrown if there were two concatenated docs.)+ // Belt-and-suspenders: count opening braces at column 0.+ const topLevelBraces = stdout.split('\n').filter((l) => l === '{').length;+ expect(topLevelBraces).toBe(1);+ });+});++describe('--json shim: non-JSON behavior is preserved', () => {+ it('xds theme build (no --json, missing arg) writes to stderr and exits 1', () => {+ const {status, stdout, stderr} = runCli(['theme', 'build']);+ expect(status).toBe(1);+ expect(stdout).toBe('');+ expect(stderr).toMatch(/missing required argument/i);+ });++ it('xds --bogus-flag (no --json) writes to stderr and exits 1', () => {+ const {status, stdout, stderr} = runCli(['--bogus-flag']);+ expect(status).toBe(1);+ expect(stdout).toBe('');+ expect(stderr).toMatch(/unknown option/i);+ });++ it('xds bogus-cmd (no --json) writes to stderr and exits 1', () => {+ const {status, stdout, stderr} = runCli(['bogus-cmd']);+ expect(status).toBe(1);+ expect(stdout).toBe('');+ expect(stderr).toMatch(/unknown command/i);+ });++ it('xds --detail bogus (no --json) writes to stderr and exits 1', () => {+ const {status, stdout, stderr} = runCli(['--detail', 'bogus']);+ expect(status).toBe(1);+ expect(stdout).toBe('');+ expect(stderr).toMatch(/--detail/);+ });++ it('xds --help (no --json) writes raw help text to stdout, exit 0', () => {+ const {status, stdout, stderr} = runCli(['--help']);+ expect(status).toBe(0);+ expect(stdout).toMatch(/^Usage: xds/);+ expect(stderr).toBe('');+ });+});++describe('--json shim: stdout discipline under --json', () => {+ it('all error envelopes have empty stderr (no leak of legacy "error: ..." line)', () => {+ const cases = [+ ['theme', 'build', '--json'],+ ['--bogus-flag', '--json'],+ ['bogus-cmd', '--json'],+ ['--detail', 'bogus', '--json'],+ ];+ for (const args of cases) {+ const {stderr} = runCli(args);+ expect(stderr, `stderr should be empty for: ${args.join(' ')}`).toBe('');+ }+ });+});