-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsourcecapsule.user.js
More file actions
12050 lines (11531 loc) · 488 KB
/
Copy pathsourcecapsule.user.js
File metadata and controls
12050 lines (11531 loc) · 488 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
// ==UserScript==
// @name SourceCapsule - Save X/Twitter Threads & Articles as Markdown for LLMs + Offline HTML
// @namespace https://github.com/wolfgang-aura/SourceCapsule
// @version 1.6.0
// @description One click saves an X (Twitter) thread, Article, or post as clean Markdown for LLM context (Claude, ChatGPT) plus a self-contained offline HTML archive - images, video, and quoted posts embedded, with honest completeness reporting. Local-first, with optional expiring AI readable links.
// @author wolfgang-aura
// @license MIT
// @match https://x.com/*
// @match https://twitter.com/*
// @match https://mobile.x.com/*
// @match https://mobile.twitter.com/*
// @icon https://abs.twimg.com/favicons/twitter.3.ico
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @connect pbs.twimg.com
// @connect video.twimg.com
// @connect abs.twimg.com
// @connect cdn.syndication.twimg.com
// @connect x.com
// @connect twitter.com
// @connect 127.0.0.1
// @connect localhost
// @connect sourcecapsule-share.wolfgang-aura.workers.dev
// @run-at document-start
// @noframes
// @downloadURL https://raw.githubusercontent.com/wolfgang-aura/SourceCapsule/main/sourcecapsule.user.js
// @updateURL https://raw.githubusercontent.com/wolfgang-aura/SourceCapsule/main/sourcecapsule.user.js
// ==/UserScript==
/*
* SourceCapsule
* -------------
* Saves an X (Twitter) Article or single post as ONE self-contained .html file
* that opens fully offline: every image and short video is base64-inlined, and
* quoted tweets are rebuilt as real, styled, selectable HTML (not screenshots).
*
* ARCHITECTURE (read this before editing)
* =======================================
* The code is split into two layers with a deliberate seam between them:
*
* 1. FRAGILE LAYER - anything that reads X's DOM. X reshuffles its markup
* often, so ALL of its selectors live in the CONFIG block below, and the
* extraction functions produce a plain-object "model". When X breaks the
* tool, the fix is almost always here, and almost always just a selector.
*
* 2. STABLE LAYER - the durable engine: privileged fetch -> base64 ->
* assemble HTML -> download. It only ever touches the model, never X's DOM,
* so it rarely needs to change.
*
* The model is the contract between the two. See buildModel* (producers) and
* assembleHtml (consumer).
*
* WHY A USERSCRIPT? CORS. Reading the raw bytes of pbs.twimg.com /
* video.twimg.com media to base64-encode them is blocked from a normal page
* context. GM_xmlhttpRequest (with the @connect grants above) is the privileged
* fetch that makes inlining possible. That single constraint is why this is a
* userscript and not a plain content script.
*/
(function () {
'use strict';
// ===========================================================================
// CONFIG - *** EDIT HERE WHEN X CHANGES ***
// ---------------------------------------------------------------------------
// If the tool stops finding part of the page, a selector below is almost
// certainly stale. Update it here; the rest of the code should not need to
// change. Each selector lists fallbacks (tried in order).
// ===========================================================================
const CONFIG = {
selectors: {
// The main content column of a status / article page.
primaryColumn: ['div[data-testid="primaryColumn"]', 'main[role="main"]'],
// A single tweet block (the primary post and any quoted/embedded tweets).
tweet: ['article[data-testid="tweet"]', 'article[role="article"]'],
// The rich text of a tweet. `div[lang]` is a fallback: X wraps tweet text
// in a div carrying a `lang` attribute even if the testid changes.
tweetText: ['div[data-testid="tweetText"]', 'div[lang]'],
// Author name/handle block within a tweet.
userName: ['div[data-testid="User-Name"]'],
// Avatar image within a tweet.
avatar: ['div[data-testid="Tweet-User-Avatar"] img', 'img[src*="profile_images"]'],
// Photos within a tweet.
tweetPhoto: [
'div[data-testid="tweetPhoto"] img',
'a[href*="/photo/"] img',
'img[src*="pbs.twimg.com/media/"]',
],
// Video container within a tweet.
videoPlayer: ['div[data-testid="videoPlayer"]', 'div[data-testid="videoComponent"]'],
// External link-preview card within a tweet (the payload of a link post).
card: ['div[data-testid="card.wrapper"]', 'a[data-testid="card.wrapper"]'],
// Clickable quoted-post wrapper. X has periodically added/removed the
// tabindex attribute without changing the card semantics.
quoteCard: ['div[role="link"][tabindex="0"]', 'div[role="link"]'],
// "Show more" link X renders on long-form (note) posts in timeline views;
// its presence means the visible text is only a preview.
showMore: ['[data-testid="tweet-text-show-more-link"]'],
// X's inline dead-end box for a quoted post that is itself gone on X
// (deleted, banned/suspended, or restricted account): "This Post is
// unavailable." etc. Nothing is capturable, but the archive must say so.
quoteTombstone: ['[data-testid="tombstone"]'],
// Poll containers and observed fields. Results may be hidden until the poll closes;
// extraction records only text/ARIA values X actually rendered.
poll: [
'div[data-testid="cardPoll"]',
'div[role="radiogroup"]',
'[data-testid*="poll" i]',
'[aria-label*="poll" i]',
],
pollChoice: [
'[role="radio"]',
'[role="progressbar"]',
'[data-testid*="pollOption" i]',
'[data-testid*="choice" i][aria-label]',
'[aria-label*="%"]',
],
pollQuestion: ['[data-testid="pollQuestion"]', '[role="heading"]'],
pollMeta: ['[data-testid="pollMetadata"]', '[aria-label*="vote" i]'],
// Time element (carries the canonical permalink).
timeLink: ['a[href*="/status/"] time'],
// Section headings X inserts between a conversation and recommendation feeds
// such as "Discover more". These are thread boundaries, never continuations.
threadBoundaryHeading: ['[role="heading"]', 'h1', 'h2', 'h3'],
// Long-form Article rich-text root.
articleRoot: [
'div[data-testid="twitterArticleReadView"]',
'div[data-testid="twitterArticleRichTextView"]',
'div[data-testid="twitterArticleReader"]',
],
articleTextRoot: ['div[data-testid="longformRichTextComponent"]'],
// Long-form Article title.
articleTitle: [
'div[data-testid="twitter-article-title"]',
'div[data-testid="twitterArticleTitle"]',
'h1[role="heading"]',
'h1',
],
},
video: {
inlineEnabled: true,
inlineCapBytes: Infinity, // Fetch any discovered MP4; fallback only after preservation fails.
minPlayableBytes: 32 * 1024,
// TweetDetail bodies for media-heavy threads can exceed 2 MB. Keep a
// bounded but roomier window so quote refs near the end survive; any
// remaining truncation is surfaced in diagnostics instead of hidden.
networkCaptureMaxChars: 6_000_000,
},
image: {
preferOriginal: true, // request the full-resolution pbs.twimg.com variant
},
fetchTimeoutMs: 30000,
buttonId: 'sourcecapsule-btn',
// Per-post Export buttons attached to each post on status/article pages, so the
// user picks exactly which post to export instead of relying on one page-level
// button (avoids accidentally exporting the wrong tweet). Set false to disable.
perPostButtons: true,
postControlClass: 'sourcecapsule-post-ctl',
postControlFlag: 'data-sourcecapsule-ctl',
toastId: 'sourcecapsule-toast',
styleId: 'sourcecapsule-style',
debug: true,
debugEmbed: true,
// Scroll the page top-to-bottom before extracting so X's lazy/virtualized
// media loads into the DOM. The #1 suspected cause of missing tweet images.
forceLoad: true,
forceLoadMaxMs: 45000,
forceLoadSettleMs: 2500,
mediaFetchRetries: 4,
mediaFetchRetryBaseMs: 650,
// Parallel media downloads during the main inline pass. Small on purpose:
// enough to cut big-thread export time ~3x, low enough to stay under X's
// rate limits. The rescue/repair passes stay sequential - they are retrying
// failures, and gentler pacing is what lets those succeed.
mediaFetchConcurrency: 3,
// Backoff multiplier applied when a fetch is rate-limited (HTTP 429): those
// need substantially more room than transient socket errors to clear.
rateLimitBackoffFactor: 4,
// Retries for cdn.syndication.twimg.com fetches. Every quote-recovery layer
// rides on this endpoint, so a single transient failure must not silently
// degrade a quote card to its (possibly empty) DOM scrape.
syndicationFetchRetries: 3,
syndicationFetchRetryBaseMs: 700,
// Pause before the strict-gate auto-repair round retries remaining blockers,
// giving transient conditions (rate limits, dropped connections) time to clear.
repairPauseMs: 1500,
videoNudgeTimeoutMs: 700,
// Fetch each embedded/quoted tweet by id from X's public syndication endpoint
// to get its authoritative text + media, instead of scraping the fragile,
// virtualized article DOM. This is what makes quote media reliably correct.
useSyndication: true,
share: {
// Hosted share service (Cloudflare Worker + R2). Point this at a local
// `npm run dev:share` (http://127.0.0.1:8787) through the userscript-manager
// menu when developing; new hosts also need an @connect grant above.
defaultApiBase: 'https://sourcecapsule-share.wolfgang-aura.workers.dev',
maxBytes: 25 * 1024 * 1024,
expiryDays: [1, 7, 30],
defaultExpiryDays: 7,
},
installUrl: 'https://github.com/wolfgang-aura/SourceCapsule#installation',
};
const APP = 'SourceCapsule';
const VERSION = '1.6.0';
// ===========================================================================
// Small utilities
// ===========================================================================
const log = (...a) => CONFIG.debug && console.log(`[${APP}]`, ...a);
const warn = (...a) => console.warn(`[${APP}]`, ...a);
const errlog = (...a) => console.error(`[${APP}]`, ...a);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Run `worker(item)` over `items` with at most `limit` in flight. Each item is
* awaited exactly once; worker must handle its own errors (a throw aborts the run). */
async function runWithConcurrency(items, limit, worker) {
const queue = (items || []).slice();
const width = Math.max(1, Math.min(Number(limit) || 1, queue.length));
const runners = [];
for (let i = 0; i < width; i++) {
runners.push(
(async () => {
while (queue.length) {
await worker(queue.shift());
}
})()
);
}
await Promise.all(runners);
}
const withTimeout = (promise, ms) =>
Promise.race([
Promise.resolve(promise).catch((error) => ({ error })),
sleep(ms).then(() => ({ timedOut: true })),
]);
/** Return the first element matching any selector in the list, or null. */
function pick(root, selectorList, { quiet = false } = {}) {
const list = Array.isArray(selectorList) ? selectorList : [selectorList];
for (const sel of list) {
const el = (root || document).querySelector(sel);
if (el) return el;
}
if (!quiet) warn('selector miss (none matched):', list.join(' || '));
return null;
}
/** Return all elements matching the FIRST selector in the list that hits. */
function pickAll(root, selectorList) {
const list = Array.isArray(selectorList) ? selectorList : [selectorList];
for (const sel of list) {
const els = (root || document).querySelectorAll(sel);
if (els.length) return Array.from(els);
}
return [];
}
/** Return matches for all selectors, including root, without stopping early. */
function pickAllMatchesIncludingRoot(root, selectorList) {
const list = Array.isArray(selectorList) ? selectorList : [selectorList];
const seen = new Set();
const els = [];
const add = (el) => {
if (el && !seen.has(el)) {
seen.add(el);
els.push(el);
}
};
for (const sel of list) {
if (root && root.matches && root.matches(sel)) add(root);
(root || document).querySelectorAll(sel).forEach(add);
}
return els;
}
function escapeHtml(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeJsonScript(s) {
return escapeJsonForHtml(s);
}
function slugify(s) {
const base = String(s || '')
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.slice(0, 80)
.replace(/^-+|-+$/g, '');
return base || 'x-export';
}
function nowStamp() {
return new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
}
function humanBytes(n) {
if (!n && n !== 0) return '?';
const u = ['B', 'KB', 'MB', 'GB'];
let i = 0;
while (n >= 1024 && i < u.length - 1) {
n /= 1024;
i++;
}
return `${n.toFixed(i ? 1 : 0)} ${u[i]}`;
}
function formatDuration(seconds) {
const n = Number(seconds);
if (!Number.isFinite(n) || n <= 0) return '';
const total = Math.round(n);
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
if (h) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function escapeAttr(s) {
return escapeHtml(s);
}
// Only http(s)/mailto URLs may become an href in the EXPORTED file, which opens in a
// file:// context. This neutralizes javascript:/data:/vbscript: schemes that would
// otherwise survive escaping and execute when a reader clicks a link in the archive.
// Returns '' for anything not on the scheme allowlist; callers must drop the link then.
function safeUrl(u) {
const s = String(u == null ? '' : u).trim();
if (!s) return '';
return /^(?:https?:|mailto:)/i.test(s) ? s : '';
}
// https://x.com/<handle> from a stored "@handle" or "handle". Empty when the handle
// isn't a valid X username. Used as a last-resort link when a quoted post's exact
// permalink couldn't be recovered - a working profile link is always preferable to
// a dead-end "source unavailable" notice.
function authorProfileUrl(handle) {
const raw = String(handle || '')
.trim()
.replace(/^@/, '');
return /^[A-Za-z0-9_]{1,15}$/.test(raw) ? `https://x.com/${raw}` : '';
}
// X's syndication API returns tweet text with &, <, > already HTML-encoded (the classic
// Twitter behaviour). Decode those back to plain text before our own escaping, so we don't
// double-encode and render a literal "&" in the archive. Decode & last so an
// encoded "<" doesn't get turned into a real "<".
function decodeBasicEntities(s) {
return String(s == null ? '' : s)
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
function countBlocks(blocks, predicate) {
let count = 0;
const walk = (items) => {
(items || []).forEach((b) => {
if (predicate(b)) count += 1;
if (b.kind === 'quote' || b.kind === 'blockquote') walk(b.blocks);
});
};
walk(blocks);
return count;
}
function normalizeExternalLinks(html) {
return String(html || '').replace(
/<a\b([^>]*\bhref="(https?:\/\/[^"]+)"[^>]*)>/gi,
(tag, attrs) => {
let next = attrs;
if (/\btarget\s*=/.test(next)) {
next = next.replace(/\btarget\s*=\s*"[^"]*"/i, 'target="_blank"');
} else {
next += ' target="_blank"';
}
if (/\brel\s*=/.test(next)) {
next = next.replace(/\brel\s*=\s*"([^"]*)"/i, (relTag, relValue) => {
const rels = new Set(
String(relValue || '')
.split(/\s+/)
.filter(Boolean)
);
rels.add('noopener');
rels.add('noreferrer');
return `rel="${Array.from(rels).join(' ')}"`;
});
} else {
next += ' rel="noopener noreferrer"';
}
return `<a${next}>`;
}
);
}
function videoDimensionsFromUrl(url) {
const match = String(url || '').match(/\/(\d{2,5})x(\d{2,5})(?:\/|[._-])/);
if (!match) return {};
const width = Number(match[1]);
const height = Number(match[2]);
return Number.isFinite(width) && Number.isFinite(height) ? { width, height } : {};
}
function applyVideoDimensions(block, dimensions) {
const width = Number(dimensions && dimensions.width);
const height = Number(dimensions && dimensions.height);
if (Number.isFinite(width) && width > 0) block.width = Math.round(width);
if (Number.isFinite(height) && height > 0) block.height = Math.round(height);
}
function escapeJsonForHtml(s) {
return String(s)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026')
.replace(/[\s\S]/g, (c) => {
const code = c.charCodeAt(0);
if (code <= 0x7f) return c;
return `\\u${code.toString(16).padStart(4, '0')}`;
});
}
function safeIsoTime(value) {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? '' : d.toISOString();
}
function readableUtcTime(value) {
const iso = safeIsoTime(value);
if (!iso) return 'Unknown time';
return iso.replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC');
}
function decodeHtmlCodePoint(match, code, radix = 10) {
const n = parseInt(code, radix);
try {
return Number.isFinite(n) ? String.fromCodePoint(n) : match;
} catch {
return match;
}
}
function textFromHtml(html) {
return String(html || '')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, ' ')
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/&#(\d+);/g, (match, code) => decodeHtmlCodePoint(match, code))
.replace(/&#x([0-9a-f]+);/gi, (match, code) => decodeHtmlCodePoint(match, code, 16))
.replace(/\s+/g, ' ')
.trim();
}
function blockTextForLanguage(block) {
if (!block) return '';
if (block.kind === 'heading') return block.text || '';
if (block.kind === 'paragraph') return textFromHtml(block.html);
if (block.kind === 'code') return block.text || '';
if (block.kind === 'list') return (block.items || []).map(textFromHtml).join(' ');
if (block.kind === 'quote' || block.kind === 'blockquote')
return (block.blocks || []).map(blockTextForLanguage).join(' ');
return '';
}
function inferDocumentLang(model) {
const text = [model.title, model.heading, ...(model.blocks || []).map(blockTextForLanguage)]
.join(' ')
.slice(0, 12000);
const cjk = (text.match(/[\u3400-\u9fff]/g) || []).length;
const latin = (text.match(/[A-Za-z]/g) || []).length;
if (cjk >= 12 && cjk >= latin * 0.25) return 'zh-CN';
return 'en';
}
function statusIdFromSourceUrl(url) {
const id = statusIdFromUrl(url);
if (id) return id;
const article = String(url || '').match(/\/article\/(\d+)/);
return article ? article[1] : '';
}
// Reserved first-path segments on x.com/twitter.com that are NOT user handles.
const NON_HANDLE_SEGMENTS = new Set([
'i',
'home',
'search',
'explore',
'notifications',
'messages',
'settings',
'compose',
'hashtag',
'intent',
'share',
'login',
'signup',
'about',
'tos',
'privacy',
]);
/**
* Best-effort author handle from a post/article URL (e.g. https://x.com/dingyi/status/123 ->
* "@dingyi"). Used only as a fallback when the DOM author metadata is missing. Returns '' for
* reserved paths (/i/, /home, ...) or anything that does not look like a handle.
*/
function handleFromSourceUrl(url) {
const m = String(url || '').match(
/^https?:\/\/(?:[\w-]+\.)*(?:x|twitter)\.com\/([A-Za-z0-9_]{1,15})(?:[/?#]|$)/i
);
if (!m) return '';
if (NON_HANDLE_SEGMENTS.has(m[1].toLowerCase())) return '';
return `@${m[1]}`;
}
function publishedAtFromElement(root, expectedStatusId = '') {
const times = Array.from(
(root || document).querySelectorAll
? (root || document).querySelectorAll('time[datetime]')
: []
);
if (!times.length) return '';
const normalizedExpected = String(expectedStatusId || '');
const matching = normalizedExpected
? times.find((time) => {
const anchor = time.closest && time.closest('a[href*="/status/"]');
return anchor && statusIdFromUrl(anchor.href) === normalizedExpected;
})
: null;
const time = matching || times[0];
return safeIsoTime(time.getAttribute('datetime') || '');
}
function normalizeVideoUrl(url) {
if (!url) return '';
let value = String(url).trim();
if (!value || value.startsWith('blob:') || value.startsWith('data:')) return '';
value = value
.replace(/\\u0026/g, '&')
.replace(/\\\//g, '/')
.replace(/&/g, '&');
try {
return new URL(value, typeof location !== 'undefined' ? location.href : undefined).toString();
} catch {
return /^https?:\/\//.test(value) ? value : '';
}
}
function videoUrlKind(url) {
const lower = String(url || '').toLowerCase();
if (lower.includes('.mp4')) return 'mp4';
if (lower.includes('.m3u8')) return 'hls';
return '';
}
function isInterestingVideoUrl(url) {
const lower = String(url || '').toLowerCase();
return (
lower.includes('video.twimg.com') ||
lower.includes('.mp4') ||
lower.includes('.m3u8') ||
lower.includes('amplify_video') ||
lower.includes('ext_tw_video') ||
lower.includes('tweet_video')
);
}
function videoCandidate(url, source = 'unknown', extra = {}) {
const normalized = normalizeVideoUrl(url);
if (!normalized || !isInterestingVideoUrl(normalized)) return null;
return {
url: normalized,
kind: videoUrlKind(normalized),
source,
bitrate: Number(extra.bitrate) > 0 ? Number(extra.bitrate) : undefined,
...videoDimensionsFromUrl(normalized),
...extra,
};
}
function addVideoCandidate(out, seen, candidate) {
if (!candidate || !candidate.url || seen.has(candidate.url)) return;
seen.add(candidate.url);
out.push(candidate);
}
function videoCandidatesFromText(text, source = 'text') {
const out = [];
const seen = new Set();
const raw = String(text || '');
const patterns = [
/https?:\\\/\\\/video\.twimg\.com\\\/[^"'<>\\\s]+/g,
/https?:\/\/video\.twimg\.com\/[^"' <>\s]+/g,
];
patterns.forEach((pattern) => {
raw.replace(pattern, (url) => {
addVideoCandidate(out, seen, videoCandidate(url, source));
return url;
});
});
return out;
}
function xVideoMediaKey(url) {
const value = String(url || '');
const match = value.match(
/(?:amplify_video_thumb|amplify_video|ext_tw_video_thumb|ext_tw_video|tweet_video_thumb|tweet_video)\/(\d+)/i
);
return match ? match[1] : '';
}
function structuredPosterUrl(value) {
if (!value) return '';
if (typeof value === 'string') return value;
if (typeof value !== 'object') return '';
return (
value.original_img_url ||
value.url ||
value.media_url_https ||
value.media_url ||
value.preview_image_url ||
value.thumbnail_url ||
''
);
}
function sortVideoCandidates(candidates) {
return (candidates || []).slice().sort((a, b) => {
if (a.kind !== b.kind) return a.kind === 'mp4' ? -1 : 1;
const bitrateDelta = (Number(b.bitrate) || 0) - (Number(a.bitrate) || 0);
if (bitrateDelta) return bitrateDelta;
const pixelsB = (Number(b.width) || 0) * (Number(b.height) || 0);
const pixelsA = (Number(a.width) || 0) * (Number(a.height) || 0);
return pixelsB - pixelsA;
});
}
function videoCandidatesFromStructuredData(value, source = 'json') {
const out = [];
const seen = new Set();
const add = (url, candidateSource, extra) =>
addVideoCandidate(out, seen, videoCandidate(url, candidateSource, extra));
const walk = (item, itemSource) => {
if (!item) return;
if (typeof item === 'string') {
videoCandidatesFromText(item, itemSource).forEach((candidate) =>
addVideoCandidate(out, seen, candidate)
);
return;
}
if (Array.isArray(item)) {
item.forEach((child) => walk(child, itemSource));
return;
}
if (typeof item !== 'object') return;
const variants =
item.video_info && Array.isArray(item.video_info.variants)
? item.video_info.variants
: Array.isArray(item.variants)
? item.variants
: [];
const posterUrl =
structuredPosterUrl(item.media_url_https) ||
structuredPosterUrl(item.media_url) ||
structuredPosterUrl(item.preview_image_url) ||
structuredPosterUrl(item.preview_image) ||
structuredPosterUrl(item.thumbnail_url);
const mediaKey = item.media_key || item.id_str || item.id || xVideoMediaKey(posterUrl);
variants.forEach((variant) => {
if (!variant || !variant.url) return;
add(variant.url, `${itemSource}:variant`, {
bitrate: variant.bitrate,
contentType: variant.content_type || variant.contentType || '',
posterUrl,
mediaKey,
});
});
if (
item.url &&
(item.content_type === 'video/mp4' ||
item.contentType === 'video/mp4' ||
String(item.url).includes('.mp4') ||
String(item.url).includes('.m3u8'))
) {
add(item.url, itemSource, {
bitrate: item.bitrate,
contentType: item.content_type || item.contentType || '',
posterUrl,
mediaKey,
});
}
Object.keys(item).forEach((key) => walk(item[key], itemSource));
};
walk(value, source);
return sortVideoCandidates(out);
}
function videoCandidatesFromJsonText(text, source = 'json') {
const raw = String(text || '').trim();
if (!raw || (raw[0] !== '{' && raw[0] !== '[')) return [];
try {
return videoCandidatesFromStructuredData(JSON.parse(raw), source);
} catch {
return [];
}
}
// ===========================================================================
// STABLE LAYER - privileged fetch + base64 inlining
// ===========================================================================
/** Hosts the privileged byte fetch is allowed to hit. All inlineable X media lives on
* *.twimg.com; restricting here (in addition to the @connect grants) bounds SSRF so a
* crafted media URL in a post cannot make the script fetch an arbitrary origin. */
function isAllowedMediaHost(url) {
try {
const host = new URL(url, location.href).hostname.toLowerCase();
return host === 'twimg.com' || host.endsWith('.twimg.com');
} catch {
return false;
}
}
/** Fetch raw bytes through the userscript manager (bypasses page CORS). */
function gmFetchBytesOnce(url) {
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') {
reject(new Error('GM_xmlhttpRequest unavailable - is the userscript manager granting it?'));
return;
}
if (!isAllowedMediaHost(url)) {
reject(new Error(`Refusing to fetch non-twimg media host: ${url}`));
return;
}
GM_xmlhttpRequest({
method: 'GET',
url,
headers: {
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,video/*,*/*;q=0.8',
'Cache-Control': 'no-cache',
},
referrer: 'https://x.com/',
referrerPolicy: 'strict-origin-when-cross-origin',
responseType: 'arraybuffer',
timeout: CONFIG.fetchTimeoutMs,
onload: (res) => {
if (res.status >= 200 && res.status < 300 && res.response) {
const header = (res.responseHeaders || '').match(/content-type:\s*([^\r\n;]+)/i);
const mime = (header && header[1] ? header[1] : guessMime(url)).trim();
resolve({ bytes: new Uint8Array(res.response), mime });
} else {
const error = new Error(`HTTP ${res.status} for ${url}`);
error.status = res.status;
reject(error);
}
},
onerror: (event) =>
reject(
new Error(`${(event && (event.error || event.message)) || 'Network error'} for ${url}`)
),
ontimeout: () => reject(new Error(`Timeout (${CONFIG.fetchTimeoutMs}ms) for ${url}`)),
});
});
}
async function gmFetchBytes(url) {
const attempts = Math.max(1, Number(CONFIG.mediaFetchRetries) || 1);
let lastError = null;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const result = await gmFetchBytesOnce(url);
if (!result.bytes || !result.bytes.length) throw new Error(`Empty response for ${url}`);
return result;
} catch (error) {
lastError = error;
// 404 is authoritative for this exact URL - stop burning retries here so
// the caller can move on to its next size-variant candidate immediately.
if (error.status === 404) break;
if (attempt < attempts) {
const factor = error.status === 429 ? CONFIG.rateLimitBackoffFactor : 1;
await sleep(CONFIG.mediaFetchRetryBaseMs * attempt * factor);
}
}
}
throw lastError || new Error(`Fetch failed for ${url}`);
}
function guessMime(url) {
const u = url.split('?')[0].toLowerCase();
if (u.endsWith('.png')) return 'image/png';
if (u.endsWith('.gif')) return 'image/gif';
if (u.endsWith('.webp')) return 'image/webp';
if (u.endsWith('.mp4')) return 'video/mp4';
if (u.endsWith('.svg')) return 'image/svg+xml';
return 'image/jpeg';
}
/** ArrayBuffer/Uint8Array -> base64 (chunked to avoid call-stack limits). */
function bytesToBase64(bytes) {
let binary = '';
const chunk = 0x8000;
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
return btoa(binary);
}
/** base64 string -> Uint8Array (inverse of bytesToBase64; atob exists in Node 18+). */
function base64ToBytes(b64) {
const binary = atob(String(b64 || ''));
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
/** "data:<mime>[;base64],<payload>" -> { bytes, mime }. */
function dataUriToBytes(dataUri) {
const s = String(dataUri || '');
const comma = s.indexOf(',');
if (comma === -1 || !s.startsWith('data:')) return { bytes: new Uint8Array(0), mime: '' };
const header = s.slice(5, comma);
const mime = header.split(';')[0] || '';
const payload = s.slice(comma + 1);
const bytes = /;base64/i.test(header)
? base64ToBytes(payload)
: new TextEncoder().encode(decodeURIComponent(payload));
return { bytes, mime };
}
/** MIME -> a sensible file extension for sidecar media files. */
function mimeToExt(mime) {
switch (String(mime || '').toLowerCase()) {
case 'image/jpeg':
case 'image/jpg':
return 'jpg';
case 'image/png':
return 'png';
case 'image/gif':
return 'gif';
case 'image/webp':
return 'webp';
case 'image/svg+xml':
return 'svg';
case 'video/mp4':
return 'mp4';
default:
return 'bin';
}
}
/**
* PURE: decide the on-disk folder names for one export, given the user's layout pref.
* `date` is a pre-formatted "YYYY-MM-DD" string (caller supplies the local date). Returns the
* directory segments from the chosen root down to the per-post folder. The post-folder name is
* stable (handle + status id) so re-exporting the same post overwrites instead of duplicating.
*/
function bundlePaths(model, prefs, date) {
const layout = prefs && prefs.layout === 'flat' ? 'flat' : 'date';
const handle = String((model.author && model.author.handle) || '').replace(/^@/, '');
const statusId = statusIdFromSourceUrl(model.sourceUrl || '');
let postName;
if (handle && statusId) postName = `${slugify(handle)}-${statusId}`;
else if (statusId) postName = `post-${statusId}`;
else postName = slugify(model.title || model.heading || 'x-export');
const dateFolder = String(date || '');
if (layout === 'flat') {
const folder = dateFolder ? `${dateFolder}_${postName}` : postName;
return { layout, dateFolder, postName, postFolder: folder, segments: [folder] };
}
return {
layout,
dateFolder,
postName,
postFolder: postName,
segments: dateFolder ? [dateFolder, postName] : [postName],
};
}
/** Local "YYYY-MM-DD" for date-grouped folders (the user's day, not UTC). */
function localDateStamp(d = new Date()) {
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
function normalizeTags(value) {
const input = Array.isArray(value) ? value : String(value || '').split(',');
const seen = new Set();
return input
.map((tag) =>
String(tag || '')
.trim()
.replace(/^#+/, '')
.replace(/\s+/g, '-')
)
.filter((tag) => {
const key = tag.toLowerCase();
if (!tag || seen.has(key)) return false;
seen.add(key);
return true;
})
.slice(0, 20);
}
function applyCaptureMetadata(model, metadata = {}) {
model.userNote = String(metadata.note || '')
.trim()
.slice(0, 2000);
model.tags = normalizeTags(metadata.tags);
return model;
}
function libraryIndexEntry(model, paths, stats) {
const id = statusIdFromSourceUrl(model.sourceUrl) || slugify(model.title || 'capture');
const relativePath = [...paths.segments, `${paths.postName}.llm.md`].join('/');
return {
id,
title: markdownLineText(model.heading || model.title || 'X capture'),
author: markdownLineText(
[model.author && model.author.name, model.author && model.author.handle]
.filter(Boolean)
.join(' ')
),
type: model.thread ? `thread (${model.thread.capturedPosts} posts)` : model.type || 'post',
sourceUrl: model.sourceUrl || '',
savedAt: safeIsoTime(model.exportedAt),
path: relativePath,
note: markdownLineText(model.userNote || ''),
tags: normalizeTags(model.tags),
capture: `${stats.images} image(s), ${stats.videos} video(s), ${stats.incompleteMedia} incomplete, ${stats.missingMedia} missing`,
};
}
function renderLibraryIndexItem(entry) {
const lines = [
`<!-- sourcecapsule:item:${entry.id} -->`,
`## ${entry.title || 'X capture'}`,
'',
`- ID: ${entry.id}`,
`- Type: ${entry.type}`,
`- Author: ${entry.author || 'Unknown'}`,
`- Source: ${entry.sourceUrl}`,
`- Saved: ${entry.savedAt}`,
`- File: ${entry.path}`,
`- Capture: ${entry.capture}`,
];
if (entry.tags && entry.tags.length) lines.push(`- Tags: ${entry.tags.join(', ')}`);
if (entry.note) lines.push(`- Saved because: ${entry.note}`);
lines.push('', `<!-- /sourcecapsule:item:${entry.id} -->`);
return lines.join('\n');
}
function updateLibraryIndexText(existing, entry) {
const header = '# SourceCapsule Library Index\n\n<!-- sourcecapsule:index:v1 -->\n';
const current = String(existing || '').trim() || header.trim();
const escapedId = String(entry.id).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = new RegExp(
`<!-- sourcecapsule:item:${escapedId} -->[\\s\\S]*?<!-- /sourcecapsule:item:${escapedId} -->`,
'g'
);
const item = renderLibraryIndexItem(entry);
if (pattern.test(current)) return `${current.replace(pattern, item).trim()}\n`;
return `${current.trim()}\n\n${item}\n`;
}
// ---------------------------------------------------------------------------
// Store-only ZIP writer (no dependency). Used only as the fallback delivery on
// browsers without the File System Access API. Media is already compressed, so
// we store (method 0) rather than deflate - simpler and effectively the same size.
// ---------------------------------------------------------------------------
const CRC32_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
function crc32(bytes) {