// The fit as an edit: the model is given one effect's own page and the words said in its seconds, and answers the edits // that make the page show them, or SKIP. What it made is then checked on screen by code, not by a list of rules. import { readFile } from "node:fs/promises"; import { Script } from "node:vm"; import { Refused } from "./refused.js"; import { defaultsOf } from "./defaults.js"; import { sampleTexts } from "./fit.js"; import { isObject, type Json, type JsonObject } from "./json.js"; import { pageTexts } from "./pageText.js"; import type { Placed } from "./plan.js"; import { phrases, type Word } from "./words.js"; import type { Work } from "./work.js"; export interface Edit { old: string; new: string; } /** Why an effect the model passed on is not shown: its seconds are filled as a gap. */ export const SKIPPED = "the words in its seconds do not carry it"; export const SKIP = "SKIP"; export const editFile = (id: string): string => `edit-${id}.html`; const seconds = (value: number) => String(Math.round(value * 100) / 100); /** The words of these seconds, one phrase a line, timed from the effect's start. */ export function wordsSaid(words: Word[], p: { start: number; end: number }): string { const inside = words.filter((w) => w.end > p.start && w.start < p.end); if (!inside.length) { const next = words.filter((w) => w.start >= p.end).slice(0, 14); return next.length ? `Nothing is said in these seconds. Said just after: ${next.map((w) => w.text).join(" ")}` : "Nothing is said in these seconds."; } return phrases(inside) .map((one) => `${seconds(Math.max(0, one.start - p.start))} s: ${one.text}`) .join("\n"); } export interface EditContext { words: string; face: string; frame: { width: number; height: number }; style: string | null; } /** The one goal, the facts of these seconds, and the page. */ function editAsk(p: Placed, context: EditContext, page: string): string { const length = seconds(p.end - p.start); return [ `This effect ("${p.effect.name}") plays from ${seconds(p.start)} to ${seconds(p.end)} s of the clip, ${length} s long; the file's timeline starts at 0 with it. The speaker says what is below in these seconds. Edit this file so it shows what they say: every word, every number and every picture on screen comes from these words (shortened if need be), none of the template's sample words, figures or pictures stays; a picture that does not fit what is said is replaced by a simple inline SVG icon drawn for it, or taken out when none can be drawn; all text stays inside its own box, and nothing covers the face. Any caption or subtitle bar the template carries for lines spoken is taken out: the video has its own captions. If the words of these seconds cannot carry this effect, answer only ${SKIP}.`, `Otherwise answer only a JSON list of edits, [{"old": "...", "new": "..."}], applied in order: each "old" copied exactly from the file and found there once. Change only what must change; do not rewrite the file.`, `What is said (seconds from the effect's start):\n${context.words}`, `The frame is ${context.frame.width}x${context.frame.height} px. ${context.face}`, context.style, `The file:\n${page}`, ] .filter(Boolean) .join("\n\n"); } /** The same goal once more, with what the check saw on screen and the page as the last edits left it. */ export function editAgainAsk(p: Placed, context: EditContext, page: string, wrong: string): string { return `${editAsk(p, context, page)}\n\nThis file is your last edit. Shown on screen, it is still wrong: ${wrong}. The picture is the frame as it plays. Answer the edits to this file that put it right.`; } /** The answer's edits, or SKIP; an answer of any other shape is refused. */ export function editsOf(given: Json): Edit[] | typeof SKIP { if (typeof given === "string" && /^\W*SKIP\W*$/i.test(given.trim())) return SKIP; // {"skip": true} or {"skip": "why"} is the same answer in JSON. if (isObject(given) && (given.skip === true || (typeof given.skip === "string" && given.skip))) return SKIP; if (isObject(given) && (given.done === true || given.ok === true)) return []; const list = Array.isArray(given) ? given : isObject(given) && Array.isArray(given.edits) ? given.edits : isObject(given) && Array.isArray(given.edit) ? given.edit : null; if (!list) throw new Refused(`answer a JSON list of {"old", "new"} edits, or ${SKIP}`); return editList(list); } const editList = (list: Json[]): Edit[] => list.map((one, k) => { if (!isObject(one) || typeof one.old !== "string" || typeof one.new !== "string") throw new Refused(`edit ${k + 1} is not {"old": "...", "new": "..."} with text in both`); return { old: one.old, new: one.new }; }); /** What a fit answers for one effect: values for its row and edits to its page, both optional. */ export interface FitAnswer { params: JsonObject | null; edits: Edit[]; } /** The answer as values and edits: {"params", "edits"}, {"edit": [...]}, a list of edits, {"done": true} or SKIP. */ export function answerOf(given: Json): FitAnswer | typeof SKIP { if (typeof given === "string" && /^\W*SKIP\W*$/i.test(given.trim())) return SKIP; if (Array.isArray(given)) return { params: null, edits: editList(given) }; if (!isObject(given)) throw new Refused(`answer {"params": {...}, "edits": [{"old", "new"}, ...]}, or ${SKIP}`); if (given.skip === true || (typeof given.skip === "string" && given.skip)) return SKIP; if (given.done === true || given.ok === true) return { params: null, edits: [] }; const hasParams = given.params !== undefined && given.params !== null; const list = given.edits ?? given.edit; if (!hasParams && list === undefined) throw new Refused( `answer {"params": {...}, "edits": [{"old", "new"}, ...]} with either or both, or ${SKIP}`, ); if (hasParams && !isObject(given.params)) throw new Refused(`"params" is an object of the effect's values by name`); if (list !== undefined && list !== null && !Array.isArray(list)) throw new Refused(`"edits" is a list of {"old": "...", "new": "..."}`); return { params: isObject(given.params) ? given.params : null, edits: Array.isArray(list) ? editList(list) : [], }; } const timesIn = (text: string, part: string) => { let count = 0; for (let at = text.indexOf(part); at >= 0 && count < 2; at = text.indexOf(part, at + 1)) count += 1; return count; }; /** The page with the edits made in order; an edit whose `old` is not there exactly once is refused, as it is. */ export function applied(page: string, edits: Edit[]): string { let out = page; for (const [k, edit] of edits.entries()) { const found = edit.old ? timesIn(out, edit.old) : 0; if (found !== 1) throw new Refused( `edit ${k + 1}: "old" ${found ? "is found more than once" : "is not in the file"}: ${JSON.stringify(edit.old.slice(0, 200))}. Copy a longer, exact piece of the file.`, ); out = out.replace(edit.old, () => edit.new); } return out; } const CLASSIC = /^(|text\/javascript|application\/javascript)$/; /** An inline classic script: no src, and no type or a JavaScript one; a module parses by other rules. */ const classicScript = (attrs: string): boolean => !/(?:^|\s)src\s*=/i.test(attrs) && CLASSIC.test(/(?:^|\s)type\s*=\s*["']?([^"'\s>]*)/i.exec(attrs)?.[1]?.toLowerCase() ?? ""); export function brokenScripts(page: string): string[] { const out: string[] = []; for (const m of page.matchAll(/]*)>([\s\S]*?)<\/script\b[^>]*>/gi)) { if (!classicScript(m[1] ?? "")) continue; try { new Script(m[2] ?? ""); } catch (err) { out.push(err instanceof Error ? err.message : String(err)); } } return out; } /** The page an effect plays: as the model edited it, or the template's own. */ export async function editedPage(work: Work, p: Placed): Promise { return work.has(editFile(p.id)) ? readFile(work.file(editFile(p.id)), "utf8") : p.effect.template; } const plain = (text: string) => text.toLowerCase().replace(/\s+/g, " ").trim(); const SAMPLE_WORDS = 3; /** The template's own sentences, which the screen must not show: three words or more, none said in the clip. */ export function samplesOf(template: string, said: string): string[] { const heard = plain(said); const all = [ ...pageTexts(template).map((one) => one.text), ...sampleTexts(defaultsOf(template)).map(([, text]) => text), ]; return [...new Set(all.map(plain))].filter( (text) => text.split(" ").filter((word) => /\p{L}/u.test(word)).length >= SAMPLE_WORDS && !heard.includes(text), ); }