commit 8c8874945692adc946bd6d9b778f17bbec6baa98
parent a1ca78d0742e3a62ff6f0d7cfaf6ed9a7e02d6f2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 18:50:00 -0500
x-trending S1: the library's config key, capture parser and store
A posts channel carrying `xTrending` is an X trending library (lib/xTrending/config.ts:
the marker and a read's caps, the trending page URL). social/xTrendingParse.ts reads a
saved capture's GraphQL answers into posts (stopping at a tweet, skipping promoted
entries and other surfaces' operations) with each post's media by kind.
lib/xTrending/store.ts is the one writer of trending/topics.json and membership.json
and the listing, which reads the files and the posts shards, never the index.
Fixtures are invented.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
9 files changed, 1259 insertions(+), 0 deletions(-)
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -2,6 +2,7 @@ import { coerceLocalMediaConfig, type LocalMediaConfig } from "./localMedia";
import { PLATFORM_VALUES, type Platform } from "./platform";
import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config";
import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config";
+import { coerceXTrendingConfig, type XTrendingConfig } from "./xTrending/config";
import {
isDownloadFormatPreset,
isSourceVideoQuality,
@@ -302,6 +303,8 @@ export type ChannelConfig = {
wayback?: WaybackPagesConfig;
// Release 38: an X search channel's query (lib/xSearch/config.ts).
xSearch?: XSearchConfig;
+ // Lane x-trending: an X trending library's marker and caps (lib/xTrending/config.ts).
+ xTrending?: XTrendingConfig;
// External library inputs are not managed media. A config change never moves files.
localMedia?: LocalMediaConfig;
};
@@ -398,6 +401,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".',
xSearch:
'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.',
+ xTrending:
+ 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics (`channels/<slug>/trending/`). `{maxScrolls?, maxPosts?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.',
localMedia:
"Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.",
};
@@ -618,6 +623,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
mirror: coerceMirrorConfig,
wayback: coerceWaybackPagesConfig,
xSearch: coerceXSearchConfig,
+ xTrending: coerceXTrendingConfig,
localMedia: coerceLocalMediaConfig,
};
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -90,6 +90,7 @@ export const channelConfigObjectSchema = z.object({
mirror: field("mirror"),
wayback: field("wayback"),
xSearch: field("xSearch"),
+ xTrending: field("xTrending"),
localMedia: field("localMedia"),
});
diff --git a/common/lib/xTrending/config.test.ts b/common/lib/xTrending/config.test.ts
@@ -0,0 +1,74 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ coerceXTrendingConfig,
+ isXTrendingChannel,
+ parseXTrendingUrl,
+ xTrendingLimits,
+} from "./config";
+import { parseChannelConfig } from "../channelConfig";
+
+test("a trending page URL is its id; anything else is refused", () => {
+ assert.deepEqual(parseXTrendingUrl("https://x.com/i/trending/1900000000000000001"), {
+ trendId: "1900000000000000001",
+ url: "https://x.com/i/trending/1900000000000000001",
+ });
+ // twitter.com, a trailing slash, a query and a fragment all name the same page.
+ assert.equal(
+ parseXTrendingUrl(" https://twitter.com/i/trending/1900000000000000001/?src=trend_click#top ")?.url,
+ "https://x.com/i/trending/1900000000000000001",
+ );
+ for (const bad of [
+ "",
+ "x.com/i/trending/1",
+ "https://x.com/i/trending/",
+ "https://x.com/i/trending/abc",
+ "https://x.com/i/trending/1/more",
+ "https://x.com/example/status/1",
+ "https://x.com/search?q=1",
+ "https://x.com.example.test/i/trending/1",
+ "ftp://x.com/i/trending/1",
+ null,
+ 42,
+ ]) {
+ assert.equal(parseXTrendingUrl(bad), null, String(bad));
+ }
+});
+
+test("the marker is an object; its caps are kept only in range", () => {
+ assert.deepEqual(coerceXTrendingConfig({}), {});
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 4, maxPosts: 30, other: 1 }), { maxScrolls: 4, maxPosts: 30 });
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 21, maxPosts: 0 }), {});
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 2.5, maxPosts: "9" }), {});
+ for (const bad of [undefined, null, true, "yes", 1, []]) assert.equal(coerceXTrendingConfig(bad), undefined);
+});
+
+test("a library is a posts channel on X carrying the marker, and its config survives a parse", () => {
+ const config = parseChannelConfig({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ name: "Trending",
+ xTrending: { maxPosts: 40 },
+ });
+ assert.ok(config);
+ assert.deepEqual(config!.xTrending, { maxPosts: 40 });
+ assert.equal(isXTrendingChannel(config), true);
+ assert.equal(isXTrendingChannel({ sourceKind: "social", platform: "twitter" }), false);
+ assert.equal(isXTrendingChannel({ sourceKind: "video", platform: "twitter", xTrending: {} }), false);
+ assert.equal(isXTrendingChannel({ sourceKind: "social", platform: "bluesky", xTrending: {} }), false);
+ assert.equal(isXTrendingChannel(null), false);
+});
+
+test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; out of range is refused", () => {
+ assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 8, posts: 60 } });
+ assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 60 } });
+ assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }, { scrolls: 20, posts: 200 }), {
+ ok: true,
+ limits: { scrolls: 20, posts: 200 },
+ });
+ assert.deepEqual(xTrendingLimits({}, { scrolls: 21 }), { ok: false, error: '"scrolls" is a whole number, 1–20' });
+ assert.deepEqual(xTrendingLimits({}, { posts: 201 }), { ok: false, error: '"posts" is a whole number, 1–200' });
+ assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–200' });
+ assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–20' });
+});
diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts
@@ -0,0 +1,114 @@
+// AN X TRENDING LIBRARY (lane x-trending, slice 1): a PRIVATE posts channel on
+// platform "twitter", `sourceKind: "social"`, with no `url` — nothing syncs it.
+// Its records are the posts X's trending pages (x.com/i/trending/<id>) showed,
+// from any author, read one page at a time by `read-x-trending`
+// (controller/readXTrending.ts) and grouped into the operator's topics
+// (lib/xTrending/store.ts). `config.xTrending` marks the channel and may hold
+// the caps a read uses when the ask names none.
+//
+// NEVER ON A SITE, IN NO INDEX BUILD: every site writer refuses it
+// (lib/site.ts), and buildIndex skips it, so no staging index, shard,
+// corpus.json, llms.txt or MCP corpus tool carries its posts. The library's
+// own listing reads its files (store.ts), never the index.
+//
+// Client-safe and a LEAF (no imports): lib/channelConfig.ts composes the
+// coercion below, and the channel form imports the URL helper.
+
+export type XTrendingConfig = {
+ // How many times a read moves to the bottom of the loaded page (each brings
+ // at most one more page of the timeline). Absent: X_TRENDING_DEFAULT_SCROLLS.
+ maxScrolls?: number;
+ // A read stops scrolling once it has seen this many posts. Absent:
+ // X_TRENDING_DEFAULT_POSTS.
+ maxPosts?: number;
+};
+
+export const X_TRENDING_DEFAULT_SCROLLS = 8;
+export const X_TRENDING_MAX_SCROLLS = 20;
+export const X_TRENDING_DEFAULT_POSTS = 60;
+export const X_TRENDING_MAX_POSTS = 200;
+// A read ends after this many scrolls in a row that brought no new post.
+export const X_TRENDING_IDLE_SCROLLS = 2;
+
+function capOf(v: unknown, max: number): number | undefined {
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= max ? v : undefined;
+}
+
+// `config.xTrending`: an object (the marker), its caps kept when valid and
+// omitted when not. Anything that is not an object is no library.
+export function coerceXTrendingConfig(v: unknown): XTrendingConfig | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ const out: XTrendingConfig = {};
+ const scrolls = capOf(r.maxScrolls, X_TRENDING_MAX_SCROLLS);
+ const posts = capOf(r.maxPosts, X_TRENDING_MAX_POSTS);
+ if (scrolls !== undefined) out.maxScrolls = scrolls;
+ if (posts !== undefined) out.maxPosts = posts;
+ return out;
+}
+
+// An X trending library: a posts channel on platform "twitter" carrying the
+// marker. Structural, so this leaf needs no import of the config's type.
+export function isXTrendingChannel(
+ config: { sourceKind?: string; platform?: string; xTrending?: unknown } | null | undefined,
+): boolean {
+ return config?.sourceKind === "social" && config.platform === "twitter" && Boolean(config.xTrending);
+}
+
+export const X_TRENDING_NOT_ON_A_SITE = (slug: string) =>
+ `${slug} is an X trending library: it is private, and never put on a site.`;
+
+export const X_TRENDING_HAS_NO_URL =
+ "An X trending library has no URL: its pages are read one at a time (pnpm ops read-x-trending, or Read a trending page on its channel page).";
+
+export const NOT_AN_X_TRENDING_LIBRARY = (slug: string) =>
+ `${slug} is not an X trending library (create one with platform "x-trending").`;
+
+export const NOT_A_TRENDING_URL =
+ "not a trending page URL: give X's trending page, https://x.com/i/trending/<number>";
+
+const X_HOST_RE = /^(?:www\.|mobile\.)?(?:x|twitter)\.com$/i;
+
+export type XTrendingRef = {
+ // X's numeric id of the trending page.
+ trendId: string;
+ // The page as it is asked: always x.com, no query, no fragment.
+ url: string;
+};
+
+// An X trending page URL (x.com or twitter.com /i/trending/<digits>), or null.
+// The query string and fragment are dropped: the page is its id.
+export function parseXTrendingUrl(input: unknown): XTrendingRef | null {
+ if (typeof input !== "string" || !input.trim()) return null;
+ let u: URL;
+ try {
+ u = new URL(input.trim());
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (!X_HOST_RE.test(u.hostname)) return null;
+ const m = /^\/i\/trending\/(\d{1,25})\/?$/.exec(u.pathname);
+ if (!m) return null;
+ return { trendId: m[1], url: `https://x.com/i/trending/${m[1]}` };
+}
+
+export type XTrendingLimits = { scrolls: number; posts: number };
+
+// The caps of one read: the ask's, else the channel's, else the defaults.
+// A value outside 1–max is refused with a sentence, never clamped.
+export function xTrendingLimits(
+ config: XTrendingConfig | undefined,
+ ask: { scrolls?: unknown; posts?: unknown } = {},
+): { ok: true; limits: XTrendingLimits } | { ok: false; error: string } {
+ const one = (asked: unknown, stored: number | undefined, dflt: number, max: number, what: string) => {
+ if (asked === undefined || asked === null) return stored ?? dflt;
+ const n = capOf(asked, max);
+ return n === undefined ? `"${what}" is a whole number, 1–${max}` : n;
+ };
+ const scrolls = one(ask.scrolls, config?.maxScrolls, X_TRENDING_DEFAULT_SCROLLS, X_TRENDING_MAX_SCROLLS, "scrolls");
+ if (typeof scrolls === "string") return { ok: false, error: scrolls };
+ const posts = one(ask.posts, config?.maxPosts, X_TRENDING_DEFAULT_POSTS, X_TRENDING_MAX_POSTS, "posts");
+ if (typeof posts === "string") return { ok: false, error: posts };
+ return { ok: true, limits: { scrolls, posts } };
+}
diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts
@@ -0,0 +1,219 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ listXTrending,
+ readXTrendingMembership,
+ readXTrendingTopics,
+ recordXTrendingRead,
+ topicIdFromTitle,
+ topicTitleProblem,
+ trendingReadDir,
+} from "./store";
+import { writePosts } from "../posts-server";
+import type { Post } from "../posts";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-store-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+const READ_A = "tr-01JA0000000000000000000000";
+const READ_B = "tr-01JB0000000000000000000000";
+const READ_C = "tr-01JC0000000000000000000000";
+const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" };
+const REF_2 = { trendId: "1900000000000000002", url: "https://x.com/i/trending/1900000000000000002" };
+
+function post(id: string, author: string, text: string): Post {
+ return {
+ id,
+ slug: `lib/${id}`,
+ channelSlug: "lib",
+ author,
+ createdAt: "2026-11-16T12:00:00.000Z",
+ uploadDate: "20261116",
+ text,
+ url: `https://x.com/${author}/status/${id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ };
+}
+
+function root(name: string): string {
+ const dir = path.join(TMP, name);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+test("a read id is checked where it becomes a path", () => {
+ assert.equal(trendingReadDir("/c/lib", READ_A), `/c/lib/trending/reads/${READ_A}`);
+ for (const bad of ["../x", "tr-short", "xr-01JA0000000000000000000000", ""]) {
+ assert.throws(() => trendingReadDir("/c/lib", bad), /not a trending read id/);
+ }
+});
+
+test("a topic id comes from its title; a title is refused when empty or too long", () => {
+ assert.equal(topicIdFromTitle(" Kettle Festival 2026! "), "kettle-festival-2026");
+ assert.equal(topicIdFromTitle("!!!"), "");
+ assert.equal(topicTitleProblem("Kettles"), null);
+ assert.match(topicTitleProblem(" ") ?? "", /topic/);
+ assert.match(topicTitleProblem("x".repeat(121)) ?? "", /at most 120/);
+});
+
+test("the first read of a page makes a topic named for it; a re-read adds posts, keeps old ones, appends the read", async () => {
+ const dir = root("reread");
+ await writePosts(dir, [post("101", "teapot_news", "one"), post("102", "saucer_fan", "two")]);
+ const first = await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ postIds: ["101", "102"],
+ added: 2,
+ media: { "101": { count: 2, kinds: ["image"] } },
+ });
+ assert.deepEqual(first, {
+ topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: true },
+ placed: 2,
+ kept: 0,
+ });
+ await writePosts(dir, [post("103", "lid_watch", "three")]);
+ const second = await recordXTrendingRead(dir, {
+ readId: READ_B,
+ at: "2026-11-17T11:00:00.000Z",
+ ref: REF,
+ postIds: ["103", "101"],
+ added: 1,
+ });
+ assert.deepEqual(second, {
+ topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: false },
+ placed: 1,
+ kept: 1,
+ });
+ const topics = await readXTrendingTopics(dir);
+ assert.equal(topics.length, 1);
+ assert.deepEqual(topics[0].sources, [
+ {
+ trendId: REF.trendId,
+ url: REF.url,
+ reads: [
+ { id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 },
+ { id: READ_B, at: "2026-11-17T11:00:00.000Z", posts: 2, added: 1 },
+ ],
+ },
+ ]);
+ const members = await readXTrendingMembership(dir);
+ assert.deepEqual(Object.keys(members).sort(), ["101", "102", "103"]);
+ assert.deepEqual(members["101"].seen.map((s) => [s.read, s.rank]), [
+ [READ_A, 1],
+ [READ_B, 2],
+ ]);
+ // 102 was not on the page the second time: it stays.
+ assert.deepEqual(members["102"].seen.map((s) => s.read), [READ_A]);
+ // The same read recorded twice changes nothing.
+ await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 1 });
+ assert.equal((await readXTrendingTopics(dir))[0].sources[0].reads.length, 2);
+ assert.equal((await readXTrendingMembership(dir))["101"].seen.length, 2);
+});
+
+test("a named topic is found by id or title, else made; a second page merges into it; a placed post keeps its topic", async () => {
+ const dir = root("named");
+ await writePosts(dir, [post("201", "a", "one"), post("202", "b", "two"), post("203", "c", "three")]);
+ const made = await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ topic: "Kettle Festival",
+ postIds: ["201"],
+ added: 1,
+ });
+ assert.deepEqual(made.topic, { id: "kettle-festival", title: "Kettle Festival", created: true });
+ // Another page, into the same topic by its title in another case.
+ const merged = await recordXTrendingRead(dir, {
+ readId: READ_B,
+ at: "2026-11-17T11:00:00.000Z",
+ ref: REF_2,
+ topic: "kettle festival",
+ postIds: ["202", "201"],
+ added: 1,
+ });
+ assert.deepEqual(merged.topic, { id: "kettle-festival", title: "Kettle Festival", created: false });
+ // A third read into another topic: 201 stays where it was placed.
+ const other = await recordXTrendingRead(dir, {
+ readId: READ_C,
+ at: "2026-11-17T12:00:00.000Z",
+ ref: REF_2,
+ topic: "Saucers",
+ postIds: ["201", "203"],
+ added: 1,
+ });
+ assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1 });
+ const members = await readXTrendingMembership(dir);
+ assert.equal(members["201"].topic, "kettle-festival");
+ assert.equal(members["203"].topic, "saucers");
+ const topics = await readXTrendingTopics(dir);
+ assert.deepEqual(topics.map((t) => [t.id, t.sources.map((s) => s.trendId)]), [
+ ["kettle-festival", [REF.trendId, REF_2.trendId]],
+ ["saucers", [REF_2.trendId]],
+ ]);
+});
+
+test("the listing gives each post's words, author, media, reads and topic — and nothing of the raw capture", async () => {
+ const dir = root("listing");
+ await writePosts(dir, [post("301", "teapot_news", "The kettle festival opens today."), post("302", "saucer_fan", "Second.")]);
+ mkdirSync(trendingReadDir(dir, READ_A), { recursive: true });
+ await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ topic: "Kettles",
+ postIds: ["301", "302", "999"],
+ added: 2,
+ media: { "301": { count: 2, kinds: ["image"] } },
+ });
+ const all = await listXTrending(dir);
+ assert.deepEqual(all.topics, [
+ {
+ id: "kettles",
+ title: "Kettles",
+ posts: 2,
+ sources: [{ trendId: REF.trendId, url: REF.url, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }],
+ },
+ ]);
+ // 999 is a member with no archived post (a write that never landed): not listed.
+ assert.deepEqual(all.posts, [
+ {
+ id: "301",
+ author: "teapot_news",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/teapot_news/status/301",
+ text: "The kettle festival opens today.",
+ media: { count: 2, kinds: ["image"] },
+ topic: "kettles",
+ reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }],
+ },
+ {
+ id: "302",
+ author: "saucer_fan",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/saucer_fan/status/302",
+ text: "Second.",
+ media: { count: 0, kinds: [] },
+ topic: "kettles",
+ reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }],
+ },
+ ]);
+ assert.equal(all.total, 2);
+ assert.deepEqual(all.reads, [READ_A]);
+ assert.equal((await listXTrending(dir, { limit: 1 })).posts.length, 1);
+ assert.equal((await listXTrending(dir, { limit: 1 })).total, 2);
+ assert.equal((await listXTrending(dir, { topic: "nope" })).posts.length, 0);
+ // The files are plain JSON with a version.
+ assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "topics.json"), "utf8")).version, 1);
+ assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "membership.json"), "utf8")).version, 1);
+});
+
+test("an empty library lists nothing", async () => {
+ assert.deepEqual(await listXTrending(root("empty")), { topics: [], posts: [], total: 0, reads: [] });
+});
diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts
@@ -0,0 +1,394 @@
+// AN X TRENDING LIBRARY'S OWN FILES (lane x-trending, slice 1), beside its
+// posts (the channel's ordinary month shards, lib/posts-server.ts):
+//
+// channels/<lib>/trending/topics.json the operator's topics, each with
+// the trending pages read into it
+// and every read's id and time
+// channels/<lib>/trending/membership.json post id → its topic, the reads
+// that showed it, its media by kind
+// channels/<lib>/trending/reads/<readId>/ one read of one page, raw:
+// responses.jsonl every GraphQL JSON answer the page fetched
+// page.png the page as it stood when it had loaded
+// read.json the read's record: operation NAMES and SIZES only
+//
+// THE RAW CAPTURE IS PRIVATE AND STAYS HERE: it can hold other accounts' data
+// and fields bound to the reading session. No route serves `reads/`, nothing
+// indexes it, and the listing below never returns it. A post is parsed from
+// the saved file only (social/xTrendingParse.ts).
+//
+// THIS MODULE IS THE ONE WRITER of topics.json and membership.json; every
+// write goes through the file's lock (withJsonFileLock) and is atomic. A
+// re-read of a page adds posts and appends a read; it never drops a post, and
+// never moves one out of the topic it is in.
+//
+// The listing reads these files and the posts shards — never the index (the
+// library is in no index build).
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { readdir } from "node:fs/promises";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
+import { readAllPosts } from "../posts-server";
+import type { Post } from "../posts";
+import type { XTrendingRef } from "./config";
+
+export const TRENDING_DIRNAME = "trending";
+export const TRENDING_READS_DIRNAME = "reads";
+export const TRENDING_RESPONSES_FILENAME = "responses.jsonl";
+export const TRENDING_PAGE_SHOT_FILENAME = "page.png";
+export const TRENDING_READ_FILENAME = "read.json";
+
+export function trendingDir(channelRoot: string): string {
+ return path.join(channelRoot, TRENDING_DIRNAME);
+}
+
+const READ_ID = /^tr-[0-9A-Z]{26}$/;
+
+export function isXTrendingReadId(id: unknown): id is string {
+ return typeof id === "string" && READ_ID.test(id);
+}
+
+// One read's directory. The id is checked here, where it becomes a path.
+export function trendingReadDir(channelRoot: string, readId: string): string {
+ if (!isXTrendingReadId(readId)) throw new Error(`"${readId}" is not a trending read id`);
+ return path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME, readId);
+}
+
+function topicsPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "topics.json");
+}
+
+function membershipPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "membership.json");
+}
+
+export type XTrendingMediaKind = "image" | "video" | "gif";
+export type XTrendingMedia = { count: number; kinds: XTrendingMediaKind[] };
+
+export type XTrendingSourceRead = {
+ // The read's id (`reads/<id>/`), when it ran, the posts it showed and how
+ // many of them were new to the library.
+ id: string;
+ at: string;
+ posts: number;
+ added: number;
+};
+
+// One trending page read into a topic. `title` and `summary` are X's own
+// words for the page, filled once the parser knows where the page keeps them.
+export type XTrendingSource = {
+ trendId: string;
+ url: string;
+ title?: string;
+ summary?: string;
+ reads: XTrendingSourceRead[];
+};
+
+export type XTrendingTopic = {
+ id: string;
+ // The operator's name for it (X's title is the source's).
+ title: string;
+ createdAt: string;
+ sources: XTrendingSource[];
+};
+
+export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number };
+
+export type XTrendingMember = {
+ topic: string;
+ seen: XTrendingSeen[];
+ media?: XTrendingMedia;
+};
+
+type TopicsFile = { version: 1; topics: XTrendingTopic[] };
+type MembershipFile = { version: 1; posts: Record<string, XTrendingMember> };
+
+const str = (v: unknown): v is string => typeof v === "string" && v !== "";
+
+function parseTopics(raw: unknown): XTrendingTopic[] {
+ const list = (raw as { topics?: unknown } | null)?.topics;
+ if (!Array.isArray(list)) return [];
+ const out: XTrendingTopic[] = [];
+ for (const t of list) {
+ if (!t || typeof t !== "object" || !str(t.id) || !str(t.title)) continue;
+ const sources: XTrendingSource[] = [];
+ for (const s of Array.isArray(t.sources) ? t.sources : []) {
+ if (!s || typeof s !== "object" || !str(s.trendId) || !str(s.url)) continue;
+ const reads: XTrendingSourceRead[] = [];
+ for (const r of Array.isArray(s.reads) ? s.reads : []) {
+ if (!r || typeof r !== "object" || !isXTrendingReadId(r.id) || !str(r.at)) continue;
+ reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0 });
+ }
+ sources.push({
+ trendId: s.trendId,
+ url: s.url,
+ ...(str(s.title) ? { title: s.title } : {}),
+ ...(str(s.summary) ? { summary: s.summary } : {}),
+ reads,
+ });
+ }
+ out.push({ id: t.id, title: t.title, createdAt: str(t.createdAt) ? t.createdAt : "", sources });
+ }
+ return out;
+}
+
+const MEDIA_KINDS: readonly XTrendingMediaKind[] = ["image", "video", "gif"];
+
+function parseMembership(raw: unknown): Record<string, XTrendingMember> {
+ const posts = (raw as { posts?: unknown } | null)?.posts;
+ if (!posts || typeof posts !== "object" || Array.isArray(posts)) return {};
+ const out: Record<string, XTrendingMember> = {};
+ for (const [id, m] of Object.entries(posts as Record<string, Partial<XTrendingMember> | null>)) {
+ if (!/^\d+$/.test(id) || !m || typeof m !== "object" || !str(m.topic)) continue;
+ const seen: XTrendingSeen[] = [];
+ for (const s of Array.isArray(m.seen) ? m.seen : []) {
+ if (!s || typeof s !== "object" || !isXTrendingReadId(s.read) || !str(s.trendId) || !str(s.at)) continue;
+ seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0 });
+ }
+ const media =
+ m.media && typeof m.media === "object" && Number(m.media.count) > 0
+ ? {
+ count: Number(m.media.count),
+ kinds: (Array.isArray(m.media.kinds) ? m.media.kinds : []).filter((k): k is XTrendingMediaKind =>
+ MEDIA_KINDS.includes(k as XTrendingMediaKind),
+ ),
+ }
+ : undefined;
+ out[id] = { topic: m.topic, seen, ...(media ? { media } : {}) };
+ }
+ return out;
+}
+
+export async function readXTrendingTopics(channelRoot: string): Promise<XTrendingTopic[]> {
+ const read = await readJsonFile(topicsPath(channelRoot));
+ return read.ok ? parseTopics(read.value) : [];
+}
+
+export async function readXTrendingMembership(channelRoot: string): Promise<Record<string, XTrendingMember>> {
+ const read = await readJsonFile(membershipPath(channelRoot));
+ return read.ok ? parseMembership(read.value) : {};
+}
+
+// A topic id from a title: lower-case words joined by "-", at most 48
+// characters; "" when the title has no letter or digit.
+export function topicIdFromTitle(title: string): string {
+ return title
+ .normalize("NFKD")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 48)
+ .replace(/-+$/, "");
+}
+
+export const X_TRENDING_TOPIC_TITLE_MAX = 120;
+
+// Why this cannot be a topic's name, or null.
+export function topicTitleProblem(title: unknown): string | null {
+ if (typeof title !== "string" || !title.trim()) return `"topic" is a topic's id or a name for a new one`;
+ if (title.trim().length > X_TRENDING_TOPIC_TITLE_MAX) {
+ return `A topic's name is at most ${X_TRENDING_TOPIC_TITLE_MAX} characters`;
+ }
+ return null;
+}
+
+export type RecordReadInput = {
+ readId: string;
+ at: string;
+ ref: XTrendingRef;
+ // The topic asked for: an existing topic's id or title, or a new one's
+ // title. Absent: the topic this page was read into before, else a new one
+ // named for the page.
+ topic?: string;
+ // The page's posts, first shown first.
+ postIds: ReadonlyArray<string>;
+ // How many of them the library did not hold before this read.
+ added: number;
+ media?: Readonly<Record<string, XTrendingMedia>>;
+};
+
+export type RecordReadResult = {
+ topic: { id: string; title: string; created: boolean };
+ // Posts this read placed in the topic (new to the library's membership).
+ placed: number;
+ // Posts the library already had, left in the topic they were in.
+ kept: number;
+};
+
+// One read, recorded: its topic found or made, the page added to the topic's
+// sources, the read appended, and every post it showed given a place (a post
+// already placed keeps its topic and gains the read).
+export async function recordXTrendingRead(channelRoot: string, input: RecordReadInput): Promise<RecordReadResult> {
+ if (!isXTrendingReadId(input.readId)) throw new Error(`"${input.readId}" is not a trending read id`);
+ const topic = await withJsonFileLock(topicsPath(channelRoot), async () => {
+ const topics = await readXTrendingTopics(channelRoot);
+ const asked = input.topic?.trim();
+ let found: XTrendingTopic | undefined;
+ if (asked) {
+ found =
+ topics.find((t) => t.id === asked) ??
+ topics.find((t) => t.title.toLowerCase() === asked.toLowerCase());
+ } else {
+ found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId));
+ }
+ let created = false;
+ if (!found) {
+ const title = asked || `Trending ${input.ref.trendId}`;
+ const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`;
+ let id = base;
+ for (let n = 2; topics.some((t) => t.id === id); n++) id = `${base}-${n}`;
+ found = { id, title, createdAt: input.at, sources: [] };
+ topics.push(found);
+ created = true;
+ }
+ let source = found.sources.find((s) => s.trendId === input.ref.trendId);
+ if (!source) {
+ source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] };
+ found.sources.push(source);
+ }
+ if (!source.reads.some((r) => r.id === input.readId)) {
+ source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added });
+ }
+ await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true });
+ return { id: found.id, title: found.title, created };
+ });
+ const counts = await withJsonFileLock(membershipPath(channelRoot), async () => {
+ const posts = await readXTrendingMembership(channelRoot);
+ let placed = 0;
+ let kept = 0;
+ input.postIds.forEach((id, i) => {
+ const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1 };
+ const have = posts[id];
+ if (have) {
+ kept++;
+ if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen);
+ if (!have.media && input.media?.[id]) have.media = input.media[id];
+ } else {
+ placed++;
+ posts[id] = { topic: topic.id, seen: [seen], ...(input.media?.[id] ? { media: input.media[id] } : {}) };
+ }
+ });
+ await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true });
+ return { placed, kept };
+ });
+ return { topic, ...counts };
+}
+
+// ── the listing ────────────────────────────────────────────────────────────
+
+export type XTrendingTopicRow = {
+ id: string;
+ title: string;
+ posts: number;
+ sources: Array<{
+ trendId: string;
+ url: string;
+ title?: string;
+ summary?: string;
+ reads: number;
+ lastReadAt: string | null;
+ }>;
+};
+
+// One post of the library, as the listing gives it: what it says, who said
+// it, what media it carries, which reads showed it, and its topic. Never the
+// raw capture.
+export type XTrendingPostRow = {
+ id: string;
+ author: string;
+ authorName?: string;
+ createdAt: string;
+ url: string;
+ text: string;
+ media: XTrendingMedia;
+ topic: string;
+ reads: Array<{ read: string; trendId: string; at: string }>;
+};
+
+export type XTrendingListing = {
+ topics: XTrendingTopicRow[];
+ posts: XTrendingPostRow[];
+ // Posts matching the ask, before `limit`.
+ total: number;
+ // Reads on disk (probes included), newest first.
+ reads: string[];
+};
+
+export const X_TRENDING_LIST_DEFAULT = 100;
+export const X_TRENDING_LIST_MAX = 500;
+
+export async function listXTrendingReadIds(channelRoot: string): Promise<string[]> {
+ try {
+ const names = await readdir(path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME));
+ return names.filter(isXTrendingReadId).sort().reverse();
+ } catch {
+ return [];
+ }
+}
+
+const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.at : a), "");
+
+// The library's topics and posts. `topic` narrows the posts to one topic (its
+// id); `limit` caps them (the newest read's first, in page order).
+export async function listXTrending(
+ channelRoot: string,
+ opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post> } = {},
+): Promise<XTrendingListing> {
+ const [topics, membership, reads] = await Promise.all([
+ readXTrendingTopics(channelRoot),
+ readXTrendingMembership(channelRoot),
+ listXTrendingReadIds(channelRoot),
+ ]);
+ const archived = new Map((opts.posts ?? (await readAllPosts(channelRoot))).map((p) => [p.id, p]));
+ const count = new Map<string, number>();
+ for (const [id, m] of Object.entries(membership)) {
+ if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1);
+ }
+ const rows: XTrendingPostRow[] = [];
+ for (const [id, m] of Object.entries(membership)) {
+ if (opts.topic && m.topic !== opts.topic) continue;
+ const post = archived.get(id);
+ if (!post) continue;
+ rows.push({
+ id,
+ author: post.author,
+ ...(post.authorName ? { authorName: post.authorName } : {}),
+ createdAt: post.createdAt,
+ url: post.url,
+ text: post.text,
+ media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] },
+ topic: m.topic,
+ reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })),
+ });
+ }
+ const rank = (id: string) => {
+ const m = membership[id];
+ const at = lastSeen(m);
+ return m.seen.find((s) => s.at === at)?.rank ?? 0;
+ };
+ rows.sort((a, b) => {
+ const [la, lb] = [lastSeen(membership[a.id]), lastSeen(membership[b.id])];
+ if (la !== lb) return la < lb ? 1 : -1;
+ return rank(a.id) - rank(b.id) || (a.id < b.id ? -1 : 1);
+ });
+ const limit = Math.min(Math.max(1, opts.limit ?? X_TRENDING_LIST_DEFAULT), X_TRENDING_LIST_MAX);
+ return {
+ topics: topics.map((t) => ({
+ id: t.id,
+ title: t.title,
+ posts: count.get(t.id) ?? 0,
+ sources: t.sources.map((s) => ({
+ trendId: s.trendId,
+ url: s.url,
+ ...(s.title ? { title: s.title } : {}),
+ ...(s.summary ? { summary: s.summary } : {}),
+ reads: s.reads.length,
+ lastReadAt: s.reads.reduce<string | null>((a, r) => (a === null || r.at > a ? r.at : a), null),
+ })),
+ })),
+ posts: rows.slice(0, limit),
+ total: rows.length,
+ reads,
+ };
+}
diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts
@@ -0,0 +1,129 @@
+// AN INVENTED TRENDING-PAGE CAPTURE, for tests and the editor's e2e fake
+// browser (fakeXProfileBrowser.ts). Every id, handle, name and word here is
+// made up; the SHAPES are X's public GraphQL tweet-result shapes as this repo
+// already reads them (xPlaywrightFetcher.ts): `{__typename: "Tweet", rest_id,
+// core.user_results.result, legacy}`, a TweetWithVisibilityResults wrapper, a
+// quoted result, a promoted entry. The operation names are invented too — the
+// real ones are learned from the first real read (the probe).
+
+export const FIXTURE_TREND_ID = "1900000000000000001";
+export const FIXTURE_TREND_URL = `https://x.com/i/trending/${FIXTURE_TREND_ID}`;
+export const FIXTURE_TREND_OP = "ExampleTrendPage";
+export const FIXTURE_TIMELINE_OP = "ExampleTrendTimeline";
+
+export type FixtureTweet = {
+ id: string;
+ handle: string;
+ name?: string;
+ text: string;
+ // "Wed Oct 10 20:19:24 +0000 2018", X's legacy form.
+ createdAt?: string;
+ media?: Array<"photo" | "video" | "animated_gif">;
+ quoted?: FixtureTweet;
+ replyTo?: { id: string; handle: string };
+ // Names under user.core (newer answers) instead of user.legacy.
+ namesInCore?: boolean;
+ // Wrapped in a TweetWithVisibilityResults, the inner tweet untagged.
+ wrapped?: boolean;
+ promoted?: boolean;
+};
+
+export function fixtureTweetResult(t: FixtureTweet): Record<string, unknown> {
+ const names = { screen_name: t.handle, name: t.name ?? t.handle };
+ const tweet: Record<string, unknown> = {
+ rest_id: t.id,
+ core: { user_results: { result: { __typename: "User", rest_id: `9${t.id.slice(-6)}`, ...(t.namesInCore ? { core: names, legacy: {} } : { legacy: names }) } } },
+ legacy: {
+ id_str: t.id,
+ conversation_id_str: t.replyTo?.id ?? t.id,
+ created_at: t.createdAt ?? "Mon Nov 16 12:00:00 +0000 2026",
+ full_text: t.text,
+ lang: "en",
+ favorite_count: 12,
+ retweet_count: 3,
+ reply_count: 1,
+ quote_count: 0,
+ entities: { urls: [] },
+ ...(t.media?.length
+ ? {
+ extended_entities: {
+ media: t.media.map((type, i) => ({
+ type,
+ media_key: `3_${t.id}${i}`,
+ media_url_https: `https://pbs.twimg.com/media/Fixture${t.id.slice(-4)}${i}.jpg`,
+ })),
+ },
+ }
+ : {}),
+ ...(t.quoted ? { quoted_status_id_str: t.quoted.id, is_quote_status: true } : {}),
+ ...(t.replyTo ? { in_reply_to_status_id_str: t.replyTo.id, in_reply_to_screen_name: t.replyTo.handle } : {}),
+ },
+ ...(t.quoted ? { quoted_status_result: { result: fixtureTweetResult(t.quoted) } } : {}),
+ };
+ return t.wrapped ? { __typename: "TweetWithVisibilityResults", tweet } : { __typename: "Tweet", ...tweet };
+}
+
+function entry(t: FixtureTweet): Record<string, unknown> {
+ return {
+ entryId: `tweet-${t.id}`,
+ content: {
+ entryType: "TimelineTimelineItem",
+ itemContent: {
+ itemType: "TimelineTweet",
+ tweet_results: { result: fixtureTweetResult(t) },
+ ...(t.promoted ? { promotedMetadata: { advertiser_results: {} } } : {}),
+ },
+ },
+ };
+}
+
+// One timeline answer holding these posts.
+export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unknown> {
+ return {
+ data: {
+ timeline: {
+ instructions: [
+ { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", value: "fixture-cursor" } }] },
+ ],
+ },
+ },
+ };
+}
+
+export const FIXTURE_FIRST_PAGE: FixtureTweet[] = [
+ { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] },
+ {
+ id: "1900000000000001002",
+ handle: "saucer_fan",
+ text: "Quoting the festival post.",
+ wrapped: true,
+ quoted: { id: "1900000000000000900", handle: "kettle_org", text: "Festival programme attached.", media: ["photo"] },
+ },
+ { id: "1900000000000001003", handle: "advert_co", text: "Buy our kettles.", promoted: true },
+ { id: "1900000000000001004", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true },
+];
+
+export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [
+ { id: "1900000000000001004", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true },
+ { id: "1900000000000001005", handle: "lid_watch", text: "A reply about the queue.", replyTo: { id: "1900000000000001001", handle: "teapot_news" }, media: ["animated_gif"] },
+];
+
+const graphqlUrl = (op: string, n: number) =>
+ `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=%7B%22rest_id%22%3A%22${FIXTURE_TREND_ID}%22%7D`;
+
+export type FixtureResponse = { url: string; status: number; body?: unknown; text?: string };
+
+// What the page fetches on load, and after each scroll to the bottom.
+export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: FixtureResponse[][] } {
+ return {
+ load: [
+ { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: { data: { example_trend: { rest_id: FIXTURE_TREND_ID } } } },
+ { url: graphqlUrl(FIXTURE_TIMELINE_OP, 2), status: 200, body: fixtureTimelineBody(FIXTURE_FIRST_PAGE) },
+ // Not GraphQL: never saved.
+ { url: "https://x.com/i/api/1.1/example.json", status: 200, body: { ok: true } },
+ // Another surface's posts: saved, never read as the page's.
+ { url: graphqlUrl("HomeTimeline", 3), status: 200, body: fixtureTimelineBody([{ id: "1900000000000007777", handle: "home_only", text: "Not on the trending page." }]) },
+ ],
+ scrolls: [[{ url: graphqlUrl(FIXTURE_TIMELINE_OP, 4), status: 200, body: fixtureTimelineBody(FIXTURE_SECOND_PAGE) }], [], []],
+ };
+}
diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts
@@ -0,0 +1,111 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ collectTimelineTweets,
+ graphqlOpOf,
+ mediaSummaryOf,
+ parseTrendingCapture,
+ type TrendingCaptureLine,
+} from "./xTrendingParse";
+import {
+ FIXTURE_FIRST_PAGE,
+ FIXTURE_TIMELINE_OP,
+ FIXTURE_TREND_OP,
+ fixtureTimelineBody,
+ fixtureTrendingResponses,
+} from "./__fixtures__/xTrendingCapture";
+
+function linesOf(responses: Array<{ url: string; status: number; body?: unknown }>): TrendingCaptureLine[] {
+ return responses
+ .filter((r) => graphqlOpOf(r.url))
+ .map((r, i) => ({
+ n: i + 1,
+ at: "2026-11-17T10:00:00.000Z",
+ op: graphqlOpOf(r.url)!,
+ status: r.status,
+ url: r.url,
+ bytes: JSON.stringify(r.body ?? null).length,
+ body: r.body,
+ }));
+}
+
+test("an operation is named by the GraphQL URL's path; nothing else is one", () => {
+ assert.equal(graphqlOpOf("https://x.com/i/api/graphql/abc123/ExampleTrendTimeline?variables=%7B%7D"), "ExampleTrendTimeline");
+ assert.equal(graphqlOpOf("https://api.x.com/i/api/graphql/abc/Op"), "Op");
+ assert.equal(graphqlOpOf("https://x.com/i/api/1.1/example.json"), null);
+ assert.equal(graphqlOpOf("https://x.com.example.test/i/api/graphql/abc/Op"), null);
+ assert.equal(graphqlOpOf("https://example.test/i/api/graphql/abc/Op"), null);
+});
+
+test("the walk lists the page's posts once each, in order: no promoted entry, no quoted post", () => {
+ const tweets = collectTimelineTweets(fixtureTimelineBody(FIXTURE_FIRST_PAGE));
+ assert.deepEqual(
+ tweets.map((t) => t.rest_id),
+ ["1900000000000001001", "1900000000000001002", "1900000000000001004"],
+ );
+ // The quoted post rides on the post quoting it.
+ assert.equal((tweets[1].quoted as { rest_id: string }).rest_id, "1900000000000000900");
+ // Names under user.core are read as names under user.legacy are.
+ assert.deepEqual(tweets[2].user, { name: "spout_clips", nick: "Spout Clips" });
+});
+
+test("media is counted by kind from the answer", () => {
+ const [first, , video] = collectTimelineTweets(fixtureTimelineBody(FIXTURE_FIRST_PAGE));
+ assert.deepEqual(mediaSummaryOf(first), { count: 2, kinds: ["image"] });
+ assert.deepEqual(mediaSummaryOf(video), { count: 1, kinds: ["video"] });
+ assert.equal(mediaSummaryOf({ full_text: "no media" }), undefined);
+});
+
+test("a capture parses to posts, their media and the operations' names and sizes", () => {
+ const f = fixtureTrendingResponses();
+ const parsed = parseTrendingCapture(linesOf([...f.load, ...f.scrolls.flat()]), "trending");
+ assert.deepEqual(
+ parsed.posts.map((p) => [p.id, p.author, p.channelSlug]),
+ [
+ ["1900000000000001001", "teapot_news", "trending"],
+ ["1900000000000001002", "saucer_fan", "trending"],
+ ["1900000000000001004", "spout_clips", "trending"],
+ ["1900000000000001005", "lid_watch", "trending"],
+ ],
+ );
+ const quoting = parsed.posts[1];
+ assert.equal(quoting.quoted?.id, "1900000000000000900");
+ assert.equal(quoting.quoted?.author, "kettle_org");
+ assert.equal(parsed.posts[3].isReply, true);
+ assert.equal(parsed.posts[3].replyTo?.id, "1900000000000001001");
+ assert.equal(parsed.posts[0].url, "https://x.com/teapot_news/status/1900000000000001001");
+ assert.deepEqual(parsed.media, {
+ "1900000000000001001": { count: 2, kinds: ["image"] },
+ "1900000000000001004": { count: 1, kinds: ["video"] },
+ "1900000000000001005": { count: 1, kinds: ["gif"] },
+ });
+ // Another surface's answer is counted, and its posts are not the page's.
+ assert.deepEqual(
+ parsed.operations.map((o) => [o.op, o.responses, o.tweets]),
+ [
+ [FIXTURE_TREND_OP, 1, 0],
+ [FIXTURE_TIMELINE_OP, 2, 5],
+ ["HomeTimeline", 1, 0],
+ ],
+ );
+ assert.equal(parsed.responses, 4);
+ assert.ok(parsed.posts.every((p) => p.author !== "home_only" && p.author !== "advert_co"));
+});
+
+test("an answer that failed, or whose body was not kept, yields nothing", () => {
+ const body = fixtureTimelineBody(FIXTURE_FIRST_PAGE);
+ const line = (over: Partial<TrendingCaptureLine>): TrendingCaptureLine => ({
+ n: 1,
+ at: "2026-11-17T10:00:00.000Z",
+ op: FIXTURE_TIMELINE_OP,
+ status: 200,
+ url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline",
+ bytes: 10,
+ body,
+ ...over,
+ });
+ assert.equal(parseTrendingCapture([line({ status: 429 })], "t").posts.length, 0);
+ assert.equal(parseTrendingCapture([line({ body: undefined, skipped: "too-large" })], "t").posts.length, 0);
+ assert.equal(parseTrendingCapture([line({})], "t").posts.length, 3);
+ assert.equal(parseTrendingCapture([line({ body: { data: {} } })], "t").posts.length, 0);
+});
diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts
@@ -0,0 +1,211 @@
+// WHAT A SAVED TRENDING-PAGE CAPTURE HOLDS (lane x-trending, slice 1).
+//
+// A read of x.com/i/trending/<id> (xTrendingRead.ts) saves every GraphQL JSON
+// answer the page itself fetched, one per line, in
+// `channels/<lib>/trending/reads/<readId>/responses.jsonl`. This module is the
+// ONLY reader of that file's bodies: the posts are parsed from the SAVED file,
+// never from the live page, so a better parser never costs a second read
+// (`read-x-trending {"reparse": <readId>}` is offline).
+//
+// X's operation names for this page are not known offline (the first real
+// read is the probe), so nothing here matches an operation by name to FIND
+// posts: every answer is walked for tweet results, as the Playwright fallback
+// does (xPlaywrightFetcher.ts collectTweetsFromGraphQL). Unlike that walk,
+// this one stops AT a tweet: the post it quotes or reposts is that post's
+// context, not another post of the page; and it skips promoted entries. A few
+// operations known to belong to other surfaces of the app are ignored by name.
+//
+// Pure but for readCaptureLines (node:fs).
+
+import { readFile } from "node:fs/promises";
+import type { Post } from "../lib/posts";
+import { normalizeXTweets, xIdOf, type XTweetRaw } from "./xNormalize";
+
+// One answer the page fetched, as saved. `body` is absent when the answer was
+// not kept (`skipped` says why): not JSON, too large, or past the read's cap.
+export type TrendingCaptureLine = {
+ n: number;
+ at: string;
+ // The GraphQL operation's name, from the URL's path.
+ op: string;
+ status: number;
+ url: string;
+ bytes: number;
+ body?: unknown;
+ skipped?: "not-json" | "too-large" | "over-cap" | "unread";
+};
+
+const GRAPHQL_RE = /^https:\/\/(?:[a-z0-9-]+\.)?(?:x|twitter)\.com\/i\/api\/graphql\/[^/?#]+\/([A-Za-z0-9_]+)(?:[?#]|$)/;
+
+// The operation a response URL names (x.com/i/api/graphql/<query id>/<Op>),
+// or null for anything that is not one of X's GraphQL answers.
+export function graphqlOpOf(url: string): string | null {
+ return GRAPHQL_RE.exec(url)?.[1] ?? null;
+}
+
+// Operations of OTHER surfaces a logged-in page may fetch beside its own: the
+// home timelines, notifications, the sidebar. Their posts are not the page's.
+export const X_TRENDING_IGNORED_OPS: readonly string[] = [
+ "HomeTimeline",
+ "HomeLatestTimeline",
+ "NotificationsTimeline",
+ "ExploreSidebar",
+ "SidebarUserRecommendations",
+ "PinnedTimelines",
+];
+
+function obj(v: unknown): Record<string, unknown> | undefined {
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined;
+}
+
+// A tweet result: `{rest_id, legacy: {full_text, …}, core}` — tagged
+// `__typename: "Tweet"` or bare (the inside of a TweetWithVisibilityResults).
+function tweetLegacy(rec: Record<string, unknown>): Record<string, unknown> | undefined {
+ const legacy = obj(rec.legacy);
+ if (!legacy || typeof legacy.full_text !== "string") return undefined;
+ if (typeof rec.rest_id !== "string" && typeof legacy.id_str !== "string") return undefined;
+ return legacy;
+}
+
+// A nested result (`quoted_status_result`, `retweeted_status_result`): its
+// tweet, through a visibility wrapper.
+function nestedTweet(v: unknown): XTweetRaw | undefined {
+ const result = obj(obj(v)?.result);
+ if (!result) return undefined;
+ const inner = obj(result.tweet) ?? result;
+ const legacy = tweetLegacy(inner);
+ return legacy ? flatten(inner, legacy, false) : undefined;
+}
+
+// `{rest_id, legacy, core}` as the flat record the shared normalizer reads.
+function flatten(rec: Record<string, unknown>, legacy: Record<string, unknown>, withContext: boolean): XTweetRaw {
+ const out: XTweetRaw = { ...legacy };
+ if (typeof rec.rest_id === "string") out.rest_id = rec.rest_id;
+ if (rec.note_tweet) out.note_tweet = rec.note_tweet;
+ // The author: core.user_results.result, its names under `legacy` or (newer
+ // answers) under `core`.
+ const user = obj(obj(obj(rec.core)?.user_results)?.result);
+ const names = { ...obj(user?.core), ...obj(user?.legacy) } as Record<string, unknown>;
+ if (typeof names.screen_name === "string") {
+ out.user = { name: names.screen_name, ...(typeof names.name === "string" ? { nick: names.name } : {}) };
+ }
+ if (withContext) {
+ const quoted = nestedTweet(rec.quoted_status_result);
+ if (quoted) out.quoted = quoted;
+ const reposted = nestedTweet(legacy.retweeted_status_result ?? rec.retweeted_status_result);
+ if (reposted) out.retweeted_status = reposted;
+ }
+ delete out.retweeted_status_result;
+ return out;
+}
+
+// Every post of the page in one answer, in the order the answer lists them.
+// The walk stops at a tweet (what it quotes or reposts is carried on it) and
+// never enters a promoted entry.
+export function collectTimelineTweets(payload: unknown): XTweetRaw[] {
+ const out: XTweetRaw[] = [];
+ const seen = new Set<unknown>();
+ const visit = (node: unknown): void => {
+ if (!node || typeof node !== "object" || seen.has(node)) return;
+ seen.add(node);
+ if (Array.isArray(node)) {
+ for (const item of node) visit(item);
+ return;
+ }
+ const rec = node as Record<string, unknown>;
+ if (rec.promotedMetadata) return;
+ const legacy = tweetLegacy(rec);
+ if (legacy) {
+ out.push(flatten(rec, legacy, true));
+ return;
+ }
+ for (const value of Object.values(rec)) visit(value);
+ };
+ visit(payload);
+ return out;
+}
+
+export type TrendingMediaKind = "image" | "video" | "gif";
+export type TrendingMediaSummary = { count: number; kinds: TrendingMediaKind[] };
+
+const MEDIA_KIND: Record<string, TrendingMediaKind> = { photo: "image", video: "video", animated_gif: "gif" };
+
+// What media a post carries, by kind — counted from the answer, nothing fetched.
+export function mediaSummaryOf(raw: XTweetRaw): TrendingMediaSummary | undefined {
+ const media = obj(raw.extended_entities)?.media ?? obj(raw.entities)?.media;
+ if (!Array.isArray(media) || media.length === 0) return undefined;
+ const kinds = new Set<TrendingMediaKind>();
+ for (const m of media) {
+ const kind = MEDIA_KIND[String(obj(m)?.type ?? "")];
+ if (kind) kinds.add(kind);
+ }
+ return { count: media.length, kinds: [...kinds].sort() };
+}
+
+export type TrendingOperation = { op: string; responses: number; bytes: number; statuses: number[]; tweets: number };
+
+export type ParsedTrendingCapture = {
+ // The page's posts, first shown first, each once.
+ posts: Post[];
+ // Post id → its media, for the posts that carry any.
+ media: Record<string, TrendingMediaSummary>;
+ // Operation names and sizes only: what read.json may say of the capture.
+ operations: TrendingOperation[];
+ responses: number;
+ bytes: number;
+};
+
+// The capture, parsed. `channelSlug` is the library's (a Post names its channel).
+export function parseTrendingCapture(
+ lines: ReadonlyArray<TrendingCaptureLine>,
+ channelSlug: string,
+): ParsedTrendingCapture {
+ const raws: XTweetRaw[] = [];
+ const media: Record<string, TrendingMediaSummary> = {};
+ const ops = new Map<string, TrendingOperation>();
+ let bytes = 0;
+ for (const line of lines) {
+ const op = ops.get(line.op) ?? { op: line.op, responses: 0, bytes: 0, statuses: [], tweets: 0 };
+ ops.set(line.op, op);
+ op.responses++;
+ op.bytes += line.bytes;
+ bytes += line.bytes;
+ if (!op.statuses.includes(line.status)) op.statuses.push(line.status);
+ if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue;
+ if (line.status < 200 || line.status >= 300) continue;
+ const found = collectTimelineTweets(line.body);
+ op.tweets += found.length;
+ for (const raw of found) {
+ raws.push(raw);
+ const id = xIdOf(raw);
+ const summary = mediaSummaryOf(raw);
+ if (id && summary && !media[id]) media[id] = summary;
+ }
+ }
+ const posts = normalizeXTweets(raws, channelSlug);
+ const kept: Record<string, TrendingMediaSummary> = {};
+ for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id];
+ return {
+ posts,
+ media: kept,
+ operations: [...ops.values()].sort((a, b) => a.op.localeCompare(b.op)),
+ responses: lines.length,
+ bytes,
+ };
+}
+
+// The saved file's lines; a line that is not JSON (a write cut short) is skipped.
+export async function readCaptureLines(file: string): Promise<TrendingCaptureLine[]> {
+ const text = await readFile(file, "utf8");
+ const out: TrendingCaptureLine[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const rec = JSON.parse(line) as TrendingCaptureLine;
+ if (rec && typeof rec.op === "string" && typeof rec.status === "number") out.push(rec);
+ } catch {
+ /* a torn line */
+ }
+ }
+ return out;
+}