-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
1207 lines (1047 loc) · 42.9 KB
/
script.js
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
let showDetailedView = true;
let allEntries = [];
let displayedEntries = [];
let selectedKeys = {};
let globalSelectedKeys = {};
let selectedEntryIds = new Set();
let fuse;
let allDataForSearch = [];
let exportType = 'standard'; // Can be 'standard' or 'grouped'
let startX, startWidth, resizableTh;
// Call the initialization function when the page loads
document.addEventListener('DOMContentLoaded', function () {
initializeColumnVisibility();
});
// Initialize column visibility
function initializeColumnVisibility() {
const toggles = document.querySelectorAll('.column-toggle');
toggles.forEach(toggle => {
const column = toggle.dataset.column;
const isVisible = toggle.checked;
const headerCell = document.querySelector(`th[data-column="${column}"]`);
if (headerCell) {
headerCell.style.display = isVisible ? '' : 'none';
}
const cells = document.querySelectorAll(`td[data-column="${column}"]`);
cells.forEach(cell => {
cell.style.display = isVisible ? '' : 'none';
});
});
}
function updateColumnVisibility() {
const toggles = document.querySelectorAll('.column-toggle');
toggles.forEach(toggle => {
const column = toggle.dataset.column;
const isVisible = toggle.checked;
const headerCell = document.querySelector(`th[data-column="${column}"]`);
if (headerCell) {
headerCell.style.display = isVisible ? '' : 'none';
}
const cells = document.querySelectorAll(`td[data-column="${column}"]`);
cells.forEach(cell => {
cell.style.display = isVisible ? '' : 'none';
});
});
}
function updateExpandedRows() {
const expandedRows = document.querySelectorAll('.entry-row.expanded');
expandedRows.forEach(expRow => {
const entryId = expRow.dataset.entryId;
const entry = allEntries.find(e => e.__id === entryId);
if (entry) {
// Remove the current expanded row
const nextRow = expRow.nextSibling;
if (nextRow && nextRow.classList.contains('expanded-row')) {
nextRow.parentNode.removeChild(nextRow);
}
// Re-expand the row with the updated view
toggleRowExpansion(expRow, entry, true);
}
});
}
function prepareDataForSearch(entries) {
allDataForSearch = entries.map((entry) => {
return {
id: entry.__id,
entry: entry,
// Index specific fields for better performance
searchContent: getSearchableContent(entry)
};
});
const options = {
keys: ['searchContent'],
threshold: 0.3,
ignoreLocation: true,
minMatchCharLength: 2
};
fuse = new Fuse(allDataForSearch, options);
}
function displayEntries(entries) {
const tbody = document.getElementById('entriesBody');
tbody.innerHTML = ''; // Clear previous entries
entries.forEach((entry) => {
const row = document.createElement('tr');
row.classList.add('entry-row');
row.dataset.entryId = entry.__id; // Add this line
const selectCell = document.createElement('td');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'select-checkbox';
checkbox.dataset.id = entry.__id;
checkbox.checked = selectedEntryIds.has(entry.__id);
selectCell.appendChild(checkbox);
selectCell.dataset.column = 'select';
row.appendChild(selectCell);
// Started DateTime
const startedDateTime = document.createElement('td');
startedDateTime.textContent = entry.startedDateTime || '';
startedDateTime.dataset.column = 'startedDateTime';
row.appendChild(startedDateTime);
// Method
const method = document.createElement('td');
method.textContent = entry.request ? entry.request.method : '';
method.dataset.column = 'method';
row.appendChild(method);
// URL without query string
const url = document.createElement('td');
let urlText = entry.request ? entry.request.url : '';
let urlWithoutQuery = urlText;
try {
const parsedUrl = new URL(urlText);
urlWithoutQuery = parsedUrl.origin + parsedUrl.pathname;
} catch (e) {
// If parsing fails, fallback to original URL
urlWithoutQuery = urlText;
}
url.textContent = urlWithoutQuery;
url.title = urlText; // Show full URL on hover
url.dataset.column = 'url';
row.appendChild(url);
// Query String
const queryString = document.createElement('td');
queryString.textContent = getQueryString(entry.request ? entry.request.queryString : []);
queryString.title = queryString.textContent;
queryString.dataset.column = 'queryString';
row.appendChild(queryString);
// Status
const status = document.createElement('td');
status.textContent = entry.response ? entry.response.status : '';
status.dataset.column = 'status';
row.appendChild(status);
// Status Text
const statusText = document.createElement('td');
statusText.textContent = entry.response ? entry.response.statusText : '';
statusText.dataset.column = 'statusText';
row.appendChild(statusText);
// Time
const time = document.createElement('td');
time.textContent = entry.time || '';
time.dataset.column = 'time';
row.appendChild(time);
// Avoid triggering the row click when clicking on the checkbox
checkbox.addEventListener('click', function (event) {
event.stopPropagation();
if (checkbox.checked) {
selectedEntryIds.add(entry.__id);
} else {
selectedEntryIds.delete(entry.__id);
}
});
row.addEventListener('click', function () {
toggleRowExpansion(row, entry);
});
tbody.appendChild(row);
});
updateColumnVisibility();
makeColumnsResizable(); // Initialize resizers after rendering entries
}
function getQueryString(queryArray) {
return queryArray.map(q => `${q.name}=${q.value}`).join('&');
}
function getSearchableContent(entry) {
const content = [];
// Include relevant fields for searching
if (entry.request) {
content.push(entry.request.method);
content.push(entry.request.url);
if (entry.request.headers) {
entry.request.headers.forEach(header => {
content.push(header.name + ': ' + header.value);
});
}
if (entry.request.queryString) {
entry.request.queryString.forEach(param => {
content.push(param.name + '=' + param.value);
});
}
if (entry.request.postData && entry.request.postData.text) {
content.push(entry.request.postData.text);
}
}
if (entry.response) {
content.push(entry.response.status + ' ' + entry.response.statusText);
if (entry.response.headers) {
entry.response.headers.forEach(header => {
content.push(header.name + ': ' + header.value);
});
}
if (entry.response.content && entry.response.content.text) {
let responseBody = entry.response.content.text;
// Decode if necessary
if (entry.response.content.encoding === 'base64') {
try {
responseBody = atob(responseBody);
} catch (e) {
console.error('Failed to decode base64 response content:', e);
}
}
content.push(responseBody);
}
}
// Include any other properties you find relevant
if (entry._initiator && entry._initiator.url) {
content.push(entry._initiator.url);
}
// Flatten the content array into a single string
return content.join(' ');
}
function toggleRowExpansion(row, entry, isUpdating = false) {
const isExpanded = row.classList.contains('expanded');
if (isExpanded && !isUpdating) {
// Collapse the row
const nextRow = row.nextSibling;
if (nextRow && nextRow.classList.contains('expanded-row')) {
nextRow.parentNode.removeChild(nextRow);
}
row.classList.remove('expanded'); // Remove the class
} else {
// Collapse other expanded rows if not updating
if (!isUpdating) {
const expandedRows = document.querySelectorAll('.entry-row.expanded');
expandedRows.forEach(expRow => {
expRow.classList.remove('expanded');
const nextRow = expRow.nextSibling;
if (nextRow && nextRow.classList.contains('expanded-row')) {
nextRow.parentNode.removeChild(nextRow);
}
});
// Reset selectedKeys for the new entry
selectedKeys = {};
}
// Remove existing expanded row if any
const nextRow = row.nextSibling;
if (nextRow && nextRow.classList.contains('expanded-row')) {
nextRow.parentNode.removeChild(nextRow);
}
// Expand the current row
const expandedRow = document.createElement('tr');
expandedRow.classList.add('expanded-row');
const expandedCell = document.createElement('td');
expandedCell.colSpan = row.children.length;
const expandedContent = document.createElement('div');
expandedContent.classList.add('expanded-content');
// Build JSON tree
const jsonTreeContainer = document.createElement('div');
jsonTreeContainer.classList.add('json-tree');
const seen = new Set();
const dataRoot = entry; // Set dataRoot for use in buildJsonTree
buildJsonTree(jsonTreeContainer, entry, [], seen, dataRoot);
// Add buttons
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('button-container');
const applySelectionButton = document.createElement('button');
applySelectionButton.textContent = 'Apply Selection to All Entries';
applySelectionButton.addEventListener('click', function (event) {
event.stopPropagation();
globalSelectedKeys = JSON.parse(JSON.stringify(selectedKeys));
alert('Selection applied to all entries.');
});
buttonContainer.appendChild(applySelectionButton);
const downloadButton = document.createElement('button');
downloadButton.textContent = 'Download This Entry';
downloadButton.addEventListener('click', function (event) {
event.stopPropagation();
const selectedData = getSelectedData(entry, selectedKeys, [], new Set(), entry);
if (selectedData === undefined) {
alert('No data selected for this entry.');
return;
}
downloadJSON(selectedData, 'entry.json');
});
buttonContainer.appendChild(downloadButton);
expandedContent.appendChild(buttonContainer);
expandedContent.appendChild(jsonTreeContainer);
expandedCell.appendChild(expandedContent);
expandedRow.appendChild(expandedCell);
row.parentNode.insertBefore(expandedRow, row.nextSibling);
row.classList.add('expanded');
}
}
function buildJsonTree(container, data, path, seen, dataRoot) {
// Ensure path, seen, and dataRoot are provided
if (!path) path = [];
if (!seen) seen = new Set();
if (!dataRoot) dataRoot = data;
if (typeof data === 'object' && data !== null) {
if (seen.has(data)) {
// Circular reference detected
const circularRef = document.createElement('span');
circularRef.textContent = ' (circular reference)';
container.appendChild(circularRef);
return;
}
seen.add(data);
}
const ul = document.createElement('ul');
if (!showDetailedView) {
// Show only response.content.text
// When accessing response.content
const responseContent = getValueAtPath(dataRoot, ['response', 'content']);
if (responseContent && typeof responseContent.text !== 'undefined' && responseContent.text !== null) {
let responseContentText = responseContent.text;
const fullPath = ['response', 'content', 'text'];
let value = responseContentText;
let isObject = typeof value === 'object' && value !== null;
// Additional logging for debugging
console.log(`Processing response.content.text for entry ID: ${dataRoot.__id}`);
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.dataset.path = JSON.stringify(fullPath);
checkbox.checked = getSelectedKey(fullPath);
checkbox.addEventListener('change', function (event) {
event.stopPropagation();
setSelectedKey(fullPath, checkbox.checked);
if (checkbox.checked && isObject) {
selectAllChildNodes(value, fullPath);
}
});
const li = document.createElement('li');
li.appendChild(checkbox);
const keySpan = document.createElement('span');
keySpan.textContent = 'response.content.text';
li.appendChild(keySpan);
// Handle parsing and displaying the text content
let parsedValue;
let parsingSucceeded = false;
// Check if the content is JSON
let textContent = value;
if (responseContent.encoding === 'base64') {
try {
textContent = atob(value);
} catch (e) {
console.warn('Failed to decode base64 content:', e);
}
}
let mimeType = responseContent.mimeType || 'text/plain';
if (mimeType.includes('json') || mimeType.includes('UTF-8')) {
try {
parsedValue = JSON.parse(textContent);
parsingSucceeded = true;
} catch (e) {
console.warn('Failed to parse JSON from text field:', e);
}
}
if (parsingSucceeded) {
// Display as a nested JSON tree
isObject = true;
value = parsedValue;
const expandToggle = document.createElement('span');
expandToggle.className = 'expand-toggle';
expandToggle.textContent = '';
expandToggle.addEventListener('click', function (event) {
event.stopPropagation();
li.classList.toggle('expanded');
childUl.classList.toggle('hidden');
});
li.insertBefore(expandToggle, keySpan.nextSibling);
const childUl = document.createElement('ul');
childUl.className = 'hidden';
buildJsonTree(childUl, value, fullPath, seen, dataRoot);
li.appendChild(childUl);
} else {
// Display the formatted string
const pre = document.createElement('pre');
pre.textContent = formatJSONString(textContent);
addCopyButtonToPre(pre);
li.appendChild(pre);
}
ul.appendChild(li);
} else {
const li = document.createElement('li');
li.textContent = 'No response content available.';
ul.appendChild(li);
}
} else {
// Detailed view: display the full data
if (Array.isArray(data)) {
data.forEach((item, index) => {
const li = document.createElement('li');
const fullPath = path.concat(index);
const isObject = typeof item === 'object' && item !== null;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.dataset.path = JSON.stringify(fullPath);
checkbox.checked = getSelectedKey(fullPath);
checkbox.addEventListener('change', function (event) {
event.stopPropagation();
setSelectedKey(fullPath, checkbox.checked);
if (checkbox.checked && isObject) {
selectAllChildNodes(item, fullPath);
}
});
li.appendChild(checkbox);
const keySpan = document.createElement('span');
keySpan.textContent = `[${index}]`;
keySpan.classList.add('array-key');
li.appendChild(keySpan);
if (isObject) {
const expandToggle = document.createElement('span');
expandToggle.className = 'expand-toggle';
expandToggle.textContent = '';
expandToggle.addEventListener('click', function (event) {
event.stopPropagation();
li.classList.toggle('expanded');
childUl.classList.toggle('hidden');
});
li.insertBefore(expandToggle, keySpan.nextSibling);
const childUl = document.createElement('ul');
childUl.className = 'hidden';
buildJsonTree(childUl, item, fullPath, seen, dataRoot);
li.appendChild(childUl);
} else {
li.appendChild(document.createTextNode(`: ${item}`));
}
ul.appendChild(li);
});
} else {
for (const key in data) {
if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
const li = document.createElement('li');
const fullPath = path.concat(key);
let value = data[key];
let isObject = typeof value === 'object' && value !== null;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.dataset.path = JSON.stringify(fullPath);
checkbox.checked = getSelectedKey(fullPath);
checkbox.addEventListener('change', function (event) {
event.stopPropagation();
setSelectedKey(fullPath, checkbox.checked);
if (checkbox.checked && isObject) {
selectAllChildNodes(value, fullPath);
}
});
li.appendChild(checkbox);
const keySpan = document.createElement('span');
keySpan.textContent = key;
li.appendChild(keySpan);
// Handle 'text' field parsing as before
if (key === 'text' && typeof value === 'string') {
const parentPath = path.slice(0, -1);
const parentData = getValueAtPath(dataRoot, parentPath);
let textContent = value;
if (parentData && parentData.encoding === 'base64') {
try {
textContent = atob(value);
} catch (e) {
console.warn('Failed to decode base64 content:', e);
}
}
let mimeType = parentData && parentData.mimeType ? parentData.mimeType : 'text/plain';
let parsedValue;
let parsingSucceeded = false;
if (mimeType.includes('json')) {
try {
parsedValue = JSON.parse(textContent);
parsingSucceeded = true;
} catch (e) {
console.warn('Failed to parse JSON from text field:', e);
}
}
if (mimeType.includes('charset=UTF-8')) {
console.log('mimeType.includes(charset=UTF-8)');
try {
parsedValue = decodeURIComponent(value);
console.log('parsedValue', parsedValue);
parsingSucceeded = true;
} catch (e) {
console.warn('Failed to decode content:', value);
}
}
// last try with a custom mimeType unescaping, that is actually utf-8 encoded json but doesn't say it
else {
try {
parsedValue = recursiveUnescape(value);
parsingSucceeded = true;
} catch (e) {
console.warn('Failed to decode content:', value);
}
}
if (parsingSucceeded) {
// Display as a nested JSON tree
isObject = true;
value = parsedValue;
const expandToggle = document.createElement('span');
expandToggle.className = 'expand-toggle';
expandToggle.textContent = '';
expandToggle.addEventListener('click', function (event) {
event.stopPropagation();
li.classList.toggle('expanded');
childUl.classList.toggle('hidden');
});
li.insertBefore(expandToggle, keySpan.nextSibling);
const childUl = document.createElement('ul');
childUl.className = 'hidden';
buildJsonTree(childUl, value, fullPath, seen, dataRoot);
li.appendChild(childUl);
} else {
// Display the formatted string
const pre = document.createElement('pre');
pre.textContent = formatJSONString(textContent);
addCopyButtonToPre(pre);
li.appendChild(pre);
}
} else if (isObject) {
const expandToggle = document.createElement('span');
expandToggle.className = 'expand-toggle';
expandToggle.textContent = '';
expandToggle.addEventListener('click', function (event) {
event.stopPropagation();
li.classList.toggle('expanded');
childUl.classList.toggle('hidden');
});
li.insertBefore(expandToggle, keySpan.nextSibling);
const childUl = document.createElement('ul');
childUl.className = 'hidden';
buildJsonTree(childUl, value, fullPath, seen, dataRoot);
li.appendChild(childUl);
} else {
li.appendChild(document.createTextNode(`: ${value}`));
}
ul.appendChild(li);
}
}
}
container.appendChild(ul);
}
function addCopyButtonToPre(preElement) {
// Check if the element is a <pre>
if (!(preElement instanceof HTMLElement) || preElement.tagName.toLowerCase() !== 'pre') {
console.error('addCopyButtonToPre: Provided element is not a <pre> element.');
return;
}
// Avoid adding multiple buttons to the same <pre>
if (preElement.querySelector('.copy-button')) {
console.warn('addCopyButtonToPre: <pre> element already has a copy button.');
return;
}
// Create the button element
const button = document.createElement('button');
button.className = 'copy-button';
button.textContent = 'Copy';
// Define the copy action
button.addEventListener('click', async () => {
// Disable the button to prevent multiple clicks
button.disabled = true;
try {
// Clone the <pre> element to exclude the button's text
const clone = preElement.cloneNode(true);
const buttonInClone = clone.querySelector('.copy-button');
if (buttonInClone) {
buttonInClone.remove(); // Remove the button from the clone
}
// Get the text content from the cloned <pre>
const textToCopy = clone.textContent.trim();
// Use the Clipboard API if available
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(textToCopy);
} else {
// Fallback method for older browsers
const textarea = document.createElement('textarea');
textarea.value = textToCopy;
// Prevent scrolling to bottom
textarea.style.position = 'fixed';
textarea.style.top = '0';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const successful = document.execCommand('copy');
if (!successful) throw new Error('Failed to copy text');
document.body.removeChild(textarea);
}
// Provide feedback to the user
button.textContent = 'Copied!';
button.classList.add('copied');
// Revert the button text after 2 seconds
setTimeout(() => {
button.textContent = 'Copy';
button.classList.remove('copied');
button.disabled = false;
}, 2000);
} catch (err) {
console.error('Error copying text: ', err);
alert('Failed to copy text. Please try again.');
button.disabled = false;
}
});
// Append the button to the <pre> element
preElement.appendChild(button);
}
function formatJSONString(jsonString) {
try {
const jsonObj = JSON.parse(jsonString);
return JSON.stringify(jsonObj, null, 2);
} catch (e) {
// If parsing fails, return the original string
return jsonString;
}
}
function unescapeNestedJson(s) {
try {
return JSON.parse(s);
} catch (error) {
return s.replace(/\\"/g, '"');
}
}
function recursiveUnescape(obj) {
if (typeof obj === 'string') {
// Throw an error for a specific test case
if (obj.includes('TEST_FAIL_CONDITION')) {
throw new Error('Test failure condition met');
}
return unescapeNestedJson(obj);
} else if (Array.isArray(obj)) {
return obj.map(recursiveUnescape);
} else if (typeof obj === 'object' && obj !== null) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, recursiveUnescape(v)])
);
} else {
return obj;
}
}
function convertUTF8ToJSON(value) {
try {
// First, try to decode the string using UTF-8
const decodedString = new TextDecoder('utf-8').decode(new Uint8Array(value.split('').map(c => c.charCodeAt(0))));
// If successful, parse it as JSON
return JSON.parse(decodedString);
} catch (e) {
console.warn('Failed to decode or parse content:', e.message);
// If decoding or parsing fails, return the original value
return value;
}
}
function selectAllChildNodes(data, path) {
const stack = [{ data, path }];
let localSeen = new Set();
while (stack.length > 0) {
const { data: currentData, path: currentPath } = stack.pop();
if (typeof currentData !== 'object' || currentData === null) continue;
if (localSeen.has(currentData)) continue;
localSeen.add(currentData);
if (Array.isArray(currentData)) {
currentData.forEach((item, index) => {
const fullPath = currentPath.concat(index);
setSelectedKey(fullPath, true);
if (typeof item === 'object' && item !== null) {
stack.push({ data: item, path: fullPath });
}
});
} else {
for (const key in currentData) {
if (!Object.prototype.hasOwnProperty.call(currentData, key)) continue;
const fullPath = currentPath.concat(key);
setSelectedKey(fullPath, true);
if (typeof currentData[key] === 'object' && currentData[key] !== null) {
stack.push({ data: currentData[key], path: fullPath });
}
}
}
}
}
function setSelectedKey(path, isSelected) {
const pathStr = JSON.stringify(path);
if (isSelected) {
selectedKeys[pathStr] = true;
} else {
delete selectedKeys[pathStr];
}
}
function getSelectedKey(path) {
const pathStr = JSON.stringify(path);
return selectedKeys.hasOwnProperty(pathStr);
}
function getSelectedData(data, selectionKeys, path = [], seen = new Set(), dataRoot = data) {
if (typeof data === 'object' && data !== null) {
if (seen.has(data)) {
// Circular reference detected
return undefined;
}
seen.add(data);
}
const pathStr = JSON.stringify(path);
if (selectionKeys[pathStr]) {
// If the current path is selected, return the data at this path
// Check if the current path ends with 'text' and the data is a string
if (path[path.length - 1] === 'text' && typeof data === 'string') {
// Check if the parent object has an 'encoding' field
const parentPath = path.slice(0, -1);
const parentData = getValueAtPath(dataRoot, parentPath);
let textContent = data;
// Check if encoding is 'base64'
if (parentData && parentData.encoding === 'base64') {
try {
textContent = atob(data);
} catch (e) {
console.warn('Failed to decode base64 content:', e);
}
}
// Attempt to parse the JSON string
try {
const parsedData = JSON.parse(textContent);
return parsedData;
} catch (e) {
console.warn('Failed to parse JSON from text field:', e);
return textContent;
}
} else {
return data;
}
}
if (typeof data !== 'object' || data === null) {
return undefined;
}
let hasSelectedChild = false;
let result = Array.isArray(data) ? [] : {};
if (Array.isArray(data)) {
for (let index = 0; index < data.length; index++) {
const childPath = path.concat(index);
const childData = getSelectedData(data[index], selectionKeys, childPath, seen, dataRoot);
if (childData !== undefined) {
result[index] = childData;
hasSelectedChild = true;
}
}
} else {
for (const key in data) {
if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
const childPath = path.concat(key);
const childData = getSelectedData(data[key], selectionKeys, childPath, seen, dataRoot);
if (childData !== undefined) {
result[key] = childData;
hasSelectedChild = true;
}
}
}
if (hasSelectedChild) {
return result;
} else {
return undefined;
}
}
function getValueAtPath(dataRoot, path) {
let value = dataRoot;
for (const key of path) {
if (value && typeof value === 'object') {
value = value[key];
} else {
return undefined;
}
}
return value;
}
function collectGroupedData(data, selectionKeys, groupedData, path = [], seen = new Set(), dataRoot = data) {
if (typeof data === 'object' && data !== null) {
if (seen.has(data)) {
// Circular reference detected
return;
}
seen.add(data);
}
const pathStr = JSON.stringify(path);
if (selectionKeys[pathStr]) {
const key = path.join('.');
let valueToAdd = data;
// Check if the current path ends with 'text' and the data is a string
if (path[path.length - 1] === 'text' && typeof data === 'string') {
// Check if the parent object has an 'encoding' field
const parentPath = path.slice(0, -1);
const parentData = getValueAtPath(dataRoot, parentPath);
let textContent = data;
// Check if encoding is 'base64'
if (parentData && parentData.encoding === 'base64') {
try {
textContent = atob(data);
} catch (e) {
console.warn('Failed to decode base64 content:', e);
}
} else if (parentData && parentData.encoding === 'utf-8') {
try {
textContent = decodeURIComponent(data);
} catch (e) {
console.warn('Failed to decode content:', e);
}
}
// Attempt to parse the JSON string
try {
valueToAdd = JSON.parse(textContent);
} catch (e) {
try {
valueToAdd = recursiveParse(textContent);
} catch (e) {
console.warn('Failed to parse JSON from text field:', e);
valueToAdd = textContent; // Keep data as is (the original string)
}
}
} else {
// Deep copy the data to avoid reference issues
valueToAdd = JSON.parse(JSON.stringify(data));
}
if (!groupedData[key]) {
groupedData[key] = [];
}
groupedData[key].push(valueToAdd);
return; // Do not go deeper once the selected node is found
}
if (typeof data !== 'object' || data === null) {
return;
}
if (Array.isArray(data)) {
for (let index = 0; index < data.length; index++) {
const childPath = path.concat(index);
collectGroupedData(data[index], selectionKeys, groupedData, childPath, seen, dataRoot);
}
} else {
for (const key in data) {
if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
const childPath = path.concat(key);
collectGroupedData(data[key], selectionKeys, groupedData, childPath, seen, dataRoot);
}
}
}
function recursiveParse(input) {
// If input is not a string, return it as is
if (typeof input !== 'string') {
return input;
}
// Remove surrounding quotes if present
if (input.startsWith('"') && input.endsWith('"')) {
input = input.slice(1, -1);
}
// Replace escaped quotes with actual quotes
input = input.replace(/\\"/g, '"');
try {
// Parse the JSON string
const parsed = JSON.parse(input);
// If parsed is an object, recursively parse its properties
if (typeof parsed === 'object' && parsed !== null) {
for (const key in parsed) {
parsed[key] = recursiveParse(parsed[key]);
}
}
return parsed;
} catch (e) {
// If parsing fails, return the unescaped string
return input;
}
}
function downloadJSON(data, filename) {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// Make table columns resizable
function makeColumnsResizable() {
const table = document.getElementById('entriesTable');
const cols = table.querySelectorAll('th');
cols.forEach(function (th) {
const resizer = th.querySelector('.resizer');
if (resizer && !resizer.dataset.initialized) {