128 lines
6.2 KiB
TypeScript
128 lines
6.2 KiB
TypeScript
// L1c: X's live engagement counts. On a post page X subscribes to `/tweet_engagement/<id>` on its
|
|
// live pipeline (a streamed `fetch` of `https://api.x.com/live_pipeline/events`, one `data: {json}`
|
|
// line per message) and its action bar shows `max(liveCounts.likeCount, favorite_count)`, where each
|
|
// pushed `like_count` is also merged with `max`, and only X's own click handler ever lowers the live
|
|
// value (-1 on unlike). A push sent while a like/unlike is still on its way (live 2026-09-28: the
|
|
// FavoriteTweet push `like_count: "3"` arrived ~400 ms after the request, when the post was already
|
|
// unliked again) therefore raises the count for good: UI "3 Likes. Like" while X's store and the
|
|
// server both say 2, until a reload. Same `max` merge for `retweet_count` and `bookmark_count`.
|
|
//
|
|
// While the viewer's own like/repost/bookmark request for a post is in flight, and for
|
|
// LIVE_QUIET_MS after the last one ended, the matching count field is removed from that post's
|
|
// pushes; X's own optimistic ±1 bookkeeping (which follows every click) stays in charge. Other
|
|
// fields, other posts and every other message pass through byte for byte.
|
|
|
|
export type CountKind = 'like' | 'retweet' | 'bookmark';
|
|
|
|
const FIELD: Record<CountKind, string> = { like: 'like_count', retweet: 'retweet_count', bookmark: 'bookmark_count' };
|
|
/** How long after the viewer's last request for a post its pushed count is still treated as stale. */
|
|
export const LIVE_QUIET_MS = 5000;
|
|
const TOPIC = /^\/tweet_engagement\/(\d{1,25})$/;
|
|
const PIPELINE_PATH = '/live_pipeline/events';
|
|
|
|
/** X's live pipeline event stream (api.x.com, or api.twitter.com on twitter.com). */
|
|
export function isLivePipelineUrl(raw: string): boolean {
|
|
if (!raw.includes(PIPELINE_PATH)) return false;
|
|
try {
|
|
const url = new URL(raw);
|
|
return url.protocol === 'https:' && (url.hostname === 'api.x.com' || url.hostname === 'api.twitter.com') && url.pathname === PIPELINE_PATH;
|
|
} catch { return false; }
|
|
}
|
|
|
|
export type CountHold = {
|
|
begin(kind: CountKind, id: string): void;
|
|
end(kind: CountKind, id: string): void;
|
|
held(kind: CountKind, id: string): boolean;
|
|
size(): number;
|
|
};
|
|
|
|
/** Per post and count: requests in flight, and the time until which pushes are still stale. */
|
|
export function createCountHold(now: () => number = Date.now): CountHold {
|
|
const entries = new Map<string, { pending: number; until: number }>();
|
|
return {
|
|
begin(kind, id) {
|
|
const key = `${kind}:${id}`;
|
|
const entry = entries.get(key) ?? { pending: 0, until: 0 };
|
|
entry.pending++;
|
|
entries.set(key, entry);
|
|
},
|
|
end(kind, id) {
|
|
const entry = entries.get(`${kind}:${id}`);
|
|
if (!entry) return;
|
|
entry.pending = Math.max(0, entry.pending - 1);
|
|
entry.until = now() + LIVE_QUIET_MS;
|
|
},
|
|
held(kind, id) {
|
|
const key = `${kind}:${id}`;
|
|
const entry = entries.get(key);
|
|
if (!entry) return false;
|
|
if (entry.pending > 0 || now() < entry.until) return true;
|
|
entries.delete(key);
|
|
return false;
|
|
},
|
|
size: () => entries.size,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* One line of the event stream. A `data:` line of a `/tweet_engagement/<id>` message loses the
|
|
* held count fields; anything else (and anything unparsable) is returned unchanged.
|
|
*/
|
|
export function filterLiveLine(line: string, held: (kind: CountKind, id: string) => boolean, onDrop?: () => void): string {
|
|
if (!line.startsWith('data:') || !line.includes('tweet_engagement')) return line;
|
|
const cr = line.endsWith('\r') ? '\r' : '';
|
|
let message: unknown;
|
|
try { message = JSON.parse(line.slice(5, line.length - cr.length)); } catch { return line; }
|
|
if (!message || typeof message !== 'object') return line;
|
|
const { topic, payload } = message as { topic?: unknown; payload?: { tweet_engagement?: unknown } };
|
|
const id = typeof topic === 'string' ? TOPIC.exec(topic)?.[1] : undefined;
|
|
const counts = payload && typeof payload === 'object' ? payload.tweet_engagement : undefined;
|
|
if (!id || !counts || typeof counts !== 'object' || Array.isArray(counts)) return line;
|
|
let next: Record<string, unknown> | null = null;
|
|
for (const kind of Object.keys(FIELD) as CountKind[]) {
|
|
const field = FIELD[kind];
|
|
if (!(field in counts) || !held(kind, id)) continue;
|
|
next ??= { ...(counts as Record<string, unknown>) };
|
|
delete next[field];
|
|
onDrop?.();
|
|
}
|
|
if (!next) return line;
|
|
return `data: ${JSON.stringify({ ...(message as object), payload: { ...payload, tweet_engagement: next } })}${cr}`;
|
|
}
|
|
|
|
/** The event stream with `filterLiveLine` applied to every complete line; cancel reaches the source. */
|
|
export function filterLiveStream(source: ReadableStream<Uint8Array>, held: (kind: CountKind, id: string) => boolean, onDrop?: () => void): ReadableStream<Uint8Array> {
|
|
const reader = source.getReader();
|
|
const decoder = new TextDecoder('utf-8');
|
|
const encoder = new TextEncoder();
|
|
let rest = '';
|
|
return new ReadableStream<Uint8Array>({
|
|
async pull(controller) {
|
|
for (;;) {
|
|
let chunk: ReadableStreamReadResult<Uint8Array>;
|
|
try { chunk = await reader.read(); } catch (error) { controller.error(error); return; }
|
|
if (chunk.done) {
|
|
const tail = rest + decoder.decode();
|
|
rest = '';
|
|
if (tail) controller.enqueue(encoder.encode(filterLiveLine(tail, held, onDrop)));
|
|
controller.close();
|
|
return;
|
|
}
|
|
const lines = (rest + decoder.decode(chunk.value, { stream: true })).split('\n');
|
|
rest = lines.pop() ?? '';
|
|
if (!lines.length) continue;
|
|
controller.enqueue(encoder.encode(lines.map(line => filterLiveLine(line, held, onDrop)).join('\n') + '\n'));
|
|
return;
|
|
}
|
|
},
|
|
cancel(reason) { return reader.cancel(reason); },
|
|
});
|
|
}
|
|
|
|
/** X's response with the filtered stream as its body (same status, headers and URL). */
|
|
export function withFilteredBody(response: Response, held: (kind: CountKind, id: string) => boolean, onDrop?: () => void): Response {
|
|
if (!response.ok || !response.body) return response;
|
|
const filtered = new Response(filterLiveStream(response.body, held, onDrop), { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
try { Object.defineProperty(filtered, 'url', { value: response.url }); } catch { /* ignore */ }
|
|
return filtered;
|
|
}
|