// WORDS BLANKED FROM WHAT IS PUBLISHED (operator, 3 Nov: "Leave out his real // name since we don't really need it, even if he says it himself blank and // skip it"; "don't manipulate original data, just don't show it in the // public views"). umtool/docs/knobs.md, "Redacted words". // // A REDACTION is a list of terms -- a word or a phrase -- matched without // regard to case, as whole words unless `wholeWord: false`, the words of a // phrase across any run of spaces or punctuation ("Quentin Example" matches // "quentin, EXAMPLE", and "QuentinExample" as a handle runs them together), a // possessive 's taken with it. Its sources, merged by // the reader (post-redact-files.mjs): // // render.posts.redact [{ term, wholeWord?, note? }] the project's own list // /redactions.json the same shape every project's (the corpus's) // channels//posts-markup.json one post's MARKUP: // { "": { redact?: [{ term, wholeWord?, scope? } | { start, end, scope?, index? }], // censor?: [{ media: , blur?: {strength?, boxes?, label?} }] } } // a term (in `scope` -- "text", "parent", "quoted" -- or the whole post), or a span of the // archived text, in code units (`index`: which parent, nearest first); `censor` blurs an // attachment of the post in every project (post-censor.mjs) // // NOTHING IS REWRITTEN: the archive's rows, the manifest's snapshot and a // narration's script keep their words. Redaction happens only where PUBLIC // output is made -- the rendered card (each match a solid bar of the word's // width: no letters, not a blur), the read a voice synthesizes (the match // dropped, its spaces and dangling punctuation tidied), a video's chapter // line and an attachment's burnt-in captions. umtool's own views show the // words; Play's "As published" shows the bars. // // PURE (the build, the route, Play and the writers). import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; import { validateClockRender } from "./post-clock.mjs"; import { applyLexicon } from "./post-say.mjs"; import { speakAnonymised } from "./post-anon.mjs"; import { validateProgressRender } from "./post-progress.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ export const REDACT_MARK = ""; const MARKS_RE = /+/g; export const POST_REDACT_MAX = 200; export const POST_REDACT_TERM_MAX = 120; export const POST_MARKUP_SCOPES = Object.freeze(["text", "parent", "quoted"]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); const WORD = "[\\p{L}\\p{N}]"; const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&"); /** A term's words (letters and digits): what it matches, across any punctuation. */ export const termWords = (term) => str(term).split(/[^\p{L}\p{N}]+/u).filter(Boolean); /** A list's terms as `{ term, wholeWord }`, a bare string read as a term. */ export function normalizeTerms(list) { return (Array.isArray(list) ? list : []) .map((t) => (typeof t === "string" ? { term: t } : t)) .filter((t) => isObj(t) && termWords(t.term).length) .map((t) => ({ term: t.term, wholeWord: t.wholeWord !== false })); } /** One term's pattern source, or null when it has no word to match. */ export function termPattern(t) { const words = termWords(t?.term); if (!words.length) return null; // Between a phrase's words, any run of spaces or punctuation -- or none, as a handle writes it ("QuentinExample"). const body = `${words.map(escRe).join("[^\\p{L}\\p{N}]*")}(?:['’]s)?`; return t?.wholeWord === false ? body : `(? b.term.length - a.term.length) .map(termPattern) .filter(Boolean); return src.length ? new RegExp(src.join("|"), "giu") : null; } /** * `text` with every match of `terms` (and every `spans` range, `{start, end}` * in code units) turned into REDACT_MARKs, one per code unit, its spaces kept * -- its length, every offset and its words (runs of non-space) kept, so a * layout measured on it and a word index counted on it are the original's. Returns * `{ text, spans }`: the merged ranges, sorted. * * @param {string} text * @param {Array|RegExp|null} terms * @param {{ spans?: Array<{start: number, end: number}> }} [o] */ export function redactText(text, terms, { spans: extra = [] } = {}) { const s = str(text); const re = terms instanceof RegExp ? new RegExp(terms.source, terms.flags) : redactPattern(terms); const ranges = []; if (re && s) for (const m of s.matchAll(re)) if (m[0]) ranges.push([m.index, m.index + m[0].length]); for (const sp of Array.isArray(extra) ? extra : []) { const a = Math.max(0, Math.floor(Number(sp?.start))); const b = Math.min(s.length, Math.floor(Number(sp?.end))); if (Number.isFinite(a) && Number.isFinite(b) && b > a) ranges.push([a, b]); } if (!ranges.length) return { text: s, spans: [] }; ranges.sort((x, y) => x[0] - y[0]); const merged = []; for (const r of ranges) { const last = merged[merged.length - 1]; if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]); else merged.push([...r]); } let out = ""; let at = 0; for (const [a, b] of merged) { // Every code unit marked but the spaces: a phrase stays as many card words as it was (a word zoom's indices hold). out += s.slice(at, a) + s.slice(a, b).replace(/\S/g, REDACT_MARK); at = b; } return { text: out + s.slice(at), spans: merged.map(([start, end]) => ({ start, end })) }; } /** Does `text` hold a redacted match (or a masked slur, post-slurs.mjs)? */ export const hasMarks = (text) => str(text).includes(REDACT_MARK) || hasSlurMarks(text); /** * Marked text with the marks DROPPED, as a read or a line of text says it: * the spaces either side collapsed to one, a bracket left empty removed, and * punctuation left dangling -- a comma before a full stop, a clause's comma * at a sentence's start -- taken away. Only around a mark; the rest verbatim. */ export function dropMarks(marked) { // A masked slur (post-slurs.mjs): its placeholder read as its mask, the gaps of one spelt apart gone. const unmasked = decodePlaceholder(str(marked).replace(/[ \t]*\uE0FF/g, "")); // A phrase's marks with its spaces between them are one run to drop. const parts = unmasked.split(/\uE000(?:[\s\uE000]*\uE000)?/); if (parts.length === 1) return parts[0]; let out = parts[0]; for (let i = 1; i < parts.length; i += 1) { let L = out.replace(/[ \t]+$/, ""); let R = parts[i].replace(/^[ \t]+/, ""); if (/[(\[]$/.test(L) && /^[)\]]/.test(R)) { L = L.slice(0, -1).replace(/[ \t]+$/, ""); R = R.slice(1).replace(/^[ \t]+/, ""); } if ((L === "" || /[.!?…\n,;:(\[]$/.test(L)) && /^[,;:]/.test(R)) R = R.replace(/^[,;:][ \t]*/, ""); if (/[,;:]$/.test(L) && /^[.!?…,;:]/.test(R)) L = L.slice(0, -1); const glue = L === "" || /\n$/.test(L) || R === "" || /^[\n,.!?;:…)\]]/.test(R) ? "" : " "; out = L + glue + R; } return out.trim(); } /** `text` as SAID with `terms` left out (a synthesized read; a chapter line). */ export const spokenWithout = (text, terms) => { const r = redactText(text, terms); return r.spans.length ? dropMarks(r.text) : str(text); }; /** The width a run of `n` marks is drawn at, in em (a sans face's average letter). */ export const barEm = (n) => Math.round(n * 0.52 * 100) / 100; /** HTML (already escaped) with each run of marks drawn as a solid bar of its width -- no letters inside. */ export const barsHtml = (html) => placeholdersHtml(str(html)).replace(MARKS_RE, (m) => ``); /** The bar's CSS, for a page that draws them. */ export const BAR_CSS = (fg) => `.rbar { display: inline-block; height: 0.92em; vertical-align: -0.12em; background: ${fg}; border-radius: 0.12em; }\n${SLUR_CSS(fg)}`; // --------------------------------------------------------------------------- // The project's list and a post's markup. // --------------------------------------------------------------------------- /** The project's own list (`render.posts.redact`). */ export const projectRedactOf = (render) => (Array.isArray(render?.posts?.redact) ? render.posts.redact : []); /** Every reason a list of terms (the project's, or the corpus's file) is refused. */ export function validateRedactTerms(list, where = "render.posts.redact") { if (list === undefined) return []; if (!Array.isArray(list)) return [`${where} must be a list of {term, wholeWord?}`]; const errors = []; if (list.length > POST_REDACT_MAX) errors.push(`${where} holds at most ${POST_REDACT_MAX} terms`); list.forEach((t, i) => { const w = `${where}[${i}]`; if (!isObj(t)) return errors.push(`${w} must be {term, wholeWord?}`); for (const k of Object.keys(t)) if (!["term", "wholeWord", "note"].includes(k)) errors.push(`${w}.${k} is not a key of a term (term, wholeWord, note)`); if (typeof t.term !== "string" || !termWords(t.term).length) errors.push(`${w}.term must hold a word (letters or digits)`); else if (t.term.length > POST_REDACT_TERM_MAX) errors.push(`${w}.term is longer than ${POST_REDACT_TERM_MAX} characters`); if (t.wholeWord !== undefined && typeof t.wholeWord !== "boolean") errors.push(`${w}.wholeWord must be true or false`); if (t.note !== undefined && typeof t.note !== "string") errors.push(`${w}.note must be words`); }); return errors; } /** Every reason `render.posts` cannot be built (its `redact` list). */ export function validatePostsRender(render) { const p = render?.posts; if (p === undefined) return []; if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"]; // Its clock (post-clock.mjs): the cut's default and zone. // Its progress bar (post-progress.mjs): the cut's default. return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock), ...validateProgressRender(p.progress)]; } /** Every reason a channel's posts-markup.json is refused. */ export function validatePostsMarkup(doc, where = "posts-markup.json") { if (!isObj(doc)) return [`${where} must be {"": {redact?: […], censor?: […]}}`]; const errors = []; for (const [id, m] of Object.entries(doc)) { const w = `${where} ${id}`; if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) errors.push(`${w}: not a post id`); if (!isObj(m) || (m.redact !== undefined && !Array.isArray(m.redact)) || Object.keys(m).some((k) => !["redact", "censor", "note"].includes(k))) { errors.push(`${w} must be {redact?: […], censor?: […]}`); continue; } errors.push(...censorMarkupErrors(m.censor, `${w}.censor`)); (m.redact ?? []).forEach((r, i) => { const wi = `${w}.redact[${i}]`; if (!isObj(r)) return errors.push(`${wi} must be {term} or {start, end}`); if (r.scope !== undefined && !POST_MARKUP_SCOPES.includes(r.scope)) errors.push(`${wi}.scope must be one of ${POST_MARKUP_SCOPES.join(", ")}`); if (r.index !== undefined && !(Number.isInteger(r.index) && r.index >= 0 && r.index < 2)) errors.push(`${wi}.index must be 0 or 1 (a parent, nearest first)`); if (r.term !== undefined) { if (typeof r.term !== "string" || !termWords(r.term).length) errors.push(`${wi}.term must hold a word`); if (r.wholeWord !== undefined && typeof r.wholeWord !== "boolean") errors.push(`${wi}.wholeWord must be true or false`); } else if (!(Number.isInteger(r.start) && Number.isInteger(r.end) && r.start >= 0 && r.end > r.start)) { errors.push(`${wi} must name a term, or a span {start, end} of the text (code units, end after start)`); } }); } return errors; } /** * A REDACTION as the readers resolve it: `{ terms, markup }` -- every term * that applies everywhere (the corpus's and the project's) and each post's * markup by `/` (the entry's `post`). * * and `slurs`, the cut's SLUR FILTER (post-slurs.mjs resolveSlurs: its list, on or off). * * and `say`, the project's PRONUNCIATION LEXICON (post-say.mjs: `narration/lexicon.json`, read by the umtool * side's projectRedaction) -- applied by spokenRead only, never to anything drawn. * * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record, slurs?: ReturnType | null, say?: Array> | null }} Redaction */ /** Is there anything to blank? */ export const redactionOn = (red) => !!red && (normalizeTerms(red.terms).length > 0 || Object.keys(red.markup ?? {}).length > 0 || slursOn(red.slurs)); /** The terms that apply to post item `entry` in `scope` (everywhere, then its markup's). */ export function termsFor(entry, red, scope = null) { const mine = red?.markup?.[str(entry?.post)]?.redact ?? []; const local = mine.filter((r) => isObj(r) && typeof r.term === "string" && (!scope || !r.scope || r.scope === scope)); return [...normalizeTerms(red?.terms), ...normalizeTerms(local)]; } const spansFor = (entry, red, scope, index = 0) => (red?.markup?.[str(entry?.post)]?.redact ?? []).filter( (r) => isObj(r) && r.term === undefined && (r.scope ?? "text") === scope && (scope !== "parent" || (r.index ?? 0) === index), ); /** * Post item `entry` AS PUBLISHED: a copy with every match marked (redactText) * in what its card draws -- its words, its author's name and handle, the * posts it answers and quotes (their words, a paraphrase, their names), the * repost line, a "replying to" handle and the subjects the authors' rule * reads (so a subject marked is still the subject). The entry itself is * never touched; with nothing to blank, it is returned as it is. * * @param {Record} entry * @param {Redaction|null|undefined} red */ export function redactEntry(entry, red) { if (!redactionOn(red) || !isObj(entry)) return entry; const all = redactPattern(termsFor(entry, red)); const scoped = (scope) => redactPattern(termsFor(entry, red, scope)); const mark = (v, re, spans = []) => (typeof v === "string" ? redactText(v, re, { spans }).text : v); const ref = (r, scope, index = 0) => { if (!isObj(r)) return r; const re = scoped(scope); const out = { ...r }; for (const k of ["author", "handle"]) if (k in out) out[k] = mark(out[k], all); if ("text" in out) out.text = mark(out.text, re, spansFor(entry, red, scope, index)); if ("paraphrase" in out) out.paraphrase = mark(out.paraphrase, re); if ("transcript" in out) out.transcript = mark(out.transcript, re); return out; }; const out = { ...entry }; for (const k of ["author", "handle", "replyingTo"]) if (k in out) out[k] = mark(out[k], all); out.text = mark(entry.text, scoped("text"), spansFor(entry, red, "text")); if (Array.isArray(entry.subjects)) out.subjects = entry.subjects.map((h) => mark(h, all)); if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: mark(entry.repostedBy.author, all), handle: mark(entry.repostedBy.handle, all) }; if (Array.isArray(entry.parents)) out.parents = entry.parents.map((p, i) => ref(p, "parent", i)); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted"); // A post its words link to (post-thread.mjs): marked by the project's terms, as a quoted post is. if (Array.isArray(entry.links)) out.links = entry.links.map((p) => ref(p, "quoted")); // ITS SCREENS (post-screens.mjs): every line's words and its speaker marked by the project's terms. if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, (v) => mark(v, all)); return slurEntry(out, red?.slurs); } /** * A SCENE TILE's post (post-conversation.mjs: a post the run left on screen, * drawn on the next item's card) AS PUBLISHED: its words marked by the terms * of the item it came from (`ref.src`: `{ post, scope: "text"|"parent"|"quoted", * index }`) -- the same marks that item's card drew -- its name and handle by * the project's, its slurs masked. A copy; the ref itself with nothing to do. * * @param {Record} ref * @param {Redaction|null|undefined} red */ export function redactSceneRef(ref, red) { if (!isObj(ref)) return ref; let out = ref; if (redactionOn(red)) { const src = isObj(ref.src) ? ref.src : {}; const from = { post: str(src.post) }; const scope = ["text", "parent", "quoted"].includes(src.scope) ? src.scope : "text"; const all = redactPattern(termsFor(from, red)); const re = redactPattern(termsFor(from, red, scope)); // A paraphrase is not the words a span was marked on: its terms only. const spans = ref.paraphrased ? [] : spansFor(from, red, scope, Number.isInteger(src.index) ? src.index : 0); const mark = (v, p, sp = []) => (typeof v === "string" ? redactText(v, p, { spans: sp }).text : v); out = { ...ref, author: mark(ref.author, all), handle: mark(ref.handle, all), text: mark(ref.text, re, spans) }; } if (slursOn(red?.slurs)) out = { ...out, text: maskSlurs(str(out.text), red.slurs).text, ...(typeof out.author === "string" ? { author: maskSlurs(out.author, red.slurs).text } : {}) }; return out; } /** * A post item's words with every SLUR masked (post-slurs.mjs maskSlurs) as * the filter's `visual` draws them: its words, its author's name, the repost * line's, the posts it answers and quotes (their words, a paraphrase, their * names). Handles are left as they are (they are what the card's rules match * on). A copy; the entry itself when the filter is off. */ export function slurEntry(entry, slurs) { if (!slursOn(slurs) || !isObj(entry)) return entry; const m = (v) => (typeof v === "string" ? maskSlurs(v, slurs).text : v); const ref = (r) => (isObj(r) ? { ...r, ...("author" in r ? { author: m(r.author) } : {}), ...("text" in r ? { text: m(r.text) } : {}), ...("paraphrase" in r ? { paraphrase: m(r.paraphrase) } : {}) } : r); const out = { ...entry, text: m(entry.text) }; if ("author" in out) out.author = m(out.author); if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: m(entry.repostedBy.author) }; if (Array.isArray(entry.parents)) out.parents = entry.parents.map(ref); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted); if (Array.isArray(entry.links)) out.links = entry.links.map((r) => (isObj(r) && "transcript" in r ? { ...ref(r), transcript: m(r.transcript) } : ref(r))); if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, m); return out; } /** * A screens list (post-screens.mjs) with each line's words, its speaker, its time and the title passed through `m` (a * copy) -- and each EXCERPT the same way, so it is still a run of its line's words as drawn (else the card would have * to draw the whole line: it draws none, and the build refuses -- screenDrawErrors). */ function screensMarked(screens, m) { return screens.map((sc) => (isObj(sc) && Array.isArray(sc.lines) ? { ...sc, ...("title" in sc ? { title: m(sc.title) } : {}), lines: sc.lines.map((l) => (isObj(l) ? { ...l, ...("text" in l ? { text: m(l.text) } : {}), ...("who" in l ? { who: m(l.who) } : {}), ...("time" in l ? { time: m(l.time) } : {}) } : l)), ...(Array.isArray(sc.read) ? { read: sc.read.map((x) => (isObj(x) && typeof x.text === "string" ? { ...x, text: m(x.text) } : x)) } : {}), } : sc)); } // --------------------------------------------------------------------------- // What is SAID and what a line of text SHOWS, the redaction and the slur filter together. // --------------------------------------------------------------------------- /** "@grok" -> "at grok", "@Some_One" -> "at Some One": a handle in the words, as a voice says it. */ export const sayHandles = (text) => str(text).replace(/(^|[\s("'“])@([A-Za-z0-9_]{1,30})\b/g, (_, pre, h) => `${pre}at ${h.replace(/_+/g, " ").trim()}`); /** * The words a voice is asked to SAY for `text` (a post item's script): every * redacted term left out, and each slur as the filter's voice has it -- skip, * left out as a redacted term is; placeholder, its stand-in said ("f-slur"); * beep, said (the render lays the beep over it by the take's word timings, * post-render.mjs). Returns `{ text, slurs, lexicon? }`: `slurs` is what the take's * audio will do with them (take.slurs: "said" | "skip" | "placeholder"), null * when the text holds none; `lexicon` the pronunciation entries applied * (post-say.mjs, `red.say`), present only when one was -- what the take records. * * The LEXICON is applied first, but never inside a slur (whatever the filter's * voice) or a redacted term: those spans keep their words for the filter and * the redaction, which then run over the result -- so a spoken form that says a * slur or a blanked name is masked or dropped too. * * @param {string} text * @param {Record} entry * @param {Redaction|null|undefined} red * @param {{ voice?: "skip"|"beep"|"placeholder" }} [o] the voice to use (default the filter's) * @returns {{ text: string, slurs: "said" | "skip" | "placeholder" | null, lexicon?: Array<{ word: string, say: string, item?: string }>, anonymised?: string[] }} */ export function spokenRead(text0, entry, red, { voice = undefined } = {}) { // AN ANONYMOUS HANDLE (post-anon.mjs; `red.anon`, the project's set: postRedaction.mjs projectRedaction) is said as // its character's shown name, never as written; `anonymised` lists the handles so replaced. const an = red?.anon ? speakAnonymised(str(text0), red.anon) : { text: text0, handles: [] }; const text = an.text; const withAnon = (r) => (an.handles.length ? { ...r, anonymised: an.handles } : r); const s = red?.slurs; const terms = termsFor(entry, red); const lex = Array.isArray(red?.say) && red.say.length && str(text) ? applyLexicon(str(text), red.say, { item: str(entry?.id) || null, protect: [...(s ? slurMatches(str(text), s) : []), ...redactText(str(text), terms).spans] }) : { text: str(text), applied: [] }; const said = (r) => withAnon(lex.applied.length ? { ...r, lexicon: lex.applied } : r); // A handle left inside the sentence (speakableText keeps those; the lexicon may have said it its own way) is said "at ". const t = sayHandles(lex.text); const hits = s ? slurMatches(t, s) : []; if (!hits.length) return said({ text: spokenWithout(t, terms), slurs: null }); const v = voice ?? s.voice; if (!slursOn(s) || v === "beep") return said({ text: spokenWithout(t, terms), slurs: "said" }); if (v === "placeholder") { let out = ""; let at = 0; for (const h of hits) { out += t.slice(at, h.start) + sayFor(s, h); at = h.end; } return said({ text: spokenWithout(out + t.slice(at), terms), slurs: "placeholder" }); } const marked = redactText(t, terms, { spans: hits }); return said({ text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }); } /** * A line of text as published (an attachment's burnt-in caption): a * redacted term left out; a slur, blacked out, left out too, or drawn as its * mask (placeholder). */ export function shownLine(text, entry, red) { const r = redactText(text, termsFor(entry, red)); const masked = slursOn(red?.slurs) ? maskSlurs(r.text, red.slurs).text : r.text; return masked === str(text) ? str(text) : dropMarks(masked); } /** The redaction's mark is the blackout's (post-slurs.mjs draws a blacked-out slur with the redaction's bar). */ export const MARKS_AGREE = BLACKOUT_MARK === REDACT_MARK;