dp-worker 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/bird/ops.js +44 -0
  2. package/dist/bird/ops.js.map +1 -1
  3. package/dist/bird/sidecar-entry.js +16 -2
  4. package/dist/bird/sidecar-entry.js.map +1 -1
  5. package/dist/chrome-extension/omni-flow/manifest.json +1 -1
  6. package/node_modules/dp-shared/dist/bird-contracts.d.ts +308 -0
  7. package/node_modules/dp-shared/dist/bird-contracts.d.ts.map +1 -1
  8. package/node_modules/dp-shared/dist/bird-contracts.js +228 -0
  9. package/node_modules/dp-shared/dist/bird-contracts.js.map +1 -1
  10. package/node_modules/dp-shared/dist/post-drafts-contracts.d.ts +3 -3
  11. package/package.json +2 -2
  12. package/vendor/bird/LICENSE +21 -0
  13. package/vendor/bird/README.md +58 -0
  14. package/vendor/bird/dist/cli/pagination.d.ts +35 -0
  15. package/vendor/bird/dist/cli/pagination.js +43 -0
  16. package/vendor/bird/dist/cli/program.d.ts +5 -0
  17. package/vendor/bird/dist/cli/program.js +113 -0
  18. package/vendor/bird/dist/cli/shared.d.ts +77 -0
  19. package/vendor/bird/dist/cli/shared.js +327 -0
  20. package/vendor/bird/dist/cli.d.ts +12 -0
  21. package/vendor/bird/dist/cli.js +29 -0
  22. package/vendor/bird/dist/commands/bookmarks.d.ts +4 -0
  23. package/vendor/bird/dist/commands/bookmarks.js +189 -0
  24. package/vendor/bird/dist/commands/check.d.ts +4 -0
  25. package/vendor/bird/dist/commands/check.js +43 -0
  26. package/vendor/bird/dist/commands/follow.d.ts +4 -0
  27. package/vendor/bird/dist/commands/follow.js +91 -0
  28. package/vendor/bird/dist/commands/help.d.ts +4 -0
  29. package/vendor/bird/dist/commands/help.js +19 -0
  30. package/vendor/bird/dist/commands/home.d.ts +4 -0
  31. package/vendor/bird/dist/commands/home.js +43 -0
  32. package/vendor/bird/dist/commands/lists.d.ts +4 -0
  33. package/vendor/bird/dist/commands/lists.js +125 -0
  34. package/vendor/bird/dist/commands/news.d.ts +4 -0
  35. package/vendor/bird/dist/commands/news.js +131 -0
  36. package/vendor/bird/dist/commands/post.d.ts +4 -0
  37. package/vendor/bird/dist/commands/post.js +101 -0
  38. package/vendor/bird/dist/commands/query-ids.d.ts +4 -0
  39. package/vendor/bird/dist/commands/query-ids.js +80 -0
  40. package/vendor/bird/dist/commands/read.d.ts +4 -0
  41. package/vendor/bird/dist/commands/read.js +152 -0
  42. package/vendor/bird/dist/commands/search.d.ts +4 -0
  43. package/vendor/bird/dist/commands/search.js +115 -0
  44. package/vendor/bird/dist/commands/unbookmark.d.ts +4 -0
  45. package/vendor/bird/dist/commands/unbookmark.js +36 -0
  46. package/vendor/bird/dist/commands/user-tweets.d.ts +4 -0
  47. package/vendor/bird/dist/commands/user-tweets.js +109 -0
  48. package/vendor/bird/dist/commands/users.d.ts +4 -0
  49. package/vendor/bird/dist/commands/users.js +295 -0
  50. package/vendor/bird/dist/index.d.ts +2 -0
  51. package/vendor/bird/dist/index.js +2 -0
  52. package/vendor/bird/dist/lib/cli-args.d.ts +7 -0
  53. package/vendor/bird/dist/lib/cli-args.js +25 -0
  54. package/vendor/bird/dist/lib/cookies.d.ts +31 -0
  55. package/vendor/bird/dist/lib/cookies.js +81 -0
  56. package/vendor/bird/dist/lib/extract-bookmark-folder-id.d.ts +2 -0
  57. package/vendor/bird/dist/lib/extract-bookmark-folder-id.js +20 -0
  58. package/vendor/bird/dist/lib/extract-list-id.d.ts +2 -0
  59. package/vendor/bird/dist/lib/extract-list-id.js +19 -0
  60. package/vendor/bird/dist/lib/extract-tweet-id.d.ts +2 -0
  61. package/vendor/bird/dist/lib/extract-tweet-id.js +14 -0
  62. package/vendor/bird/dist/lib/features.json +17 -0
  63. package/vendor/bird/dist/lib/index.d.ts +10 -0
  64. package/vendor/bird/dist/lib/index.js +4 -0
  65. package/vendor/bird/dist/lib/normalize-handle.d.ts +6 -0
  66. package/vendor/bird/dist/lib/normalize-handle.js +31 -0
  67. package/vendor/bird/dist/lib/output.d.ts +29 -0
  68. package/vendor/bird/dist/lib/output.js +88 -0
  69. package/vendor/bird/dist/lib/paginate-cursor.d.ts +27 -0
  70. package/vendor/bird/dist/lib/paginate-cursor.js +37 -0
  71. package/vendor/bird/dist/lib/query-ids.json +20 -0
  72. package/vendor/bird/dist/lib/runtime-features.d.ts +19 -0
  73. package/vendor/bird/dist/lib/runtime-features.js +151 -0
  74. package/vendor/bird/dist/lib/runtime-query-ids.d.ts +33 -0
  75. package/vendor/bird/dist/lib/runtime-query-ids.js +264 -0
  76. package/vendor/bird/dist/lib/thread-filters.d.ts +8 -0
  77. package/vendor/bird/dist/lib/thread-filters.js +124 -0
  78. package/vendor/bird/dist/lib/twitter-client-base.d.ts +38 -0
  79. package/vendor/bird/dist/lib/twitter-client-base.js +129 -0
  80. package/vendor/bird/dist/lib/twitter-client-bookmarks.d.ts +7 -0
  81. package/vendor/bird/dist/lib/twitter-client-bookmarks.js +61 -0
  82. package/vendor/bird/dist/lib/twitter-client-constants.d.ts +43 -0
  83. package/vendor/bird/dist/lib/twitter-client-constants.js +50 -0
  84. package/vendor/bird/dist/lib/twitter-client-engagement.d.ts +16 -0
  85. package/vendor/bird/dist/lib/twitter-client-engagement.js +81 -0
  86. package/vendor/bird/dist/lib/twitter-client-features.d.ts +14 -0
  87. package/vendor/bird/dist/lib/twitter-client-features.js +347 -0
  88. package/vendor/bird/dist/lib/twitter-client-follow.d.ts +8 -0
  89. package/vendor/bird/dist/lib/twitter-client-follow.js +178 -0
  90. package/vendor/bird/dist/lib/twitter-client-home.d.ts +13 -0
  91. package/vendor/bird/dist/lib/twitter-client-home.js +138 -0
  92. package/vendor/bird/dist/lib/twitter-client-lists.d.ts +11 -0
  93. package/vendor/bird/dist/lib/twitter-client-lists.js +321 -0
  94. package/vendor/bird/dist/lib/twitter-client-media.d.ts +11 -0
  95. package/vendor/bird/dist/lib/twitter-client-media.js +136 -0
  96. package/vendor/bird/dist/lib/twitter-client-news.d.ts +47 -0
  97. package/vendor/bird/dist/lib/twitter-client-news.js +283 -0
  98. package/vendor/bird/dist/lib/twitter-client-posting.d.ts +8 -0
  99. package/vendor/bird/dist/lib/twitter-client-posting.js +218 -0
  100. package/vendor/bird/dist/lib/twitter-client-search.d.ts +19 -0
  101. package/vendor/bird/dist/lib/twitter-client-search.js +157 -0
  102. package/vendor/bird/dist/lib/twitter-client-timelines.d.ts +23 -0
  103. package/vendor/bird/dist/lib/twitter-client-timelines.js +471 -0
  104. package/vendor/bird/dist/lib/twitter-client-tweet-detail.d.ts +25 -0
  105. package/vendor/bird/dist/lib/twitter-client-tweet-detail.js +295 -0
  106. package/vendor/bird/dist/lib/twitter-client-types.d.ts +407 -0
  107. package/vendor/bird/dist/lib/twitter-client-types.js +2 -0
  108. package/vendor/bird/dist/lib/twitter-client-user-lookup.d.ts +16 -0
  109. package/vendor/bird/dist/lib/twitter-client-user-lookup.js +224 -0
  110. package/vendor/bird/dist/lib/twitter-client-user-tweets.d.ts +22 -0
  111. package/vendor/bird/dist/lib/twitter-client-user-tweets.js +154 -0
  112. package/vendor/bird/dist/lib/twitter-client-users.d.ts +9 -0
  113. package/vendor/bird/dist/lib/twitter-client-users.js +358 -0
  114. package/vendor/bird/dist/lib/twitter-client-utils.d.ts +173 -0
  115. package/vendor/bird/dist/lib/twitter-client-utils.js +511 -0
  116. package/vendor/bird/dist/lib/twitter-client.d.ts +23 -0
  117. package/vendor/bird/dist/lib/twitter-client.js +21 -0
  118. package/vendor/bird/dist/lib/version.d.ts +6 -0
  119. package/vendor/bird/dist/lib/version.js +174 -0
  120. package/vendor/bird/upstream-package.json +61 -0
