-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlogsieve.js
More file actions
3003 lines (2627 loc) · 96.6 KB
/
Copy pathlogsieve.js
File metadata and controls
3003 lines (2627 loc) · 96.6 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
/**
* LogSieve - Log File Analysis Tool
* JavaScript functionality for filtering, parsing, and visualizing log data
*/
// ---------- Utilities ----------
// (Moved to shared.js)
// ---------- Log Parsing Helpers ----------
// (Moved to shared.js)
/**
* Parse various time string formats and return ISO (UTC) string or empty string.
* For naive timestamps (no timezone) this treats them as local timestamps.
* @param {string} s
* @returns {string}
*/
// `parseTimestampToISO` is provided by `shared.js` and loaded before this file.
// Format an ISO or raw timestamp string to user's localized datetime with tz
// `formatLocalDatetime` is provided by `shared.js`.
/**
* Remove timestamp prefix from log line
* @param {string} line - Log line text
* @returns {string} - Line without timestamp prefix
*/
// `stripPrefix` (remove timestamp prefix) is provided by `shared.js`.
/**
* Check if a line starts a new exception event (even without timestamp)
* These patterns indicate standalone exception entries
* @param {string} line - Log line text
* @returns {boolean} - True if line starts a new exception
*/
// `isExceptionStart` is provided by `shared.js`.
/**
* Check if a line is a continuation line (part of a multi-line event)
* Continuation lines are typically:
* - Stack trace lines (starting with whitespace + "at", "File", etc.)
* - Exception lines (starting with common exception types)
* - Lines that don't have a timestamp and start with whitespace
* @param {string} line - Log line text
* @returns {boolean} - True if line is a continuation line
*/
// `isContinuationLine` is provided by `shared.js`.
/**
* Tokenize string for search purposes
* @param {string} s - String to tokenize
* @returns {Array<string>} - Array of tokens
*/
// `tokenize` is provided by `shared.js`.
// ---------- Storage Manager ----------
// `generateUUID` is provided by `shared.js`.
/**
* Storage manager for localStorage operations
*/
const Storage = {
KEYS: {
EXTRACTORS: 'logsieve-extractors',
FILTERS: 'logsieve-filters',
ACTIVE_EXTRACTORS: 'logsieve-active-extractors',
TRANSFORMS: 'logsieve-transforms',
ACTIVE_TRANSFORMS: 'logsieve-active-transforms',
PREFS: 'logsieve-prefs',
THEME: 'logsieve-theme'
},
/**
* Get all saved extractors
* @returns {Array<Object>} - Array of extractor objects
*/
getExtractors() {
try {
const data = localStorage.getItem(this.KEYS.EXTRACTORS);
return data ? JSON.parse(data) : [];
} catch (e) {
console.error('Failed to load extractors:', e);
return [];
}
},
/**
* Save an extractor (create or update)
* @param {Object} extractor - Extractor object
* @returns {Object} - Saved extractor with id
*/
saveExtractor(extractor) {
const extractors = this.getExtractors();
if (!extractor.id) {
extractor.id = generateUUID();
extractor.created = new Date().toISOString();
}
extractor.updated = new Date().toISOString();
const idx = extractors.findIndex(e => e.id === extractor.id);
if (idx >= 0) {
extractors[idx] = extractor;
} else {
extractors.push(extractor);
}
localStorage.setItem(this.KEYS.EXTRACTORS, JSON.stringify(extractors));
return extractor;
},
/**
* Delete an extractor by id
* @param {string} id - Extractor id
*/
deleteExtractor(id) {
const extractors = this.getExtractors().filter(e => e.id !== id);
localStorage.setItem(this.KEYS.EXTRACTORS, JSON.stringify(extractors));
// Remove from active list if present
const active = this.getActiveExtractors().filter(aid => aid !== id);
this.setActiveExtractors(active);
},
/**
* Get active extractor IDs
* @returns {Array<string>} - Array of active extractor IDs
*/
getActiveExtractors() {
try {
const data = localStorage.getItem(this.KEYS.ACTIVE_EXTRACTORS);
return data ? JSON.parse(data) : [];
} catch (e) {
console.error('Failed to load active extractors:', e);
return [];
}
},
/**
* Set active extractor IDs
* @param {Array<string>} ids - Array of extractor IDs
*/
setActiveExtractors(ids) {
// Deduplicate and clean up IDs
const uniqueIds = [...new Set(ids)];
const validExtractors = this.getExtractors();
const validIds = uniqueIds.filter(id => validExtractors.some(e => e.id === id));
localStorage.setItem(this.KEYS.ACTIVE_EXTRACTORS, JSON.stringify(validIds));
},
getTransforms() {
try {
const data = localStorage.getItem(this.KEYS.TRANSFORMS);
return data ? JSON.parse(data) : [];
} catch (e) {
console.error('Failed to load transforms:', e);
return [];
}
},
saveTransform(transform) {
const transforms = this.getTransforms();
if (!transform.id) {
transform.id = generateUUID();
transform.created = new Date().toISOString();
}
transform.updated = new Date().toISOString();
const idx = transforms.findIndex(t => t.id === transform.id);
if (idx >= 0) transforms[idx] = transform;
else transforms.push(transform);
localStorage.setItem(this.KEYS.TRANSFORMS, JSON.stringify(transforms));
return transform;
},
deleteTransform(id) {
const transforms = this.getTransforms().filter(t => t.id !== id);
localStorage.setItem(this.KEYS.TRANSFORMS, JSON.stringify(transforms));
const active = this.getActiveTransforms().filter(tid => tid !== id);
this.setActiveTransforms(active);
},
getActiveTransforms() {
try {
const data = localStorage.getItem(this.KEYS.ACTIVE_TRANSFORMS);
return data ? JSON.parse(data) : [];
} catch (e) {
console.error('Failed to load active transforms:', e);
return [];
}
},
setActiveTransforms(ids) {
const uniqueIds = [...new Set(ids)];
const validTransforms = this.getTransforms();
const validIds = uniqueIds.filter(id => validTransforms.some(t => t.id === id));
localStorage.setItem(this.KEYS.ACTIVE_TRANSFORMS, JSON.stringify(validIds));
},
/**
* Get all saved filters
* @returns {Array<Object>} - Array of filter objects
*/
getFilters() {
try {
const data = localStorage.getItem(this.KEYS.FILTERS);
return data ? JSON.parse(data) : [];
} catch (e) {
console.error('Failed to load filters:', e);
return [];
}
},
/**
* Save a filter (create or update)
* @param {Object} filter - Filter object
* @returns {Object} - Saved filter with id
*/
saveFilter(filter) {
const filters = this.getFilters();
if (!filter.id) {
filter.id = generateUUID();
filter.created = new Date().toISOString();
}
filter.updated = new Date().toISOString();
const idx = filters.findIndex(f => f.id === filter.id);
if (idx >= 0) {
filters[idx] = filter;
} else {
filters.push(filter);
}
localStorage.setItem(this.KEYS.FILTERS, JSON.stringify(filters));
return filter;
},
/**
* Delete a filter by id
* @param {string} id - Filter id
*/
deleteFilter(id) {
const filters = this.getFilters().filter(f => f.id !== id);
localStorage.setItem(this.KEYS.FILTERS, JSON.stringify(filters));
},
/**
* Get user preferences
* @returns {Object} - Preferences object
*/
getPrefs() {
try {
const data = localStorage.getItem(this.KEYS.PREFS);
return data ? JSON.parse(data) : {
defaultPageSize: 50,
extractorMergeStrategy: 'last-wins',
unsafeJsTransforms: false
};
} catch (e) {
console.error('Failed to load preferences:', e);
return { defaultPageSize: 50, extractorMergeStrategy: 'last-wins', unsafeJsTransforms: false };
}
},
/**
* Save user preferences
* @param {Object} prefs - Preferences object
*/
savePrefs(prefs) {
localStorage.setItem(this.KEYS.PREFS, JSON.stringify(prefs));
},
/**
* Export all data
* @returns {Object} - All stored data
*/
exportAll() {
return {
extractors: this.getExtractors(),
filters: this.getFilters(),
transforms: this.getTransforms(),
activeExtractors: this.getActiveExtractors(),
activeTransforms: this.getActiveTransforms(),
prefs: this.getPrefs(),
exportDate: new Date().toISOString(),
version: '1.0'
};
},
/**
* Import data with merge option
* @param {Object} data - Data to import
* @param {boolean} merge - Whether to merge with existing data
* @returns {Object} - Import results
*/
importAll(data, merge = true) {
const results = { extractors: 0, filters: 0, transforms: 0, errors: [] };
try {
if (data.extractors) {
const existing = merge ? this.getExtractors() : [];
const imported = data.extractors.map(e => {
// Generate new ID if merging to avoid conflicts
if (merge) e.id = generateUUID();
return e;
});
localStorage.setItem(this.KEYS.EXTRACTORS, JSON.stringify([...existing, ...imported]));
results.extractors = imported.length;
}
if (data.filters) {
const existing = merge ? this.getFilters() : [];
const imported = data.filters.map(f => {
if (merge) f.id = generateUUID();
return f;
});
localStorage.setItem(this.KEYS.FILTERS, JSON.stringify([...existing, ...imported]));
results.filters = imported.length;
}
if (data.transforms) {
const existing = merge ? this.getTransforms() : [];
const imported = data.transforms.map(t => {
if (merge) t.id = generateUUID();
return t;
});
localStorage.setItem(this.KEYS.TRANSFORMS, JSON.stringify([...existing, ...imported]));
results.transforms = imported.length;
}
if (data.activeTransforms && !merge) {
localStorage.setItem(this.KEYS.ACTIVE_TRANSFORMS, JSON.stringify(data.activeTransforms));
}
if (data.prefs && !merge) {
this.savePrefs(data.prefs);
}
} catch (e) {
results.errors.push(e.message);
}
return results;
}
};
// ---------- Data Model ----------
let rows = []; // Full dataset
let view = []; // Filtered/sorted view
let page = 1; // Current page number
let per = 50; // Items per page
let totalRows = 0; // Total rows in filtered view
let fieldNames = new Set(); // Track all extracted field names
let visibleColumns = new Set(); // Columns the user wants to show; empty => show all
let columnOrder = []; // ordered list of columns (strings)
let currentFilterConfig = null;
let builderOpen = true; // make builder primary and visible by default
// applied* states capture what was last applied with the Apply button
let appliedFilterConfig = null;
let appliedAdvancedQuery = null;
// Detected user's timezone name (IANA). Set at startup for consistent rendering
const userTimeZone = (Intl && Intl.DateTimeFormat && Intl.DateTimeFormat().resolvedOptions().timeZone) || 'Local';
let sortByIdOrder = 'asc';
let editingTransformId = null;
let pipelineOrder = [];
// ---------- Worker Communication ----------
let worker = null;
let pendingRequests = new Map(); // Track pending worker requests
/**
* Initialize the WebWorker
*/
function initWorker() {
if (worker) return; // Already initialized
worker = new Worker('logsieve-worker.js');
worker.onmessage = handleWorkerMessage;
worker.onerror = handleWorkerError;
}
/**
* Handle messages from the worker
*/
function handleWorkerMessage(e) {
const { type, data, id } = e.data;
// Resolve pending request if this is a response to a specific request
if (id && pendingRequests.has(id)) {
if (type !== 'PROGRESS') {
const resolve = pendingRequests.get(id);
pendingRequests.delete(id);
resolve({ type, data });
return;
}
}
// Handle unsolicited messages
switch (type) {
case 'PARSE_COMPLETE':
// rows = data.rows || []; // Worker no longer sends full rows for performance
fieldNames = new Set(data.fieldNames || []);
if (data.fieldRegistry) {
FieldRegistry.deserialize(data.fieldRegistry);
}
// Ensure visible columns and column order reflect new dataset
initializeVisibleColumnsFromPrefs();
initializeColumnOrderFromPrefs();
renderColumnsPanel();
$("#info").textContent = `Parsed ${fmt(data.rowCount)} entries`;
$("#uploadProgress").style.display = 'none';
// After parsing completes and results are displayed, collapse the Upload section and open Results
const uploadSection = document.getElementById('section-upload');
if (uploadSection) uploadSection.classList.remove('active');
// Set Results nav active for clarity
navigateToSection('results');
renderPipelineList();
renderTransformErrorAlert(null);
applyFilters();
break;
case 'FILTER_COMPLETE':
view = data.view || [];
page = 1; // Reset to first page
totalRows = data.viewLength || 0; // Store total rows for pagination
$("#filterProgress").style.display = 'none';
$("#savedFilterProgress").style.display = 'none';
render();
break;
case 'PIPELINE_COMPLETE':
fieldNames = new Set(data.fieldNames || []);
if (data.fieldRegistry) FieldRegistry.deserialize(data.fieldRegistry);
initializeVisibleColumnsFromPrefs();
initializeColumnOrderFromPrefs();
mergeNewFieldsIntoOrder();
renderColumnsPanel();
page = 1;
totalRows = data.viewLength || 0;
$("#filterProgress").style.display = 'none';
const pipelineProgress = $("#pipelineProgress");
if (pipelineProgress) pipelineProgress.style.display = 'none';
$("#savedFilterProgress").style.display = 'none';
updateSortOptions();
renderQueryFields();
renderPipelineList();
renderTransformErrorAlert(data.transformResults || null);
render();
break;
case 'EXTRACTORS_COMPLETE':
fieldNames = new Set(data.newFieldNames || []);
if (data.fieldRegistry) {
FieldRegistry.deserialize(data.fieldRegistry);
}
// Update columns panel and merge new fields into saved order
initializeVisibleColumnsFromPrefs();
initializeColumnOrderFromPrefs();
mergeNewFieldsIntoOrder();
renderColumnsPanel();
const extractHits = data.results?.total || 0;
const transformChanged = data.transformResults?.changed || 0;
$("#extractInfo").textContent = `Extractors: ${fmt(extractHits)} matches · Transforms: ${fmt(transformChanged)} changed`;
$("#extractorProgress").style.display = 'none';
updateSortOptions();
renderQueryFields();
renderPipelineList();
renderTransformErrorAlert(data.transformResults || null);
applyFilters();
break;
case 'PAGE_DATA':
// Handle paginated data for rendering
renderPage(data);
break;
case 'STATS_DATA':
renderStatsFromWorker(data);
break;
case 'FULL_VIEW_DATA':
// This is handled by the pending request resolver
break;
case 'PARSE_QUERY_RESULT':
// This is handled by the pending request resolver
break;
case 'SUMMARY_STATS_COMPLETE':
$("#summary-progress").style.display = 'none';
renderSummaryStats(data);
break;
case 'PROGRESS':
const { percent, message, operation } = data;
if (operation === 'parsing') {
const container = $("#uploadProgress");
const fill = $("#uploadProgressFill");
const text = $("#uploadProgressText");
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
} else if (operation === 'extracting') {
const container = $("#extractorProgress");
const fill = $("#extractorProgressFill");
const text = $("#extractorProgressText");
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
} else if (operation === 'filtering') {
const container = $("#filterProgress");
const fill = $("#filterProgressFill");
const text = $("#filterProgressText");
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
} else if (operation === 'pipeline') {
const container = $("#pipelineProgress");
const fill = $("#pipelineProgressFill");
const text = $("#pipelineProgressText");
if (container && fill && text) {
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
}
} else if (operation === 'saved-filtering') {
const container = $("#savedFilterProgress");
const fill = $("#savedFilterProgressFill");
const text = $("#savedFilterProgressText");
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
} else if (operation === 'summary') {
const container = $("#summary-progress");
const fill = $("#summary-progress-fill");
const text = $("#summary-progress-text");
container.style.display = 'block';
fill.style.width = percent + '%';
text.textContent = message;
}
break;
case 'ERROR':
console.error('Worker error:', data.message);
alert('Processing error: ' + data.message);
break;
default:
console.warn('Unknown worker message type:', type);
}
}
function renderTransformErrorAlert(transformResults) {
const el = $("#transformErrorAlert");
if (!el) return;
const failed = transformResults?.failed || 0;
if (!failed) {
el.style.display = 'none';
el.innerHTML = '';
return;
}
const samples = Array.isArray(transformResults.errorSamples) ? transformResults.errorSamples.slice(0, 5) : [];
const sampleHtml = samples.length
? `<ul>${samples.map(s => `<li>${escapeHtml(s.transformName || s.transformId || 'Transform')}${s.rowId ? ` (row ${escapeHtml(String(s.rowId))})` : ''}: ${escapeHtml(s.error || 'Unknown error')}</li>`).join('')}</ul>`
: '';
el.innerHTML = `<div class="title">Transform errors detected</div>
<div>${fmt(failed)} transformation failure(s) occurred during the last run.</div>
${sampleHtml}`;
el.style.display = 'block';
}
/**
* Handle worker errors
*/
function handleWorkerError(error) {
console.error('Worker error:', error);
alert('Worker error: ' + error.message);
}
/**
* Send a message to the worker and optionally wait for response
*/
function sendToWorker(type, data, waitForResponse = false) {
if (!worker) {
throw new Error('Worker not initialized');
}
// Ensure data is serializable by deep cloning
const serializableData = (() => {
try {
const str = JSON.stringify(data);
return str === undefined ? null : JSON.parse(str);
} catch (e) {
console.error('Data not serializable, using null', data, e);
return null;
}
})();
const message = { type, data: serializableData };
if (waitForResponse) {
const id = generateUUID();
message.id = id;
return new Promise((resolve) => {
pendingRequests.set(id, resolve);
worker.postMessage(message);
});
} else {
worker.postMessage(message);
}
}
// ---------- Field Registry & Operators ----------
// (Moved to shared.js)
/**
* Migrate v1 filter to v2 format
*/
function migrateFilter(oldFilter) {
if (!oldFilter) return oldFilter;
if (oldFilter.version === 2) return oldFilter;
const rules = [];
if (oldFilter.level) {
rules.push({ id: generateUUID(), field: 'level', operator: 'equals', value: oldFilter.level, logic: 'AND', enabled: true });
}
if (oldFilter.from) rules.push({ id: generateUUID(), field: 'ts', operator: 'after', value: oldFilter.from, logic: 'AND', enabled: true });
if (oldFilter.to) rules.push({ id: generateUUID(), field: 'ts', operator: 'before', value: oldFilter.to, logic: 'AND', enabled: true });
if (rules.length > 0) rules[rules.length - 1].logic = null;
return { ...oldFilter, version: 2, quickSearch: oldFilter.query || '', rules, sort: { field: oldFilter.sort || 'id', order: oldFilter.order || 'desc' }, _legacy: { query: oldFilter.query, regex: oldFilter.regex } };
}
function migrateAllFilters() {
const filters = Storage.getFilters();
let migrated = 0;
filters.forEach(filter => { if (!filter.version || filter.version !== 2) { const v2 = migrateFilter(filter); Storage.saveFilter(v2); migrated++; } });
if (migrated > 0) console.log(`Migrated ${migrated} filters to v2 format`);
}
function getPipelineOrderFromPrefs() {
const prefs = Storage.getPrefs() || {};
pipelineOrder = Array.isArray(prefs.pipelineOrder) ? prefs.pipelineOrder.slice() : [];
return pipelineOrder;
}
function savePipelineOrderToPrefs() {
const prefs = Storage.getPrefs() || {};
prefs.pipelineOrder = pipelineOrder.slice();
Storage.savePrefs(prefs);
}
function buildPipelineSteps() {
const steps = [];
const prefs = Storage.getPrefs() || {};
const rules = currentFilterConfig?.rules || [];
for (const rule of rules) {
const label = `Filter: ${rule.field} ${rule.operator}${rule.value ? ' ' + rule.value : ''}`;
steps.push({
key: `filter-rule:${rule.id}`,
type: 'filter-rule',
label,
enabled: rule.enabled !== false,
rule
});
}
const advancedQuery = $("#textQuery")?.value.trim();
if (advancedQuery) {
steps.push({
key: 'filter-advanced',
type: 'advanced-query',
label: `Filter: Advanced Query`,
enabled: true,
queryText: advancedQuery
});
}
const activeExtractorIds = Storage.getActiveExtractors();
const extractorMap = new Map(Storage.getExtractors().map(e => [e.id, e]));
for (const id of activeExtractorIds) {
const ext = extractorMap.get(id);
if (!ext) continue;
steps.push({
key: `extractor:${id}`,
type: 'extractor',
label: `Extractor: ${ext.name}`,
enabled: ext.enabled !== false,
mergeStrategy: prefs.extractorMergeStrategy || 'last-wins',
extractor: ext
});
}
const activeTransformIds = Storage.getActiveTransforms();
const transformMap = new Map(Storage.getTransforms().map(t => [t.id, t]));
for (const id of activeTransformIds) {
const t = transformMap.get(id);
if (!t) continue;
steps.push({
key: `transform:${id}`,
type: 'transform',
label: `Transform: ${t.name || t.operation}`,
enabled: t.enabled !== false,
transform: t
});
}
const order = getPipelineOrderFromPrefs();
const byKey = new Map(steps.map(s => [s.key, s]));
const ordered = [];
for (const key of order) {
const step = byKey.get(key);
if (step) {
ordered.push(step);
byKey.delete(key);
}
}
for (const step of byKey.values()) ordered.push(step);
pipelineOrder = ordered.map(s => s.key);
savePipelineOrderToPrefs();
return ordered;
}
function renderPipelineList() {
const list = $("#pipelineList");
if (!list) return;
const steps = buildPipelineSteps();
if (steps.length === 0) {
list.innerHTML = '<div class="empty-state">No pipeline steps yet. Add filter rules, extractors, or transformations.</div>';
return;
}
list.innerHTML = steps.map(step => {
const kind = step.type === 'filter-rule' || step.type === 'advanced-query' ? 'Filter' : (step.type === 'extractor' ? 'Extractor' : 'Transform');
return `
<div class="library-item" data-step-key="${step.key}" draggable="true">
<input type="checkbox" class="pipeline-toggle" data-step-key="${step.key}" ${step.enabled ? 'checked' : ''} />
<div class="library-item-content">
<div class="library-item-title">${escapeHtml(kind)}</div>
<div class="library-item-pattern">${escapeHtml(step.label)}</div>
</div>
<div class="library-item-actions"><span class="drag-handle" style="cursor:grab; color:var(--muted)">≡</span></div>
</div>
`;
}).join('');
list.querySelectorAll('.pipeline-toggle').forEach(cb => {
cb.addEventListener('change', (e) => {
const key = e.target.dataset.stepKey;
const checked = e.target.checked;
if (key.startsWith('filter-rule:')) {
const id = key.split(':')[1];
const rule = (currentFilterConfig?.rules || []).find(r => r.id === id);
if (rule) rule.enabled = checked;
} else if (key.startsWith('extractor:')) {
const id = key.split(':')[1];
const active = Storage.getActiveExtractors();
if (checked && !active.includes(id)) active.push(id);
if (!checked) Storage.setActiveExtractors(active.filter(x => x !== id));
else Storage.setActiveExtractors(active);
renderExtractorList();
} else if (key.startsWith('transform:')) {
const id = key.split(':')[1];
const active = Storage.getActiveTransforms();
if (checked && !active.includes(id)) active.push(id);
if (!checked) Storage.setActiveTransforms(active.filter(x => x !== id));
else Storage.setActiveTransforms(active);
renderTransformationList();
}
updateExtractorInfo();
renderPipelineList();
});
});
let dragSrcEl = null;
list.addEventListener('dragstart', (e) => {
const el = e.target.closest('.library-item');
if (!el) return;
dragSrcEl = el;
el.classList.add('dragging');
});
list.addEventListener('dragover', (e) => {
e.preventDefault();
const afterEl = getDragAfterElement(list, e.clientY);
if (!dragSrcEl) return;
if (!afterEl) list.appendChild(dragSrcEl);
else list.insertBefore(dragSrcEl, afterEl);
});
list.addEventListener('dragend', () => {
if (dragSrcEl) dragSrcEl.classList.remove('dragging');
pipelineOrder = [...list.querySelectorAll('.library-item')].map(n => n.dataset.stepKey);
savePipelineOrderToPrefs();
dragSrcEl = null;
});
function getDragAfterElement(container, y) {
const els = [...container.querySelectorAll('.library-item:not(.dragging)')];
let closest = { offset: Number.NEGATIVE_INFINITY, element: null };
for (const child of els) {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) closest = { offset, element: child };
}
return closest.element;
}
}
function runPipeline(operation = 'pipeline') {
const sortConfig = {
field: $("#sort").value,
order: $("#order").value
};
const prefs = Storage.getPrefs();
const steps = buildPipelineSteps();
const progress = $("#pipelineProgress");
const progressFill = $("#pipelineProgressFill");
const progressText = $("#pipelineProgressText");
if (progress && progressFill && progressText) {
progress.style.display = 'block';
progressFill.style.width = '0%';
progressText.textContent = 'Running pipeline...';
}
sendToWorker('RUN_PIPELINE', {
operation,
steps,
sort: sortConfig,
transformRuntime: {
unsafeMode: !!prefs.unsafeJsTransforms,
maxTotalMs: 2500,
maxOutputLength: 100000
}
});
}
/**
* Apply all active filters to the dataset
*/
function applyFilters(operation = 'filtering') {
runPipeline(operation);
}
/**
* Get current page of results based on pagination settings
* @param {Array} list - List to paginate
* @returns {Array} - Current page items
*/
function paginate(list) {
per = +$("#per").value;
const start = (page - 1) * per;
return list.slice(start, start + per);
}
/**
* Render the current view to the UI
*/
function render() {
// Request current page data from worker
sendToWorker('GET_PAGE', { page, per });
}
/**
* Render a specific page of data
*/
function renderPage(pageData) {
const t0 = performance.now();
const body = $("#tbody");
const theadRow = $("#thead-row");
body.innerHTML = "";
// Update table headers with dynamic field columns using user-defined columnOrder
const order = getCurrentColumnOrder();
const displayedCols = order.filter(c => isColumnVisible(c));
// Build header cells matching displayed columns
const headerHtml = displayedCols.map(col => {
if (col === 'id') {
const arrow = sortByIdOrder === 'asc' ? '▲' : '▼';
return `<th style="width:72px; cursor:pointer" class="id-header">ID ${arrow}</th>`;
}
if (col === 'ts') return `<th style="width:210px">Timestamp <br/>(<span id="tzLabel">${escapeHtml(userTimeZone)}</span>)</th>`;
if (col === 'level') return `<th style="width:120px">Level</th>`;
if (col === 'message') return `<th style="max-width:80ch">Message</th>`;
return `<th style="width:150px">${escapeHtml(col)}</th>`;
}).join('');
theadRow.innerHTML = headerHtml;
// Attach click handler to ID header
const idHeader = theadRow.querySelector('.id-header');
if (idHeader) {
idHeader.addEventListener('click', () => {
sortByIdOrder = sortByIdOrder === 'asc' ? 'desc' : 'asc';
$("#sort").value = 'id';
$("#order").value = sortByIdOrder;
applyFilters();
});
}
const pageRows = pageData.pageRows;
const frag = document.createDocumentFragment();
for (const r of pageRows) {
const tr = document.createElement('tr');
// Build cells in same order as headers
const cellsHtml = displayedCols.map(col => {
if (col === 'id') return `<td>${r.id}</td>`;
else if (col === 'ts') return `<td>${formatLocalDatetime(r.ts) || ''}</td>`;
else if (col === 'level') return `<td><span class="lvl-${r.level}">${r.level || ''}</span></td>`;
else if (col === 'message') return `<td><pre>${escapeHtml(r.message)}</pre><details><summary>raw</summary><pre>${escapeHtml(r.raw)}</pre></details></td>`;
const val = r.fields?.[col];
if (val === undefined || val === null) return '<td></td>';
if (Array.isArray(val)) {
if (val.length === 1) return `<td>${escapeHtml(val[0])}</td>`;
return `<td><code>${escapeHtml(JSON.stringify(val))}</code></td>`;
}
return `<td>${escapeHtml(String(val))}</td>`;
}).join('');
tr.innerHTML = cellsHtml;
frag.appendChild(tr);
}
body.appendChild(frag);
// Update UI elements
$("#pageLabel").textContent = `${pageData.currentPage} / ${pageData.totalPages}`;
$("#renderInfo").textContent = `${fmt(pageData.totalRows)} rows · showing ${fmt(pageRows.length)} · ${Math.round(performance.now() - t0)}ms`;
$("#countTag").textContent = `${fmt(pageData.totalRows)} lines`;
// Store total rows for pagination calculations
totalRows = pageData.totalRows;
// Request stats separately
sendToWorker('GET_STATS');
}
/**
* Update the filter status tag
*/
function updateFilterTag() {
const bits = [];
if (currentFilterConfig && currentFilterConfig.rules && currentFilterConfig.rules.length) bits.push('builder');
const hasAdvanced = !!(
appliedAdvancedQuery &&
(
(appliedAdvancedQuery.version === 3 && appliedAdvancedQuery.ast) ||
(Array.isArray(appliedAdvancedQuery.rules) && appliedAdvancedQuery.rules.length)
)
);
if (hasAdvanced) bits.push('advanced');
$("#filterTag").textContent = bits.length ? `filters: ${bits.join(',')}` : 'no filters';
}
/**
* Render statistics and sparkline chart
*/
function renderStats() {
// Stats are now requested separately and handled in renderStatsFromWorker
}
/**
* Render statistics from worker data
*/
function renderStatsFromWorker(stats) {
$("#sRows").textContent = fmt(stats.totalRows);
$("#sInfo").textContent = fmt(stats.infoCount);
$("#sWarn").textContent = fmt(stats.warnCount);
$("#sErr").textContent = fmt(stats.errorCount);
// Create time-bucket sparkline (per minute)
drawSpark($("#spark"), stats.timeBuckets);
}
/**
* Draw sparkline chart on canvas
* @param {HTMLCanvasElement} canvas - Canvas element
* @param {Array<number>} arr - Data points to plot
*/
function drawSpark(canvas, arr) {
const ctx = canvas.getContext('2d');
const w = canvas.width = canvas.clientWidth * devicePixelRatio;
const h = canvas.height = canvas.clientHeight * devicePixelRatio;
ctx.clearRect(0, 0, w, h);
if (!arr.length) return;