| 1 | import { randomBytes } from 'node:crypto'; |
| 2 | import { chmod, lstat, mkdir, readFile, realpath, rename, unlink, writeFile } from 'node:fs/promises'; |
| 3 | import { homedir, tmpdir } from 'node:os'; |
| 4 | import path from 'node:path'; |
| 5 | const DEFAULT_CACHE_FILENAME = 'query-ids-cache.json'; |
| 6 | const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; |
| 7 | const DEFAULT_FETCH_TIMEOUT_MS = 10_000; |
| 8 | const DEFAULT_REFRESH_TIMEOUT_MS = 15_000; |
| 9 | const DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024; |
| 10 | const DEFAULT_MAX_BUNDLES = 30; |
| 11 | const DEFAULT_MAX_REDIRECTS = 5; |
| 12 | const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); |
| 13 | const ALLOWED_DISCOVERY_HOSTS = new Set(['x.com', 'abs.twimg.com']); |
| 14 | const DISCOVERY_PAGES = [ |
| 15 | 'https://x.com/?lang=en', |
| 16 | 'https://x.com/explore', |
| 17 | 'https://x.com/notifications', |
| 18 | 'https://x.com/settings/profile', |
| 19 | ]; |
| 20 | const BUNDLE_URL_REGEX = /https:\/\/abs\.twimg\.com\/responsive-web\/client-web(?:-legacy)?\/[A-Za-z0-9.-]+\.js/g; |
| 21 | export const QUERY_ID_REGEX = /^[a-zA-Z0-9_-]+$/; |
| 22 | const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); |
| 23 | const OPERATION_PATTERNS = [ |
| 24 | { |
| 25 | regex: /e\.exports=\{queryId\s*:\s*["']([^"']+)["']\s*,\s*operationName\s*:\s*["']([^"']+)["']/gs, |
| 26 | operationGroup: 2, |
| 27 | queryIdGroup: 1, |
| 28 | }, |
| 29 | { |
| 30 | regex: /e\.exports=\{operationName\s*:\s*["']([^"']+)["']\s*,\s*queryId\s*:\s*["']([^"']+)["']/gs, |
| 31 | operationGroup: 1, |
| 32 | queryIdGroup: 2, |
| 33 | }, |
| 34 | { |
| 35 | regex: /operationName\s*[:=]\s*["']([^"']+)["'](.{0,4000}?)queryId\s*[:=]\s*["']([^"']+)["']/gs, |
| 36 | operationGroup: 1, |
| 37 | queryIdGroup: 3, |
| 38 | }, |
| 39 | { |
| 40 | regex: /queryId\s*[:=]\s*["']([^"']+)["'](.{0,4000}?)operationName\s*[:=]\s*["']([^"']+)["']/gs, |
| 41 | operationGroup: 3, |
| 42 | queryIdGroup: 1, |
| 43 | }, |
| 44 | ]; |
| 45 | const HEADERS = { |
| 46 | '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', |
| 47 | Accept: 'text/html,application/json;q=0.9,*/*;q=0.8', |
| 48 | 'Accept-Language': 'en-US,en;q=0.9', |
| 49 | }; |
| 50 | export function createAbortError(reason) { |
| 51 | if (reason instanceof Error) { |
| 52 | return reason; |
| 53 | } |
| 54 | const message = typeof reason === 'string' && reason ? reason : 'The operation was aborted'; |
| 55 | const err = new Error(message); |
| 56 | err.name = 'AbortError'; |
| 57 | return err; |
| 58 | } |
| 59 | export async function raceWithAbort(promise, signal) { |
| 60 | if (!signal) { |
| 61 | return promise; |
| 62 | } |
| 63 | if (signal.aborted) { |
| 64 | promise.catch(() => {}); |
| 65 | throw createAbortError(signal.reason); |
| 66 | } |
| 67 | promise.catch(() => {}); |
| 68 | let onAbort; |
| 69 | const abortPromise = new Promise((_, reject) => { |
| 70 | onAbort = () => reject(createAbortError(signal.reason)); |
| 71 | signal.addEventListener('abort', onAbort, { once: true }); |
| 72 | }); |
| 73 | try { |
| 74 | return await Promise.race([promise, abortPromise]); |
| 75 | } |
| 76 | finally { |
| 77 | signal.removeEventListener('abort', onAbort); |
| 78 | } |
| 79 | } |
| 80 | export function validateDiscoveryUrl(rawUrl) { |
| 81 | let parsed; |
| 82 | try { |
| 83 | parsed = rawUrl instanceof URL ? rawUrl : new URL(rawUrl); |
| 84 | } |
| 85 | catch { |
| 86 | throw new Error(`Invalid discovery URL: ${String(rawUrl)}`); |
| 87 | } |
| 88 | if (parsed.protocol !== 'https:') { |
| 89 | throw new Error(`Blocked non-HTTPS discovery URL: ${parsed.protocol}`); |
| 90 | } |
| 91 | if (parsed.username || parsed.password) { |
| 92 | throw new Error('Blocked discovery URL with credentials'); |
| 93 | } |
| 94 | if (parsed.port !== '') { |
| 95 | throw new Error(`Blocked discovery URL with non-default port: ${parsed.port}`); |
| 96 | } |
| 97 | const host = parsed.hostname.toLowerCase(); |
| 98 | if (!ALLOWED_DISCOVERY_HOSTS.has(host)) { |
| 99 | throw new Error(`Blocked discovery URL host: ${host}`); |
| 100 | } |
| 101 | return parsed; |
| 102 | } |
| 103 | function truncateUtf8Bytes(buf, maxBytes) { |
| 104 | if (maxBytes <= 0) { |
| 105 | return ''; |
| 106 | } |
| 107 | let end = Math.min(buf.byteLength, maxBytes); |
| 108 | if (end < buf.byteLength && (buf[end] & 0xc0) === 0x80) { |
| 109 | let start = end - 1; |
| 110 | while (start > 0 && (buf[start] & 0xc0) === 0x80) { |
| 111 | start -= 1; |
| 112 | } |
| 113 | end = start; |
| 114 | } |
| 115 | return buf.subarray(0, end).toString('utf8'); |
| 116 | } |
| 117 | export async function readResponseTextBounded(response, maxBytes, signal, { truncateOnLimit = false } = {}) { |
| 118 | if (signal?.aborted) { |
| 119 | await response.body?.cancel().catch(() => {}); |
| 120 | throw createAbortError(signal.reason); |
| 121 | } |
| 122 | const contentLengthHeader = response.headers?.get?.('content-length'); |
| 123 | if (!truncateOnLimit && contentLengthHeader) { |
| 124 | const declared = Number.parseInt(contentLengthHeader, 10); |
| 125 | if (Number.isFinite(declared) && declared > maxBytes) { |
| 126 | await response.body?.cancel().catch(() => {}); |
| 127 | throw new Error(`Response exceeded ${maxBytes} byte limit`); |
| 128 | } |
| 129 | } |
| 130 | if (response.body && typeof response.body.getReader === 'function') { |
| 131 | const reader = response.body.getReader(); |
| 132 | const decoder = new TextDecoder('utf-8'); |
| 133 | let totalBytes = 0; |
| 134 | let text = ''; |
| 135 | const onAbort = () => { |
| 136 | reader.cancel().catch(() => {}); |
| 137 | }; |
| 138 | if (signal) { |
| 139 | signal.addEventListener('abort', onAbort, { once: true }); |
| 140 | } |
| 141 | try { |
| 142 | while (true) { |
| 143 | const { done, value } = await raceWithAbort(reader.read(), signal); |
| 144 | if (signal?.aborted) { |
| 145 | throw createAbortError(signal.reason); |
| 146 | } |
| 147 | if (done) { |
| 148 | break; |
| 149 | } |
| 150 | if (value && value.byteLength > 0) { |
| 151 | if (totalBytes + value.byteLength > maxBytes) { |
| 152 | if (truncateOnLimit) { |
| 153 | const remaining = Math.max(0, maxBytes - totalBytes); |
| 154 | if (remaining > 0) { |
| 155 | text += decoder.decode(value.subarray(0, remaining), { stream: true }); |
| 156 | } |
| 157 | await reader.cancel().catch(() => {}); |
| 158 | break; |
| 159 | } |
| 160 | await reader.cancel().catch(() => {}); |
| 161 | throw new Error(`Response exceeded ${maxBytes} byte limit`); |
| 162 | } |
| 163 | totalBytes += value.byteLength; |
| 164 | text += decoder.decode(value, { stream: true }); |
| 165 | } |
| 166 | } |
| 167 | if (signal?.aborted) { |
| 168 | throw createAbortError(signal.reason); |
| 169 | } |
| 170 | text += decoder.decode(); |
| 171 | return text; |
| 172 | } |
| 173 | finally { |
| 174 | if (signal) { |
| 175 | signal.removeEventListener('abort', onAbort); |
| 176 | } |
| 177 | try { |
| 178 | reader.releaseLock(); |
| 179 | } |
| 180 | catch { |
| 181 | // ignore |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | let text = null; |
| 186 | if (typeof response.text === 'function') { |
| 187 | text = await raceWithAbort(response.text(), signal); |
| 188 | } |
| 189 | else if (typeof response.json === 'function') { |
| 190 | const parsed = await raceWithAbort(response.json(), signal); |
| 191 | text = JSON.stringify(parsed ?? null); |
| 192 | } |
| 193 | if (text !== null) { |
| 194 | if (signal?.aborted) { |
| 195 | throw createAbortError(signal.reason); |
| 196 | } |
| 197 | const buf = Buffer.from(text, 'utf8'); |
| 198 | if (buf.byteLength > maxBytes) { |
| 199 | if (truncateOnLimit) { |
| 200 | return truncateUtf8Bytes(buf, maxBytes); |
| 201 | } |
| 202 | throw new Error(`Response exceeded ${maxBytes} byte limit`); |
| 203 | } |
| 204 | return text; |
| 205 | } |
| 206 | return ''; |
| 207 | } |
| 208 | async function fetchText(fetchImpl, url, opts = {}) { |
| 209 | const fetchTimeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS; |
| 210 | const maxBytes = opts.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES; |
| 211 | const maxRedirects = opts.maxRedirects ?? DEFAULT_MAX_REDIRECTS; |
| 212 | const deadlineMs = opts.deadlineMs; |
| 213 | const callerSignal = opts.signal; |
| 214 | |
| 215 | let currentUrl = validateDiscoveryUrl(url).toString(); |
| 216 | const controller = new AbortController(); |
| 217 | let timeoutId = null; |
| 218 | const onCallerAbort = () => controller.abort(callerSignal.reason); |
| 219 | if (callerSignal) { |
| 220 | if (callerSignal.aborted) { |
| 221 | throw createAbortError(callerSignal.reason); |
| 222 | } |
| 223 | callerSignal.addEventListener('abort', onCallerAbort, { once: true }); |
| 224 | } |
| 225 | const remainingMs = deadlineMs !== undefined ? deadlineMs - Date.now() : fetchTimeoutMs; |
| 226 | const effectiveTimeoutMs = Math.min(fetchTimeoutMs, remainingMs); |
| 227 | if (!Number.isFinite(effectiveTimeoutMs) || effectiveTimeoutMs <= 0) { |
| 228 | if (callerSignal) { |
| 229 | callerSignal.removeEventListener('abort', onCallerAbort); |
| 230 | } |
| 231 | throw createAbortError('Discovery refresh timed out'); |
| 232 | } |
| 233 | timeoutId = setTimeout(() => { |
| 234 | controller.abort(createAbortError(`Discovery request timed out after ${effectiveTimeoutMs}ms`)); |
| 235 | }, effectiveTimeoutMs); |
| 236 | |
| 237 | try { |
| 238 | let redirects = 0; |
| 239 | while (true) { |
| 240 | const response = await raceWithAbort( |
| 241 | fetchImpl(currentUrl, { |
| 242 | headers: HEADERS, |
| 243 | redirect: 'manual', |
| 244 | signal: controller.signal, |
| 245 | }), |
| 246 | controller.signal, |
| 247 | ); |
| 248 | if (response.url) { |
| 249 | try { |
| 250 | validateDiscoveryUrl(response.url); |
| 251 | } |
| 252 | catch (err) { |
| 253 | await response.body?.cancel().catch(() => {}); |
| 254 | throw err; |
| 255 | } |
| 256 | } |
| 257 | if (REDIRECT_STATUSES.has(response.status)) { |
| 258 | await response.body?.cancel().catch(() => {}); |
| 259 | const location = response.headers?.get?.('location'); |
| 260 | if (!location) { |
| 261 | throw new Error(`HTTP ${response.status} redirect without Location for ${currentUrl}`); |
| 262 | } |
| 263 | if (redirects >= maxRedirects) { |
| 264 | throw new Error(`Too many redirects while fetching ${url}`); |
| 265 | } |
| 266 | currentUrl = validateDiscoveryUrl(new URL(location, currentUrl)).toString(); |
| 267 | redirects += 1; |
| 268 | continue; |
| 269 | } |
| 270 | if (!response.ok) { |
| 271 | let body = ''; |
| 272 | try { |
| 273 | body = await readResponseTextBounded( |
| 274 | response, |
| 275 | 512, |
| 276 | controller.signal, |
| 277 | { truncateOnLimit: true }, |
| 278 | ); |
| 279 | } |
| 280 | catch (err) { |
| 281 | if (controller.signal.aborted || err?.name === 'AbortError') { |
| 282 | throw err; |
| 283 | } |
| 284 | } |
| 285 | throw new Error(`HTTP ${response.status} for ${currentUrl}: ${body.slice(0, 120)}`); |
| 286 | } |
| 287 | return await readResponseTextBounded(response, maxBytes, controller.signal); |
| 288 | } |
| 289 | } |
| 290 | finally { |
| 291 | if (timeoutId !== null) { |
| 292 | clearTimeout(timeoutId); |
| 293 | } |
| 294 | if (callerSignal) { |
| 295 | callerSignal.removeEventListener('abort', onCallerAbort); |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | function resolveDefaultCachePath() { |
| 300 | const override = process.env.BIRD_QUERY_IDS_CACHE; |
| 301 | if (override && override.trim().length > 0) { |
| 302 | return path.resolve(override.trim()); |
| 303 | } |
| 304 | return path.join(homedir(), '.config', 'bird', DEFAULT_CACHE_FILENAME); |
| 305 | } |
| 306 | export function parseSnapshot(raw) { |
| 307 | if (!raw || typeof raw !== 'object') { |
| 308 | return null; |
| 309 | } |
| 310 | const record = raw; |
| 311 | const fetchedAt = typeof record.fetchedAt === 'string' ? record.fetchedAt : null; |
| 312 | const ttlMs = typeof record.ttlMs === 'number' && Number.isFinite(record.ttlMs) ? record.ttlMs : null; |
| 313 | const ids = record.ids && typeof record.ids === 'object' && !Array.isArray(record.ids) ? record.ids : null; |
| 314 | const discovery = record.discovery && typeof record.discovery === 'object' ? record.discovery : null; |
| 315 | if (!fetchedAt || !ttlMs || !ids || !discovery) { |
| 316 | return null; |
| 317 | } |
| 318 | const pages = Array.isArray(discovery.pages) ? discovery.pages : null; |
| 319 | const bundles = Array.isArray(discovery.bundles) ? discovery.bundles : null; |
| 320 | if (!pages || !bundles) { |
| 321 | return null; |
| 322 | } |
| 323 | const normalizedIds = Object.create(null); |
| 324 | for (const [key, value] of Object.entries(ids)) { |
| 325 | if (FORBIDDEN_KEYS.has(key)) { |
| 326 | continue; |
| 327 | } |
| 328 | if (typeof value === 'string') { |
| 329 | const trimmed = value.trim(); |
| 330 | if (trimmed.length > 0 && QUERY_ID_REGEX.test(trimmed)) { |
| 331 | normalizedIds[key] = trimmed; |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | return { |
| 336 | fetchedAt, |
| 337 | ttlMs, |
| 338 | ids: normalizedIds, |
| 339 | discovery: { |
| 340 | pages: pages.filter((p) => typeof p === 'string'), |
| 341 | bundles: bundles.filter((b) => typeof b === 'string'), |
| 342 | }, |
| 343 | }; |
| 344 | } |
| 345 | async function readSnapshotFromDisk(cachePath) { |
| 346 | try { |
| 347 | const raw = await readFile(cachePath, 'utf8'); |
| 348 | return parseSnapshot(JSON.parse(raw)); |
| 349 | } |
| 350 | catch { |
| 351 | return null; |
| 352 | } |
| 353 | } |
| 354 | async function resolveTrustedCacheRoot(resolvedDir) { |
| 355 | const rawRoots = [homedir(), tmpdir()]; |
| 356 | if (process.platform === 'darwin') { |
| 357 | rawRoots.push('/tmp'); |
| 358 | } |
| 359 | const candidates = []; |
| 360 | for (const rawRoot of rawRoots) { |
| 361 | if (!rawRoot) { |
| 362 | continue; |
| 363 | } |
| 364 | const resolved = path.resolve(rawRoot); |
| 365 | let real = resolved; |
| 366 | try { |
| 367 | real = await realpath(resolved); |
| 368 | } |
| 369 | catch { |
| 370 | continue; |
| 371 | } |
| 372 | candidates.push({ prefix: resolved, realRoot: real }); |
| 373 | if (real !== resolved) { |
| 374 | candidates.push({ prefix: real, realRoot: real }); |
| 375 | } |
| 376 | } |
| 377 | candidates.sort((a, b) => b.prefix.length - a.prefix.length); |
| 378 | for (const { prefix, realRoot } of candidates) { |
| 379 | const rel = path.relative(prefix, resolvedDir); |
| 380 | if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) { |
| 381 | return { root: realRoot, relativeDir: rel }; |
| 382 | } |
| 383 | } |
| 384 | const fsRoot = path.parse(resolvedDir).root; |
| 385 | return { root: fsRoot, relativeDir: path.relative(fsRoot, resolvedDir) }; |
| 386 | } |
| 387 | async function ensurePrivateDirectoryNoSymlinks(dir) { |
| 388 | const resolvedDir = path.resolve(dir); |
| 389 | const { root, relativeDir } = await resolveTrustedCacheRoot(resolvedDir); |
| 390 | const rootStat = await lstat(root); |
| 391 | if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) { |
| 392 | throw new Error('Refusing to write cache inside symlink or non-directory'); |
| 393 | } |
| 394 | const segments = relativeDir ? relativeDir.split(path.sep).filter(Boolean) : []; |
| 395 | let current = root; |
| 396 | for (const segment of segments) { |
| 397 | current = path.join(current, segment); |
| 398 | let st; |
| 399 | try { |
| 400 | st = await lstat(current); |
| 401 | } |
| 402 | catch (err) { |
| 403 | if (err?.code !== 'ENOENT') { |
| 404 | throw err; |
| 405 | } |
| 406 | try { |
| 407 | await mkdir(current, { mode: 0o700 }); |
| 408 | } |
| 409 | catch (mkdirErr) { |
| 410 | if (mkdirErr?.code !== 'EEXIST') { |
| 411 | throw mkdirErr; |
| 412 | } |
| 413 | } |
| 414 | st = await lstat(current); |
| 415 | } |
| 416 | if (st.isSymbolicLink() || !st.isDirectory()) { |
| 417 | throw new Error('Refusing to write cache inside symlink or non-directory'); |
| 418 | } |
| 419 | } |
| 420 | return current; |
| 421 | } |
| 422 | export async function writeFileAtomicPrivate(targetPath, content) { |
| 423 | const resolvedTarget = path.resolve(targetPath); |
| 424 | const baseName = path.basename(resolvedTarget); |
| 425 | if (!baseName || baseName === '.' || baseName === '..') { |
| 426 | throw new Error('Invalid cache file path'); |
| 427 | } |
| 428 | const safeDir = await ensurePrivateDirectoryNoSymlinks(path.dirname(resolvedTarget)); |
| 429 | const safeTargetPath = path.join(safeDir, baseName); |
| 430 | try { |
| 431 | const targetStat = await lstat(safeTargetPath); |
| 432 | if (targetStat.isSymbolicLink() || !targetStat.isFile()) { |
| 433 | throw new Error('Refusing to overwrite symlink or non-regular cache file'); |
| 434 | } |
| 435 | } |
| 436 | catch (err) { |
| 437 | if (err?.code !== 'ENOENT') { |
| 438 | throw err; |
| 439 | } |
| 440 | } |
| 441 | const tempName = `.${baseName}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`; |
| 442 | const tempPath = path.join(safeDir, tempName); |
| 443 | try { |
| 444 | await writeFile(tempPath, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 }); |
| 445 | if (process.platform !== 'win32') { |
| 446 | await chmod(tempPath, 0o600).catch(() => {}); |
| 447 | } |
| 448 | await rename(tempPath, safeTargetPath); |
| 449 | } |
| 450 | catch (err) { |
| 451 | await unlink(tempPath).catch(() => {}); |
| 452 | throw err; |
| 453 | } |
| 454 | } |
| 455 | async function writeSnapshotToDisk(cachePath, snapshot) { |
| 456 | await writeFileAtomicPrivate(cachePath, `${JSON.stringify(snapshot, null, 2)}\n`); |
| 457 | } |
| 458 | function extractOperations(bundleContents, bundleLabel, targets, discovered) { |
| 459 | for (const pattern of OPERATION_PATTERNS) { |
| 460 | pattern.regex.lastIndex = 0; |
| 461 | while (true) { |
| 462 | const match = pattern.regex.exec(bundleContents); |
| 463 | if (match === null) { |
| 464 | break; |
| 465 | } |
| 466 | const operationName = match[pattern.operationGroup]; |
| 467 | const queryId = match[pattern.queryIdGroup]; |
| 468 | if (!operationName || !queryId) { |
| 469 | continue; |
| 470 | } |
| 471 | if (!targets.has(operationName)) { |
| 472 | continue; |
| 473 | } |
| 474 | if (!QUERY_ID_REGEX.test(queryId)) { |
| 475 | continue; |
| 476 | } |
| 477 | if (discovered.has(operationName)) { |
| 478 | continue; |
| 479 | } |
| 480 | discovered.set(operationName, { queryId, bundle: bundleLabel }); |
| 481 | if (discovered.size === targets.size) { |
| 482 | return; |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | async function fetchAndExtract(fetchImpl, bundleUrls, targets, opts = {}, discovered = new Map()) { |
| 488 | const deadlineMs = opts.deadlineMs; |
| 489 | const outerSignal = opts.signal; |
| 490 | const CONCURRENCY = 6; |
| 491 | for (let i = 0; i < bundleUrls.length; i += CONCURRENCY) { |
| 492 | if (discovered.size === targets.size) { |
| 493 | break; |
| 494 | } |
| 495 | if (deadlineMs !== undefined && Date.now() >= deadlineMs) { |
| 496 | break; |
| 497 | } |
| 498 | if (outerSignal?.aborted) { |
| 499 | break; |
| 500 | } |
| 501 | const chunk = bundleUrls.slice(i, i + CONCURRENCY); |
| 502 | const batchController = new AbortController(); |
| 503 | const onOuterAbort = () => batchController.abort(outerSignal.reason); |
| 504 | if (outerSignal) { |
| 505 | if (outerSignal.aborted) { |
| 506 | batchController.abort(outerSignal.reason); |
| 507 | } |
| 508 | else { |
| 509 | outerSignal.addEventListener('abort', onOuterAbort, { once: true }); |
| 510 | } |
| 511 | } |
| 512 | const batchOpts = { ...opts, signal: batchController.signal }; |
| 513 | try { |
| 514 | await Promise.all(chunk.map(async (url) => { |
| 515 | if (discovered.size === targets.size || batchController.signal.aborted) { |
| 516 | return; |
| 517 | } |
| 518 | if (deadlineMs !== undefined && Date.now() >= deadlineMs) { |
| 519 | return; |
| 520 | } |
| 521 | const label = url.split('/').at(-1) ?? url; |
| 522 | try { |
| 523 | const js = await fetchText(fetchImpl, url, batchOpts); |
| 524 | extractOperations(js, label, targets, discovered); |
| 525 | if (discovered.size === targets.size) { |
| 526 | batchController.abort(createAbortError('All target query IDs discovered')); |
| 527 | } |
| 528 | } |
| 529 | catch { |
| 530 | // ignore failed or batch-aborted sibling bundles |
| 531 | } |
| 532 | })); |
| 533 | } |
| 534 | finally { |
| 535 | if (outerSignal) { |
| 536 | outerSignal.removeEventListener('abort', onOuterAbort); |
| 537 | } |
| 538 | } |
| 539 | if (discovered.size === targets.size) { |
| 540 | break; |
| 541 | } |
| 542 | } |
| 543 | return discovered; |
| 544 | } |
| 545 | async function discoverAndExtract(fetchImpl, targets, opts = {}) { |
| 546 | const maxBundles = opts.maxBundles ?? DEFAULT_MAX_BUNDLES; |
| 547 | const deadlineMs = opts.deadlineMs; |
| 548 | const seenBundles = new Set(); |
| 549 | const scannedPages = []; |
| 550 | const discovered = new Map(); |
| 551 | for (const page of DISCOVERY_PAGES) { |
| 552 | if (discovered.size === targets.size) { |
| 553 | break; |
| 554 | } |
| 555 | if (seenBundles.size >= maxBundles) { |
| 556 | break; |
| 557 | } |
| 558 | if (deadlineMs !== undefined && Date.now() >= deadlineMs) { |
| 559 | break; |
| 560 | } |
| 561 | scannedPages.push(page); |
| 562 | const newBundles = []; |
| 563 | try { |
| 564 | const html = await fetchText(fetchImpl, page, opts); |
| 565 | for (const match of html.matchAll(BUNDLE_URL_REGEX)) { |
| 566 | const bundleUrl = match[0]; |
| 567 | if (seenBundles.has(bundleUrl)) { |
| 568 | continue; |
| 569 | } |
| 570 | seenBundles.add(bundleUrl); |
| 571 | newBundles.push(bundleUrl); |
| 572 | if (seenBundles.size >= maxBundles) { |
| 573 | break; |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | catch { |
| 578 | // ignore discovery page failures; other pages often work |
| 579 | continue; |
| 580 | } |
| 581 | if (newBundles.length > 0) { |
| 582 | await fetchAndExtract(fetchImpl, newBundles, targets, opts, discovered); |
| 583 | } |
| 584 | } |
| 585 | const bundleUrls = [...seenBundles]; |
| 586 | if (bundleUrls.length === 0) { |
| 587 | throw new Error('No client bundles discovered; x.com layout may have changed.'); |
| 588 | } |
| 589 | return { bundleUrls, discovered, scannedPages }; |
| 590 | } |
| 591 | export function createRuntimeQueryIdStore(options = {}) { |
| 592 | const fetchImpl = options.fetchImpl ?? fetch; |
| 593 | const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; |
| 594 | const defaultFetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS; |
| 595 | const defaultRefreshTimeoutMs = options.refreshTimeoutMs ?? DEFAULT_REFRESH_TIMEOUT_MS; |
| 596 | const defaultMaxBytes = options.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES; |
| 597 | const defaultMaxBundles = options.maxBundles ?? DEFAULT_MAX_BUNDLES; |
| 598 | const defaultMaxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS; |
| 599 | const cachePath = options.cachePath ? path.resolve(options.cachePath) : resolveDefaultCachePath(); |
| 600 | let memorySnapshot = null; |
| 601 | let loadOnce = null; |
| 602 | let refreshInFlight = null; |
| 603 | const loadSnapshot = async () => { |
| 604 | if (memorySnapshot) { |
| 605 | return memorySnapshot; |
| 606 | } |
| 607 | if (!loadOnce) { |
| 608 | loadOnce = (async () => { |
| 609 | const fromDisk = await readSnapshotFromDisk(cachePath); |
| 610 | memorySnapshot = fromDisk; |
| 611 | return fromDisk; |
| 612 | })(); |
| 613 | } |
| 614 | return loadOnce; |
| 615 | }; |
| 616 | const getSnapshotInfo = async () => { |
| 617 | const snapshot = await loadSnapshot(); |
| 618 | if (!snapshot) { |
| 619 | return null; |
| 620 | } |
| 621 | const fetchedAtMs = new Date(snapshot.fetchedAt).getTime(); |
| 622 | const ageMs = Number.isFinite(fetchedAtMs) ? Math.max(0, Date.now() - fetchedAtMs) : Number.POSITIVE_INFINITY; |
| 623 | const effectiveTtl = Number.isFinite(snapshot.ttlMs) ? snapshot.ttlMs : ttlMs; |
| 624 | const isFresh = ageMs <= effectiveTtl; |
| 625 | return { snapshot, cachePath, ageMs, isFresh }; |
| 626 | }; |
| 627 | const getQueryId = async (operationName) => { |
| 628 | if (typeof operationName !== 'string' || FORBIDDEN_KEYS.has(operationName)) { |
| 629 | return null; |
| 630 | } |
| 631 | const info = await getSnapshotInfo(); |
| 632 | if (!info) { |
| 633 | return null; |
| 634 | } |
| 635 | const value = info.snapshot.ids[operationName]; |
| 636 | return typeof value === 'string' && QUERY_ID_REGEX.test(value) ? value : null; |
| 637 | }; |
| 638 | const refresh = async (operationNames, opts = {}) => { |
| 639 | if (refreshInFlight) { |
| 640 | return refreshInFlight; |
| 641 | } |
| 642 | refreshInFlight = (async () => { |
| 643 | const current = await getSnapshotInfo(); |
| 644 | if (!opts.force && current?.isFresh) { |
| 645 | return current; |
| 646 | } |
| 647 | const refreshTimeoutMs = opts.refreshTimeoutMs ?? defaultRefreshTimeoutMs; |
| 648 | const fetchOpts = { |
| 649 | fetchTimeoutMs: opts.fetchTimeoutMs ?? defaultFetchTimeoutMs, |
| 650 | maxBytes: opts.maxBytes ?? defaultMaxBytes, |
| 651 | maxBundles: opts.maxBundles ?? defaultMaxBundles, |
| 652 | maxRedirects: opts.maxRedirects ?? defaultMaxRedirects, |
| 653 | deadlineMs: Date.now() + refreshTimeoutMs, |
| 654 | signal: opts.signal, |
| 655 | }; |
| 656 | const targets = new Set(operationNames); |
| 657 | const { bundleUrls, discovered, scannedPages } = await discoverAndExtract( |
| 658 | fetchImpl, |
| 659 | targets, |
| 660 | fetchOpts, |
| 661 | ); |
| 662 | if (discovered.size === 0) { |
| 663 | return current ?? null; |
| 664 | } |
| 665 | const ids = Object.create(null); |
| 666 | for (const name of operationNames) { |
| 667 | if (FORBIDDEN_KEYS.has(name)) { |
| 668 | continue; |
| 669 | } |
| 670 | const entry = discovered.get(name); |
| 671 | if (entry?.queryId && QUERY_ID_REGEX.test(entry.queryId)) { |
| 672 | ids[name] = entry.queryId; |
| 673 | } |
| 674 | } |
| 675 | const snapshot = { |
| 676 | fetchedAt: new Date().toISOString(), |
| 677 | ttlMs, |
| 678 | ids, |
| 679 | discovery: { |
| 680 | pages: scannedPages, |
| 681 | bundles: bundleUrls.map((url) => url.split('/').at(-1) ?? url), |
| 682 | }, |
| 683 | }; |
| 684 | memorySnapshot = snapshot; |
| 685 | try { |
| 686 | await writeSnapshotToDisk(cachePath, snapshot); |
| 687 | } |
| 688 | catch { |
| 689 | // Keep the refreshed snapshot in memory on read-only filesystems |
| 690 | // or unwritable cache paths. |
| 691 | } |
| 692 | return getSnapshotInfo(); |
| 693 | })().finally(() => { |
| 694 | refreshInFlight = null; |
| 695 | }); |
| 696 | return refreshInFlight; |
| 697 | }; |
| 698 | return { |
| 699 | cachePath, |
| 700 | ttlMs, |
| 701 | getSnapshotInfo, |
| 702 | getQueryId, |
| 703 | refresh, |
| 704 | clearMemory() { |
| 705 | memorySnapshot = null; |
| 706 | loadOnce = null; |
| 707 | }, |
| 708 | }; |
| 709 | } |
| 710 | export const runtimeQueryIds = createRuntimeQueryIdStore(); |
| 711 | //# sourceMappingURL=runtime-query-ids.js.map |