-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
3756 lines (3419 loc) · 163 KB
/
Copy pathmain.js
File metadata and controls
3756 lines (3419 loc) · 163 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
/* ==========================================================================
Shared dialogs and notices
========================================================================== */
(() => {
try {
const identifier = localStorage.getItem('fridg3_hard_ban_id') || '';
if (!/^[a-f0-9]{64}$/.test(identifier)) return;
const cookieMatch = document.cookie.match(/(?:^|;\s*)fridg3_hard_ban_id=([a-f0-9]{64})(?:;|$)/);
if (cookieMatch && cookieMatch[1] === identifier) return;
const domain = location.hostname === 'fridge.dev' || location.hostname.endsWith('.fridge.dev')
? '; Domain=.fridge.dev'
: '';
document.cookie = `fridg3_hard_ban_id=${identifier}; Path=/; Max-Age=157680000; SameSite=Lax${location.protocol === 'https:' ? '; Secure' : ''}${domain}`;
if (sessionStorage.getItem('fridg3_hard_ban_cookie_synced') !== identifier) {
sessionStorage.setItem('fridg3_hard_ban_cookie_synced', identifier);
location.reload();
}
} catch (_error) {
// Storage may be unavailable in privacy-restricted browser contexts.
}
})();
let hostRedirectInProgress = false;
function siteEscapeHtml(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function showSitePopup(options) {
const config = options || {};
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'site-popup-overlay';
if (config.className) overlay.classList.add(...String(config.className).split(/\s+/).filter(Boolean));
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
const dialog = document.createElement('div');
dialog.className = 'site-popup-dialog';
const title = document.createElement('div');
title.className = 'site-popup-title';
title.textContent = config.title || 'notice';
const detail = document.createElement('div');
detail.className = 'site-popup-detail';
if (config.html) {
detail.innerHTML = config.html;
} else {
detail.textContent = config.detail || '';
}
let input = null;
if (config.input === true) {
input = document.createElement('input');
input.className = 'site-popup-input';
input.type = config.inputType || 'text';
input.value = config.inputValue || '';
input.placeholder = config.inputPlaceholder || '';
input.autocomplete = 'off';
}
const noButtons = config.noButtons === true;
const actions = document.createElement('div');
actions.className = 'site-popup-actions';
const cancelText = config.cancelText || '';
let cancel = null;
if (cancelText) {
cancel = document.createElement('button');
cancel.className = 'site-popup-button site-popup-cancel';
cancel.type = 'button';
cancel.textContent = cancelText;
actions.append(cancel);
}
const customText = config.customText || '';
let custom = null;
if (customText) {
custom = document.createElement('button');
custom.className = 'site-popup-button site-popup-custom';
custom.type = 'button';
custom.textContent = customText;
actions.append(custom);
}
let ok = null;
if (!noButtons) {
ok = document.createElement('button');
ok.className = 'site-popup-button site-popup-ok';
ok.type = 'button';
ok.textContent = config.okText || 'ok';
actions.append(ok);
}
dialog.append(title, detail);
if (input) dialog.append(input);
if (!noButtons) dialog.append(actions);
overlay.append(dialog);
const close = (value) => {
document.removeEventListener('keydown', onKeydown);
overlay.classList.add('is-closing');
window.setTimeout(() => overlay.remove(), 160);
resolve(value);
};
const onKeydown = (event) => {
if (event.key === 'Escape') close(input ? null : false);
if (event.key === 'Enter') close(input ? input.value : true);
};
if (cancel) cancel.addEventListener('click', () => close(input ? null : false));
if (custom) custom.addEventListener('click', async () => {
if (typeof config.customAction === 'function') {
await config.customAction(custom);
if (config.customCloses === false) return;
}
close('custom');
});
if (ok) ok.addEventListener('click', () => close(input ? input.value : true));
if (!noButtons) {
overlay.addEventListener('click', event => {
if (event.target === overlay) close(input ? null : false);
});
document.addEventListener('keydown', onKeydown);
}
document.body.append(overlay);
if (input) {
input.focus();
input.select();
}
});
}
window.showSitePopup = showSitePopup;
function showSiteNotice(title, detail) {
return showSitePopup({
title: title || 'notice',
detail: detail || '',
okText: 'ok'
});
}
function showSitePrompt(title, detail, value) {
return showSitePopup({
title: title || 'input',
detail: detail || '',
input: true,
inputValue: value || '',
okText: 'ok',
cancelText: 'cancel'
});
}
window.showSiteNotice = showSiteNotice;
window.showSitePrompt = showSitePrompt;
function initIpRestrictionNotification() {
fetch('/api/ip-restriction/', { credentials: 'same-origin', cache: 'no-store' })
.then(response => response.ok ? response.json() : null)
.then(data => {
if (!data || !data.ok || !data.restricted || !data.notificationId) return;
const storageKey = `fridg3-ip-restriction-notice-${data.notificationId}`;
try {
if (localStorage.getItem(storageKey) === '1') return;
localStorage.setItem(storageKey, '1');
} catch (_) {
if (window.__fridg3IpRestrictionNotice === storageKey) return;
window.__fridg3IpRestrictionNotice = storageKey;
}
const messageHtml = data.reason
? `<strong>Reason:</strong> ${siteEscapeHtml(data.reason)}`
: '';
showSitePopup({
title: data.title || 'Your IP address has been restricted from uploading content to the website',
html: messageHtml,
okText: 'ok'
});
})
.catch(() => {});
}
window.addEventListener('DOMContentLoaded', () => {
initIpRestrictionNotification();
window.setInterval(initIpRestrictionNotification, 60000);
});
document.addEventListener('pointerdown', event => {
document.querySelectorAll('.site-action-menu[open]').forEach(menu => {
if (!menu.contains(event.target)) menu.removeAttribute('open');
});
}, true);
document.addEventListener('click', event => {
const activeMenu = event.target.closest('.site-action-menu');
document.querySelectorAll('.site-action-menu[open]').forEach(menu => {
if (menu !== activeMenu || event.target.closest('.site-action-menu-item')) menu.removeAttribute('open');
});
});
document.addEventListener('keydown', event => {
if (event.key !== 'Escape') return;
document.querySelectorAll('.site-action-menu[open]').forEach(menu => menu.removeAttribute('open'));
});
document.addEventListener('click', event => {
const listing = event.target.closest('.restricted-ip-history-link[data-history-href]');
if (!listing || event.target.closest('a, button, input, textarea, select')) return;
window.location.href = listing.dataset.historyHref;
});
document.addEventListener('keydown', event => {
if (event.key !== 'Enter' && event.key !== ' ') return;
const listing = event.target.closest('.restricted-ip-history-link[data-history-href]');
if (!listing || event.target.closest('a, button, input, textarea, select')) return;
event.preventDefault();
window.location.href = listing.dataset.historyHref;
});
const fridg3DebugLogs = { client: [], server: [] };
let fridg3AccessLogs = [];
const FRIDG3_DEBUG_LOG_LIMIT = 1000;
const FRIDG3_ACCESS_LOG_LIMIT = 10000;
let fridg3ProcessLogTimer = null;
let fridg3AccessLogTimer = null;
let fridg3AccessLogRequestActive = false;
let fridg3ProcessLogCursor = { identity: '', offset: 0 };
let fridg3ProcessLogRequestActive = false;
let fridg3DebugEnabled = false;
let fridg3DebugStartupSeeded = false;
let fridg3DebugListenersActive = false;
let fridg3OriginalFetch = null;
let fridg3OriginalConsoleError = null;
let fridg3OriginalConsoleWarn = null;
let fridg3DebugHistoryRestored = false;
let fridg3ServerHistoryRestored = false;
let fridg3ServerDebugAuthorized = false;
let fridg3DebugPersistTimer = null;
const fridg3DeferredOutputUpdates = new Map();
let fridg3SelectionUpdateListenerBound = false;
const fridg3VirtualDebugOutputs = new WeakMap();
function fridg3OutputHasActiveSelection(output) {
const selection = window.getSelection ? window.getSelection() : null;
if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
return output.contains(selection.anchorNode) || output.contains(selection.focusNode);
}
function fridg3FlushDeferredOutputUpdates() {
fridg3DeferredOutputUpdates.forEach((update, output) => {
if (fridg3OutputHasActiveSelection(output)) return;
fridg3DeferredOutputUpdates.delete(output);
update();
});
if (fridg3DeferredOutputUpdates.size === 0 && fridg3SelectionUpdateListenerBound) {
document.removeEventListener('selectionchange', fridg3FlushDeferredOutputUpdates);
fridg3SelectionUpdateListenerBound = false;
}
}
function fridg3RunAfterOutputSelection(output, update) {
if (!fridg3OutputHasActiveSelection(output)) {
update();
return;
}
fridg3DeferredOutputUpdates.set(output, update);
if (!fridg3SelectionUpdateListenerBound) {
document.addEventListener('selectionchange', fridg3FlushDeferredOutputUpdates);
fridg3SelectionUpdateListenerBound = true;
}
}
function fridg3PersistDebugHistory() {
if (fridg3DebugPersistTimer) window.clearTimeout(fridg3DebugPersistTimer);
fridg3DebugPersistTimer = null;
try {
sessionStorage.setItem('fridg3DebugClientHistory', JSON.stringify(fridg3DebugLogs.client.filter(entry => !entry.transient)));
if (fridg3ServerDebugAuthorized) {
sessionStorage.setItem('fridg3DebugServerHistory', JSON.stringify(fridg3DebugLogs.server));
}
} catch (_) { /* storage may be unavailable or full */ }
}
function fridg3ScheduleDebugHistoryPersist() {
if (fridg3DebugPersistTimer) return;
fridg3DebugPersistTimer = window.setTimeout(fridg3PersistDebugHistory, 100);
}
function fridg3ReadDebugHistory(key) {
try {
const parsed = JSON.parse(sessionStorage.getItem(key) || '[]');
if (!Array.isArray(parsed)) return [];
return parsed.filter(entry => entry && typeof entry.timestamp === 'string' && typeof entry.message === 'string')
.slice(-FRIDG3_DEBUG_LOG_LIMIT)
.map(entry => {
entry.channel = key.includes('Server') ? 'server' : 'client';
if (!entry.createdAt) {
const parts = entry.timestamp.split(':').map(Number);
if (parts.length === 3 && parts.every(Number.isFinite)) {
const inferred = new Date();
inferred.setHours(parts[0], parts[1], parts[2], 0);
if (inferred.getTime() > Date.now() + 60000) inferred.setDate(inferred.getDate() - 1);
entry.createdAt = inferred.toISOString();
}
}
if (/^\[PHP\]\s+warning:/i.test(entry.message)) {
entry.isError = false;
entry.isWarning = true;
}
if (/^\[PHP\]\s+(?:loaded\s+|.*\brequest (?:initialized|completed)(?:\b|$))/i.test(entry.message)) {
entry.category = 'loaded';
}
return entry;
});
} catch (_) {
return [];
}
}
function fridg3RestoreClientDebugHistory() {
if (fridg3DebugHistoryRestored) return;
fridg3DebugHistoryRestored = true;
fridg3DebugLogs.client.push(...fridg3ReadDebugHistory('fridg3DebugClientHistory'));
}
function fridg3RestoreServerDebugHistory() {
if (fridg3ServerHistoryRestored) return;
fridg3ServerHistoryRestored = true;
const restored = fridg3ReadDebugHistory('fridg3DebugServerHistory');
if (restored.length) {
fridg3DebugLogs.server.unshift(...restored);
if (fridg3DebugLogs.server.length > FRIDG3_DEBUG_LOG_LIMIT) {
fridg3DebugLogs.server.splice(0, fridg3DebugLogs.server.length - FRIDG3_DEBUG_LOG_LIMIT);
}
}
}
function fridg3DebugAppend(channel, value, processLog = false, transient = false) {
if (!fridg3DebugEnabled) return;
const target = channel === 'server' ? 'server' : 'client';
const now = new Date();
const timestamp = [now.getHours(), now.getMinutes(), now.getSeconds()]
.map(part => String(part).padStart(2, '0'))
.join(':');
const message = typeof value === 'string' ? value : String(value);
const networkStatusMatch = message.match(/^\[(?:network|upload)\]\s+[A-Z]+\s+\S+\s+(\d{3})$/);
const networkStatus = networkStatusMatch ? Number(networkStatusMatch[1]) : 0;
const explicitPhpWarning = /^\[PHP\]\s+warning:/i.test(message);
const entry = {
timestamp,
createdAt: now.toISOString(),
message,
processLog,
transient,
channel: target,
category: /^\[PHP\]\s+(?:loaded\s+|.*\brequest (?:initialized|completed)(?:\b|$))/i.test(message)
? 'loaded'
: /^\[(?:network|upload)\](?:\s|$)/i.test(message)
? 'network'
: /^\[settings\](?:\s|$)/i.test(message)
|| message === '[sidebar/player] sidebar and shared content initialized'
? 'settings'
: '',
isError: !explicitPhpWarning && (networkStatus >= 400 || /(?:\berror\b|\bfailed\b|\bfailure\b|\bfatal\b|\bexception\b|\brejected\b|\bblocked\b|\binvalid\b|\bunavailable\b|HTTP\s+[45]\d\d)/i.test(message)),
isWarning: explicitPhpWarning || (networkStatus >= 300 && networkStatus < 400) || /(?:\bwarning\b|\bwarn(?:ed|ing)?\b)/i.test(message),
isSuccess: (networkStatus >= 200 && networkStatus < 300) || /(?:SPA form submission completed:\s*\/(?:feed|journal)\/create\b|(?:post|data|media|image|attachment|paste|file)[^\n]*(?:upload(?:ed)?|created|queued|saved(?: successfully)?)|(?:upload|save)[^\n]*(?:completed|succeeded|successful|saved))/i.test(message),
};
fridg3DebugLogs[target].push(entry);
const trimmed = fridg3DebugLogs[target].length > FRIDG3_DEBUG_LOG_LIMIT;
if (trimmed) fridg3DebugLogs[target].splice(0, fridg3DebugLogs[target].length - FRIDG3_DEBUG_LOG_LIMIT);
fridg3ScheduleDebugHistoryPersist();
const output = target === 'server'
? document.querySelector('.debug-console-server-output')
: document.querySelector('.debug-console-client-output');
if (output) fridg3RenderDebugOutput(output, fridg3DebugLogs[target]);
}
function fridg3RenderDebugOutput(output, entries) {
const channel = output.classList.contains('debug-console-server-output') ? 'server' : 'client';
fridg3RunAfterOutputSelection(output, () => {
const visibleEntries = entries.filter(entry =>
fridg3DebugEntryVisible(entry) && fridg3DebugSearchMatches(channel, entry.message)
);
fridg3SetVirtualDebugOutput(output, visibleEntries, fridg3CreateDebugLogLine);
});
}
function fridg3SetVirtualDebugOutput(output, items, createRow) {
let state = fridg3VirtualDebugOutputs.get(output);
const wasAtBottom = !state || output.scrollHeight - output.scrollTop - output.clientHeight < 20;
if (!state) {
state = { items: [], createRow, rowHeight: 18, frame: 0 };
fridg3VirtualDebugOutputs.set(output, state);
output.addEventListener('scroll', () => {
if (state.frame) return;
state.frame = window.requestAnimationFrame(() => {
state.frame = 0;
fridg3RunAfterOutputSelection(output, () => fridg3RenderVirtualDebugOutput(output, false));
});
}, { passive: true });
}
state.items = items;
state.createRow = createRow;
fridg3RenderVirtualDebugOutput(output, wasAtBottom);
}
function fridg3RenderVirtualDebugOutput(output, forceBottom) {
const state = fridg3VirtualDebugOutputs.get(output);
if (!state) return;
const count = state.items.length;
const rowHeight = Math.max(1, state.rowHeight || 18);
const overscan = 12;
const viewportRows = Math.max(1, Math.ceil((output.clientHeight || 300) / rowHeight));
const start = forceBottom
? Math.max(0, count - viewportRows - overscan)
: Math.max(0, Math.floor(output.scrollTop / rowHeight) - overscan);
const end = forceBottom
? count
: Math.min(count, start + viewportRows + overscan * 2);
const fragment = document.createDocumentFragment();
const topSpacer = document.createElement('span');
topSpacer.className = 'debug-log-virtual-spacer';
topSpacer.style.height = `${start * rowHeight}px`;
topSpacer.setAttribute('aria-hidden', 'true');
fragment.append(topSpacer);
for (let index = start; index < end; index += 1) fragment.append(state.createRow(state.items[index]));
const bottomSpacer = document.createElement('span');
bottomSpacer.className = 'debug-log-virtual-spacer';
bottomSpacer.style.height = `${Math.max(0, count - end) * rowHeight}px`;
bottomSpacer.setAttribute('aria-hidden', 'true');
fragment.append(bottomSpacer);
output.replaceChildren(fragment);
const renderedRows = output.querySelectorAll('.debug-log-entry');
if (renderedRows.length) {
const renderedHeight = Array.from(renderedRows).reduce((height, row) => height + row.getBoundingClientRect().height, 0);
const measured = renderedHeight / renderedRows.length;
if (Number.isFinite(measured) && measured > 0) state.rowHeight = state.rowHeight * 0.7 + measured * 0.3;
}
if (forceBottom) output.scrollTop = output.scrollHeight;
}
function fridg3DebugEntryVisible(entry) {
if (entry.processLog) {
const toggle = document.getElementById('debug-process-logs-toggle');
if (toggle && !toggle.checked) return false;
}
if (entry.category === 'settings') {
const toggle = document.getElementById('debug-settings-logs-toggle');
if (toggle && !toggle.checked) return false;
}
if (entry.category === 'network') {
const toggle = document.getElementById('debug-network-logs-toggle');
if (toggle && !toggle.checked) return false;
}
if (entry.category === 'loaded') {
const toggle = document.getElementById('debug-loaded-logs-toggle');
if (toggle && !toggle.checked) return false;
}
const channel = entry.channel === 'server' || entry.processLog ? 'server' : 'client';
if (entry.isError) {
const toggle = document.getElementById(`debug-${channel}-errors-toggle`);
if (toggle && !toggle.checked) return false;
} else if (entry.isWarning) {
const toggle = document.getElementById(`debug-${channel}-warnings-toggle`);
if (toggle && !toggle.checked) return false;
}
return true;
}
function fridg3CreateDebugLogLine(entry) {
const line = document.createElement('span');
line.className = 'debug-log-entry';
const timestamp = document.createElement('span');
timestamp.className = 'debug-log-timestamp';
timestamp.textContent = `[${entry.timestamp}]`;
fridg3SetDebugTimestampTooltip(timestamp, entry.createdAt);
line.append(timestamp, document.createTextNode(' '));
if (entry.processLog) {
const processTag = document.createElement('span');
processTag.className = 'debug-log-source';
processTag.textContent = '[PROCESS]';
line.append(processTag, document.createTextNode(' '));
}
const sourceMatch = entry.message.match(/^(\[[^\]]+\])(?:\s+|$)(.*)$/s);
const message = document.createElement('span');
message.className = 'debug-log-message';
if (entry.isError) message.classList.add('is-error');
else if (entry.isWarning) message.classList.add('is-warning');
else if (entry.isSuccess) message.classList.add('is-success');
if (sourceMatch) {
const source = document.createElement('span');
source.className = 'debug-log-source';
source.textContent = sourceMatch[1];
line.append(source, document.createTextNode(' '));
message.textContent = sourceMatch[2];
} else {
message.textContent = entry.message;
}
line.append(message);
fridg3HighlightDebugLine(line, entry.channel === 'server' || entry.processLog ? 'server' : 'client');
return line;
}
function fridg3SetDebugTimestampTooltip(element, value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return;
element.setAttribute('data-tooltip', date.toLocaleString(undefined, {
dateStyle: 'full',
timeStyle: 'long',
}));
element.dataset.debugFullTimestamp = element.getAttribute('data-tooltip');
if (typeof bindSiteTooltip === 'function') bindSiteTooltip(element);
}
function fridg3HighlightDebugLine(line, channel) {
const input = document.querySelector(`[data-debug-search="${channel}"]`);
const query = input ? input.value.trim() : '';
if (!query) return;
const lowerQuery = query.toLocaleLowerCase();
const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
nodes.forEach(node => {
const text = node.nodeValue || '';
const lowerText = text.toLocaleLowerCase();
let cursor = 0;
let match = lowerText.indexOf(lowerQuery);
if (match === -1) return;
const fragment = document.createDocumentFragment();
while (match !== -1) {
fragment.append(document.createTextNode(text.slice(cursor, match)));
const mark = document.createElement('mark');
mark.className = 'debug-log-highlight';
mark.textContent = text.slice(match, match + query.length);
fragment.append(mark);
cursor = match + query.length;
match = lowerText.indexOf(lowerQuery, cursor);
}
fragment.append(document.createTextNode(text.slice(cursor)));
node.replaceWith(fragment);
});
}
function fridg3DebugSearchMatches(channel, text) {
const input = document.querySelector(`[data-debug-search="${channel}"]`);
const query = input ? input.value.trim().toLocaleLowerCase() : '';
return !query || String(text || '').toLocaleLowerCase().includes(query);
}
function fridg3EnsureDebugConsole() {
let panel = document.getElementById('debug-console');
if (panel) return panel;
panel = document.createElement('aside');
panel.id = 'debug-console';
panel.hidden = true;
panel.setAttribute('aria-label', 'debug console');
panel.innerHTML = '<div class="debug-console-resize-handle" role="separator" tabindex="0" aria-label="resize debug console" aria-orientation="vertical"></div>'
+ '<div class="debug-console-inner"><div class="debug-console-tabs" role="tablist">'
+ '<button type="button" class="is-active" data-debug-tab="client" role="tab">client</button>'
+ '<button type="button" class="is-disabled" data-admin-debug-tab data-debug-tab="server" role="tab" aria-disabled="true" '
+ 'data-tooltip="These logs are unavailable to non-admins due to security concerns.">server</button>'
+ '<button type="button" class="is-disabled" data-admin-debug-tab data-debug-tab="access" role="tab" aria-disabled="true" hidden>access</button></div>'
+ '<div class="debug-console-client-panel is-active" data-debug-output="client" role="tabpanel">'
+ '<div class="checkbox-group debug-client-log-options"><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-settings-logs-toggle" checked>'
+ '<span>settings</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-network-logs-toggle" checked>'
+ '<span>network</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-client-warnings-toggle" checked>'
+ '<span>warnings</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-client-errors-toggle" checked>'
+ '<span>errors</span></label>'
+ '<button type="button" class="debug-log-clear-button" data-debug-clear="client" aria-label="clear client log" data-tooltip="clear client log">'
+ '<i class="fa-solid fa-trash" aria-hidden="true"></i></button></div>'
+ '<div class="debug-log-search"><input type="search" data-debug-search="client" aria-label="search client log" placeholder="search client log"></div>'
+ '<pre class="debug-console-output debug-console-client-output"></pre></div>'
+ '<div class="debug-console-server-panel" data-debug-output="server" role="tabpanel">'
+ '<div class="checkbox-group debug-server-log-options" hidden><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-loaded-logs-toggle" checked>'
+ '<span>loaded</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-process-logs-toggle">'
+ '<span>process</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-server-warnings-toggle">'
+ '<span>warnings</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-server-errors-toggle">'
+ '<span>errors</span></label>'
+ '<button type="button" class="debug-log-clear-button" data-debug-clear="server" aria-label="clear server log" data-tooltip="clear server log">'
+ '<i class="fa-solid fa-trash" aria-hidden="true"></i></button></div>'
+ '<div class="debug-log-search debug-admin-log-search" hidden><input type="search" data-debug-search="server" aria-label="search server log" placeholder="search server log"></div>'
+ '<span class="debug-process-log-status" hidden></span>'
+ '<pre class="debug-console-output debug-console-server-output"></pre></div>'
+ '<div class="debug-console-access-panel" data-debug-output="access" role="tabpanel">'
+ '<div class="checkbox-group debug-access-log-options" hidden><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-access-guests-toggle" checked><span>guests</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-access-users-toggle" checked><span>users</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-access-admins-toggle" checked><span>admins</span></label><label class="checkbox-label">'
+ '<input class="checkbox" type="checkbox" id="debug-access-hard-banned-toggle" checked><span>hard-banned</span></label>'
+ '<button type="button" class="debug-log-clear-button" data-debug-clear="access" aria-label="clear access log" data-tooltip="clear access log">'
+ '<i class="fa-solid fa-trash" aria-hidden="true"></i></button></div>'
+ '<div class="debug-log-search debug-admin-log-search" hidden><input type="search" data-debug-search="access" aria-label="search access log" placeholder="search access log"></div>'
+ '<pre class="debug-console-output debug-console-access-output"></pre></div></div>';
panel.addEventListener('click', event => {
const timestamp = event.target.closest('.debug-log-timestamp[data-debug-full-timestamp]');
if (timestamp && isMobileTemplateActive()) {
showSitePopup({ title: 'timestamp', detail: timestamp.dataset.debugFullTimestamp, okText: 'ok' });
return;
}
const button = event.target.closest('[data-debug-tab]');
if (!button) return;
if (button.getAttribute('aria-disabled') === 'true') return;
fridg3SelectDebugTab(panel, button.dataset.debugTab, true);
});
document.body.append(panel);
fridg3InitDebugConsoleResize(panel);
if (typeof initTooltips === 'function') initTooltips();
fridg3InitClientLogControls(panel);
fridg3InitAccessLogControls(panel);
fridg3InitDebugSearch(panel);
fridg3InitDebugClearControls(panel);
Object.keys(fridg3DebugLogs).forEach(channel => {
const output = channel === 'server'
? panel.querySelector('.debug-console-server-output')
: panel.querySelector('.debug-console-client-output');
if (output) fridg3RenderDebugOutput(output, fridg3DebugLogs[channel]);
});
fridg3InitProcessLogControl(panel);
return panel;
}
function fridg3InitAccessLogControls(panel) {
[
['#debug-access-guests-toggle', 'debugIncludeAccessGuests'],
['#debug-access-users-toggle', 'debugIncludeAccessUsers'],
['#debug-access-admins-toggle', 'debugIncludeAccessAdmins'],
['#debug-access-hard-banned-toggle', 'debugIncludeAccessHardBanned'],
].forEach(([selector, storageKey]) => {
const toggle = panel.querySelector(selector);
if (!toggle) return;
try { toggle.checked = localStorage.getItem(storageKey) !== 'false'; } catch (_) { /* ignore */ }
toggle.addEventListener('change', () => {
try { localStorage.setItem(storageKey, toggle.checked ? 'true' : 'false'); } catch (_) { /* ignore */ }
fridg3RenderAccessLogs(fridg3AccessLogs);
});
});
const output = panel.querySelector('.debug-console-access-output');
if (output) {
output.addEventListener('click', event => {
const ipElement = event.target.closest('.debug-access-ip[data-access-ip]');
if (!ipElement || !isMobileTemplateActive()) return;
event.preventDefault();
fridg3OpenMobileAccessIpMenu(ipElement);
});
output.addEventListener('contextmenu', event => {
const ipElement = event.target.closest('.debug-access-ip[data-access-ip]');
if (!ipElement) return;
event.preventDefault();
fridg3OpenAccessIpMenu(ipElement, event.clientX, event.clientY);
});
}
}
function fridg3OpenAccessIpMenu(ipElement, clientX, clientY) {
document.querySelectorAll('.debug-access-context-menu').forEach(menu => menu.remove());
const ip = ipElement.dataset.accessIp || '';
const hardBanned = ipElement.classList.contains('is-hard-banned');
const action = hardBanned ? 'whitelist' : 'hard-ban';
const menu = document.createElement('div');
menu.className = 'debug-access-context-menu';
menu.setAttribute('role', 'menu');
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('role', 'menuitem');
button.innerHTML = hardBanned
? '<i class="fa-solid fa-check" aria-hidden="true"></i><span>whitelist IP</span>'
: '<i class="fa-solid fa-ban" aria-hidden="true"></i><span>hard-ban IP</span>';
menu.append(button);
document.body.append(menu);
const bounds = menu.getBoundingClientRect();
menu.style.left = `${Math.max(8, Math.min(clientX, window.innerWidth - bounds.width - 8))}px`;
menu.style.top = `${Math.max(8, Math.min(clientY, window.innerHeight - bounds.height - 8))}px`;
const close = () => {
menu.remove();
document.removeEventListener('pointerdown', closeOnOutsideClick);
document.removeEventListener('keydown', closeOnEscape);
};
const closeOnOutsideClick = event => {
if (!menu.contains(event.target)) close();
};
const closeOnEscape = event => {
if (event.key === 'Escape') close();
};
document.addEventListener('pointerdown', closeOnOutsideClick);
document.addEventListener('keydown', closeOnEscape);
button.addEventListener('click', async () => {
close();
const confirmed = await showSitePopup({
title: hardBanned ? `whitelist ${ip}?` : `hard-ban ${ip}?`,
detail: hardBanned
? 'this IP will bypass manual hard bans, source banlists, and identity-based hard bans.'
: 'this IP will be added to the custom hard-ban list.',
okText: hardBanned ? 'whitelist IP' : 'hard-ban IP',
cancelText: 'cancel',
});
if (!confirmed) return;
try {
const params = new URLSearchParams({ ip });
const response = await fetch('/api/debug-access-logs/', {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-Fridg3-Debug-Action': action,
},
body: params.toString(),
});
const data = await response.json();
if (!response.ok || !data.ok) throw new Error(data.error || 'hard-ban update failed');
fridg3AccessLogs.forEach(entry => {
if (entry.ip === ip) entry.hardBanned = data.hardBanned === true;
});
fridg3RenderAccessLogs(fridg3AccessLogs);
} catch (_) {
await showSiteNotice('unable to update hard bans', `the hard-ban state for ${ip} could not be saved.`);
}
});
button.focus();
}
async function fridg3OpenMobileAccessIpMenu(ipElement) {
const ip = ipElement.dataset.accessIp || 'unknown';
const hardBanned = ipElement.classList.contains('is-hard-banned');
const selected = await showSitePopup({
title: ip,
detail: 'choose an IP action.',
customText: 'details',
customAction: () => {
window.open(ipElement.href, '_blank', 'noopener,noreferrer');
},
okText: hardBanned ? 'whitelist IP' : 'hard-ban IP',
cancelText: 'cancel',
});
if (selected !== true) return;
const action = hardBanned ? 'whitelist' : 'hard-ban';
const confirmed = await showSitePopup({
title: hardBanned ? `whitelist ${ip}?` : `hard-ban ${ip}?`,
detail: hardBanned
? 'this IP will be allowed past manual hard bans, source banlists, and identity-based hard bans.'
: 'this IP will be added to the custom hard-ban list.',
okText: hardBanned ? 'whitelist IP' : 'hard-ban IP',
cancelText: 'cancel',
});
if (!confirmed) return;
try {
const params = new URLSearchParams({ ip });
const response = await fetch('/api/debug-access-logs/', {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-Fridg3-Debug-Action': action,
},
body: params.toString(),
});
const data = await response.json();
if (!response.ok || !data.ok) throw new Error(data.error || 'hard-ban update failed');
fridg3AccessLogs.forEach(entry => {
if (entry.ip === ip) entry.hardBanned = data.hardBanned === true;
});
fridg3RenderAccessLogs(fridg3AccessLogs);
} catch (_) {
await showSiteNotice('unable to update hard bans', `the hard-ban state for ${ip} could not be saved.`);
}
}
function fridg3InitDebugSearch(panel) {
panel.querySelectorAll('[data-debug-search]').forEach(input => {
const channel = input.dataset.debugSearch;
try { input.value = sessionStorage.getItem(`fridg3DebugSearch:${channel}`) || ''; } catch (_) { /* ignore */ }
input.addEventListener('input', () => {
try { sessionStorage.setItem(`fridg3DebugSearch:${channel}`, input.value); } catch (_) { /* ignore */ }
if (channel === 'access') {
fridg3RenderAccessLogs(fridg3AccessLogs);
return;
}
const output = panel.querySelector(`.debug-console-${channel}-output`);
if (output) fridg3RenderDebugOutput(output, fridg3DebugLogs[channel]);
});
});
}
function fridg3InitDebugClearControls(panel) {
panel.querySelectorAll('[data-debug-clear]').forEach(button => {
button.addEventListener('click', async () => {
const channel = button.dataset.debugClear;
const confirmed = await showSitePopup({
title: `clear ${channel} log?`,
detail: `this will remove all entries from the ${channel} log.`,
okText: 'clear log',
cancelText: 'cancel',
});
if (!confirmed) return;
if (channel === 'access') {
button.disabled = true;
try {
const response = await fetch('/api/debug-access-logs/', {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-Fridg3-Debug-Action': 'clear',
},
});
const data = await response.json();
if (!response.ok || !data.ok) throw new Error(data.error || 'clear failed');
fridg3AccessLogs = [];
fridg3RenderAccessLogs([]);
} catch (_) {
await showSiteNotice('unable to clear access log', 'the access log could not be cleared.');
} finally {
button.disabled = false;
}
return;
}
fridg3DebugLogs[channel].length = 0;
if (channel === 'client') {
fridg3DebugHistoryRestored = true;
try { sessionStorage.removeItem('fridg3DebugClientHistory'); } catch (_) { /* ignore */ }
} else {
fridg3ServerHistoryRestored = true;
try { sessionStorage.removeItem('fridg3DebugServerHistory'); } catch (_) { /* ignore */ }
}
const output = panel.querySelector(`.debug-console-${channel}-output`);
if (output) fridg3RenderDebugOutput(output, fridg3DebugLogs[channel]);
fridg3ScheduleDebugHistoryPersist();
});
});
}
function fridg3InitDebugConsoleResize(panel) {
const handle = panel.querySelector('.debug-console-resize-handle');
if (!handle || handle.dataset.bound === '1') return;
handle.dataset.bound = '1';
try {
const savedWidth = Number(localStorage.getItem('fridg3DebugConsoleWidth'));
if (savedWidth >= 260 && savedWidth <= window.innerWidth * 0.9) panel.style.width = `${savedWidth}px`;
} catch (_) { /* ignore */ }
handle.addEventListener('pointerdown', event => {
if (event.button !== 0) return;
event.preventDefault();
const startX = event.clientX;
const startWidth = panel.getBoundingClientRect().width;
handle.setPointerCapture(event.pointerId);
const move = moveEvent => {
const width = Math.max(260, Math.min(window.innerWidth * 0.9, startWidth + startX - moveEvent.clientX));
panel.style.width = `${Math.round(width)}px`;
};
const stop = stopEvent => {
handle.removeEventListener('pointermove', move);
handle.removeEventListener('pointerup', stop);
handle.removeEventListener('pointercancel', stop);
try { localStorage.setItem('fridg3DebugConsoleWidth', String(Math.round(panel.getBoundingClientRect().width))); } catch (_) { /* ignore */ }
if (handle.hasPointerCapture(stopEvent.pointerId)) handle.releasePointerCapture(stopEvent.pointerId);
};
handle.addEventListener('pointermove', move);
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
});
handle.addEventListener('keydown', event => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
const direction = event.key === 'ArrowLeft' ? 1 : -1;
const width = Math.max(260, Math.min(window.innerWidth * 0.9, panel.getBoundingClientRect().width + direction * 20));
panel.style.width = `${Math.round(width)}px`;
try { localStorage.setItem('fridg3DebugConsoleWidth', String(Math.round(width))); } catch (_) { /* ignore */ }
});
}
function fridg3SelectDebugTab(panel, channel, persist = false) {
const button = panel.querySelector(`[data-debug-tab="${channel}"]`);
if (!button || button.getAttribute('aria-disabled') === 'true') return false;
panel.querySelectorAll('[data-debug-tab]').forEach(tab => tab.classList.toggle('is-active', tab === button));
panel.querySelectorAll('[data-debug-output]').forEach(output => output.classList.toggle('is-active', output.dataset.debugOutput === channel));
if (persist) {
try { sessionStorage.setItem('fridg3DebugSelectedTab', channel); } catch (_) { /* ignore */ }
}
if (channel === 'access' && fridg3ServerDebugAuthorized) fridg3StartAccessLogPolling();
else fridg3StopAccessLogPolling();
if (isMobileTemplateActive() && document.body.classList.contains('mobile-debug-console-open')) {
fridg3PositionMobileDebugToggle(panel, true);
window.requestAnimationFrame(() => fridg3ScrollActiveDebugOutputToBottom(panel));
}
return true;
}
function fridg3InitClientLogControls(panel) {
const controls = [
['#debug-settings-logs-toggle', 'debugIncludeSettingsLogs'],
['#debug-network-logs-toggle', 'debugIncludeNetworkLogs'],
['#debug-client-warnings-toggle', 'debugIncludeClientWarnings'],
['#debug-client-errors-toggle', 'debugIncludeClientErrors'],
];
controls.forEach(([selector, storageKey]) => {
const toggle = panel.querySelector(selector);
if (!toggle) return;
try { toggle.checked = localStorage.getItem(storageKey) !== 'false'; } catch (_) { /* ignore */ }
toggle.addEventListener('change', () => {
try { localStorage.setItem(storageKey, toggle.checked ? 'true' : 'false'); } catch (_) { /* ignore */ }
const output = panel.querySelector('.debug-console-client-output');
if (output) fridg3RenderDebugOutput(output, fridg3DebugLogs.client);
});
});
}
function fridg3SetDebugMode(enabled) {
const mobile = document.body.classList.contains('mobile-template');
const shouldEnable = enabled === true;
fridg3DebugEnabled = shouldEnable;
const mobileToggle = fridg3InitMobileDebugToggle();
if (!shouldEnable) {
fridg3DeactivateDebugRuntime();
const existingPanel = document.getElementById('debug-console');
if (existingPanel && mobileToggle) fridg3PositionMobileDebugToggle(existingPanel, false);
if (existingPanel) existingPanel.hidden = true;
if (mobileToggle) {
mobileToggle.hidden = true;
mobileToggle.setAttribute('aria-expanded', 'false');
}
document.body.classList.remove('mobile-debug-console-open');
return;
}
fridg3ActivateDebugRuntime();
const panel = fridg3EnsureDebugConsole();
if (mobile && mobileToggle) fridg3PositionMobileDebugToggle(panel, false);
panel.hidden = mobile;
if (mobileToggle) {
mobileToggle.hidden = false;
mobileToggle.setAttribute('aria-expanded', 'false');
}
}
function fridg3InitMobileDebugToggle() {
const button = document.getElementById('show-debug-console');
if (!button) return null;
if (button.dataset.bound !== '1') {
button.dataset.bound = '1';
button.addEventListener('click', () => {
if (!fridg3DebugEnabled) return;
const panel = fridg3EnsureDebugConsole();
const opening = panel.hidden;
fridg3PositionMobileDebugToggle(panel, opening);
panel.hidden = !opening;
button.setAttribute('aria-expanded', opening ? 'true' : 'false');
button.setAttribute('aria-label', opening ? 'hide debug console' : 'show debug console');
button.setAttribute('data-tooltip', opening ? 'hide debug console' : 'show debug console');
document.body.classList.toggle('mobile-debug-console-open', opening);
if (opening) window.requestAnimationFrame(() => fridg3ScrollActiveDebugOutputToBottom(panel));
});
}
return button;
}
function fridg3PositionMobileDebugToggle(panel, insideConsole) {
const button = document.getElementById('show-debug-console');
if (!button || !isMobileTemplateActive()) return;
if (insideConsole) {
const search = panel.querySelector('[data-debug-output].is-active .debug-log-search');
if (search) search.append(button);
button.classList.add('is-in-debug-console');
} else {
document.body.append(button);
button.classList.remove('is-in-debug-console');
}
}
function fridg3ScrollActiveDebugOutputToBottom(panel) {
const output = panel.querySelector('[data-debug-output].is-active .debug-console-output');
if (!output) return;