diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 8204f192c0..63d510ea11 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -82,6 +82,9 @@ here: the `Unknown command:` line and the suggestion under it, the the `measure ` shortcut prints. Other lines a command prints are as they were. `--json` output is not changed by this. +When a `--json` run fails, the `error.message` it answers with carries a repeated +value as it was given, not in the visible-text form; `lambda`, `cloudrun` and +`beats` do this too. **`--json` for agents and scripts.** Most commands accept it, before or after the command name: `hyperframes --json info` is the same run as diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts index b2678df00b..a4c2aa5dff 100644 --- a/packages/cli/src/cli.lifecycle.test.ts +++ b/packages/cli/src/cli.lifecycle.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; @@ -31,6 +31,37 @@ afterEach(async () => { const PLAIN = "(no --json)"; +async function answersWithItsTextAsGiven(argv: string[], given: string, exit: number) { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + let answered = ""; + const outSpy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => { + answered += String(chunk); + return true; + }) as never); + try { + mockTelemetry(); + process.argv = ["node", "cli.ts", ...argv, "--json"]; + await import("./cli.js"); + + const said = errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain(given.replace("\u0007", "\\x07")); + expect(said).not.toContain("\u0007"); + const body = JSON.parse(answered.trim().split("\n").at(-1) ?? "") as { + ok: boolean; + error: { message: string }; + }; + expect(body.ok).toBe(false); + expect(process.exitCode).toBe(exit); + expect(body.error.message).toContain(given); + expect(body.error.message).not.toContain("\\x07"); + } finally { + outSpy.mockRestore(); + errorSpy.mockRestore(); + exitSpy.mockRestore(); + } +} + describe("CLI lifecycle", () => { it("queues a command failure before exit, without waiting on a network flush", async () => { let resolveEvents!: (events: { @@ -477,6 +508,104 @@ describe("CLI lifecycle", () => { } }); + // fails without the fix: the envelope's message was the line as people see it, escapes included. + it.each([ + [ + "an unknown lambda subcommand", + ["lambda", "de\u0007ploy"], + "Unknown subcommand: de\u0007ploy", + 2, + ], + ["an unknown lambda sites verb", ["lambda", "sites", "cr\u0007eate"], 'verb "cr\u0007eate"', 2], + [ + "a lambda stack with no state", + ["lambda", "progress", "r1", "--stack-name", "st\u0007ack"], + 'no stack state for "st\u0007ack"', + 1, + ], + [ + "an unknown cloudrun subcommand", + ["cloudrun", "de\u0007ploy"], + "Unknown subcommand: de\u0007ploy", + 2, + ], + [ + "an unknown cloudrun sites verb", + ["cloudrun", "sites", "cr\u0007eate"], + 'verb "cr\u0007eate"', + 2, + ], + [ + "a missing cloudrun batch file", + [ + "cloudrun", + "render-batch", + ".", + "--batch", + "ba\u0007tch.jsonl", + "--width", + "8", + "--height", + "8", + ], + "batch file not found: ba\u0007tch.jsonl", + 1, + ], + ])("answers a --json run for %s with its text as given", async (_name, argv, given, exit) => { + await answersWithItsTextAsGiven(argv, given, exit); + }); + + const STACK = { + stackName: "other", + region: "us-east-1", + bucketName: "some-bucket", + stateMachineArn: "arn:aws:states:us-east-1:123456789012:stateMachine:render", + functionName: "render", + lambdaMemoryMb: 1024, + }; + const stackFile = (dir: string, text: string) => { + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(join(dir, ".hyperframes", "lambda-stack-st\u0007ack.json"), text); + }; + const LAMBDA_PROGRESS = ["lambda", "progress", "r1", "--stack-name", "st\u0007ack"]; + + // fails without the fix: the envelope's message was the line as people see it, escapes included. + // A control character in a file name is refused on Windows. + it.skipIf(process.platform === "win32").each([ + [ + "a lambda stack file that cannot be read", + (dir: string) => stackFile(dir, "{"), + LAMBDA_PROGRESS, + "lambda-stack-st\u0007ack.json is not valid JSON", + ], + [ + "a lambda stack file that names another stack", + (dir: string) => stackFile(dir, JSON.stringify(STACK)), + LAMBDA_PROGRESS, + 'names stack "other", not "st\u0007ack"', + ], + [ + "a beats run whose music file is missing", + (dir: string) => + writeFileSync( + join(dir, "index.html"), + '
', + ), + ["beats"], + "Audio file not found: mu\u0007sic.mp3", + ], + ])("answers a --json run for %s with its text as given", async (_name, write, argv, given) => { + const dir = mkdtempSync(join(tmpdir(), "hf-cli-given-")); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + try { + write(dir); + await answersWithItsTextAsGiven(argv, given, 1); + } finally { + cwd.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); + // fails without the fix: the envelope's message was the line as people see it, escapes included. it("answers a --json run for a missing file with the file's name as given", async () => { const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); diff --git a/packages/cli/src/commands/beats.ts b/packages/cli/src/commands/beats.ts index 0831b0d7ac..544efec7e8 100644 --- a/packages/cli/src/commands/beats.ts +++ b/packages/cli/src/commands/beats.ts @@ -12,7 +12,8 @@ import { } from "@hyperframes/core/beats"; import { parseHTMLContent } from "@hyperframes/core/compiler"; import { walkCompositionDescendants } from "@hyperframes/parsers"; -import { isSafePath, resolveWithinProject, terminalLines, terminalText } from "@hyperframes/core"; +import { isSafePath, resolveWithinProject, terminalText } from "@hyperframes/core"; +import { printFailureLine } from "../utils/jsonError.js"; import type { Example } from "./_examples.js"; import { resolveProject, type ProjectDir } from "../utils/project.js"; import type { AudioSignal } from "@hyperframes/core/audio-analysis"; @@ -26,7 +27,7 @@ export const examples: Example[] = [ ]; function fail(message: string): never { - console.error(c.error(terminalLines(message))); + printFailureLine((show) => c.error(show(message))); failCommand(); } diff --git a/packages/cli/src/commands/cloudrun.ts b/packages/cli/src/commands/cloudrun.ts index cdea64354f..92ab977e14 100644 --- a/packages/cli/src/commands/cloudrun.ts +++ b/packages/cli/src/commands/cloudrun.ts @@ -22,6 +22,7 @@ import { type CanvasResolution, terminalLines, terminalText } from "@hyperframes import { parseOutputResolutionFlag } from "../utils/parseOutputResolution.js"; import type { Example } from "./_examples.js"; import { c } from "../ui/colors.js"; +import { printFailureLine } from "../utils/jsonError.js"; import { reportVariableIssues, resolveVariablesArg, @@ -258,7 +259,9 @@ export default defineCommand({ case "destroy": return runDestroy(args); default: - console.error(`${c.error("Unknown subcommand:")} ${terminalText(subcommand)}\n${HELP}`); + printFailureLine( + (show) => `${c.error("Unknown subcommand:")} ${show(subcommand)}\n${HELP}`, + ); failUsage(); } }, @@ -497,8 +500,9 @@ function writeCloudBuildConfig(image: string): string { // fallow-ignore-next-line complexity async function runSites(args: Record): Promise { if (args.target !== "create") { - console.error( - `[cloudrun sites] unknown verb "${terminalText(String(args.target))}". Only "create" is supported.`, + printFailureLine( + (show) => + `[cloudrun sites] unknown verb "${show(String(args.target))}". Only "create" is supported.`, ); failUsage(); } @@ -671,7 +675,7 @@ async function runRenderBatch(args: Record): Promise { const fps = resolveCloudRunFps(args, projectDir, "render-batch"); buildRenderConfig(args, fps, width, height, undefined); if (!existsSync(resolve(batchPath))) { - console.error(`[cloudrun render-batch] batch file not found: ${terminalText(batchPath)}`); + printFailureLine((show) => `[cloudrun render-batch] batch file not found: ${show(batchPath)}`); failCommand(); } const entries = parseBatchFile(resolve(batchPath)); diff --git a/packages/cli/src/commands/lambda.ts b/packages/cli/src/commands/lambda.ts index 21fb0abdcd..a1999d5d65 100644 --- a/packages/cli/src/commands/lambda.ts +++ b/packages/cli/src/commands/lambda.ts @@ -16,7 +16,7 @@ import { parseOutputResolutionFlag } from "../utils/parseOutputResolution.js"; import type { Example } from "./_examples.js"; import type { VideoArch } from "./lambda/videoImage.js"; import { c } from "../ui/colors.js"; -import { terminalText } from "@hyperframes/core"; +import { printFailureLine } from "../utils/jsonError.js"; import { deliveryFlagArgs, parseDeliveryFlags } from "../utils/deliveryFlags.js"; import { defaultCloudFps } from "../utils/compositionFps.js"; import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; @@ -289,8 +289,9 @@ export default defineCommand({ } case "sites": { if (args.target !== "create") { - console.error( - `[lambda sites] unknown verb "${terminalText(String(args.target))}". Only "create" is supported.`, + printFailureLine( + (show) => + `[lambda sites] unknown verb "${show(String(args.target))}". Only "create" is supported.`, ); failUsage(); } @@ -455,7 +456,9 @@ export default defineCommand({ return; } default: - console.error(`${c.error("Unknown subcommand:")} ${terminalText(subcommand)}\n${HELP}`); + printFailureLine( + (show) => `${c.error("Unknown subcommand:")} ${show(subcommand)}\n${HELP}`, + ); failUsage(); } }, diff --git a/packages/cli/src/commands/lambda/state.ts b/packages/cli/src/commands/lambda/state.ts index c837c5ed11..37e0e94cf5 100644 --- a/packages/cli/src/commands/lambda/state.ts +++ b/packages/cli/src/commands/lambda/state.ts @@ -1,5 +1,5 @@ import { failCommand } from "../../utils/commandResult.js"; -import { terminalText } from "@hyperframes/core"; +import { printFailureLine } from "../../utils/jsonError.js"; /** * Persists `hyperframes lambda` stack outputs (bucket, state-machine ARN, * region) so `render` / `progress` / `destroy` don't need to re-derive @@ -155,22 +155,24 @@ export function requireStack(stackName: string, cwd: string = process.cwd()): St const path = stateFilePath(stackName, cwd); const deploy = `Run \`hyperframes lambda deploy${stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${stackName}`}\``; if (typeof stack === "string") { - console.error(terminalText(`[hyperframes lambda] ${path} ${stack}. ${deploy} to rewrite it.`)); + printFailureLine((show) => + show(`[hyperframes lambda] ${path} ${stack}. ${deploy} to rewrite it.`), + ); failCommand(); } if (!stack) { const known = listStackNames(cwd); const hint = known.length ? ` Known stacks here: ${known.join(", ")}.` : ""; - console.error( - terminalText( + printFailureLine((show) => + show( `[hyperframes lambda] no stack state for "${stackName}" at ${path}. ${deploy} first.${hint}`, ), ); failCommand(); } if (!sameFileOnCaseInsensitiveDisk(String(stack.stackName), stackName)) { - console.error( - terminalText( + printFailureLine((show) => + show( `[hyperframes lambda] ${path} names stack "${stack.stackName}", not "${stackName}". ${deploy} to rewrite it.`, ), );