diff --git a/packages/cli/src/capture/coreExtractionPhase.ts b/packages/cli/src/capture/coreExtractionPhase.ts index c8232e596d..95cc191b39 100644 --- a/packages/cli/src/capture/coreExtractionPhase.ts +++ b/packages/cli/src/capture/coreExtractionPhase.ts @@ -28,6 +28,7 @@ import { isDegradableEvaluateTimeoutError } from "./captureTimeout.js"; import { waitForPageReady } from "./navigateForCapture.js"; import { lazyScrollForCapture } from "./lazyScrollForCapture.js"; import { filterExtractedScripts } from "./filterExtractedScripts.js"; +import { terminalLines } from "@hyperframes/core"; export interface CoreExtractionInput { page1: Page; @@ -278,7 +279,7 @@ export async function runCoreExtraction(input: CoreExtractionInput): Promise { } }); + it("prints a thrown error's control characters as visible escapes and keeps its lines", async () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + mockInitCommand(() => { + throw new Error("Install failed: a\u001b]52;c;eA==\u0007\n b\u009b"); + }); + mockTelemetry(); + + process.argv = ["node", "cli.ts", "init"]; + await import("./cli.js"); + + const said = errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain("Install failed: a\\x1b]52;c;eA==\\x07\n b\\x9b"); + for (const control of ["\u001b]", "\u0007", "\u009b"]) expect(said).not.toContain(control); + } finally { + 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/cli.ts b/packages/cli/src/cli.ts index 4088f5ddbc..38014d8d11 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -95,6 +95,7 @@ import { closestMatch, closestNames, commandRedirect, fileHint } from "./utils/d import { errorBox } from "./ui/format.js"; import { failureShown, jsonErrorBody, watchOutput, writeJsonFailure } from "./utils/jsonError.js"; import { isDevMode } from "./utils/env.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { CliResultSignal, CliRuntimeError, @@ -397,7 +398,7 @@ function printNotices(): void { _printStalePinNotice?.(); } _printSkillsUpdateNotice?.(); - if (_appHistoryNotice) process.stderr.write(`◇ ${_appHistoryNotice}\n`); + if (_appHistoryNotice) process.stderr.write(`◇ ${terminalText(_appHistoryNotice)}\n`); } registerRootExitRequester((exitCode) => { @@ -704,7 +705,7 @@ async function executeCli(): Promise { const usage = error instanceof CliUsageError && !error.result.presented; if (usage && !error.hint) await showRequestedUsage(console.error); if (!typed || !error.result.presented) { - console.error(error instanceof Error ? error.message : String(error)); + console.error(terminalLines(error instanceof Error ? error.message : String(error))); } if (usage && error.hint) console.error(error.hint); } diff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.ts index ce08e1db99..02f38053f2 100644 --- a/packages/cli/src/commands/add.test.ts +++ b/packages/cli/src/commands/add.test.ts @@ -606,6 +606,24 @@ describe("add command run() — several names", () => { expect(existsSync(join(dir, "compositions", "deprecated-block.html"))).toBe(true); }); + it("prints a deprecation note from the registry with control characters escaped", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const note = DEPRECATED_BLOCK_ITEM.deprecated; + DEPRECATED_BLOCK_ITEM.deprecated = `gone${esc}]52;c;cA==${String.fromCharCode(7)}`; + vi.spyOn(console, "log").mockImplementation(() => {}); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await runWrapped(["deprecated-block", "--dir", dir, "--no-clipboard"]); + } finally { + DEPRECATED_BLOCK_ITEM.deprecated = note; + } + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).toContain("is deprecated: gone\\x1b]52;c;cA==\\x07"); + }); + it("keeps the installs that worked when one name is unknown, and fails the call", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => {}); diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index 07ddd12d63..0ada3add8b 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -19,6 +19,8 @@ import { isProjectRootMissing, ITEM_TYPE_DIRS, realpath, + terminalLines, + terminalText, type RegistryItem, } from "@hyperframes/core"; import { c } from "../ui/colors.js"; @@ -82,6 +84,8 @@ export function remapTarget( return originalTarget; } +const registryError = (message: string): string => c.error(terminalLines(message)); + // ── Include-snippet builders ──────────────────────────────────────────────── // Shown to the user after install so they know how to wire the item into // their host composition. Copied to clipboard by default. @@ -201,13 +205,14 @@ async function installOne(name: string, context: InstallContext): Promise 0) { // Say it out loud. A component's values are baked into the file rather @@ -682,7 +687,7 @@ export default defineCommand({ if (result.snippet) { console.log(""); console.log(c.dim("Include snippet:")); - console.log(` ${result.snippet}`); + console.log(` ${terminalText(result.snippet)}`); console.log(""); console.log( result.clipboardCopied @@ -693,7 +698,7 @@ export default defineCommand({ } catch (singleErr) { // Not a single item — try as a tag for bulk install if (!(singleErr instanceof AddError) || singleErr.code !== "unknown-item") { - failCaught(singleErr, json, c.error); + failCaught(singleErr, json, registryError); } let config = loadProjectConfig(projectDir); @@ -713,7 +718,7 @@ export default defineCommand({ } if (items.length === 0) { - failCaught(singleErr, json, c.error); + failCaught(singleErr, json, registryError); } if (!json) { diff --git a/packages/cli/src/commands/browserScript.ts b/packages/cli/src/commands/browserScript.ts new file mode 100644 index 0000000000..5dafe29a2b --- /dev/null +++ b/packages/cli/src/commands/browserScript.ts @@ -0,0 +1,13 @@ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +export function loadBrowserScript(name: string): string { + const candidates = [join(__dirname, name), join(__dirname, "commands", name)]; + for (const candidate of candidates) { + if (existsSync(candidate)) return readFileSync(candidate, "utf-8"); + } + throw new Error(`Missing browser script ${name}`); +} diff --git a/packages/cli/src/commands/capture.ts b/packages/cli/src/commands/capture.ts index ea8bf9c3d0..b9361212a1 100644 --- a/packages/cli/src/commands/capture.ts +++ b/packages/cli/src/commands/capture.ts @@ -8,6 +8,7 @@ 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 { terminalLines, terminalText } from "@hyperframes/core"; import { parseTimeoutMs } from "../utils/timeoutArg.js"; const CAPTURE_PHASE_PREFIX = "HYPERFRAMES_CAPTURE_PHASE "; @@ -259,7 +260,7 @@ export default defineCommand({ done: " Done", }; const label = stages[stage] || ` ${stage}`; - console.log(detail ? `${label} ${detail}` : label); + console.log(terminalText(detail ? `${label} ${detail}` : label)); }, ); @@ -295,7 +296,9 @@ export default defineCommand({ console.log(); const icon = result.ok ? c.success("◇") : c.error("✗"); const status = result.ok ? "Captured" : "Capture failed"; - console.log(icon + ` ${status} ${c.bold(result.title)} → ${c.dim(outputDir)}`); + console.log( + icon + ` ${status} ${c.bold(terminalText(result.title))} → ${c.dim(outputDir)}`, + ); console.log(); console.log(` ${c.dim("Screenshots:")} ${result.screenshots.length}`); console.log(` ${c.dim("Assets:")} ${result.assets.length}`); @@ -313,23 +316,25 @@ export default defineCommand({ } console.log(` ${c.dim("Sections:")} ${result.tokens.sections.length}`); console.log( - ` ${c.dim("Fonts:")} ${result.tokens.fonts - .map(function (f) { - return ( - f.family + - " (" + - (f.variable && f.weightRange - ? f.weightRange[0] + "-" + f.weightRange[1] + " variable" - : f.weights.join(",")) + - ")" - ); - }) - .join(", ")}`, + ` ${c.dim("Fonts:")} ${terminalText( + result.tokens.fonts + .map(function (f) { + return ( + f.family + + " (" + + (f.variable && f.weightRange + ? f.weightRange[0] + "-" + f.weightRange[1] + " variable" + : f.weights.join(",")) + + ")" + ); + }) + .join(", "), + )}`, ); if (result.warnings.length > 0) { console.log(); for (const w of result.warnings) { - console.log(` ${c.warn("⚠")} ${w}`); + console.log(` ${c.warn("⚠")} ${terminalLines(w)}`); } } console.log(); @@ -353,7 +358,7 @@ export default defineCommand({ if (isJson) { console.log(JSON.stringify(jsonFailure("runtime_error", errMsg))); } else { - console.error(`\n ✗ Capture failed: ${errMsg}\n`); + console.error(`\n ✗ Capture failed: ${terminalLines(errMsg)}\n`); } scheduleCliExit(1); failCommand(); diff --git a/packages/cli/src/commands/capture/video.test.ts b/packages/cli/src/commands/capture/video.test.ts index a3f7c15444..46223a0f7c 100644 --- a/packages/cli/src/commands/capture/video.test.ts +++ b/packages/cli/src/commands/capture/video.test.ts @@ -206,3 +206,34 @@ describe("runVideoMode", () => { }, ); }); + +describe("runVideoMode --list", () => { + it("prints manifest values with control characters escaped", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const projectDir = mkdtempSync(join(tmpdir(), "hf-video-list-")); + onTestFinished(() => rmSync(projectDir, { recursive: true, force: true })); + mkdirSync(join(projectDir, "extracted")); + writeFileSync( + join(projectDir, "extracted", "video-manifest.json"), + JSON.stringify([ + ENTRY(0, { + heading: `Launch${esc}[2J`, + url: `https://cdn.example.com/a${esc}]8;;https://x.test${String.fromCharCode(7)}.mp4`, + }), + ]), + ); + 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") + .replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), ""); + expect(printed).not.toContain(esc); + expect(printed).toContain('heading: "Launch\\x1b[2J"'); + expect(printed).toContain("a\\x1b]8;;https://x.test\\x07.mp4"); + }); +}); diff --git a/packages/cli/src/commands/capture/video.ts b/packages/cli/src/commands/capture/video.ts index 73931721e5..a360707714 100644 --- a/packages/cli/src/commands/capture/video.ts +++ b/packages/cli/src/commands/capture/video.ts @@ -5,6 +5,7 @@ import { c } from "../../ui/colors.js"; 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"; const MAX_VIDEO_BYTES = 250 * 1024 * 1024; const VIDEO_CONTENT_TYPE_RE = /^(video\/|application\/(mp4|octet-stream|x-mpegurl))/i; @@ -101,6 +102,8 @@ export function safeFilename(name: string): string { export { VIDEO_CONTENT_TYPE_RE, MAX_VIDEO_BYTES }; +const shown = (value: unknown): string => terminalText(String(value)); + export interface ManifestEntry { index: number; url: string; @@ -206,7 +209,9 @@ 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: ${(e as Error).message}`); + console.error( + `${c.error("✗")} video-manifest.json is malformed: ${shown((e as Error).message)}`, + ); setCommandExitCode(1); return; } @@ -221,9 +226,9 @@ export async function runVideoMode(args: VideoModeArgs): Promise { ); for (const e of manifest) { console.log( - ` ${c.bold(`[${e.index}]`)} ${e.filename} — ${e.sourceWidth || e.width}×${e.sourceHeight || e.height}` + - (e.heading ? `\n heading: "${e.heading}"` : "") + - `\n url: ${e.url}`, + ` ${c.bold(`[${shown(e.index)}]`)} ${shown(e.filename)} — ${shown(e.sourceWidth || e.width)}×${shown(e.sourceHeight || e.height)}` + + (e.heading ? `\n heading: "${shown(e.heading)}"` : "") + + `\n url: ${shown(e.url)}`, ); } return; @@ -232,7 +237,7 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const pick = pickManifestEntry(manifest, args); if (!pick.ok) { console.error( - `${c.error("✗")} ${pick.message}` + + `${c.error("✗")} ${shown(pick.message)}` + (pick.code === "no-match-url" ? `\n Run with --list to see what's available.` : ""), ); setCommandExitCode(1); @@ -245,7 +250,7 @@ export async function runVideoMode(args: VideoModeArgs): Promise { console.error( `${c.error("✗")} filename "${safeFilename(entry.filename || basename(entry.url))}" ` + `collides with manifest entr${collisions.length === 1 ? "y" : "ies"} ` + - `${collisions.map((co) => `[${co.index}]`).join(", ")}. ` + + `${collisions.map((co) => `[${shown(co.index)}]`).join(", ")}. ` + `Refusing to download — the on-disk file's bytes would not match the requested entry.`, ); setCommandExitCode(1); @@ -267,15 +272,15 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const relPath = isW2hLayout ? `capture/assets/videos/${fname}` : `assets/videos/${fname}`; console.log( - `${c.accent("▸")} downloading [${entry.index}] ${entry.filename} (${entry.sourceWidth || entry.width}×${entry.sourceHeight || entry.height})`, + `${c.accent("▸")} downloading [${shown(entry.index)}] ${shown(entry.filename)} (${shown(entry.sourceWidth || entry.width)}×${shown(entry.sourceHeight || entry.height)})`, ); - console.log(` from: ${entry.url}`); + console.log(` from: ${shown(entry.url)}`); try { const bytes = await streamToFile(entry.url, outPath); const sizeKb = Math.round(bytes / 1024); const sizeStr = sizeKb > 1024 ? `${(sizeKb / 1024).toFixed(1)}MB` : `${sizeKb}KB`; console.log(`${c.success("◇")} wrote ${relPath} (${sizeStr})`); - const snippetId = `video-${entry.index}`; + const snippetId = `video-${shown(entry.index)}`; console.log( ` Reference it from a beat composition as:\n` + ` `, @@ -287,7 +292,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: ${message}`); + console.error(`${c.error("✗")} download failed: ${shown(message)}`); setCommandExitCode(1); } } diff --git a/packages/cli/src/commands/catalog.test.ts b/packages/cli/src/commands/catalog.test.ts index d877a362fe..e96ba11dfb 100644 --- a/packages/cli/src/commands/catalog.test.ts +++ b/packages/cli/src/commands/catalog.test.ts @@ -317,6 +317,18 @@ describe("catalog when the registry cannot be read", () => { }); }); +describe("catalog on a terminal", () => { + it("prints registry tags with control characters escaped", async () => { + const esc = String.fromCharCode(27); + state.registry = [block("count-up", [`odd${esc}]52;c;cA==${String.fromCharCode(7)}`])]; + + const output = await runCatalog({}); + + expect(output).not.toContain(esc); + expect(output).toContain("odd\\x1b]52;c;cA==\\x07"); + }); +}); + describe("catalog --json meaning search", () => { it("reports the registry moves meaning search cannot see", async () => { // Published after the user's artifact was fetched: in the registry, absent diff --git a/packages/cli/src/commands/catalog.ts b/packages/cli/src/commands/catalog.ts index e871a1e4c8..70bc3fa812 100644 --- a/packages/cli/src/commands/catalog.ts +++ b/packages/cli/src/commands/catalog.ts @@ -11,7 +11,7 @@ export const examples: Example[] = [ ]; import * as clack from "../ui/prompts.js"; -import { realpath, type ItemType, type RegistryItem } from "@hyperframes/core"; +import { realpath, terminalText, type ItemType, type RegistryItem } from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { loadAllItems } from "../registry/resolver.js"; import { readRegistryManifest } from "../registry/remote.js"; @@ -232,7 +232,7 @@ export default defineCommand({ // Asked for the whole manifest on purpose: its item list defines coverage, // and its artifact revision is the one owner of vector freshness. const manifest = await readRegistryManifest(config.registry).catch((error: unknown) => { - console.error(error instanceof Error ? error.message : String(error)); + console.error(terminalText(error instanceof Error ? error.message : String(error))); return finishCommand(1); }); const entries = manifest.items; @@ -471,7 +471,7 @@ export default defineCommand({ const options = matching.map((item) => ({ value: item.name, label: item.name, - hint: item.description, + hint: terminalText(item.description), })); const selected = await clack.select({ @@ -491,18 +491,18 @@ export default defineCommand({ }); for (const warning of result.warnings) { - console.warn(c.warn(`Warning: ${warning}`)); + console.warn(c.warn(`Warning: ${terminalText(warning)}`)); } console.log(""); console.log(`${c.success("✓")} Installed ${c.accent(result.name)} (${result.type})`); const root = realpath(dir); for (const file of result.written) { - console.log(` ${c.dim(relative(root, file))}`); + console.log(` ${c.dim(terminalText(relative(root, file)))}`); } if (result.snippet) { console.log(""); console.log(c.dim("Include snippet:")); - console.log(` ${result.snippet}`); + console.log(` ${terminalText(result.snippet)}`); } return; } @@ -516,9 +516,9 @@ export default defineCommand({ for (const item of matching) { const type = item.type.replace("hyperframes:", ""); - const tags = item.tags?.length ? c.dim(` [${item.tags.join(", ")}]`) : ""; + const tags = item.tags?.length ? c.dim(` [${terminalText(item.tags.join(", "))}]`) : ""; console.log( - `${c.cyan(item.name.padEnd(NAME_COL))}${type.padEnd(TYPE_COL)}${item.description}${tags}`, + `${c.cyan(item.name.padEnd(NAME_COL))}${type.padEnd(TYPE_COL)}${terminalText(item.description)}${tags}`, ); } diff --git a/packages/cli/src/commands/catch-up.test.ts b/packages/cli/src/commands/catch-up.test.ts index e664dc5292..1b1899259b 100644 --- a/packages/cli/src/commands/catch-up.test.ts +++ b/packages/cli/src/commands/catch-up.test.ts @@ -60,4 +60,50 @@ describe("catch-up", () => { expect(human).not.toContain("shipped"); expect(JSON.parse(await run(true)).turns).toEqual([]); }); + + it("prints history, file names and the folder name with control characters as visible escapes", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const bel = String.fromCharCode(7); + const osc = `${esc}]52;c;cHduZWQ=${bel}`; + // Windows refuses control characters in file and folder names, so there only the history + // text carries them. + const names = process.platform !== "win32"; + const parent = mkdtempSync(join(tmpdir(), "hf-catch-up-")); + const dir = join(parent, names ? `video${esc}[2J` : "video"); + mkdirSync(join(dir, ".hyperframes"), { recursive: true }); + writeFileSync(join(dir, "index.html"), ""); + const seenAt = Date.parse("2026-01-01T09:00:00Z"); + markSeen(dir, { at: seenAt, checked: seenAt }); + writeFileSync(join(dir, names ? `scene${esc}[1A.html` : "scene.html"), ""); + writeFileSync( + join(dir, ".hyperframes", APP_HISTORY), + `${JSON.stringify({ + at: "2026-01-01T10:00:00.000Z", + engine: "claude", + asked: `make it red${osc}`, + did: `done\r${esc}[2Kfaked`, + files: [`a${bel}.html`], + })}\n`, + ); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + await catchUp.run?.({ args: { _: [], dir, json: false }, rawArgs: [], cmd: catchUp }); + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + log.mockRestore(); + const colors = new RegExp(`${esc}\\[[0-9;]*m`, "g"); + const shown = printed.replace(colors, ""); + + const controls = [...shown].filter((ch) => { + const code = ch.charCodeAt(0); + return (code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f); + }); + expect(controls).toEqual([]); + expect(shown).toContain("make it red\\x1b]52;c;cHduZWQ=\\x07"); + expect(shown).toContain("done\\x0d\\x1b[2Kfaked"); + expect(shown).toContain("a\\x07.html"); + if (names) { + expect(shown).toContain("scene\\x1b[1A.html"); + expect(shown).toContain("video\\x1b[2J"); + } + }); }); diff --git a/packages/cli/src/commands/catch-up.ts b/packages/cli/src/commands/catch-up.ts index d2b0b45566..b4742b63bd 100644 --- a/packages/cli/src/commands/catch-up.ts +++ b/packages/cli/src/commands/catch-up.ts @@ -9,6 +9,7 @@ import { type AppTurn, } from "../utils/appHistory.js"; import { resolveProject } from "../utils/project.js"; +import { terminalText } from "@hyperframes/core"; export const examples: Example[] = [ ["See what was done in the desktop app since you last looked", "hyperframes catch-up"], @@ -18,7 +19,8 @@ export const examples: Example[] = [ const AGENTS: Record = { claude: "Claude Code", codex: "Codex", grok: "Grok" }; -const oneLine = (text: string): string => text.replace(/\s*\n+\s*/g, " "); +const oneLine = (text: string): string => terminalText(text.replace(/\s*\n+\s*/g, " ")); +const names = (files: string[]): string => terminalText(files.join(", ")); const when = (at: string): string => new Date(at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); @@ -28,7 +30,7 @@ function printTurn(turn: AppTurn): void { if (turn.asked) console.log(` The person: ${oneLine(turn.asked)}`); if (turn.did) console.log(` Framey (${AGENTS[turn.engine] ?? "the app"}): ${oneLine(turn.did)}`); - if (turn.files.length) console.log(` ${c.dim(`Changed: ${turn.files.join(", ")}`)}`); + if (turn.files.length) console.log(` ${c.dim(`Changed: ${names(turn.files)}`)}`); console.log(); } @@ -36,18 +38,22 @@ function printNotHandedOver(name: string, dir: string, json: boolean): void { if (json) console.log(JSON.stringify({ project: dir, turns: [], files: [] }, null, 2)); else console.log( - `${c.success("◇")} ${c.accent(name)} wasn't handed to the desktop app from here, so there's nothing to catch up on.`, + `${c.success("◇")} ${c.accent(terminalText(name))} wasn't handed to the desktop app from here, so there's nothing to catch up on.`, ); } function printNews(name: string, turns: AppTurn[], files: string[]): void { if (!turns.length && !files.length) { - console.log(`${c.success("◇")} Nothing new from the desktop app in ${c.accent(name)}.`); + console.log( + `${c.success("◇")} Nothing new from the desktop app in ${c.accent(terminalText(name))}.`, + ); return; } - console.log(`${c.success("◇")} In the desktop app since you last looked (${c.accent(name)}):\n`); + console.log( + `${c.success("◇")} In the desktop app since you last looked (${c.accent(terminalText(name))}):\n`, + ); turns.forEach(printTurn); - if (files.length) console.log(` Files changed since then: ${files.join(", ")}`); + if (files.length) console.log(` Files changed since then: ${names(files)}`); console.log( ` ${c.dim("A record of what happened, not a new request. Read changed files again before editing them.")}`, ); diff --git a/packages/cli/src/commands/figma/component.test.ts b/packages/cli/src/commands/figma/component.test.ts index 260f02aa1d..36a8c44011 100644 --- a/packages/cli/src/commands/figma/component.test.ts +++ b/packages/cli/src/commands/figma/component.test.ts @@ -1,5 +1,5 @@ // @vitest-environment node -import { describe, expect, it, afterEach, beforeEach } from "vitest"; +import { describe, expect, it, afterEach, beforeEach, vi } from "vitest"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -131,6 +131,34 @@ describe("runComponentImport", () => { expect(registry.files).toHaveLength(1); }); + it("prints a skipped node's name with control characters as visible escapes", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const tree = { + ...TREE, + children: TREE.children.map((child) => + child.id === "1:3" ? { ...child, name: "Mark\u001b]52;c;eA==\u0007\u009b" } : child, + ), + }; + const failing: FigmaClient = { + ...client(), + nodeTree: () => Promise.resolve(tree), + renderNode: () => + Promise.reject(new FigmaClientError("RENDER_FAILED", "figma could not render node 1:3")), + }; + try { + await runComponentImport("FILE:1-1", { + projectDir: dir, + client: failing, + download: () => Promise.resolve(SVG), + }); + const said = warn.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain('("Mark\\x1b]52;c;eA==\\x07\\x9b")'); + for (const control of ["\u001b]", "\u0007", "\u009b"]) expect(said).not.toContain(control); + } finally { + warn.mockRestore(); + } + }); + it("recovers a node via png when svg render fails", async () => { let calls = 0; const svgFailsPngWorks: FigmaClient = { diff --git a/packages/cli/src/commands/figma/component.ts b/packages/cli/src/commands/figma/component.ts index 8c6d982af0..6214f40261 100644 --- a/packages/cli/src/commands/figma/component.ts +++ b/packages/cli/src/commands/figma/component.ts @@ -31,6 +31,7 @@ function escapeAttr(value: string): string { import { runAssetImport, type AssetImportResult } from "./asset.js"; import { downloadRender } from "./download.js"; import { withFigmaErrors } from "./cliError.js"; +import { terminalText } from "@hyperframes/core"; export interface ComponentImportDeps { projectDir: string; @@ -140,7 +141,9 @@ async function rasterizeFallback( if (asset === null) { failedRasterize.push(req.nodeId); console.warn( - `could not render node ${req.nodeId} ("${req.name}") as svg or png — leaving its placeholder without src`, + terminalText( + `could not render node ${req.nodeId} ("${req.name}") as svg or png — leaving its placeholder without src`, + ), ); continue; } diff --git a/packages/cli/src/commands/keyframes.test.ts b/packages/cli/src/commands/keyframes.test.ts index 682693d552..57b00f780a 100644 --- a/packages/cli/src/commands/keyframes.test.ts +++ b/packages/cli/src/commands/keyframes.test.ts @@ -60,6 +60,41 @@ describe("keyframes JSON output", () => { }); }); +describe("keyframes human output", () => { + it("prints selectors, values and keyframe text from the project with control characters escaped", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const bel = String.fromCharCode(7); + const dir = mkdtempSync(join(tmpdir(), "hf-keyframes-human-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + const source = join(dir, "index.html"); + writeFileSync( + source, + wrap( + `const tl = gsap.timeline({ paused: true }); tl.to("#dot${esc}[2J", { x: "40px${esc}]52;c;cA==${bel}", duration: 1 }, 0); window.__timelines = { main: tl };`, + ).replace( + "", + ``, + ), + ); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + onTestFinished(() => log.mockRestore()); + + await runCommand(keyframesCommand, { rawArgs: [source, "--runtime", "all"] }); + + const colors = new RegExp(`${esc}\\[[0-9;]*m`, "g"); + const output = log.mock.calls + .map((args) => args.join(" ")) + .join("\n") + .replace(colors, ""); + expect(output).not.toContain(esc); + expect(output).not.toContain(bel); + expect(output).toContain("#dot\\x1b[2J"); + expect(output).toContain("40px\\x1b]52;c;cA==\\x07"); + expect(output).toContain("a\\x1b[1A"); + }); +}); + describe("keyframes direct composition scope", () => { it("keeps the project root and passes the nested HTML entry to --shot", () => { const projectDir = mkdtempSync(join(tmpdir(), "hf-keyframes-target-")); diff --git a/packages/cli/src/commands/keyframes.ts b/packages/cli/src/commands/keyframes.ts index ed0156676d..afcd875d54 100644 --- a/packages/cli/src/commands/keyframes.ts +++ b/packages/cli/src/commands/keyframes.ts @@ -750,7 +750,7 @@ export function collectCompositions(indexPath: string): SurfacedComposition[] { function fmtProps(props: Record): string { return Object.entries(props) .filter(([k]) => k !== "ease") - .map(([k, v]) => `${k}:${v}`) + .map(([k, v]) => terminalText(`${k}:${v}`)) .join(" "); } @@ -762,18 +762,25 @@ function printTween(t: SurfacedTween): void { const timing = c.dim( `@${formatSeconds(t.start)}→${formatSeconds(t.end)} (${formatSeconds(t.duration)})`, ); - const group = t.group ? c.dim(` ${t.group}`) : ""; - console.log(` ${c.accent(t.target)}${group} ${c.dim(t.method)}/${t.shape} ${timing}`); + const group = t.group ? c.dim(` ${terminalText(t.group)}`) : ""; + console.log( + ` ${c.accent(terminalText(t.target))}${group} ${c.dim(terminalText(t.method))}/${t.shape} ${timing}`, + ); if (t.shape === "motionPath") { console.log(c.dim(` motionPath arc (${t.keyframes.length} stops)`)); } else { const kfLine = t.keyframes.map((k) => `${k.pct}% {${fmtProps(k.properties)}}`).join(" "); console.log(` ${c.dim(kfLine)}`); } - if (t.unresolved.length) console.log(c.dim(` unresolved: ${t.unresolved.join(", ")}`)); + if (t.unresolved.length) + console.log(c.dim(` unresolved: ${terminalText(t.unresolved.join(", "))}`)); if (t.composedWith?.length) { for (const a of t.composedWith) { - console.log(c.dim(` ↑ composed with ${c.accent(a.selector)}${c.dim(": " + a.summary)}`)); + console.log( + c.dim( + ` ↑ composed with ${c.accent(terminalText(a.selector))}${c.dim(": " + terminalText(a.summary))}`, + ), + ); } } console.log(); @@ -784,7 +791,7 @@ function printTrace(tr: SurfacedTrace): void { const end = Math.max(...tr.strokes.flatMap((s) => (s.end === null ? [] : [s.end]))); const n = tr.strokes.length; console.log( - ` ${c.accent(tr.target)}${c.dim(" position")} ${c.dim("trace")} ${c.dim(`${n} strokes`)} ${c.dim(`@${start}s→${end}s`)}`, + ` ${c.accent(terminalText(tr.target))}${c.dim(" position")} ${c.dim("trace")} ${c.dim(`${n} strokes`)} ${c.dim(`@${start}s→${end}s`)}`, ); tr.strokes.forEach((s, i) => { const kfLine = s.keyframes.map((k) => `${k.pct}% {${fmtProps(k.properties)}}`).join(" "); @@ -1009,20 +1016,24 @@ function printComposition(cmp: SurfacedComposition): void { function printCssKeyframes(cssKeyframes: SurfacedCssKeyframes): void { const selectors = cssKeyframes.selectors.length - ? cssKeyframes.selectors.join(", ") + ? terminalText(cssKeyframes.selectors.join(", ")) : "(no selector found)"; console.log( - ` ${c.accent(`@keyframes ${cssKeyframes.name}`)}${c.dim(" css")} ${c.dim(selectors)}`, + ` ${c.accent(`@keyframes ${terminalText(cssKeyframes.name)}`)}${c.dim(" css")} ${c.dim(selectors)}`, ); for (const stop of cssKeyframes.keyframes) { - console.log(` ${c.dim(`${stop.selector} {${stop.declarations.join("; ")}}`)}`); + console.log(` ${c.dim(terminalText(`${stop.selector} {${stop.declarations.join("; ")}}`))}`); } console.log(); } function printAnime(anime: SurfacedAnimeAnimation): void { - const targets = anime.targets.length ? anime.targets.join(", ") : "(targets not parsed)"; - const durations = anime.durations.length ? ` duration ${anime.durations.join(",")}` : ""; + const targets = anime.targets.length + ? terminalText(anime.targets.join(", ")) + : "(targets not parsed)"; + const durations = anime.durations.length + ? ` duration ${terminalText(anime.durations.join(","))}` + : ""; const registered = anime.registered ? "registered" : "not registered"; console.log( ` ${c.accent(`anime.${anime.kind}`)}${c.dim(` ${registered}`)} ${c.dim(`${targets}${durations}`)}`, diff --git a/packages/cli/src/commands/layout.test.ts b/packages/cli/src/commands/layout.test.ts index ab63315c5e..ed9a12c92a 100644 --- a/packages/cli/src/commands/layout.test.ts +++ b/packages/cli/src/commands/layout.test.ts @@ -1,4 +1,6 @@ +import { runCommand } from "citty"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { CliRuntimeError } from "../utils/commandResult.js"; import { bundleToSingleHtmlFailureMock, metaDescription, @@ -49,3 +51,37 @@ describe("layout command deprecation (U5)", () => { expect(parsed._meta.deprecated).toBe(true); }); }); + +describe("layout command terminal output", () => { + it("prints a folder name and a page error with control characters as visible escapes", async () => { + const { resolveProject } = await import("../utils/project.js"); + const { bundleToSingleHtml } = await import("@hyperframes/core/compiler"); + vi.mocked(resolveProject).mockReturnValueOnce({ + dir: "/fake-project", + name: "evil\u001b]0;title\u0007", + indexPath: "/fake-project/index.html", + }); + vi.mocked(bundleToSingleHtml).mockRejectedValueOnce( + new Error("page threw \u001b[2J\u009b\nsecond line"), + ); + const printed: string[] = []; + const keep = (...args: unknown[]) => { + printed.push(args.map(String).join(" ")); + }; + vi.spyOn(console, "log").mockImplementation(keep); + vi.spyOn(console, "error").mockImplementation(keep); + vi.spyOn(process.stderr, "write").mockImplementation(() => true); + vi.spyOn(process, "exit").mockImplementation(() => undefined as never); + + await runCommand(createInspectCommand("layout"), { rawArgs: [] }).catch((error: unknown) => { + if (!(error instanceof CliRuntimeError && error.result.presented)) throw error; + }); + + const text = printed.join("\n"); + expect(text).toContain("evil\\x1b]0;title\\x07"); + expect(text).toContain("page threw \\x1b[2J\\x9b\nsecond line"); + for (const control of ["\u0007", "\u009b", "\u001b]", "\u001b[2J"]) { + expect(text).not.toContain(control); + } + }); +}); diff --git a/packages/cli/src/commands/layout.ts b/packages/cli/src/commands/layout.ts index 67cf7c795c..a67a7ee260 100644 --- a/packages/cli/src/commands/layout.ts +++ b/packages/cli/src/commands/layout.ts @@ -1,10 +1,8 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { launchManagedBrowser, resolveManagedGpuMode } from "../browser/launch.js"; import { launchWithPageNetwork } from "../browser/pageNetwork.js"; import { failCommand, setCommandExitCode } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; -import { existsSync, readFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; import type { Example } from "./_examples.js"; import { c } from "../ui/colors.js"; import { resolveProject } from "../utils/project.js"; @@ -39,9 +37,9 @@ import { type SeekCompositionTimelineOptions, } from "../capture/captureCompositionFrame.js"; import { failureMessage, jsonFailure } from "../utils/jsonError.js"; +import { parseLayoutIssue } from "../utils/checkBrowser.js"; +import { loadBrowserScript } from "./browserScript.js"; -const __filename = fileURLToPath(import.meta.url); -const __dirname = dirname(__filename); const LAYOUT_SEEK_OPTIONS: SeekCompositionTimelineOptions = AUDIT_SEEK_OPTIONS; // All new envelope fields are optional (?); additive changes don't bump this. const INSPECT_SCHEMA_VERSION = 1; @@ -288,14 +286,6 @@ async function runLayoutAudit( } } -export function loadBrowserScript(name: string): string { - const candidates = [join(__dirname, name), join(__dirname, "commands", name)]; - for (const candidate of candidates) { - if (existsSync(candidate)) return readFileSync(candidate, "utf-8"); - } - throw new Error(`Missing browser script ${name}`); -} - function loadLayoutAuditScript(): string { return loadBrowserScript("layout-audit.browser.js"); } @@ -320,7 +310,7 @@ async function collectLayoutIssues( }, { time, tolerance }, ); - issues.push(...(sampleIssues as LayoutIssue[])); + if (Array.isArray(sampleIssues)) issues.push(...sampleIssues.flatMap(parseLayoutIssue)); } return issues; } @@ -531,7 +521,7 @@ export function createInspectCommand(commandName: "inspect" | "layout") { ? ` + motion spec (${motionSpec.assertions.length} assertion(s))` : ""; console.log( - `${c.accent("◆")} Inspecting layout for ${c.accent(project.name)} (${sampleLabel}${motionLabel})`, + `${c.accent("◆")} Inspecting layout for ${c.accent(terminalText(project.name))} (${sampleLabel}${motionLabel})`, ); } @@ -651,7 +641,7 @@ export function createInspectCommand(commandName: "inspect" | "layout") { ); failCommand(); } - console.error(`${c.error("✗")} Inspect failed: ${message}`); + console.error(`${c.error("✗")} Inspect failed: ${terminalLines(message)}`); failCommand(); } }, diff --git a/packages/cli/src/timeline/describeProject.test.ts b/packages/cli/src/timeline/describeProject.test.ts index 992ac4809a..6f58fe412a 100644 --- a/packages/cli/src/timeline/describeProject.test.ts +++ b/packages/cli/src/timeline/describeProject.test.ts @@ -219,6 +219,20 @@ describe("describeProject", () => { expect(row!.children).toEqual([]); }); + it("prints ids and src values from the project with control characters escaped", async () => { + // Built rather than written: a literal control character in the source is a lint error. + const esc = String.fromCharCode(27); + const index = project(); + writeFileSync( + index, + `
`, + ); + const text = formatTimeline(await describeProject(index)); + expect(text).not.toContain(esc); + expect(text).toContain("logo\\x1b[2J"); + expect(text).toContain("src=logo\\x1b]52;c;cA==\\x07.png"); + }); + it("claims no duration source for a leaf with nothing authored and no children", async () => { const index = project(); writeFileSync(index, `
`); diff --git a/packages/cli/src/timeline/formatTimeline.ts b/packages/cli/src/timeline/formatTimeline.ts index 564436dfc2..e0e0baeb6f 100644 --- a/packages/cli/src/timeline/formatTimeline.ts +++ b/packages/cli/src/timeline/formatTimeline.ts @@ -4,6 +4,7 @@ import { type TimelineRow, type TimelineTrack, } from "./describeProject.js"; +import { terminalText } from "@hyperframes/core"; const BAR_WIDTH = 40; const n = (v: number) => String(Math.round(v * 1000) / 1000); @@ -65,7 +66,9 @@ function line(row: TimelineRow, total: number): string { const times = row.host ? `${span(row.absStart, row.absEnd)} (local ${span(row.start, row.end)}) nested in ${row.host} ${row.file}` : span(row.start, row.end); - return ` |${bar(row, total)}| ${row.ref} ${row.id} ${times} ${details(row)}`.trimEnd(); + return terminalText( + ` |${bar(row, total)}| ${row.ref} ${row.id} ${times} ${details(row)}`.trimEnd(), + ); } function header({ kind, rows }: TimelineTrack): string { diff --git a/packages/cli/src/utils/checkBrowser.test.ts b/packages/cli/src/utils/checkBrowser.test.ts index 283213d3de..8b24050959 100644 --- a/packages/cli/src/utils/checkBrowser.test.ts +++ b/packages/cli/src/utils/checkBrowser.test.ts @@ -23,6 +23,7 @@ import { runBrowserCheck, collectSeekClock, mergeHelperDrafts, + parseLayoutIssue, samplingBrowserCount, RENDER_READY_WARNING_SUFFIX, } from "./checkBrowser.js"; @@ -1115,6 +1116,28 @@ it("hides only the ReadPixels stall check's own reads cause, not the film's othe ).toEqual([otherDriverNote.text(), ordinaryWarning.text()]); }); +describe("parseLayoutIssue", () => { + const rect = { left: 0, top: 0, right: 10, bottom: 10, width: 10, height: 10 }; + const raw = (code: string) => ({ + code, + severity: "error", + time: 1, + selector: "#title", + message: "clipped", + rect, + }); + + it("keeps an issue with a known code", () => { + expect(parseLayoutIssue(raw("clipped_text"))).toEqual([raw("clipped_text")]); + }); + + it("drops an issue whose code the audit never produces", () => { + expect(parseLayoutIssue(raw("clipped_text\u001b]52;c;Y2xpcA==\u0007"))).toEqual([]); + expect(parseLayoutIssue({ ...raw("clipped_text"), rect: "wide" })).toEqual([]); + expect(parseLayoutIssue("clipped_text")).toEqual([]); + }); +}); + describe("collectSeekClock", () => { afterEach(() => { Reflect.deleteProperty(window, "__timelines"); diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts index 7e56c33672..864f04006e 100644 --- a/packages/cli/src/utils/checkBrowser.ts +++ b/packages/cli/src/utils/checkBrowser.ts @@ -29,7 +29,7 @@ import { shouldIgnoreHttpError, shouldIgnoreRequestFailure, } from "../commands/validate.js"; -import { loadBrowserScript } from "../commands/layout.js"; +import { loadBrowserScript } from "../commands/browserScript.js"; import { normalizeErrorMessage } from "./errorMessage.js"; import { ambiguousIssue, type MotionFrame } from "./motionAudit.js"; import type { LayoutIssue, LayoutIssueCode, LayoutRect } from "./layoutAudit.js"; @@ -2091,7 +2091,7 @@ function joinContrastEntries( }); } -function parseLayoutIssue(value: unknown): LayoutIssue[] { +export function parseLayoutIssue(value: unknown): LayoutIssue[] { if (!isRecord(value)) return []; const code = layoutCodeValue(Reflect.get(value, "code")); const severity = severityValue(Reflect.get(value, "severity")); diff --git a/packages/cli/src/utils/layoutAudit.test.ts b/packages/cli/src/utils/layoutAudit.test.ts index fd1f9c71de..91ec56f795 100644 --- a/packages/cli/src/utils/layoutAudit.test.ts +++ b/packages/cli/src/utils/layoutAudit.test.ts @@ -180,6 +180,16 @@ describe("layoutAudit helpers", () => { expect(formatted).toContain("\n Fix: pad \\x1b]52;c;Y2xpcA==\\x07"); }); + it("shows control characters in an issue code from the page as visible escapes", () => { + const formatted = formatLayoutIssue({ + ...issue("text_box_overflow", "error"), + code: "text_box_overflow\u001b]52;c;Y2xpcA==\u0007" as LayoutIssue["code"], + }); + + expect(formatted).not.toContain("\u001b"); + expect(formatted).toContain("text_box_overflow\\x1b]52;c;Y2xpcA==\\x07"); + }); + it("formats collapsed issue time ranges", () => { const formatted = formatLayoutIssue({ ...issue("text_box_overflow", "error"), diff --git a/packages/cli/src/utils/layoutAudit.ts b/packages/cli/src/utils/layoutAudit.ts index 908831d06d..57245ca08d 100644 --- a/packages/cli/src/utils/layoutAudit.ts +++ b/packages/cli/src/utils/layoutAudit.ts @@ -158,7 +158,7 @@ export function formatLayoutIssue(issue: LayoutIssue): string { } const parts = [ timeLabel, - issue.code, + terminalText(issue.code), terminalText(issue.selector), issue.containerSelector ? `inside ${terminalText(issue.containerSelector)}` : "", issue.overflow ? `overflowed ${formatOverflow(issue.overflow)}` : "", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a50244e1bd..0cbedad7d6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -495,4 +495,4 @@ export { type MotionBlurFingerprint, type MotionBlurFingerprintField, } from "./motionBlurFingerprint.js"; -export { terminalText, terminalTextDeep } from "./terminalText.js"; +export { terminalLines, terminalText, terminalTextDeep } from "./terminalText.js"; diff --git a/packages/core/src/terminalText.test.ts b/packages/core/src/terminalText.test.ts index d192d4d446..565ae4e777 100644 --- a/packages/core/src/terminalText.test.ts +++ b/packages/core/src/terminalText.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { terminalText, terminalTextDeep } from "./terminalText.js"; +import { terminalLines, terminalText, terminalTextDeep } from "./terminalText.js"; describe("terminalText", () => { it("leaves ordinary text and tabs alone", () => { @@ -13,6 +13,14 @@ describe("terminalText", () => { }); }); +describe("terminalLines", () => { + it("keeps line breaks and escapes every other control in each line", () => { + expect(terminalLines("Install failed\n a\u001b]0;t\u0007\r\n b\u009b")).toBe( + "Install failed\n a\\x1b]0;t\\x07\\x0d\n b\\x9b", + ); + }); +}); + describe("terminalTextDeep", () => { it("escapes every string in nested arrays and objects and keeps other values", () => { const shown = terminalTextDeep({ diff --git a/packages/core/src/terminalText.ts b/packages/core/src/terminalText.ts index 905cdc8620..7aedc29eee 100644 --- a/packages/core/src/terminalText.ts +++ b/packages/core/src/terminalText.ts @@ -10,6 +10,10 @@ export function terminalText(text: string): string { return shown; } +export function terminalLines(text: string): string { + return text.split("\n").map(terminalText).join("\n"); +} + const isPlainObject = (value: object) => { const proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null;