.redact=on drops it)",
" check: the transcription read against the screenshot (by you, now); --undo takes it back. A screen not checked is a",
" lint WARNING. An e-mail address, a phone number, an order or reference number in a line is masked whatever you do.",
" read: the thread read with the screens (posts narrate - --take --thread): his words from the take that plays",
" (--post-take n: another), each read line in its speaker's voice; --line-take: that line from the item's take n;",
" a line's CHOSEN take (take.=, the bench's select) in its place. A recording nobody chose is said, never read in.",
" --reading N|next and the tuning flags: every synthesized piece read anew (next: each one past its own highest);",
" with --for that one piece only (the bench's Read again on a line), the rest from the parts cache. Each piece",
" keeps the reading the playing read gave it while it says the same words. --no-pick: the new take is not picked.",
" record: ONE LINE in your voice -- the line as the read says it (its shapes and redaction left out) recorded, then",
" cleaned and converted to its SPEAKER's character's stock voice (none: kept as recorded; --as may only name that one),",
" each a new take, none of them picked; choose it for the line (set take.=), then read. --check-words",
" (the editor's transcribe op): refused when it is heard saying a shape or a number in words, an @handle, an",
" anonymous author's handle or name, or a redacted term; nothing kept. Without it nothing hears the recording.",
].join("\n");
export class ScreenUsageError extends Error {
constructor(message) {
super(message);
this.name = "ScreenUsageError";
}
}
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const str = (v) => (typeof v === "string" ? v : "");
const unq = (v) => String(v).replace(/^"(.*)"$/s, "$1");
const fail = (m) => {
throw new ScreenUsageError(m);
};
/** Lines of TEXT as screen lines. */
export { lineOfText };
export const linesOfText = (text) => String(text).split(/\r?\n/).map(lineOfText).filter(Boolean);
/** What `--from ` holds: `{ screen?: {…}, lines?: […] }` (JSON: a screen, { lines }, or a list of lines; else text lines). */
export async function readFrom(file) {
const raw = await readFile(file, "utf8").catch(() => fail(`--from ${file}: not there`));
const t = raw.trim();
if (t.startsWith("{") || t.startsWith("[")) {
let v;
try {
v = JSON.parse(t);
} catch (e) {
fail(`--from ${file}: not JSON (${e instanceof Error ? e.message : e})`);
}
if (Array.isArray(v)) return { lines: v.map((l) => (typeof l === "string" ? lineOfText(l) : l)).filter(Boolean) };
if (isObj(v) && Array.isArray(v.lines) && Object.keys(v).length === 1) return { lines: v.lines };
if (isObj(v)) return { screen: v };
fail(`--from ${file}: a screen, { lines }, or a list of lines`);
}
return { lines: linesOfText(raw) };
}
const numList = (v, what) => {
const parts = String(v).split(",").map((x) => x.trim()).filter(Boolean);
if (!parts.length || !parts.every((x) => /^\d{1,2}$/.test(x))) fail(`${what} takes line numbers (0, 1, …) separated by commas`);
return parts.map(Number);
};
const span = (v) => {
const m = /^\s*(\d+(?:\.\d+)?)\s*[,-]\s*(\d+(?:\.\d+)?)\s*$/.exec(String(v));
if (!m) fail(`at takes , (seconds of the video: 3.5,8)`);
return [Math.round(Number(m[1]) * 100) / 100, Math.round(Number(m[2]) * 100) / 100];
};
const readOf = (v) => (v === "all" || v === "none" ? v : numList(v, "read").map((line) => ({ line })));
/**
* A screen with `key=value` pairs laid on (the `set` keys, SCREEN_USAGE), pure; a copy. Throws ScreenUsageError for a
* key it does not know or a value it cannot read; what the build refuses is the writer's to say.
*/
export function applyPairs(screen, pairs, { takeId = null } = {}) {
const sc = JSON.parse(JSON.stringify(screen));
sc.lines = Array.isArray(sc.lines) ? sc.lines : [];
const lineAt = (n) => {
if (!isObj(sc.lines[n])) fail(`line ${n}: the screen has lines 0–${sc.lines.length - 1}`);
return sc.lines[n];
};
const drops = [];
for (const pair of pairs) {
const eq = pair.indexOf("=");
if (eq < 1) fail(`${pair}: = (posts screen --help)`);
const key = pair.slice(0, eq);
const v = unq(pair.slice(eq + 1));
const off = v === "off" || v === "";
let m;
if (key === "kind") {
if (!SCREEN_KINDS.includes(v)) fail(`kind= takes ${SCREEN_KINDS.join(", ")}`);
sc.kind = v;
} else if (key === "title") {
if (off) delete sc.title;
else sc.title = v;
} else if (key === "media") {
if (!/^\d$/.test(v)) fail("media= takes the attachment's index (0, 1, …)");
sc.media = Number(v);
} else if (key === "at") {
if (off) delete sc.at;
else sc.at = span(v);
} else if (key === "unread") {
if (!SCREEN_UNREAD.includes(v)) fail(`unread= takes ${SCREEN_UNREAD.join(" or ")}`);
sc.unread = v;
} else if (key === "ref") {
if (off) delete sc.ref;
else sc.ref = v;
} else if (key === "read") {
sc.read = readOf(v);
} else if ((m = /^read\.(\d{1,2})$/.exec(key))) {
const n = Number(m[1]);
lineAt(n);
const list = sc.read === "all" ? sc.lines.map((l, i) => (isObj(l) && l.redact !== true ? { line: i } : null)).filter(Boolean) : Array.isArray(sc.read) ? sc.read : [];
const rest = list.filter((x) => x?.line !== n);
if (v === "off") sc.read = rest;
else sc.read = [...rest, v === "on" ? { line: n } : { line: n, text: v }].sort((a, b) => a.line - b.line);
} else if (key === "line.add") {
const l = lineOfText(v);
if (!l) fail("line.add= takes a line (who: words)");
sc.lines.push(l);
} else if ((m = /^line\.(\d{1,2})$/.exec(key))) {
if (v !== "off") fail(`${key}= takes off (the line removed; line.${m[1]}.text= to change its words)`);
lineAt(Number(m[1]));
drops.push(Number(m[1]));
} else if ((m = /^line\.(\d{1,2})\.(who|side|text|time|redact)$/.exec(key))) {
const l = lineAt(Number(m[1]));
const f = m[2];
if (f === "side") {
if (v === "auto") delete l.side;
else if (!SCREEN_SIDES.includes(v)) fail(`${key}= takes left, right or auto`);
else l.side = v;
} else if (f === "redact") {
if (v === "on") {
l.redact = true;
// A redacted line is never read: its "said as" goes with it (review 1, finding 7).
const n = Number(m[1]);
if (isObj(sc.saidAs) && sc.saidAs[String(n)] !== undefined) {
delete sc.saidAs[String(n)];
if (!Object.keys(sc.saidAs).length) delete sc.saidAs;
}
}
else if (v === "off") delete l.redact;
else fail(`${key}= takes on or off`);
} else if (f === "text") l.text = v;
else if (off) delete l[f];
else l[f] = v;
} else if ((m = /^take\.(\d{1,2})$/.exec(key))) {
// The take CHOSEN for a line (a recording of it): its number as --list counts, made its id; off unchooses.
const n = Number(m[1]);
lineAt(n);
const lt = isObj(sc.lineTakes) ? { ...sc.lineTakes } : {};
if (off) delete lt[String(n)];
else {
if (!takeId) fail(`${key}= takes a take's number (posts screen
- list shows the line's recordings)`);
lt[String(n)] = takeId(v, n);
}
if (Object.keys(lt).length) sc.lineTakes = lt;
else delete sc.lineTakes;
} else if ((m = /^said\.(\d{1,2})$/.exec(key))) {
// What line n is SAID AS (saidAs; never drawn -- the card shows the line as written); off: its own words.
const n = Number(m[1]);
lineAt(n);
const sa = isObj(sc.saidAs) ? { ...sc.saidAs } : {};
if (off) delete sa[String(n)];
else sa[String(n)] = v;
if (Object.keys(sa).length) sc.saidAs = sa;
else delete sc.saidAs;
} else fail(`${key} is not a screen's knob (posts screen --help)`);
}
// Lines removed: the read's line numbers follow them (a dropped line's read goes too) -- the bench's rule too.
return drops.length ? withoutLines(sc, drops) : sc;
}
/** The next free screen id of an item: s1, s2, … */
export function nextScreenId(e) {
const have = new Set(screensOf(e).map((s) => s.id));
for (let n = 1; ; n += 1) if (!have.has(`s${n}`)) return `s${n}`;
}
/** One screen as listing lines (text). */
export function screenListing(e, sc) {
const reads = new Map(screenReadLines(sc).map((r) => [r.n, r]));
const recordings = lineRecordingsOf(e);
const m = (Array.isArray(e.media) ? e.media : [])[sc.media];
const head = `${sc.id} ${sc.kind}${sc.title ? ` "${sc.title}"` : ""} attachment ${sc.media}${m ? ` (${m.kind})` : ""}${Array.isArray(sc.at) ? ` at ${sc.at[0]}–${sc.at[1]} s` : ""} read ${sc.read === "all" ? "all" : sc.read === "none" ? "none (transcribed only)" : `${reads.size} line(s)`}${sc.unread === "dim" ? ", the rest dim" : ""} ${sc.checked ? `checked by ${sc.checked.by} ${String(sc.checked.at).slice(0, 10)}` : "NOT CHECKED"}`;
const rows = sc.lines.map((l, n) => {
const r = reads.get(n);
const mark = l?.redact ? "x" : r ? (r.cutBefore || r.cutAfter ? "~" : "*") : " ";
const ex = r && (r.cutBefore || r.cutAfter) ? ` [reads: "${str(l.text).slice(r.start, r.end)}"]` : "";
const recs = recordings.find((L) => L.screen === sc.id && L.n === n);
const rec = recs ? ` [recorded: ${recs.takes.map((x) => `take ${x.n}${x.chosen ? " (chosen)" : ""}${x.current ? "" : " (line changed since)"}`).join(", ")}]` : "";
const as = isObj(sc.saidAs) && typeof sc.saidAs[String(n)] === "string" ? ` [said as: "${sc.saidAs[String(n)]}"]` : "";
return ` ${mark} ${String(n).padStart(2)} ${(l?.side ? `[${l.side}] ` : "") + (l?.who ? `${l.who}: ` : "- ")}${l?.redact ? "(redacted)" : str(l?.text)}${l?.time ? ` | ${l.time}` : ""}${ex}${as}${rec}`;
});
return [head, ...rows];
}
/**
* `umtool posts screen
- …`. `project` is resolved; `rest` the words after the project
* (`
- [] [pairs…]`); `opt` the posts command's flags and helpers.
*/
export async function screenCommand(project, rest, { flags, str: flag, multi, json = false, out = (s) => console.log(s), dryRun = false, tts = null }) {
const [ref, verb, ...words] = rest;
if (!ref || !verb || flags.has("--help")) {
out(SCREEN_USAGE);
return 2;
}
// The token of the manifest as READ here: a write after someone else's is refused (StaleToken), never laid over it.
const token0 = await manifestToken(project.dir);
const manifest = await readManifest(project.dir);
if (!manifest) throw new ScreenUsageError(`${project.id} has no manifest`);
const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
const e = tl.find((x) => x?.type === "post" && (x.id === ref || String(x.post ?? "").split("/")[1] === ref));
if (!e) throw new ScreenUsageError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
const screens = screensOf(e);
const write = async (next, what) => {
const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, e.id, { screens: next.length ? next : null }, { token: token0 }));
const entry = result.entry;
const { pickedTake, isNarrated } = await import("umtool-report-to-video/post-narration");
const { partRoles } = await import("umtool-report-to-video/post-thread");
const { lineTakeWarnings } = await import("umtool-report-to-video/post-thread");
const warnings = [...screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? partRoles(entry).map((r) => r.role) : [] }), ...lineTakeWarnings(entry)];
const { threadReadErrors } = await import("umtool-report-to-video/post-thread");
const { followKnobs } = await import("umtool-report-to-video/read-follow");
const { planContext } = await import("umtool-report-to-video/post-conversation");
const m2 = await readManifest(project.dir);
const i = (m2?.timeline ?? []).findIndex((x) => x?.id === e.id);
const at = i >= 0 ? m2.timeline[i] : null;
const { readSaysHiddenErrors } = await import("umtool-report-to-video/post-thread");
const refused = at && isNarrated(at) ? [...threadReadErrors(at, m2.render ?? {}, { ...planContext(m2.timeline, i, m2.render ?? {}), followOn: followKnobs(at, m2.render ?? {}).on }), ...readSaysHiddenErrors(at)] : [];
if (json) {
out(JSON.stringify({ ok: true, id: e.id, what, screens: entry.screens ?? [], warnings, refusedUntilRead: refused, token: result.token, editNotes }, null, 2));
return 0;
}
out(`${e.id}: ${what}`);
for (const sc of screensOf(entry)) for (const l of screenListing(entry, sc)) out(` ${l}`);
for (const x of refused) out(` the build REFUSES the read as it is until it is re-made (umtool posts screen ${project.id} ${e.id} read): ${x}`);
for (const w of warnings) out(` warning: ${w}`);
if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel} (umtool timeline ${project.id} undo)`);
if (editNotes) out(` edit noted for ${editNotes.generatedBy}`);
return 0;
};
const byId = (id) => {
if (!id) fail(`which screen? (${screens.map((s) => s.id).join(", ") || "it has none"})`);
const sc = screens.find((s) => s.id === id);
if (!sc) fail(`${e.id} has no screen ${id} (${screens.map((s) => s.id).join(", ") || "none"})`);
return sc;
};
if (verb === "list") {
if (json) {
out(JSON.stringify({ ok: true, id: e.id, screens, rows: Object.fromEntries(screens.map((s) => [s.id, screenRows(s)])), errors: validateScreens(e), warnings: screenWarnings(e, { narrated: (await import("umtool-report-to-video/post-narration")).isNarrated(e), takeRoles: (await import("umtool-report-to-video/post-thread")).partRoles(e).map((r) => r.role) }) }, null, 2));
return 0;
}
if (!screens.length) out(`${e.id}: no screens (umtool posts screen ${project.id} ${e.id} add --media --kind dm --from )`);
for (const sc of screens) for (const l of screenListing(e, sc)) out(l);
return 0;
}
if (verb === "add" && flags.has("--from-read")) {
// A PICTURE-ONLY post's read made its screen (post-screens.mjs screenFromRead): typed once, as its script.
if (flag("--from") !== null || multi("--line").length) fail("--from-read makes the lines from the read: not with --from or --line");
const id = flag("--id") ?? nextScreenId(e);
if (screens.some((s) => s.id === id)) fail(`${e.id} has a screen ${id} already (set changes it)`);
const mi = flag("--media");
if (mi !== null && !/^\d$/.test(String(mi))) fail("--media takes the attachment's index");
const made = screenFromRead(e, { pictureOnly: ownPictureOnly(e), id, media: mi === null ? null : Number(mi), kind: flag("--kind") });
if (made.error) fail(made.error);
const sc = { ...made.screen, ...(flag("--title") !== null ? { title: flag("--title") } : {}) };
if (dryRun) {
const errs = validateScreens({ ...e, screens: [...screens, sc] });
out(json ? JSON.stringify({ ok: !errs.length, dryRun: true, screen: sc, errors: errs }, null, 2) : [`would add ${sc.id} from its read:`, ...screenListing(e, sc).map((l) => ` ${l}`), ...errs.map((x) => ` refused: ${x}`)].join("\n"));
return errs.length ? 1 : 0;
}
// What is true now: the screen is not drawn and its read is the old one until the read is made again.
return write([...screens, sc], `added screen ${sc.id} from its read (${sc.lines.length} line(s), not checked) -- not drawn, and the item still plays its read as it was (its script, every word of it), until the read is made again: umtool posts screen ${project.id} ${e.id} read (its lines are then the read, the masked parts never said)`);
}
if (verb === "add") {
const from = flag("--from") ? await readFrom(path.resolve(String(flag("--from")))) : {};
const base = from.screen ?? {};
const id = flag("--id") ?? base.id ?? nextScreenId(e);
if (screens.some((s) => s.id === id)) fail(`${e.id} has a screen ${id} already (set changes it)`);
const lines = [...(from.lines ?? base.lines ?? []), ...multi("--line").map(lineOfText).filter(Boolean)];
const sc = {
...base,
id,
...(flag("--media") !== null ? { media: /^\d$/.test(String(flag("--media"))) ? Number(flag("--media")) : fail("--media takes the attachment's index") } : base.media === undefined ? { media: 0 } : {}),
...(flag("--at") !== null ? { at: span(flag("--at")) } : {}),
...(flag("--kind") !== null ? { kind: flag("--kind") } : {}),
...(flag("--title") !== null ? { title: flag("--title") } : {}),
...(flag("--ref") !== null ? { ref: flag("--ref") } : {}),
...(flag("--unread") !== null ? { unread: flag("--unread") } : {}),
source: "transcribed",
lines,
read: flag("--read") !== null ? readOf(flag("--read")) : base.read ?? "all",
};
if (!sc.kind) fail("--kind dm|email|post|text: what the screenshot is");
if (dryRun) {
const errs = validateScreens({ ...e, screens: [...screens, sc] });
out(json ? JSON.stringify({ ok: !errs.length, dryRun: true, screen: sc, errors: errs }, null, 2) : [`would add ${sc.id}:`, ...screenListing(e, sc).map((l) => ` ${l}`), ...errs.map((x) => ` refused: ${x}`)].join("\n"));
return errs.length ? 1 : 0;
}
return write([...screens, sc], `added screen ${sc.id}`);
}
if (verb === "set") {
const sc = byId(words[0]);
let next = sc;
if (flag("--from")) {
const from = await readFrom(path.resolve(String(flag("--from"))));
next = from.screen ? { ...from.screen, id: sc.id } : { ...sc, lines: from.lines ?? sc.lines };
// New lines: the checked mark goes (it was for the words before).
delete next.checked;
}
const pairs = words.slice(1);
if (!pairs.length && !flag("--from")) fail("set =… (posts screen --help)");
next = applyPairs(next, pairs, { takeId: (v, n) => {
const takes = Array.isArray(e.narration?.takes) ? e.narration.takes : [];
const k = Number(v);
if (!/^\d{1,3}$/.test(String(v)) || k < 1 || k > takes.length) fail(`take.${n}= takes a take's number (1–${takes.length}) or off`);
const t = takes[k - 1];
if (!isObj(t?.screenLine) || t.screenLine.screen !== sc.id) fail(`take ${k} is not a recording of a line of screen ${sc.id}${isObj(t?.screenLine) ? ` (it is of screen ${t.screenLine.screen})` : ""}: record it (posts screen
${e.id} record ${sc.id} ${n} --recording )`);
// Owned by its CONTENT: it must say line n as it is now (its words, its speaker), whatever line it was recorded as.
if (lineTakeCurrent(e, t, sc.id, n) !== true) fail(`take ${k} does not say line ${n} of screen ${sc.id} as it is now (it was recorded for line ${t.screenLine.n}: other words or another speaker): record it (posts screen ${e.id} record ${sc.id} ${n} --recording )`);
return takeIdOf(t);
} });
// Words changed: what was checked is not what is there now.
if (JSON.stringify(next.lines) !== JSON.stringify(sc.lines)) delete next.checked;
// A line redacted drops its "said as": said in the answer.
const dropped = Object.keys(isObj(sc.saidAs) ? sc.saidAs : {}).filter((k) => !(isObj(next.saidAs) && k in next.saidAs) && next.lines?.[Number(k)]?.redact === true);
return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}${dropped.length ? ` (line ${dropped.join(", ")} redacted: its said-as dropped -- a redacted line is never read)` : ""}`);
}
if (verb === "rm") {
const sc = byId(words[0]);
return write(screens.filter((s) => s.id !== sc.id), `removed screen ${sc.id}`);
}
if (verb === "check") {
const sc = byId(words[0]);
const next = { ...sc };
if (flags.has("--undo")) delete next.checked;
else next.checked = { by: flag("--by") ?? process.env.USER ?? "operator", at: new Date().toISOString() };
return write(screens.map((s) => (s.id === sc.id ? next : s)), flags.has("--undo") ? `screen ${sc.id}: not checked` : `screen ${sc.id}: checked`);
}
if (verb === "read") {
if (!screens.length) fail(`${e.id} has no screens to read (add one first)`);
const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs");
const { lineTakesOf, threadTunedOf, tuningFlags } = await import("./postNarrationCli.mjs");
const postTake = flag("--post-take") ?? defaultPostTake(e);
const o = screenReadOptions(e, { flags, flag, multi });
return threadCommand(project, e, {
manifest, json, out, ...o, parents: parentsSelector(o.parents), engine: flag("--engine"), note: flag("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun,
// The playing read's (re-attached while their lines say the same), the screens' CHOSEN ones over them, the flags' over all.
postTake, lineTakes: { ...defaultLineTakes(e), ...chosenLineTakes(e), ...lineTakesOf(multi("--line-take")) },
// Its readings and tunings (lane line-rerun): the flags' (--reading, the tuning flags, --for, --tuned), over the
// playing read's -- each piece's kept while it says the same words.
tuned: threadTunedOf(tuningFlags(flag), { str: flag, multi }), inherit: playingTuned(e), keepPick: flags.has("--no-pick"), events: flags.has("--events"),
// The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub) -- the lanes then never held.
...(tts ? { ask: tts, lanes: null } : {}),
});
}
if (verb === "record") {
// ONE LINE in a person's voice (screenLineRecord.mjs): new takes, none picked; chosen for its line by hand.
const sc = byId(words[0]);
if (!/^\d{1,2}$/.test(String(words[1] ?? ""))) fail(`record ${sc.id} : which line (0–${sc.lines.length - 1})?`);
const file = flag("--recording");
if (!file) fail("record takes --recording (a sound file: your read of the line)");
const { recordScreenLine, LineRecordError } = await import("./screenLineRecord.mjs");
const events = flags.has("--events");
const role = `screen:${sc.id}:${Number(words[1])}`;
let r;
try {
r = await recordScreenLine(project, e.id, role, path.resolve(String(file)), {
as: flag("--as"), label: flag("--label") ?? "operator",
clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined,
...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}),
convert: !flags.has("--no-convert"), note: flag("--note"),
...(flag("--pitch") !== null ? { pitch: flag("--pitch") } : {}), ...(flag("--semitones") !== null ? { semitones: Number(flag("--semitones")) } : {}),
checkWords: flags.has("--check-words"), worker: flag("--worker"),
emit: (ev, f) => (events ? out(JSON.stringify({ ev, ...f })) : !json && f?.message && out(f.message)),
});
} catch (err) {
const { NarrateError } = await import("./postNarrationCli.mjs");
if (err instanceof LineRecordError || err instanceof NarrateError) {
if (events || json) out(JSON.stringify({ ...(events ? { ev: "result" } : {}), ok: false, id: e.id, role, error: err.message }));
else out(`refused: ${err.message}`);
return 1;
}
throw err;
}
const m2 = await readManifest(project.dir);
const after = (m2?.timeline ?? []).find((x) => x?.id === e.id);
const numbers = r.takes.map((x) => 1 + (after?.narration?.takes ?? []).findIndex((t) => t.file === x.file));
const res = { ok: true, id: e.id, role, takes: r.takes.map((x, i) => ({ ...x, n: numbers[i] })), notes: r.notes, disclosure: r.disclosure, character: r.character, prompt: r.line.prompt };
if (events) out(JSON.stringify({ ev: "result", ...res }));
else if (json) out(JSON.stringify(res, null, 2));
else {
out(`${e.id}: line ${words[1]} of screen ${sc.id} recorded -- ${r.takes.map((x, i) => `take ${numbers[i]} ${x.step}`).join(", ")}; none picked`);
for (const n of r.notes) out(` ${n}`);
out(` disclosure in the read: ${r.disclosure}`);
out(` choose it for the line: umtool posts screen ${project.id} ${e.id} set ${sc.id} take.${words[1]}=${numbers.at(-1)} then: umtool posts screen ${project.id} ${e.id} read`);
}
return 0;
}
fail(`posts screen ${verb}: list, add, set, rm, check, read or record`);
return 2;
}
/**
* HIS OWN LINE for a screens read (`read` with no --post-take): the take that plays when it is not a thread read (its
* number, from 1), else the take the thread read that plays used for it (`read.postTake.n`), else none (synthesized;
* from the parts cache when it was before).
*/
export function defaultPostTake(e) {
// A screen made from its read IS his read (postThreadRead.mjs): no take of his words stands in for it.
if (screensOf(e).some((sc) => sc.source === "read")) return null;
const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0;
const t = takes[k];
if (!t || e?.narration?.off === true) return null;
const thread = /-thread\.wav$/.test(str(t.file)) || t.read?.kind === "thread";
if (!thread) return k + 1;
const f = str(t.read?.postTake?.file);
// Its number then may have moved: found again by its file.
const at = takes.findIndex((x) => str(x?.file) === f);
return at >= 0 ? at + 1 : null;
}
/** The playing thread read's pieces' readings and tunings (`read.tuned`, each with the words it said), or `{}`. */
export function playingTuned(e) {
const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
const k = Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0;
const t = takes[k]?.read;
return t?.kind === "thread" && isObj(t.tuned) ? t.tuned : {};
}
/**
* The lines the playing thread read took from takes (`read.lineTakes`), found again by their files -- each ONLY while
* its line still says what it said then (`line`, stored with it): a line edited, removed or moved is read afresh, never
* with the old recording. `{ : n }`.
*/
export function defaultLineTakes(e) {
const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
const k = Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0;
const lt = takes[k]?.read?.lineTakes;
if (!isObj(lt)) return {};
const out = {};
for (const [role, x] of Object.entries(lt)) {
const at = takes.findIndex((t) => str(t?.file) === str(x?.file));
const m = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/.exec(role);
const sc = m ? screensOf(e).find((s) => s.id === m[1]) : null;
const now = sc ? lineWritten(screenLineSaid(sc, Number(m[2]))) : "";
// A RECORDING OF A LINE (`screenLine`) is read in only while the screen CHOOSES it (chosenLineTakes): never re-attached here.
if (at >= 0 && isObj(takes[at]?.screenLine)) continue;
if (at >= 0 && typeof x?.line === "string" && now && norm(x.line) === norm(now)) out[role] = at + 1;
}
return out;
}
const norm = (t) => String(t ?? "").replace(/\s+/g, " ").trim();
/** A line's words as a read writes them (post-narration.mjs draftScript). */
const lineWritten = (t) => draftScript(String(t ?? "")).script;
/**
* THE READ's OPTIONS for `posts screen … read`, pure: the playing thread read's own (`read`: its parents, skips,
* quoted / linked, seen, voices, voice, speed) -- so making the screens' read never quietly resets the read it
* replaces -- each flag given winning. `{ parents, skip, quoted, linked, readSeen, overrides, voice, speed }`.
*/
export function screenReadOptions(e, { flags, flag, multi }) {
const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0;
const r = takes[k]?.read?.kind === "thread" ? takes[k].read : {};
const vf = multi("--voice-for");
const overrides = vf.length ? voiceOverridesOf(vf) : {};
const skip = multi("--skip-parent");
return {
parents: flag("--parents") ?? (r.parents !== undefined ? String(r.parents) : "0"),
skip: skip.length ? skip : Array.isArray(r.skip) ? [...r.skip] : [],
quoted: flags.has("--no-quoted") ? false : r.quoted !== false,
linked: flags.has("--no-linked") ? false : r.linked !== false,
readSeen: flags.has("--read-seen") || r.seen === true,
overrides: vf.length ? overrides : isObj(r.voiceFor) ? { ...r.voiceFor } : {},
voice: flag("--voice") ?? (typeof r.voice === "string" ? r.voice : null),
speed: flag("--speed") !== null ? Number(flag("--speed")) : typeof r.speed === "number" ? r.speed : null,
};
}