From 470c68c3a8d950f4aeb9035d8755082c657c4baa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 15 Nov 2026 15:37:31 -0500 Subject: [PATCH 1/2] fix: warnings that name project files print control characters as visible escapes The CLI already escaped control characters in the text its own commands print, but warnings from core, producer and engine went to the terminal raw. A composition whose sub-composition path held ESC or BEL still drove the terminal through the bundler's "Skipping sub-composition" warning in `info --media` and `snapshot`. terminalText moves to core so there is one sanitiser, the CLI imports it from there, and the library warnings that carry project text (the bundler, the producer logger, the file server, render path skips, asset load failures, FrameCapture, the import map, fonts, figma and atomic file warnings) pass that text through it. --- packages/cli/src/commands/check.ts | 2 +- packages/cli/src/commands/compositions.ts | 2 +- packages/cli/src/commands/info.ts | 3 +- packages/cli/src/commands/keyframes.ts | 2 +- packages/cli/src/commands/lint.ts | 2 +- packages/cli/src/commands/snapshot.ts | 2 +- .../server/studioServer.renderBrowser.test.ts | 2 +- packages/cli/src/utils/layoutAudit.ts | 2 +- .../cli/src/utils/leftOutReference.test.ts | 2 +- packages/cli/src/utils/leftOutReference.ts | 2 +- packages/cli/src/utils/lintFormat.ts | 2 +- packages/cli/src/utils/receivedRender.test.ts | 2 +- packages/cli/src/utils/receivedRender.ts | 3 +- packages/core/src/atomicFile.ts | 7 +++- .../compiler/htmlBundler.terminalText.test.ts | 36 +++++++++++++++++++ packages/core/src/compiler/htmlBundler.ts | 5 ++- .../src/compiler/inlineSubCompositions.ts | 6 +++- packages/core/src/figma/jsonl.ts | 5 ++- packages/core/src/fonts/deterministicFonts.ts | 5 +-- packages/core/src/index.ts | 1 + .../utils => core/src}/terminalText.test.ts | 0 .../src/utils => core/src}/terminalText.ts | 0 packages/engine/src/services/frameCapture.ts | 10 ++++-- packages/producer/src/logger.test.ts | 9 +++++ packages/producer/src/logger.ts | 12 ++++--- packages/producer/src/services/fileServer.ts | 6 ++-- .../producer/src/services/render/shared.ts | 7 ++-- .../src/services/render/stages/probeStage.ts | 3 +- 28 files changed, 106 insertions(+), 34 deletions(-) create mode 100644 packages/core/src/compiler/htmlBundler.terminalText.test.ts rename packages/{cli/src/utils => core/src}/terminalText.test.ts (100%) rename packages/{cli/src/utils => core/src}/terminalText.ts (100%) diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 6da1d44cfd9..2c016f66212 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { captureArtifactRevision } from "../utils/artifactCapture.js"; import { pngDimensions } from "../utils/pngDimensions.js"; import { randomUUID } from "node:crypto"; @@ -18,7 +19,6 @@ import type { ArgsDef } from "citty"; import type { Example } from "./_examples.js"; import { parseAt } from "./layout.js"; import { c } from "../ui/colors.js"; -import { terminalText } from "../utils/terminalText.js"; import { registerBrowserSessionCleanup } from "../browser/launch.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { CliUsageError, failUsage, setCommandExitCode } from "../utils/commandResult.js"; diff --git a/packages/cli/src/commands/compositions.ts b/packages/cli/src/commands/compositions.ts index f1abc76e1c4..303a5227ddf 100644 --- a/packages/cli/src/commands/compositions.ts +++ b/packages/cli/src/commands/compositions.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import { readFileSync } from "node:fs"; @@ -15,7 +16,6 @@ import { ensureDOMParser } from "../utils/dom.js"; import { resolveProject } from "../utils/project.js"; import { resolveReferencedStart } from "@hyperframes/engine"; import { withMeta } from "../utils/updateCheck.js"; -import { terminalText } from "../utils/terminalText.js"; interface CompositionInfo { id: string; diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts index 79cad6e718f..3aef4cd40a2 100644 --- a/packages/cli/src/commands/info.ts +++ b/packages/cli/src/commands/info.ts @@ -8,14 +8,13 @@ export const examples: Example[] = [ ["List the clips the render hears, on the film's clock", "hyperframes info --media --json"], ]; import { join } from "node:path"; -import { parseHtml, CANVAS_DIMENSIONS } from "@hyperframes/core"; +import { parseHtml, CANVAS_DIMENSIONS, terminalText } from "@hyperframes/core"; import { findRootCompositionElement, readCompositionSize, } from "@hyperframes/core/runtime/composition-length"; import { readDataDurationSeconds } from "@hyperframes/parsers/media-duration"; import { heardClips } from "../utils/projectMedia.js"; -import { terminalText } from "../utils/terminalText.js"; import { c } from "../ui/colors.js"; import { formatBytes, label } from "../ui/format.js"; import { ensureDOMParser } from "../utils/dom.js"; diff --git a/packages/cli/src/commands/keyframes.ts b/packages/cli/src/commands/keyframes.ts index aa80e544fd4..d566495aeec 100644 --- a/packages/cli/src/commands/keyframes.ts +++ b/packages/cli/src/commands/keyframes.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import { existsSync, readFileSync } from "node:fs"; import { isWithinProjectRoot, readProjectFile } from "@hyperframes/parsers/asset-resolution"; @@ -9,7 +10,6 @@ import { } from "@hyperframes/core/gsap-parser"; import type { Example } from "./_examples.js"; import { c } from "../ui/colors.js"; -import { terminalText } from "../utils/terminalText.js"; import { ensureDOMParser } from "../utils/dom.js"; import { resolveProject } from "../utils/project.js"; import { withMeta } from "../utils/updateCheck.js"; diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.ts index 1108b95a991..d7f4cf8af7c 100644 --- a/packages/cli/src/commands/lint.ts +++ b/packages/cli/src/commands/lint.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { setCommandExitCode } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -18,7 +19,6 @@ import { isUnderCompositions, resolveLintTarget } from "../utils/project.js"; import { trackLintRun } from "../telemetry/lintRun.js"; import { getRunId } from "../telemetry/runId.js"; import { withMeta } from "../utils/updateCheck.js"; -import { terminalText } from "../utils/terminalText.js"; export default defineCommand({ meta: { diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts index fdcd2db983a..53c1d11f7a1 100644 --- a/packages/cli/src/commands/snapshot.ts +++ b/packages/cli/src/commands/snapshot.ts @@ -88,6 +88,7 @@ import { sourceTimeAt, timeAtSourceTime, type RateSpec, + terminalText, } from "@hyperframes/core"; import { parseHTML } from "linkedom"; import { resolveProject } from "../utils/project.js"; @@ -101,7 +102,6 @@ import { normalizeErrorMessage, atStep } from "../utils/errorMessage.js"; import { describeSharpLoadFailure } from "../utils/sharpLoadFailure.js"; import { serveStaticProjectHtml } from "../utils/staticProjectServer.js"; import { c } from "../ui/colors.js"; -import { terminalText } from "../utils/terminalText.js"; import { writeCaptureFileSync } from "../capture/captureFile.js"; import { runCancellableProcess } from "../utils/cancellableProcess.js"; import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js"; diff --git a/packages/cli/src/server/studioServer.renderBrowser.test.ts b/packages/cli/src/server/studioServer.renderBrowser.test.ts index 6ca37a10c42..d0cc1d97806 100644 --- a/packages/cli/src/server/studioServer.renderBrowser.test.ts +++ b/packages/cli/src/server/studioServer.renderBrowser.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createStudioServer, type StudioServer } from "./studioServer.js"; -import { terminalText } from "../utils/terminalText.js"; +import { terminalText } from "@hyperframes/core"; const mocks = vi.hoisted(() => ({ resolveRenderBrowser: vi.fn(), diff --git a/packages/cli/src/utils/layoutAudit.ts b/packages/cli/src/utils/layoutAudit.ts index 9b522d76ebb..908831d06db 100644 --- a/packages/cli/src/utils/layoutAudit.ts +++ b/packages/cli/src/utils/layoutAudit.ts @@ -1,5 +1,5 @@ +import { terminalText } from "@hyperframes/core"; import { formatFindingTimes } from "./checkFindings.js"; -import { terminalText } from "./terminalText.js"; export interface LayoutRect { left: number; top: number; diff --git a/packages/cli/src/utils/leftOutReference.test.ts b/packages/cli/src/utils/leftOutReference.test.ts index 6d8b11e2666..f22947b6626 100644 --- a/packages/cli/src/utils/leftOutReference.test.ts +++ b/packages/cli/src/utils/leftOutReference.test.ts @@ -4,7 +4,7 @@ import { dirname, join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { stagePublishFiles } from "./publishProject.js"; import type { LeftOutReference } from "./leftOutReference.js"; -import { terminalText } from "./terminalText.js"; +import { terminalText } from "@hyperframes/core"; const dirs: string[] = []; afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true }))); diff --git a/packages/cli/src/utils/leftOutReference.ts b/packages/cli/src/utils/leftOutReference.ts index efb72a6cfed..d15102b37a6 100644 --- a/packages/cli/src/utils/leftOutReference.ts +++ b/packages/cli/src/utils/leftOutReference.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { isAbsolute, relative } from "node:path"; import { type LeftOutReason, @@ -5,7 +6,6 @@ import { } from "@hyperframes/studio-server/outside-file"; import { realFilePath } from "@hyperframes/studio-server/safe-path"; import { namesAnotherNetworkRoot } from "@hyperframes/parsers/asset-resolution"; -import { terminalText } from "./terminalText.js"; export type { LeftOutReason }; diff --git a/packages/cli/src/utils/lintFormat.ts b/packages/cli/src/utils/lintFormat.ts index 98a486b5143..bbc0b00ebe7 100644 --- a/packages/cli/src/utils/lintFormat.ts +++ b/packages/cli/src/utils/lintFormat.ts @@ -1,5 +1,5 @@ +import { terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; -import { terminalText } from "./terminalText.js"; import type { ProjectLintResult } from "./lintProject.js"; export interface LintFormatOptions { diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 43a6c6b7a72..437b1efc7b4 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { compileForRender } from "../../../producer/src/services/htmlCompiler.js"; import { outsideAssetsAllowed } from "./receivedRender.js"; -import { terminalText } from "./terminalText.js"; +import { terminalText } from "@hyperframes/core"; const SIGNATURES = { png: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d]), diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 0b352e7aa01..1e9dd5b5869 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -10,13 +10,12 @@ import { import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; -import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; +import { isNonRelativeUrl, isPathInside, terminalText } from "@hyperframes/core"; import { namesAnotherNetworkRoot, resolveCompositionSrc, } from "@hyperframes/parsers/asset-resolution"; import { linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; -import { terminalText } from "./terminalText.js"; import { walkBudget } from "./walkBudget.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; diff --git a/packages/core/src/atomicFile.ts b/packages/core/src/atomicFile.ts index bc4933b7493..c17dc7c2958 100644 --- a/packages/core/src/atomicFile.ts +++ b/packages/core/src/atomicFile.ts @@ -3,6 +3,7 @@ import { createHash, randomBytes } from "node:crypto"; import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { realpath } from "./safePath.js"; import { renameWithRetry } from "./renameWithRetry.js"; +import { terminalText } from "./terminalText.js"; type SiblingFileSystem = Pick; type DirectFileSystem = SiblingFileSystem & Pick; @@ -91,7 +92,11 @@ export function createFileAtomically( try { operations.unlinkSync(tempPath); } catch (error) { - console.warn(`[hyperframes] created ${filePath} but could not remove ${tempPath}: ${error}`); + console.warn( + terminalText( + `[hyperframes] created ${filePath} but could not remove ${tempPath}: ${error}`, + ), + ); } }); } diff --git a/packages/core/src/compiler/htmlBundler.terminalText.test.ts b/packages/core/src/compiler/htmlBundler.terminalText.test.ts new file mode 100644 index 00000000000..c8e3d9aa4eb --- /dev/null +++ b/packages/core/src/compiler/htmlBundler.terminalText.test.ts @@ -0,0 +1,36 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { bundleToSingleHtml } from "./htmlBundler"; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("bundler warnings that name project files", () => { + it.each([ + ["raw", "sub\u001b]0;title\u0007\u001b[2K.html"], + ["as numeric entities", "sub]0;title.html"], + ])( + "write control characters in a sub-composition path out as visible escapes (%s)", + async (_, src) => { + const dir = mkdtempSync(join(tmpdir(), "hf-bundler-terminal-")); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + writeFileSync( + join(dir, "index.html"), + `
`, + ); + await bundleToSingleHtml(dir, { runtime: "placeholder" }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("Skipping sub-composition"); + expect(printed).toContain("\\x1b]0;title\\x07"); + for (const control of ["\u001b", "\u0007"]) expect(printed).not.toContain(control); + }, + ); +}); diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index c301a482cc9..71ec61aebde 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -88,6 +88,7 @@ import { ensureHfIds } from "@hyperframes/parsers/hf-ids"; import { readTextFile } from "@hyperframes/parsers/asset-resolution"; import { HF_COLOR_GRADING_ATTR } from "../colorGrading"; import { assignMediaRenderIds } from "./mediaRenderIds"; +import { terminalText } from "../terminalText.js"; const DEFAULT_RUNTIME_SCRIPT_URL = ""; @@ -1226,7 +1227,9 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi scriptErrorLabel: "[HyperFrames] composition script error:", onMissingComposition: (srcPath: string, reason?: string) => { console.warn( - `[Bundler] Skipping sub-composition "${srcPath}": ${reason ?? "the file could not be found"}.`, + terminalText( + `[Bundler] Skipping sub-composition "${srcPath}": ${reason ?? "the file could not be found"}.`, + ), ); }, }); diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts index c4f591e156f..e9f86ca74ca 100644 --- a/packages/core/src/compiler/inlineSubCompositions.ts +++ b/packages/core/src/compiler/inlineSubCompositions.ts @@ -49,6 +49,7 @@ import { extractedCompositionAssets, } from "./compositionAssembly"; import { SCENE_NO_SWAP_ATTR, SCENE_PART_ATTR } from "../sceneParts"; +import { terminalText } from "../terminalText"; // Anything a scene script can leave running, pending or registered outside its timeline, or that // throws when run again: only the timeline is torn down when a scene is swapped, so when unsure, refuse. @@ -625,7 +626,10 @@ export function inlineSubCompositions( return authored.endsWith("/") && !urlLike.endsWith("/") ? `${urlLike}/` : urlLike; }); if (map) importMaps.push(map); - else console.warn(`[HyperFrames] ${src}: import map is not valid JSON, so it is skipped.`); + else + console.warn( + terminalText(`[HyperFrames] ${src}: import map is not valid JSON, so it is skipped.`), + ); } else if (type === "module" && !externalSrc) { const prelude = scriptCompositionId ? scopedModulePrelude(runtimeCompId || scopeCompId || scriptCompositionId, src) diff --git a/packages/core/src/figma/jsonl.ts b/packages/core/src/figma/jsonl.ts index a068624e958..2c4a7f97d8c 100644 --- a/packages/core/src/figma/jsonl.ts +++ b/packages/core/src/figma/jsonl.ts @@ -1,4 +1,5 @@ import { existsSync, readFileSync } from "node:fs"; +import { terminalText } from "../terminalText"; /** Parse a .jsonl file into values, skipping blank/malformed lines. */ export function readJsonlValues(path: string): unknown[] { @@ -12,7 +13,9 @@ export function readJsonlValues(path: string): unknown[] { } catch { // ponytail: skip malformed lines (partial write from a crash), but say // so — a silent skip reads as "no record found" downstream. - console.warn(`skipping malformed jsonl line in ${path}: ${trimmed.slice(0, 40)}…`); + console.warn( + terminalText(`skipping malformed jsonl line in ${path}: ${trimmed.slice(0, 40)}…`), + ); } } return out; diff --git a/packages/core/src/fonts/deterministicFonts.ts b/packages/core/src/fonts/deterministicFonts.ts index 78a7d46a3a1..967ccaf59be 100644 --- a/packages/core/src/fonts/deterministicFonts.ts +++ b/packages/core/src/fonts/deterministicFonts.ts @@ -28,6 +28,7 @@ import { type FontDiagPath, } from "./fontDiagnostics.js"; import { hyperframesCacheDir } from "../cacheDir.js"; +import { terminalText } from "../terminalText.js"; export type { FontDiagnostics }; @@ -1879,8 +1880,8 @@ export interface FontLogger { } const STDERR_LOGGER: FontLogger = { - warn: (message) => console.warn(`[WARN] ${message}`), - info: (message) => console.error(`[INFO] ${message}`), + warn: (message) => console.warn(terminalText(`[WARN] ${message}`)), + info: (message) => console.error(terminalText(`[INFO] ${message}`)), }; export interface InjectDeterministicFontFacesOptions { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 692a937600c..6e411271d3d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -495,3 +495,4 @@ export { type MotionBlurFingerprint, type MotionBlurFingerprintField, } from "./motionBlurFingerprint.js"; +export { terminalText } from "./terminalText.js"; diff --git a/packages/cli/src/utils/terminalText.test.ts b/packages/core/src/terminalText.test.ts similarity index 100% rename from packages/cli/src/utils/terminalText.test.ts rename to packages/core/src/terminalText.test.ts diff --git a/packages/cli/src/utils/terminalText.ts b/packages/core/src/terminalText.ts similarity index 100% rename from packages/cli/src/utils/terminalText.ts rename to packages/core/src/terminalText.ts diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts index 7a28ad405e7..1bcbefc51c7 100644 --- a/packages/engine/src/services/frameCapture.ts +++ b/packages/engine/src/services/frameCapture.ts @@ -31,6 +31,7 @@ import { RUNTIME_BOOTSTRAP_ATTR, SCENE_CALLBACK_ERROR_PREFIX, type RawAuthoredTiming, + terminalText, } from "@hyperframes/core"; import { readReferenceBackground } from "./referenceBackground.js"; @@ -2350,7 +2351,9 @@ export async function pollSubCompositionTimelines( onPending?.(pendingIds); const missing = pendingIds.join(", "); if (scriptFailureBail) { - console.warn(`[FrameCapture] Composition(s) still waiting on the failed script: ${missing}.`); + console.warn( + `[FrameCapture] Composition(s) still waiting on the failed script: ${terminalText(missing)}.`, + ); } else { console.warn( `[FrameCapture] Sub-composition timelines not registered after ${timeoutMs}ms: ${missing}. ` + @@ -2548,7 +2551,10 @@ function recordCaptureWarnings(session: CaptureSession, warnings: readonly Captu continue; } session.warnings.push(warning); - console.warn(`[FrameCapture:${warning.code}] ${warning.message}`, warning.details ?? {}); + console.warn( + `[FrameCapture:${warning.code}] ${terminalText(warning.message)}`, + warning.details ?? {}, + ); } } diff --git a/packages/producer/src/logger.test.ts b/packages/producer/src/logger.test.ts index 90b6797a2f0..b826e152a2b 100644 --- a/packages/producer/src/logger.test.ts +++ b/packages/producer/src/logger.test.ts @@ -185,6 +185,15 @@ describe("createConsoleLogger", () => { expect(errorSpy.mock.calls[0]?.[0]).toBe('[INFO] hello {"a":1,"b":"two"}'); }); + it("writes control characters in the message out as visible escapes", () => { + const log = createConsoleLogger("info"); + log.warn("clip \u001b]0;title\u0007.mp4", { src: "\u001b" }); + + expect(warnSpy.mock.calls[0]?.[0]).toBe( + '[WARN] clip \\x1b]0;title\\x07.mp4 {"src":"\\u001b"}', + ); + }); + it("emits message only when meta is omitted", () => { const log = createConsoleLogger("info"); log.info("plain"); diff --git a/packages/producer/src/logger.ts b/packages/producer/src/logger.ts index 34952b40e7d..0397a38c1a9 100644 --- a/packages/producer/src/logger.ts +++ b/packages/producer/src/logger.ts @@ -1,7 +1,7 @@ /** * Pluggable Producer Logger * - * Lightweight pluggable logger with zero dependencies. + * Lightweight pluggable logger. * Default implementation writes to console with level filtering. * * All levels write to stderr (console.error/console.warn), never stdout — @@ -14,6 +14,8 @@ * implementing the ProducerLogger interface. */ +import { terminalText } from "@hyperframes/core"; + export type LogLevel = "error" | "warn" | "info" | "debug"; export interface ProducerLogger { @@ -67,22 +69,22 @@ export function createConsoleLogger(level: LogLevel = "info"): ProducerLogger { return { error(message, meta) { if (shouldLog("error")) { - console.error(`[ERROR] ${message}${formatMeta(meta)}`); + console.error(`[ERROR] ${terminalText(message)}${formatMeta(meta)}`); } }, warn(message, meta) { if (shouldLog("warn")) { - console.warn(`[WARN] ${message}${formatMeta(meta)}`); + console.warn(`[WARN] ${terminalText(message)}${formatMeta(meta)}`); } }, info(message, meta) { if (shouldLog("info")) { - console.error(`[INFO] ${message}${formatMeta(meta)}`); + console.error(`[INFO] ${terminalText(message)}${formatMeta(meta)}`); } }, debug(message, meta) { if (shouldLog("debug")) { - console.error(`[DEBUG] ${message}${formatMeta(meta)}`); + console.error(`[DEBUG] ${terminalText(message)}${formatMeta(meta)}`); } }, isLevelEnabled(msgLevel) { diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.ts index 7388001b5e4..9dc44a90792 100644 --- a/packages/producer/src/services/fileServer.ts +++ b/packages/producer/src/services/fileServer.ts @@ -30,7 +30,7 @@ import { join, extname, resolve, sep } from "node:path"; import { injectScriptsAtHeadStart, injectScriptsIntoHtml } from "@hyperframes/core/compiler"; import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document"; import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-mark"; -import { fpsToNumber, type Fps } from "@hyperframes/core"; +import { fpsToNumber, type Fps, terminalText } from "@hyperframes/core"; import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path"; import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags"; import { openRangeEnd } from "@hyperframes/studio-server/media-range"; @@ -820,7 +820,7 @@ export function createFileServer(options: FileServerOptions): Promise console.warn(`[FileServer] ${line}`); + const warnLeftOut = (line: string) => console.warn(`[FileServer] ${terminalText(line)}`); let listeningPort = -1; app.use(async function loadEachFileOnlyAsItsNamedType(c, next) { @@ -852,7 +852,7 @@ export function createFileServer(options: FileServerOptions): Promise Date: Sun, 15 Nov 2026 16:40:21 -0500 Subject: [PATCH 2/2] fix: every library warning that carries project text escapes control characters --- .../compiler/htmlBundler.terminalText.test.ts | 19 +++++ packages/core/src/compiler/htmlBundler.ts | 20 ++++-- packages/core/src/compiler/importMaps.ts | 6 +- packages/engine/src/services/audioFxRender.ts | 5 +- packages/engine/src/services/audioMixer.ts | 5 +- .../frameCapture-subTimelineTerminal.test.ts | 50 +++++++++++++ packages/engine/src/services/frameCapture.ts | 72 ++++++++++++------- packages/producer/src/logger.test.ts | 7 ++ packages/producer/src/logger.ts | 2 +- .../producer/src/services/htmlCompiler.ts | 5 +- 10 files changed, 155 insertions(+), 36 deletions(-) create mode 100644 packages/engine/src/services/frameCapture-subTimelineTerminal.test.ts diff --git a/packages/core/src/compiler/htmlBundler.terminalText.test.ts b/packages/core/src/compiler/htmlBundler.terminalText.test.ts index c8e3d9aa4eb..e5ab86af98a 100644 --- a/packages/core/src/compiler/htmlBundler.terminalText.test.ts +++ b/packages/core/src/compiler/htmlBundler.terminalText.test.ts @@ -33,4 +33,23 @@ describe("bundler warnings that name project files", () => { for (const control of ["\u001b", "\u0007"]) expect(printed).not.toContain(control); }, ); + + it("write control characters in an inline template's id out as visible escapes when its import map is skipped", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-bundler-terminal-")); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const id = "sc]0;title"; + try { + writeFileSync( + join(dir, "index.html"), + `
`, + ); + await bundleToSingleHtml(dir, { runtime: "placeholder" }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("sc\\x1b]0;title\\x07: import map is not valid JSON"); + for (const control of ["\u001b", "\u0007"]) expect(printed).not.toContain(control); + }); }); diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index 71ec61aebde..3f4d3d17912 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -383,13 +383,17 @@ function safeStatSize(filePath: string): number | null { function warnAssetTooLargeToInline(assetPath: string, byteLength: number): void { const mb = (byteLength / (1024 * 1024)).toFixed(1); console.warn( - `[HyperFrames] Not inlining "${assetPath}" (${mb} MB exceeds the ${MAX_INLINE_ASSET_BYTES / (1024 * 1024)} MB inline limit). The bundle may not be self-contained.`, + terminalText( + `[HyperFrames] Not inlining "${assetPath}" (${mb} MB exceeds the ${MAX_INLINE_ASSET_BYTES / (1024 * 1024)} MB inline limit). The bundle may not be self-contained.`, + ), ); } function warnInlineBudgetExhausted(assetPath: string): void { console.warn( - `[HyperFrames] Not inlining "${assetPath}" and later assets: the bundle already inlines ${MAX_INLINED_BUNDLE_CHARS / (1024 * 1024)} MB of data URLs. The bundle may not be self-contained.`, + terminalText( + `[HyperFrames] Not inlining "${assetPath}" and later assets: the bundle already inlines ${MAX_INLINED_BUNDLE_CHARS / (1024 * 1024)} MB of data URLs. The bundle may not be self-contained.`, + ), ); } @@ -462,7 +466,9 @@ function warnColorGradingLutNotInlined(lutSrc: string): void { const trimmed = lutSrc.trim(); if (!isRelativeUrl(trimmed)) return; console.warn( - `[HyperFrames] Could not inline color grading LUT "${trimmed}". The rendered bundle may not be self-contained.`, + terminalText( + `[HyperFrames] Could not inline color grading LUT "${trimmed}". The rendered bundle may not be self-contained.`, + ), ); } @@ -1025,7 +1031,9 @@ function hoistCompositionScripts( if (map) opts.importMaps.push(map); else console.warn( - `[HyperFrames] ${opts.compId}: import map is not valid JSON, so it is skipped.`, + terminalText( + `[HyperFrames] ${opts.compId}: import map is not valid JSON, so it is skipped.`, + ), ); } else if (!externalSrc && type === "module") { const prelude = opts.compId ? scopedModulePrelude(opts.runtimeCompId || opts.compId) : ""; @@ -1138,7 +1146,9 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi }); if (!staticGuard.isValid) { console.warn( - `[StaticGuard] Invalid HyperFrame contract: ${staticGuard.missingKeys.join("; ")}`, + terminalText( + `[StaticGuard] Invalid HyperFrame contract: ${staticGuard.missingKeys.join("; ")}`, + ), ); } } diff --git a/packages/core/src/compiler/importMaps.ts b/packages/core/src/compiler/importMaps.ts index c5920fde8f3..bbc074226f6 100644 --- a/packages/core/src/compiler/importMaps.ts +++ b/packages/core/src/compiler/importMaps.ts @@ -1,3 +1,5 @@ +import { terminalText } from "../terminalText"; + type SpecifierMap = Record; /** The subset of an import map a composition can declare. */ @@ -65,7 +67,9 @@ function mergeEntries(into: SpecifierMap, from: SpecifierMap | undefined, where: }); } else if (into[specifier] !== url) { console.warn( - `[HyperFrames] import map conflict for "${specifier}"${where}: keeping ${into[specifier]}, ignoring ${url}.`, + terminalText( + `[HyperFrames] import map conflict for "${specifier}"${where}: keeping ${into[specifier]}, ignoring ${url}.`, + ), ); } } diff --git a/packages/engine/src/services/audioFxRender.ts b/packages/engine/src/services/audioFxRender.ts index f032e8bab9b..7fe41c35df7 100644 --- a/packages/engine/src/services/audioFxRender.ts +++ b/packages/engine/src/services/audioFxRender.ts @@ -35,6 +35,7 @@ import { createEnvelopeWalker } from "./audioVolumeEnvelope.js"; import { riffChunks, wavFormatTag } from "./wavChunks.js"; import { windowPrerollSeconds } from "./audioFxWarmup.js"; import type { AudioVolumeKeyframe } from "./audioMixer.types.js"; +import { terminalText } from "@hyperframes/core"; export class AudioFxRenderError extends Error { constructor(message: string) { @@ -424,7 +425,9 @@ function chainPrerollSeconds( ); if (capped) { console.warn( - `Audio FX for track ${trackId}: the chain remembers longer than the ${limits.maxPrerollSeconds}s pre-roll cap, so its oldest repeats are cut at window seams`, + terminalText( + `Audio FX for track ${trackId}: the chain remembers longer than the ${limits.maxPrerollSeconds}s pre-roll cap, so its oldest repeats are cut at window seams`, + ), ); } return seconds; diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts index 444e66e9d40..58cd3ff1bc3 100644 --- a/packages/engine/src/services/audioMixer.ts +++ b/packages/engine/src/services/audioMixer.ts @@ -70,6 +70,7 @@ import { sourceTimeAt, timeAtSourceTime, type RateSpec, + terminalText, } from "@hyperframes/core"; import { readMasterFxChain, resolveAudioGroups } from "@hyperframes/core/audio-groups"; import { applyAudioFxChain, AudioFxRenderError } from "./audioFxRender.js"; @@ -1564,7 +1565,9 @@ export async function processCompositionAudio( // Fallback: if no duration was specified, probe the actual file if (element.end - element.start <= 0) { console.warn( - `[audioMixer] ${element.id} has no data-duration or data-end; its length is unknown, so it plays to the end of its source`, + terminalText( + `[audioMixer] ${element.id} has no data-duration or data-end; its length is unknown, so it plays to the end of its source`, + ), ); let metadata; try { diff --git a/packages/engine/src/services/frameCapture-subTimelineTerminal.test.ts b/packages/engine/src/services/frameCapture-subTimelineTerminal.test.ts new file mode 100644 index 00000000000..f938652da63 --- /dev/null +++ b/packages/engine/src/services/frameCapture-subTimelineTerminal.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Page } from "puppeteer-core"; +import { pollSubCompositionTimelines } from "./frameCapture.js"; + +const PENDING_ID = "scene\u001b]0;title\u0007"; + +// The id scan returns a composition id that carries terminal controls; every other evaluate says "not ready". +function pageWithPendingId(): Page { + return { + evaluate: vi.fn(async (expr: string | (() => unknown)) => { + if (typeof expr === "function") return true; + return expr.includes("m.push(id)") ? [PENDING_ID] : false; + }), + } as unknown as Page; +} + +function printedWarnings(warn: ReturnType): string { + return warn.mock.calls.map((call: unknown[]) => call.join(" ")).join("\n"); +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("pollSubCompositionTimelines warnings that name compositions and scripts", () => { + it("write control characters out as visible escapes when a script failed", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const outcome = await pollSubCompositionTimelines(pageWithPendingId(), 60_000, { + intervalMs: 5, + getScriptLoadFailures: () => ["http://localhost/a\u001b[2K.js"], + scriptFailureGraceMs: 10, + }); + + expect(outcome).toBe("script_failure"); + const printed = printedWarnings(warn); + expect(printed).toContain("a\\x1b[2K.js"); + expect(printed).toContain("scene\\x1b]0;title\\x07"); + for (const control of ["\u001b", "\u0007"]) expect(printed).not.toContain(control); + }); + + it("write control characters out as visible escapes when the wait times out", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const outcome = await pollSubCompositionTimelines(pageWithPendingId(), 30, { intervalMs: 5 }); + + expect(outcome).toBe("timeout"); + const printed = printedWarnings(warn); + expect(printed).toContain("scene\\x1b]0;title\\x07"); + for (const control of ["\u001b", "\u0007"]) expect(printed).not.toContain(control); + }); +}); diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts index 1bcbefc51c7..acdb6763795 100644 --- a/packages/engine/src/services/frameCapture.ts +++ b/packages/engine/src/services/frameCapture.ts @@ -1201,7 +1201,9 @@ async function initDrawElementOrTransparentBackground( session.deGateReason = reason; session.deFallbackTrigger = trigger; console.error( - `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ${message}`, + terminalText( + `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ${message}`, + ), ); await routeToFallback(); }; @@ -1306,8 +1308,10 @@ async function initDrawElementOrTransparentBackground( session.deGateReason = "3d_init_failed"; session.deFallbackTrigger = "3d_init_failed"; console.error( - `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ` + - `3D projection init failed (${threeD.reason ?? "unknown"})`, + terminalText( + `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ` + + `3D projection init failed (${threeD.reason ?? "unknown"})`, + ), ); await routeToFallback(); return; @@ -1392,7 +1396,9 @@ async function cssEffectRiskFrames( return live && withFramesAfterCallback(live, scan.callbackFrom, fps, totalFrames); } catch (error) { console.error( - `[engine] fast capture: effect scan failed (${error instanceof Error ? error.message : String(error)})`, + terminalText( + `[engine] fast capture: effect scan failed (${error instanceof Error ? error.message : String(error)})`, + ), ); return null; } finally { @@ -2318,10 +2324,12 @@ export async function pollSubCompositionTimelines( if (failed.length > 0 && sinceFailure >= graceMs) { scriptFailureBail = true; console.warn( - `[FrameCapture] Sub-composition timeline wait cut short after ${now - start}ms: ` + - `script(s) failed (${failed.join(", ")}), so ` + - `the timeline registration they carry can never arrive. ` + - `Fix the script.`, + terminalText( + `[FrameCapture] Sub-composition timeline wait cut short after ${now - start}ms: ` + + `script(s) failed (${failed.join(", ")}), so ` + + `the timeline registration they carry can never arrive. ` + + `Fix the script.`, + ), ); break; } @@ -2356,9 +2364,11 @@ export async function pollSubCompositionTimelines( ); } else { console.warn( - `[FrameCapture] Sub-composition timelines not registered after ${timeoutMs}ms: ${missing}. ` + - `Compositions that load data asynchronously (e.g. fetch) must register window.__timelines[id] after setup completes. ` + - `Compositions intentionally driven without GSAP timelines (CSS animations / rAF) can mark the host with data-no-timeline to skip this wait.`, + terminalText( + `[FrameCapture] Sub-composition timelines not registered after ${timeoutMs}ms: ${missing}. ` + + `Compositions that load data asynchronously (e.g. fetch) must register window.__timelines[id] after setup completes. ` + + `Compositions intentionally driven without GSAP timelines (CSS animations / rAF) can mark the host with data-no-timeline to skip this wait.`, + ), ); } return scriptFailureBail ? "script_failure" : "timeout"; @@ -3117,7 +3127,7 @@ export async function initializeSession(session: CaptureSession): Promise !quietRuntimeDetail(text) && !loggedEarlierInRender(session, text) ) { - console.error(diagnostic.text); + console.error(terminalText(diagnostic.text)); } appendBrowserDiagnostic(session, diagnostic.text); @@ -3133,7 +3143,7 @@ export async function initializeSession(session: CaptureSession): Promise const text = `[Browser:PAGEERROR] ${message}`; // Benign play/pause race during frame capture — suppress terminal noise, keep in buffer. - if (!isPlayPauseAbort(message)) console.error(text); + if (!isPlayPauseAbort(message)) console.error(terminalText(text)); appendBrowserDiagnostic(session, text); }); @@ -3261,8 +3271,10 @@ export async function initializeSession(session: CaptureSession): Promise pollVideosReady(page, skipVideoIds, pageReadyTimeout), waitForImagesReady(page, pageReadyTimeout, (failedImages) => console.warn( - `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. ` + - `Continuing render. Affected images may appear blank/missing in early frames.`, + terminalText( + `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. ` + + `Continuing render. Affected images may appear blank/missing in early frames.`, + ), ), ), page.evaluate(`document.fonts?.ready`), @@ -3281,8 +3293,10 @@ export async function initializeSession(session: CaptureSession): Promise .join(", "); }, skipVideoIds); console.warn( - `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. ` + - `Continuing render. Affected videos will appear as blank/black frames.`, + terminalText( + `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. ` + + `Continuing render. Affected videos will appear as blank/black frames.`, + ), ); } recordReadiness( @@ -3404,8 +3418,10 @@ export async function initializeSession(session: CaptureSession): Promise pollVideosReady(page, bfSkipVideoIds, pageReadyTimeout), waitForImagesReady(page, pageReadyTimeout, (failedImages) => console.warn( - `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. ` + - `Continuing render. Affected images may appear blank/missing in early frames.`, + terminalText( + `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. ` + + `Continuing render. Affected images may appear blank/missing in early frames.`, + ), ), ), page.evaluate(`document.fonts?.ready`), @@ -3424,8 +3440,10 @@ export async function initializeSession(session: CaptureSession): Promise .join(", "); }, bfSkipVideoIds); console.warn( - `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. ` + - `Continuing render. Affected videos will appear as blank/black frames.`, + terminalText( + `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. ` + + `Continuing render. Affected videos will appear as blank/black frames.`, + ), ); } recordReadiness( @@ -5455,7 +5473,7 @@ async function captureFrameCore( session.page, pageMotionBlurRecorder(session), ).catch(() => null); - if (blur) console.error(blur); + if (blur) console.error(terminalText(blur)); } // Retain this freshly-captured buffer so the following static frames can reuse it. @@ -5821,9 +5839,11 @@ export async function captureFramesBatchPipelined( throw new DrawElementCaptureError(frameIndices[failedAt] ?? failedAt, reason, error); } else { console.error( - `[engine] fast capture: batch produce failed at frame ` + - `${frameIndices[failedAt] ?? "?"} (${error ?? "?"}); ` + - `re-capturing ${frameIndices.length - failedAt} frame(s) per-frame`, + terminalText( + `[engine] fast capture: batch produce failed at frame ` + + `${frameIndices[failedAt] ?? "?"} (${error ?? "?"}); ` + + `re-capturing ${frameIndices.length - failedAt} frame(s) per-frame`, + ), ); for (let i = failedAt; i < frameIndices.length; i++) { const frameIndex = frameIndices[i]; @@ -5923,7 +5943,7 @@ export async function closeCaptureSession(session: CaptureSession): Promise { ); }); + it("writes DEL and C1 controls in meta out as visible escapes, which JSON leaves raw", () => { + const log = createConsoleLogger("info"); + log.warn("clip", { src: "a\u009b31mb\u007fc" }); + + expect(warnSpy.mock.calls[0]?.[0]).toBe('[WARN] clip {"src":"a\\x9b31mb\\x7fc"}'); + }); + it("emits message only when meta is omitted", () => { const log = createConsoleLogger("info"); log.info("plain"); diff --git a/packages/producer/src/logger.ts b/packages/producer/src/logger.ts index 0397a38c1a9..fb4790486e7 100644 --- a/packages/producer/src/logger.ts +++ b/packages/producer/src/logger.ts @@ -64,7 +64,7 @@ export function createConsoleLogger(level: LogLevel = "info"): ProducerLogger { const shouldLog = (msgLevel: LogLevel): boolean => LOG_LEVEL_PRIORITY[msgLevel] <= threshold; const formatMeta = (meta?: Record): string => - meta ? ` ${JSON.stringify(meta)}` : ""; + meta ? ` ${terminalText(JSON.stringify(meta))}` : ""; return { error(message, meta) { diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 951b0a82a51..de89718d679 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -56,6 +56,7 @@ import { type RateSpec, type ResolvedDuration, type UnresolvedElement, + terminalText, } from "@hyperframes/core"; import { MAX_AUDIO_GAIN } from "@hyperframes/core/audio-gain"; import { CAPTURE_CANVAS_SELECTOR } from "@hyperframes/core/html-in-canvas"; @@ -1185,7 +1186,9 @@ function inlineSubCompositions( // hit here means the file changed on disk between that pre-flight // check and this later inline step (e.g. a concurrent scene-writer). console.warn( - `[Compiler] Skipping sub-composition "${srcPath}": ${reason ?? "the file is missing or empty"}.`, + terminalText( + `[Compiler] Skipping sub-composition "${srcPath}": ${reason ?? "the file is missing or empty"}.`, + ), ); }, },