diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 6da1d44cfd..2c016f6621 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 0dccbd27f7..be412854eb 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 79cad6e718..3aef4cd40a 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 aa80e544fd..d566495aee 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 1108b95a99..d7f4cf8af7 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 fdcd2db983..53c1d11f7a 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 6ca37a10c4..d0cc1d9780 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 9b522d76eb..908831d06d 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 6d8b11e266..f22947b662 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 efb72a6cfe..d15102b37a 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 98a486b514..bbc0b00ebe 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 43a6c6b7a7..437b1efc7b 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 0b352e7aa0..1e9dd5b586 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 bc4933b749..c17dc7c295 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 0000000000..e5ab86af98 --- /dev/null +++ b/packages/core/src/compiler/htmlBundler.terminalText.test.ts @@ -0,0 +1,55 @@ +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); + }, + ); + + 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 c301a482cc..3f4d3d1791 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 = ""; @@ -382,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.`, + ), ); } @@ -461,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.`, + ), ); } @@ -1024,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) : ""; @@ -1137,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("; ")}`, + ), ); } } @@ -1226,7 +1237,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/importMaps.ts b/packages/core/src/compiler/importMaps.ts index c5920fde8f..bbc074226f 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/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts index c4f591e156..e9f86ca74c 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 a068624e95..2c4a7f97d8 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 78a7d46a3a..967ccaf59b 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 692a937600..6e411271d3 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/audioFxRender.ts b/packages/engine/src/services/audioFxRender.ts index f032e8bab9..7fe41c35df 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 444e66e9d4..58cd3ff1bc 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 0000000000..f938652da6 --- /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 7a28ad405e..acdb676379 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"; @@ -1200,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(); }; @@ -1305,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; @@ -1391,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 { @@ -2317,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; } @@ -2350,12 +2359,16 @@ 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}. ` + - `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"; @@ -2548,7 +2561,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 ?? {}, + ); } } @@ -3111,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); @@ -3127,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); }); @@ -3255,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`), @@ -3275,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( @@ -3398,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`), @@ -3418,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( @@ -5449,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. @@ -5815,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]; @@ -5917,7 +5943,7 @@ export async function closeCaptureSession(session: CaptureSession): Promise { 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("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 34952b40e7..fb4790486e 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 { @@ -62,27 +64,27 @@ 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) { 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 7388001b5e..9dc44a9079 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