// LOOK PRESETS (release 39, the video modules): a named render block a // manifest stands on. `"preset": ""` at the manifest's top level (the // key `render.preset` is the x264 encoder preset, and stays that) names a // file `umtool/presets/.json` -- `{ name, description, render }` -- // whose `render` is the BASE LAYER under the manifest's own: // // preset → manifest → style → take patch // // each applied over the one before as an RFC 7386 merge patch (mergePatch). // So a manifest names only what it changes from its preset, a take's style // and patch change it again, and a `null` anywhere above removes the key it // names from everything below -- the preset's value included. // // Resolved at the one door every reader of a cut goes through (build-video // `selectVariant`) and where a take merges its patches (takeMaker // `makeTake`, takeManifest `resolveTakeManifest`). A resolved manifest // carries `presetApplied: ` and no `preset`, so it is never laid twice. // // THE OUTPUT MODE (`render.mode`, common lib/report/look.mjs) is a render key // like any other, so it resolves here with the rest: the mode a reader sees is // the last layer's, and a "basic" anywhere above wins whatever chrome a lower // layer lays -- selectVariant then lays no brand and no intro, and the build // hands the cut to the basic renderer (basic.mjs). The built-in `basic` // preset is that one key. // // The presets directory is `UMTOOL_PRESETS_DIR` when set (the e2e suite's), // else umtool/presets beside this package. Read synchronously: a preset is a // small file, read where a manifest is (and cached by mtime). import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { mergePatch } from "./montage-styles.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); /** The directory the presets are read from (and `umtool preset save` writes to). */ export const presetsDir = () => process.env.UMTOOL_PRESETS_DIR || path.resolve(/* turbopackIgnore: true */ HERE, "..", "presets"); export const PRESET_NAME_RE = /^[a-z][a-z0-9-]{0,47}$/; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const cache = new Map(); /** Every reason a preset document is not one. */ export function presetErrors(doc, name = doc?.name) { const errors = []; if (!isObj(doc)) return ["a preset is { name, description?, render }"]; for (const k of Object.keys(doc)) if (!["name", "description", "render", "from"].includes(k)) errors.push(`preset.${k} is not a preset key (name, description, render, from)`); if (typeof doc.name !== "string" || !PRESET_NAME_RE.test(doc.name)) errors.push("preset.name must be lower-case letters, digits and dashes"); if (name !== undefined && doc.name !== name) errors.push(`preset.name "${doc.name}" is not its file's name "${name}"`); if (!isObj(doc.render)) errors.push("preset.render must be an object (the render block it lays under a manifest)"); if (isObj(doc.render) && "chrome" in doc.render && doc.render.chrome !== undefined && !isObj(doc.render.chrome)) errors.push("preset.render.chrome must be an object"); return errors; } /** The preset by name: `{ name, description, render }`. Throws a sentence naming the presets on an unknown one. */ export function loadPreset(name, { dir = presetsDir() } = {}) { if (typeof name !== "string" || !PRESET_NAME_RE.test(name)) throw new Error(`"${name}" is not a preset name (lower-case letters, digits and dashes)`); const file = path.join(/* turbopackIgnore: true */ dir, `${name}.json`); let st; try { st = statSync(/* turbopackIgnore: true */ file); } catch { const known = presetNames({ dir }); throw new Error(`no preset "${name}"${known.length ? ` — one of ${known.join(", ")}` : ` (no presets in ${dir})`}`); } const hit = cache.get(file); if (hit && hit.mtime === st.mtimeMs) return structuredClone(hit.doc); const doc = JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8")); const errors = presetErrors(doc, name); if (errors.length) throw new Error(`preset ${name}: ${errors.join("; ")}`); cache.set(file, { mtime: st.mtimeMs, doc }); return structuredClone(doc); } /** The presets on disk, by name. */ export function presetNames({ dir = presetsDir() } = {}) { if (!existsSync(/* turbopackIgnore: true */ dir)) return []; return readdirSync(/* turbopackIgnore: true */ dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).filter((n) => PRESET_NAME_RE.test(n)).sort(); } /** Every preset: `{ name, description }`, by name; an unreadable one with its `error`. */ export function listPresets({ dir = presetsDir() } = {}) { return presetNames({ dir }).map((name) => { try { const p = loadPreset(name, { dir }); return { name, description: p.description ?? "", keys: Object.keys(p.render).sort(), ...(p.from ? { from: p.from } : {}) }; } catch (e) { return { name, description: "", error: String(e?.message ?? e) }; } }); } /** * The manifest a reader sees: the preset `manifest.preset` (or the last of * `patches` that names one) under the manifest, then each patch over it. * Without a preset, `patches` over the manifest -- exactly what makeTake * always did. Returns a new object. * * @param {Record} manifest * @param {Array | null | undefined>} [patches] * @returns {Record} */ export function resolvePresetLayers(manifest, patches = [], opts = {}) { const layers = patches.filter(Boolean); const merged = layers.reduce((m, p) => mergePatch(m, p), manifest); const name = merged?.preset; if (name === undefined || name === null || name === "") return merged; const preset = loadPreset(name, opts); const out = [manifest, ...layers].reduce((m, p) => mergePatch(m, p), { render: preset.render }); delete out.preset; out.presetApplied = name; return out; } /** selectVariant's step: a manifest naming a preset, laid on it; any other as it is. */ export function presetManifest(manifest) { return manifest && typeof manifest.preset === "string" && manifest.preset ? resolvePresetLayers(manifest) : manifest; } // --------------------------------------------------------------------------- // Saving a preset from a project: its LOOK, never its content. // --------------------------------------------------------------------------- /** The render keys a preset keeps: the look (sizes, faces, palette, pacing, encode, QR, intro, the deck's settings). */ export const PRESET_RENDER_KEYS = Object.freeze([ "width", "height", "fps", "audioRate", "audioChannels", "maxHeightSource", "fontRegular", "fontBold", "palette", "transition", "transitionStyle", "fetchPad", "snapWindow", "silenceMinDur", "silenceRelDb", "snapLead", "snapTail", "lockedEdges", "footerHeight", "headerHeight", "slideSeconds", "crf", "preset", "audioBitrate", "qr", "endFade", "loudness", "captions", "intro", "chrome", "brand", "mode", "basic", ]); /** * The chrome keys that are a cut's CONTENT, not its look: left out of a * saved preset (a deck's claim checks, markers, counter series, the finale's * stats, a thread list, the story modules' lists). */ const CONTENT = { deck: ["claims", "markers", "counter"], "deck.finale": ["stats", "statsTitle"], // The verdicts' relabels and the tally's settings are the counter's // (migrate.mjs): they travel with a cut's series, and a counter beside // them is refused. factcheck: ["verdicts", "tally"], pair: ["pairs"], chapter: ["list"], status: ["items"], }; /** * A preset document from a manifest (`umtool preset save`): its look keys, * its chrome less the cut's content, its preset (when it names one) laid * under it. `dropped` names every content key left out. * * @returns {{ preset: { name: string, description: string, render: Record, from?: string }, dropped: string[] }} */ export function presetFromManifest(manifest, { name, description = "", from = null } = {}) { if (!PRESET_NAME_RE.test(String(name))) throw new Error(`"${name}" is not a preset name (lower-case letters, digits and dashes)`); const m = presetManifest(manifest); const r = isObj(m?.render) ? m.render : {}; const render = {}; const dropped = []; for (const k of PRESET_RENDER_KEYS) if (r[k] !== undefined) render[k] = structuredClone(r[k]); for (const k of Object.keys(r)) if (!PRESET_RENDER_KEYS.includes(k)) dropped.push(`render.${k}`); const chrome = render.chrome; if (isObj(chrome)) { for (const k of ["threads", "flips", "stats", "fx"]) { if (chrome[k] !== undefined) { dropped.push(`render.chrome.${k}`); delete chrome[k]; } } for (const [where, keys] of Object.entries(CONTENT)) { const obj = where.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), chrome); if (!isObj(obj)) continue; for (const k of keys) if (obj[k] !== undefined) { dropped.push(`render.chrome.${where}.${k}`); delete obj[k]; } } for (const k of ["pair", "chapter", "status"]) if (isObj(chrome[k]) && !Object.keys(chrome[k]).length) delete chrome[k]; if (isObj(chrome.deck?.finale) && !Object.keys(chrome.deck.finale).length) delete chrome.deck.finale; } if (isObj(render.intro)) { // The site an intro names is the cut's; "auto" (the manifest's own) travels. if (render.intro.site !== undefined && render.intro.site !== "auto") { dropped.push("render.intro.site"); delete render.intro.site; } } return { preset: { name, description, render, ...(from ? { from } : {}) }, dropped }; }