@@ -0,0 +1,264 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ const DEFAULT_CACHE_FILENAME = 'query-ids-cache.json';
5
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
6
+ const DISCOVERY_PAGES = [
7
+ 'https://x.com/?lang=en',
8
+ 'https://x.com/explore',
9
+ 'https://x.com/notifications',
10
+ 'https://x.com/settings/profile',
11
+ ];
12
+ const BUNDLE_URL_REGEX = /https:\/\/abs\.twimg\.com\/responsive-web\/client-web(?:-legacy)?\/[A-Za-z0-9.-]+\.js/g;
13
+ const QUERY_ID_REGEX = /^[a-zA-Z0-9_-]+$/;
14
+ const OPERATION_PATTERNS = [
15
+ {
16
+ regex: /e\.exports=\{queryId\s*:\s*["']([^"']+)["']\s*,\s*operationName\s*:\s*["']([^"']+)["']/gs,
17
+ operationGroup: 2,
18
+ queryIdGroup: 1,
19
+ },
20
+ {
21
+ regex: /e\.exports=\{operationName\s*:\s*["']([^"']+)["']\s*,\s*queryId\s*:\s*["']([^"']+)["']/gs,
22
+ operationGroup: 1,
23
+ queryIdGroup: 2,
24
+ },
25
+ {
26
+ regex: /operationName\s*[:=]\s*["']([^"']+)["'](.{0,4000}?)queryId\s*[:=]\s*["']([^"']+)["']/gs,
27
+ operationGroup: 1,
28
+ queryIdGroup: 3,
29
+ },
30
+ {
31
+ regex: /queryId\s*[:=]\s*["']([^"']+)["'](.{0,4000}?)operationName\s*[:=]\s*["']([^"']+)["']/gs,
32
+ operationGroup: 3,
33
+ queryIdGroup: 1,
34
+ },
35
+ ];
36
+ const HEADERS = {
37
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
38
+ Accept: 'text/html,application/json;q=0.9,*/*;q=0.8',
39
+ 'Accept-Language': 'en-US,en;q=0.9',
40
+ };
41
+ async function fetchText(fetchImpl, url) {
42
+ const response = await fetchImpl(url, { headers: HEADERS });
43
+ if (!response.ok) {
44
+ const body = await response.text().catch(() => '');
45
+ throw new Error(`HTTP ${response.status} for ${url}: ${body.slice(0, 120)}`);
46
+ }
47
+ return response.text();
48
+ }
49
+ function resolveDefaultCachePath() {
50
+ const override = process.env.BIRD_QUERY_IDS_CACHE;
51
+ if (override && override.trim().length > 0) {
52
+ return path.resolve(override.trim());
53
+ }
54
+ return path.join(homedir(), '.config', 'bird', DEFAULT_CACHE_FILENAME);
55
+ }
56
+ function parseSnapshot(raw) {
57
+ if (!raw || typeof raw !== 'object') {
58
+ return null;
59
+ }
60
+ const record = raw;
61
+ const fetchedAt = typeof record.fetchedAt === 'string' ? record.fetchedAt : null;
62
+ const ttlMs = typeof record.ttlMs === 'number' && Number.isFinite(record.ttlMs) ? record.ttlMs : null;
63
+ const ids = record.ids && typeof record.ids === 'object' ? record.ids : null;
64
+ const discovery = record.discovery && typeof record.discovery === 'object' ? record.discovery : null;
65
+ if (!fetchedAt || !ttlMs || !ids || !discovery) {
66
+ return null;
67
+ }
68
+ const pages = Array.isArray(discovery.pages) ? discovery.pages : null;
69
+ const bundles = Array.isArray(discovery.bundles) ? discovery.bundles : null;
70
+ if (!pages || !bundles) {
71
+ return null;
72
+ }
73
+ const normalizedIds = {};
74
+ for (const [key, value] of Object.entries(ids)) {
75
+ if (typeof value === 'string' && value.trim().length > 0) {
76
+ normalizedIds[key] = value.trim();
77
+ }
78
+ }
79
+ return {
80
+ fetchedAt,
81
+ ttlMs,
82
+ ids: normalizedIds,
83
+ discovery: {
84
+ pages: pages.filter((p) => typeof p === 'string'),
85
+ bundles: bundles.filter((b) => typeof b === 'string'),
86
+ },
87
+ };
88
+ }
89
+ async function readSnapshotFromDisk(cachePath) {
90
+ try {
91
+ const raw = await readFile(cachePath, 'utf8');
92
+ return parseSnapshot(JSON.parse(raw));
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ async function writeSnapshotToDisk(cachePath, snapshot) {
99
+ await mkdir(path.dirname(cachePath), { recursive: true });
100
+ await writeFile(cachePath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
101
+ }
102
+ async function discoverBundles(fetchImpl) {
103
+ const bundles = new Set();
104
+ for (const page of DISCOVERY_PAGES) {
105
+ try {
106
+ const html = await fetchText(fetchImpl, page);
107
+ for (const match of html.matchAll(BUNDLE_URL_REGEX)) {
108
+ bundles.add(match[0]);
109
+ }
110
+ }
111
+ catch {
112
+ // ignore discovery page failures; other pages often work
113
+ }
114
+ }
115
+ const discovered = [...bundles];
116
+ if (discovered.length === 0) {
117
+ throw new Error('No client bundles discovered; x.com layout may have changed.');
118
+ }
119
+ return discovered;
120
+ }
121
+ function extractOperations(bundleContents, bundleLabel, targets, discovered) {
122
+ for (const pattern of OPERATION_PATTERNS) {
123
+ pattern.regex.lastIndex = 0;
124
+ while (true) {
125
+ const match = pattern.regex.exec(bundleContents);
126
+ if (match === null) {
127
+ break;
128
+ }
129
+ const operationName = match[pattern.operationGroup];
130
+ const queryId = match[pattern.queryIdGroup];
131
+ if (!operationName || !queryId) {
132
+ continue;
133
+ }
134
+ if (!targets.has(operationName)) {
135
+ continue;
136
+ }
137
+ if (!QUERY_ID_REGEX.test(queryId)) {
138
+ continue;
139
+ }
140
+ if (discovered.has(operationName)) {
141
+ continue;
142
+ }
143
+ discovered.set(operationName, { queryId, bundle: bundleLabel });
144
+ if (discovered.size === targets.size) {
145
+ return;
146
+ }
147
+ }
148
+ }
149
+ }
150
+ async function fetchAndExtract(fetchImpl, bundleUrls, targets) {
151
+ const discovered = new Map();
152
+ const CONCURRENCY = 6;
153
+ for (let i = 0; i < bundleUrls.length; i += CONCURRENCY) {
154
+ const chunk = bundleUrls.slice(i, i + CONCURRENCY);
155
+ await Promise.all(chunk.map(async (url) => {
156
+ if (discovered.size === targets.size) {
157
+ return;
158
+ }
159
+ const label = url.split('/').at(-1) ?? url;
160
+ try {
161
+ const js = await fetchText(fetchImpl, url);
162
+ extractOperations(js, label, targets, discovered);
163
+ }
164
+ catch {
165
+ // ignore failed bundles
166
+ }
167
+ }));
168
+ if (discovered.size === targets.size) {
169
+ break;
170
+ }
171
+ }
172
+ return discovered;
173
+ }
174
+ export function createRuntimeQueryIdStore(options = {}) {
175
+ const fetchImpl = options.fetchImpl ?? fetch;
176
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
177
+ const cachePath = options.cachePath ? path.resolve(options.cachePath) : resolveDefaultCachePath();
178
+ let memorySnapshot = null;
179
+ let loadOnce = null;
180
+ let refreshInFlight = null;
181
+ const loadSnapshot = async () => {
182
+ if (memorySnapshot) {
183
+ return memorySnapshot;
184
+ }
185
+ if (!loadOnce) {
186
+ loadOnce = (async () => {
187
+ const fromDisk = await readSnapshotFromDisk(cachePath);
188
+ memorySnapshot = fromDisk;
189
+ return fromDisk;
190
+ })();
191
+ }
192
+ return loadOnce;
193
+ };
194
+ const getSnapshotInfo = async () => {
195
+ const snapshot = await loadSnapshot();
196
+ if (!snapshot) {
197
+ return null;
198
+ }
199
+ const fetchedAtMs = new Date(snapshot.fetchedAt).getTime();
200
+ const ageMs = Number.isFinite(fetchedAtMs) ? Math.max(0, Date.now() - fetchedAtMs) : Number.POSITIVE_INFINITY;
201
+ const effectiveTtl = Number.isFinite(snapshot.ttlMs) ? snapshot.ttlMs : ttlMs;
202
+ const isFresh = ageMs <= effectiveTtl;
203
+ return { snapshot, cachePath, ageMs, isFresh };
204
+ };
205
+ const getQueryId = async (operationName) => {
206
+ const info = await getSnapshotInfo();
207
+ if (!info) {
208
+ return null;
209
+ }
210
+ return info.snapshot.ids[operationName] ?? null;
211
+ };
212
+ const refresh = async (operationNames, opts = {}) => {
213
+ if (refreshInFlight) {
214
+ return refreshInFlight;
215
+ }
216
+ refreshInFlight = (async () => {
217
+ const current = await getSnapshotInfo();
218
+ if (!opts.force && current?.isFresh) {
219
+ return current;
220
+ }
221
+ const targets = new Set(operationNames);
222
+ const bundleUrls = await discoverBundles(fetchImpl);
223
+ const discovered = await fetchAndExtract(fetchImpl, bundleUrls, targets);
224
+ if (discovered.size === 0) {
225
+ return current ?? null;
226
+ }
227
+ const ids = {};
228
+ for (const name of operationNames) {
229
+ const entry = discovered.get(name);
230
+ if (entry?.queryId) {
231
+ ids[name] = entry.queryId;
232
+ }
233
+ }
234
+ const snapshot = {
235
+ fetchedAt: new Date().toISOString(),
236
+ ttlMs,
237
+ ids,
238
+ discovery: {
239
+ pages: [...DISCOVERY_PAGES],
240
+ bundles: bundleUrls.map((url) => url.split('/').at(-1) ?? url),
241
+ },
242
+ };
243
+ await writeSnapshotToDisk(cachePath, snapshot);
244
+ memorySnapshot = snapshot;
245
+ return getSnapshotInfo();
246
+ })().finally(() => {
247
+ refreshInFlight = null;
248
+ });
249
+ return refreshInFlight;
250
+ };
251
+ return {
252
+ cachePath,
253
+ ttlMs,
254
+ getSnapshotInfo,
255
+ getQueryId,
256
+ refresh,
257
+ clearMemory() {
258
+ memorySnapshot = null;
259
+ loadOnce = null;
260
+ },
261
+ };
262
+ }
263
+ export const runtimeQueryIds = createRuntimeQueryIdStore();
264
+ //# sourceMappingURL=runtime-query-ids.js.map
@@ -0,0 +1,8 @@
1
+ import type { TweetData, TweetWithMeta } from './twitter-client-types.js';
2
+ export declare function filterAuthorChain(tweets: TweetData[], bookmarkedTweet: TweetData): TweetData[];
3
+ export declare function filterAuthorOnly(tweets: TweetData[], bookmarkedTweet: TweetData): TweetData[];
4
+ export declare function filterFullChain(tweets: TweetData[], bookmarkedTweet: TweetData, options?: {
5
+ includeAncestorBranches?: boolean;
6
+ }): TweetData[];
7
+ export declare function addThreadMetadata(tweet: TweetData, allConversationTweets: TweetData[]): TweetWithMeta;
8
+ //# sourceMappingURL=thread-filters.d.ts.map
@@ -0,0 +1,124 @@
1
+ const sortByCreatedAt = (tweets) => tweets.slice().sort((a, b) => {
2
+ const aTime = a.createdAt ? Date.parse(a.createdAt) : 0;
3
+ const bTime = b.createdAt ? Date.parse(b.createdAt) : 0;
4
+ return aTime - bTime;
5
+ });
6
+ export function filterAuthorChain(tweets, bookmarkedTweet) {
7
+ const author = bookmarkedTweet.author.username;
8
+ const byId = new Map(tweets.map((tweet) => [tweet.id, tweet]));
9
+ const chainIds = new Set();
10
+ let current = bookmarkedTweet;
11
+ while (current && current.author.username === author) {
12
+ chainIds.add(current.id);
13
+ const parentId = current.inReplyToStatusId;
14
+ if (!parentId) {
15
+ break;
16
+ }
17
+ const parent = byId.get(parentId);
18
+ if (!parent || parent.author.username !== author) {
19
+ break;
20
+ }
21
+ current = parent;
22
+ }
23
+ let changed = true;
24
+ while (changed) {
25
+ changed = false;
26
+ for (const tweet of tweets) {
27
+ if (tweet.author.username !== author) {
28
+ continue;
29
+ }
30
+ if (chainIds.has(tweet.id)) {
31
+ continue;
32
+ }
33
+ if (tweet.inReplyToStatusId && chainIds.has(tweet.inReplyToStatusId)) {
34
+ chainIds.add(tweet.id);
35
+ changed = true;
36
+ }
37
+ }
38
+ }
39
+ return sortByCreatedAt(tweets.filter((tweet) => chainIds.has(tweet.id)));
40
+ }
41
+ export function filterAuthorOnly(tweets, bookmarkedTweet) {
42
+ const author = bookmarkedTweet.author.username;
43
+ return tweets.filter((tweet) => tweet.author.username === author);
44
+ }
45
+ export function filterFullChain(tweets, bookmarkedTweet, options = {}) {
46
+ const byId = new Map(tweets.map((tweet) => [tweet.id, tweet]));
47
+ const repliesByParent = new Map();
48
+ for (const tweet of tweets) {
49
+ if (!tweet.inReplyToStatusId) {
50
+ continue;
51
+ }
52
+ const list = repliesByParent.get(tweet.inReplyToStatusId) ?? [];
53
+ list.push(tweet);
54
+ repliesByParent.set(tweet.inReplyToStatusId, list);
55
+ }
56
+ const chainIds = new Set();
57
+ const ancestorIds = [];
58
+ chainIds.add(bookmarkedTweet.id);
59
+ let current = bookmarkedTweet;
60
+ while (current?.inReplyToStatusId) {
61
+ const parent = byId.get(current.inReplyToStatusId);
62
+ if (!parent) {
63
+ break;
64
+ }
65
+ if (!chainIds.has(parent.id)) {
66
+ chainIds.add(parent.id);
67
+ ancestorIds.push(parent.id);
68
+ }
69
+ current = parent;
70
+ }
71
+ const addDescendants = (startIds) => {
72
+ const queue = [...startIds];
73
+ while (queue.length > 0) {
74
+ const currentId = queue.shift();
75
+ if (!currentId) {
76
+ continue;
77
+ }
78
+ if (!chainIds.has(currentId)) {
79
+ chainIds.add(currentId);
80
+ }
81
+ const replies = repliesByParent.get(currentId) ?? [];
82
+ for (const reply of replies) {
83
+ if (chainIds.has(reply.id)) {
84
+ continue;
85
+ }
86
+ chainIds.add(reply.id);
87
+ queue.push(reply.id);
88
+ }
89
+ }
90
+ };
91
+ addDescendants([bookmarkedTweet.id]);
92
+ if (options.includeAncestorBranches) {
93
+ for (const ancestorId of ancestorIds) {
94
+ addDescendants([ancestorId]);
95
+ }
96
+ }
97
+ return sortByCreatedAt(tweets.filter((tweet) => chainIds.has(tweet.id)));
98
+ }
99
+ export function addThreadMetadata(tweet, allConversationTweets) {
100
+ const author = tweet.author.username;
101
+ const hasSelfReplies = allConversationTweets.some((candidate) => candidate.inReplyToStatusId === tweet.id && candidate.author.username === author);
102
+ const isRoot = !tweet.inReplyToStatusId;
103
+ let threadPosition;
104
+ if (isRoot && !hasSelfReplies) {
105
+ threadPosition = 'standalone';
106
+ }
107
+ else if (isRoot && hasSelfReplies) {
108
+ threadPosition = 'root';
109
+ }
110
+ else if (!isRoot && hasSelfReplies) {
111
+ threadPosition = 'middle';
112
+ }
113
+ else {
114
+ threadPosition = 'end';
115
+ }
116
+ return {
117
+ ...tweet,
118
+ isThread: hasSelfReplies || !isRoot,
119
+ threadPosition,
120
+ hasSelfReplies,
121
+ threadRootId: tweet.conversationId ?? null,
122
+ };
123
+ }
124
+ //# sourceMappingURL=thread-filters.js.map
@@ -0,0 +1,38 @@
1
+ import { type OperationName } from './twitter-client-constants.js';
2
+ import type { CurrentUserResult, TwitterClientOptions } from './twitter-client-types.js';
3
+ export type Constructor<T = object> = new (...args: any[]) => T;
4
+ export type AbstractConstructor<T = object> = abstract new (...args: any[]) => T;
5
+ export type Mixin<TBase extends AbstractConstructor<TwitterClientBase>, TAdded> = abstract new (...args: ConstructorParameters<TBase>) => TwitterClientBase & TAdded;
6
+ export declare abstract class TwitterClientBase {
7
+ protected authToken: string;
8
+ protected ct0: string;
9
+ protected cookieHeader: string;
10
+ protected userAgent: string;
11
+ protected timeoutMs?: number;
12
+ protected quoteDepth: number;
13
+ protected clientUuid: string;
14
+ protected clientDeviceId: string;
15
+ protected clientUserId?: string;
16
+ constructor(options: TwitterClientOptions);
17
+ protected abstract getCurrentUser(): Promise<CurrentUserResult>;
18
+ protected sleep(ms: number): Promise<void>;
19
+ protected getQueryId(operationName: OperationName): Promise<string>;
20
+ protected refreshQueryIds(): Promise<void>;
21
+ protected withRefreshedQueryIdsOn404<T extends {
22
+ success: boolean;
23
+ had404?: boolean;
24
+ }>(attempt: () => Promise<T>): Promise<{
25
+ result: T;
26
+ refreshed: boolean;
27
+ }>;
28
+ protected getTweetDetailQueryIds(): Promise<string[]>;
29
+ protected getSearchTimelineQueryIds(): Promise<string[]>;
30
+ protected fetchWithTimeout(url: string, init: RequestInit): Promise<Response>;
31
+ protected getHeaders(): Record<string, string>;
32
+ protected createTransactionId(): string;
33
+ protected getBaseHeaders(): Record<string, string>;
34
+ protected getJsonHeaders(): Record<string, string>;
35
+ protected getUploadHeaders(): Record<string, string>;
36
+ protected ensureClientUserId(): Promise<void>;
37
+ }
38
+ //# sourceMappingURL=twitter-client-base.d.ts.map
@@ -0,0 +1,129 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { runtimeQueryIds } from './runtime-query-ids.js';
3
+ import { QUERY_IDS, TARGET_QUERY_ID_OPERATIONS } from './twitter-client-constants.js';
4
+ import { normalizeQuoteDepth } from './twitter-client-utils.js';
5
+ export class TwitterClientBase {
6
+ authToken;
7
+ ct0;
8
+ cookieHeader;
9
+ userAgent;
10
+ timeoutMs;
11
+ quoteDepth;
12
+ clientUuid;
13
+ clientDeviceId;
14
+ clientUserId;
15
+ constructor(options) {
16
+ if (!options.cookies.authToken || !options.cookies.ct0) {
17
+ throw new Error('Both authToken and ct0 cookies are required');
18
+ }
19
+ this.authToken = options.cookies.authToken;
20
+ this.ct0 = options.cookies.ct0;
21
+ this.cookieHeader = options.cookies.cookieHeader || `auth_token=${this.authToken}; ct0=${this.ct0}`;
22
+ this.userAgent =
23
+ options.userAgent ||
24
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
25
+ this.timeoutMs = options.timeoutMs;
26
+ this.quoteDepth = normalizeQuoteDepth(options.quoteDepth);
27
+ this.clientUuid = randomUUID();
28
+ this.clientDeviceId = randomUUID();
29
+ }
30
+ async sleep(ms) {
31
+ await new Promise((resolve) => setTimeout(resolve, ms));
32
+ }
33
+ async getQueryId(operationName) {
34
+ const cached = await runtimeQueryIds.getQueryId(operationName);
35
+ return cached ?? QUERY_IDS[operationName];
36
+ }
37
+ async refreshQueryIds() {
38
+ if (process.env.NODE_ENV === 'test') {
39
+ return;
40
+ }
41
+ try {
42
+ await runtimeQueryIds.refresh(TARGET_QUERY_ID_OPERATIONS, { force: true });
43
+ }
44
+ catch {
45
+ // ignore refresh failures; callers will fall back to baked-in IDs
46
+ }
47
+ }
48
+ async withRefreshedQueryIdsOn404(attempt) {
49
+ const firstAttempt = await attempt();
50
+ if (firstAttempt.success || !firstAttempt.had404) {
51
+ return { result: firstAttempt, refreshed: false };
52
+ }
53
+ await this.refreshQueryIds();
54
+ const secondAttempt = await attempt();
55
+ return { result: secondAttempt, refreshed: true };
56
+ }
57
+ async getTweetDetailQueryIds() {
58
+ const primary = await this.getQueryId('TweetDetail');
59
+ return Array.from(new Set([primary, '97JF30KziU00483E_8elBA', 'aFvUsJm2c-oDkJV75blV6g']));
60
+ }
61
+ async getSearchTimelineQueryIds() {
62
+ const primary = await this.getQueryId('SearchTimeline');
63
+ return Array.from(new Set([primary, 'M1jEez78PEfVfbQLvlWMvQ', '5h0kNbk3ii97rmfY6CdgAA', 'Tp1sewRU1AsZpBWhqCZicQ']));
64
+ }
65
+ async fetchWithTimeout(url, init) {
66
+ if (!this.timeoutMs || this.timeoutMs <= 0) {
67
+ return fetch(url, init);
68
+ }
69
+ const controller = new AbortController();
70
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
71
+ try {
72
+ return await fetch(url, { ...init, signal: controller.signal });
73
+ }
74
+ finally {
75
+ clearTimeout(timeoutId);
76
+ }
77
+ }
78
+ getHeaders() {
79
+ return this.getJsonHeaders();
80
+ }
81
+ createTransactionId() {
82
+ return randomBytes(16).toString('hex');
83
+ }
84
+ getBaseHeaders() {
85
+ const headers = {
86
+ accept: '*/*',
87
+ 'accept-language': 'en-US,en;q=0.9',
88
+ authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
89
+ 'x-csrf-token': this.ct0,
90
+ 'x-twitter-auth-type': 'OAuth2Session',
91
+ 'x-twitter-active-user': 'yes',
92
+ 'x-twitter-client-language': 'en',
93
+ 'x-client-uuid': this.clientUuid,
94
+ 'x-twitter-client-deviceid': this.clientDeviceId,
95
+ 'x-client-transaction-id': this.createTransactionId(),
96
+ cookie: this.cookieHeader,
97
+ 'user-agent': this.userAgent,
98
+ origin: 'https://x.com',
99
+ referer: 'https://x.com/',
100
+ };
101
+ if (this.clientUserId) {
102
+ headers['x-twitter-client-user-id'] = this.clientUserId;
103
+ }
104
+ return headers;
105
+ }
106
+ getJsonHeaders() {
107
+ return {
108
+ ...this.getBaseHeaders(),
109
+ 'content-type': 'application/json',
110
+ };
111
+ }
112
+ getUploadHeaders() {
113
+ // Note: do not set content-type; URLSearchParams/FormData need to set it (incl boundary) themselves.
114
+ return this.getBaseHeaders();
115
+ }
116
+ async ensureClientUserId() {
117
+ if (process.env.NODE_ENV === 'test') {
118
+ return;
119
+ }
120
+ if (this.clientUserId) {
121
+ return;
122
+ }
123
+ const result = await this.getCurrentUser();
124
+ if (result.success && result.user?.id) {
125
+ this.clientUserId = result.user.id;
126
+ }
127
+ }
128
+ }
129
+ //# sourceMappingURL=twitter-client-base.js.map
@@ -0,0 +1,7 @@
1
+ import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
2
+ import type { BookmarkMutationResult } from './twitter-client-types.js';
3
+ export interface TwitterClientBookmarkMethods {
4
+ unbookmark(tweetId: string): Promise<BookmarkMutationResult>;
5
+ }
6
+ export declare function withBookmarks<TBase extends AbstractConstructor<TwitterClientBase>>(Base: TBase): Mixin<TBase, TwitterClientBookmarkMethods>;
7
+ //# sourceMappingURL=twitter-client-bookmarks.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { TWITTER_API_BASE, TWITTER_GRAPHQL_POST_URL } from './twitter-client-constants.js';
2
+ export function withBookmarks(Base) {
3
+ class TwitterClientBookmarks extends Base {
4
+ // biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
5
+ constructor(...args) {
6
+ super(...args);
7
+ }
8
+ async unbookmark(tweetId) {
9
+ // TODO: verify if DeleteBookmark requires client user ID or additional payload fields; add ensureClientUserId() if needed (needs live API test).
10
+ const variables = { tweet_id: tweetId };
11
+ let queryId = await this.getQueryId('DeleteBookmark');
12
+ let urlWithOperation = `${TWITTER_API_BASE}/${queryId}/DeleteBookmark`;
13
+ const buildBody = () => JSON.stringify({ variables, queryId });
14
+ const buildHeaders = () => ({ ...this.getHeaders(), referer: `https://x.com/i/status/${tweetId}` });
15
+ let body = buildBody();
16
+ const parseResponse = async (response) => {
17
+ if (!response.ok) {
18
+ const text = await response.text();
19
+ return { success: false, error: `HTTP ${response.status}: ${text.slice(0, 200)}` };
20
+ }
21
+ const data = (await response.json());
22
+ if (data.errors && data.errors.length > 0) {
23
+ return { success: false, error: data.errors.map((e) => e.message).join(', ') };
24
+ }
25
+ return { success: true };
26
+ };
27
+ try {
28
+ let response = await this.fetchWithTimeout(urlWithOperation, {
29
+ method: 'POST',
30
+ headers: buildHeaders(),
31
+ body,
32
+ });
33
+ if (response.status === 404) {
34
+ await this.refreshQueryIds();
35
+ queryId = await this.getQueryId('DeleteBookmark');
36
+ urlWithOperation = `${TWITTER_API_BASE}/${queryId}/DeleteBookmark`;
37
+ body = buildBody();
38
+ response = await this.fetchWithTimeout(urlWithOperation, {
39
+ method: 'POST',
40
+ headers: buildHeaders(),
41
+ body,
42
+ });
43
+ if (response.status === 404) {
44
+ const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
45
+ method: 'POST',
46
+ headers: buildHeaders(),
47
+ body,
48
+ });
49
+ return parseResponse(retry);
50
+ }
51
+ }
52
+ return parseResponse(response);
53
+ }
54
+ catch (error) {
55
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
56
+ }
57
+ }
58
+ }
59
+ return TwitterClientBookmarks;
60
+ }
61
+ //# sourceMappingURL=twitter-client-bookmarks.js.map
@@ -0,0 +1,43 @@
1
+ export declare const TWITTER_API_BASE = "https://x.com/i/api/graphql";
2
+ export declare const TWITTER_GRAPHQL_POST_URL = "https://x.com/i/api/graphql";
3
+ export declare const TWITTER_UPLOAD_URL = "https://upload.twitter.com/i/media/upload.json";
4
+ export declare const TWITTER_MEDIA_METADATA_URL = "https://x.com/i/api/1.1/media/metadata/create.json";
5
+ export declare const TWITTER_STATUS_UPDATE_URL = "https://x.com/i/api/1.1/statuses/update.json";
6
+ export declare const SETTINGS_SCREEN_NAME_REGEX: RegExp;
7
+ export declare const SETTINGS_USER_ID_REGEX: RegExp;
8
+ export declare const SETTINGS_NAME_REGEX: RegExp;
9
+ export declare const FALLBACK_QUERY_IDS: {
10
+ readonly CreateTweet: "TAJw1rBsjAtdNgTdlo2oeg";
11
+ readonly CreateRetweet: "ojPdsZsimiJrUGLR1sjUtA";
12
+ readonly DeleteRetweet: "iQtK4dl5hBmXewYZuEOKVw";
13
+ readonly CreateFriendship: "8h9JVdV8dlSyqyRDJEPCsA";
14
+ readonly DestroyFriendship: "ppXWuagMNXgvzx6WoXBW0Q";
15
+ readonly FavoriteTweet: "lI07N6Otwv1PhnEgXILM7A";
16
+ readonly UnfavoriteTweet: "ZYKSe-w7KEslx3JhSIk5LA";
17
+ readonly CreateBookmark: "aoDbu3RHznuiSkQ9aNM67Q";
18
+ readonly DeleteBookmark: "Wlmlj2-xzyS1GN3a6cj-mQ";
19
+ readonly TweetDetail: "97JF30KziU00483E_8elBA";
20
+ readonly SearchTimeline: "M1jEez78PEfVfbQLvlWMvQ";
21
+ readonly UserArticlesTweets: "8zBy9h4L90aDL02RsBcCFg";
22
+ readonly UserTweets: "Wms1GvIiHXAPBaCr9KblaA";
23
+ readonly Bookmarks: "RV1g3b8n_SGOHwkqKYSCFw";
24
+ readonly Following: "BEkNpEt5pNETESoqMsTEGA";
25
+ readonly Followers: "kuFUYP9eV1FPoEy4N-pi7w";
26
+ readonly Likes: "JR2gceKucIKcVNB_9JkhsA";
27
+ readonly BookmarkFolderTimeline: "KJIQpsvxrTfRIlbaRIySHQ";
28
+ readonly ListOwnerships: "wQcOSjSQ8NtgxIwvYl1lMg";
29
+ readonly ListMemberships: "BlEXXdARdSeL_0KyKHHvvg";
30
+ readonly ListLatestTweetsTimeline: "2TemLyqrMpTeAmysdbnVqw";
31
+ readonly ListByRestId: "wXzyA5vM_aVkBL9G8Vp3kw";
32
+ readonly HomeTimeline: "edseUwk9sP5Phz__9TIRnA";
33
+ readonly HomeLatestTimeline: "iOEZpOdfekFsxSlPQCQtPg";
34
+ readonly ExploreSidebar: "lpSN4M6qpimkF4nRFPE3nQ";
35
+ readonly ExplorePage: "kheAINB_4pzRDqkzG3K-ng";
36
+ readonly GenericTimelineById: "uGSr7alSjR9v6QJAIaqSKQ";
37
+ readonly TrendHistory: "Sj4T-jSB9pr0Mxtsc1UKZQ";
38
+ readonly AboutAccountQuery: "zs_jFPFT78rBpXv9Z3U2YQ";
39
+ };
40
+ export type OperationName = keyof typeof FALLBACK_QUERY_IDS;
41
+ export declare const QUERY_IDS: Record<OperationName, string>;
42
+ export declare const TARGET_QUERY_ID_OPERATIONS: Array<OperationName>;
43
+ //# sourceMappingURL=twitter-client-constants.d.ts.map