// The editor's X trending library, stubbed for umtool's Posts library page // (library.spec.ts; lane posts-library): GET /api/ops/trending with the judge // view's asks, and the presses — judge-trending, watch-trending, // purge-trending, and (lane x-trending-publish) organise-trending, // publish-trending and x-search-lead's archive — over an invented library held in memory // (library-fixture.mjs libraryState). Every press is RECORDED with the `by` // it carried, which is the part no page shows. // // POST /__stub/trending {reset?: true, mode?: "ok" | "unreachable" | "none"} // "unreachable": every trending route drops the connection (the editor is down); // "none": the editor holds no library // GET /__stub/trending -> { mode, requests, reads, judgements, captured, watches, topics, published, archived } // `reads`: how many times the listing was asked (GET /api/ops/trending) since the reset // // Nothing here asks X, or any host, anything. import { createHash } from "node:crypto"; import { libraryState } from "./library-fixture.mjs"; const fresh = () => ({ ...libraryState(), published: {}, archived: {} }); let state = fresh(); let mode = "ok"; let requests = []; let reads = 0; let jobs = 0; const NOW = "2026-11-18T09:00:00.000Z"; // Lane x-trending-publish: organise-trending, publish-trending and the lead action's archive. const ROUTES = ["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending", "/api/ops/organise-trending", "/api/ops/publish-trending", "/api/ops/x-search-lead"]; const effective = (p) => { const own = state.judgements.posts[p.id]; const thread = state.judgements.threads[p.thread]; // The operator's entry outranks an agent's; between two of one hand, the post's own. if (own && thread) return own.by === "agent" && thread.by === "operator" ? { ...thread, from: "thread" } : own; return own ?? (thread ? { ...thread, from: "thread" } : undefined); }; function watchSentence(w) { if (!w) return undefined; if (w.ended) return w.ended.sentence; const every = `every ${w.intervalMinutes} min until 10:00 UTC${w.shots ? ", screenshotting every new post" : ""}`; if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since 12:00 UTC, until the operator switches it on again: ${w.paused.sentence}`; if (w.paused) return `Watched ${every} — PAUSED since 12:00 UTC: ${w.paused.sentence}`; return `Watched ${every}; ${w.ticks} ticks so far, next at the next scan.`; } function captureFiles(p) { if (!state.captured.includes(p.id)) return undefined; const media = []; if (p.kinds.includes("image")) media.push({ name: `${p.id}_1.jpg`, kind: "image", bytes: 68 }); if (p.kinds.includes("video")) media.push({ name: `${p.id}_2.mp4`, kind: "video", bytes: 58 }); return { shot: "shot.png", ...(p.context ? { threadShot: "shot-thread.png", context: p.context } : {}), media }; } function row(p, detail) { const judgement = effective(p); const captured = state.captured.includes(p.id); return { id: p.id, author: p.author, authorName: p.authorName, createdAt: p.createdAt, url: p.url, text: p.text, media: { count: p.mediaCount, kinds: p.kinds }, topic: p.topic, reads: [{ read: "tr-01JA0000000000000000000000", trendId: "1900000000000000001", at: p.firstSeenAt }], ...(p.gone ? { gone: p.gone } : {}), ...(p.goneTabs ? { goneTabs: p.goneTabs } : {}), ...(p.capture && (captured || p.capture.state !== "captured") ? { capture: { ...p.capture, shot: captured, files: captureFiles(p)?.media.length ?? 0 } } : {}), thread: p.thread, ...(judgement ? { judgement } : {}), ...(detail ? { detail: { post: { isReply: p.isReply === true, isRepost: false, ...(p.replyTo ? { replyTo: p.replyTo } : {}), links: [], ...(p.mediaCount ? { mediaCount: p.mediaCount } : {}) }, firstSeenAt: p.firstSeenAt, ...(state.judgements.posts[p.id] ? { ownJudgement: state.judgements.posts[p.id] } : {}), ...(state.judgements.threads[p.thread] ? { threadJudgement: state.judgements.threads[p.thread] } : {}), ...(captureFiles(p) ? { capture: captureFiles(p) } : {}), }, } : {}), }; } function listing(sp) { const topic = topicOf(sp.get("topic"))?.id ?? sp.get("topic"); const detail = sp.get("detail") === "1"; const words = (sp.get("q") ?? "").toLowerCase().split(/\s+/).filter(Boolean); const author = sp.get("author")?.replace(/^@/, "").toLowerCase() ?? null; const since = sp.get("since"); const stateOf = (p) => effective(p)?.state ?? "unjudged"; const inTopic = state.posts.filter((p) => !topic || p.topic === topic); const rows = inTopic.filter( (p) => (!sp.get("state") || stateOf(p) === sp.get("state")) && (sp.get("gone") !== "1" || p.gone) && (sp.get("media") !== "1" || p.mediaCount > 0) && (author === null || p.author.toLowerCase() === author) && (!since || p.firstSeenAt > since) && words.every((w) => `${p.text} ${p.author} ${p.authorName}`.toLowerCase().includes(w)), ); const seen = detail && sp.get("seen") ? JSON.parse(sp.get("seen")) : null; const offset = Number(sp.get("offset") ?? 0); const limit = Number(sp.get("limit") ?? 100); const authors = new Map(); for (const p of inTopic) authors.set(p.author, (authors.get(p.author) ?? 0) + 1); return { ok: true, slug: state.slug, name: state.name, topics: state.topics.map((t) => { const mine = state.posts.filter((p) => p.topic === t.id); const counts = { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 }; for (const p of mine) { counts[stateOf(p)]++; if (p.gone) counts.gone++; } const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null; const pub = detail ? state.published?.[t.id] : undefined; return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: t.sources ?? [] }; }), posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), total: rows.length, reads: [], ...(detail ? { authors: [...authors].map(([a, n]) => ({ author: a, posts: n })).sort((a, b) => b.posts - a.posts || (a.author < b.author ? -1 : 1)) } : {}), ...(sp.get("ids") === "1" ? { ids: rows.map((p) => p.id) } : {}), }; } // ── lane x-trending-publish ──────────────────────────────────────────────── /** A topic by its id, the id of one merged into it, or its name. */ function topicOf(name) { if (!name) return undefined; return state.topics.find((t) => t.id === name) ?? state.topics.find((t) => t.aliases?.includes(name)) ?? state.topics.find((t) => t.title.toLowerCase() === String(name).toLowerCase()); } const slugOf = (title) => title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); const live = (w) => !!w && w.on && !w.ended; const none = (name) => ({ ok: false, error: `This library has no topic "${name}" (its topics: ${state.topics.map((t) => t.id).join(", ")}).` }); // The editor's rules (common/lib/xTrending/organise.ts): a rename keeps the id; a move changes a post's topic; // a merge is the operator's, keeps the merged ids as aliases and ONE watch (the target's when it is live). function organise(body) { if (body.by !== "agent" && body.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; if (body.op === "rename") { const topic = topicOf(body.topic); if (!topic) return none(body.topic); // The editor's refusal while a read of the library is queued or running (review 1 S9). if (state.reading) return { ok: false, error: "A read of this library is queued or running: rename its topic once it has finished (its job is on /jobs). A read names its topic, by id or by name, and a name changed under it could send its posts to a new topic." }; const other = state.topics.find((t) => t !== topic && (t.id === body.title || t.title.toLowerCase() === String(body.title).toLowerCase())); if (other) return { ok: false, error: `Topic "${other.title}" (${other.id}) already answers to "${body.title}": a topic's name is its own. Merge the two, or choose another name.` }; const was = topic.title; topic.title = String(body.title).trim(); return { ok: true, slug: state.slug, op: "rename", topic: topic.id, title: topic.title, was, changed: was !== topic.title, sentence: `Topic "${was}" is now "${topic.title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }; } if (body.op === "move") { let to = topicOf(body.to); let created = false; if (!to) { if (!body.create) return { ok: false, error: `${none(body.to).error} To move posts into a new topic, say "create": true.` }; to = { id: slugOf(body.to), title: body.to }; state.topics.push(to); created = true; } const wanted = body.thread ? state.posts.filter((p) => p.thread === body.thread).map((p) => p.id) : body.ids ?? []; const moved = []; const skipped = []; for (const pid of wanted) { const p = state.posts.find((x) => x.id === pid); if (!p) skipped.push({ id: pid, reason: "not in this library" }); else if (p.topic === to.id) skipped.push({ id: pid, reason: `already in "${to.title}"` }); else { p.movedFrom = p.topic; p.movedBy = body.by; p.topic = to.id; moved.push(pid); } } return { ok: true, slug: state.slug, op: "move", to: { id: to.id, title: to.title, created }, moved, skipped, sentence: `${moved.length} post${moved.length === 1 ? "" : "s"} moved to "${to.title}".${skipped.length ? ` ${skipped.length} post${skipped.length === 1 ? "" : "s"} skipped: ${skipped[0].reason}.` : ""}${moved.length ? " Their judgements and captures are untouched." : ""}` }; } if (body.op === "merge") { if (body.by !== "operator") return { ok: false, error: "Merging topics is the operator's press: it cannot be undone (there is no unmerge)." }; const into = topicOf(body.into); if (!into) return none(body.into); const from = []; for (const name of body.from ?? []) { const t = topicOf(name); if (!t) return none(name); if (t === into) return { ok: false, error: `"${name}" is the topic that stays ("${into.title}"): a topic is not merged into itself.` }; from.push(t); } const merged = from.map((t) => ({ id: t.id, title: t.title, posts: state.posts.filter((p) => p.topic === t.id).length, pages: 1 })); let watchSentence = ""; const dropped = []; for (const t of from) { for (const p of state.posts) if (p.topic === t.id) p.topic = into.id; if (live(t.watch)) { if (live(into.watch)) dropped.push(t.title); else { into.watch = t.watch; watchSentence = ` The watch of "${t.title}" is now the watch of "${into.title}".`; } } into.aliases = [...(into.aliases ?? []), t.id, ...(t.aliases ?? [])]; state.topics.splice(state.topics.indexOf(t), 1); } if (dropped.length) watchSentence = ` The watch of "${into.title}" stands with its own terms. The watch of ${dropped.map((d) => `"${d}"`).join(", ")} is gone: one topic has one watch.`; const posts = merged.reduce((n, m) => n + m.posts, 0); return { ok: true, slug: state.slug, op: "merge", into: { id: into.id, title: into.title }, merged, posts, pages: 1 + merged.length, watch: { dropped }, sentence: `${merged.map((m) => `"${m.title}"`).join(", ")} ${merged.length === 1 ? "is" : "are"} now part of "${into.title}": ${posts} post${posts === 1 ? "" : "s"} moved. The judgements are untouched. This cannot be undone.${watchSentence}` }; } return { ok: false, error: `"op" is "rename", "move" or "merge"` }; } // The editor's rule (common/controller/publishXTrending.ts): the posts KEPT BY THE OPERATOR, in two steps held // by a digest; the slug fixed at the first publish; a re-publish adds and removes nothing. function publish(body) { const topic = topicOf(body.topic); if (!topic) return { ok: false, error: `${state.slug} has no topic "${body.topic}"` }; const record = state.published[topic.id]; if (record && body.channel !== undefined && body.channel !== record.channel) return { ok: false, error: `"${topic.title}" is published into the channel "${record.channel}": a topic has one channel, fixed at its first publish.` }; const channel = record?.channel ?? body.channel ?? slugOf(topic.title); const kept = state.posts.filter((p) => p.topic === topic.id && effective(p)?.state === "keep" && effective(p).by === "operator"); if (kept.length === 0) return { ok: false, error: `The operator has kept no post in "${topic.title}": there is nothing to publish. (An agent's keep is a suggestion and is not published.)` }; const have = new Set(record?.posts ?? []); const fresh = kept.filter((p) => !have.has(p.id)); const files = fresh.reduce((n, p) => n + (state.captured.includes(p.id) ? 1 + (captureFiles(p)?.media.length ?? 0) : 0), 0); const textOnly = kept.filter((p) => !state.captured.includes(p.id)).map((p) => p.id); const noLongerKept = [...have].filter((pid) => !kept.some((p) => p.id === pid)); const confirm = createHash("sha256").update(JSON.stringify([state.slug, topic.id, channel, fresh.map((p) => p.id).sort(), state.sites?.[channel] ?? []])).digest("hex").slice(0, 24); const answer = { ok: true, slug: state.slug, library: state.slug, topic: { id: topic.id, title: topic.title }, channel, creates: !record, kept: kept.length, posts: fresh.length, ids: fresh.map((p) => p.id), already: kept.length - fresh.length, files, bytes: files * 68, textOnly, noLongerKept, sites: state.sites?.[channel] ?? [], movedIn: fresh.filter((p) => p.movedBy).map((p) => ({ id: p.id, by: p.movedBy, from: p.movedFrom })), mismatched: [], confirm }; const n = (k, what) => `${k} ${what}${k === 1 ? "" : "s"}`; const onSites = answer.sites.length && fresh.length ? ` THIS CHANNEL IS ON THE SITE ${answer.sites.join(", ")}: ${fresh.length === 1 && files === 0 ? "this post goes" : "these posts go"} public at its next build.` : ""; const say = (would) => `${sayHead(would)}${onSites}`; const sayHead = (would) => fresh.length === 0 && record ? `Nothing to add: the channel "${channel}" already holds the ${n(kept.length, "post")} the operator kept in "${topic.title}".` : `Publishing "${topic.title}" ${record ? (would ? "would add to" : "added to") : would ? "would make" : "made"} the channel "${channel}"${record ? "" : ", on no site,"} ${would ? "writing" : "and wrote"} ${n(fresh.length, "post")} and ${n(files, "file")} (${files * 68} B); ${answer.already} of the ${n(kept.length, "kept post")} ${answer.already === 1 ? "is" : "are"} there already.${noLongerKept.length ? ` ${n(noLongerKept.length, "post")} published before ${noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).` : ""}`; if (body.dryRun === true) return { ...answer, dryRun: true, sentence: say(true) }; if (body.by !== "operator") return { ok: false, error: "Publishing a topic is the operator's press: an agent may ask for the dry run" }; if (body.confirm !== confirm) return { ok: false, error: "What would be published has changed since it was counted (a post kept or dropped, a capture finished, a post moved): nothing was written. Ask for the dry run again." }; state.published[topic.id] = { channel, posts: [...have, ...fresh.map((p) => p.id)] }; return { ...answer, dryRun: false, sentence: say(false) }; } function accounts(sp) { const topic = topicOf(sp.get("topic"))?.id ?? null; const rows = new Map(); for (const p of state.posts) { if (topic && p.topic !== topic) continue; const row = rows.get(p.author) ?? { handle: p.author, key: p.author.toLowerCase(), name: p.authorName, posts: 0, kept: 0, keptByOperator: 0, topics: [], last: p.createdAt }; row.posts++; const j = effective(p); if (j?.state === "keep") { row.kept++; if (j.by === "operator") row.keptByOperator++; } if (!row.topics.includes(p.topic)) row.topics.push(p.topic); if (state.archived[p.author]) row.archivedAs = [state.archived[p.author]]; rows.set(p.author, row); } const all = [...rows.values()].sort((a, b) => b.posts - a.posts || (a.key < b.key ? -1 : 1)); return { ok: true, slug: state.slug, accounts: all, total: all.length, posts: all.reduce((n, a) => n + a.posts, 0), more: 0 }; } // The lead action's archive, for an account of the library: -x, and NO fetch unless asked. function lead(body) { if (body.action !== "archive") return { ok: false, error: `${state.slug} is not an X search channel (its config has no xSearch query).` }; const handle = String(body.handle ?? "").replace(/^@/, ""); if (!state.posts.some((p) => p.author.toLowerCase() === handle.toLowerCase())) return { ok: false, error: `${state.slug} holds no post by @${handle}: "Archive this account" is for an account in the library.` }; if (state.archived[handle]) return { ok: false, error: `@${handle} is already archived: ${state.archived[handle]}.` }; const slug = `${handle.toLowerCase()}-x`; if (body.dryRun === true) return { ok: true, dryRun: true, slug, fields: { url: `https://x.com/${handle}` } }; state.archived[handle] = slug; if (body.fetch === true) return { ok: true, slug, jobIds: [`stub-fetch-${++jobs}`] }; // The editor's sentence (common/lib/xSearch/leads.ts xLeadSyncOffSentence). return { ok: true, slug, jobIds: [], syncOff: true, sentence: `Made the channel "${slug}" for @${handle}, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. ` + `To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["${slug}"],"tier":"normal"}'). ` + `Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"${slug}"}').`, }; } function judge(body) { const before = new Map(state.posts.map((p) => [p.id, effective(p)?.state])); const written = []; const skipped = []; for (const item of body.set ?? []) { const key = item.id ?? item.thread; const bag = item.id !== undefined ? state.judgements.posts : state.judgements.threads; if (!state.posts.some((p) => (item.id !== undefined ? p.id === key : p.thread === key))) { skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "not a post of the library" }); continue; } if (body.by === "agent" && bag[key]?.by === "operator") { skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "the operator judged it" }); continue; } if (item.state === "undecided") delete bag[key]; else bag[key] = { state: item.state, ...(item.note ? { note: item.note } : {}), by: body.by, at: NOW }; written.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), state: item.state }); } const kept = state.posts.filter((p) => effective(p)?.state === "keep" && before.get(p.id) !== "keep").map((p) => p.id); return { ok: true, slug: state.slug, written, skipped, kept, ...(kept.length && body.archive !== false ? { archive: { jobId: `stub-capture-${++jobs}`, ids: kept } } : {}) }; } function watch(body) { const topic = state.topics.find((t) => t.id === body.topic); if (!topic) return { ok: false, error: `${state.slug} has no topic "${body.topic}"` }; if (body.on && topic.watch?.paused?.reason === "failing" && body.by !== "operator") return { ok: false, error: "This watch is paused as failing: only the operator switches it on again." }; if (!body.on) topic.watch = { ...(topic.watch ?? {}), on: false, ended: { at: NOW, reason: "off", sentence: "Switched off: not watched." } }; else topic.watch = { on: true, intervalMinutes: body.intervalMinutes ?? 30, startedAt: NOW, until: "2026-11-20T10:00:00.000Z", shots: body.shots === true, by: body.by ?? "agent", ticks: 0, failures: 0, nextSource: 0, goneSources: [] }; return { ok: true, slug: state.slug, topic: topic.id, watch: topic.watch, sentence: watchSentence(topic.watch) }; } const digest = (ids) => createHash("sha256").update(JSON.stringify([state.slug, [...ids].sort()])).digest("hex").slice(0, 16); // The editor's rule (common/lib/xTrending/purge.ts): the OPERATOR's drops only; an agent's are counted and // left; the posts gone from the page are named, and the sentence is true of them. function purge(body) { const scoped = state.posts.filter((p) => (!body.topic || p.topic === body.topic) && effective(p)?.state === "drop" && state.captured.includes(p.id)); const mine = scoped.filter((p) => effective(p).by === "operator"); const ids = mine.map((p) => p.id).sort(); const agentDropped = scoped.length - mine.length; const gone = mine.filter((p) => p.gone).map((p) => ({ id: p.id, at: p.gone.at })); const files = ids.reduce((n, pid) => n + 2 + (captureFiles(state.posts.find((p) => p.id === pid))?.media.length ?? 0), 0); const bytes = files * 68; const confirm = digest(ids); const what = `the capture${ids.length === 1 ? "" : "s"} of ${ids.length} dropped post${ids.length === 1 ? "" : "s"}: ${files} file${files === 1 ? "" : "s"}, ${bytes} B`; const agent = agentDropped ? ` ${agentDropped} post${agentDropped === 1 ? "" : "s"} an agent dropped ${agentDropped === 1 ? "is" : "are"} left alone: a purge takes the operator's drops only.` : ""; const only = gone.length ? ` ${ids.length === 1 ? "It is" : `${gone.length} of them ${gone.length === 1 ? "is" : "are"}`} gone from the page: this is the only copy: X no longer showed this post at ${gone[0].at.slice(0, 10)} ${gone[0].at.slice(11, 16)} UTC; removing it cannot be undone.` : ""; const again = ids.length - gone.length > 0 ? ` Keeping ${gone.length ? "the other one" : ids.length === 1 ? "it" : "one of them"} again captures it again.` : ""; const answer = { ok: true, slug: state.slug, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, gone, agentDropped, skipped: [], confirm }; if (body.dryRun === true) { return { ...answer, dryRun: true, sentence: ids.length ? `Would remove ${what}. The judgements stay.${only}${again}${agent}` : `No post the operator dropped has a capture: nothing to remove.${agent}` }; } if (body.by !== "operator") return { ok: false, error: "Removing dropped posts' captures is the operator's press" }; if (body.confirm !== confirm) return { ok: false, error: `The dropped posts with a capture have changed since the dry run (${ids.length} now): nothing was removed. Run the dry run again and confirm what it shows.` }; state.captured = state.captured.filter((pid) => !ids.includes(pid)); return { ...answer, dryRun: false, sentence: `Removed ${what}. The judgements stay.${agent}` }; } /** The spec's door. True when answered. */ export function trendingControl(req, res, url, { json, readBody }) { if (url.pathname !== "/__stub/trending") return false; if (req.method === "GET") { req.resume(); json(res, 200, { mode, requests, reads, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])), topics: state.topics.map((t) => ({ id: t.id, title: t.title, aliases: t.aliases ?? [], posts: state.posts.filter((p) => p.topic === t.id).map((p) => p.id) })), published: state.published, archived: state.archived, }); return true; } readBody(req, (body) => { if (body?.reset === true) { state = fresh(); requests = []; reads = 0; jobs = 0; mode = "ok"; } // What the editor would know and umtool cannot: a read in flight, and the sites a channel is on. if (body?.reading !== undefined) state.reading = body.reading === true; if (body?.sites !== undefined) state.sites = body.sites; if (body?.mode !== undefined) { if (!["ok", "unreachable", "none"].includes(body.mode)) return json(res, 400, { error: `mode "${body.mode}" is not one of ok, unreachable, none` }); mode = body.mode; } json(res, 200, { ok: true, mode }); }); return true; } /** The editor's trending routes (behind the bearer). True when answered. */ export function trendingRoute(req, res, url, { json, readBody, authorization }) { if (!ROUTES.includes(url.pathname)) return false; if (mode === "unreachable") { req.socket.destroy(); return true; } if (req.method === "GET" && url.pathname === "/api/ops/trending") { req.resume(); reads++; if (!url.searchParams.has("slug")) { const all = listing(new URLSearchParams({ detail: "1" })); json(res, 200, { ok: true, libraries: mode === "none" ? [] : [{ slug: state.slug, name: state.name, topics: all.topics.length, posts: all.total, unjudged: all.topics.reduce((n, t) => n + t.counts.unjudged, 0) }] }); return true; } if (mode === "none" || url.searchParams.get("slug") !== state.slug) { json(res, 404, { ok: false, error: `No such channel: ${url.searchParams.get("slug")}` }); return true; } if (url.searchParams.get("accounts") === "1") { json(res, 200, accounts(url.searchParams)); return true; } const topic = url.searchParams.get("topic"); if (topic && !state.topics.some((t) => t.id === topic || t.aliases?.includes(topic))) { json(res, 400, { ok: false, error: `${state.slug} has no topic "${topic}" (its topics: ${state.topics.map((t) => t.id).join(", ")})` }); return true; } json(res, 200, listing(url.searchParams)); return true; } if (req.method !== "POST") return false; readBody(req, (body) => { const action = url.pathname.slice("/api/ops/".length); requests.push({ action, body, authorization }); if (!body || body.slug !== state.slug) return json(res, 400, { ok: false, error: `${body?.slug} is not an X trending library` }); const answer = action === "judge-trending" ? judge(body) : action === "watch-trending" ? watch(body) : action === "organise-trending" ? organise(body) : action === "publish-trending" ? publish(body) : action === "x-search-lead" ? lead(body) : purge(body); json(res, answer.ok ? 200 : 400, answer); }); return true; }