// `umtool modules` and `umtool preset` (release 39, the video modules): the // module registry, a project's module-config.json applied, and the look // presets -- from a terminal, through the same writers the app uses. // // umtool modules list [--json] every module: id, kind, slot, where its settings live // umtool modules apply [--config F] [--dry-run] [--json] // module-config.json onto the project's manifest // umtool modules apply [--config F] --take [--label L] [--at S --dur S | --full] // [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out F] // … as a take's patch instead: the project is not touched // umtool preset list [--json] // umtool preset show [--json] // umtool preset save --from [--description D] [--force] // umtool preset apply the cut stands on the preset (`preset`); `none` removes it import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { MODULES } from "umtool-report-to-video/modules"; import { moduleConfigToManifest } from "umtool-report-to-video/modules/config-loader"; import { storyClipErrors } from "umtool-report-to-video/modules/story-settings"; import { validateIntroSettings } from "umtool-report-to-video/modules/intro"; import { listPresets, loadPreset, presetFromManifest, presetsDir, resolvePresetLayers, PRESET_NAME_RE } from "umtool-report-to-video/presets"; import { validateChrome } from "umtool-report-to-video/deck"; import { validateClaims } from "umtool-report-to-video/factcheck"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { manifestToken, replaceManifest, updatePreset } from "./manifest.mjs"; export const MODULES_USAGE = [ "usage: umtool modules list [--json]", " umtool modules apply [--config FILE] [--dry-run] [--json]", " umtool modules apply [--config FILE] --take [--label L] [--at S --dur S | --full]", " [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]", "", "apply reads the project's module-config.json (or --config): the modules a video wants, in the", "design's vocabulary, mapped into the manifest's homes (modules/config-loader.mjs) -- the preset, the", "deck's subtitle, QR, counter series and rail markers, each clip's marks, the stamps, the chapters, the", "pairs, the status ledger, the intro and the finale. Everything with no home is listed, with its path.", "Without --take the project's manifest is rewritten (a snapshot first; Undo last edit takes it back);", "with --take the mapping is that take's patch (written to takes/.modules-patch.json, or --patch-out)", "and the take is made from it as `umtool take` makes one -- the project's manifest is not touched.", ].join("\n"); export const PRESET_USAGE = [ "usage: umtool preset list [--json]", " umtool preset show [--json]", " umtool preset save --from [--description D] [--force]", " umtool preset apply [--replace] [--json]", "", "A look preset (umtool/presets/.json) is a render block a manifest stands on: `\"preset\": \"\"`", "at the manifest's top level lays it UNDER the manifest -- preset → manifest → style → take patch, each", "a JSON merge patch over the one before. save keeps a project's look and leaves its content out (its", "claim checks, markers, counter series, finale stats, the story modules' lists); apply names the preset", "on the cut (nothing of it is copied in), refused when the cut over it would not build. --replace also CLEARS", "the manifest's own value of every key the preset sets (an undo point first, revisions/…-auto-before-preset-replace),", "so the preset's renders. Built in: plain-deck, huck-deck, ember-deck, archive-catalog, basic (the footage alone).", ].join("\n"); class CliError extends Error {} function parse(args, valued) { const flags = {}; const positional = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a.startsWith("--")) { if (valued.includes(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); (flags[a] ??= []).push(args[++i]); } else (flags[a] ??= []).push(""); } else positional.push(a); } return { flags, positional, one: (n) => flags[n]?.[flags[n].length - 1], has: (n) => n in flags }; } async function pickProject(arg, root) { if (!arg) throw new CliError("which project? pass an id, a name, or a directory"); const r = await resolveProject(arg, root); if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${arg}"`); return r.project; } const readJson = async (file, what) => { try { return JSON.parse(await readFile(file, "utf8")); } catch (e) { throw new CliError(`${what} ${file}: ${e instanceof Error ? e.message : e}`); } }; /** Every reason the manifest a module config makes would not build (the writers' and the build's checks). */ export function appliedProblems(manifest) { const seen = resolvePresetLayers(manifest); const { chrome, ...rest } = seen.render ?? {}; return [ ...(chrome !== undefined && chrome !== null ? validateChrome(chrome, rest) : []), ...storyClipErrors(seen), ...validateClaims(seen), ...(seen.render?.intro !== undefined ? validateIntroSettings(seen.render.intro) : []), ]; } /** * `umtool modules …` * @param {string[]} args everything after `modules` * @returns {Promise} */ export async function modulesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, take = null } = {}) { try { const p = parse(args, ["--config", "--take", "--label", "--at", "--dur", "--from", "--patch-out", "--group"]); const [sub, projectArg] = p.positional; const json = p.has("--json"); if (!sub || p.has("--help")) { log(MODULES_USAGE); return sub ? 0 : 2; } if (sub === "list") { const rows = MODULES.map((m) => ({ id: m.id, title: m.title, kind: m.kind, slot: m.slot, z: m.z, configKey: m.configKey ?? null, ...(m.host ? { host: m.host } : {}), ui: Array.isArray(m.ui), preview: typeof m.preview === "function", })); if (json) log(JSON.stringify(rows, null, 2)); else for (const r of rows) log(`${r.id.padEnd(12)} ${r.kind.padEnd(15)} ${r.slot.padEnd(8)} z${String(r.z).padEnd(4)} ${r.configKey ?? "—"}`); return 0; } if (sub !== "apply") throw new CliError(`unknown modules command "${sub}" — list or apply`); const project = await pickProject(projectArg, reportsRoot); const configFile = path.resolve(p.one("--config") ?? path.join(project.dir, "module-config.json")); const config = await readJson(configFile, "--config"); const manifestPath = path.join(project.dir, "video.manifest.json"); const manifest = await readJson(manifestPath, "the manifest"); const token = await manifestToken(project.dir); const { patch, unmapped, notes } = moduleConfigToManifest(config, manifest); if (typeof patch.preset === "string") { try { loadPreset(patch.preset); } catch (e) { throw new CliError(`the config's preset: ${e instanceof Error ? e.message : e}`); } } const next = mergePatch(manifest, patch); const problems = appliedProblems(next); const takeId = p.one("--take"); const report = { project: project.id, config: configFile, take: takeId ?? null, patch, unmapped, notes, problems }; const say = () => { if (json) return log(JSON.stringify(report, null, 2)); log(`${project.id}: ${Object.keys(patch).length ? `sets ${describe(patch)}` : "nothing to set"}`); if (unmapped.length) log(`not mapped (${unmapped.length}):\n ${unmapped.join("\n ")}`); if (notes.length) log(`notes:\n ${notes.join("\n ")}`); if (problems.length) log(`refused -- the cut would not build:\n ${problems.join("\n ")}`); }; if (problems.length) { say(); return 1; } if (p.has("--dry-run")) { say(); return 0; } if (!takeId) { const r = await replaceManifest(project.dir, next, { token, op: "modules" }); report.token = r.token; say(); if (!json) log(`written: ${manifestPath} (snapshot ${r.snapshot?.id ?? r.snapshot?.file ?? "taken"})`); return 0; } const patchFile = path.resolve(p.one("--patch-out") ?? path.join(project.dir, "takes", `${takeId}.modules-patch.json`)); await mkdir(path.dirname(patchFile), { recursive: true }); await writeFile(patchFile, JSON.stringify(patch, null, 2) + "\n", "utf8"); say(); if (!json) log(`the take's patch: ${patchFile}`); const pass = ["--at", "--dur", "--from", "--group"].flatMap((f) => (p.has(f) ? [f, p.one(f)] : [])); const bare = ["--full", "--quick", "--force", "--keep-frames"].filter((f) => p.has(f)); const takeArgs = [project.dir, "--id", takeId, "--label", p.one("--label") ?? `modules (${path.basename(configFile)})`, "--patch", patchFile, ...pass, ...bare]; const run = take ?? (await import("./takeCli.mjs")).takeCommand; return await run(takeArgs, { reportsRoot, log, err }); } catch (e) { if (e instanceof CliError) { err(e.message); return 2; } err(e instanceof Error ? e.message : String(e)); return 1; } } /** A patch's top-level homes, in words. */ function describe(patch) { const parts = []; if (patch.preset) parts.push(`preset ${patch.preset}`); const c = patch.render?.chrome ?? {}; for (const k of Object.keys(c)) { if (k === "deck") parts.push(`deck.{${Object.keys(c.deck).join(", ")}}`); else parts.push(`chrome.${k}`); } if (patch.render?.intro) parts.push("intro"); if (patch.timeline) parts.push("the timeline's marks and finale run"); return parts.join(", "); } /** * `umtool preset …` * @param {string[]} args everything after `preset` * @returns {Promise} */ export async function presetCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) { try { const p = parse(args, ["--from", "--description"]); const [sub, a, b] = p.positional; const json = p.has("--json"); if (!sub || p.has("--help")) { log(PRESET_USAGE); return sub ? 0 : 2; } if (sub === "list") { const rows = listPresets(); if (json) log(JSON.stringify(rows, null, 2)); else if (!rows.length) log(`no presets in ${presetsDir()}`); else for (const r of rows) log(`${r.name.padEnd(18)} ${r.error ? `(unreadable: ${r.error})` : r.description}`); return 0; } if (sub === "show") { if (!a) throw new CliError("which preset?"); const doc = loadPreset(a); log(json ? JSON.stringify(doc, null, 2) : `${doc.name}: ${doc.description ?? ""}\n${JSON.stringify(doc.render, null, 2)}`); return 0; } if (sub === "save") { if (!a || !PRESET_NAME_RE.test(a)) throw new CliError("preset save : lower-case letters, digits and dashes"); if (!p.has("--from")) throw new CliError("preset save --from "); const project = await pickProject(p.one("--from"), reportsRoot); const manifest = await readJson(path.join(project.dir, "video.manifest.json"), "the manifest"); const file = path.join(presetsDir(), `${a}.json`); const exists = await readFile(file, "utf8").then(() => true, () => false); if (exists && !p.has("--force")) throw new CliError(`${file} exists — pass --force to replace it`); const { preset, dropped } = presetFromManifest(manifest, { name: a, description: p.one("--description") ?? `The look of ${project.id}.`, from: project.id }); await mkdir(presetsDir(), { recursive: true }); await writeFile(file, JSON.stringify(preset, null, 2) + "\n", "utf8"); if (json) log(JSON.stringify({ file, preset, dropped }, null, 2)); else { log(`saved ${file} (${Object.keys(preset.render).length} render keys, from ${project.id})`); if (dropped.length) log(`left out (the cut's content, not its look):\n ${dropped.join("\n ")}`); } return 0; } if (sub === "apply") { if (!a || !b) throw new CliError("preset apply "); const project = await pickProject(b, reportsRoot); const replace = p.has("--replace"); if (replace && a === "none") throw new CliError("--replace clears the keys a preset sets: name one, not none"); const r = await updatePreset(project.dir, a === "none" ? null : a, { replace }); if (json) log(JSON.stringify({ project: project.id, ...r }, null, 2)); else { log(r.preset ? `${project.id} stands on the preset ${r.preset}` : `${project.id} stands on no preset`); if (replace) { log(r.cleared?.length ? `cleared the manifest's own ${r.cleared.join(", ")} (the preset's renders)` : "the manifest set none of the preset's keys: nothing cleared"); if (r.snapshot?.rel) log(`undo point: ${r.snapshot.rel}`); } } return 0; } throw new CliError(`unknown preset command "${sub}" — list, show, save or apply`); } catch (e) { if (e instanceof CliError) { err(e.message); return 2; } err(e instanceof Error ? (e.errors ? `${e.message}` : e.message) : String(e)); return 1; } }