// A POST ITEM's CONTEXT FROM ITS CAPTURE (umtool/docs/report-video.md, "Post // items"): the post it quotes and the post it answers, as the post's page // showed them -- `capture.json`'s `context`, read by the editor's // capture-posts (common/social/xPostContext.ts) -- filled into the entry when // the archive row lacks them. // // The archive often does: an X timeline read kept no quote until the fetcher // asked for it, and a reply's parent is another account's post, never // archived with the account's own. So a post item that the archive gives no // `quoted` (or one with no words) and no `parents` takes the capture's: // // quoted <- context.quoted { id?, author?, handle?, badge?, date?, text, url? } // parents <- [context.parent] (the post it answers; the capture reads one) // // SNAPSHOTTED like the rest of the entry: written into it when it is made // (postReel.mjs postEntryFrom -- `posts reel`, `timeline insert post:`) or // refreshed (`umtool posts context `, every post item at once, one // write). What the archive gives is never replaced: the capture only fills // what is missing, and a ref the archive names is only completed by a context // post that is the same post (its id, else its author). The card's own rule // (post-item.mjs authorRedaction) decides whose name and face it shows -- a // parent or a quoted author who is not the subject is blurred unless gold- or // grey-checked; the badge the capture read is what it decides by. // // Plain ESM: the CLI runs it under bare node. // // A STATUS LINK IS A QUOTE (operator, 4 Nov: a post that embeds another by // its link, not X's quote): a post item with no quoted post whose words (or // its archive row's links) carry an x.com / twitter.com status link takes the // post it names as its `quoted` (`via: "link"`) when any channel's posts // archive holds it (read lazily, only for a link), else the capture's. The // same pass snapshots the row's `threadId` as the entry's `conversation` // (post-conversation.mjs reads a conversation by it). import { isTrendingLibrary } from "./xTrendingMarker.mjs"; import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; import { joinSplitLinks } from "umtool-report-to-video/post-narration"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, setPostItemsContext } from "./manifest.mjs"; import { findPostRow } from "./postsCli.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; const BADGES = new Set(["blue", "gold", "grey", "other"]); /** The longest context text a ref takes (post-item.mjs refuses past 25,000). */ const TEXT_MAX = 10000; const POST_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; /** * A post item ref from a capture's context post, kept to the shape the * validator takes; null for nothing usable (no author and no words). */ export function contextRefOf(p) { if (!isObj(p)) return null; const handle = str(p.handle).replace(/^@/, ""); const text = str(p.text).slice(0, TEXT_MAX); const okHandle = HANDLE_RE.test(handle) ? handle : ""; if (!okHandle && !text.trim()) return null; const id = ID_RE.test(str(p.id)) ? str(p.id) : ""; const url = /^https?:\/\//.test(str(p.url)) ? p.url : ""; const date = str(p.date) && Number.isFinite(Date.parse(p.date)) ? p.date : ""; return { ...(id ? { id } : {}), ...(str(p.author) ? { author: str(p.author).slice(0, 200) } : {}), ...(okHandle ? { handle: okHandle } : {}), ...(BADGES.has(p.badge) ? { badge: p.badge } : {}), ...(date ? { date } : {}), text, ...(url ? { url } : {}), }; } const sameHandle = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase(); /** Whether `ref` (the archive's) and `ctx` (the capture's) are the same post: their ids, else their authors. */ export function sameRef(ref, ctx) { if (str(ref?.id) && str(ctx?.id)) return String(ref.id) === String(ctx.id); if (str(ref?.handle) && str(ctx?.handle)) return sameHandle(ref.handle, ctx.handle); return !str(ref?.id) && !str(ref?.handle); } /** `ref` completed from `ctx`: every field the archive gave kept, the rest the capture's. */ function completed(ref, ctx) { const out = { ...ctx }; for (const [k, v] of Object.entries(ref)) if (v !== undefined && v !== null && v !== "") out[k] = v; return out; } /** * FILL `entry` (a post item, mutated) from its capture's `context`: the * quoted post where the entry has none (or one with no words, the same post), * the post it answers where it has no parents. Returns what it filled: * a subset of ["quoted", "parents"]. */ export function applyCaptureContext(entry, context) { const filled = []; if (!isObj(entry) || !isObj(context)) return filled; const q = contextRefOf(context.quoted); if (q) { if (!isObj(entry.quoted)) { entry.quoted = q; filled.push("quoted"); } else if (!str(entry.quoted.text).trim() && sameRef(entry.quoted, q)) { entry.quoted = completed(entry.quoted, q); filled.push("quoted"); } } const p = contextRefOf(context.parent); if (p) { const parents = Array.isArray(entry.parents) ? entry.parents.filter(isObj) : []; if (!parents.length) { entry.parents = [p]; filled.push("parents"); } else if (!str(parents[0].text).trim() && sameRef(parents[0], p)) { entry.parents = [completed(parents[0], p), ...parents.slice(1)]; filled.push("parents"); } } return filled; } /** An x.com / twitter.com status link: its handle and the post's id. */ const STATUS_RE = /https?:\/\/(?:www\.|mobile\.)?(?:x|twitter)\.com\/([A-Za-z0-9_]{1,30})\/status(?:es)?\/(\d{5,25})/gi; /** * The status links in a post's words (X's split links put back first) and in * its archive row's `links`, in order, each once: `[{ handle, id }]`. Pure. */ export function statusLinksOf(text, links = []) { const out = []; const seen = new Set(); const from = [joinSplitLinks(str(text)), ...(Array.isArray(links) ? links.map((l) => (typeof l === "string" ? l : str(l?.url) || str(l?.expanded))) : [])]; for (const t of from) { for (const m of t.matchAll(STATUS_RE)) { if (seen.has(m[2])) continue; seen.add(m[2]); out.push({ handle: m[1], id: m[2] }); } } return out; } /** A post item ref from an archive row (postsCli.mjs findPostRow's), `via: "link"`; null for nothing usable. */ export function refFromRow(row) { if (!isObj(row)) return null; const ref = contextRefOf({ id: str(row.id), author: str(row.authorName), handle: str(row.author), date: str(row.createdAt), text: str(row.text), url: str(row.url) }); return ref ? { ...ref, via: "link" } : null; } /** * A RESOLVER of status ids to archived posts across every channel's posts * archive (`channels//posts/*.jsonl`), lazy: the channels are listed on * the first call, a channel named for the link's handle read first, each id * looked up once. */ export function statusResolver(channelsDir) { let slugs = null; const cache = new Map(); return async function resolve({ handle, id }) { if (cache.has(id)) return cache.get(id); if (slugs === null) { const names = await readdir(channelsDir).catch(() => []); slugs = []; // Never an X trending library: a link must not resolve to a private one. for (const n of names) if (POST_KEY_RE.test(n) && !(await isTrendingLibrary(channelsDir, n)) && (await stat(path.join(channelsDir, n, "posts")).catch(() => null))?.isDirectory()) slugs.push(n); } const h = str(handle).toLowerCase(); const order = [...slugs.filter((s) => h && s.toLowerCase().startsWith(h)), ...slugs.filter((s) => !(h && s.toLowerCase().startsWith(h)))]; let row = null; for (const slug of order) { const hit = await findPostRow(channelsDir, slug, id).catch(() => null); if (hit?.row) { row = hit.row; break; } } cache.set(id, row); return row; }; } /** * The `context` of a post's capture (`channels//posts-media//capture.json`), * or null when there is no capture or it read none. */ export async function readCaptureContext(channelsDir, slug, postId) { if (!POST_KEY_RE.test(slug) || !ID_RE.test(String(postId)) || postId === "_avatars") return null; try { const cap = JSON.parse(await readFile(path.join(channelsDir, slug, "posts-media", String(postId), "capture.json"), "utf8")); return isObj(cap?.context) ? cap.context : null; } catch { return null; } } /** The ops call that reads the context of `ids` (one channel's), ready to paste. */ export function contextCaptureCall(slug, ids) { return `pnpm ops capture-posts --json '${JSON.stringify({ slug, ids, contextOnly: true })}' --wait`; } /** * REFRESH EVERY POST ITEM's CONTEXT from its capture (`umtool posts context * `): each post item whose capture read a context it lacks gets it, * in ONE write (one undo point), refused whole in the build's words. * `dryRun`: nothing written. A post whose capture read none is listed with * the capture-posts call that reads it (`missing`, by channel). * * @param {{ id: string, dir: string }} project * @param {{ channelsDir?: string | null, dryRun?: boolean }} [o] */ export async function postsContext(project, { channelsDir = null, dryRun = false } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new Error(`${project.id} has no manifest`); const dir = channelsDir ?? channelsDirFor(project.dir, manifest); const items = (Array.isArray(manifest.timeline) ? manifest.timeline : []).filter((e) => e?.type === "post" && typeof e.post === "string"); /** @type {Record} */ const patches = {}; const report = []; /** @type {Map} */ const missing = new Map(); const resolve = statusResolver(dir); for (const e of items) { const [slug, rowId] = e.post.split("/"); // A repost is drawn as its original: the original's capture first. const shownId = str(e.originalId) || rowId; const context = (await readCaptureContext(dir, slug, shownId)) ?? (shownId !== rowId ? await readCaptureContext(dir, slug, rowId) : null); const copy = structuredClone(e); const filled = context ? applyCaptureContext(copy, context) : []; // Its archive row: the conversation it is part of, and the links its words carry. const row = ID_RE.test(String(shownId)) ? (await findPostRow(dir, slug, String(shownId)).catch(() => null))?.row ?? null : null; // A status link is a quote, when it has none (or one with no words): the post it names, archived anywhere. if (!isObj(copy.quoted) || !str(copy.quoted.text).trim()) { for (const link of statusLinksOf(e.text, row?.links)) { if (link.id === shownId || link.id === rowId) continue; const ref = refFromRow(await resolve(link)); if (!ref) continue; copy.quoted = isObj(copy.quoted) && sameRef(copy.quoted, ref) ? completed(copy.quoted, ref) : ref; if (!filled.includes("quoted")) filled.push("quoted"); break; } } const conv = str(row?.threadId); if (!str(e.conversation) && ID_RE.test(conv)) { copy.conversation = conv; filled.push("conversation"); } if (!context && !filled.length) { report.push({ id: e.id, post: e.post, state: "no-context" }); if (!missing.has(slug)) missing.set(slug, []); missing.get(slug).push(shownId); continue; } if (!filled.length) { report.push({ id: e.id, post: e.post, state: "complete" }); continue; } patches[e.id] = { ...(filled.includes("quoted") ? { quoted: copy.quoted } : {}), ...(filled.includes("parents") ? { parents: copy.parents } : {}), ...(filled.includes("conversation") ? { conversation: copy.conversation } : {}), }; report.push({ id: e.id, post: e.post, state: "filled", filled, ...patches[e.id] }); } const summary = { items: items.length, filled: Object.keys(patches).length, complete: report.filter((r) => r.state === "complete").length, noContext: report.filter((r) => r.state === "no-context").length, channelsDir: dir, report, missing: [...missing].map(([slug, ids]) => ({ slug, ids, call: contextCaptureCall(slug, ids) })), }; if (dryRun || !summary.filled) return { ...summary, dryRun: dryRun === true, result: null, editNotes: null }; const { result, editNotes } = await withEditNotes(project, async () => setPostItemsContext(project.dir, patches, { token: await manifestToken(project.dir) }), ); return { ...summary, dryRun: false, result, editNotes }; }