Files
hyperframes/packages/cli/src/utils/commandResult.ts
T
wonjangandClaude Fable 5.2 47d007e5b0 fix(cli): render --json gives each missing tool, a held slot and an old Node its own code (#7842)
* fix(cli): render --json gives each missing tool, a held slot and an old Node its own code

Every failed `render --json` answered with `error.code: "runtime_error"`, so a
script could only tell a missing FFmpeg from a busy render slot by matching the
human message. A CliRuntimeError now carries a code, as CliUsageError does, and
the envelope reports it: chrome_not_found, ffmpeg_not_found, ffprobe_not_found,
render_locked. A Node older than 22 prints the envelope too
(node_version_unsupported) when the run asked for --json. Other failures keep
runtime_error.

Refs #7408

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(cli): give the bin entry test's runtimeVersion stub the new JSON export

bin/hyperframes.mjs now imports runtimeVersionJson, so the stub dist file
binEntry.test.ts writes must export it too, or the bin fails to load.

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 18:16:11 +00:00

187 lines
5.4 KiB
TypeScript

export type CommandResultKind = "success" | "usage_error" | "runtime_error";
export interface CommandResult {
exitCode: number;
kind: CommandResultKind;
/** The command already emitted its structured/human output. */
presented?: boolean;
}
const SUCCESS_RESULT: CommandResult = { exitCode: 0, kind: "success" };
let pendingResult: CommandResult = SUCCESS_RESULT;
let rootExitRequester: ((exitCode: number) => void) | undefined;
let rootExitCodeSanitizer: (() => void) | undefined;
export const USAGE_EXIT_CODE = 2;
export class CliUsageError extends Error {
readonly result: CommandResult;
readonly hint?: string;
readonly code: string;
constructor(
message = "Invalid command usage",
options: { exitCode?: number; presented?: boolean; hint?: string; code?: string } = {},
) {
super(message);
this.name = "CliUsageError";
this.hint = options.hint;
this.code = options.code ?? "usage_error";
this.result = {
exitCode: options.exitCode ?? USAGE_EXIT_CODE,
kind: "usage_error",
presented: options.presented,
};
}
}
export class CliRuntimeError extends Error {
readonly result: CommandResult;
readonly code: string;
constructor(
message = "Command failed",
options: { exitCode?: number; presented?: boolean; cause?: unknown; code?: string } = {},
) {
super(message, options.cause === undefined ? undefined : { cause: options.cause });
this.name = "CliRuntimeError";
this.code = options.code ?? "runtime_error";
this.result = {
exitCode: options.exitCode ?? 1,
kind: "runtime_error",
presented: options.presented,
};
}
}
/** Internal control-flow signal for an early, already-presented result. */
export class CliResultSignal extends Error {
readonly result: CommandResult;
constructor(result: CommandResult) {
super(`CLI result ${result.exitCode}`);
this.name = "CliResultSignal";
this.result = result;
}
}
export function failCommand(exitCode = 1, cause?: unknown, code?: string): never {
throw new CliRuntimeError("Command failed", { exitCode, presented: true, cause, code });
}
export function failUsage(exitCode = USAGE_EXIT_CODE): never {
throw new CliUsageError("Invalid command usage", { exitCode, presented: true });
}
let firstFailureStack: string | undefined;
const noteFailure = (exitCode: number) => {
if (exitCode !== 0) firstFailureStack ??= new Error("the run failed here").stack;
};
export const failureOrigin = (): string | undefined => firstFailureStack;
export function finishCommand(exitCode = 0): never {
noteFailure(exitCode);
throw new CliResultSignal({
exitCode,
kind: exitCode === 0 ? "success" : "runtime_error",
presented: true,
});
}
/** Record a non-fatal result while allowing output/finalizers to complete. */
export function setCommandResult(result: CommandResult): void {
noteFailure(result.exitCode);
if (pendingResult.exitCode !== 0 && result.exitCode === 0) return;
pendingResult = result;
}
export function setCommandExitCode(exitCode: number): void {
setCommandResult({
exitCode,
kind: exitCode === 0 ? "success" : "runtime_error",
presented: true,
});
}
export function consumeCommandResult(): CommandResult {
const result = pendingResult;
pendingResult = SUCCESS_RESULT;
return result;
}
/** Called only by cli.ts to retain ownership of forced process termination. */
export function registerRootExitRequester(requester: (exitCode: number) => void): void {
rootExitRequester = requester;
}
/** Called only by cli.ts to retain ownership of process exit-code mutation. */
export function registerRootExitCodeSanitizer(sanitizer: () => void): void {
rootExitCodeSanitizer = sanitizer;
}
/** Ask cli.ts to clear stray process exit state after a successful render. */
export function sanitizeSuccessfulExitCode(): void {
rootExitCodeSanitizer?.();
}
export async function outputWritten(): Promise<void> {
const written = (stream: NodeJS.WriteStream) =>
new Promise<void>((resolve) => stream.write("", () => resolve()));
await Promise.all([written(process.stdout), written(process.stderr)]);
}
let drainsToExit = false;
const DRAIN_GRACE_MS = 8_000;
export function drainToExit(): void {
drainsToExit = true;
}
export interface ProcessEnd {
exit(exitCode: number): void;
setExitCode(exitCode: number): void;
later: typeof setTimeout;
}
export function endProcess(exitCode: number, host: ProcessEnd): void {
if (!drainsToExit) return host.exit(exitCode);
host.setExitCode(exitCode);
host.later(() => host.exit(exitCode), DRAIN_GRACE_MS).unref();
}
/** Ask cli.ts to finalize telemetry/output and then terminate the process. */
export function requestCliExit(exitCode = 0): void {
noteFailure(exitCode);
if (!rootExitRequester) {
setCommandResult({
exitCode,
kind: exitCode === 0 ? "success" : "runtime_error",
presented: true,
});
return;
}
rootExitRequester(exitCode);
}
type UnrefableTimer = {
unref: () => void;
};
function isUnrefableTimer(
timer: ReturnType<typeof setTimeout>,
): timer is ReturnType<typeof setTimeout> & UnrefableTimer {
return (
typeof timer === "object" &&
timer !== null &&
"unref" in timer &&
typeof timer.unref === "function"
);
}
/** For a command whose result is out: ends the process if anything it started is still holding it. */
export function scheduleCliExit(exitCode = 0): void {
const timer = setTimeout(() => requestCliExit(exitCode), 100);
if (isUnrefableTimer(timer)) timer.unref();
}