diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts index 71b6e8443d..4046714992 100644 --- a/packages/cli/src/cli.lifecycle.test.ts +++ b/packages/cli/src/cli.lifecycle.test.ts @@ -508,6 +508,51 @@ describe("CLI lifecycle", () => { } }); + // fails without the fix: the envelope's message was the line as people see it, escapes included. + it.each([ + [ + "a capture URL that does not parse", + ["capture", "ht tp\u0007"], + "Invalid URL: ht tp\u0007", + 2, + ], + [ + "a capture --video folder with no manifest", + ["capture", "--video", join(tmpdir(), "hf-no\u0007ne")], + `no video-manifest.json at ${join(tmpdir(), "hf-no\u0007ne", "extracted")}`, + 1, + ], + ])("answers a --json run for %s with the value as given", async (_name, argv, given, exit) => { + 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(); + } + }); + it("exits 1 and scores a failure when the pipe closes before the run delivered", async () => { const trackCommandResult = vi.fn(); const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); diff --git a/packages/cli/src/commands/capture.test.ts b/packages/cli/src/commands/capture.test.ts index 81c83f02c6..68f9f9e6bc 100644 --- a/packages/cli/src/commands/capture.test.ts +++ b/packages/cli/src/commands/capture.test.ts @@ -455,3 +455,58 @@ describe("capture command — vision control", () => { }, ); }); + +describe("capture command: what it prints", () => { + afterEach(() => { + captureWebsiteMock.mockClear(); + vi.restoreAllMocks(); + }); + + const printed = (spy: { mock: { calls: unknown[][] } }): string => + spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + + // fails without the fix: the address was printed as given + it("shows control characters in a refused address as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + + await expect( + captureCommand.run!({ args: { url: "not a url\u0007\u001b[2J" } } as never), + ).rejects.toBeInstanceOf(CliUsageError); + + expect(printed(error)).toBe("Invalid URL: not a url\\x07\\x1b[2J"); + }); + + // fails without the fix: the address and the output folder were printed as given + it("shows control characters in the address and output folder of a finished run as text", async () => { + vi.useFakeTimers(); + registerRootExitRequester(() => {}); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + captureWebsiteMock.mockResolvedValueOnce({ + ok: true, + projectDir: "/tmp/capture", + url: "https://example.com", + title: "Example", + extracted: {}, + screenshots: [], + tokens: { sections: [], fonts: [] }, + assets: [], + dropped: {}, + warnings: [] as string[], + } as never); + + try { + await captureCommand.run!({ + args: { url: "https://example.com/a\u0007b", output: "/tmp/hf-capture\u001b[2Jout" }, + } as never); + } finally { + vi.useRealTimers(); + } + + const text = printed(log); + expect(text).toContain("Capturing https://example.com/a\\x07b"); + // The folder is printed as a full path, whose root and separators differ by platform. + expect(text).toMatch(/Captured Example → \S*hf-capture\\x1b\[2Jout/); + expect(text).not.toContain("\u0007"); + expect(text).not.toContain("\u001b[2J"); + }); +}); diff --git a/packages/cli/src/commands/capture.ts b/packages/cli/src/commands/capture.ts index 912a90f5fe..479804d9a0 100644 --- a/packages/cli/src/commands/capture.ts +++ b/packages/cli/src/commands/capture.ts @@ -7,7 +7,7 @@ import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { diag } from "../ui/diagnostics.js"; import type { CapturePhaseProgress } from "../capture/types.js"; import { parseCaptureDeadline } from "../capture/captureWatchdog.js"; -import { jsonFailure } from "../utils/jsonError.js"; +import { jsonFailure, printFailureLine } from "../utils/jsonError.js"; import { terminalLines, terminalText } from "@hyperframes/core"; import { parseTimeoutMs } from "../utils/timeoutArg.js"; @@ -135,7 +135,7 @@ export default defineCommand({ try { captureUpstreamProxy(); } catch (error) { - console.error(terminalLines(normalizeErrorMessage(error))); + printFailureLine((show) => show(normalizeErrorMessage(error))); failCommand(); } @@ -162,7 +162,7 @@ export default defineCommand({ try { url = resolveLocalCaptureTarget(localFile, localRoot).fileUrl; } catch (err) { - console.error(terminalLines(normalizeErrorMessage(err))); + printFailureLine((show) => show(normalizeErrorMessage(err))); failCommand(); } } else { @@ -179,7 +179,7 @@ export default defineCommand({ try { new URL(url); } catch { - console.error(`Invalid URL: ${url}`); + printFailureLine((show) => `Invalid URL: ${show(String(url))}`); failUsage(); } } @@ -220,7 +220,7 @@ export default defineCommand({ if (!isJson) { const { c } = await import("../ui/colors.js"); console.log(); - console.log(c.dim("◆") + " Capturing " + c.bold(url)); + console.log(c.dim("◆") + " Capturing " + c.bold(terminalText(url))); if (isDefaultOutput && outputName !== "capture") { console.log(` ${c.dim(`(./capture/ exists; writing to ./${outputName}/)`)}`); } @@ -297,7 +297,8 @@ export default defineCommand({ const icon = result.ok ? c.success("◇") : c.error("✗"); const status = result.ok ? "Captured" : "Capture failed"; console.log( - icon + ` ${status} ${c.bold(terminalText(result.title))} → ${c.dim(outputDir)}`, + icon + + ` ${status} ${c.bold(terminalText(result.title))} → ${c.dim(terminalText(outputDir))}`, ); console.log(); console.log(` ${c.dim("Screenshots:")} ${result.screenshots.length}`); diff --git a/packages/cli/src/commands/capture/video.test.ts b/packages/cli/src/commands/capture/video.test.ts index 46223a0f7c..ac46f52780 100644 --- a/packages/cli/src/commands/capture/video.test.ts +++ b/packages/cli/src/commands/capture/video.test.ts @@ -237,3 +237,43 @@ describe("runVideoMode --list", () => { expect(printed).toContain("a\\x1b]8;;https://x.test\\x07.mp4"); }); }); + +describe("runVideoMode: the project folder in what it prints", () => { + const bell = String.fromCharCode(7); + + it("shows control characters in a folder with no manifest as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + onTestFinished(() => error.mockRestore()); + + await runVideoMode({ project: join(tmpdir(), `hf-missing${bell}dir`), list: true }); + + expect(consumeCommandResult().exitCode).toBe(1); + const printed = error.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).not.toContain(bell); + expect(printed.match(/hf-missing\\x07dir/g)).toHaveLength(2); + }); + + // Windows does not allow a control character in a folder name. + it.skipIf(process.platform === "win32")( + "shows control characters in the manifest path of a listing as text", + async () => { + const root = mkdtempSync(join(tmpdir(), "hf-video-path-")); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const projectDir = join(root, `site${bell}one`); + mkdirSync(join(projectDir, "extracted"), { recursive: true }); + writeFileSync( + join(projectDir, "extracted", "video-manifest.json"), + JSON.stringify([ENTRY(0)]), + ); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + onTestFinished(() => log.mockRestore()); + + await runVideoMode({ project: projectDir, list: true }); + + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).not.toContain(bell); + expect(printed).toContain("1 video entry in "); + expect(printed).toContain("site\\x07one"); + }, + ); +}); diff --git a/packages/cli/src/commands/capture/video.ts b/packages/cli/src/commands/capture/video.ts index e8ae88300d..0e10241a5d 100644 --- a/packages/cli/src/commands/capture/video.ts +++ b/packages/cli/src/commands/capture/video.ts @@ -6,6 +6,7 @@ import { safeFetch } from "../../capture/assetDownloader.js"; import { ensureCaptureDirSync } from "../../capture/captureFile.js"; import { CAPTURE_USER_AGENT } from "../../capture/userAgent.js"; import { terminalText } from "@hyperframes/core"; +import { printFailureLine } from "../../utils/jsonError.js"; const MAX_VIDEO_BYTES = 250 * 1024 * 1024; const VIDEO_CONTENT_TYPE_RE = /^(video\/|application\/(mp4|octet-stream|x-mpegurl))/i; @@ -198,8 +199,9 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const manifestPath = existsSync(directPath) ? directPath : w2hPath; const isW2hLayout = manifestPath === w2hPath; if (!existsSync(manifestPath)) { - console.error( - `${c.error("✗")} no video-manifest.json at ${directPath} or ${w2hPath}\n` + + printFailureLine( + (show) => + `${c.error("✗")} no video-manifest.json at ${show(directPath)} or ${show(w2hPath)}\n` + ` Was this directory produced by \`hyperframes capture\`?`, ); setCommandExitCode(1); @@ -209,8 +211,8 @@ export async function runVideoMode(args: VideoModeArgs): Promise { try { manifest = JSON.parse(readFileSync(manifestPath, "utf-8")); } catch (e) { - console.error( - `${c.error("✗")} video-manifest.json is malformed: ${shown((e as Error).message)}`, + printFailureLine( + (show) => `${c.error("✗")} video-manifest.json is malformed: ${show((e as Error).message)}`, ); setCommandExitCode(1); return; @@ -222,7 +224,7 @@ export async function runVideoMode(args: VideoModeArgs): Promise { return; } console.log( - `${manifest.length} video entr${manifest.length === 1 ? "y" : "ies"} in ${manifestPath}:`, + `${manifest.length} video entr${manifest.length === 1 ? "y" : "ies"} in ${shown(manifestPath)}:`, ); for (const e of manifest) { console.log( @@ -236,8 +238,9 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const pick = pickManifestEntry(manifest, args); if (!pick.ok) { - console.error( - `${c.error("✗")} ${shown(pick.message)}` + + printFailureLine( + (show) => + `${c.error("✗")} ${show(pick.message)}` + (pick.code === "no-match-url" ? `\n Run with --list to see what's available.` : ""), ); setCommandExitCode(1); @@ -247,10 +250,11 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const collisions = findFilenameCollision(manifest, entry); if (collisions.length > 0) { - console.error( - `${c.error("✗")} filename "${safeFilename(entry.filename || basename(entry.url))}" ` + + printFailureLine( + (show) => + `${c.error("✗")} filename "${safeFilename(entry.filename || basename(entry.url))}" ` + `collides with manifest entr${collisions.length === 1 ? "y" : "ies"} ` + - `${collisions.map((co) => `[${shown(co.index)}]`).join(", ")}. ` + + `${collisions.map((co) => `[${show(String(co.index))}]`).join(", ")}. ` + `Refusing to download — the on-disk file's bytes would not match the requested entry.`, ); setCommandExitCode(1); @@ -263,7 +267,7 @@ export async function runVideoMode(args: VideoModeArgs): Promise { try { ensureCaptureDirSync(projectDir, outDir); } catch (e) { - console.error(`${c.error("✗")} ${terminalText((e as Error).message)}`); + printFailureLine((show) => `${c.error("✗")} ${show((e as Error).message)}`); setCommandExitCode(1); return; } @@ -292,7 +296,7 @@ export async function runVideoMode(args: VideoModeArgs): Promise { return; } const message = (e as Error).message.replace(/\r/g, "").replace(/\n/g, ""); - console.error(`${c.error("✗")} download failed: ${shown(message)}`); + printFailureLine((show) => `${c.error("✗")} download failed: ${show(message)}`); setCommandExitCode(1); } } diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index f731c61781..5e9fff6d3a 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -927,6 +927,38 @@ it("prints composition text in a finding with its control characters as visible expect(out).toContain("Fix: use \\x1b]52;c;Y2xpcA==\\x07"); }); +it("prints a replayed pass's time and finding code with control characters as visible escapes", async () => { + const planted: CheckFinding = { + code: "audio_quiet\u0007", + severity: "warning", + message: "voice.wav is quiet", + selector: "#v", + dataAttributes: {}, + sourceFile: "scene.html", + bbox: { x: 0, y: 0, width: 0, height: 0 }, + time: 1, + }; + const { report } = await runScenario( + fakeDriver(), + {}, + { inspectAudio: vi.fn(async () => [planted]) }, + ); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const command = createCheckCommand({ + resolveProject: () => PROJECT, + runPipeline: vi.fn(async () => ({ ...report, cached: { at: "2026-01-02\u001b[2J" } })), + prepareMedia: vi.fn(async () => []), + withMeta: (value) => value, + }); + + await runCommand(command, { rawArgs: [] }).catch(() => undefined); + + const out = log.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + for (const control of ["\u0007", "\u001b[2J"]) expect(out).not.toContain(control); + expect(out).toContain("since the pass at 2026-01-02\\x1b[2J;"); + expect(out).toContain("audio_quiet\\x07: voice.wav is quiet"); +}); + it("prints a contrast finding's selector, colour and source with control characters escaped", async () => { const planted: CheckContrastFinding = { code: "contrast_aa_failure", diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 118f1a8c74..9a4bcd0940 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -784,7 +784,7 @@ function browserSkippedLine(report: CheckReport): string { function printHumanReport(report: CheckReport): void { if (report.cached) console.log( - `${c.dim("◇")} Nothing changed since the pass at ${report.cached.at}; showing that result. Remote scripts and assets were not fetched again. Run with --no-cache to check again.`, + `${c.dim("◇")} Nothing changed since the pass at ${terminalText(report.cached.at)}; showing that result. Remote scripts and assets were not fetched again. Run with --no-cache to check again.`, ); if (report.scope) { console.log( @@ -902,7 +902,9 @@ function printSnapshotSection(report: CheckReport): void { function printFinding(finding: CheckFinding): void { const where = `${terminalText(finding.sourceFile)} ${terminalText(finding.selector)} ${formatFindingTimes(finding)}`; - console.log(` ${findingIcon(finding)} ${finding.code}: ${terminalText(finding.message)}`); + console.log( + ` ${findingIcon(finding)} ${terminalText(finding.code)}: ${terminalText(finding.message)}`, + ); console.log(` ${c.dim(where)}`); if (finding.fixHint) console.log(` ${c.dim(`Fix: ${terminalText(finding.fixHint)}`)}`); } diff --git a/packages/cli/src/commands/keyframes.ts b/packages/cli/src/commands/keyframes.ts index 9eb21f3c7f..b865b808b0 100644 --- a/packages/cli/src/commands/keyframes.ts +++ b/packages/cli/src/commands/keyframes.ts @@ -885,7 +885,7 @@ function onionShotOptions(args: ShotArgs & { selector?: string }) { } function printOnionShotSaved(saved: string, elementCount: number): void { - console.log(`${c.success("◇")} onion-skin screenshot saved ${c.accent(saved)}`); + console.log(`${c.success("◇")} onion-skin screenshot saved ${c.accent(terminalText(saved))}`); console.log( c.dim( ` ${elementCount} element${elementCount === 1 ? "" : "s"} · open it to verify the motion matches your target, then read the keyframes below.`, diff --git a/packages/cli/src/commands/media-use/generate.output.test.ts b/packages/cli/src/commands/media-use/generate.output.test.ts new file mode 100644 index 0000000000..d61fad8182 --- /dev/null +++ b/packages/cli/src/commands/media-use/generate.output.test.ts @@ -0,0 +1,26 @@ +import { afterEach, expect, it, vi } from "vitest"; + +// Built rather than written: a literal control character in the source is a lint error. +const bell = String.fromCharCode(7); + +vi.mock("../../heygen/generate.js", async (orig) => ({ + ...(await orig()), + generate: async (request: { out: string }, onWait?: (status: string) => void) => { + onWait?.(`processing${bell}`); + return { out: request.out }; + }, +})); + +const { default: generate } = await import("./generate.js"); + +afterEach(() => vi.restoreAllMocks()); + +it("shows control characters in the job status the service reports as text", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const args = { type: "image", prompt: "a cup", out: "cup.png", "max-credits": "500" }; + + await generate.run!({ args, rawArgs: [] } as never); + + expect(error.mock.calls).toEqual([["generate: processing\\x07…"]]); +}); diff --git a/packages/cli/src/commands/media-use/generate.ts b/packages/cli/src/commands/media-use/generate.ts index f78c15ba73..3c1a413289 100644 --- a/packages/cli/src/commands/media-use/generate.ts +++ b/packages/cli/src/commands/media-use/generate.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { defineCommand } from "../../utils/defineCommand.js"; import type { Example } from "../_examples.js"; import { jsonArg, num, runMeasure } from "../../measure/command.js"; @@ -199,7 +200,7 @@ export default defineCommand({ checkLimit(credits, num(args["max-credits"], "--max-credits"), isVendorPriced(request)); const made = await generate( request, - (status) => console.error(`generate: ${status}…`), + (status) => console.error(`generate: ${terminalText(status)}…`), credits ?? undefined, ); return { ...made, price, credits, ...(voice ? { voice } : {}) }; diff --git a/packages/cli/src/commands/open.terminal.test.ts b/packages/cli/src/commands/open.terminal.test.ts index 07c859ee01..c6525364bd 100644 --- a/packages/cli/src/commands/open.terminal.test.ts +++ b/packages/cli/src/commands/open.terminal.test.ts @@ -5,10 +5,11 @@ import { runCommand } from "citty"; import { expect, it, vi } from "vitest"; import { consumeCommandResult } from "../utils/commandResult.js"; +const desktop = vi.hoisted(() => ({ app: "HyperFrames" })); vi.mock("../utils/desktopApp.js", async (importOriginal) => ({ ...(await importOriginal()), desktopInstalled: () => true, - openInDesktop: () => ({ opened: true, app: "HyperFrames", handedOver: null }), + openInDesktop: () => ({ opened: true, app: desktop.app, handedOver: null }), })); vi.mock("./previewLifecycle.js", async (importOriginal) => ({ ...(await importOriginal()), @@ -46,3 +47,23 @@ it.skipIf(process.platform === "win32")( } }, ); + +it("prints an app name with control characters as visible escapes", async () => { + const bell = String.fromCharCode(7); + const dir = mkdtempSync(join(tmpdir(), "hf-open-app-")); + writeFileSync(join(dir, "index.html"), ""); + desktop.app = `studio.nightly${bell}`; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + await runCommand(open, { rawArgs: [dir] }); + const human = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(human).not.toContain(bell); + expect(human).toContain("in studio.nightly\\x07"); + } finally { + desktop.app = "HyperFrames"; + log.mockRestore(); + consumeCommandResult(); + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts index e9b8ac9b55..7c2af15b9f 100644 --- a/packages/cli/src/commands/open.ts +++ b/packages/cli/src/commands/open.ts @@ -102,7 +102,7 @@ function printPreview(preview: PreviewBeforeOpen, opened: boolean): void { function printResult(project: ProjectDir, result: DesktopOpenResult): void { if (result.opened) { console.log( - `${c.success("◇")} Opening ${c.accent(terminalText(project.name))} in ${result.app}`, + `${c.success("◇")} Opening ${c.accent(terminalText(project.name))} in ${terminalText(result.app)}`, ); if (result.handedOver) { const agent = { claude: "Claude Code", codex: "Codex", grok: "Grok" }[ diff --git a/packages/cli/src/commands/previewLifecycle.test.ts b/packages/cli/src/commands/previewLifecycle.test.ts index 7d6e282661..639487cbc5 100644 --- a/packages/cli/src/commands/previewLifecycle.test.ts +++ b/packages/cli/src/commands/previewLifecycle.test.ts @@ -1587,3 +1587,27 @@ describe("where a preview's session is kept", () => { expect(readdirSync(state)).toEqual([]); }); }); + +describe("background preview log warning", () => { + it("shows control characters in a log path that cannot be opened as text", async () => { + const bell = String.fromCharCode(7); + // A file where the state folder should be, so the log's folder cannot be made. + const blocker = join(tempDir("hf-preview-state-"), "file"); + writeFileSync(blocker, ""); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + onTestFinished(() => warn.mockRestore()); + + await startBackgroundPreview(projectDir, 3002, { + forceNew: true, + scan: async () => [], + spawn: () => ({ pid: 5432, unref: vi.fn() }), + sleep: async () => {}, + stateHome: join(blocker, `state${bell}home`), + }).catch(() => {}); + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("background preview log not written: cannot open "); + expect(printed).toContain("state\\x07home"); + expect(printed).not.toContain(bell); + }); +}); diff --git a/packages/cli/src/commands/previewLifecycle.ts b/packages/cli/src/commands/previewLifecycle.ts index 6f74f66d17..21b636be09 100644 --- a/packages/cli/src/commands/previewLifecycle.ts +++ b/packages/cli/src/commands/previewLifecycle.ts @@ -20,6 +20,7 @@ import { scanActiveServers, type ActiveServer, } from "../server/portUtils.js"; +import { terminalText } from "@hyperframes/core"; import { namedCacheDir } from "@hyperframes/core/cache-dir"; import type { BrowserGpuMode } from "../browser/gpuPolicy.js"; import { windowsLocalAppData } from "../utils/windowsAppData.js"; @@ -246,7 +247,7 @@ function openLog(logPath: string): number { return openSync(logPath, "a", 0o600); } catch (error) { console.warn( - `[hyperframes] background preview log not written: cannot open ${logPath} (${error})`, + `[hyperframes] background preview log not written: cannot open ${terminalText(logPath)} (${terminalText(String(error))})`, ); return openSync(devNull, "a"); } diff --git a/packages/cli/src/commands/timeline.output.test.ts b/packages/cli/src/commands/timeline.output.test.ts new file mode 100644 index 0000000000..411a356494 --- /dev/null +++ b/packages/cli/src/commands/timeline.output.test.ts @@ -0,0 +1,33 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCommand } from "citty"; +import { afterEach, expect, it, vi } from "vitest"; +import timeline from "./timeline.js"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + +it("shows control characters in a runtime query's answer as text, and keeps its lines", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const bell = String.fromCharCode(7); + const dir = mkdtempSync(join(tmpdir(), "hf-timeline-out-")); + writeFileSync(join(dir, "index.html"), ""); + vi.stubEnv("HF_INSPECT_URL", "http://127.0.0.1:4599"); + vi.stubGlobal("fetch", async (url: string) => + url.endsWith("/info") + ? new Response(JSON.stringify({ project: dir })) + : new Response(JSON.stringify({ text: `#hero${bell}\n 0s to 2s` })), + ); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + await runCommand(timeline, { rawArgs: [dir, "--at", "1"] }); + + expect(log.mock.calls).toEqual([["#hero\\x07\n 0s to 2s"]]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/src/commands/timeline.ts b/packages/cli/src/commands/timeline.ts index abe323be26..61fcae3fac 100644 --- a/packages/cli/src/commands/timeline.ts +++ b/packages/cli/src/commands/timeline.ts @@ -1,3 +1,4 @@ +import { terminalLines } from "@hyperframes/core"; import { type ArgDef } from "citty"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -172,7 +173,7 @@ export default defineCommand({ }); const result = await response.json(); if (!response.ok) throw new Error(result.error ?? "Timeline query failed"); - console.log(args.json ? JSON.stringify(result) : result.text); + console.log(args.json ? JSON.stringify(result) : terminalLines(String(result.text))); return; } ensureDOMParser(); diff --git a/packages/cli/src/commands/upgrade.output.test.ts b/packages/cli/src/commands/upgrade.output.test.ts new file mode 100644 index 0000000000..6eebc4c7da --- /dev/null +++ b/packages/cli/src/commands/upgrade.output.test.ts @@ -0,0 +1,60 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCommand } from "citty"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; + +// Built rather than written: a literal control character in the source is a lint error. +const bell = String.fromCharCode(7); +const latest = `9.9.9${bell}`; + +vi.mock("../utils/updateCheck.js", async (orig) => ({ + ...(await orig()), + checkForUpdate: vi.fn(async () => ({ current: "0.7.48", latest, updateAvailable: true })), +})); +const outro = vi.hoisted(() => vi.fn()); +vi.mock("../ui/prompts.js", async (orig) => ({ + ...(await orig()), + intro: vi.fn(), + outro, + spinner: () => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() }), +})); + +const { default: upgrade } = await import("./upgrade.js"); + +describe("upgrade command: a version that is not a plain version number", () => { + afterEach(() => { + vi.restoreAllMocks(); + outro.mockClear(); + consumeCommandResult(); + }); + + it("shows its control characters as text in a check", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await runCommand(upgrade, { rawArgs: ["--check"] }); + + const printed = [...log.mock.calls, ...outro.mock.calls].map((call) => call.join(" ")); + expect(printed.join("\n")).not.toContain(bell); + expect(printed.some((line) => line.includes("Latest:") && line.includes("9.9.9\\x07"))).toBe( + true, + ); + expect(printed.at(-1)).toContain("Update available: v9.9.9\\x07"); + }); + + it("shows its control characters as text for a project's pins", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-upgrade-out-")); + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x", scripts: {} })); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + await runCommand(upgrade, { rawArgs: ["--project", dir] }); + + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).not.toContain(bell); + expect(printed).toContain("Project pins already on hyperframes@9.9.9\\x07"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts index 52190e9369..a87745c514 100644 --- a/packages/cli/src/commands/upgrade.ts +++ b/packages/cli/src/commands/upgrade.ts @@ -13,6 +13,7 @@ import { readdirSync, readFileSync, } from "node:fs"; +import { terminalText } from "@hyperframes/core"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { join, resolve } from "node:path"; import { c } from "../ui/colors.js"; @@ -99,11 +100,11 @@ export default defineCommand({ console.log(); console.log(` ${c.dim("Current:")} ${c.bold("v" + result.current)}`); - console.log(` ${c.dim("Latest:")} ${c.bold(c.accent("v" + result.latest))}`); + console.log(` ${c.dim("Latest:")} ${c.bold(c.accent("v" + terminalText(result.latest)))}`); console.log(); if (checkOnly) { - clack.outro(c.accent("Update available: v" + result.latest)); + clack.outro(c.accent("Update available: v" + terminalText(result.latest))); return; } @@ -240,7 +241,7 @@ function printNpxFallback(reason: string, npxFallback: string, autoYes: boolean) console.log(); if (autoYes) { console.log( - ` ${c.dim("Couldn't detect a global install to upgrade")} ${c.dim("(" + reason + ")")}`, + ` ${c.dim("Couldn't detect a global install to upgrade")} ${c.dim("(" + terminalText(reason) + ")")}`, ); } console.log(` ${c.accent(npxFallback)}`); @@ -338,7 +339,9 @@ function printProjectPinResult( return; } if (!res.changed) { - console.log(` ${c.success("◇")} Project pins already on hyperframes@${res.to}`); + console.log( + ` ${c.success("◇")} Project pins already on hyperframes@${terminalText(res.to)}`, + ); return; } const verb = checkOnly ? "would bump" : "bumped"; @@ -355,7 +358,7 @@ export function runDetectedInstall( ): void { const location = globalInstallLocation(); if ("reason" in location) { - clack.outro(c.dim(location.reason)); + clack.outro(c.dim(terminalText(location.reason))); setCommandExitCode(1); return; }