#!/usr/bin/env node
// assemble-index.mjs — deterministic top-level index.html assembly for a
// HyperFrames project. No subagent, no judgment: turns STORYBOARD.md + the
// built frame files (+ optional audio_meta.json) into the standalone index.html
// the renderer consumes, and stages the frame-named capture assets into assets/.
//
// index.html is a *standalone* composition (root
directly in
// , no
wrapper — template is for sub-comps). Structure is
// modeled on the canonical fixture packages/studio/fixtures/storyboard-sample/
// index.html and the authoritative head/audio template in
// packages/core/docs/quickstart-template.html. Frame mount order = STORYBOARD
// document order. Transitions are NOT written here — the transitions injector
// mutates this file afterward (data-start/duration/track-index + GSAP).
//
// Track lanes (same-track time-overlap is illegal — lint timeline_track_too_dense):
// 1 frame sub-comp clips (sequential; the injector 0/1-ping-pongs for overlaps)
// 2 captions sub-comp clip (full-duration overlay, on top of frames)
// 10 per-frame voice
// 11 BGM
// 20+i SFX (one lane each)
//
// audio_meta.json contract (produced by audio.mjs; OPTIONAL — absent ⇒ silent
// video, frames only). Durations come from STORYBOARD (audio sync-durations
// writes them), NOT from here; this file carries only media PATHS, keyed by
// frame number:
// { "bgm": { "path": "assets/bgm/x.mp3", "volume": 0.12 } | null,
// "voices":[ { "frame": 3, "path": "assets/voice/03.wav" } ],
// "sfx": [ { "frame": 3, "file": "assets/sfx/x.mp3", "offset_s": 0,
// "duration_s": 1.0, "volume": 0.35 } ] }
//
// Reads: --storyboard STORYBOARD.md, --hyperframes ,
// [--audio-meta audio_meta.json]. On disk: each built frame's src html,
// capture/{assets,assets/videos,screenshots}/ for staging, compositions/captions.html.
// Writes: /index.html + stages assets/ + (guard ① below)
// repairs a frame file in place when its root is missing data-width/height.
//
// Pre-assembly frame guards (run in the same pass that reads each frame, so common
// `lint` failures surface HERE instead of after assembly + a wasted render):
// ① AUTO-REPAIR — a sub-comp root missing data-width/data-height: inject the canvas
// dims (the renderer needs them on the cloned root; else lint root_missing_dimensions).
// ② HARD FAIL — / inside a sub-comp: the runtime only drives media that
// is a DIRECT child of the host root, so sub-comp media renders blank/black.
// ③ HARD FAIL — a timed element (data-start+duration+track-index) that is not the root
// and lacks class="clip" (shows the whole frame), or two same-track clips that overlap.
//
// Exit 0 = index.html written + summary. Exit 1 = fatal contract break (no
// frames, a built/animated frame missing its src/file, a frame with no
// duration, an inner data-composition-id mismatch, or a guard ②/③ violation).
// No backstop: fix upstream.
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { basename, join, resolve } from "node:path";
import { parseStoryboard } from "./lib/storyboard.mjs";
import { parseFormat } from "./lib/dimensions.mjs";
import { stageAssets } from "./lib/assets.mjs";
import { parseColors, semanticColors } from "./lib/tokens.mjs";
import { bgmDefaultVolume } from "../../media-use/audio/scripts/lib/bgm.mjs";
// ---------- argv ----------
const argv = process.argv.slice(2);
const flag = (name, def) => {
const i = argv.indexOf(`--${name}`);
return i >= 0 && i + 1 < argv.length ? argv[i + 1] : def;
};
function die(msg) {
console.error(`✗ assemble-index.mjs: ${msg}`);
process.exit(1);
}
// Ensure the BGM track is at least `total` seconds long. HeyGen (and most music
// libraries) return a short loopable clip (~15–30s); mounting it at data-duration=total
// would leave the video's TAIL SILENT. If the file is short, loop-extend it to `total`
// (with a 0.4s fade-in + 1.5s fade-out) into a sibling *.loop.mp3 and return that path.
// Needs ffprobe+ffmpeg (present in the render env); degrades to the original + a warning
// when they're absent, so assembly never hard-fails on audio tooling.
function ensureBgmCovers(relPath, hyperframesDir, total) {
const abs = join(hyperframesDir, relPath);
const probe = spawnSync(
"ffprobe",
["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", abs],
{ encoding: "utf8" },
);
if (probe.status !== 0) return { looped: false, short: false, reason: "ffprobe unavailable" };
const dur = parseFloat(String(probe.stdout || "").trim());
if (!Number.isFinite(dur) || dur <= 0)
return { looped: false, short: false, reason: "unreadable duration" };
if (dur >= total - 0.1) return { looped: false, short: false, dur }; // already covers
const relOut = relPath.replace(/\.([^./]+)$/, ".loop.$1");
const absOut = join(hyperframesDir, relOut);
const fadeOut = Math.max(0, total - 1.5);
const ff = spawnSync(
"ffmpeg",
[
"-y",
"-stream_loop",
"-1",
"-i",
abs,
"-t",
String(total),
"-af",
`afade=t=in:st=0:d=0.4,afade=t=out:st=${fadeOut}:d=1.5`,
"-c:a",
"libmp3lame",
"-q:a",
"2",
absOut,
],
{ encoding: "utf8" },
);
if (ff.status !== 0 || !existsSync(absOut))
return { looped: false, short: true, dur, reason: "ffmpeg unavailable" };
return { looped: true, rel: relOut, from: dur };
}
const hyperframesDir = resolve(flag("hyperframes", "."));
const storyboardPath = resolve(flag("storyboard", join(hyperframesDir, "STORYBOARD.md")));
const audioMetaPath = resolve(flag("audio-meta", join(hyperframesDir, "audio_meta.json")));
const outPath = resolve(flag("out", join(hyperframesDir, "index.html")));
const r3 = (x) => Math.round(x * 1000) / 1000;
const anomalies = [];
const frameErrors = []; // fatal per-frame composition violations (guards ②/③) — reported together
const repairs = []; // auto-repairs applied to frame files in place (guard ①)
// ---------- parse storyboard ----------
if (!existsSync(storyboardPath)) die(`STORYBOARD.md not found at ${storyboardPath}`);
const manifest = parseStoryboard(readFileSync(storyboardPath, "utf8"));
const { width: WIDTH, height: HEIGHT } = parseFormat(manifest.globals.format);
// ---------- per-frame composition guards (see header ①②③) ----------
// String-level checks on each frame's HTML — no DOM parse, deterministic, run in
// the same pass that already reads the file. OPEN_TAG matches one opening tag while
// tolerating quoted attribute values that contain ">" (e.g. inline styles).
const OPEN_TAG = "<([a-zA-Z][a-zA-Z0-9-]*)((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>";
const attrPresent = (attrs, name) => new RegExp(`(?:^|\\s)${name}(?:[\\s=]|$)`).test(attrs);
const attrValue = (attrs, name) => {
const m = attrs.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`));
return m ? (m[1] ?? m[2]) : null;
};
// The root (or a nested-comp mount) legitimately carries timing without class="clip".
const isRootish = (attrs) =>
/(?:^|\s)id\s*=\s*["']root["']/.test(attrs) ||
attrPresent(attrs, "data-composition-id") ||
attrPresent(attrs, "data-composition-src");
// Locate the composition root opening tag: prefer id="root", else the first element
// carrying data-composition-id. Returns { start, end, full, attrs } or null.
function findRootTag(html) {
const re = new RegExp(OPEN_TAG, "g");
let m;
let firstCompId = null;
while ((m = re.exec(html))) {
const attrs = m[2];
if (/(?:^|\s)id\s*=\s*["']root["']/.test(attrs))
return { start: m.index, end: m.index + m[0].length, full: m[0], attrs };
if (attrPresent(attrs, "data-composition-id") && !firstCompId)
firstCompId = { start: m.index, end: m.index + m[0].length, full: m[0], attrs };
}
return firstCompId;
}
// Returns { errors: string[], repairedHtml: string|null, repairNote: string|null }.
function guardFrame(html, label) {
const errors = [];
// Scan a copy with comments +
${body.join("\n")}