Crust logoCrust

JSON

Print a command's result as machine-readable JSON.

Usage

cli.ts
import { Crust } from "@crustjs/core";
import { json } from "@crustjs/extensions";

const app = new Crust("my-cli").extend(json()).command("deploy", (cmd) =>
	cmd.action(({ stdout }) => {
		stdout("Deploying...");
		return { id: "dep_42", url: "https://example.com" };
	}),
);

await app.execute();
$ my-cli deploy --json
Deploying...                                  # stderr
{"id":"dep_42","url":"https://example.com"}   # stdout

json() adds a recursive boolean --json flag. Without the flag, nothing changes. It also adds a "JSON output" section to the root command's help, man page, and generated skills, so an agent reading the CLI's documentation knows what --json prints.

Behavior

With --json, stdout carries only JSON: the command's result, or NDJSON for streaming commands. Pipes and files always get clean data.

  • The Command Action's return value is printed to stdout as one line of JSON. An action that returns undefined prints nothing.
  • A failure is written to stderr as one line of JSON instead of the Error: line. A CrustError prints its toJSON() ({ "code", "message", "details"? }); any other error prints { "message": error.message }, and a thrown non-Error value prints { "message": String(value) }. No other field of an application error is read, except that @crustjs/openapi's ApiResponseError adds details with the HTTP status.
  • The action's and Contexts' stderr() lines, spinners, and progress go to stderr as they're written.
  • Cleanup that fails after a failure was already written, such as a Context whose disposal throws, or while a cancellation unwinds, is written to stderr as one more line per failed cleanup, {"type":"cleanup","error":…}, with the same error JSON. It goes to stderr even for a generator action, so stdout keeps exactly one final line.
  • Exit codes are unchanged.

Text printed with stdout()

What happens to the text a command prints with stdout() depends on whether it declares .output():

CommandUnder --json, its stdout() text…stderr
declares .output() and returns datais dropped, because the JSON is the same datano duplicate text
declares .output(), returns nothing, fails or is cancelledis written to stderr when the command endsthe text, then any error JSON
no .output()moves to stderr as it's printed (live)the text

A command that declares .output() returns data, so its result replaces the table it prints for people:

users.ts
const users = defineCommand("users", { description: "List users" }, (cmd) =>
	cmd
		.output(z.array(z.object({ id: z.number(), name: z.string() })))
		.action(({ stdout }) => {
			const rows = [
				{ id: 1, name: "Ada" },
				{ id: 2, name: "Linus" },
			];
			stdout("ID  NAME");
			for (const row of rows) stdout(`${row.id}   ${row.name}`);
			return rows;
		}),
);
$ my-cli users --json
[{"id":1,"name":"Ada"},{"id":2,"name":"Linus"}]   # stdout; nothing on stderr

If users returned nothing, failed, or was cancelled, its table would be written to stderr when it ended, followed by any error JSON:

$ my-cli users --json
ID  NAME                         # stderr
1   Ada                          # stderr
{"message":"connection reset"}   # stderr

deploy in Usage has no .output(), so Deploying... moves to stderr as it's printed. This includes output a Context writes, even while another Extension's setup pulls it. Output an Extension writes with its own stdout, such as --help, is never moved.

Write progress and instructions that must appear while the command runs (for example a login URL) with stderr() or a spinner. They're always live:

login.ts
const login = defineCommand("login", { description: "Log in" }, (cmd) =>
	cmd.output(z.object({ user: z.string() })).action(async ({ stderr }) => {
		// stderr() is always live, so the user sees this while the command waits.
		stderr("Open https://example.com/device and enter ABCD-1234");
		return { user: await waitForApproval() };
	}),
);

stdout vs stderr

A terminal shows both streams, so a person running my-cli users --json sees everything. Pipes, >, and agents read only stdout: my-cli users --json | jq '.[0].name' and my-cli users --json > users.json get just the JSON, while stderr still goes to the terminal. That's why data goes to stdout and messages for people go to stderr.

The result must be JSON data: finite numbers, strings, booleans, null, and plain arrays and objects of them. A result JSON cannot represent exactly, such as a BigInt, a cycle, a function, -0, or a class instance like Date or Map, fails the command with exit code 1 and an error naming the problem. Convert such values before returning them, for example date.toISOString().

Generator actions

An async generator action streams newline-delimited JSON (NDJSON) on stdout instead, so a consumer reads one channel line by line:

$ tool sync --json
{"type":"event","data":{"file":"a.txt"}}   # written as the action yields
{"type":"event","data":{"file":"b.txt"}}
{"type":"result","data":{"synced":2}}
  • Each yielded value prints as {"type":"event","data":…} as soon as it is yielded.
  • The stream ends with exactly one {"type":"result","data":…} line for the return value, even when it is undefined (the line then has no data), or, if the command fails after the action started, one {"type":"error","error":…} line with the same error JSON as above. That failure is not also written to stderr.
  • Events and the result must be JSON data, as above; one that is not, including a yielded undefined, fails the command with an error line. Only an undefined result is allowed.
  • In a command that declares .output(), its stdout() text is dropped once the result line carries data, and written to stderr for an undefined result or a failure, as above.
  • A failure before the action started, such as a validation error, prints stderr JSON as for any other action. A failure after the result line, such as a Context cleanup failure, also goes to stderr, so stdout never has two final lines.

An ordinary action keeps the bare result line.

Under run()

Pass { flags: { json: true } } to run():

  • outcome.stdout holds the JSON result. For a generator action, it holds the event lines and the result line, but no error line.
  • A failure is not rendered; read it from outcome.error.
  • For a command that declares .output() and returns data, outcome.stdout holds only the JSON and outcome.stderr none of its stdout() text.

Limitations

  • json() sets the invocation's renderer. An application can have only one, so json() can't be combined with another Extension that sets .renderer().
  • Failures before flags are bound print as plain text, because --json is not yet known: unknown commands under a parent without a Command Action, and argv syntax errors such as an unknown flag or a flag missing its value. execute() prints Core's default Error: line for them. A failure in an Extension's setup, such as an invalid --input, comes after binding and is JSON.
  • If another Extension's onError hook claims a failure, it keeps that Extension's format, and a generator action's stream ends without a final line.
  • A cancelled invocation (exit code 130, or 143 after SIGTERM) is not rendered, so its stream also ends without a final line.

On this page