// WHAT A SAVED TRENDING-PAGE CAPTURE HOLDS (lane x-trending, slice 1). // // A read of x.com/i/trending/ (xTrendingRead.ts) saves every GraphQL JSON // answer the page itself fetched, one per line, in // `channels//trending/reads//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": }` 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. // // WHAT THE FIRST REAL READ SHOWED (lane x-followups; the shapes are in // __fixtures__/xTrendingRealShape.ts, with invented data): one answer carries // the page itself — X's title and summary for the trend, when X last updated // them, and the page's TABS, each a label and the id of the timeline it // lists (trendPageOf) — and the posts come from a timeline operation whose // request names that timeline id and, after the first, the cursor it // continues from. The first timeline answer ends with cursor ENTRIES; every // later one carries its new cursors in TimelineReplaceEntry instructions // (timelineShapeOf reads both). The page is found by its SHAPE, the timeline // by the posts it lists: no operation is matched by name here either. // // 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//), // 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 | undefined { return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : undefined; } // A tweet result: `{rest_id, legacy: {full_text, …}, core}` — tagged // `__typename: "Tweet"` or bare (the inside of a TweetWithVisibilityResults). function tweetLegacy(rec: Record): Record | 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, legacy: Record, 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; 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(); 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; 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 = { 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(); for (const m of media) { // An own key only: a `type` of "constructor" or "toString" is no kind. const type = String(obj(m)?.type ?? ""); if (Object.hasOwn(MEDIA_KIND, type)) kinds.add(MEDIA_KIND[type]); } return { count: media.length, kinds: [...kinds].sort() }; } // ONE MEDIA FILE OF A POST, AS THE ANSWER NAMES IT (lane x-trending-2): where // X's media CDN serves it. Nothing is fetched here; a capture job fetches // `fetchUrl` later, with no login (lib/xTrending/mediaStore.ts keeps it once). // // url the address as the answer gives it: the file's identity, what // the library's media index remembers it by // fetchUrl what is asked of the CDN: a picture at its original size // (`?format=&name=orig`), a video's highest-bitrate // progressive mp4 // // ONLY X's two media hosts, over https, are ever named: an address anywhere // else in an answer is not a media source (a capture is other people's data, // and nothing in it may point a fetch at another host). export type TrendingMediaSource = { kind: TrendingMediaKind; url: string; fetchUrl: string; ext: string; bitrate?: number; }; export const X_MEDIA_CDN_HOSTS: readonly string[] = ["pbs.twimg.com", "video.twimg.com"]; // An https address on one of X's media hosts, or null. export function xMediaCdnUrl(v: unknown): URL | null { if (typeof v !== "string") return null; let u: URL; try { u = new URL(v); } catch { return null; } if (u.protocol !== "https:" || u.username || u.password || u.port) return null; return X_MEDIA_CDN_HOSTS.includes(u.hostname) ? u : null; } const IMAGE_EXT = /\.(jpe?g|png|webp)$/i; // A post's media files, in the order the post carries them. A file the answer // names no usable address for (a video with no progressive mp4, an address on // another host) is left out: the count in mediaSummaryOf still says it exists. export function mediaSourcesOf(raw: XTweetRaw): TrendingMediaSource[] { const media = obj(raw.extended_entities)?.media ?? obj(raw.entities)?.media; if (!Array.isArray(media)) return []; const out: TrendingMediaSource[] = []; for (const item of media) { const m = obj(item); if (!m) continue; const type = String(m.type ?? ""); if (!Object.hasOwn(MEDIA_KIND, type)) continue; const kind = MEDIA_KIND[type]; if (kind === "image") { const u = xMediaCdnUrl(m.media_url_https); const ext = u ? IMAGE_EXT.exec(u.pathname)?.[1].toLowerCase() : undefined; if (!u || !ext || u.hostname !== "pbs.twimg.com") continue; const base = `${u.origin}${u.pathname.replace(IMAGE_EXT, "")}`; out.push({ kind, url: `${u.origin}${u.pathname}`, fetchUrl: `${base}?format=${ext === "jpeg" ? "jpg" : ext}&name=orig`, ext: ext === "jpeg" ? "jpg" : ext }); continue; } // A video or an animated GIF: the progressive mp4 with the highest bitrate. const variants = obj(m.video_info)?.variants; let best: { u: URL; bitrate: number } | undefined; for (const v of Array.isArray(variants) ? variants : []) { const variant = obj(v); if (!variant || variant.content_type !== "video/mp4") continue; const u = xMediaCdnUrl(variant.url); if (!u || u.hostname !== "video.twimg.com" || !/\.mp4$/i.test(u.pathname)) continue; const bitrate = typeof variant.bitrate === "number" && Number.isFinite(variant.bitrate) ? variant.bitrate : 0; if (!best || bitrate > best.bitrate) best = { u, bitrate }; } if (!best) continue; const url = `${best.u.origin}${best.u.pathname}`; out.push({ kind, url, fetchUrl: url, ext: "mp4", ...(best.bitrate ? { bitrate: best.bitrate } : {}) }); } return out; } // Every post's media sources in a saved capture, by post id (the first answer // that names a post's media wins). For the capture job: it reads the reads // that showed the posts it was asked for. export function mediaSourcesInCapture(lines: ReadonlyArray): Map { const out = new Map(); for (const line of lines) { if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue; if (line.status < 200 || line.status >= 300) continue; for (const raw of collectTimelineTweets(line.body)) { const id = xIdOf(raw); if (!id || out.has(id)) continue; const sources = mediaSourcesOf(raw); if (sources.length > 0) out.set(id, sources); } } return out; } // What a request asked for: the `variables` of the GraphQL URL. `cursor` is the // cursor it continues from, `timelineId` the timeline it lists (a trending // page's tab). Empty when the URL has none or cannot be read. export function requestVariablesOf(url: string): { cursor?: string; timelineId?: string } { try { const raw = new URL(url).searchParams.get("variables"); const v = raw ? (JSON.parse(raw) as { cursor?: unknown; timelineId?: unknown } | null) : null; const text = (x: unknown) => (typeof x === "string" && x ? x : undefined); const cursor = text(v?.cursor); const timelineId = text(v?.timelineId); return { ...(cursor ? { cursor } : {}), ...(timelineId ? { timelineId } : {}) }; } catch { return {}; } } // The cursor a request carried. Undefined when the URL has none or cannot be read. export function requestCursorOf(url: string): string | undefined { return requestVariablesOf(url).cursor; } // ONE TAB OF A TRENDING PAGE: its label as X shows it and the timeline it lists. export type TrendingPageTab = { label: string; timelineId: string }; // WHAT THE PAGE SAYS OF ITSELF: X's title and summary for the trend (X's own // words, written by X), when X last updated them, and the page's tabs. export type TrendingPageInfo = { title?: string; summary?: string; lastUpdatedAt?: string; tabs: TrendingPageTab[]; }; const oneLine = (v: unknown): string | undefined => { if (typeof v !== "string") return undefined; const text = v.replace(/\s+/g, " ").trim(); return text || undefined; }; // The page, from one answer's body: `data..result.page` holding an // `article` (title, article_text.text) and/or `post_timelines` (label, // post_timeline.id). Undefined for an answer that is not the page — the // answers that share its `data` key but carry no `page` included. export function trendPageOf(body: unknown): TrendingPageInfo | undefined { const data = obj(obj(body)?.data); if (!data) return undefined; for (const value of Object.values(data)) { const page = obj(obj(obj(value)?.result)?.page); if (!page) continue; const article = obj(page.article); const title = oneLine(article?.title); const summary = oneLine(obj(article?.article_text)?.text); const tabs: TrendingPageTab[] = []; for (const item of Array.isArray(page.post_timelines) ? page.post_timelines : []) { const label = oneLine(obj(item)?.label); const timelineId = obj(obj(item)?.post_timeline)?.id; if (!label || typeof timelineId !== "string" || !timelineId) continue; if (!tabs.some((t) => t.timelineId === timelineId)) tabs.push({ label, timelineId }); } if (!title && !summary && tabs.length === 0) continue; const ms = page.last_updated_at_ms; const at = typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? new Date(ms) : undefined; return { ...(title ? { title } : {}), ...(summary ? { summary } : {}), ...(at && !Number.isNaN(at.getTime()) ? { lastUpdatedAt: at.toISOString() } : {}), tabs, }; } return undefined; } // What an answer says of its timeline: whether it carries instructions at all, // and the BOTTOM cursor it ends with (the last one, when it names several). // // A cursor is read wherever the answer keeps one, in the two places the real // page uses and any other: // - a cursor ENTRY among a TimelineAddEntries' entries (the first answer of // a timeline): `{entryId: "cursor-bottom-…", content: {cursorType: // "Bottom", value}}`; // - a TimelineReplaceEntry instruction (every later answer, which lists no // cursor entry): `{type: "TimelineReplaceEntry", entry_id_to_replace: // "cursor-bottom-…", entry: {entryId, content: {cursorType: "Bottom", // value}}}` — beside one for the top cursor, which is not the bottom's. // A cursor of a MODULE inside the timeline (a "show more" of a carousel) is // not the timeline's: only `cursorType: "Bottom"`, or a `cursor-bottom` id, is. export function timelineShapeOf(payload: unknown): { instructions: boolean; bottom?: string } { let instructions = false; let bottom: string | undefined; const seen = new Set(); const cursorOf = (content: Record | undefined): string | undefined => { const v = content?.value ?? obj(content?.itemContent)?.value; return typeof v === "string" && v ? v : undefined; }; 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; if (Array.isArray(rec.instructions)) instructions = true; const value = typeof rec.value === "string" && rec.value ? rec.value : undefined; if (value && rec.cursorType === "Bottom") bottom = value; if (typeof rec.entryId === "string" && rec.entryId.startsWith("cursor-bottom")) { const v = cursorOf(obj(rec.content)); if (v) bottom = v; } // The replacement of the bottom cursor's entry, named by the entry it replaces. if (rec.type === "TimelineReplaceEntry" && typeof rec.entry_id_to_replace === "string" && rec.entry_id_to_replace.startsWith("cursor-bottom")) { const v = cursorOf(obj(obj(rec.entry)?.content)); if (v) bottom = v; } for (const child of Object.values(rec)) visit(child); }; visit(payload); return { instructions, ...(bottom ? { bottom } : {}) }; } 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; // Operation names and sizes only: what read.json may say of the capture. operations: TrendingOperation[]; responses: number; bytes: number; // THE CAPTURE SHOWS THE PAGE'S END (review 1 S2, review 2 N4). All of: // - no answer of the page failed: every one a 2xx whose body was kept, // carrying no GraphQL `errors`, and — for an operation that lists the // page's posts — carrying timeline instructions; // - the LAST answer of the listing operation is the CONTINUATION FROM THE // BOTTOM: its request carries the bottom cursor the answer before it // ended with (a refresh from the top, or any other cursor, that brings // nothing new says nothing about the bottom); // - and it brought no post the capture had not already seen. // False whenever the capture cannot tell — which cursor an answer was for // included. Only a capture that shows the end may be read as "what this // page no longer shows". // // PER TIMELINE (lane x-followups): a trending page has tabs, each its own // timeline, and one read may list two of them (Top, then Latest). The rule // above is asked of EACH timeline by itself (`timelines[].pageEnd`): its own // last answer, continuing from its own previous bottom cursor, bringing no // post that timeline had not shown. What one tab no longer shows says // nothing of the other. `pageEnd` here is the one timeline's when the // capture lists exactly one, and false for a capture that lists two. pageEnd: boolean; // What the page says of itself (trendPageOf), when an answer carried it. page?: TrendingPageInfo; // The timelines whose posts the capture lists, first listed first: the // timeline id its requests named (absent when they named none), the tab of // the page it is (when the page names that id), and how many of the page's // posts it showed first. // `postIds`: every post that timeline listed, in its own order (a post two // tabs show is in both); `pageEnd`: the capture shows that timeline's end. timelines: Array<{ timelineId?: string; tab?: string; posts: number; postIds: string[]; pageEnd: boolean }>; // Post id → the label of the tab that showed it first, for the posts whose // timeline is one of the page's tabs. tabs: Record; }; // The capture, parsed. `channelSlug` is the library's (a Post names its channel). // // WHICH ANSWERS ARE THE PAGE'S: every answer of an operation that is not in // X_TRENDING_IGNORED_OPS and lists posts. `pageTabsOnly` (review 3 S8; the // controller sets it when a tab of the read was abandoned because the page // changed) narrows that to the timelines the trend answer names as its own // tabs: an answer for any other timeline, or naming none, came from wherever // the page went, and is counted in the capture (operations, responses, // bytes) but not read. With no trend answer in the capture, no timeline is // the page's own and nothing is read. export function parseTrendingCapture( lines: ReadonlyArray, channelSlug: string, opts: { pageTabsOnly?: boolean } = {}, ): ParsedTrendingCapture { const own = opts.pageTabsOnly ? new Set( (lines .filter((l) => !X_TRENDING_IGNORED_OPS.includes(l.op) && l.body !== undefined && l.status >= 200 && l.status < 300) .map((l) => trendPageOf(l.body)) .find((pg) => pg !== undefined)?.tabs ?? [] ).map((t) => t.timelineId), ) : null; const raws: XTweetRaw[] = []; const media: Record = {}; const ops = new Map(); let bytes = 0; // Per answer of the page's own operations, in order: its operation, the // timeline it asked for, and how many posts it brought that no earlier // answer had. const answers: Array<{ op: string; timelineId?: string; fresh: number; freshOfTimeline: number; asked?: string; bottom?: string; instructions: boolean }> = []; // Timeline id ("" when a request named none) → the posts it listed, in order. const listedBy = new Map(); const seenIds = new Set(); // Post id → the timeline id of the answer that showed it first. const firstTimeline = new Map(); let page: TrendingPageInfo | undefined; let failed = false; 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 (X_TRENDING_IGNORED_OPS.includes(line.op)) continue; if (line.body === undefined || line.status < 200 || line.status >= 300) { failed = true; continue; } // A 200 that carries GraphQL errors answered only in part, or not at all. const errors = obj(line.body)?.errors; if (Array.isArray(errors) && errors.length > 0) failed = true; // The page itself: the first answer that carries it. page ??= trendPageOf(line.body); const asked = requestVariablesOf(line.url); // Not one of the page's own timelines, after the page changed: kept, unread. if (own && !(asked.timelineId !== undefined && own.has(asked.timelineId))) continue; const found = collectTimelineTweets(line.body); op.tweets += found.length; let fresh = 0; let freshOfTimeline = 0; const key = asked.timelineId ?? ""; for (const raw of found) { raws.push(raw); const id = xIdOf(raw); if (id) { const listed = listedBy.get(key) ?? []; listedBy.set(key, listed); if (!listed.includes(id)) { listed.push(id); freshOfTimeline++; } } if (id && !seenIds.has(id)) { seenIds.add(id); fresh++; if (asked.timelineId) firstTimeline.set(id, asked.timelineId); } const summary = mediaSummaryOf(raw); if (id && summary && !media[id]) media[id] = summary; } const shape = timelineShapeOf(line.body); answers.push({ op: line.op, fresh, freshOfTimeline, instructions: shape.instructions, ...(asked.timelineId ? { timelineId: asked.timelineId } : {}), ...(asked.cursor ? { asked: asked.cursor } : {}), ...(shape.bottom ? { bottom: shape.bottom } : {}), }); } // The answers of the operations that ever listed posts, in order. const listing = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0); if (listing.some((a) => !a.instructions)) failed = true; const timelineIds = [...new Set(listing.map((a) => a.timelineId).filter((id): id is string => id !== undefined))]; // One timeline's end: its own last answer continues from its own previous // bottom cursor (the same operation) and brought nothing that timeline had // not shown. const endOf = (key: string): boolean => { const own = listing.filter((a) => (a.timelineId ?? "") === key); const last = own.at(-1); const before = last ? own.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; return !failed && last !== undefined && before?.bottom !== undefined && last.asked === before.bottom && last.freshOfTimeline === 0; }; const keys = [...new Set(listing.map((a) => a.timelineId ?? ""))]; const pageEnd = keys.length === 1 && endOf(keys[0]); const posts = normalizeXTweets(raws, channelSlug); const kept: Record = {}; for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id]; // Which tab showed what: the page's tabs by the timeline id they list. const labelOf = new Map((page?.tabs ?? []).map((t) => [t.timelineId, t.label])); const tabs: Record = {}; const shownFirst = new Map(); for (const p of posts) { const timelineId = firstTimeline.get(p.id); const label = timelineId ? labelOf.get(timelineId) : undefined; if (label) tabs[p.id] = label; if (timelineId) shownFirst.set(timelineId, (shownFirst.get(timelineId) ?? 0) + 1); } const untagged = posts.length - [...shownFirst.values()].reduce((a, n) => a + n, 0); const isPost = new Set(posts.map((p) => p.id)); const listedOf = (key: string) => (listedBy.get(key) ?? []).filter((id) => isPost.has(id)); const timelines: ParsedTrendingCapture["timelines"] = timelineIds.map((timelineId) => ({ timelineId, ...(labelOf.get(timelineId) ? { tab: labelOf.get(timelineId)! } : {}), posts: shownFirst.get(timelineId) ?? 0, postIds: listedOf(timelineId), pageEnd: endOf(timelineId), })); if (untagged > 0 || (timelines.length === 0 && listing.length > 0)) { timelines.push({ posts: untagged, postIds: listedOf(""), pageEnd: keys.includes("") && endOf("") }); } return { posts, media: kept, operations: [...ops.values()].sort((a, b) => a.op.localeCompare(b.op)), responses: lines.length, bytes, pageEnd, ...(page ? { page } : {}), timelines, tabs, }; } // The saved file's lines; a line that is not JSON (a write cut short) is skipped. export async function readCaptureLines(file: string): Promise { 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; }