// DRAFTED FIELDS — THE one copy of where a generated manifest field says it was // drafted, the one writer every draft task goes through, and the rules that // keep an operator's words from being overwritten (release 28, M0). // // Plain JS (with JSDoc types, and ./drafted.d.mts for TypeScript) for the // reason ./verdicts.mjs is: umtool's report-to-video scripts and its manifest // writer are `.mjs` run by bare `node`, and the common tasks are TypeScript; // both read and write the same marks. // // WHERE THE MARK LIVES. A provenance is `{ task, model, at, iteration?, attempt }` // (`at` ISO; `attempt` 1 or 2, the one kept). An ENTRY's field carries it on the // entry, keyed by field — `entry.drafted = { onscreen, narration, lines }` (any // entry's on-screen text, a card's narration, a teaser's lines). A MANIFEST // field carries it in a top-level map keyed by path — `manifest.drafted = // { "timeline", "render.chrome.flips", "render.chrome.threads", // "publish.youtube", "publish.x", "publish.bluesky" }` ("timeline" is the cut's ORDER; "render.chrome.threads" // covers each clip's `thread` key too). Nowhere else. // // WHO OWNS A FIELD. Empty: nobody (a draft may fill it). Non-empty with a mark: // the task that drafted it (a forced re-draft may replace it). Non-empty with // NO mark: the operator — written by hand, or edited since it was drafted — // and never replaced, forced or not (`applyDraft`). An edit through umtool's // manifest writer removes the mark (`clearEditedDrafts`), which is what makes // an edited field the operator's. // // A mark whose field is gone (an orphan) is dropped with a warning // (`pruneDrafted`); a mark that is malformed or in a place no field may be // drafted is refused (`validateDrafted`). import { createHash } from "node:crypto"; import { SOCIAL_PLATFORMS, validateSocialPost } from "./social.mjs"; /** The entry fields that may be drafted, and the entry types each is on (null: any). */ export const DRAFTED_ENTRY_FIELDS = Object.freeze({ onscreen: null, narration: Object.freeze(["card"]), lines: Object.freeze(["teaser"]), }); /** The manifest fields that may be drafted, by path. */ export const DRAFTED_MANIFEST_FIELDS = Object.freeze(["timeline", "render.chrome.flips", "render.chrome.threads", "publish.youtube", "publish.x", "publish.bluesky"]); /** * Each draftable field's own task: the one that drafts it, and the `` of * its review address (`reviewAddress`), whichever task drafted it this time — * so a field's review has ONE address. */ export const FIELD_TASKS = Object.freeze({ onscreen: "onscreen", narration: "narrate", lines: "teaser", timeline: "cut", "render.chrome.flips": "flips", "render.chrome.threads": "threads", "publish.youtube": "youtube", "publish.x": "social", "publish.bluesky": "social", }); /** The keys of a provenance, in the order they are written. */ export const PROVENANCE_KEYS = Object.freeze(["task", "model", "at", "iteration", "attempt"]); /** The keys `publish` may hold (release 29 G2 adds the social posts and the video's URL). */ export const PUBLISH_KEYS = Object.freeze(["youtube", "x", "bluesky", "videoUrl"]); /** `publish.youtube`'s limits: YouTube's own (a title of 100, a description of 5000). */ export const PUBLISH_YOUTUBE_LIMITS = Object.freeze({ title: 100, description: 5000 }); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); /** @param {string} field */ export const isEntryField = (field) => Object.prototype.hasOwnProperty.call(DRAFTED_ENTRY_FIELDS, field); /** @param {string} field */ export const isManifestField = (field) => DRAFTED_MANIFEST_FIELDS.includes(field); /** * Every reason `v` is not a provenance, naming `where` (empty: it is one). * * @param {unknown} v * @param {string} where * @returns {string[]} */ export function provenanceProblems(v, where) { if (!isObj(v)) return [`${where} must be { task, model, at, iteration?, attempt }`]; const errors = []; for (const k of Object.keys(v)) if (!PROVENANCE_KEYS.includes(k)) errors.push(`${where}.${k} is not a provenance key (${PROVENANCE_KEYS.join(", ")})`); const word = (k, max) => { if (typeof v[k] !== "string" || !v[k].trim()) errors.push(`${where}.${k} must be a name`); else if (v[k].length > max || /[\r\n]/.test(v[k])) errors.push(`${where}.${k} must be one line of at most ${max} characters`); }; word("task", 64); word("model", 200); if (typeof v.at !== "string" || Number.isNaN(Date.parse(v.at))) errors.push(`${where}.at must be an ISO date and time`); if (v.iteration !== undefined && !(Number.isInteger(v.iteration) && v.iteration > 0)) errors.push(`${where}.iteration must be a positive whole number`); if (v.attempt !== 1 && v.attempt !== 2) errors.push(`${where}.attempt must be 1 or 2 (the attempt kept)`); return errors; } /** * A provenance, its keys in order. `at` defaults to now. * * @param {{ task: string, model: string, at?: Date | string, iteration?: number, attempt?: number }} p */ export function makeProvenance({ task, model, at = new Date(), iteration, attempt = 1 }) { return { task, model, at: typeof at === "string" ? at : at.toISOString(), ...(iteration !== undefined && iteration !== null ? { iteration } : {}), attempt, }; } /** * A mark a CODE path made (`model: "code"`): the converter's timeline * (release 28 M1). It says who made the field so a task may redraft it, and * it needs no review — the drafts review and the final gate leave it out. * * @param {unknown} p */ export const isCodeDraft = (p) => isObj(p) && p.model === "code"; /** Every timeline entry with this id (a cut's `variant` twins share one). */ export function entriesWithId(manifest, id) { return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.id === id); } const pathParts = (field) => field.split("."); function readPath(obj, field) { let cur = obj; for (const p of pathParts(field)) { if (!isObj(cur)) return undefined; cur = cur[p]; } return cur; } /** * A field's value: an entry's (`target.entry` an id; the first entry with it) * or the manifest's (`target.entry` absent). "timeline" is the timeline itself. * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target */ export function readField(manifest, { entry = null, field }) { if (entry !== null && entry !== undefined) return entriesWithId(manifest, entry)[0]?.[field]; return readPath(manifest, field); } /** * Is this value of this field empty -- nothing a person wrote? A narration with * no words, an on-screen block with no text, a list with nothing in it. * * @param {string} field * @param {unknown} v */ export function isEmptyField(field, v) { if (v === undefined || v === null || v === "") return true; if (field === "narration") return !(isObj(v) && typeof v.text === "string" && v.text.trim()); if (field === "onscreen") return !(isObj(v) && ["title", "subtitle"].some((k) => typeof v[k] === "string" && v[k].trim())); if (field === "render.chrome.flips") return !(isObj(v) && Array.isArray(v.pairs) && v.pairs.length); if (field === "render.chrome.threads") return !(isObj(v) && Array.isArray(v.list) && v.list.length); if (field === "publish.youtube") return !(isObj(v) && ["title", "description"].some((k) => typeof v[k] === "string" && v[k].trim())); if (field === "publish.x" || field === "publish.bluesky") return !(isObj(v) && typeof v.post === "string" && v.post.trim()); if (Array.isArray(v)) return v.length === 0; if (isObj(v)) return Object.keys(v).length === 0; return false; } /** * A field's drafted mark, or null. * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target */ export function draftedOf(manifest, { entry = null, field }) { if (entry !== null && entry !== undefined) { const e = entriesWithId(manifest, entry)[0]; const p = isObj(e?.drafted) ? e.drafted[field] : undefined; return isObj(p) ? p : null; } const p = isObj(manifest?.drafted) ? manifest.drafted[field] : undefined; return isObj(p) ? p : null; } /** * Who a field belongs to now: "empty", "drafted" or "operator". * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target * @returns {"empty" | "drafted" | "operator"} */ export function ownerOf(manifest, target) { if (isEmptyField(target.field, readField(manifest, target))) return "empty"; return draftedOf(manifest, target) ? "drafted" : "operator"; } function assertTarget({ entry = null, field }) { const onEntry = entry !== null && entry !== undefined; if (onEntry && !isEntryField(field)) throw new Error(`${field} is not a field an entry's draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`); if (!onEntry && !isManifestField(field)) throw new Error(`${field} is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")})`); } function setMark(manifest, { entry = null, field }, provenance) { if (entry !== null && entry !== undefined) { for (const e of entriesWithId(manifest, entry)) e.drafted = { ...(isObj(e.drafted) ? e.drafted : {}), [field]: { ...provenance } }; } else { manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), [field]: { ...provenance } }; } } /** * THE writer every draft task uses. Sets the field to `value` and marks it * drafted -- unless the field is the operator's (non-empty, no mark), which is * never replaced, `force` or not; or is a draft already and `force` is not set. * The caller keeps a refused value as an alternative (`-draft.json`). * Mutates `manifest`. * * applied: true * applied: false, reason "operator" a field somebody wrote or edited * applied: false, reason "drafted" a draft already, and no `force` * applied: false, reason "missing" no entry with that id, or (flips, * threads) no `render.chrome` to hold it * * An entry id names every entry with it (variant twins). "timeline" takes the * new timeline array; "render.chrome.threads" takes `{ list }` (the task sets * each clip's `thread` key itself once applied). * * @param {any} manifest * @param {{ entry?: string | null, field: string, value: unknown, provenance: Record, force?: boolean }} o * @returns {{ applied: true } | { applied: false, reason: "operator" | "drafted" | "missing" }} */ export function applyDraft(manifest, { entry = null, field, value, provenance, force = false }) { const target = { entry, field }; assertTarget(target); const bad = provenanceProblems(provenance, "provenance"); if (bad.length) throw new Error(bad.join("; ")); const onEntry = entry !== null && entry !== undefined; if (onEntry) { const es = entriesWithId(manifest, entry); if (!es.length) return { applied: false, reason: "missing" }; const types = DRAFTED_ENTRY_FIELDS[field]; if (types && !es.every((e) => types.includes(e.type))) throw new Error(`${entry} is a ${es[0].type}: ${field} is drafted only on a ${types.join(" or ")}`); } else if (field.startsWith("render.chrome.") && !isObj(manifest?.render?.chrome)) { return { applied: false, reason: "missing" }; } const owner = ownerOf(manifest, target); if (owner === "operator") return { applied: false, reason: "operator" }; if (owner === "drafted" && !force) return { applied: false, reason: "drafted" }; const copy = () => (value === undefined ? undefined : JSON.parse(JSON.stringify(value))); if (onEntry) { for (const e of entriesWithId(manifest, entry)) e[field] = copy(); } else if (field === "timeline") { manifest.timeline = copy(); } else { const parts = pathParts(field); let cur = manifest; for (const p of parts.slice(0, -1)) { if (!isObj(cur[p])) cur[p] = {}; cur = cur[p]; } cur[parts.at(-1)] = copy(); } setMark(manifest, target, provenance); return { applied: true }; } /** * Remove a field's drafted mark (the operator's edit). True when there was one. * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target */ export function clearDrafted(manifest, { entry = null, field }) { let had = false; if (entry !== null && entry !== undefined) { for (const e of entriesWithId(manifest, entry)) { if (!isObj(e.drafted) || !(field in e.drafted)) continue; had = true; delete e.drafted[field]; if (!Object.keys(e.drafted).length) delete e.drafted; } return had; } if (isObj(manifest?.drafted) && field in manifest.drafted) { had = true; delete manifest.drafted[field]; if (!Object.keys(manifest.drafted).length) delete manifest.drafted; } return had; } /** JSON with every object's keys sorted: one text per value, whatever order it was built in. */ export function stableStringify(v) { if (Array.isArray(v)) return `[${v.map((x) => (x === undefined ? "null" : stableStringify(x))).join(",")}]`; if (isObj(v)) { return `{${Object.keys(v) .filter((k) => v[k] !== undefined) .sort() .map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`) .join(",")}}`; } return JSON.stringify(v ?? null); } /** * What a field IS, for telling an edit from no edit and for a review's key: the * value -- except "timeline", whose draft is the ORDER (the entries' ids), and * "render.chrome.threads", which is the list and every clip's `thread` key. * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target */ export function fieldSignature(manifest, target) { if ((target.entry === null || target.entry === undefined) && target.field === "timeline") { return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).map((e) => e?.id ?? null); } if ((target.entry === null || target.entry === undefined) && target.field === "render.chrome.threads") { const clips = {}; for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && e.thread !== undefined) clips[e.id] = e.thread; return { threads: readField(manifest, target) ?? null, clips }; } return readField(manifest, target) ?? null; } /** A value's content key: sha256 of its stable JSON, hex. */ export function valueKey(v) { return createHash("sha256").update(stableStringify(v)).digest("hex"); } /** * A field's content key (`fieldSignature` hashed). A review's verdict is on * this key, so an edit or a re-draft leaves it unapproved. (A card's narration * is keyed by umtool's `narrationKey` instead -- the words and the voice -- * report-to-video/drafts-review.mjs.) */ export function fieldKey(manifest, target) { return valueKey(fieldSignature(manifest, target)); } /** * Every drafted field of a manifest, in timeline order then the manifest's: * `{ entry, field, provenance, value }`. An entry id is listed once (variant * twins share a field). Orphans (a mark on an empty field) are left out. * * @param {any} manifest * @returns {{ entry: string | null, field: string, provenance: Record, value: unknown }[]} */ export function draftedFields(manifest) { const out = []; const seen = new Set(); for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (!isObj(e) || !isObj(e.drafted)) continue; for (const [field, p] of Object.entries(e.drafted)) { const k = `${e.id}\u0000${field}`; if (seen.has(k) || !isEntryField(field) || !isObj(p) || isEmptyField(field, e[field])) continue; seen.add(k); out.push({ entry: e.id, field, provenance: p, value: e[field] }); } } if (isObj(manifest?.drafted)) { for (const field of DRAFTED_MANIFEST_FIELDS) { const p = manifest.drafted[field]; const value = readField(manifest, { field }); if (!isObj(p) || isEmptyField(field, value)) continue; out.push({ entry: null, field, provenance: p, value }); } } return out; } /** The review address of a field: `//`. */ export function reviewAddress({ entry = null, field }) { const task = FIELD_TASKS[field] ?? "draft"; return `${task}/${entry === null || entry === undefined ? "*" : entry}/${field}`; } /** An address back to its parts, or null. */ export function parseReviewAddress(address) { if (typeof address !== "string") return null; const m = /^([A-Za-z0-9_-]{1,64})\/([^/]{1,200})\/([A-Za-z0-9_.-]{1,64})$/.exec(address); if (!m) return null; const [, task, entry, field] = m; return { task, entry: entry === "*" ? null : entry, field }; } /** * The marks whose field is gone or empty (or whose key is not a field at * all), as `{ where, entry, field }`. Read-only: `pruneDrafted` drops them. * * @param {any} manifest */ export function orphanDrafts(manifest) { const out = []; (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => { if (!isObj(e) || !isObj(e.drafted)) return; for (const field of Object.keys(e.drafted)) { if (isEntryField(field) && isEmptyField(field, e[field])) out.push({ where: `timeline[${i}] (${e.id}).drafted.${field}`, entry: e.id, field }); } }); if (isObj(manifest?.drafted)) { for (const field of Object.keys(manifest.drafted)) { if (isManifestField(field) && isEmptyField(field, readField(manifest, { field }))) out.push({ where: `drafted["${field}"]`, entry: null, field }); } } return out; } /** * Drop every orphan mark (and a `drafted` map left empty). Mutates; returns a * sentence per mark dropped. * * @param {any} manifest * @returns {string[]} */ export function pruneDrafted(manifest) { const dropped = orphanDrafts(manifest); for (const o of dropped) { if (o.entry === null) clearDrafted(manifest, { field: o.field }); else { for (const e of Array.isArray(manifest.timeline) ? manifest.timeline : []) { if (!isObj(e) || e.id !== o.entry || !isObj(e.drafted) || !(o.field in e.drafted) || !isEmptyField(o.field, e[o.field])) continue; delete e.drafted[o.field]; if (!Object.keys(e.drafted).length) delete e.drafted; } } } for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && isObj(e.drafted) && !Object.keys(e.drafted).length) delete e.drafted; if (isObj(manifest?.drafted) && !Object.keys(manifest.drafted).length) delete manifest.drafted; return dropped.map((o) => `${o.where}: its field is gone, so the drafted mark is dropped`); } /** * The operator's write: every drafted field whose value differs between * `before` and `after` loses its mark in `after` (it is the operator's now), * and orphans are dropped. Mutates `after`; returns the fields cleared as * `{ entry, field }`. What umtool's manifest writer runs on every write. * * @param {any} before * @param {any} after */ export function clearEditedDrafts(before, after) { const cleared = []; for (const d of draftedFields(after)) { const t = { entry: d.entry, field: d.field }; // A mark that was not there before is the writer's own (a draft applied in // this write): leave it. if (!draftedOf(before, t)) continue; if (stableStringify(fieldSignature(before, t)) !== stableStringify(fieldSignature(after, t))) { clearDrafted(after, t); cleared.push(t); } } pruneDrafted(after); return cleared; } /** * Every reason the manifest's drafted marks cannot be built: a mark that is * not a provenance, or one in a place no field may be drafted (an unknown * field, `narration` on a clip, `lines` on a card, a `drafted` key under the * render block or `publish`). An orphan is NOT an error (`orphanDrafts`). * * @param {any} manifest * @returns {string[]} */ export function validateDrafted(manifest) { const errors = []; if (manifest?.drafted !== undefined) { if (!isObj(manifest.drafted)) errors.push("drafted must be an object of field path → provenance"); else { for (const [k, p] of Object.entries(manifest.drafted)) { if (!isManifestField(k)) { errors.push(`drafted["${k}"] is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")}; an entry's own fields are marked on the entry)`); continue; } errors.push(...provenanceProblems(p, `drafted["${k}"]`)); } } } (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => { if (!isObj(e)) return; for (const field of Object.keys(DRAFTED_ENTRY_FIELDS)) { if (isObj(e[field]) && "drafted" in e[field]) errors.push(`timeline[${i}] (${e.id}).${field}.drafted: the mark goes on the entry (drafted.${field}), not inside the field`); } if (e.drafted === undefined) return; const w = `timeline[${i}] (${e.id}).drafted`; if (!isObj(e.drafted)) { errors.push(`${w} must be an object of field → provenance`); return; } for (const [field, p] of Object.entries(e.drafted)) { if (!isEntryField(field)) { errors.push(`${w}.${field} is not an entry field a draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`); continue; } const types = DRAFTED_ENTRY_FIELDS[field]; if (types && !types.includes(e.type)) errors.push(`${w}.${field}: a ${e.type ?? "entry"} has no ${field} to draft (only a ${types.join(" or ")})`); errors.push(...provenanceProblems(p, `${w}.${field}`)); } }); if (isObj(manifest?.render) && "drafted" in manifest.render) errors.push("render.drafted: a manifest field's mark goes in the top-level drafted map"); if (isObj(manifest?.publish)) { if ("drafted" in manifest.publish) errors.push("publish.drafted: a manifest field's mark goes in the top-level drafted map"); for (const k of ["youtube", ...SOCIAL_PLATFORMS]) { if (isObj(manifest.publish[k]) && "drafted" in manifest.publish[k]) errors.push(`publish.${k}.drafted: the mark goes in the top-level drafted map`); } } return errors; } /** * `publish` (release 28; release 29 G2): what is published beside the video. * `publish.youtube { title, description }`, two strings (M6 fills it); its * problems, and a key `publish` does not know, are ERRORS (the build refuses, * as since release 28). `publish.x`, `publish.bluesky` `{ post, thread? }` and * `publish.videoUrl` are not the video's: their problems are WARNINGS * (`publishWarnings`), so a hand-edited post past its count never stops a * build or an edit of the cut (review fix, release 29). * * @param {any} manifest * @returns {string[]} */ export function validatePublish(manifest) { const p = manifest?.publish; if (p === undefined) return []; if (!isObj(p)) return ["publish must be an object ({ youtube, x, bluesky, videoUrl })"]; const errors = []; for (const k of Object.keys(p)) if (!PUBLISH_KEYS.includes(k) && k !== "drafted") errors.push(`publish.${k} is not a publish key (${PUBLISH_KEYS.join(", ")})`); const y = p.youtube; if (y === undefined) return errors; if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"]; for (const k of Object.keys(y)) if (k !== "title" && k !== "description" && k !== "drafted") errors.push(`publish.youtube.${k} is not a YouTube field (title, description)`); for (const k of ["title", "description"]) { if (typeof y[k] !== "string") { errors.push(`publish.youtube.${k} must be a string`); continue; } if (y[k].length > PUBLISH_YOUTUBE_LIMITS[k]) errors.push(`publish.youtube.${k} is ${y[k].length} characters (at most ${PUBLISH_YOUTUBE_LIMITS[k]})`); } if (typeof y.title === "string" && /[\r\n]/.test(y.title)) errors.push("publish.youtube.title must be one line"); return errors; } /** * The social posts' and the video URL's problems (release 29 G2), as * warnings: `publish.x` / `publish.bluesky` within their platform's count * (./social.mjs), `publish.videoUrl` an http(s) URL. `only` limits them to one * key (the field's own writer refuses on these). * * @param {any} manifest * @param {{ only?: "x" | "bluesky" | "videoUrl" }} [o] * @returns {string[]} */ export function publishWarnings(manifest, { only } = {}) { const p = manifest?.publish; if (!isObj(p)) return []; const out = []; if ((!only || only === "videoUrl") && p.videoUrl !== undefined && !(typeof p.videoUrl === "string" && /^https?:\/\/\S+$/i.test(p.videoUrl.trim()))) { out.push("publish.videoUrl must be the video's http(s) URL"); } for (const k of SOCIAL_PLATFORMS) { if (only && only !== k) continue; if (p[k] !== undefined) out.push(...validateSocialPost(k, p[k]).filter((e) => !e.endsWith(".drafted: the mark goes in the top-level drafted map"))); } return out; }