mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-03 04:38:33 +00:00
feat(media-use): color grading — grade/lut resolve, smart-grade, grade-compare + compare (#2041)
* feat(media-use): color grading — grade/lut resolve, smart-grade, grade-compare CLI Add color grading to media-use as first-class resolve types plus a faithful comparison command. All local, offline, deterministic — no model, no GPU. - resolve -t grade / -t lut: produce a data-color-grading block (or a frozen .cube). Look cascade: core preset (no file) -> bundled .cube library -> parametric buildCube. Emitted .cube is Rec.709 and validated against core's colorLuts constraints (LUT_3D_SIZE <= 64) before it is frozen. - smart grade (grade --for <media>): ffmpeg signalstats -> adjust suggestion (exposure / contrast / white balance), surfaced with the measured evidence on stderr as a starting point; never auto-applied. - hyperframes grade-compare: renders N candidate grades onto a reference frame through the real runtime shader into one labeled comparison PNG, so an agent picks a look without opening Studio. Prepends an "original" baseline cell by default (--no-baseline to omit). Shares the headless-capture pipeline with snapshot via capture/captureCompositionFrame. - media-use SKILL: proactive "media opportunity pass" guidance (grounded signal -> offer, ask once, surface don't mutate). Verified: media-use 116/116, grade-compare 7/7, snapshot 9/9, lint + format clean, full build green, comparison renders end to end. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * test(cli): narrow grade-compare baseline assertion off unknown-typed grading Assert the whole cell via toEqual instead of reaching into .grading.preset / .grading.lut on the unknown-typed field, keeping the test typecheck-clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * feat(media-use): agent-authored LUTs via --params + validate --from cube; never-read-.cube guardrail - resolve -t lut / -t grade --params '<json>': build a parametric .cube from explicit params (bypassing the intent cascade), validate, and freeze in one step. --intent becomes the optional description. Lets an agent commit a look it computed itself. - --from <file.cube> now validates the ingested LUT for lut/grade types and rejects an invalid/oversized cube (no partial write) — the escape hatch for a LUT the agent generated with its own code. - SKILL.md: hard rule to never read a .cube body into context (~size^3 lines, zero legible signal) — inspect via grade-compare (see it) or cube-validate (ok/size), read the manifest description for meaning; plus both authoring paths and the parametric-vs-film-stock ceiling note. Verified: media-use 116/116, lint + format clean; smokes — --params builds a valid frozen cube, grade --params returns a lut block, bad JSON and an oversized --from cube are both rejected with no stray file. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * fix(cli): grade-compare validates referenced LUTs, warns on no-op cells, caps candidates Bug-bash follow-ups — grade-compare silently accepted bad input: - Validate LUT *content*, not just existence: each referenced .cube is parsed with core's parseCubeLut (now exported from @hyperframes/core) and rejected with a per-cell error ("LUT for \"<label>\" is not a valid .cube: ..."). A file that exists but isn't a valid cube no longer renders a silent no-op cell. - Warn on inactive cells: a grading that normalizes to inactive (e.g. a malformed {lut:12345}) emits a stderr warning naming the cell; the auto-prepended "original" baseline is intentionally inactive and stays silent. stdout remains valid JSON. - Cap candidates at 16 (excluding baseline): over-cap input renders the first N and reports {truncated:true, total:M} on stdout + a stderr note — no silent drop, no unbounded giant sheet. Verified: grade-compare 10/10; non-cube LUT → clear error; {lut:12345} → warning + ok; 20 cells → cells=17 truncated total=20; valid runs unchanged. Lint/format clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * feat(cli): general `hyperframes compare` visual-variant primitive Generalize grade-compare's "render N variants → one labeled sheet → the agent looks and picks" loop into a standalone command that works on ANY variation (font, layout, motion, grade, whole compositions) — the tool never needs to know what differs. - `hyperframes compare <path...> [--at <sec>] [--labels a,b,c] [--out] [--cols] [--json]`: renders each agent-authored composition variant through the real runtime (captureCompositionFrame) and stitches one labeled comparison sheet + JSON ({ok, sheet, rendered, variants, truncated?/total?}). 2+ paths required; caps at 16 with loud truncation. It presents, it does not judge — choosing is the caller's job. - Factored the shared "render a labeled set → contact sheet" path so compare, grade-compare, and snapshot all sit on it (no duplication). grade-compare is now the first color-specific specialization of this primitive. - New pathArgs util + contactSheet test; hyperframes-cli SKILL documents compare as the agent's "see your own renders and choose" primitive. Verified: 26/26 across compare + grade-compare + snapshot + contactSheet (no regressions); compare renders 3 variants into one visibly-distinct labeled sheet; 2+-path error path clean; lint/format clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * fix(ci): green the skills CI — skip ffmpeg tests when absent, oxfmt markdown The "Test: skills" CI job runs bare `node --test` with no ffmpeg on PATH (by design — skills tests are meant to be node-builtin-only). The grade-analyzer + smart-grade tests shell to ffmpeg and were failing there with ENOENT. Guard them to skip when ffmpeg isn't on PATH; they still run locally / where it is. Also oxfmt README.md + hyperframes/media-use SKILL.md (the whole-repo `oxfmt --check .` Format job caught markdown left unformatted by the rebase conflict resolution). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * fix(ci): skip core-conformance test when tsx is unavailable The "Test: skills" CI job installs no deps, so the normalizeHfColorGrading conformance test (which imports core's TS via `node --import tsx`) failed there. Guard it to skip when tsx can't resolve; runs locally / in the deps-installed Test job. Completes the skills-CI greening (the ffmpeg guards handled the rest). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * fix(cli): escape grade-compare src double-quotes (CodeQL XSS) + Windows-safe compare test - grade-compare built `<img src="...">` (double-quoted) with the single-quote escaper, leaving `"` unescaped — a `"` in the frame path could break out (CodeQL: incomplete HTML attribute sanitization). Use escapeXml for src. - compare label test hard-coded POSIX paths that can't match on Windows; assert the derived labels (the subject); path resolution is covered elsewhere. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * refactor(media-use): generate LUT library from params (drop committed .cube files) The 3 bundled .cube files were 733 lines each (2,199 total) and were themselves buildCube output — pure repo bloat. Replace with compact per-look params in luts/index.json, generated on resolve; add an optional `url` for future scanned LUTs to be CDN-hosted + downloaded on demand (freezeUrl) instead of committed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * feat(media-use): serve library LUTs from CDN on-demand (static.heygen.ai/luts), params fallback Looks now carry a CDN `url` (hosted at s3://heygen-public/luts → static.heygen.ai/luts/<id>.cube); resolve downloads + validates + freezes on demand, like bgm/image. `params` stays as the deterministic offline fallback (--local-only, or if the download fails), so resolution is never blocked on the network. Provider prefers url, falls back to params. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv * fix(media-use): address #2041 review — atomic LUT writes, compare telemetry, follow-ups - Atomic .cube writes: library provider (url + params) and the parametric generator now write to a .tmp path, validate, then rename, so a crash can never orphan an invalid .cube at the final path (was validate-after-write). - track("media_use_resolve") now emits provenance.via (url/params-fallback/params). - grade-compare + compare: --timeout flag (was hardcoded 5000) and a media_use_compare event (cells, truncated, total, render_ready_timed_out); openSettledCompositionPage now surfaces the render-ready timeout. - compare staging skips node_modules/.git; --for gets an upfront existence check. - Rec.709 luma comment; HYPERFRAMES_ANALYZE_TIMEOUT_MS override; measured note uses basename; LUT s3 hosting moved from index.json into luts/README.md. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01H5k87mPZ4d6yiFwcWSb8Vv --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
7face26f04
commit
57b3c78987
@@ -0,0 +1,39 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runFfmpegOnce } from "./captureCompositionFrame.js";
|
||||
|
||||
function tempDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "hf-capture-frame-test-"));
|
||||
}
|
||||
|
||||
describe("runFfmpegOnce", () => {
|
||||
it("returns the process exit code and collected stderr", async () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const script = join(dir, "fail.cjs");
|
||||
writeFileSync(script, 'process.stderr.write("ffmpeg failed"); process.exit(3);\n');
|
||||
|
||||
const result = await runFfmpegOnce(process.execPath, [script], 1000);
|
||||
|
||||
expect(result).toEqual({ code: 3, stderr: "ffmpeg failed", timedOut: false });
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("terminates the process when the timeout elapses", async () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const script = join(dir, "hang.cjs");
|
||||
writeFileSync(script, "setTimeout(() => {}, 10000);\n");
|
||||
|
||||
const result = await runFfmpegOnce(process.execPath, [script], 50);
|
||||
|
||||
expect(result.timedOut).toBe(true);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import type { Browser, Page } from "puppeteer-core";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
|
||||
|
||||
const CHROME_LAUNCH_ARGS = [
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--enable-webgl",
|
||||
"--use-gl=angle",
|
||||
"--use-angle=swiftshader",
|
||||
];
|
||||
|
||||
const SHADER_TRANSITIONS_TIMEOUT_MS = 90_000;
|
||||
const CAPTURE_SETTLE_MS = 1500;
|
||||
|
||||
export interface SettledCompositionPage {
|
||||
browser: Browser;
|
||||
page: Page;
|
||||
// True when the runtime never signaled __renderReady within the timeout — the
|
||||
// capture proceeds anyway (possibly mid-animation), so callers can surface it.
|
||||
renderReadyTimedOut: boolean;
|
||||
}
|
||||
|
||||
export interface OpenSettledCompositionPageOptions {
|
||||
renderReadyTimeoutMs: number;
|
||||
renderReadyWarningSuffix: string;
|
||||
}
|
||||
|
||||
export interface FfmpegRunResult {
|
||||
code: number | null;
|
||||
stderr: string;
|
||||
timedOut: boolean;
|
||||
}
|
||||
|
||||
function compositionRuntimeReadyInBrowser(): boolean {
|
||||
return Boolean(Reflect.get(window, "__renderReady"));
|
||||
}
|
||||
|
||||
function shaderTransitionsReadyInBrowser(): boolean {
|
||||
function shaderTransitionRegistryReady(): boolean | undefined {
|
||||
const hf = Reflect.get(window, "__hf");
|
||||
if (typeof hf !== "object" || hf === null) return undefined;
|
||||
|
||||
const shaderTransitions = Reflect.get(hf, "shaderTransitions");
|
||||
if (typeof shaderTransitions !== "object" || shaderTransitions === null) return undefined;
|
||||
|
||||
for (const key of Object.keys(shaderTransitions)) {
|
||||
const entry = Reflect.get(shaderTransitions, key);
|
||||
if (typeof entry !== "object" || entry === null) return false;
|
||||
if (Reflect.get(entry, "ready") !== true) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function shaderLoadingOverlayReady(): boolean {
|
||||
const overlay = document.querySelector("[data-hyper-shader-loading]");
|
||||
if (!overlay) return true;
|
||||
if (!(overlay instanceof HTMLElement)) return true;
|
||||
return window.getComputedStyle(overlay).display === "none";
|
||||
}
|
||||
|
||||
return shaderTransitionRegistryReady() ?? shaderLoadingOverlayReady();
|
||||
}
|
||||
|
||||
async function waitForCompositionSettle(
|
||||
page: Page,
|
||||
options: OpenSettledCompositionPageOptions,
|
||||
): Promise<boolean> {
|
||||
const runtimeReady = await page
|
||||
.waitForFunction(compositionRuntimeReadyInBrowser, { timeout: options.renderReadyTimeoutMs })
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
|
||||
if (!runtimeReady) {
|
||||
console.warn(
|
||||
`\n ${c.warn("⚠")} Runtime did not become render-ready within ${options.renderReadyTimeoutMs}ms — ${options.renderReadyWarningSuffix}`,
|
||||
);
|
||||
}
|
||||
|
||||
await page
|
||||
.waitForFunction(shaderTransitionsReadyInBrowser, {
|
||||
timeout: SHADER_TRANSITIONS_TIMEOUT_MS,
|
||||
})
|
||||
.catch(() => {
|
||||
console.warn(` ${c.warn("⚠")} Shader transitions did not finish pre-rendering`);
|
||||
});
|
||||
|
||||
await page.evaluate(() => document.fonts.ready).catch(() => {});
|
||||
await new Promise((resolveSettle) => setTimeout(resolveSettle, CAPTURE_SETTLE_MS));
|
||||
return runtimeReady;
|
||||
}
|
||||
|
||||
export async function openSettledCompositionPage(
|
||||
html: string,
|
||||
url: string,
|
||||
options: OpenSettledCompositionPageOptions,
|
||||
): Promise<SettledCompositionPage> {
|
||||
const { ensureBrowser } = await import("../browser/manager.js");
|
||||
const browser = await ensureBrowser();
|
||||
const puppeteer = await import("puppeteer-core");
|
||||
|
||||
let chromeBrowser: Browser | undefined;
|
||||
try {
|
||||
chromeBrowser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: CHROME_LAUNCH_ARGS,
|
||||
});
|
||||
|
||||
const page = await chromeBrowser.newPage();
|
||||
await page.setViewport(resolveCompositionViewportFromHtml(html));
|
||||
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 10000 });
|
||||
const renderReadyTimedOut = !(await waitForCompositionSettle(page, options));
|
||||
return { browser: chromeBrowser, page, renderReadyTimedOut };
|
||||
} catch (err) {
|
||||
await chromeBrowser?.close().catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function seekCompositionTimeline(
|
||||
page: Pick<Page, "evaluate">,
|
||||
timeSeconds: number,
|
||||
): Promise<void> {
|
||||
await page.evaluate((t: number) => {
|
||||
const player = (window as any).__player;
|
||||
if (!player) return;
|
||||
const safe = Math.max(0, Number(t) || 0);
|
||||
if (typeof player.renderSeek === "function") {
|
||||
player.renderSeek(safe);
|
||||
} else if (typeof player.seek === "function") {
|
||||
player.seek(safe);
|
||||
}
|
||||
if ((window as any).gsap?.ticker?.tick) {
|
||||
(window as any).gsap.ticker.tick();
|
||||
}
|
||||
}, timeSeconds);
|
||||
|
||||
await page.evaluate(`new Promise(function(r) {
|
||||
var settled = false;
|
||||
function finish() { if (settled) return; settled = true; r(); }
|
||||
window.setTimeout(finish, 100);
|
||||
requestAnimationFrame(function() { requestAnimationFrame(finish); });
|
||||
})`);
|
||||
}
|
||||
|
||||
export async function runFfmpegOnce(
|
||||
ffmpegPath: string,
|
||||
args: readonly string[],
|
||||
timeoutMs: number,
|
||||
): Promise<FfmpegRunResult> {
|
||||
return await new Promise((resolvePromise) => {
|
||||
const ff = spawn(ffmpegPath, args);
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
ff.kill("SIGTERM");
|
||||
}, timeoutMs);
|
||||
|
||||
ff.stderr.on("data", (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
ff.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolvePromise({ code, stderr, timedOut });
|
||||
});
|
||||
ff.on("error", () => {
|
||||
clearTimeout(timer);
|
||||
resolvePromise({ code: null, stderr: "ffmpeg spawn failed", timedOut });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createContactSheet } from "./contactSheet.js";
|
||||
|
||||
function tempDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "hf-contact-sheet-test-"));
|
||||
}
|
||||
|
||||
describe("createContactSheet", () => {
|
||||
it("writes PNG output when the output path uses a .png extension", async () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const a = join(dir, "a.png");
|
||||
const b = join(dir, "b.png");
|
||||
const out = join(dir, "sheet.png");
|
||||
await sharp({
|
||||
create: {
|
||||
width: 16,
|
||||
height: 9,
|
||||
channels: 3,
|
||||
background: { r: 255, g: 0, b: 0 },
|
||||
},
|
||||
})
|
||||
.png()
|
||||
.toFile(a);
|
||||
await sharp({
|
||||
create: {
|
||||
width: 16,
|
||||
height: 9,
|
||||
channels: 3,
|
||||
background: { r: 0, g: 255, b: 0 },
|
||||
},
|
||||
})
|
||||
.png()
|
||||
.toFile(b);
|
||||
|
||||
await createContactSheet([a, b], out, {
|
||||
cols: 2,
|
||||
labelMode: "custom",
|
||||
labels: ["A", "B"],
|
||||
maxImages: 2,
|
||||
});
|
||||
|
||||
await expect(sharp(out).metadata()).resolves.toMatchObject({ format: "png" });
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -93,17 +93,20 @@ export async function createContactSheet(
|
||||
overlays.push({ input: labelSvg, left: x, top: y });
|
||||
}
|
||||
|
||||
await sharp({
|
||||
const sheet = sharp({
|
||||
create: {
|
||||
width: totalW,
|
||||
height: totalH,
|
||||
channels: 3,
|
||||
background: { r: 26, g: 26, b: 26 },
|
||||
},
|
||||
})
|
||||
.composite(overlays)
|
||||
.jpeg({ quality })
|
||||
.toFile(outputPath);
|
||||
}).composite(overlays);
|
||||
|
||||
if (extname(outputPath).toLowerCase() === ".png") {
|
||||
await sheet.png().toFile(outputPath);
|
||||
} else {
|
||||
await sheet.jpeg({ quality }).toFile(outputPath);
|
||||
}
|
||||
|
||||
return outputPath;
|
||||
}
|
||||
@@ -263,6 +266,7 @@ export async function createAssetContactSheet(
|
||||
* parent assets/ root (for external SVGs downloaded as <img src="*.svg">).
|
||||
* Files are deduplicated by basename so duplicates across dirs are collapsed.
|
||||
*/
|
||||
// fallow-ignore-next-line complexity
|
||||
export async function createSvgContactSheet(
|
||||
svgsDir: string,
|
||||
outputPath: string,
|
||||
|
||||
@@ -139,6 +139,8 @@ const commandLoaders = {
|
||||
events: () => import("./commands/events.js").then((m) => m.default),
|
||||
validate: () => import("./commands/validate.js").then((m) => m.default),
|
||||
snapshot: () => import("./commands/snapshot.js").then((m) => m.default),
|
||||
"grade-compare": () => import("./commands/grade-compare.js").then((m) => m.default),
|
||||
compare: () => import("./commands/compare.js").then((m) => m.default),
|
||||
capture: () => import("./commands/capture.js").then((m) => m.default),
|
||||
lambda: () => import("./commands/lambda.js").then((m) => m.default),
|
||||
cloudrun: () => import("./commands/cloudrun.js").then((m) => m.default),
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
buildCompareSuccessPayload,
|
||||
capCompareVariants,
|
||||
parseCompareArgs,
|
||||
prepareCompareVariantProjects,
|
||||
} from "./compare.js";
|
||||
|
||||
function tempDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "hf-compare-test-"));
|
||||
}
|
||||
|
||||
describe("parseCompareArgs", () => {
|
||||
it("requires at least two composition paths", () => {
|
||||
expect(() => parseCompareArgs({ _: ["variant-a"] }, "/tmp")).toThrow(
|
||||
"need 2+ paths to compare",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects --labels when the count does not match the path count", () => {
|
||||
expect(() =>
|
||||
parseCompareArgs({ _: ["variant-a", "variant-b"], labels: "one,two,three" }, "/tmp"),
|
||||
).toThrow("--labels count (3) must match path count (2)");
|
||||
});
|
||||
|
||||
it("derives default labels from directory basenames and html filenames", () => {
|
||||
const parsed = parseCompareArgs(
|
||||
{ _: ["./looks/warm", "./looks/cool.html", "/tmp/hero.alt.html"] },
|
||||
"/work/project",
|
||||
);
|
||||
|
||||
// Labels are the subject here — derived cross-platform via path.basename.
|
||||
// (inputPath/displayPath are absolute/relative resolutions that differ by OS
|
||||
// — separators + drive letter on Windows — and are covered by the resolution
|
||||
// tests; asserting them literally here made this a POSIX-only test.)
|
||||
expect(parsed.variants.map((v) => v.label)).toEqual(["warm", "cool", "hero.alt"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("capCompareVariants", () => {
|
||||
it("truncates over-cap variants and exposes truncation metadata for JSON output", () => {
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
try {
|
||||
const variants = Array.from({ length: 20 }, (_, index) => ({
|
||||
label: `variant ${index + 1}`,
|
||||
inputPath: `/tmp/variant-${index + 1}`,
|
||||
displayPath: `variant-${index + 1}`,
|
||||
}));
|
||||
|
||||
const capped = capCompareVariants(variants);
|
||||
|
||||
expect(capped.variants).toHaveLength(16);
|
||||
expect(capped.variants.at(0)?.label).toBe("variant 1");
|
||||
expect(capped.variants.at(15)?.label).toBe("variant 16");
|
||||
expect(capped.truncated).toBe(true);
|
||||
expect(capped.total).toBe(20);
|
||||
expect(buildCompareSuccessPayload("/tmp/compare.png", capped.variants, capped)).toMatchObject(
|
||||
{
|
||||
ok: true,
|
||||
sheet: "/tmp/compare.png",
|
||||
rendered: 16,
|
||||
truncated: true,
|
||||
total: 20,
|
||||
},
|
||||
);
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Warning: 20 compare variants exceed the 16-variant cap"),
|
||||
);
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareCompareVariantProjects", () => {
|
||||
it("uses project directories directly and stages standalone html files as index.html", () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const projectDir = join(dir, "variant-a");
|
||||
const htmlDir = join(dir, "variant-b");
|
||||
const projectIndex = join(projectDir, "index.html");
|
||||
const htmlFile = join(htmlDir, "candidate.html");
|
||||
mkdirSync(projectDir, { recursive: true });
|
||||
mkdirSync(htmlDir, { recursive: true });
|
||||
writeFileSync(projectIndex, "<!doctype html><title>A</title>", { flag: "wx" });
|
||||
writeFileSync(htmlFile, "<!doctype html><title>B</title>", { flag: "wx" });
|
||||
writeFileSync(join(htmlDir, "asset.txt"), "asset");
|
||||
|
||||
const prepared = prepareCompareVariantProjects([
|
||||
{ label: "A", inputPath: projectDir, displayPath: "variant-a" },
|
||||
{ label: "B", inputPath: htmlFile, displayPath: "variant-b/candidate.html" },
|
||||
]);
|
||||
|
||||
try {
|
||||
expect(prepared).toHaveLength(2);
|
||||
expect(prepared[0]).toMatchObject({
|
||||
label: "A",
|
||||
inputPath: projectDir,
|
||||
displayPath: "variant-a",
|
||||
projectDir,
|
||||
});
|
||||
expect(prepared[0]?.stagedDir).toBeUndefined();
|
||||
expect(prepared[1]?.projectDir).not.toBe(htmlDir);
|
||||
expect(prepared[1]?.stagedDir).toBe(prepared[1]?.projectDir);
|
||||
expect(readFileSync(join(prepared[1]!.projectDir, "index.html"), "utf-8")).toContain(
|
||||
"<title>B</title>",
|
||||
);
|
||||
expect(readFileSync(join(prepared[1]!.projectDir, "asset.txt"), "utf-8")).toBe("asset");
|
||||
expect(existsSync(join(prepared[1]!.projectDir, "candidate.html"))).toBe(false);
|
||||
} finally {
|
||||
for (const variant of prepared) {
|
||||
if (variant.stagedDir) rmSync(variant.stagedDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("errors clearly for inputs that are not composition projects or html files", () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const badFile = join(dir, "notes.txt");
|
||||
writeFileSync(badFile, "not a composition");
|
||||
|
||||
expect(() =>
|
||||
prepareCompareVariantProjects([
|
||||
{ label: "notes", inputPath: badFile, displayPath: "notes.txt" },
|
||||
{ label: "other", inputPath: join(dir, "missing"), displayPath: "missing" },
|
||||
]),
|
||||
).toThrow(/not a composition input.*notes\.txt/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,413 @@
|
||||
import { cpSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { defineCommand } from "citty";
|
||||
import { createContactSheet } from "../capture/contactSheet.js";
|
||||
import {
|
||||
openSettledCompositionPage,
|
||||
seekCompositionTimeline,
|
||||
} from "../capture/captureCompositionFrame.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { normalizeErrorMessage } from "../utils/errorMessage.js";
|
||||
import { displayPathFromInput, readOptionalString, resolveFromBase } from "../utils/pathArgs.js";
|
||||
import { trackCompareSheet } from "../telemetry/events.js";
|
||||
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
|
||||
import { withMeta } from "../utils/updateCheck.js";
|
||||
import type { Example } from "./_examples.js";
|
||||
|
||||
const MAX_COMPARE_VARIANTS = 16;
|
||||
const MAX_COLUMNS = 4;
|
||||
const DEFAULT_RENDER_READY_TIMEOUT_MS = 5000;
|
||||
|
||||
export interface CompareVariantSpec {
|
||||
label: string;
|
||||
inputPath: string;
|
||||
displayPath: string;
|
||||
}
|
||||
|
||||
export interface PreparedCompareVariant extends CompareVariantSpec {
|
||||
projectDir: string;
|
||||
stagedDir?: string;
|
||||
}
|
||||
|
||||
export interface ParsedCompareArgs {
|
||||
variants: CompareVariantSpec[];
|
||||
outPath: string;
|
||||
atSeconds: number;
|
||||
cols?: number;
|
||||
json: boolean;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
export interface CompareVariantCapResult {
|
||||
variants: CompareVariantSpec[];
|
||||
truncated: boolean;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface CompareSuccessPayload {
|
||||
ok: true;
|
||||
sheet: string;
|
||||
variants: { label: string; path: string }[];
|
||||
rendered: number;
|
||||
truncated?: true;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export const examples: Example[] = [
|
||||
[
|
||||
"Compare two agent-authored composition variants",
|
||||
"hyperframes compare ./variants/a ./variants/b --out compare.png",
|
||||
],
|
||||
[
|
||||
"Compare three variants at a specific timeline time",
|
||||
"hyperframes compare ./a ./b ./c --at 2.5 --labels classic,bold,quiet --json",
|
||||
],
|
||||
];
|
||||
|
||||
function defaultLabelForPath(input: string): string {
|
||||
const name = basename(input);
|
||||
return extname(name).toLowerCase() === ".html" ? basename(name, extname(name)) : name;
|
||||
}
|
||||
|
||||
function parsePathArgs(args: { _?: readonly unknown[] }): string[] {
|
||||
return (args._ ?? [])
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseLabels(value: unknown, pathCount: number): string[] | undefined {
|
||||
const raw = readOptionalString(value);
|
||||
if (!raw) return undefined;
|
||||
const labels = raw.split(",").map((part) => part.trim());
|
||||
if (labels.some((label) => label.length === 0)) {
|
||||
throw new Error("--labels entries must be non-empty");
|
||||
}
|
||||
if (labels.length !== pathCount) {
|
||||
throw new Error(`--labels count (${labels.length}) must match path count (${pathCount})`);
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
function parseAtSeconds(value: unknown): number {
|
||||
const raw = readOptionalString(value);
|
||||
if (!raw) return 0;
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
throw new Error("--at must be a non-negative number of seconds");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseColumns(value: unknown): number | undefined {
|
||||
const raw = readOptionalString(value);
|
||||
if (!raw) return undefined;
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isInteger(parsed) || parsed < 1) {
|
||||
throw new Error("--cols must be a positive integer");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function defaultCompareCols(cellCount: number): number {
|
||||
return Math.max(1, Math.min(MAX_COLUMNS, Math.ceil(Math.sqrt(cellCount))));
|
||||
}
|
||||
|
||||
export function parseCompareArgs(
|
||||
args: {
|
||||
_?: readonly unknown[];
|
||||
labels?: unknown;
|
||||
out?: unknown;
|
||||
at?: unknown;
|
||||
cols?: unknown;
|
||||
json?: unknown;
|
||||
timeout?: unknown;
|
||||
},
|
||||
cwd = process.cwd(),
|
||||
): ParsedCompareArgs {
|
||||
const paths = parsePathArgs(args);
|
||||
if (paths.length < 2) {
|
||||
throw new Error("need 2+ paths to compare");
|
||||
}
|
||||
|
||||
const labels = parseLabels(args.labels, paths.length);
|
||||
const variants = paths.map((input, index) => ({
|
||||
label: labels?.[index] ?? defaultLabelForPath(input),
|
||||
inputPath: resolveFromBase(cwd, input),
|
||||
displayPath: displayPathFromInput(cwd, input),
|
||||
}));
|
||||
|
||||
return {
|
||||
variants,
|
||||
outPath: resolveFromBase(cwd, readOptionalString(args.out) ?? "compare.png"),
|
||||
atSeconds: parseAtSeconds(args.at),
|
||||
cols: parseColumns(args.cols),
|
||||
json: args.json === true,
|
||||
timeoutMs:
|
||||
Number.parseInt(readOptionalString(args.timeout) ?? "", 10) ||
|
||||
DEFAULT_RENDER_READY_TIMEOUT_MS,
|
||||
};
|
||||
}
|
||||
|
||||
export function capCompareVariants(
|
||||
variants: readonly CompareVariantSpec[],
|
||||
): CompareVariantCapResult {
|
||||
const total = variants.length;
|
||||
if (total <= MAX_COMPARE_VARIANTS) {
|
||||
return { variants: [...variants], truncated: false, total };
|
||||
}
|
||||
console.error(
|
||||
c.warn(
|
||||
`Warning: ${total} compare variants exceed the ${MAX_COMPARE_VARIANTS}-variant cap — rendering the first ${MAX_COMPARE_VARIANTS} of ${total}; re-run with fewer variants or split into multiple runs.`,
|
||||
),
|
||||
);
|
||||
return {
|
||||
variants: variants.slice(0, MAX_COMPARE_VARIANTS),
|
||||
truncated: true,
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCompareSuccessPayload(
|
||||
sheet: string,
|
||||
variants: readonly CompareVariantSpec[],
|
||||
capResult: CompareVariantCapResult,
|
||||
): CompareSuccessPayload {
|
||||
const payload: CompareSuccessPayload = {
|
||||
ok: true,
|
||||
sheet,
|
||||
variants: variants.map((variant) => ({
|
||||
label: variant.label,
|
||||
path: variant.displayPath,
|
||||
})),
|
||||
rendered: variants.length,
|
||||
};
|
||||
if (capResult.truncated) {
|
||||
payload.truncated = true;
|
||||
payload.total = capResult.total;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function inputError(variant: CompareVariantSpec): Error {
|
||||
return new Error(
|
||||
`Variant "${variant.label}" is not a composition input (${variant.displayPath}): expected a directory containing index.html or a .html file`,
|
||||
);
|
||||
}
|
||||
|
||||
function stageHtmlVariant(variant: CompareVariantSpec): PreparedCompareVariant {
|
||||
const stagedDir = mkdtempSync(join(tmpdir(), "hf-compare-variant-"));
|
||||
try {
|
||||
// Copy the composition's sibling files but skip heavy/irrelevant trees — a
|
||||
// variant sitting next to node_modules or .git shouldn't drag them into tmp.
|
||||
cpSync(dirname(variant.inputPath), stagedDir, {
|
||||
recursive: true,
|
||||
filter: (src) => {
|
||||
const base = basename(src);
|
||||
return base !== "node_modules" && base !== ".git";
|
||||
},
|
||||
});
|
||||
const sourceName = basename(variant.inputPath);
|
||||
if (sourceName !== "index.html") {
|
||||
renameSync(join(stagedDir, sourceName), join(stagedDir, "index.html"));
|
||||
}
|
||||
return {
|
||||
...variant,
|
||||
projectDir: stagedDir,
|
||||
stagedDir,
|
||||
};
|
||||
} catch (err) {
|
||||
rmSync(stagedDir, { recursive: true, force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareCompareVariantProjects(
|
||||
variants: readonly CompareVariantSpec[],
|
||||
): PreparedCompareVariant[] {
|
||||
const prepared: PreparedCompareVariant[] = [];
|
||||
try {
|
||||
for (const variant of variants) {
|
||||
if (!existsSync(variant.inputPath)) {
|
||||
throw inputError(variant);
|
||||
}
|
||||
const stat = statSync(variant.inputPath);
|
||||
if (stat.isDirectory() && existsSync(join(variant.inputPath, "index.html"))) {
|
||||
prepared.push({
|
||||
...variant,
|
||||
projectDir: variant.inputPath,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (stat.isFile() && extname(variant.inputPath).toLowerCase() === ".html") {
|
||||
prepared.push(stageHtmlVariant(variant));
|
||||
continue;
|
||||
}
|
||||
throw inputError(variant);
|
||||
}
|
||||
return prepared;
|
||||
} catch (err) {
|
||||
for (const variant of prepared) {
|
||||
if (variant.stagedDir) {
|
||||
rmSync(variant.stagedDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupPreparedCompareVariants(variants: readonly PreparedCompareVariant[]): void {
|
||||
for (const variant of variants) {
|
||||
if (variant.stagedDir) {
|
||||
rmSync(variant.stagedDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function renderCompareVariant(
|
||||
variant: PreparedCompareVariant,
|
||||
opts: { atSeconds: number; framePath: string; timeoutMs: number },
|
||||
): Promise<{ framePath: string; renderReadyTimedOut: boolean }> {
|
||||
try {
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
const html = await bundleToSingleHtml(variant.projectDir);
|
||||
const server = await serveStaticProjectHtml(variant.projectDir, html);
|
||||
try {
|
||||
const {
|
||||
browser: chromeBrowser,
|
||||
page,
|
||||
renderReadyTimedOut,
|
||||
} = await openSettledCompositionPage(html, server.url, {
|
||||
renderReadyTimeoutMs: opts.timeoutMs,
|
||||
renderReadyWarningSuffix: `comparison variant "${variant.label}" may be inaccurate`,
|
||||
});
|
||||
try {
|
||||
if (opts.atSeconds > 0) {
|
||||
await seekCompositionTimeline(page, opts.atSeconds);
|
||||
}
|
||||
await page.screenshot({ path: opts.framePath, type: "png" });
|
||||
return { framePath: opts.framePath, renderReadyTimedOut };
|
||||
} finally {
|
||||
await chromeBrowser.close();
|
||||
}
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Render failed for variant "${variant.label}" (${variant.displayPath}): ${normalizeErrorMessage(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function renderCompareSheet(parsed: ParsedCompareArgs): Promise<CompareSuccessPayload> {
|
||||
const capResult = capCompareVariants(parsed.variants);
|
||||
const variants = capResult.variants;
|
||||
const prepared = prepareCompareVariantProjects(variants);
|
||||
const frameDir = mkdtempSync(join(tmpdir(), "hf-compare-frames-"));
|
||||
const framePaths: string[] = [];
|
||||
|
||||
try {
|
||||
let renderReadyTimedOut = false;
|
||||
for (let i = 0; i < prepared.length; i++) {
|
||||
const variant = prepared[i]!;
|
||||
const framePath = join(frameDir, `variant-${String(i + 1).padStart(2, "0")}.png`);
|
||||
const rendered = await renderCompareVariant(variant, {
|
||||
atSeconds: parsed.atSeconds,
|
||||
framePath,
|
||||
timeoutMs: parsed.timeoutMs,
|
||||
});
|
||||
framePaths.push(rendered.framePath);
|
||||
renderReadyTimedOut = renderReadyTimedOut || rendered.renderReadyTimedOut;
|
||||
}
|
||||
|
||||
mkdirSync(dirname(parsed.outPath), { recursive: true });
|
||||
await createContactSheet(framePaths, parsed.outPath, {
|
||||
cols: parsed.cols ?? defaultCompareCols(framePaths.length),
|
||||
maxImages: framePaths.length,
|
||||
labelMode: "custom",
|
||||
labels: variants.map((variant) => variant.label),
|
||||
});
|
||||
|
||||
trackCompareSheet({
|
||||
command: "compare",
|
||||
cells: variants.length,
|
||||
truncated: capResult.truncated,
|
||||
total: capResult.total,
|
||||
renderReadyTimedOut,
|
||||
});
|
||||
return buildCompareSuccessPayload(parsed.outPath, variants, capResult);
|
||||
} finally {
|
||||
cleanupPreparedCompareVariants(prepared);
|
||||
rmSync(frameDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function printJson(payload: object): void {
|
||||
console.log(JSON.stringify(withMeta(payload), null, 2));
|
||||
}
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: "compare",
|
||||
description: "Render independent composition variants into one labeled comparison sheet",
|
||||
},
|
||||
args: {
|
||||
path: {
|
||||
type: "positional",
|
||||
description: "Composition project directory or .html file (pass 2+ paths)",
|
||||
required: false,
|
||||
},
|
||||
at: {
|
||||
type: "string",
|
||||
description: "Timeline time in seconds to seek before screenshotting each variant",
|
||||
},
|
||||
labels: {
|
||||
type: "string",
|
||||
description: "Comma-separated labels matching the variant path count",
|
||||
},
|
||||
out: {
|
||||
type: "string",
|
||||
description: "Output comparison sheet path (default: ./compare.png)",
|
||||
},
|
||||
cols: {
|
||||
type: "string",
|
||||
description: "Grid columns (default: sqrt heuristic, capped at 4)",
|
||||
},
|
||||
timeout: {
|
||||
type: "string",
|
||||
description: "Render-ready timeout in ms per variant (default: 5000)",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
description: "Output result as JSON",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
async run({ args }) {
|
||||
const jsonRequested = args.json === true;
|
||||
try {
|
||||
const parsed = parseCompareArgs(args);
|
||||
if (!parsed.json) {
|
||||
console.log(
|
||||
`${c.accent("◆")} Rendering ${Math.min(parsed.variants.length, MAX_COMPARE_VARIANTS)} of ${parsed.variants.length} composition variants`,
|
||||
);
|
||||
}
|
||||
const payload = await renderCompareSheet(parsed);
|
||||
if (parsed.json) {
|
||||
printJson(payload);
|
||||
} else {
|
||||
console.log(`\n${c.success("◇")} Comparison sheet saved to ${payload.sheet}`);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = normalizeErrorMessage(err);
|
||||
if (jsonRequested) {
|
||||
printJson({ ok: false, error: message });
|
||||
} else {
|
||||
console.error(`\n${c.error("✗")} Compare failed: ${message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join } from "node:path";
|
||||
import { HF_COLOR_GRADING_ATTR, serializeHfColorGrading } from "@hyperframes/core";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
buildGradeCompareHtml,
|
||||
buildGradeCompareSuccessPayload,
|
||||
capCandidateCells,
|
||||
parseGradeCompareArgs,
|
||||
parseGradesFile,
|
||||
prepareGradeCompareTempProject,
|
||||
prependBaselineCell,
|
||||
resolveLutCells,
|
||||
warnInactiveGradingCells,
|
||||
} from "./grade-compare.js";
|
||||
|
||||
function tempDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "hf-grade-compare-test-"));
|
||||
}
|
||||
|
||||
function validCubeLut(): string {
|
||||
return `LUT_3D_SIZE 2
|
||||
0 0 0
|
||||
1 0 0
|
||||
0 1 0
|
||||
1 1 0
|
||||
0 0 1
|
||||
1 0 1
|
||||
0 1 1
|
||||
1 1 1
|
||||
`;
|
||||
}
|
||||
|
||||
describe("parseGradesFile", () => {
|
||||
it("parses a valid grades array into labeled cells", () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const file = join(dir, "grades.json");
|
||||
writeFileSync(
|
||||
file,
|
||||
JSON.stringify([
|
||||
{ label: "warm", grading: { preset: "warm-daylight" } },
|
||||
{ label: "punch", grading: { adjust: { exposure: 0.5, contrast: 0.4 } } },
|
||||
]),
|
||||
);
|
||||
|
||||
expect(parseGradesFile(file)).toEqual([
|
||||
{ label: "warm", grading: { preset: "warm-daylight" } },
|
||||
{ label: "punch", grading: { adjust: { exposure: 0.5, contrast: 0.4 } } },
|
||||
]);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("errors clearly for missing or invalid grades files", () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
expect(() => parseGradesFile(join(dir, "missing.json"))).toThrow(
|
||||
/Grades file not found: .*missing\.json/,
|
||||
);
|
||||
|
||||
const invalid = join(dir, "invalid.json");
|
||||
writeFileSync(invalid, JSON.stringify({ label: "not an array" }));
|
||||
expect(() => parseGradesFile(invalid)).toThrow(
|
||||
"Grades file must be a JSON array of { label, grading } objects",
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("prependBaselineCell", () => {
|
||||
it("prepends an ungraded 'original' reference cell", () => {
|
||||
const candidates = resolveLutCells("/tmp/luts/film.cube");
|
||||
const withBaseline = prependBaselineCell(candidates);
|
||||
expect(withBaseline).toHaveLength(candidates.length + 1);
|
||||
// empty grading (no preset / no lut) → normalizes to inactive → renders the
|
||||
// source frame untouched, giving a reference to judge candidates against
|
||||
expect(withBaseline.at(0)).toEqual({ label: "original", grading: {} });
|
||||
expect(withBaseline.slice(1)).toEqual(candidates);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLutCells", () => {
|
||||
it("expands comma-separated LUT paths into labeled grading cells", () => {
|
||||
expect(resolveLutCells("/tmp/luts/film.cube,./cool.look.cube")).toEqual([
|
||||
{ label: "film", grading: { lut: { src: "/tmp/luts/film.cube" } } },
|
||||
{ label: "cool.look", grading: { lut: { src: "./cool.look.cube" } } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseGradeCompareArgs", () => {
|
||||
it("requires exactly one grade source", () => {
|
||||
expect(() => parseGradeCompareArgs({ for: "frame.png" })).toThrow(
|
||||
"Exactly one of --grades or --luts is required",
|
||||
);
|
||||
expect(() =>
|
||||
parseGradeCompareArgs({ for: "frame.png", grades: "grades.json", luts: "a.cube" }),
|
||||
).toThrow("Exactly one of --grades or --luts is required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGradeCompareHtml", () => {
|
||||
it("renders one labeled color-graded image per cell with composition metadata", () => {
|
||||
const cells = [
|
||||
{ label: "warm <daylight>", grading: { preset: "warm-daylight" } },
|
||||
{ label: "cool", grading: { adjust: { temperature: -0.8 } } },
|
||||
{ label: "punchy", grading: { adjust: { exposure: 0.5, contrast: 0.4 } } },
|
||||
];
|
||||
|
||||
const html = buildGradeCompareHtml({
|
||||
cells,
|
||||
frameSrc: "frame.png",
|
||||
frameWidth: 640,
|
||||
frameHeight: 360,
|
||||
});
|
||||
|
||||
const escapedAttr = HF_COLOR_GRADING_ATTR.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
|
||||
const attrPattern = new RegExp(`<img[^>]+${escapedAttr}=`, "g");
|
||||
expect(html.match(attrPattern)).toHaveLength(cells.length);
|
||||
expect(html).toContain('data-composition-id="grade-compare"');
|
||||
expect(html).toContain('data-width="1168"');
|
||||
expect(html).toContain('data-height="742"');
|
||||
expect(html).toContain('data-duration="1"');
|
||||
expect(html).toContain("warm <daylight>");
|
||||
for (const cell of cells) {
|
||||
expect(html).toContain(`${HF_COLOR_GRADING_ATTR}='${serializeHfColorGrading(cell.grading)}'`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareGradeCompareTempProject", () => {
|
||||
it("copies the frame and LUTs into a temp project and rewrites LUT src values", async () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const framePath = join(dir, "frame.png");
|
||||
const lutPath = join(dir, "look.cube");
|
||||
writeFileSync(framePath, "fake-png");
|
||||
writeFileSync(lutPath, validCubeLut());
|
||||
|
||||
const prepared = await prepareGradeCompareTempProject({
|
||||
projectDir: dir,
|
||||
framePath,
|
||||
frameBuffer: Buffer.from("fake-png"),
|
||||
cells: [
|
||||
{ label: "film", grading: { lut: { src: basename(lutPath), intensity: 0.7 } } },
|
||||
{ label: "warm", grading: { preset: "warm-daylight" } },
|
||||
],
|
||||
frameWidth: 640,
|
||||
frameHeight: 360,
|
||||
});
|
||||
|
||||
try {
|
||||
expect(readFileSync(join(prepared.tempDir, "frame.png"), "utf-8")).toBe("fake-png");
|
||||
expect(readFileSync(join(prepared.tempDir, "lut-0.cube"), "utf-8")).toBe(validCubeLut());
|
||||
expect(readFileSync(join(prepared.tempDir, "index.html"), "utf-8")).toContain(
|
||||
`${HF_COLOR_GRADING_ATTR}='${serializeHfColorGrading({
|
||||
lut: { src: "lut-0.cube", intensity: 0.7 },
|
||||
})}'`,
|
||||
);
|
||||
} finally {
|
||||
rmSync(prepared.tempDir, { recursive: true, force: true });
|
||||
}
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an existing LUT file whose .cube content cannot be parsed", async () => {
|
||||
const dir = tempDir();
|
||||
try {
|
||||
const framePath = join(dir, "frame.png");
|
||||
const lutPath = join(dir, "broken.cube");
|
||||
writeFileSync(framePath, "fake-png");
|
||||
writeFileSync(lutPath, "plain text, not cube data\n");
|
||||
|
||||
await expect(
|
||||
prepareGradeCompareTempProject({
|
||||
projectDir: dir,
|
||||
framePath,
|
||||
frameBuffer: Buffer.from("fake-png"),
|
||||
cells: [{ label: "broken look", grading: { lut: { src: basename(lutPath) } } }],
|
||||
frameWidth: 640,
|
||||
frameHeight: 360,
|
||||
}),
|
||||
).rejects.toThrow(/LUT for "broken look" is not a valid \.cube:/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("warnInactiveGradingCells", () => {
|
||||
it("warns to stderr for normalized-but-inactive candidate grades", () => {
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
try {
|
||||
expect(() =>
|
||||
warnInactiveGradingCells([{ label: "numeric lut", grading: { lut: 12345 } }]),
|
||||
).not.toThrow();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'Warning: grading for "numeric lut" is inactive/no-op — it will render ungraded',
|
||||
),
|
||||
);
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("capCandidateCells", () => {
|
||||
it("truncates over-cap candidates and exposes truncation metadata for JSON output", () => {
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
try {
|
||||
const cells = Array.from({ length: 18 }, (_, index) => ({
|
||||
label: `candidate ${index + 1}`,
|
||||
grading: { adjust: { exposure: index / 10 } },
|
||||
}));
|
||||
|
||||
const capped = capCandidateCells(cells);
|
||||
|
||||
expect(capped.cells).toHaveLength(16);
|
||||
expect(capped.cells.at(0)?.label).toBe("candidate 1");
|
||||
expect(capped.cells.at(15)?.label).toBe("candidate 16");
|
||||
expect(capped.truncated).toBe(true);
|
||||
expect(capped.total).toBe(18);
|
||||
expect(buildGradeCompareSuccessPayload("grade-compare.png", 17, capped)).toEqual({
|
||||
ok: true,
|
||||
sheet: "grade-compare.png",
|
||||
cells: 17,
|
||||
truncated: true,
|
||||
total: 18,
|
||||
});
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"Warning: 18 candidate grades exceed the 16-cell cap — rendering the first 16 of 18; re-run with fewer grades or split into multiple runs.",
|
||||
),
|
||||
);
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,698 @@
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, extname, join, resolve } from "node:path";
|
||||
import {
|
||||
HF_COLOR_GRADING_ATTR,
|
||||
isHfColorGradingActive,
|
||||
normalizeHfColorGrading,
|
||||
parseCubeLut,
|
||||
serializeHfColorGrading,
|
||||
} from "@hyperframes/core";
|
||||
import { defineCommand } from "citty";
|
||||
import sharp from "sharp";
|
||||
import type { Example } from "./_examples.js";
|
||||
import { openSettledCompositionPage, runFfmpegOnce } from "../capture/captureCompositionFrame.js";
|
||||
import { findFFmpeg } from "../browser/ffmpeg.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { normalizeErrorMessage } from "../utils/errorMessage.js";
|
||||
import { displayPathFromBase, readOptionalString, resolveFromBase } from "../utils/pathArgs.js";
|
||||
import { trackCompareSheet } from "../telemetry/events.js";
|
||||
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
|
||||
import { withMeta } from "../utils/updateCheck.js";
|
||||
|
||||
const COMPOSITION_ID = "grade-compare";
|
||||
const COMPOSITION_DURATION = "1";
|
||||
const DEFAULT_CELL_WIDTH = 560;
|
||||
const MAX_CANDIDATE_CELLS = 16;
|
||||
const MAX_COLUMNS = 4;
|
||||
const GRID_PADDING = 16;
|
||||
const LABEL_HEIGHT = 32;
|
||||
const FFMPEG_EXTRACT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export interface GradeCompareCell {
|
||||
label: string;
|
||||
grading: unknown;
|
||||
}
|
||||
|
||||
interface ParsedGradeCompareArgs {
|
||||
framePath: string;
|
||||
projectDir: string;
|
||||
outPath: string;
|
||||
source: { kind: "grades"; path: string } | { kind: "luts"; value: string };
|
||||
json: boolean;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
interface PreparedGradeCompareProject {
|
||||
tempDir: string;
|
||||
html: string;
|
||||
cells: GradeCompareCell[];
|
||||
}
|
||||
|
||||
export interface CandidateCellCapResult {
|
||||
cells: GradeCompareCell[];
|
||||
truncated: boolean;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface GradeCompareSuccessPayload {
|
||||
ok: true;
|
||||
sheet: string;
|
||||
cells: number;
|
||||
truncated?: true;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
interface GradeCompareHtmlOptions {
|
||||
cells: readonly GradeCompareCell[];
|
||||
frameSrc: string;
|
||||
frameWidth: number;
|
||||
frameHeight: number;
|
||||
}
|
||||
|
||||
interface ReferenceFrame {
|
||||
buffer: Buffer;
|
||||
width: number;
|
||||
height: number;
|
||||
stagedName: string;
|
||||
}
|
||||
|
||||
export const examples: Example[] = [
|
||||
[
|
||||
"Compare grade presets on one reference frame",
|
||||
"hyperframes grade-compare --for frame.png --grades grades.json",
|
||||
],
|
||||
[
|
||||
"Compare LUT files and print agent-friendly JSON",
|
||||
"hyperframes grade-compare --for frame.png --luts looks/a.cube,looks/b.cube --json",
|
||||
],
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasOwn(record: Record<string, unknown>, key: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(record, key);
|
||||
}
|
||||
|
||||
function cloneRecord(record: Record<string, unknown>): Record<string, unknown> {
|
||||
const next: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(record)) {
|
||||
next[key] = value;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function escapeSingleQuotedAttr(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function validateCell(label: string, grading: unknown): GradeCompareCell {
|
||||
if (!normalizeHfColorGrading(grading)) {
|
||||
throw new Error(`Invalid color grading for cell "${label}"`);
|
||||
}
|
||||
return { label, grading };
|
||||
}
|
||||
|
||||
export function warnInactiveGradingCells(cells: readonly GradeCompareCell[]): void {
|
||||
for (const cell of cells) {
|
||||
const normalized = normalizeHfColorGrading(cell.grading);
|
||||
if (!isHfColorGradingActive(normalized)) {
|
||||
console.error(
|
||||
c.warn(`Warning: grading for "${cell.label}" is inactive/no-op — it will render ungraded`),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function capCandidateCells(cells: readonly GradeCompareCell[]): CandidateCellCapResult {
|
||||
const total = cells.length;
|
||||
if (total <= MAX_CANDIDATE_CELLS) {
|
||||
return { cells: [...cells], truncated: false, total };
|
||||
}
|
||||
console.error(
|
||||
c.warn(
|
||||
`Warning: ${total} candidate grades exceed the ${MAX_CANDIDATE_CELLS}-cell cap — rendering the first ${MAX_CANDIDATE_CELLS} of ${total}; re-run with fewer grades or split into multiple runs.`,
|
||||
),
|
||||
);
|
||||
return { cells: cells.slice(0, MAX_CANDIDATE_CELLS), truncated: true, total };
|
||||
}
|
||||
|
||||
export function buildGradeCompareSuccessPayload(
|
||||
sheet: string,
|
||||
cells: number,
|
||||
capResult: CandidateCellCapResult,
|
||||
): GradeCompareSuccessPayload {
|
||||
if (!capResult.truncated) {
|
||||
return { ok: true, sheet, cells };
|
||||
}
|
||||
return { ok: true, sheet, cells, truncated: true, total: capResult.total };
|
||||
}
|
||||
|
||||
function serializedGradingForCell(cell: GradeCompareCell): string {
|
||||
const normalized = normalizeHfColorGrading(cell.grading);
|
||||
if (!normalized) {
|
||||
throw new Error(`Invalid color grading for cell "${cell.label}"`);
|
||||
}
|
||||
return serializeHfColorGrading(normalized);
|
||||
}
|
||||
|
||||
function lutSrcFromGrading(grading: unknown): string | null {
|
||||
if (!isRecord(grading) || !hasOwn(grading, "lut")) return null;
|
||||
const lut = grading.lut;
|
||||
if (typeof lut === "string" && lut.trim()) return lut.trim();
|
||||
if (!isRecord(lut)) return null;
|
||||
const src = lut.src;
|
||||
return typeof src === "string" && src.trim() ? src.trim() : null;
|
||||
}
|
||||
|
||||
function rewriteGradingLutSrc(grading: unknown, src: string): unknown {
|
||||
if (!isRecord(grading) || !hasOwn(grading, "lut")) return grading;
|
||||
const lut = grading.lut;
|
||||
const next = cloneRecord(grading);
|
||||
if (typeof lut === "string") {
|
||||
next.lut = { src };
|
||||
return next;
|
||||
}
|
||||
if (isRecord(lut)) {
|
||||
const nextLut = cloneRecord(lut);
|
||||
nextLut.src = src;
|
||||
next.lut = nextLut;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function parseGradesFile(filePath: string): GradeCompareCell[] {
|
||||
if (!existsSync(filePath)) {
|
||||
throw new Error(`Grades file not found: ${filePath}`);
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||
} catch (err) {
|
||||
throw new Error(`Could not parse grades JSON: ${normalizeErrorMessage(err)}`);
|
||||
}
|
||||
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new Error("Grades file must be a JSON array of { label, grading } objects");
|
||||
}
|
||||
|
||||
return parsed.map((entry, index) => {
|
||||
if (!isRecord(entry)) {
|
||||
throw new Error(`Grade entry ${index + 1} must be an object with label and grading`);
|
||||
}
|
||||
const label = entry.label;
|
||||
if (typeof label !== "string" || !label.trim()) {
|
||||
throw new Error(`Grade entry ${index + 1} must have a non-empty string label`);
|
||||
}
|
||||
if (!hasOwn(entry, "grading")) {
|
||||
throw new Error(`Grade entry "${label}" must include a grading value`);
|
||||
}
|
||||
return validateCell(label, entry.grading);
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveLutCells(luts: string): GradeCompareCell[] {
|
||||
const paths = luts
|
||||
.split(",")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
if (paths.length === 0) {
|
||||
throw new Error("--luts must include at least one LUT path");
|
||||
}
|
||||
return paths.map((lutPath) =>
|
||||
validateCell(basename(lutPath, extname(lutPath)), { lut: { src: lutPath } }),
|
||||
);
|
||||
}
|
||||
|
||||
// The ungraded frame as a leading reference cell. An empty grading object
|
||||
// normalizes to inactive, so the runtime renders the source image untouched —
|
||||
// giving the agent a baseline to judge every candidate look against.
|
||||
export function prependBaselineCell(cells: GradeCompareCell[]): GradeCompareCell[] {
|
||||
return [validateCell("original", {}), ...cells];
|
||||
}
|
||||
|
||||
export function parseGradeCompareArgs(args: {
|
||||
for?: unknown;
|
||||
grades?: unknown;
|
||||
luts?: unknown;
|
||||
project?: unknown;
|
||||
out?: unknown;
|
||||
json?: unknown;
|
||||
timeout?: unknown;
|
||||
}): ParsedGradeCompareArgs {
|
||||
const frameArg = readOptionalString(args.for);
|
||||
if (!frameArg) throw new Error("--for <path> is required");
|
||||
|
||||
const gradesArg = readOptionalString(args.grades);
|
||||
const lutsArg = readOptionalString(args.luts);
|
||||
if (Boolean(gradesArg) === Boolean(lutsArg)) {
|
||||
throw new Error("Exactly one of --grades or --luts is required");
|
||||
}
|
||||
|
||||
const projectDir = resolve(readOptionalString(args.project) ?? process.cwd());
|
||||
const framePath = resolveFromBase(projectDir, frameArg);
|
||||
const outPath = resolveFromBase(projectDir, readOptionalString(args.out) ?? "grade-compare.png");
|
||||
|
||||
return {
|
||||
framePath,
|
||||
projectDir,
|
||||
outPath,
|
||||
source: gradesArg
|
||||
? { kind: "grades", path: resolveFromBase(projectDir, gradesArg) }
|
||||
: { kind: "luts", value: lutsArg ?? "" },
|
||||
json: args.json === true,
|
||||
timeoutMs: Number.parseInt(readOptionalString(args.timeout) ?? "", 10) || 5000,
|
||||
};
|
||||
}
|
||||
|
||||
function gridMetrics(
|
||||
cellCount: number,
|
||||
frameWidth: number,
|
||||
frameHeight: number,
|
||||
): {
|
||||
columns: number;
|
||||
rows: number;
|
||||
cellImageWidth: number;
|
||||
cellImageHeight: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
const columns = Math.max(1, Math.min(MAX_COLUMNS, Math.ceil(Math.sqrt(cellCount))));
|
||||
const rows = Math.ceil(cellCount / columns);
|
||||
const cellImageWidth = DEFAULT_CELL_WIDTH;
|
||||
const aspect = frameHeight > 0 && frameWidth > 0 ? frameHeight / frameWidth : 9 / 16;
|
||||
const cellImageHeight = Math.max(1, Math.round(cellImageWidth * aspect));
|
||||
return {
|
||||
columns,
|
||||
rows,
|
||||
cellImageWidth,
|
||||
cellImageHeight,
|
||||
width: columns * cellImageWidth + (columns + 1) * GRID_PADDING,
|
||||
height: rows * (cellImageHeight + LABEL_HEIGHT) + (rows + 1) * GRID_PADDING,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildGradeCompareHtml(options: GradeCompareHtmlOptions): string {
|
||||
if (options.cells.length === 0) {
|
||||
throw new Error("At least one grade cell is required");
|
||||
}
|
||||
const metrics = gridMetrics(options.cells.length, options.frameWidth, options.frameHeight);
|
||||
|
||||
const cellHtml = options.cells
|
||||
.map((cell, index) => {
|
||||
const serialized = escapeSingleQuotedAttr(serializedGradingForCell(cell));
|
||||
const label = escapeXml(cell.label);
|
||||
const row = Math.floor(index / metrics.columns);
|
||||
const col = index % metrics.columns;
|
||||
const left = GRID_PADDING + col * (metrics.cellImageWidth + GRID_PADDING);
|
||||
const top = GRID_PADDING + row * (metrics.cellImageHeight + LABEL_HEIGHT + GRID_PADDING);
|
||||
return ` <figure class="grade-cell" style="left:${left}px;top:${top}px;width:${metrics.cellImageWidth}px;height:${metrics.cellImageHeight + LABEL_HEIGHT}px">
|
||||
<figcaption>${label}</figcaption>
|
||||
<img src="${escapeXml(options.frameSrc)}" ${HF_COLOR_GRADING_ATTR}='${serialized}' alt="${label}" />
|
||||
</figure>`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=${metrics.width}, height=${metrics.height}" />
|
||||
<title>HyperFrames Grade Compare</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
width: ${metrics.width}px;
|
||||
height: ${metrics.height}px;
|
||||
overflow: hidden;
|
||||
background: #191919;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
#${COMPOSITION_ID} {
|
||||
position: relative;
|
||||
width: ${metrics.width}px;
|
||||
height: ${metrics.height}px;
|
||||
overflow: hidden;
|
||||
background: #191919;
|
||||
}
|
||||
|
||||
.grade-cell {
|
||||
position: absolute;
|
||||
margin: 0;
|
||||
background: #0f0f0f;
|
||||
}
|
||||
|
||||
.grade-cell figcaption {
|
||||
height: ${LABEL_HEIGHT}px;
|
||||
line-height: ${LABEL_HEIGHT}px;
|
||||
padding: 0 10px;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
color: #ffffff;
|
||||
background: #111111;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.grade-cell img {
|
||||
display: block;
|
||||
width: ${metrics.cellImageWidth}px;
|
||||
height: ${metrics.cellImageHeight}px;
|
||||
object-fit: contain;
|
||||
background: #000000;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div
|
||||
id="${COMPOSITION_ID}"
|
||||
data-composition-id="${COMPOSITION_ID}"
|
||||
data-start="0"
|
||||
data-duration="${COMPOSITION_DURATION}"
|
||||
data-width="${metrics.width}"
|
||||
data-height="${metrics.height}"
|
||||
>
|
||||
${cellHtml}
|
||||
<script>
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["${COMPOSITION_ID}"] = gsap.timeline({ paused: true });
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
function frameFileNameForPath(framePath: string): string {
|
||||
const ext = extname(framePath).toLowerCase();
|
||||
if (ext === ".jpg" || ext === ".jpeg") return `frame${ext}`;
|
||||
return "frame.png";
|
||||
}
|
||||
|
||||
export async function prepareGradeCompareTempProject(opts: {
|
||||
projectDir: string;
|
||||
framePath: string;
|
||||
frameBuffer: Buffer;
|
||||
cells: readonly GradeCompareCell[];
|
||||
frameWidth: number;
|
||||
frameHeight: number;
|
||||
frameFileName?: string;
|
||||
}): Promise<PreparedGradeCompareProject> {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hf-grade-compare-"));
|
||||
try {
|
||||
const frameFileName = opts.frameFileName ?? frameFileNameForPath(opts.framePath);
|
||||
writeFileSync(join(tempDir, frameFileName), opts.frameBuffer);
|
||||
|
||||
let lutIndex = 0;
|
||||
const stagedCells = opts.cells.map((cell) => {
|
||||
const lutSrc = lutSrcFromGrading(cell.grading);
|
||||
if (!lutSrc) return cell;
|
||||
|
||||
const sourcePath = resolveFromBase(opts.projectDir, lutSrc);
|
||||
if (!existsSync(sourcePath)) {
|
||||
throw new Error(`LUT file not found for "${cell.label}": ${sourcePath}`);
|
||||
}
|
||||
const lutText = readFileSync(sourcePath, "utf-8");
|
||||
try {
|
||||
parseCubeLut(lutText, { maxSize: 64 });
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`LUT for "${cell.label}" is not a valid .cube: ${normalizeErrorMessage(err)}`,
|
||||
);
|
||||
}
|
||||
const lutExt = extname(sourcePath) || ".cube";
|
||||
const stagedName = `lut-${lutIndex}${lutExt}`;
|
||||
lutIndex += 1;
|
||||
copyFileSync(sourcePath, join(tempDir, stagedName));
|
||||
return {
|
||||
label: cell.label,
|
||||
grading: rewriteGradingLutSrc(cell.grading, stagedName),
|
||||
};
|
||||
});
|
||||
|
||||
const html = buildGradeCompareHtml({
|
||||
cells: stagedCells,
|
||||
frameSrc: frameFileName,
|
||||
frameWidth: opts.frameWidth,
|
||||
frameHeight: opts.frameHeight,
|
||||
});
|
||||
writeFileSync(join(tempDir, "index.html"), html);
|
||||
return { tempDir, html, cells: stagedCells };
|
||||
} catch (err) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function isVideoPath(filePath: string): boolean {
|
||||
const ext = extname(filePath).toLowerCase();
|
||||
return [".mp4", ".mov", ".m4v", ".webm", ".mkv", ".avi", ".mpeg", ".mpg", ".ogv"].includes(ext);
|
||||
}
|
||||
|
||||
async function extractVideoFrameToBuffer(videoPath: string): Promise<Buffer | null> {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "hf-grade-compare-frame-"));
|
||||
const outPath = join(tmp, "frame.png");
|
||||
try {
|
||||
const ffmpegPath = findFFmpeg();
|
||||
if (!ffmpegPath) return null;
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-ss",
|
||||
"0",
|
||||
"-i",
|
||||
videoPath,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-y",
|
||||
outPath,
|
||||
];
|
||||
const result = await runFfmpegOnce(ffmpegPath, args, FFMPEG_EXTRACT_TIMEOUT_MS);
|
||||
if (result.timedOut) {
|
||||
throw new Error(`ffmpeg timed out extracting first frame from ${videoPath}`);
|
||||
}
|
||||
if (result.code !== 0 || !existsSync(outPath)) {
|
||||
const detail = result.stderr.trim() ? `: ${result.stderr.trim()}` : "";
|
||||
throw new Error(`ffmpeg could not extract first frame from ${videoPath}${detail}`);
|
||||
}
|
||||
return readFileSync(outPath);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function loadReferenceFrame(framePath: string): Promise<ReferenceFrame> {
|
||||
if (!existsSync(framePath)) {
|
||||
throw new Error(`Reference frame not found: ${framePath}`);
|
||||
}
|
||||
|
||||
const buffer = isVideoPath(framePath)
|
||||
? await extractVideoFrameToBuffer(framePath)
|
||||
: readFileSync(framePath);
|
||||
if (!buffer) {
|
||||
throw new Error(`Could not extract a frame from video: ${framePath}`);
|
||||
}
|
||||
|
||||
const metadata = await sharp(buffer).metadata();
|
||||
if (!metadata.width || !metadata.height) {
|
||||
throw new Error(`Could not read reference frame dimensions: ${framePath}`);
|
||||
}
|
||||
|
||||
return {
|
||||
buffer,
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
stagedName: isVideoPath(framePath) ? "frame.png" : frameFileNameForPath(framePath),
|
||||
};
|
||||
}
|
||||
|
||||
async function captureGradeCompareSheet(
|
||||
projectDir: string,
|
||||
timeoutMs: number,
|
||||
): Promise<{ sheetPath: string; renderReadyTimedOut: boolean }> {
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
|
||||
const html = await bundleToSingleHtml(projectDir);
|
||||
const server = await serveStaticProjectHtml(projectDir, html);
|
||||
const sheetPath = join(projectDir, "grade-compare.png");
|
||||
|
||||
try {
|
||||
const {
|
||||
browser: chromeBrowser,
|
||||
page,
|
||||
renderReadyTimedOut,
|
||||
} = await openSettledCompositionPage(html, server.url, {
|
||||
renderReadyTimeoutMs: timeoutMs,
|
||||
renderReadyWarningSuffix: "grade comparison may be inaccurate",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.screenshot({ path: sheetPath, type: "png" });
|
||||
return { sheetPath, renderReadyTimedOut };
|
||||
} finally {
|
||||
await chromeBrowser.close();
|
||||
}
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
function printJson(payload: object): void {
|
||||
console.log(JSON.stringify(withMeta(payload), null, 2));
|
||||
}
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: "grade-compare",
|
||||
description: "Render candidate color grades onto a reference frame as one comparison PNG",
|
||||
},
|
||||
args: {
|
||||
for: {
|
||||
type: "string",
|
||||
description: "Reference image path, or a video path to sample at t=0",
|
||||
required: true,
|
||||
},
|
||||
grades: {
|
||||
type: "string",
|
||||
description: "JSON array of { label, grading } candidate grades",
|
||||
},
|
||||
luts: {
|
||||
type: "string",
|
||||
description: "Comma-separated .cube LUT paths to compare",
|
||||
},
|
||||
project: {
|
||||
type: "string",
|
||||
description: "Base directory for relative --for, --grades, and LUT paths (default: cwd)",
|
||||
},
|
||||
out: {
|
||||
type: "string",
|
||||
description: "Output PNG path (default: <project>/grade-compare.png)",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
description: "Output result as JSON",
|
||||
default: false,
|
||||
},
|
||||
timeout: {
|
||||
type: "string",
|
||||
description: "Render-ready timeout in ms before capture (default: 5000)",
|
||||
},
|
||||
baseline: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Prepend the ungraded frame as an 'original' reference cell (--no-baseline to omit)",
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
async run({ args }) {
|
||||
const jsonRequested = args.json === true;
|
||||
let preparedDir: string | null = null;
|
||||
try {
|
||||
const parsed = parseGradeCompareArgs({
|
||||
for: args.for,
|
||||
grades: args.grades,
|
||||
luts: args.luts,
|
||||
project: args.project,
|
||||
out: args.out,
|
||||
json: args.json,
|
||||
timeout: args.timeout,
|
||||
});
|
||||
let cells =
|
||||
parsed.source.kind === "grades"
|
||||
? parseGradesFile(parsed.source.path)
|
||||
: resolveLutCells(parsed.source.value);
|
||||
if (cells.length === 0) {
|
||||
throw new Error("At least one grade candidate is required");
|
||||
}
|
||||
const capResult = capCandidateCells(cells);
|
||||
cells = capResult.cells;
|
||||
warnInactiveGradingCells(cells);
|
||||
if (args.baseline !== false) {
|
||||
cells = prependBaselineCell(cells);
|
||||
}
|
||||
|
||||
if (!parsed.json) {
|
||||
console.log(
|
||||
`${c.accent("◆")} Rendering ${cells.length} grade candidates from ${c.accent(basename(parsed.framePath))}`,
|
||||
);
|
||||
}
|
||||
|
||||
const frame = await loadReferenceFrame(parsed.framePath);
|
||||
const prepared = await prepareGradeCompareTempProject({
|
||||
projectDir: parsed.projectDir,
|
||||
framePath: parsed.framePath,
|
||||
frameBuffer: frame.buffer,
|
||||
frameWidth: frame.width,
|
||||
frameHeight: frame.height,
|
||||
frameFileName: frame.stagedName,
|
||||
cells,
|
||||
});
|
||||
preparedDir = prepared.tempDir;
|
||||
|
||||
const { sheetPath: tempSheet, renderReadyTimedOut } = await captureGradeCompareSheet(
|
||||
prepared.tempDir,
|
||||
parsed.timeoutMs,
|
||||
);
|
||||
mkdirSync(dirname(parsed.outPath), { recursive: true });
|
||||
copyFileSync(tempSheet, parsed.outPath);
|
||||
trackCompareSheet({
|
||||
command: "grade-compare",
|
||||
cells: prepared.cells.length,
|
||||
truncated: capResult.truncated,
|
||||
total: capResult.total,
|
||||
renderReadyTimedOut,
|
||||
});
|
||||
|
||||
const sheet = displayPathFromBase(parsed.projectDir, parsed.outPath);
|
||||
if (parsed.json) {
|
||||
printJson(buildGradeCompareSuccessPayload(sheet, prepared.cells.length, capResult));
|
||||
} else {
|
||||
console.log(`\n${c.success("◇")} Grade comparison saved to ${sheet}`);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = normalizeErrorMessage(err);
|
||||
if (jsonRequested) {
|
||||
printJson({ ok: false, error: message });
|
||||
} else {
|
||||
console.error(`\n${c.error("✗")} Grade compare failed: ${message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (preparedDir) {
|
||||
rmSync(preparedDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,12 +1,15 @@
|
||||
// fallow-ignore-file complexity
|
||||
import { spawn } from "node:child_process";
|
||||
import { defineCommand } from "citty";
|
||||
import { existsSync, mkdtempSync, readFileSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join, relative, isAbsolute, basename } from "node:path";
|
||||
import {
|
||||
openSettledCompositionPage,
|
||||
runFfmpegOnce,
|
||||
seekCompositionTimeline,
|
||||
} from "../capture/captureCompositionFrame.js";
|
||||
import { resolveProject } from "../utils/project.js";
|
||||
import { normalizeErrorMessage } from "../utils/errorMessage.js";
|
||||
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
|
||||
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { findFFmpeg } from "../browser/ffmpeg.js";
|
||||
@@ -67,46 +70,25 @@ async function extractVideoFrameToBuffer(
|
||||
try {
|
||||
const ffmpegPath = findFFmpeg();
|
||||
if (!ffmpegPath) return null;
|
||||
const result = await new Promise<{ code: number | null; stderr: string; timedOut: boolean }>(
|
||||
(resolvePromise) => {
|
||||
// `-ss` before `-i` performs a fast keyframe seek; adequate for snapshot accuracy
|
||||
// (±1 frame) and orders of magnitude faster than the decode-and-scan alternative.
|
||||
const args = ["-hide_banner", "-loglevel", "error"];
|
||||
if (useVp9AlphaDecoder) {
|
||||
args.push("-c:v", "libvpx-vp9");
|
||||
}
|
||||
args.push(
|
||||
"-ss",
|
||||
String(Math.max(0, timeSeconds)),
|
||||
"-i",
|
||||
videoPath,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-y",
|
||||
outPath,
|
||||
);
|
||||
const ff = spawn(ffmpegPath, args);
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
ff.kill("SIGTERM");
|
||||
}, FFMPEG_EXTRACT_TIMEOUT_MS);
|
||||
ff.stderr.on("data", (d: Buffer) => {
|
||||
stderr += d.toString();
|
||||
});
|
||||
ff.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolvePromise({ code, stderr, timedOut });
|
||||
});
|
||||
ff.on("error", () => {
|
||||
clearTimeout(timer);
|
||||
resolvePromise({ code: null, stderr: "ffmpeg spawn failed", timedOut });
|
||||
});
|
||||
},
|
||||
// `-ss` before `-i` performs a fast keyframe seek; adequate for snapshot accuracy
|
||||
// (±1 frame) and orders of magnitude faster than the decode-and-scan alternative.
|
||||
const args = ["-hide_banner", "-loglevel", "error"];
|
||||
if (useVp9AlphaDecoder) {
|
||||
args.push("-c:v", "libvpx-vp9");
|
||||
}
|
||||
args.push(
|
||||
"-ss",
|
||||
String(Math.max(0, timeSeconds)),
|
||||
"-i",
|
||||
videoPath,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-y",
|
||||
outPath,
|
||||
);
|
||||
const result = await runFfmpegOnce(ffmpegPath, args, FFMPEG_EXTRACT_TIMEOUT_MS);
|
||||
if (result.code !== 0 || result.timedOut || !existsSync(outPath)) return null;
|
||||
return readFileSync(outPath);
|
||||
} finally {
|
||||
@@ -193,7 +175,6 @@ async function captureSnapshots(
|
||||
},
|
||||
): Promise<string[]> {
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
const { ensureBrowser } = await import("../browser/manager.js");
|
||||
|
||||
const numFrames = opts.frames ?? 5;
|
||||
|
||||
@@ -203,75 +184,12 @@ async function captureSnapshots(
|
||||
const savedPaths: string[] = [];
|
||||
|
||||
try {
|
||||
const browser = await ensureBrowser();
|
||||
const puppeteer = await import("puppeteer-core");
|
||||
const chromeBrowser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: [
|
||||
"--no-sandbox",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--enable-webgl",
|
||||
"--use-gl=angle",
|
||||
"--use-angle=swiftshader",
|
||||
],
|
||||
const { browser: chromeBrowser, page } = await openSettledCompositionPage(html, server.url, {
|
||||
renderReadyTimeoutMs: opts.timeout ?? 5000,
|
||||
renderReadyWarningSuffix: "snapshots may be inaccurate",
|
||||
});
|
||||
|
||||
try {
|
||||
const page = await chromeBrowser.newPage();
|
||||
await page.setViewport(resolveCompositionViewportFromHtml(html));
|
||||
|
||||
await page.goto(server.url, {
|
||||
waitUntil: "domcontentloaded",
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// __renderReady is set after the player is constructed AND the root
|
||||
// timeline is bound — waiting for it guarantees renderSeek will work.
|
||||
const timeoutMs = opts.timeout ?? 5000;
|
||||
const runtimeReady = await page
|
||||
.waitForFunction(() => !!(window as any).__renderReady, { timeout: timeoutMs })
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
|
||||
if (!runtimeReady) {
|
||||
console.warn(
|
||||
`\n ${c.warn("⚠")} Runtime did not become render-ready within ${timeoutMs}ms — snapshots may be inaccurate`,
|
||||
);
|
||||
}
|
||||
|
||||
// Wait for shader transition pre-rendering (HyperShader IndexedDB hydration).
|
||||
// Uses the ready state flag as primary signal, with the loading overlay
|
||||
// display:none as a fallback for older builds.
|
||||
await page
|
||||
.waitForFunction(
|
||||
() => {
|
||||
const win = window as unknown as {
|
||||
__hf?: { shaderTransitions?: Record<string, { ready?: boolean }> };
|
||||
};
|
||||
const shaderTransitions = win.__hf?.shaderTransitions;
|
||||
if (shaderTransitions !== undefined) {
|
||||
return Object.values(shaderTransitions).every((s) => s.ready === true);
|
||||
}
|
||||
const overlay = document.querySelector(
|
||||
"[data-hyper-shader-loading]",
|
||||
) as HTMLElement | null;
|
||||
if (!overlay) return true;
|
||||
return window.getComputedStyle(overlay).display === "none";
|
||||
},
|
||||
{ timeout: 90_000 },
|
||||
)
|
||||
.catch(() => {
|
||||
console.warn(` ${c.warn("⚠")} Shader transitions did not finish pre-rendering`);
|
||||
});
|
||||
|
||||
// Wait for fonts to finish loading before capturing
|
||||
await page.evaluate(() => document.fonts.ready).catch(() => {});
|
||||
|
||||
// Extra settle time for media and animations to initialize
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
|
||||
// Font verification — split into loaded / errored / unused. Only status
|
||||
// "error" is a real failure; a face still "unloaded"/"loading" after
|
||||
// document.fonts.ready + the settle wait was simply never requested by any
|
||||
@@ -406,26 +324,7 @@ async function captureSnapshots(
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
const time = positions[i]!;
|
||||
|
||||
await page.evaluate((t: number) => {
|
||||
const player = (window as any).__player;
|
||||
if (!player) return;
|
||||
const safe = Math.max(0, Number(t) || 0);
|
||||
if (typeof player.renderSeek === "function") {
|
||||
player.renderSeek(safe);
|
||||
} else if (typeof player.seek === "function") {
|
||||
player.seek(safe);
|
||||
}
|
||||
if ((window as any).gsap?.ticker?.tick) {
|
||||
(window as any).gsap.ticker.tick();
|
||||
}
|
||||
}, time);
|
||||
|
||||
await page.evaluate(`new Promise(function(r) {
|
||||
var settled = false;
|
||||
function finish() { if (settled) return; settled = true; r(); }
|
||||
window.setTimeout(finish, 100);
|
||||
requestAnimationFrame(function() { requestAnimationFrame(finish); });
|
||||
})`);
|
||||
await seekCompositionTimeline(page, time);
|
||||
|
||||
if (cameraExpr) await page.evaluate(cameraExpr);
|
||||
|
||||
|
||||
@@ -41,6 +41,11 @@ const GROUPS: Group[] = [
|
||||
["inspect", "Inspect rendered visual layout across the timeline"],
|
||||
["keyframes", "Inspect keyframes and render onion-shot diagnostics"],
|
||||
["snapshot", "Capture key frames as PNG screenshots for visual verification"],
|
||||
[
|
||||
"grade-compare",
|
||||
"Render candidate color grades onto a reference frame as one labeled comparison PNG",
|
||||
],
|
||||
["compare", "Render composition variants into one labeled comparison sheet"],
|
||||
["info", "Print project metadata"],
|
||||
["compositions", "List all compositions in a project"],
|
||||
["docs", "View inline documentation in the terminal"],
|
||||
|
||||
@@ -492,6 +492,25 @@ export function trackTranscribeUnavailable(props: { optional: boolean }): void {
|
||||
trackEvent("transcribe_unavailable", { optional: props.optional });
|
||||
}
|
||||
|
||||
// grade-compare / compare stand up headless Chrome and render up to 16 cells.
|
||||
// Cell count, truncation-cap hits, and whether the render-ready timeout fired
|
||||
// are the signals needed before safely lifting the cap. Low-cardinality only.
|
||||
export function trackCompareSheet(props: {
|
||||
command: "grade-compare" | "compare";
|
||||
cells: number;
|
||||
truncated: boolean;
|
||||
total: number;
|
||||
renderReadyTimedOut: boolean;
|
||||
}): void {
|
||||
trackEvent("media_use_compare", {
|
||||
command: props.command,
|
||||
cells: props.cells,
|
||||
truncated: props.truncated,
|
||||
total: props.total,
|
||||
render_ready_timed_out: props.renderReadyTimedOut,
|
||||
});
|
||||
}
|
||||
|
||||
// A skills install was skipped because a required prerequisite binary is
|
||||
// absent from PATH (e.g. git on a fresh Windows box). Best-effort callers
|
||||
// (init) skip cleanly rather than crash, so the skip is otherwise invisible;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
export function readOptionalString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
export function resolveFromBase(baseDir: string, input: string): string {
|
||||
return isAbsolute(input) ? input : resolve(baseDir, input);
|
||||
}
|
||||
|
||||
export function displayPathFromBase(baseDir: string, filePath: string): string {
|
||||
const rel = relative(baseDir, filePath);
|
||||
if (rel && !rel.startsWith("..") && !isAbsolute(rel)) return rel;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function displayPathFromInput(baseDir: string, input: string): string {
|
||||
return isAbsolute(input) ? displayPathFromBase(baseDir, input) : input;
|
||||
}
|
||||
Reference in New Issue
Block a user