-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
2731 lines (2486 loc) · 101 KB
/
popup.js
File metadata and controls
2731 lines (2486 loc) · 101 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
const STATIC_FILTER_STORAGE_KEY = 'hideStaticResources';
const TAB_VISIBILITY_STORAGE_KEY = 'popupTabVisibility';
const TAB_DEFINITIONS = [
{ key: 'current', buttonId: 'currentTabBtn', view: 'current', label: 'Current tab', locked: true },
{ key: 'history', buttonId: 'historyTabBtn', view: 'history', label: 'History', locked: true },
{ key: 'comments', buttonId: 'commentsTabBtn', view: 'comments', label: 'Comments', locked: false },
{ key: 'activeInterception', buttonId: 'activeInterceptionTabBtn', view: 'activeInterception', label: 'Active Interception', locked: false },
{ key: 'bugs', buttonId: 'bugsTabBtn', view: 'bugs', label: 'Bug Hunter', locked: false },
{ key: 'twitter', buttonId: 'twitterTabBtn', view: 'twitter', label: 'Twitter / X', locked: false },
{ key: 'tiktok', buttonId: 'tiktokTabBtn', view: 'tiktok', label: 'TikTok', locked: false },
{ key: 'soundcloud', buttonId: 'soundcloudTabBtn', view: 'soundcloud', label: 'SoundCloud', locked: false },
{ key: 'discord', buttonId: 'discordTabBtn', view: 'discord', label: 'Discord', locked: false },
{ key: 'facebook', buttonId: 'facebookTabBtn', view: 'facebook', label: 'Facebook', locked: false },
{ key: 'instagram', buttonId: 'instagramTabBtn', view: 'instagram', label: 'Instagram', locked: false },
{ key: 'github', buttonId: 'githubTabBtn', view: 'github', label: 'GitHub', locked: false },
{ key: 'pinterest', buttonId: 'pinterestTabBtn', view: 'pinterest', label: 'Pinterest', locked: false }
];
const TAB_DEFINITION_BY_KEY = Object.fromEntries(TAB_DEFINITIONS.map(tab => [tab.key, tab]));
const TAB_DEFINITION_BY_VIEW = Object.fromEntries(TAB_DEFINITIONS.map(tab => [tab.view, tab]));
let hideStaticResources = true;
function buildDefaultTabVisibilitySettings() {
const defaults = {};
TAB_DEFINITIONS.forEach(tab => {
defaults[tab.key] = true;
});
return defaults;
}
function normalizeTabVisibilitySettings(raw) {
const normalized = buildDefaultTabVisibilitySettings();
if (!raw || typeof raw !== 'object') return normalized;
TAB_DEFINITIONS.forEach(tab => {
if (tab.locked) {
normalized[tab.key] = true;
return;
}
if (typeof raw[tab.key] === 'boolean') {
normalized[tab.key] = raw[tab.key];
}
});
return normalized;
}
let tabVisibilitySettings = buildDefaultTabVisibilitySettings();
let tabVisibilityUiReady = false;
(function() {
const theme = localStorage.getItem('theme') || 'dark';
document.documentElement.setAttribute('data-theme', theme);
chrome.storage.local.get(['theme', 'shellMode', STATIC_FILTER_STORAGE_KEY, TAB_VISIBILITY_STORAGE_KEY], (result) => {
if (result.theme && result.theme !== theme) {
document.documentElement.setAttribute('data-theme', result.theme);
localStorage.setItem('theme', result.theme);
const icon = document.getElementById('themeIcon');
if (icon) icon.innerHTML = result.theme === 'dark' ? '☀' : '☾';
}
if (result.shellMode && (result.shellMode === 'cmd' || result.shellMode === 'ps')) {
shellMode = result.shellMode;
localStorage.setItem('shellMode', result.shellMode);
}
if (typeof result[STATIC_FILTER_STORAGE_KEY] === 'boolean') {
hideStaticResources = result[STATIC_FILTER_STORAGE_KEY];
} else {
hideStaticResources = true;
chrome.storage.local.set({ [STATIC_FILTER_STORAGE_KEY]: true });
}
if (result[TAB_VISIBILITY_STORAGE_KEY]) {
tabVisibilitySettings = normalizeTabVisibilitySettings(result[TAB_VISIBILITY_STORAGE_KEY]);
} else {
tabVisibilitySettings = buildDefaultTabVisibilitySettings();
chrome.storage.local.set({ [TAB_VISIBILITY_STORAGE_KEY]: tabVisibilitySettings });
}
chrome.runtime.sendMessage({ action: 'setHideStaticResources', enabled: hideStaticResources }, () => {});
syncTabVisibilityUi();
});
})();
function updateThemeIcon() {
const theme = document.documentElement.getAttribute('data-theme') || 'dark';
const icon = document.getElementById('themeIcon');
if (icon) icon.innerHTML = theme === 'dark' ? '☀' : '☾';
}
let currentRequests = [];
let combinedRequestsCache = [];
let activeTabId = -1;
let activeTabDomain = '';
let activeTabUrl = '';
let currentView = 'current';
let modalList = [];
let modalIndex = -1;
let twitterRefreshInterval = null;
let tiktokRefreshInterval = null;
let soundcloudRefreshInterval = null;
let discordRefreshInterval = null;
let facebookRefreshInterval = null;
let instagramRefreshInterval = null;
let githubRefreshInterval = null;
let pinterestRefreshInterval = null;
let commentsRefreshInterval = null;
let activeInterceptionRefreshInterval = null;
let currentHistoryRefreshInterval = null;
let requestUrlSearchQuery = '';
const requestFilterMethods = new Set();
const requestFilterTypes = new Set();
const FILTER_METHODS = ['GET', 'POST', 'HEAD', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
const FILTER_TYPES = ['fetch', 'document'];
const TWITTER_REFRESH_MS = 2000;
const TIKTOK_REFRESH_MS = 2000;
const SOUNDCLOUD_REFRESH_MS = 2000;
const DISCORD_REFRESH_MS = 2000;
const FACEBOOK_REFRESH_MS = 2000;
const INSTAGRAM_REFRESH_MS = 2000;
const GITHUB_REFRESH_MS = 2000;
const PINTEREST_REFRESH_MS = 2000;
const COMMENTS_REFRESH_MS = 2000;
const ACTIVE_INTERCEPTION_REFRESH_MS = 2000;
const CURRENT_HISTORY_REFRESH_MS = 1000;
let lastTwitterDataSignature = '';
let lastTikTokDataSignature = '';
let lastSoundCloudDataSignature = '';
let lastDiscordDataSignature = '';
let lastFacebookDataSignature = '';
let lastInstagramDataSignature = '';
let lastGitHubDataSignature = '';
let lastPinterestDataSignature = '';
let lastCommentsDataSignature = '';
let instagramProfilePicBlobUrls = new Set();
let activeInterceptionEntries = [];
let activeInterceptionStats = { scriptsScanned: 0, storageDbCount: 0, endpointCount: 0, endpointHits: 0, updatedAt: null };
let lastActiveInterceptionEntriesSignature = '';
let pageCommentsData = { pageUrl: '', pageTitle: '', comments: [] };
function isTabVisible(tabKey) {
const tab = TAB_DEFINITION_BY_KEY[tabKey];
if (!tab) return true;
if (tab.locked) return true;
return tabVisibilitySettings[tab.key] !== false;
}
function getPersistedTabVisibilitySettings() {
const persisted = {};
TAB_DEFINITIONS.forEach(tab => {
if (!tab.locked) {
persisted[tab.key] = isTabVisible(tab.key);
}
});
return persisted;
}
function getTabVisibilitySettingsMarkup() {
return TAB_DEFINITIONS.filter(tab => !tab.locked).map(tab => {
const button = document.getElementById(tab.buttonId);
const checked = isTabVisible(tab.key) ? ' checked' : '';
const disabled = tab.locked ? ' disabled' : '';
const lockedClass = tab.locked ? ' is-locked' : '';
const iconHtml = button ? button.innerHTML : '';
return `
<label class="settings-option${lockedClass}">
<span class="settings-option-main">
${iconHtml}
<span class="settings-option-label">${escapeHtml(tab.label)}</span>
</span>
<input type="checkbox" data-tab-key="${tab.key}"${checked}${disabled}>
</label>
`;
}).join('');
}
function attachTabVisibilitySettingsHandlers(root = document) {
const listEl = root.querySelector('#tabVisibilityList');
if (!listEl) return;
listEl.querySelectorAll('input[data-tab-key]').forEach(input => {
input.addEventListener('change', () => {
const tab = TAB_DEFINITION_BY_KEY[input.dataset.tabKey];
if (!tab || tab.locked) return;
tabVisibilitySettings[tab.key] = input.checked;
chrome.storage.local.set({ [TAB_VISIBILITY_STORAGE_KEY]: getPersistedTabVisibilitySettings() });
applyTabVisibilitySettings();
});
});
}
function applyTabVisibilitySettings() {
TAB_DEFINITIONS.forEach(tab => {
const button = document.getElementById(tab.buttonId);
if (button) button.hidden = !isTabVisible(tab.key);
});
const activeTab = TAB_DEFINITION_BY_VIEW[currentView];
if (activeTab && !isTabVisible(activeTab.key)) {
const currentTabButton = document.getElementById('currentTabBtn');
if (currentTabButton) currentTabButton.click();
}
}
function syncTabVisibilityUi() {
if (!tabVisibilityUiReady) return;
applyTabVisibilitySettings();
if (currentView === 'settings') renderSettingsView();
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme') || 'dark';
const next = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
chrome.storage.local.set({ theme: next });
if (currentView === 'settings') {
renderSettingsView();
} else {
updateThemeIcon();
}
}
function stopAllViewRefreshes() {
stopTwitterRefresh();
stopTikTokRefresh();
stopSoundCloudRefresh();
stopDiscordRefresh();
stopFacebookRefresh();
stopInstagramRefresh();
stopGitHubRefresh();
stopPinterestRefresh();
stopCommentsRefresh();
stopActiveInterceptionRefresh();
if (typeof stopBugRefresh === 'function') stopBugRefresh();
stopCurrentHistoryRefresh();
}
function resetAllPlatformDataSignatures() {
lastTwitterDataSignature = '';
lastTikTokDataSignature = '';
lastSoundCloudDataSignature = '';
lastDiscordDataSignature = '';
lastFacebookDataSignature = '';
lastInstagramDataSignature = '';
lastGitHubDataSignature = '';
lastPinterestDataSignature = '';
lastCommentsDataSignature = '';
}
function renderSettingsView() {
const container = document.getElementById('requestsContainer');
if (!container) return;
const theme = document.documentElement.getAttribute('data-theme') || 'dark';
const themeModeLabel = theme === 'dark' ? 'Dark mode' : 'Light mode';
const themeSwitchLabel = theme === 'dark' ? 'Switch to Light' : 'Switch to Dark';
container.innerHTML = `
<div class="settings-page">
<div class="settings-card">
<div class="settings-card-header">
<div class="settings-card-title">Appearance</div>
<div class="settings-card-note">Theme controls moved here from the header.</div>
</div>
<div class="settings-card-body">
<button class="settings-theme-btn" id="settingsThemeToggle">
<span class="settings-theme-main">
<span class="settings-theme-icon" id="themeIcon">☀</span>
<span class="settings-theme-copy">
<span class="settings-row-title">${themeModeLabel}</span>
<span class="settings-row-subtitle">Choose how the popup is displayed.</span>
</span>
</span>
<span class="settings-theme-value">${themeSwitchLabel}</span>
</button>
</div>
</div>
<div class="settings-card">
<div class="settings-card-header">
<div class="settings-card-title">Visible Tabs</div>
</div>
<div class="settings-card-body">
<div class="settings-list" id="tabVisibilityList">${getTabVisibilitySettingsMarkup()}</div>
</div>
</div>
</div>
`;
attachTabVisibilitySettingsHandlers(container);
document.getElementById('settingsThemeToggle')?.addEventListener('click', toggleTheme);
updateThemeIcon();
}
function isGraphQLRequest(request) {
if (!request.body || request.method !== 'POST') return false;
try {
const body = typeof request.body === 'string' ? JSON.parse(request.body) : request.body;
return body && typeof body.query === 'string';
} catch {
return false;
}
}
function parseGraphQLBody(request) {
try {
const body = typeof request.body === 'string' ? JSON.parse(request.body) : request.body;
return { query: body.query || '', variables: body.variables || {} };
} catch {
return null;
}
}
function formatGraphQLValue(value) {
if (value === null || value === undefined) return 'null';
if (typeof value === 'boolean') return String(value);
if (typeof value === 'number') return String(value);
if (typeof value === 'string') return '"' + value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
if (Array.isArray(value)) return '[' + value.map(formatGraphQLValue).join(', ') + ']';
if (typeof value === 'object') {
const fields = Object.entries(value).map(([k, v]) => `${k}: ${formatGraphQLValue(v)}`);
return '{ ' + fields.join(', ') + ' }';
}
return String(value);
}
function inlineVariables(queryStr, variables) {
if (!variables) variables = {};
let result = '';
let inString = false;
let escapeNext = false;
let i = 0;
while (i < queryStr.length) {
if (escapeNext) {
result += queryStr[i]; escapeNext = false; i++; continue;
}
if (queryStr[i] === '\\' && inString) {
result += queryStr[i]; escapeNext = true; i++; continue;
}
if (queryStr[i] === '"') {
result += queryStr[i]; inString = !inString; i++; continue;
}
if (inString) {
result += queryStr[i]; i++; continue;
}
if (queryStr[i] === '$') {
let varName = '';
let j = i + 1;
while (j < queryStr.length && /[a-zA-Z0-9_]/.test(queryStr[j])) {
varName += queryStr[j]; j++;
}
if (varName) {
const value = variables.hasOwnProperty(varName) ? variables[varName] : null;
result += formatGraphQLValue(value);
i = j;
continue;
}
}
result += queryStr[i]; i++;
}
return result;
}
function extractQueryInner(queryStr) {
let q = queryStr.trim();
q = q.replace(/^(query|subscription)\s*\w*\s*(\([^)]*\))?\s*/, '');
let depth = 0, start = -1, inStr = false, esc = false;
for (let i = 0; i < q.length; i++) {
const ch = q[i];
if (esc) { esc = false; continue; }
if (ch === '\\' && inStr) { esc = true; continue; }
if (ch === '"') { inStr = !inStr; continue; }
if (inStr) continue;
if (ch === '{') { if (depth === 0) start = i + 1; depth++; }
else if (ch === '}') { depth--; if (depth === 0 && start !== -1) return q.slice(start, i).trim(); }
}
return q;
}
function isMutation(queryStr) {
return queryStr.trim().startsWith('mutation');
}
function groupGraphQLRequests(requests) {
const groups = {};
requests.forEach((req, index) => {
if (isGraphQLRequest(req)) {
const parsed = parseGraphQLBody(req);
if (parsed && !isMutation(parsed.query)) {
if (!groups[req.url]) groups[req.url] = [];
groups[req.url].push({ request: req, index });
}
}
});
const result = [];
for (const [url, items] of Object.entries(groups)) {
if (items.length >= 2) result.push({ url, items });
}
return result;
}
function buildCombinedRequest(group) {
const seen = new Set();
const uniqueItems = [];
group.items.forEach(({ request }) => {
const parsed = parseGraphQLBody(request);
if (!parsed) return;
const key = parsed.query.replace(/\s+/g, ' ').trim();
if (!seen.has(key)) { seen.add(key); uniqueItems.push(request); }
});
if (uniqueItems.length < 2) return null;
const queryParts = [];
const descriptions = [];
uniqueItems.forEach((request, i) => {
const parsed = parseGraphQLBody(request);
if (!parsed) return;
let inner = extractQueryInner(parsed.query);
inner = inlineVariables(inner, parsed.variables);
queryParts.push(`q${i}: ${inner}`);
const fieldMatch = inner.match(/^(\w+)/);
const argMatch = inner.match(/\(([^)]*)\)/s);
let desc = fieldMatch ? fieldMatch[1] : `query ${i}`;
if (argMatch) {
const strMatch = argMatch[1].match(/"([^"]*)"/);
if (strMatch) {
const val = strMatch[1];
const short = val.split('~').pop() || val.split('@').pop() || val;
desc += ` [${short.length > 30 ? short.substring(0, 30) + '...' : short}]`;
}
}
descriptions.push(`q${i}: ${desc}`);
});
const combinedQuery = `{ ${queryParts.join(' ')} }`;
const combinedBody = JSON.stringify({ variables: {}, query: combinedQuery });
const template = group.items[0].request;
return {
url: group.url,
method: 'POST',
headers: template.headers,
body: combinedBody,
timestamp: new Date().toISOString(),
type: 'combined',
_combinedCount: uniqueItems.length,
_descriptions: descriptions,
_originalRequests: uniqueItems
};
}
function compactBody(request) {
if (!request.body || request.body === 'null') return null;
let raw = typeof request.body === 'string' ? request.body : JSON.stringify(request.body);
try {
const obj = JSON.parse(raw);
if (obj.query && typeof obj.query === 'string') {
obj.query = obj.query.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim();
}
return JSON.stringify(obj);
} catch { return raw.replace(/\n/g, ' ').replace(/\s+/g, ' '); }
}
let shellMode = 'ps';
function generateCurl(request) {
const method = request.method ? request.method.toUpperCase().replace(/[^A-Z]/g, '') : 'GET';
if (shellMode === 'ps') {
return generateCurlPS(request, method);
}
if (shellMode === 'cmd') {
return generateCurlCMD(request, method);
}
return generateCurlBash(request, method);
}
function generateCurlPS(request, method) {
const esc = (str) => String(str).replace(/'/g, "''");
let cmd = `curl.exe '${esc(request.url)}' -X ${method}`;
if (request.headers) {
const headers = Array.isArray(request.headers)
? request.headers
: Object.entries(request.headers).map(([name, value]) => ({ name, value }));
headers.forEach(h => {
const name = h.name || h[0];
const value = h.value || h[1];
const skip = ['host', 'connection', 'content-length', 'accept-encoding'];
if (String(value) === 'undefined' || String(value) === 'null' || !value) return;
if (skip.includes(name.toLowerCase())) return;
cmd += ` -H '${esc(name)}: ${esc(value)}'`;
});
}
const body = compactBody(request);
if (body) {
cmd += ` --data-raw '${esc(body)}'`;
}
cmd += ` --compressed`;
return cmd;
}
function generateCurlCMD(request, method) {
const escCmd = (str) => String(str).replace(/"/g, '\\"').replace(/&/g, '^&').replace(/\^/g, '^^');
let cmd = `curl.exe "${escCmd(request.url)}" -X ${method}`;
if (request.headers) {
const headers = Array.isArray(request.headers)
? request.headers
: Object.entries(request.headers).map(([name, value]) => ({ name, value }));
headers.forEach(h => {
const name = h.name || h[0];
const value = h.value || h[1];
const skip = ['host', 'connection', 'content-length', 'accept-encoding'];
if (String(value) === 'undefined' || String(value) === 'null' || !value) return;
if (skip.includes(name.toLowerCase())) return;
cmd += ` -H "${escCmd(name)}: ${escCmd(value)}"`;
});
}
const body = compactBody(request);
if (body) {
cmd += ` --data-raw "${escCmd(body)}"`;
}
cmd += ` --compressed`;
return cmd;
}
function generateCurlBash(request, method) {
const esc = (str) => String(str).replace(/'/g, "'\\''");
let cmd = `curl '${esc(request.url)}' -X ${method}`;
if (request.headers) {
const headers = Array.isArray(request.headers)
? request.headers
: Object.entries(request.headers).map(([name, value]) => ({ name, value }));
headers.forEach(h => {
const name = h.name || h[0];
const value = h.value || h[1];
const skip = ['host', 'connection', 'content-length', 'accept-encoding'];
if (String(value) === 'undefined' || String(value) === 'null' || !value) return;
if (skip.includes(name.toLowerCase())) return;
cmd += ` -H '${esc(name)}: ${esc(value)}'`;
});
}
const body = compactBody(request);
if (body) {
cmd += ` --data-raw '${esc(body)}'`;
}
cmd += ` --compressed`;
return cmd;
}
function generateCurlForMode(mode, request) {
const method = request.method ? request.method.toUpperCase().replace(/[^A-Z]/g, '') : 'GET';
if (mode === 'ps') return generateCurlPS(request, method);
if (mode === 'cmd') return generateCurlCMD(request, method);
return generateCurlBash(request, method);
}
function buildActiveEndpointRequest(entry) {
const method = (entry && entry.method ? String(entry.method) : 'GET').toUpperCase();
const headers = [{ name: 'Accept', value: 'application/json' }];
return {
url: entry && entry.url ? entry.url : (entry && entry.rawUrl ? entry.rawUrl : ''),
method: method || 'GET',
headers,
body: null
};
}
function formatLastSeen(value) {
if (!value) return 'just now';
const then = new Date(value).getTime();
if (!Number.isFinite(then)) return 'just now';
const diffMs = Date.now() - then;
if (diffMs < 5000) return 'just now';
if (diffMs < 60000) return `${Math.floor(diffMs / 1000)}s ago`;
if (diffMs < 3600000) return `${Math.floor(diffMs / 60000)}m ago`;
return `${Math.floor(diffMs / 3600000)}h ago`;
}
function copyTextWithButtonFeedback(text, btn) {
if (!btn) return;
navigator.clipboard.writeText(String(text || '')).then(() => {
const original = btn.textContent;
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = original;
btn.classList.remove('copied');
}, 1800);
});
}
function formatTime(ts) {
return new Date(ts).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
}
function countForCurrentSite(requests) {
if (!activeTabDomain) return 0;
return requests.filter(req => {
if (req.initiator) {
try { if (new URL(req.initiator).hostname === activeTabDomain) return true; } catch {}
}
if (req.url) {
try { if (new URL(req.url).hostname === activeTabDomain) return true; } catch {}
}
return false;
}).length;
}
function updateStats(requests) {
const siteNameEl = document.getElementById('currentSiteName');
if (siteNameEl) siteNameEl.textContent = activeTabDomain || '—';
document.getElementById('currentSiteCount').textContent = countForCurrentSite(requests);
document.getElementById('totalCount').textContent = requests.length;
}
function getResponseBodySearchString(req) {
const v = req.responseBody;
if (v === undefined || v === null) return '';
if (typeof v === 'string') return v;
try { return JSON.stringify(v); } catch (_) { return String(v); }
}
function tokenMatchesText(token, text) {
if (!token || text == null) return !token;
const t = String(text);
if (!token.includes('*')) return t.toLowerCase().includes(token.toLowerCase());
const parts = token.split('*').map(p => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
const pattern = parts.join('.*');
try {
return new RegExp(pattern, 'i').test(t);
} catch (_) {
return t.toLowerCase().includes(token.toLowerCase());
}
}
function matchRequestSearch(req, query) {
if (!query || !String(query).trim()) return true;
const tokens = String(query).trim().split(/\s+/).filter(Boolean);
const urlStr = String(req.url || '');
const bodyStr = getResponseBodySearchString(req);
return tokens.every(t => tokenMatchesText(t, urlStr) || tokenMatchesText(t, bodyStr));
}
function renderRequests(requests) {
const container = document.getElementById('requestsContainer');
updateStats(requests);
if (currentView === 'comments') {
renderCommentsTabEnhanced();
return;
}
if (currentView === 'activeInterception') {
renderActiveInterceptionTab();
return;
}
if (currentView === 'bugs') {
if (typeof renderBugTab === 'function') renderBugTab();
return;
}
if (currentView === 'settings') {
renderSettingsView();
return;
}
if (requests.length === 0 && (currentView === 'current' || currentView === 'history')) {
container.innerHTML = '<div class="empty-state"><div class="empty-text">Waiting for API requests...<br>Navigate any website to capture traffic</div></div>';
return;
}
if (currentView === 'current') {
renderCurrentTab(requests);
} else if (currentView === 'twitter') {
renderTwitterTab(requests);
} else if (currentView === 'tiktok') {
renderTikTokTab(requests);
} else if (currentView === 'soundcloud') {
renderSoundCloudTab(requests);
} else if (currentView === 'discord') {
renderDiscordTab(requests);
} else if (currentView === 'facebook') {
renderFacebookTab(requests);
} else if (currentView === 'instagram') {
renderInstagramTab(requests);
} else if (currentView === 'github') {
renderGitHubTab(requests);
} else if (currentView === 'pinterest') {
renderPinterestTab(requests);
} else {
renderHistoryTab(requests);
}
}
function escapeHtml(s) {
if (!s) return '';
const div = document.createElement('div');
div.textContent = s;
return div.innerHTML;
}
function escapeAttribute(value) {
return escapeHtml(String(value == null ? '' : value)).replace(/"/g, '"');
}
function getCodeLanguage(comment) {
const st = (comment && comment.sourceType) || '';
const url = (comment && comment.fileUrl) || '';
if (/html/i.test(st)) return 'html';
if (/style/i.test(st) || /\.css$/i.test(url)) return 'css';
if (/script/i.test(st) || /\.(js|ts|mjs|cjs|jsx|tsx)$/i.test(url)) return 'javascript';
return 'javascript';
}
function highlightCode(code, lang) {
if (!code) return '';
const ranges = [];
const add = (re, cls) => {
let m;
const copy = new RegExp(re.source, re.flags);
while ((m = copy.exec(code)) !== null) {
ranges.push({ start: m.index, end: m.index + m[0].length, cls, text: m[0] });
}
};
add(/(^\s*\d+\s*\|\s*)/gm, 'hl-line');
add(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g, 'hl-string');
add(/\/\*[\s\S]*?\*\//g, 'hl-comment');
add(/\/\/[^\n]*/g, 'hl-comment');
add(/<!--[\s\S]*?-->/g, 'hl-comment');
add(/\b(var|let|const|function|return|if|else|for|while|do|switch|case|break|continue|try|catch|throw|new|typeof|instanceof|in|of|async|await|class|extends|import|export|from|default)\b/g, 'hl-keyword');
add(/\b(true|false|null|undefined)\b/g, 'hl-literal');
add(/\b(\d+\.?\d*)\b/g, 'hl-number');
if (lang === 'html') {
add(/<\/?[\w-]+/g, 'hl-tag');
add(/[\w-]+(?=\s*=)/g, 'hl-attr');
}
ranges.sort((a, b) => a.start - b.start);
const merged = [];
for (const r of ranges) {
if (merged.length && r.start < merged[merged.length - 1].end) continue;
merged.push(r);
}
let out = '';
let pos = 0;
for (const r of merged) {
out += escapeHtml(code.slice(pos, r.start));
out += `<span class="${r.cls}">${escapeHtml(r.text)}</span>`;
pos = r.end;
}
out += escapeHtml(code.slice(pos));
return out;
}
function stripJsonXssiPrefix(str) {
if (typeof str !== 'string') return str;
const trimmed = str.trimStart();
if (trimmed.startsWith(")]}'\n")) return trimmed.slice(5);
if (trimmed.startsWith(")]}'\r\n")) return trimmed.slice(6);
if (trimmed.startsWith(")]}'")) return trimmed.slice(4).trimStart();
if (trimmed.startsWith(")]}\n")) return trimmed.slice(4);
if (trimmed.startsWith(")]}")) return trimmed.slice(3).trimStart();
return str;
}
function highlightJson(jsonStr) {
if (!jsonStr || typeof jsonStr !== 'string') return '';
const code = jsonStr;
const ranges = [];
const add = (re, cls) => {
let m;
const copy = new RegExp(re.source, re.flags);
while ((m = copy.exec(code)) !== null) {
ranges.push({ start: m.index, end: m.index + m[0].length, cls, text: m[0] });
}
};
add(/"(?:[^"\\]|\\.)*"(?=\s*:)/g, 'hl-json-key');
add(/"(?:[^"\\]|\\.)*"/g, 'hl-json-string');
add(/\b(true|false|null)\b/g, 'hl-json-literal');
add(/\b(-?\d+\.?\d*([eE][+-]?\d+)?)\b/g, 'hl-json-number');
ranges.sort((a, b) => a.start - b.start);
const merged = [];
for (const r of ranges) {
if (merged.length && r.start < merged[merged.length - 1].end) continue;
merged.push(r);
}
let out = '';
let pos = 0;
for (const r of merged) {
out += escapeHtml(code.slice(pos, r.start));
out += `<span class="${r.cls}">${escapeHtml(r.text)}</span>`;
pos = r.end;
}
out += escapeHtml(code.slice(pos));
return out;
}
function getSourceFileLabel(url) {
if (!url) return 'Unknown file';
try {
const parsed = new URL(url);
const parts = parsed.pathname.split('/').filter(Boolean);
const last = parts.length ? parts[parts.length - 1] : parsed.hostname;
return last || parsed.hostname || url;
} catch (_) {
return url;
}
}
function buildLineStarts(text) {
const starts = [0];
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) === 10) starts.push(i + 1);
}
return starts;
}
function getLineNumberForIndex(lineStarts, index) {
let low = 0;
let high = lineStarts.length - 1;
while (low <= high) {
const mid = (low + high) >> 1;
const start = lineStarts[mid];
const next = mid + 1 < lineStarts.length ? lineStarts[mid + 1] : Number.MAX_SAFE_INTEGER;
if (index < start) high = mid - 1;
else if (index >= next) low = mid + 1;
else return mid + 1;
}
return 1;
}
function buildContextSnippet(lines, startLine, endLine, radius = 10) {
const from = Math.max(1, startLine - radius);
const to = Math.min(lines.length, endLine + radius);
return lines.slice(from - 1, to).map((line, idx) => {
const lineNumber = from + idx;
return `${String(lineNumber).padStart(5, ' ')} | ${line}`;
}).join('\n');
}
function normalizeCommentPreview(text) {
return String(text || '').replace(/\s+/g, ' ').trim();
}
function stripCommentDecorators(text, syntax) {
let value = String(text || '');
if (syntax === 'html') value = value.replace(/^<!--\s?|\s?-->$/g, '');
else if (syntax === 'block') value = value.replace(/^\/\*\s?|\s?\*\/$/g, '');
else if (syntax === 'line') value = value.replace(/^\/\/\s?/, '');
return normalizeCommentPreview(value);
}
function extractHtmlComments(text, sourceMeta) {
const comments = [];
const lines = text.split(/\r?\n/);
const lineStarts = buildLineStarts(text);
const regex = /<!--([\s\S]*?)-->/g;
let match;
while ((match = regex.exec(text))) {
const full = match[0];
const startLine = getLineNumberForIndex(lineStarts, match.index);
const endLine = getLineNumberForIndex(lineStarts, match.index + full.length - 1);
comments.push({
fileUrl: sourceMeta.fileUrl,
rawUrl: sourceMeta.rawUrl || sourceMeta.fileUrl,
fileLabel: sourceMeta.fileLabel,
sourceType: sourceMeta.sourceType,
syntax: 'html',
text: stripCommentDecorators(full, 'html'),
line: startLine,
endLine,
context: buildContextSnippet(lines, startLine, endLine, 10)
});
}
return comments;
}
function extractCodeComments(text, sourceMeta, options = {}) {
const comments = [];
const lines = text.split(/\r?\n/);
const lineStarts = buildLineStarts(text);
const allowLineComments = options.allowLineComments !== false;
let i = 0;
let state = 'normal';
let startIndex = -1;
while (i < text.length) {
const ch = text[i];
const next = text[i + 1];
if (state === 'line') {
if (ch === '\n') {
const raw = text.slice(startIndex, i);
const relStart = getLineNumberForIndex(lineStarts, startIndex);
const relEnd = getLineNumberForIndex(lineStarts, Math.max(startIndex, i - 1));
const startLine = sourceMeta.lineOffset + relStart - 1;
const endLine = sourceMeta.lineOffset + relEnd - 1;
comments.push({
fileUrl: sourceMeta.fileUrl,
rawUrl: sourceMeta.rawUrl || sourceMeta.fileUrl,
fileLabel: sourceMeta.fileLabel,
sourceType: sourceMeta.sourceType,
syntax: 'line',
text: stripCommentDecorators(raw, 'line'),
line: startLine,
endLine,
context: buildContextSnippet(sourceMeta.fullLines || lines, startLine, endLine, 10)
});
state = 'normal';
}
i += 1;
continue;
}
if (state === 'block') {
if (ch === '*' && next === '/') {
const endExclusive = i + 2;
const raw = text.slice(startIndex, endExclusive);
const relStart = getLineNumberForIndex(lineStarts, startIndex);
const relEnd = getLineNumberForIndex(lineStarts, endExclusive - 1);
const startLine = sourceMeta.lineOffset + relStart - 1;
const endLine = sourceMeta.lineOffset + relEnd - 1;
comments.push({
fileUrl: sourceMeta.fileUrl,
rawUrl: sourceMeta.rawUrl || sourceMeta.fileUrl,
fileLabel: sourceMeta.fileLabel,
sourceType: sourceMeta.sourceType,
syntax: 'block',
text: stripCommentDecorators(raw, 'block'),
line: startLine,
endLine,
context: buildContextSnippet(sourceMeta.fullLines || lines, startLine, endLine, 10)
});
state = 'normal';
i += 2;
continue;
}
i += 1;
continue;
}
if (state === 'single') {
if (ch === '\\') i += 2;
else if (ch === '\'') { state = 'normal'; i += 1; }
else i += 1;
continue;
}
if (state === 'double') {
if (ch === '\\') i += 2;
else if (ch === '"') { state = 'normal'; i += 1; }
else i += 1;
continue;
}
if (state === 'template') {
if (ch === '\\') i += 2;
else if (ch === '`') { state = 'normal'; i += 1; }
else i += 1;
continue;
}
if (ch === '\'') { state = 'single'; i += 1; continue; }
if (ch === '"') { state = 'double'; i += 1; continue; }
if (ch === '`') { state = 'template'; i += 1; continue; }
if (ch === '/' && next === '*') {
startIndex = i;
state = 'block';
i += 2;
continue;
}
if (allowLineComments && ch === '/' && next === '/') {
const prev = text[i - 1] || '';
if (prev !== ':') {
startIndex = i;
state = 'line';
i += 2;
continue;
}
}
i += 1;
}
if (state === 'line' && startIndex >= 0) {
const raw = text.slice(startIndex);
const relStart = getLineNumberForIndex(lineStarts, startIndex);
const relEnd = getLineNumberForIndex(lineStarts, text.length ? text.length - 1 : 0);