An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): answer help-on-error with an error envelope under --json (#6550)
Joeyc5f45c4effca
diff --git a/.changeset/cli-spec-help-error-envelope.md b/.changeset/cli-spec-help-error-envelope.mdnew file mode 100644index 0000000000..5a79b1aae6--- /dev/null+++ b/.changeset/cli-spec-help-error-envelope.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] With `--json`, `astryx help <unknown-command>` and a command group run without a subcommand (such as `astryx layout --json`) now return an error envelope, with `ERR_UNKNOWN_COMMAND` or `ERR_MISSING_ARGUMENT`, instead of a success-shaped help envelope. Both still exit 1, as they do without `--json`.++@josephfarinadiff --git a/packages/cli/clients/cli/lib/json-shim.mjs b/packages/cli/clients/cli/lib/json-shim.mjsindex f2e00e9c15..006f1a8dbb 100644--- a/packages/cli/clients/cli/lib/json-shim.mjs+++ b/packages/cli/clients/cli/lib/json-shim.mjs@@ -29,6 +29,9 @@* 4. Routing unknown-subcommand attempts through the same error* envelope path (so `astryx bogus-cmd --json` gets exit 1 + envelope* instead of exit 0 + help envelope).+ * 5. Emitting an error envelope, not the help envelope, when Commander+ * shows help because the invocation failed (`help <unknown>`, or a+ * command group with no subcommand), which exits 1.** Non-JSON behavior is preserved exactly: every code path that printed* to stderr before still prints to stderr. Commander writes its@@ -117,6 +120,35 @@ export function buildHelpEnvelope(cmd) {};}+/**+ * The error envelope for help Commander shows because the invocation failed+ * (it then exits 1): `help <name>` for an unknown name on the root, or a+ * command group run without a subcommand.+ *+ * @param {import('commander').Command} cmd the command whose help was shown+ * @returns {ReturnType<typeof toErrorEnvelope>}+ */+export function buildHelpErrorEnvelope(cmd) {+ const available = cmd.commands+ .filter(s => !(/** @type {any} */ (s))._hidden && s.name() !== 'help')+ .map(s => s.name());+ if (!cmd.parent) {+ // Commander dispatches `help <name>` with ['help', <name>, ...] in args.+ const requested = cmd.args[1];+ return toErrorEnvelope(+ requested ? `unknown command '${requested}'` : 'unknown command',+ available.map(name => ({name, reason: 'available command'})),+ ERROR_CODES.ERR_UNKNOWN_COMMAND,+ );+ }+ const group = fullNameOf(cmd);+ return toErrorEnvelope(+ `'${group}' needs a subcommand`,+ available.map(name => ({name: `${group} ${name}`, reason: 'available subcommand'})),+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+}+/*** Emit a JSON error envelope to stdout (the JSON contract uses stdout* for both success and error).@@ -310,7 +342,9 @@ function patchOutputHelp(cmd) {if (jsonActive()) {if (!process.__xdsJsonHandled) {process.__xdsJsonHandled = true;- const env = buildHelpEnvelope(cmd);+ const env = contextOptions?.error+ ? buildHelpErrorEnvelope(cmd)+ : buildHelpEnvelope(cmd);process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);}return;@@ -334,7 +368,9 @@ function patchPrototype(CommandCtor) {if (jsonActive()) {if (!process.__xdsJsonHandled) {process.__xdsJsonHandled = true;- const env = buildHelpEnvelope(this);+ const env = contextOptions?.error+ ? buildHelpErrorEnvelope(this)+ : buildHelpEnvelope(this);process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);}return;diff --git a/packages/cli/clients/cli/lib/json-shim.test.mjs b/packages/cli/clients/cli/lib/json-shim.test.mjsindex f923cdf6b2..6c10336719 100644--- a/packages/cli/clients/cli/lib/json-shim.test.mjs+++ b/packages/cli/clients/cli/lib/json-shim.test.mjs@@ -20,7 +20,12 @@*/import {describe, it, expect} from 'vitest';+import {spawnSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {Command} from 'commander';import {runCli} from '../../../test-utils/run-cli.mjs';+import {installJsonShim} from './json-shim.mjs';+import {setJsonMode} from '../../../foundation/response/json.mjs';function parseJson(stdout) {return JSON.parse(stdout);@@ -207,3 +212,81 @@ describe('--json shim: stdout discipline under --json', () => {}});});++describe('--json shim: help shown for a failed invocation is an error envelope', () => {+ it('astryx help bogus --json emits ERR_UNKNOWN_COMMAND, exit 1', async () => {+ const {status, stdout, stderr} = await runCli(['help', 'bogus', '--json']);+ expect(status).toBe(1);+ expect(stderr).toBe('');+ const parsed = parseJson(stdout);+ expect(parsed).not.toHaveProperty('type');+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.code).toBe('ERR_UNKNOWN_COMMAND');+ expect(parsed.error).toMatch(/bogus/);+ });++ it('astryx layout --json (group, no subcommand) emits ERR_MISSING_ARGUMENT, exit 1', async () => {+ const {status, stdout, stderr} = await runCli(['layout', '--json']);+ expect(status).toBe(1);+ expect(stderr).toBe('');+ const parsed = parseJson(stdout);+ expect(parsed).not.toHaveProperty('type');+ expect(parsed.code).toBe('ERR_MISSING_ARGUMENT');+ expect(parsed.suggestions.map((s) => s.name)).toContain('layout expand');+ });++ it('astryx layout (no --json) still prints help to stderr, exit 1', async () => {+ const {status, stdout, stderr} = await runCli(['layout']);+ expect(status).toBe(1);+ expect(stdout).toBe('');+ expect(stderr).toMatch(/Usage: astryx layout/);+ });++ it('the real binary emits the same envelope for help bogus --json', () => {+ // One program per process, so the root's own outputHelp patch is used here.+ const bin = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));+ const res = spawnSync(process.execPath, [bin, 'help', 'bogus', '--json'], {+ encoding: 'utf-8',+ timeout: 20_000,+ });+ expect(res.status).toBe(1);+ expect(res.stderr).toBe('');+ const parsed = parseJson(res.stdout);+ expect(parsed).not.toHaveProperty('type');+ expect(parsed.code).toBe('ERR_UNKNOWN_COMMAND');+ });++ it('a group added after install gets the same error envelope', () => {+ const program = new Command('astryx');+ installJsonShim(program);+ // Added later, so only the prototype-level patch covers its outputHelp.+ const late = new Command('late');+ late.command('child');+ program.addCommand(late);+ /** @type {string[]} */+ const writes = [];+ const origWrite = process.stdout.write;+ // @ts-expect-error - test-only capture+ process.stdout.write = (chunk) => writes.push(String(chunk)) > 0;+ setJsonMode(true);+ delete process.__xdsJsonHandled;+ try {+ late.outputHelp({error: true});+ } finally {+ process.stdout.write = origWrite;+ setJsonMode(false);+ delete process.__xdsJsonHandled;+ }+ const parsed = parseJson(writes.join(''));+ expect(parsed.code).toBe('ERR_MISSING_ARGUMENT');+ expect(parsed.suggestions).toEqual([{name: 'late child', reason: 'available subcommand'}]);+ });++ it('astryx help layout --json still emits the help envelope, exit 0', async () => {+ const {status, stdout} = await runCli(['help', 'layout', '--json']);+ expect(status).toBe(0);+ const parsed = parseJson(stdout);+ expect(parsed.type).toBe('help');+ expect(parsed.data.command).toBe('astryx layout');+ });+});