fix: warnings that name project files print control characters as visible escapes (#7863)

* 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.

* fix: every library warning that carries project text escapes control characters
This commit is contained in:
Miguel Ángel
2026-11-16 04:56:36 +00:00
committed by GitHub
parent 8e8eeb2059
commit d42bbd67f4
33 changed files with 261 additions and 70 deletions
+1 -1
View File
@@ -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";
+1 -1
View File
@@ -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;
+1 -2
View File
@@ -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";
+1 -1
View File
@@ -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";
+1 -1
View File
@@ -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: {
+1 -1
View File
@@ -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";
@@ -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(),
+1 -1
View File
@@ -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;
@@ -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 })));
+1 -1
View File
@@ -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 };
+1 -1
View File
@@ -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 {
@@ -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]),
+1 -2
View File
@@ -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"];
+6 -1
View File
@@ -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<typeof fs, "writeFileSync" | "chmodSync" | "unlinkSync">;
type DirectFileSystem = SiblingFileSystem & Pick<typeof fs, "openSync" | "closeSync">;
@@ -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}`,
),
);
}
});
}
@@ -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&#27;]0;title&#7;&#27;[2K.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"),
`<html><body><main data-composition-id="root" data-width="320" data-height="180"><div data-composition-id="sub" data-composition-src="${src}"></div></main></body></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&#27;]0;title&#7;";
try {
writeFileSync(
join(dir, "index.html"),
`<html><body><main data-composition-id="root" data-width="320" data-height="180"><div data-composition-id="${id}"></div></main><template id="${id}-template"><div data-composition-id="${id}"><script type="importmap">{ not json</script></div></template></body></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);
});
});
+19 -6
View File
@@ -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"}.`,
),
);
},
});
+5 -1
View File
@@ -1,3 +1,5 @@
import { terminalText } from "../terminalText";
type SpecifierMap = Record<string, string | null>;
/** 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}.`,
),
);
}
}
@@ -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)
+4 -1
View File
@@ -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;
@@ -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 {
+1
View File
@@ -495,3 +495,4 @@ export {
type MotionBlurFingerprint,
type MotionBlurFingerprintField,
} from "./motionBlurFingerprint.js";
export { terminalText } from "./terminalText.js";
@@ -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;
+4 -1
View File
@@ -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 {
@@ -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<typeof vi.spyOn>): 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);
});
});
+54 -28
View File
@@ -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<void>
!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<void>
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<void>
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<void>
.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<void>
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<void>
.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<void
undefined,
pageMotionBlurRecorder(session),
);
if (blur) console.error(blur);
if (blur) console.error(terminalText(blur));
}
// Realized static-dedup telemetry: how much the cache actually helped this
// render (vs the prediction logged at arm time). Both capture paths
+16
View File
@@ -185,6 +185,22 @@ 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("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");
+8 -6
View File
@@ -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, unknown>): 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) {
+3 -3
View File
@@ -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<FileServer
const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
const app = new Hono();
const warnLeftOut = (line: string) => 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<FileServer
if (!file) {
if (!/favicon\.ico$/i.test(requestPath)) {
console.warn(`[FileServer] 404 Not Found: ${requestPath}`);
console.warn(`[FileServer] 404 Not Found: ${terminalText(requestPath)}`);
}
return c.text("Not found", 404);
}
@@ -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"}.`,
),
);
},
},
@@ -24,6 +24,7 @@ import {
CANVAS_DIMENSIONS,
checkOutputResolutionCompatibility,
type CanvasResolution,
terminalText,
} from "@hyperframes/core";
import {
mediaIdPathSegment,
@@ -168,7 +169,7 @@ export function writeCompiledArtifacts(
for (const [srcPath, html] of compiled.subCompositions) {
const outPath = join(compileDir, srcPath);
if (!isPathInside(outPath, compileDir)) {
console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
console.warn(`[Render] Skipping sub-composition with unsafe path: ${terminalText(srcPath)}`);
continue;
}
mkdirSync(dirname(outPath), { recursive: true });
@@ -183,7 +184,9 @@ export function writeCompiledArtifacts(
for (const [relativePath, absolutePath] of compiled.externalAssets) {
const outPath = resolve(join(compileDir, relativePath));
if (!isPathInside(outPath, compileDir)) {
console.warn(`[Render] Skipping external asset with unsafe path: ${relativePath}`);
console.warn(
`[Render] Skipping external asset with unsafe path: ${terminalText(relativePath)}`,
);
continue;
}
mkdirSync(dirname(outPath), { recursive: true });
@@ -56,6 +56,7 @@ import {
shiftRateLane,
sourceTimeAt,
timeAtSourceTime,
terminalText,
} from "@hyperframes/core";
import { parseHostVariableValues, readDeclaredDefaults } from "@hyperframes/core/compiler";
import { extractMediaSrcMutations } from "@hyperframes/parsers";
@@ -942,7 +943,7 @@ export async function runProbeStage(input: ProbeStageInput): Promise<ProbeStageR
failures: failedRequests.slice(0, 10),
});
for (const line of failedRequests.slice(0, 5)) {
console.warn(`[Render] Asset load failure: ${line}`);
console.warn(`[Render] Asset load failure: ${terminalText(line)}`);
}
}
}