// THE POSTS LIBRARY, ASKED OF THE EDITOR (lane posts-library). One set of // calls for umtool's Posts library page (through lib/articles/generation.ts // askEditor) and for `umtool library` (through editorAsker below): the // listing (GET /api/ops/trending) and the presses (judge-trending, // watch-trending, purge-trending; lane x-trending-publish: organise-trending, // publish-trending and, for an account, x-search-lead's archive). // // UMTOOL WRITES NOTHING OF A LIBRARY AND ASKS X NOTHING. Every press is the // editor's action; a keep's capture is the editor's paced job. This module // reads no file of the corpus. // // `ask(route, {method?, body?})` answers the editor's JSON and throws an Error // carrying its words when it refuses or cannot be reached. // // Plain ESM, no imports. export const JUDGE_CHUNK = 500; export const LIST_PAGE_MAX = 500; export const LIBRARY_STATES = ["unjudged", "keep", "drop", "later"]; export const JUDGE_STATES = ["keep", "drop", "later", "undecided"]; /** * The query of one listing ask. * @param {{ slug: string, topic?: string|null, limit?: number, offset?: number, state?: string|null, gone?: boolean, media?: boolean, author?: string|null, q?: string|null, since?: string|null, by?: string|null, seen?: Record|null, ids?: boolean, detail?: boolean }} p */ export function libraryQuery(p) { const q = new URLSearchParams({ slug: p.slug }); if (p.topic) q.set("topic", p.topic); if (p.limit) q.set("limit", String(p.limit)); if (p.offset) q.set("offset", String(p.offset)); if (p.state) q.set("state", p.state); if (p.gone) q.set("gone", "1"); if (p.media) q.set("media", "1"); if (p.author) q.set("author", p.author); if (p.q && p.q.trim()) q.set("q", p.q.trim()); if (p.since) q.set("since", p.since); if (p.by) q.set("by", p.by); // The topics' Mark seen times: with detail, every topic's new posts come back in this one read. if (p.seen && p.detail) q.set("seen", JSON.stringify(p.seen)); if (p.ids) q.set("ids", "1"); if (p.detail) q.set("detail", "1"); return `/api/ops/trending?${q.toString()}`; } /** Every library the editor holds: [{slug, name, topics, posts, unjudged}]. */ export async function listLibraries(ask) { const answer = await ask("/api/ops/trending"); return Array.isArray(answer.libraries) ? answer.libraries : []; } /** One listing ask (libraryQuery's parameters). */ export function listLibrary(ask, params) { return ask(libraryQuery(params)); } /** Every id matching a filter, in listing order. */ export async function listLibraryIds(ask, params) { const answer = await ask(libraryQuery({ ...params, ids: true, detail: false, limit: undefined, offset: undefined })); return Array.isArray(answer.ids) ? answer.ids : []; } /** Every row matching a filter, with detail, a page at a time. */ export async function listLibraryRows(ask, params) { const rows = []; for (let offset = 0; ; offset += LIST_PAGE_MAX) { const answer = await ask(libraryQuery({ ...params, detail: true, ids: false, limit: LIST_PAGE_MAX, offset })); const page = Array.isArray(answer.posts) ? answer.posts : []; rows.push(...page); if (page.length < LIST_PAGE_MAX || rows.length >= (answer.total ?? 0)) break; } return rows; } /** * Judge, at most JUDGE_CHUNK per ask (the editor's limit). Each chunk's keeps * are ONE capture job, started by the editor's action: never a job per post. * * A LATER CHUNK THAT FAILS IS NOT A SILENT PARTIAL: what the chunks before it * wrote is written, so the answer carries it with `failed` — the editor's * words, and how many of the set were never asked. (The first chunk failing * wrote nothing: it throws, as any refusal does.) * @param {{ slug: string, by: "agent"|"operator", set: Array<{id?: string, thread?: string, state: string, note?: string}>, archive?: boolean }} p * @returns {Promise<{ written: object[], skipped: object[], kept: string[], archives: object[], asks: number, failed?: { error: string, asked: number, unasked: number } }>} */ export async function judge(ask, p) { const out = { written: [], skipped: [], kept: [], archives: [], asks: 0 }; for (let i = 0; i < p.set.length; i += JUDGE_CHUNK) { let answer; try { answer = await ask("/api/ops/judge-trending", { method: "POST", body: { slug: p.slug, by: p.by, set: p.set.slice(i, i + JUDGE_CHUNK), ...(p.archive === false ? { archive: false } : {}) }, }); } catch (err) { if (i === 0) throw err; out.failed = { error: err instanceof Error ? err.message : String(err), asked: i, unasked: p.set.length - i }; return out; } out.asks++; out.written.push(...(answer.written ?? [])); out.skipped.push(...(answer.skipped ?? [])); out.kept.push(...(answer.kept ?? [])); if (answer.archive) out.archives.push(answer.archive); } return out; } /** The watch's switch, the library's settings, or one scan: watch-trending's body, as given. */ export function watch(ask, body) { return ask("/api/ops/watch-trending", { method: "POST", body }); } /** purge-trending's body, as given ({slug, dryRun: true, …} or {slug, confirm, by: "operator", …}). */ export function purge(ask, body) { return ask("/api/ops/purge-trending", { method: "POST", body }); } /** organise-trending's body, as given ({slug, op: "rename" | "move" | "merge", …, by}) (lane x-trending-publish). */ export function organise(ask, body) { return ask("/api/ops/organise-trending", { method: "POST", body }); } /** publish-trending's body, as given ({slug, topic, dryRun: true, channel?} or {slug, topic, confirm, by: "operator"}). */ export function publish(ask, body) { return ask("/api/ops/publish-trending", { method: "POST", body }); } /** * A library's accounts: { accounts: [{handle, name?, posts, kept, keptByOperator, topics, last, archivedAs?}], total, posts, more }. * @param {(route: string, init?: object) => Promise} ask * @param {{ slug: string, topic?: string | null, limit?: number }} p */ export function listAccounts(ask, { slug, topic, limit }) { const q = new URLSearchParams({ slug, accounts: "1" }); if (topic) q.set("topic", topic); if (limit) q.set("limit", String(limit)); return ask(`/api/ops/trending?${q.toString()}`); } /** * "Archive this account": the editor's x-search-lead, action "archive", for an account of the library — * `-x` on no site. FROM A LIBRARY IT ASKS X NOTHING: `fetch` is sent only when it is true. * @param {{ slug: string, handle: string, name?: string, dryRun?: boolean, fetch?: boolean }} p */ export function archiveAccount(ask, p) { return ask("/api/ops/x-search-lead", { method: "POST", body: { slug: p.slug, handle: p.handle, action: "archive", ...(p.name ? { name: p.name } : {}), ...(p.dryRun ? { dryRun: true } : {}), ...(p.fetch === true ? { fetch: true } : {}) }, }); } /** * What became of the keeps' archiving, as one sentence (or "" when nothing was kept). * @param {{ kept: string[], archives: Array<{jobId?: string, error?: string, ids: string[]}> }} r */ export function archiveSentence(r) { if (!r.kept.length) return ""; const started = r.archives.filter((a) => a.jobId); const refused = r.archives.filter((a) => a.error); const n = (k) => `${k} post${k === 1 ? "" : "s"}`; const parts = []; if (started.length) parts.push(`${n(started.reduce((s, a) => s + a.ids.length, 0))} queued for archiving (the editor's capture job${started.length === 1 ? "" : "s"} ${started.map((a) => a.jobId).join(", ")})`); if (refused.length) parts.push(`${n(refused.reduce((s, a) => s + a.ids.length, 0))} kept but not archived now: ${refused[0].error}`); if (!parts.length) parts.push(`${n(r.kept.length)} kept, not archived now`); return parts.join("; ") + "."; } /** * An asker for a process with no Next around it (the CLI): the editor's URL * and the shared token, the editor's refusals as Errors with its words. * @param {{ editorUrl: string, token: string, doFetch?: typeof fetch, timeoutMs?: number }} o */ export function editorAsker({ editorUrl, token, doFetch = fetch, timeoutMs = 30_000 }) { const base = String(editorUrl).replace(/\/+$/, ""); return async (route, init = {}) => { if (!token) throw new Error("WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with."); let res; try { res = await doFetch(`${base}${route}`, { method: init.method ?? "GET", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { throw new Error(`could not reach the editor at ${base}: ${err?.message ?? err}`); } const body = await res.json().catch(() => ({})); if (!res.ok || body.ok === false) throw new Error(String(body.error ?? `the editor answered HTTP ${res.status}`)); return body; }; }