-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread-unroll.js
More file actions
3101 lines (2880 loc) · 164 KB
/
Copy paththread-unroll.js
File metadata and controls
3101 lines (2880 loc) · 164 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* x-utils v0.1.0 · Thread unroll
* Reconstructs a thread from any post in it and exports it as clean Markdown, plain text and JSON.
*
* HOW TO RUN
* 1. Log in to x.com and open: https://x.com/<handle>/status/<id> (any post of the thread)
* 2. Open DevTools (F12, or Cmd+Option+I on macOS) and select the Console tab.
* 3. Paste this entire file and press Enter. Keep the tab in the foreground.
*
* Runs entirely inside your browser session. Nothing is sent anywhere.
* Edit the CONFIG block below to tune the run.
*
* Generated from src/tools/thread-unroll.js by `npm run build`. Do not edit dist/ by hand.
* https://x-utils.com
*/
(async () => {
"use strict";
// ==== CONFIG ====
const CONFIG = {
outputs: ["html", "md", "txt", "json"], // formats to download: "html" (report), "md", "txt", "json"
copyToClipboard: true, // copy the Markdown to the clipboard as well
scrollDelayMs: 900, // pause between scroll steps
stagnantRounds: 6, // stop after this many scroll steps without new posts
maxTweets: 300, // safety cap for very long conversations
stopAfterStrangers: 30, // stop once this many posts by other people follow the author's last post
};
// ==== x-utils runtime (inlined) ====
// ---------------------------------------------------------------------------
// x-utils runtime: logging, timing, page guards, file output.
// Every function here is plain and browser-only at call time (never at load
// time) so the same source can be unit-tested in Node.
// ---------------------------------------------------------------------------
const XU_VERSION = "0.1.0";
const XU_STYLE = {
info: "color:#1d9bf0;font-weight:600",
ok: "color:#00ba7c;font-weight:600",
warn: "color:#e0a800;font-weight:600",
error: "color:#f4212e;font-weight:600",
step: "color:#8b98a5",
};
const log = {
info: (...args) => console.log("%c• x-utils", XU_STYLE.info, ...args),
ok: (...args) => console.log("%c✓ x-utils", XU_STYLE.ok, ...args),
warn: (...args) => {
console.warn("%c! x-utils", XU_STYLE.warn, ...args);
xuOverlay.status(args.map(String).join(" "), "warn");
},
error: (...args) => {
console.error("%c✗ x-utils", XU_STYLE.error, ...args);
xuOverlay.fail(args.map(String).join(" "));
},
step: (...args) => {
console.log("%c→ x-utils", XU_STYLE.step, ...args);
xuOverlay.status(args.map(String).join(" "));
},
phase: (name) => {
xuDebug.phase = name;
xuDebug.phaseAt = new Date().toISOString();
},
banner: (name) => {
console.log(`%c x-utils ${XU_VERSION} · ${name} `, "background:#1d9bf0;color:#fff;font-weight:700;padding:2px 6px;border-radius:3px");
// Publish diagnostics from the start so a stuck run can still be inspected.
try {
window.xu = window.xu || {};
window.xu.debug = xuDebug;
xuDebug.phase = "starting";
} catch {
/* ignore */
}
xuOverlay.start(name);
},
};
// ---- in-page progress panel ----------------------------------------------
// A small card in the corner of x.com so nobody has to read the console.
// Styles are applied through the CSSOM (allowed by X's CSP). Every method is
// wrapped so a failure here can never break a tool.
// A blob: document opened from x.com inherits X's Content-Security-Policy,
// which blocks the report's script (inline and blob: alike). The in-page
// preview is therefore read-only and says so; the downloaded file is the
// interactive one.
const xuOverlay = {
root: null,
parts: null,
reportUrl: null,
reportName: null,
start(name) {
try {
if (!document.body) return;
if (this.root) this.root.remove();
for (const stale of document.querySelectorAll("[data-xu-overlay]")) stale.remove(); // panels left by earlier runs
const root = document.createElement("div");
root.setAttribute("data-xu-overlay", "");
root.style.cssText = "position:fixed;right:20px;bottom:20px;z-index:2147483647;width:340px;max-width:calc(100vw - 40px);background:#0d1220;color:#f4f6fb;border:1px solid rgba(255,255,255,.12);border-radius:14px;box-shadow:0 20px 50px -20px rgba(0,0,0,.7);font:13.5px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;padding:14px 16px 12px;box-sizing:border-box";
const head = document.createElement("div");
head.style.cssText = "display:flex;align-items:center;gap:10px;margin-bottom:8px";
const dot = document.createElement("span");
dot.style.cssText = "width:10px;height:10px;border-radius:3px;background:linear-gradient(135deg,#b3a6ff,#5ee0a8);flex:0 0 auto";
const title = document.createElement("span");
title.textContent = `x-utils · ${name}`;
title.style.cssText = "font:600 11.5px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#c7cede;flex:1";
const close = document.createElement("button");
close.type = "button";
close.textContent = "×";
close.setAttribute("aria-label", "Close");
close.style.cssText = "background:none;border:0;color:#8f9ab3;font-size:20px;line-height:1;cursor:pointer;padding:0 2px";
close.addEventListener("click", () => this.close());
head.append(dot, title, close);
const status = document.createElement("div");
status.textContent = "Starting…";
status.style.cssText = "color:#c7cede;min-height:20px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis";
const bar = document.createElement("div");
bar.style.cssText = "height:4px;border-radius:2px;background:rgba(255,255,255,.1);margin:10px 0 6px;overflow:hidden;position:relative";
const fill = document.createElement("div");
fill.style.cssText = "position:absolute;left:0;top:0;height:100%;width:35%;border-radius:2px;background:linear-gradient(90deg,#b3a6ff,#5ee0a8);animation:xu-slide 1.4s ease-in-out infinite alternate";
bar.appendChild(fill);
const foot = document.createElement("div");
foot.style.cssText = "display:flex;justify-content:space-between;align-items:center;gap:10px;font-size:12px;color:#8f9ab3";
const count = document.createElement("span");
count.textContent = "Keep this tab in the foreground";
const actions = document.createElement("span");
actions.style.cssText = "display:flex;gap:8px";
foot.append(count, actions);
root.append(head, status, bar, foot);
document.body.appendChild(root);
this.root = root;
this.parts = { status, bar, fill, count, actions };
this.reportUrl = null;
this.reportName = null;
// Indeterminate animation via CSSOM so no inline <style> is needed.
if (!document.getElementById("xu-overlay-anim")) {
const sheet = document.createElement("style");
sheet.id = "xu-overlay-anim";
document.head.appendChild(sheet);
try {
sheet.sheet.insertRule("@keyframes xu-slide{from{left:0}to{left:65%}}", 0);
} catch {
/* CSP may block; the bar simply stays static */
}
}
} catch {
/* never break the tool for a cosmetic panel */
}
},
status(text, tone) {
try {
if (!this.parts) return;
this.parts.status.textContent = text;
this.parts.status.style.color = tone === "warn" ? "#e2b35c" : "#c7cede";
} catch {
/* ignore */
}
},
count(text) {
try {
if (this.parts) this.parts.count.textContent = text;
} catch {
/* ignore */
}
},
setReport(url, filename) {
this.reportUrl = url;
this.reportName = filename;
},
openReport() {
try {
window.open(this.reportUrl, "_blank");
} catch {
/* ignore */
}
this.count(`For sorting, filtering and export, open ${this.reportName || "the .html file"} from Downloads`);
},
done(summary) {
try {
if (!this.parts) return;
this.parts.status.textContent = summary;
this.parts.status.style.color = "#5ee0a8";
this.parts.status.style.whiteSpace = "normal";
this.parts.fill.style.animation = "none";
this.parts.fill.style.width = "100%";
this.parts.count.textContent = this.reportName ? `Saved to Downloads as ${this.reportName}` : "Files are in your Downloads folder";
this.parts.actions.textContent = "";
if (this.reportUrl) {
const open = document.createElement("button");
open.type = "button";
open.textContent = "Preview (read-only)";
open.style.cssText = "background:#b3a6ff;color:#0d1220;border:0;border-radius:8px;padding:6px 11px;font:600 12.5px inherit;cursor:pointer";
open.addEventListener("click", () => this.openReport());
this.parts.actions.appendChild(open);
}
} catch {
/* ignore */
}
},
fail(text) {
try {
if (!this.parts) return;
this.parts.status.textContent = text;
this.parts.status.style.color = "#ff9a6c";
this.parts.status.style.whiteSpace = "normal";
this.parts.fill.style.animation = "none";
this.parts.fill.style.background = "#ff9a6c";
this.parts.fill.style.width = "100%";
this.parts.count.textContent = "See the console for details";
} catch {
/* ignore */
}
},
close() {
try {
if (this.root) this.root.remove();
this.root = null;
this.parts = null;
} catch {
/* ignore */
}
},
};
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function num(value) {
if (value === null || value === undefined || value === "") return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
// X uses the classic "Wed Oct 10 20:19:24 +0000 2018" format in `created_at`.
// Returns an ISO-8601 string or null.
function parseTwitterDate(value) {
if (!value) return null;
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d.toISOString();
}
function daysSince(isoDate, now = Date.now()) {
if (!isoDate) return null;
const t = new Date(isoDate).getTime();
if (Number.isNaN(t)) return null;
return Math.floor((now - t) / 86400000);
}
function todayStamp(date = new Date()) {
return date.toISOString().slice(0, 10);
}
function slug(text) {
return String(text || "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
// ---- page guards ----------------------------------------------------------
function currentPath() {
return location.pathname.replace(/\/+$/, "") || "/";
}
function requireXHost() {
if (!/(^|\.)(x|twitter)\.com$/.test(location.hostname)) {
log.error(`This tool only runs on x.com (you are on ${location.hostname}).`);
throw new Error("x-utils: wrong host");
}
}
// `patterns` is an array of strings (exact path) or RegExps tested against the path.
function requirePage(patterns, hint) {
const path = currentPath();
const ok = patterns.some((p) => (p instanceof RegExp ? p.test(path) : p === path));
if (!ok) {
log.error(`This tool must run on ${hint}. Current page: ${location.href}`);
throw new Error("x-utils: wrong page");
}
}
const XU_RESERVED_PATHS = new Set([
"i", "home", "explore", "notifications", "messages", "settings", "search",
"compose", "login", "logout", "signup", "tos", "privacy", "about", "jobs",
]);
// Handle of the logged-in account, read from the left navigation bar.
function myHandle() {
const link = document.querySelector('a[data-testid="AppTabBar_Profile_Link"]');
const href = link && link.getAttribute("href");
return href ? href.replace(/^\//, "").split(/[/?#]/)[0] || null : null;
}
// Handle in the first path segment (e.g. /jack/following -> "jack").
function pathHandle(path = currentPath()) {
const segment = path.split("/")[1];
if (!segment || XU_RESERVED_PATHS.has(segment.toLowerCase())) return null;
return segment;
}
// ---- output ---------------------------------------------------------------
const XU_MIME = { html: "text/html", csv: "text/csv", json: "application/json", md: "text/markdown", txt: "text/plain" };
function saveFile(filename, content, mime = "text/plain") {
const blob = new Blob([content], { type: `${mime};charset=utf-8` });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.style.display = "none";
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 1500);
log.ok(`Downloaded ${filename}`);
}
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}
// Writes every requested format. `files` maps format -> content string.
// Returns the list of filenames written.
async function writeOutputs(baseName, files, formats, { clipboard = false } = {}) {
const written = [];
for (const format of formats) {
const content = files[format];
if (content === undefined) {
log.warn(`No "${format}" output available for this tool; skipping.`);
continue;
}
const filename = `${baseName}.${format}`;
saveFile(filename, content, XU_MIME[format] || "text/plain");
written.push(filename);
if (format === "html") {
try {
xuOverlay.setReport(URL.createObjectURL(new Blob([previewVariant(content, filename)], { type: "text/html;charset=utf-8" })), filename);
} catch {
/* ignore */
}
}
}
if (clipboard) {
const first = formats.find((f) => files[f] !== undefined);
if (first) {
const done = await copyToClipboard(files[first]);
if (done) log.ok(`${first.toUpperCase()} copied to the clipboard.`);
else log.warn("Clipboard blocked by the browser (click the page and run again if you need it).");
}
}
return written;
}
// The preview cannot run scripts under X's CSP, so it carries a banner that
// points to the downloaded file for sorting, filtering and export.
function previewVariant(html, filename) {
const note = `<div style="position:sticky;top:0;z-index:20;background:#a86b0f;color:#fff;font:600 13.5px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;padding:10px 16px;text-align:center">Read-only preview. To sort, filter, export or share, open <span style="font-family:ui-monospace,Menlo,Consolas,monospace;font-weight:500">${filename}</span> from your Downloads folder.</div>`;
return html.replace(/<body([^>]*)>/, (m) => `${m}${note}`);
}
// Keeps the last result reachable from the console for ad-hoc inspection.
// Raw samples kept for diagnosing X format changes. Never written to files;
// only reachable as window.xu.debug after a run.
const xuDebug = { sampleUser: null, sampleCell: null, sampleTweet: null, sampleArticle: null, apiResponses: 0, responses: {}, statuses: {}, quota: {}, bounce: null, completed: null, replay: null, direct: null, scroll: null, rateLimited: null, rateLimit: null, phase: null, phaseAt: null };
function publishResult(toolName, result, summary = "Done") {
window.xu = window.xu || {};
window.xu[toolName] = result;
window.xu.last = result;
window.xu.debug = xuDebug;
log.info(`Result object available as window.xu.last (also window.xu["${toolName}"]).`);
xuOverlay.done(summary);
return result;
}
function outputBaseName(toolName, ...parts) {
return ["x-utils", toolName, ...parts.filter(Boolean).map(slug), todayStamp()].join("_");
}
// ---- DOM interaction helpers --------------------------------------------
// Clicks any visible button whose text matches `re`. Returns how many were clicked.
function clickButtons(re, { root = document, max = 5, once = false } = {}) {
let clicked = 0;
for (const el of root.querySelectorAll('[role="button"], button')) {
if (clicked >= max) break;
if (once && el.dataset.xuClicked) continue;
const text = (el.textContent || "").trim();
if (text && re.test(text)) {
if (once) el.dataset.xuClicked = "1";
el.click();
clicked++;
}
}
return clicked;
}
const XU_RETRY_RE = /^(retry|try again|reintentar|intentar de nuevo|volver a intentar|réessayer|erneut versuchen|riprova|tentar novamente|tentar de novo|opnieuw proberen|försök igen)$/i;
const XU_ERROR_TEXT_RE = /something went wrong|algo salió mal|algo ha salido mal|quelque chose s.est mal passé|etwas ist schiefgelaufen|qualcosa è andato storto|algo deu errado|er is iets misgegaan|något gick fel/i;
// Waits between retries when X rate-limits a list. Limits reset in windows of
// several minutes, so the waits grow instead of hammering the button.
const XU_BACKOFF_MS = [8000, 20000, 45000, 90000, 150000, 240000];
function retryButton() {
for (const el of document.querySelectorAll('[role="button"], button')) {
if (XU_RETRY_RE.test((el.textContent || "").trim())) return el;
}
return null;
}
// X shows "Something went wrong. Try reloading." with a Retry button when it
// rate-limits a timeline.
function rateLimitVisible() {
if (xuDebug.rateLimit && Date.now() - xuDebug.rateLimit.at < 15000) return true;
if (retryButton()) return true;
const area = document.querySelector('[role="dialog"]') || document.querySelector("main") || document.body;
return !!area && XU_ERROR_TEXT_RE.test((area.innerText || "").slice(0, 20000));
}
// How long to wait before retrying: the exact reset X announced when known
// (capped at 15 minutes), otherwise the next step of the backoff ladder.
function rateLimitWait(attempt, { blindMs = null } = {}) {
const reset = xuDebug.rateLimit && xuDebug.rateLimit.resetAt;
if (reset && reset > Date.now()) return Math.min(reset - Date.now() + 2500, 15 * 60 * 1000);
if (blindMs) return blindMs;
return XU_BACKOFF_MS[Math.min(attempt, XU_BACKOFF_MS.length - 1)];
}
function fmtDuration(seconds) {
return seconds >= 60 ? `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s` : `${seconds}s`;
}
function clickRetryIfPresent() {
const btn = retryButton();
if (btn) btn.click();
return !!btn;
}
async function countdown(ms, onTick) {
const end = Date.now() + ms;
while (Date.now() < end) {
onTick(Math.ceil((end - Date.now()) / 1000));
await sleep(Math.min(1000, end - Date.now()));
}
}
// Polls `predicate` until it returns true or the timeout passes.
async function waitFor(predicate, timeoutMs = 4000, stepMs = 100) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return true;
await sleep(stepMs);
}
return predicate();
}
// Forces X to re-request the first page of the current timeline by switching
// to a sibling tab and back (SPA navigation, the script keeps running). Waits
// for the URL to actually change both ways, so the tool never scrolls the
// wrong list. Returns true only when the original page is back on screen.
async function bounceTabs(delayMs = 1200) {
const startPath = currentPath();
// Settings menus are marked up as tabs too; bouncing through them reloads nothing.
if (/^\/settings(\/|$)/.test(startPath)) return false;
const section = startPath.split("/")[1];
const tabs = () => [...document.querySelectorAll('a[role="tab"], [role="tablist"] a')].filter((a) => a.getAttribute("href"));
const current = tabs().find((t) => t.getAttribute("aria-selected") === "true") || tabs().find((t) => t.getAttribute("href") === startPath);
// A real sibling tab lives in the same section of the URL (/user/followers ↔ /user/following, /i/history ↔ /i/history/likes).
const other = tabs().find((t) => t !== current && t.getAttribute("href") !== startPath && t.getAttribute("href").split("/")[1] === section);
xuDebug.bounce = { tabs: tabs().map((t) => t.getAttribute("href")), from: current ? current.getAttribute("href") : null, to: other ? other.getAttribute("href") : null, restored: null };
if (!current || !other) return false;
other.click();
const left = await waitFor(() => currentPath() !== startPath, 3000);
if (!left) {
xuDebug.bounce.restored = true;
return false;
}
await sleep(delayMs);
const back = tabs().find((t) => t.getAttribute("href") === startPath);
if (back) back.click();
else history.back();
let restored = await waitFor(() => currentPath() === startPath, 4000);
if (!restored) {
history.back();
restored = await waitFor(() => currentPath() === startPath, 4000);
}
xuDebug.bounce.restored = restored;
if (!restored) {
log.warn(`Could not return to ${startPath} after switching tabs; open it again and re-run the tool.`);
throw new Error("x-utils: lost the original page");
}
await sleep(delayMs);
return true;
}
// Pages without sibling tabs (a post's conversation view) are refreshed by
// leaving through an in-page profile link and coming back with history.back():
// X re-requests the conversation on the way back, which the interceptor sees.
async function bounceAway(delayMs = 1200) {
const startPath = currentPath();
const hadDialog = !!document.querySelector('[role="dialog"]');
// Prefer a profile link inside the open dialog, then anything in the main column.
const scopes = ['[role="dialog"] a[href^="/"]', 'main a[href^="/"]', 'a[href^="/"]'];
let link = null;
for (const scope of scopes) {
link = [...document.querySelectorAll(scope)].find((a) => {
const href = a.getAttribute("href");
return /^\/[A-Za-z0-9_]{1,15}$/.test(href) && href !== startPath && !XU_RESERVED_PATHS.has(href.slice(1).toLowerCase());
});
if (link) break;
}
xuDebug.bounce = { away: link ? link.getAttribute("href") : null, from: startPath, hadDialog, left: null, restored: null, dialogBack: null };
if (!link) return false;
link.click();
const left = await waitFor(() => currentPath() !== startPath, 3000);
xuDebug.bounce.left = left;
if (!left) return false;
await sleep(delayMs);
history.back();
const restored = await waitFor(() => currentPath() === startPath, 5000);
xuDebug.bounce.restored = restored;
if (restored && hadDialog) {
// Wait for the dialog and its cells to render again before anyone harvests.
xuDebug.bounce.dialogBack = await waitFor(() => !!document.querySelector('[role="dialog"] [data-testid="UserCell"], [role="dialog"] article'), 6000);
}
if (!restored) {
log.warn(`Could not return to ${startPath} after leaving the page; open it again and re-run the tool.`);
throw new Error("x-utils: lost the original page");
}
await sleep(delayMs);
return true;
}
// Some X pages (list members, a post's likers) open as a modal dialog over the
// page. The list then lives in the dialog's own scroll container, not in the
// window. Returns that element, or null when the page itself scrolls.
function scrollContainer() {
const dialog = document.querySelector('[role="dialog"]');
if (!dialog) return null;
let best = null;
for (const el of dialog.querySelectorAll("div")) {
if (el.scrollHeight <= el.clientHeight + 40) continue;
const overflow = getComputedStyle(el).overflowY;
if (overflow !== "auto" && overflow !== "scroll") continue;
if (!best || el.scrollHeight > best.scrollHeight) best = el;
}
return best;
}
// Where to look for list cells and posts: inside the open dialog if there is
// one (so sidebar "who to follow" cells are ignored), otherwise the whole page.
function contentRoot() {
return document.querySelector('[role="dialog"]') || document;
}
// Scrolls the window until `harvest()` stops returning a growing count.
// `harvest` must be idempotent: it is called on every tick and its return
// value is the current number of collected items.
async function autoScroll({
harvest,
stagnantLimit = 8,
delayMs = 800,
maxItems = Infinity,
label = "items",
beforeScroll = null,
shouldStop = null,
resumeOnQuota = true,
}) {
let box = scrollContainer();
if (box) log.step("The list is inside a dialog; scrolling the dialog.");
const scrollTop = () => (box ? box.scrollTo(0, 0) : window.scrollTo(0, 0));
const scrollStep = () => {
if (box && !box.isConnected) box = scrollContainer();
if (box) box.scrollBy(0, Math.max(200, box.clientHeight * 0.85));
else window.scrollBy(0, Math.max(200, window.innerHeight * 0.85));
};
scrollTop();
await sleep(300);
let stagnant = 0;
let last = -1;
let retries = 0;
let delay = delayMs;
let ticks = 0;
let nudges = 0;
let quotaWaits = 0;
let stopReason = null;
const finish = (reason, count) => {
xuDebug.scroll = { ticks, stopReason: reason, collected: count, quotaWaits, retries, nudges };
};
for (;;) {
ticks++;
const count = harvest();
if (count >= maxItems) {
log.info(`Reached the configured limit of ${maxItems} ${label}.`);
finish("maxItems", count);
break;
}
const loading = !!contentRoot().querySelector('[role="progressbar"]');
if (count === last) {
// X is still fetching the next page: do not count it as the end of the list (bounded below).
if (loading && stagnant < stagnantLimit * 2) stagnant += 0.5;
else stagnant++;
// Half-way through the patience budget, scroll back up a little and down
// again: X's "load more" sentinel sometimes needs to re-enter the viewport.
if (stagnant === Math.ceil(stagnantLimit / 2)) {
nudges++;
if (box) box.scrollBy(0, -Math.max(300, box.clientHeight * 0.5));
else window.scrollBy(0, -Math.max(300, window.innerHeight * 0.5));
await sleep(400);
}
} else {
stagnant = 0;
last = count;
log.step(`${label}: ${count}`);
xuOverlay.count(`${count.toLocaleString("en-US")} ${label} so far`);
}
if (rateLimitVisible()) {
if (retries >= XU_BACKOFF_MS.length) {
log.warn(`X kept rate-limiting this list after ${retries} retries. Stopping with the ${count} ${label} collected so far; run again in 15 minutes to get the rest.`);
xuDebug.rateLimited = { retries, collected: count, gaveUp: true };
finish("rateLimit", count);
break;
}
const wait = rateLimitWait(retries);
retries++;
const known = xuDebug.rateLimit && xuDebug.rateLimit.resetAt ? " (X announced when the limit resets)" : "";
log.warn(`X paused the list (rate limit). Waiting ${fmtDuration(Math.round(wait / 1000))} before retrying${known}, attempt ${retries} of ${XU_BACKOFF_MS.length}…`);
await countdown(wait, (left) => xuOverlay.count(`Rate limited by X · ${count.toLocaleString("en-US")} ${label} so far · retrying in ${fmtDuration(left)}`));
xuDebug.rateLimit = null;
clickRetryIfPresent();
await sleep(3000);
delay = Math.max(Math.round(delay * 1.5), 1500); // be gentler from here on
stagnant = 0;
xuDebug.rateLimited = { retries, collected: count, gaveUp: false };
continue;
}
if (stagnant >= stagnantLimit) {
// X's client goes quiet, with no error on screen, once the quota for this
// list is used up. Its own answers told us the reset time: wait for it.
const quota = resumeOnQuota && quotaWaits < 2 ? exhaustedQuota() : null;
if (quota && quota.resetAt - Date.now() <= 16 * 60 * 1000) {
quotaWaits++;
const wait = quota.resetAt - Date.now() + 2500;
log.warn(`X stopped loading this list: its quota for ${quota.op} is used up (X says so in its own responses). It resets in ${fmtDuration(Math.round(wait / 1000))}; waiting, then continuing with the ${count.toLocaleString("en-US")} ${label} collected so far.`);
await countdown(wait, (left) => xuOverlay.count(`X quota used up · ${count.toLocaleString("en-US")} ${label} so far · resuming in ${fmtDuration(left)}`));
delete xuDebug.quota[quota.op];
clickRetryIfPresent();
await sleep(3000);
delay = Math.max(Math.round(delay * 1.5), 1500);
stagnant = 0;
scrollStep();
await sleep(delay);
continue;
}
finish("stagnant", count);
break;
}
if (shouldStop && shouldStop(count)) {
log.step("Nothing more of interest below; stopping early.");
finish("shouldStop", count);
break;
}
if (beforeScroll) beforeScroll();
scrollStep();
await sleep(delay);
}
return harvest();
}
// ---------------------------------------------------------------------------
// Network interception. X's web client already downloads every user and tweet
// you scroll past as GraphQL JSON. We observe those responses (fetch and XHR)
// instead of issuing our own requests, so there are no extra calls, no tokens
// to manage and no additional rate-limit exposure.
// ---------------------------------------------------------------------------
const XU_API_URL_RE = /\/i\/api\//;
// The most recent GraphQL request the page made, per operation name, with the
// headers X attached. Used to re-request the first page of a list (X serves
// that page from its own cache after the tool starts, so it is never observed).
const xuRequests = new Map();
// The last "next page" cursor each operation delivered, so a list can be
// continued directly from where X's own client stopped.
const xuCursors = new Map();
// Operations that page through a list; their quota is what runs out mid-scroll.
const XU_LIST_OP_RE = /Tweets|Followers|Following|Bookmarks|Likes|Search|Timeline|Members|Blocked|Muted|TweetDetail/i;
function operationName(url) {
const match = String(url).match(/\/graphql\/[^/]+\/([A-Za-z0-9_]+)/);
return match ? match[1] : null;
}
function headersToObject(headers) {
const out = {};
if (!headers) return out;
if (typeof headers.forEach === "function" && !Array.isArray(headers)) {
headers.forEach((value, key) => {
out[key] = value;
});
return out;
}
for (const [key, value] of Array.isArray(headers) ? headers : Object.entries(headers)) out[key] = value;
return out;
}
function rememberRequest(url, method, headers, body) {
const match = String(url).match(/\/graphql\/[^/]+\/([A-Za-z0-9_]+)/);
if (!match) return;
xuRequests.set(match[1], { url: String(url), method: (method || "GET").toUpperCase(), headers: headersToObject(headers), body: typeof body === "string" ? body : null, at: Date.now() });
}
// Installs response observers. `onJson(json, url)` is called for every parsed
// JSON response whose URL matches `match`. Returns an uninstall function.
function installInterceptor(onJson, { match = XU_API_URL_RE } = {}) {
const deliver = (url, text) => {
if (!match.test(url)) return;
let json;
try {
json = JSON.parse(text);
} catch {
return;
}
const op = operationName(url);
if (op) {
const cursor = findBottomCursor(json);
if (cursor) xuCursors.set(op, cursor);
}
try {
onJson(json, url);
} catch (err) {
log.warn("Interceptor handler failed:", err);
}
};
const originalFetch = window.fetch;
window.fetch = function xuFetch(input, init) {
const promise = originalFetch.apply(this, arguments);
let url = "";
try {
url = typeof input === "string" ? input : input instanceof URL ? input.href : (input && input.url) || "";
if (url && match.test(url) && !(init && init.__xuReplay)) {
const isRequest = input && typeof input === "object" && "headers" in input && !(input instanceof URL);
rememberRequest(url, (init && init.method) || (isRequest ? input.method : "GET"), (init && init.headers) || (isRequest ? input.headers : null), init && init.body);
}
} catch {
url = "";
}
if (url && match.test(url)) {
promise
.then((res) => {
noteResponse(url, res.status, (name) => res.headers.get(name));
return res.clone().text().then((text) => deliver(url, text));
})
.catch(() => {});
}
return promise;
};
const originalOpen = XMLHttpRequest.prototype.open;
const originalSend = XMLHttpRequest.prototype.send;
const originalSetHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.open = function xuOpen(method, url) {
this.__xuUrl = String(url);
this.__xuMethod = method;
this.__xuHeaders = {};
return originalOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.setRequestHeader = function xuSetHeader(name, value) {
if (this.__xuHeaders) this.__xuHeaders[name] = value;
return originalSetHeader.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function xuSend(body) {
if (this.__xuUrl && match.test(this.__xuUrl)) {
rememberRequest(this.__xuUrl, this.__xuMethod, this.__xuHeaders, body);
this.addEventListener("load", () => {
try {
noteResponse(this.__xuUrl, this.status, (name) => this.getResponseHeader(name));
if (this.responseType === "" || this.responseType === "text") deliver(this.__xuUrl, this.responseText);
else if (this.responseType === "json" && this.response) onJson(this.response, this.__xuUrl);
} catch {
/* ignore unreadable bodies */
}
});
}
return originalSend.apply(this, arguments);
};
return function uninstall() {
window.fetch = originalFetch;
XMLHttpRequest.prototype.open = originalOpen;
XMLHttpRequest.prototype.send = originalSend;
XMLHttpRequest.prototype.setRequestHeader = originalSetHeader;
};
}
// Records what every API answer says about its quota (x-rate-limit-remaining,
// x-rate-limit-reset in epoch seconds) per operation, plus 429s explicitly.
// X's own client stops asking for pages, silently, once remaining hits 0, so
// knowing the quota from its regular answers is what lets a tool wait for the
// reset instead of mistaking the silence for the end of the list.
function noteResponse(url, status, getHeader) {
const op = operationName(url);
xuDebug.statuses[status] = (xuDebug.statuses[status] || 0) + 1;
if (op) {
xuDebug.responses[op] = (xuDebug.responses[op] || 0) + 1;
if (status !== 200) xuDebug.responses[`${op}:${status}`] = (xuDebug.responses[`${op}:${status}`] || 0) + 1;
}
let remaining = null;
let limit = null;
let resetAt = null;
try {
const rem = getHeader("x-rate-limit-remaining");
if (rem !== null && rem !== undefined && rem !== "") remaining = Number(rem);
const lim = getHeader("x-rate-limit-limit");
if (lim) limit = Number(lim);
const reset = Number(getHeader("x-rate-limit-reset"));
if (reset > 0) resetAt = reset * 1000;
} catch {
/* header not exposed */
}
if (op && (remaining !== null || status === 429)) xuDebug.quota[op] = { remaining: status === 429 ? 0 : remaining, limit, resetAt, at: Date.now() };
if (status !== 429) return;
xuDebug.rateLimit = { at: Date.now(), resetAt, limit, op, count: ((xuDebug.rateLimit && xuDebug.rateLimit.count) || 0) + 1 };
}
// The list operation whose quota X reports as used up (with a reset still in
// the future), or null. Most recent first when several qualify.
function exhaustedQuota(re = XU_LIST_OP_RE) {
let best = null;
for (const [op, q] of Object.entries(xuDebug.quota)) {
if (!re.test(op) || q.remaining !== 0 || !q.resetAt || q.resetAt <= Date.now()) continue;
if (!best || q.at > best.at) best = { op, ...q };
}
return best;
}
// Finds the "next page" cursor anywhere in a timeline response.
function findBottomCursor(json) {
let cursor = null;
walkJson(json, (node) => {
if (!cursor && node && typeof node === "object" && !Array.isArray(node) && node.cursorType === "Bottom" && typeof node.value === "string") cursor = node.value;
});
return cursor;
}
// Re-issues a list request the page already made, without its cursor (first
// page), then follows cursors while `needMore()` says the list is still
// incomplete. Goes through the wrapped fetch, so responses reach the collector
// like any other. Returns the number of pages fetched.
// With `fromCursor`, it continues from the last cursor X delivered for that
// operation instead of starting over.
// `progress()` returns how much has been collected; two pages in a row without
// progress mean X is repeating itself, so the loop stops instead of burning quota.
async function replayListPages(operationNames, needMore, { maxPages = 6, delayMs = 700, fromCursor = false, progress = null, label = "items" } = {}) {
const name = operationNames.find((n) => xuRequests.has(n));
xuDebug.replay = { candidates: operationNames, observed: [...xuRequests.keys()], used: name || null, fromCursor: !!(fromCursor && name && xuCursors.has(name)), pages: [] };
if (!name) return 0;
const req = xuRequests.get(name);
let cursor = fromCursor && xuCursors.has(name) ? xuCursors.get(name) : undefined;
let waited = false;
let lastProgress = progress ? progress() : null;
let flatPages = 0;
let pages = 0;
while (pages < maxPages && needMore()) {
let response;
try {
const url = new URL(req.url, location.origin);
if (req.method === "GET") {
const variables = JSON.parse(url.searchParams.get("variables") || "{}");
if (cursor === undefined) delete variables.cursor;
else variables.cursor = cursor;
url.searchParams.set("variables", JSON.stringify(variables));
response = await fetch(url.toString(), { method: "GET", headers: req.headers, credentials: "include", __xuReplay: true });
} else {
const body = JSON.parse(req.body || "{}");
body.variables = body.variables || {};
if (cursor === undefined) delete body.variables.cursor;
else body.variables.cursor = cursor;
response = await fetch(url.toString(), { method: "POST", headers: req.headers, credentials: "include", body: JSON.stringify(body), __xuReplay: true });
}
} catch (err) {
xuDebug.replay.pages.push({ error: String(err && err.message) });
log.step(`Re-requesting page ${pages + 1} failed: ${err && err.message}`);
break;
}
pages++;
xuDebug.replay.pages.push({ status: response.status });
if (response.status === 429 && !waited) {
// Same quota as the page itself: honour the reset X announced, once, then retry this cursor.
waited = true;
const wait = rateLimitWait(0, { blindMs: 60000 });
log.warn(`X rate-limited the direct requests after ${pages} page${pages === 1 ? "" : "s"}. Waiting ${fmtDuration(Math.round(wait / 1000))} for the reset, then continuing.`);
await countdown(wait, (left) => xuOverlay.count(`Rate limited by X · resuming in ${fmtDuration(left)}`));
xuDebug.rateLimit = null;
pages--;
continue;
}
if (!response.ok) {
log.step(`X answered ${response.status} when re-requesting page ${pages}; stopping.`);
break;
}
let json;
try {
json = await response.clone().json();
} catch {
break;
}
const nextCursor = findBottomCursor(json);
// Give the interceptor's own clone().text() chain time to deliver the page.
await sleep(delayMs);
if (progress) {
const now = progress();
flatPages = now > lastProgress ? 0 : flatPages + 1;
lastProgress = now;
// Keep the panel and console alive between pages: this can take minutes.
const quota = xuDebug.quota[name];
const left = quota && typeof quota.remaining === "number" ? ` · ${quota.remaining} request${quota.remaining === 1 ? "" : "s"} left before X's limit` : "";
xuOverlay.count(`Working… page ${pages} requested · ${now.toLocaleString("en-US")} ${label} so far${left}`);
if (pages % 5 === 0) log.step(`Still working: ${pages} pages requested, ${now} ${label} so far${left}.`);
if (flatPages >= 2) {
xuDebug.replay.stoppedBy = "no progress";
log.step(`X's last two pages added nothing new; the timeline has no more to give.`);
break;
}
}
if (!nextCursor || nextCursor === cursor) {
xuDebug.replay.stoppedBy = nextCursor ? "repeated cursor" : "no cursor";
break;
}
cursor = nextCursor;
}
await sleep(300);
return pages;
}
// Looks up accounts one by one with the profile query the page itself uses
// (UserByScreenName), which is observed whenever a profile is visited. Used for
// short lists X serves entirely from cache. Stops on the first refusal.
async function lookupUsersByHandle(handles, { delayMs = 250, max = 1000, onProgress = null } = {}) {
const req = xuRequests.get("UserByScreenName");
if (!req || req.method !== "GET") return { attempted: 0, ok: 0, stoppedBy: req ? "method" : "not observed" };
let ok = 0;
let attempted = 0;
let stoppedBy = null;
const total = Math.min(handles.length, max);
for (const handle of handles.slice(0, max)) {
attempted++;
if (onProgress && attempted % 5 === 0) onProgress(attempted, total);
try {
const url = new URL(req.url, location.origin);
const variables = JSON.parse(url.searchParams.get("variables") || "{}");
variables.screen_name = handle;
url.searchParams.set("variables", JSON.stringify(variables));
const response = await fetch(url.toString(), { method: "GET", headers: req.headers, credentials: "include", __xuReplay: true });
if (response.ok) ok++;
else {
stoppedBy = `HTTP ${response.status}`;
break;
}
} catch (err) {
stoppedBy = String(err && err.message);
break;
}
await sleep(delayMs);
}
await sleep(400);
return { attempted, ok, stoppedBy };
}
// Re-issues the profile timeline request the page made for one account
// (UserTweets or its current name) with another account's id, and returns that
// account's normalized top-level tweets. Used to learn when someone last posted
// without opening their profile. Returns { tweets, status }.
const XU_TIMELINE_OP_RE = /^(UserTweets|UserOriginalsTimeline|UserTweetsAndReplies|UserMedia)$/;
function observedTimelineOp() {
return [...xuRequests.keys()].find((n) => XU_TIMELINE_OP_RE.test(n) && xuRequests.get(n).method === "GET") || null;
}
async function replayUserTimeline(userId) {
const op = observedTimelineOp();
if (!op) return { tweets: null, status: "no timeline request observed" };
const req = xuRequests.get(op);
try {
const url = new URL(req.url, location.origin);
const variables = JSON.parse(url.searchParams.get("variables") || "{}");