-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
2372 lines (2082 loc) · 77.8 KB
/
Copy pathcontent.js
File metadata and controls
2372 lines (2082 loc) · 77.8 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
/**
* BDLawCorpus Content Script
*
* Handles extraction of legal content from bdlaws.minlaw.gov.bd
* Requirements: 7.1, 7.2, 7.3, 9.4, 9.5, 17.1, 17.2, 23.1-23.7, 24.1-24.7, 25.1-25.5, 28.1-28.6
*/
(function() {
'use strict';
// Content script version for compatibility checks
const CONTENT_SCRIPT_VERSION = '5';
// ============================================
// BDLawCorpus Legal Selectors
// Requirement 7.1: Hardcoded selectors only
// Extended selectors based on actual bdlaws.minlaw.gov.bd page structure
// ============================================
const BDLAW_LEGAL_SELECTORS = {
// Title selectors - try multiple patterns
title: [
'h1',
'.bg-act-section h3',
'.boxed-layout h3',
'.boxed-layout h4',
'.text-center h3',
'.act-title',
'.law-title',
'#act-title',
'.card-header h4',
'.card-header h3',
'.card-header h2',
'.page-title',
'h2.title',
'h3.title',
'.content-header h1',
'.content-header h2',
'.act-name',
'.law-name'
],
// Main content selectors - hierarchical fallback order
// Primary selectors (site-specific)
content: [
'#lawContent',
'.law-content',
'.act-details',
'.act-content',
'.law-body',
'.card-body',
'.content-body',
'#act-content',
'.act-text',
'.law-text'
],
// Fallback selectors (generic semantic containers)
// Used when primary selectors fail
contentFallback: [
'.boxed-layout',
'.content-wrapper',
'.main-content',
'article',
'main',
'[role="main"]'
],
// Metadata selectors
meta: [
'.act-meta',
'.law-header',
'.act-header',
'.law-meta',
'.metadata'
],
// Schedule/table selectors
schedule: [
'table',
'.schedule',
'#schedule',
'.tofshil'
],
// DOM-specific selectors for structured extraction
// Requirements: 23.1-23.7 - Act Content DOM Structure
actContainer: '.boxed-layout',
actMetadata: ['.bg-act-section', '.act-role-style'],
sectionRows: '.lineremoves',
sectionTitle: '.col-sm-3.txt-head',
sectionBody: '.col-sm-9.txt-details',
// Preamble and header content selectors (content BEFORE section rows)
// These contain act number, date, repealed notice, purpose, and preamble
actHeaderSection: '.bg-act-section', // Contains act number and date
actRepealedNotice: '.bt-act-repealed', // Contains repealed notice (if any)
actPurpose: '.act-role-style', // Contains act purpose statement
actPreamble: '.lineremove', // Singular - contains preamble (যেহেতু...সেহেতু)
// Body fallback exclusion selectors
// Elements to remove when using body as final fallback
bodyExclusions: [
'nav',
'header',
'footer',
'script',
'style',
'noscript',
'.navbar',
'.sidebar',
'.menu',
'.navigation',
'.footer',
'.header',
'.search',
'.search-box',
'.related-links',
'.breadcrumb',
'.pagination',
'[role="navigation"]',
'[role="banner"]',
'[role="contentinfo"]',
'[role="search"]'
]
};
// ============================================
// DOM-First Structure Extraction Selectors
// Requirements: Legal Structure Derivation - DOM-first approach
// ============================================
const STRUCTURE_SELECTORS = {
// Statutory links (references to other acts)
statutoryLinks: 'a[href*="act-details"]',
// Tables (for schedule detection)
tables: 'table',
// All links for reference extraction
allLinks: 'a[href]'
};
// Section markers for Bengali legal documents
const BDLAW_SECTION_MARKERS = ['ধারা', 'অধ্যায়', 'তফসিল'];
// Amendment markers for detecting deleted/modified provisions
// Requirements: 25.1 - Detect Amendment_Markers in legal text
const BDLAW_AMENDMENT_MARKERS = ['বিলুপ্ত', 'সংশোধিত', 'প্রতিস্থাপিত', '[***]'];
// UI noise patterns to filter from extracted content
// Requirements: 28.1, 28.2, 28.3 - Content Noise Filtering
const BDLAW_UI_NOISE_PATTERNS = [
'প্রিন্ট ভিউ',
/^Top$/gm,
/Copyright © \d{4}/g,
/Legislative and Parliamentary Affairs Division/g
];
// Cross-reference citation patterns for detecting references to other acts
// Requirements: 1.1, 1.2, 1.3, 2.1, 2.2, 2.3 - Citation Pattern Detection
const BDLAW_CITATION_PATTERNS = {
// English patterns - Requirements: 1.1, 1.2, 1.3
ENGLISH_ACT_FULL: /([A-Z][a-zA-Z\s]+(?:Act|Ordinance)),?\s*(\d{4})\s*\(([IVXLCDM]+|\d+)\s+of\s+(\d{4})\)/g,
ENGLISH_ACT_SHORT: /(?:Act|Ordinance)\s+([IVXLCDM]+|\d+)\s+of\s+(\d{4})/g,
// Bengali patterns - Requirements: 2.1, 2.2, 2.3
BENGALI_ACT_FULL: /([^\s,।]+(?:\s+[^\s,।]+)*\s+আইন),?\s*([\u09E6-\u09EF0-9]{4})\s*\(([\u09E6-\u09EF0-9]{4})\s*সনের\s*([\u09E6-\u09EF0-9]+)\s*নং\s*আইন\)/g,
BENGALI_ACT_SHORT: /([\u09E6-\u09EF0-9]{4})\s*সনের\s*([\u09E6-\u09EF0-9]+)\s*নং\s*(আইন|অধ্যাদেশ)/g,
BENGALI_ORDINANCE: /([^\s,।]+(?:\s+[^\s,।]+)*\s+অধ্যাদেশ),?\s*([\u09E6-\u09EF0-9]{4})\s*\(অধ্যাদেশ\s*নং\s*([\u09E6-\u09EF0-9]+),?\s*([\u09E6-\u09EF0-9]{4})\)/g,
// President's Order pattern - Special reference type
PRESIDENTS_ORDER: /P\.?O\.?\s*(?:No\.?)?\s*(\d+)\s+of\s+(\d{4})/gi
};
// Reference type classification keywords
// Requirements: 3.1, 3.2, 3.3, 3.4 - Reference Type Classification
const BDLAW_REFERENCE_TYPE_KEYWORDS = {
amendment: ['সংশোধন', 'সংশোধিত', 'amendment', 'amended', 'amending'],
repeal: ['রহিত', 'রহিতকরণ', 'বিলুপ্ত', 'repeal', 'repealed', 'repealing'],
substitution: ['প্রতিস্থাপিত', 'প্রতিস্থাপন', 'substituted', 'substitution', 'replaced'],
dependency: ['সাপেক্ষে', 'অধীন', 'অনুসারে', 'subject to', 'under', 'pursuant to'],
incorporation: ['সন্নিবেশিত', 'অন্তর্ভুক্ত', 'inserted', 'incorporated', 'added']
};
// ============================================
// LEGAL STATUS AND TEMPORAL MARKING
// Requirements: 6.1-6.3, 7.1-7.4 - Legal Integrity Enhancement
// ============================================
/**
* Patterns for detecting repealed status on source pages
* Requirements: 6.1 - Detect if act is marked as repealed on source page
*/
const BDLAW_LEGAL_STATUS_PATTERNS = {
// Bengali patterns for repealed status
repealed_bengali: [
/রহিত(?:করণ)?/gi, // "repealed" or "repeal"
/বিলুপ্ত/gi, // "abolished"
/বাতিল(?:করণ)?/gi, // "cancelled" or "cancellation"
/রদ(?:করণ)?/gi // "revoked" or "revocation"
],
// English patterns for repealed status
repealed_english: [
/\brepealed\b/gi,
/\babolished\b/gi,
/\brevoked\b/gi,
/\brescinded\b/gi,
/\bno\s+longer\s+in\s+force\b/gi
],
// Status indicator patterns (often in metadata/header sections)
status_indicators: [
/status\s*:\s*repealed/gi,
/status\s*:\s*রহিত/gi,
/\[repealed\]/gi,
/\[রহিত\]/gi,
/\(repealed\)/gi,
/\(রহিত\)/gi
]
};
/**
* Selectors for finding status information on act pages
* Requirements: 6.1 - Detect status from source page structure
*/
const BDLAW_LEGAL_STATUS_SELECTORS = [
'.act-status',
'.law-status',
'.status-badge',
'.act-meta .status',
'.bg-act-section',
'.act-role-style',
'h1',
'.act-title',
'.card-header'
];
/**
* Temporal status constant
* Requirements: 7.1 - All acts are marked as "historical_text"
*/
const BDLAW_TEMPORAL_STATUS = 'historical_text';
/**
* Temporal disclaimer constant
* Requirements: 7.4 - Include temporal disclaimer in exports
*/
const BDLAW_TEMPORAL_DISCLAIMER = 'No inference of current legal force or applicability';
// ============================================
// EXTRACTION RISK DETECTION
// Requirements: 13.1-13.6 - Legal Integrity Enhancement
// ============================================
/**
* Selectors for detecting pagination elements
* Requirements: 13.1 - Detect pagination elements
*/
const BDLAW_PAGINATION_SELECTORS = [
'.pagination',
'.page-nav',
'.pager',
'.page-numbers',
'[data-page]',
'[class*="pagination"]',
'[class*="pager"]',
'nav[aria-label*="page"]',
'.page-link',
'.page-item'
];
/**
* Selectors for detecting lazy-loaded content
* Requirements: 13.2 - Detect lazy-loaded content
*/
const BDLAW_LAZY_LOAD_SELECTORS = [
'[data-src]',
'[loading="lazy"]',
'.lazy-load',
'.lazy',
'[data-lazy]',
'[class*="lazy"]',
'img[data-original]',
'[data-srcset]'
];
/**
* Selectors for detecting external schedule/appendix links
* Requirements: 13.3 - Detect external schedule links
*/
const BDLAW_EXTERNAL_SCHEDULE_SELECTORS = [
'a[href*="schedule"]',
'a[href*="appendix"]',
'a[href*="tofshil"]',
'a[href*="form"]',
'a[href*="annex"]',
'a[href*="attachment"]'
];
/**
* Selectors for detecting hidden DOM elements
* Requirements: 13.4 - Detect hidden DOM elements
*/
const BDLAW_HIDDEN_DOM_SELECTORS = [
'[style*="display:none"]',
'[style*="display: none"]',
'[hidden]',
'.hidden',
'.d-none',
'[aria-hidden="true"]',
'.collapse:not(.show)',
'.tab-pane:not(.active)',
'[style*="visibility:hidden"]',
'[style*="visibility: hidden"]'
];
// ============================================
// Helper Functions
// ============================================
/**
* Normalize a potentially relative bdlaws URL to absolute.
* Preserves protocol from the current page context when possible.
*
* @param {string} href
* @returns {string}
*/
function bdlawNormalizeToAbsoluteUrl(href) {
if (!href || typeof href !== 'string') {
return '';
}
// Already absolute
if (/^https?:\/\//i.test(href)) {
return href;
}
// Protocol-relative URL
if (href.startsWith('//')) {
const protocol = (window.location && (window.location.protocol === 'http:' || window.location.protocol === 'https:'))
? window.location.protocol
: 'http:';
return `${protocol}${href}`;
}
try {
return new URL(href, window.location.origin).href;
} catch (_) {
return href;
}
}
/**
* Detect extraction risks in the current document
* Requirements: 13.1, 13.2, 13.3, 13.4, 13.5, 13.6 - Extraction Risk Detection
*
* Detects potential issues that could cause content truncation or incompleteness:
* - Pagination elements (content may be split across pages)
* - Lazy-loaded content (content may not be fully loaded)
* - External schedule links (schedules may be on separate pages)
* - Hidden DOM elements (content may be hidden and not extracted)
*
* @returns {Object} {possible_truncation: boolean, reason: string, detected_risks: Array}
*/
function bdlawDetectExtractionRisks() {
// Default result - no risks detected
const result = {
possible_truncation: false,
reason: 'none',
detected_risks: []
};
const reasons = [];
const detectedRisks = [];
// Requirements: 13.1 - Check for pagination elements
for (const selector of BDLAW_PAGINATION_SELECTORS) {
try {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
// Verify at least one element has meaningful content
for (const el of elements) {
const text = el.textContent || '';
// Check if it looks like actual pagination (has numbers or page indicators)
if (/\d|page|next|prev|পৃষ্ঠা/i.test(text) || el.querySelector('a')) {
if (!reasons.includes('pagination')) {
reasons.push('pagination');
}
detectedRisks.push({
type: 'pagination',
selector: selector,
element_count: elements.length,
sample_text: text.substring(0, 100).trim()
});
break;
}
}
}
} catch (e) {
// Selector failed, continue with next
continue;
}
}
// Requirements: 13.2 - Check for lazy-loaded content
for (const selector of BDLAW_LAZY_LOAD_SELECTORS) {
try {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
if (!reasons.includes('lazy_load')) {
reasons.push('lazy_load');
}
detectedRisks.push({
type: 'lazy_load',
selector: selector,
element_count: elements.length
});
break; // One detection is enough for this category
}
} catch (e) {
// Selector failed, continue with next
continue;
}
}
// Requirements: 13.3 - Check for external schedule links
for (const selector of BDLAW_EXTERNAL_SCHEDULE_SELECTORS) {
try {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
// Verify links point to different pages (not anchors on same page)
for (const el of elements) {
const href = el.getAttribute('href') || '';
// Skip anchor links (same page references)
if (href.startsWith('#')) {
continue;
}
// Skip javascript: links
if (href.startsWith('javascript:')) {
continue;
}
// This is an external link to schedule content
if (!reasons.includes('external_link')) {
reasons.push('external_link');
}
detectedRisks.push({
type: 'external_link',
selector: selector,
href: href,
link_text: (el.textContent || '').substring(0, 100).trim()
});
}
}
} catch (e) {
// Selector failed, continue with next
continue;
}
}
// Requirements: 13.4 - Check for hidden DOM elements
// Only flag if hidden elements contain substantial content
for (const selector of BDLAW_HIDDEN_DOM_SELECTORS) {
try {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
for (const el of elements) {
const text = el.textContent || '';
// Only flag if hidden element has substantial content (>50 chars)
// This avoids flagging empty hidden elements or small UI elements
if (text.trim().length > 50) {
if (!reasons.includes('hidden_dom')) {
reasons.push('hidden_dom');
}
detectedRisks.push({
type: 'hidden_dom',
selector: selector,
content_length: text.length,
sample_text: text.substring(0, 100).trim()
});
break; // One detection is enough for this category
}
}
}
} catch (e) {
// Selector failed, continue with next
continue;
}
}
// Build final result
// Requirements: 13.5 - Set possible_truncation based on detected risks
if (reasons.length > 0) {
result.possible_truncation = true;
result.reason = reasons.join(', ');
result.detected_risks = detectedRisks;
}
return result;
}
/**
* Check text for repealed status indicators
* Requirements: 6.1 - Internal helper for status detection
*
* @param {string} text - Text to check for repealed indicators
* @returns {Object} {found: boolean, indicators: string[]}
*/
function bdlawCheckForRepealedStatus(text) {
if (!text || typeof text !== 'string') {
return { found: false, indicators: [] };
}
const indicators = [];
// Check Bengali repealed patterns
for (const pattern of BDLAW_LEGAL_STATUS_PATTERNS.repealed_bengali) {
const freshPattern = new RegExp(pattern.source, pattern.flags);
const match = freshPattern.exec(text);
if (match) {
indicators.push(match[0]);
}
}
// Check English repealed patterns
for (const pattern of BDLAW_LEGAL_STATUS_PATTERNS.repealed_english) {
const freshPattern = new RegExp(pattern.source, pattern.flags);
const match = freshPattern.exec(text);
if (match) {
indicators.push(match[0]);
}
}
// Check status indicator patterns
for (const pattern of BDLAW_LEGAL_STATUS_PATTERNS.status_indicators) {
const freshPattern = new RegExp(pattern.source, pattern.flags);
const match = freshPattern.exec(text);
if (match) {
indicators.push(match[0]);
}
}
return {
found: indicators.length > 0,
indicators: indicators
};
}
/**
* Detect legal status of an act from the DOM document
* Requirements: 6.1, 6.2, 6.3 - Legal Status Tracking
*
* Detects if an act is marked as repealed on the source page by:
* 1. Checking status-specific DOM elements
* 2. Searching title/header for repealed indicators
* 3. Scanning metadata sections for status markers
*
* Returns one of:
* - "active": No repealed indicators found (default assumption)
* - "repealed": Clear repealed indicators detected
* - "unknown": Cannot determine status reliably
*
* @returns {Object} {legal_status: string, status_source: string|null, status_indicators: string[]}
*/
function bdlawDetectLegalStatus() {
// Default result - unknown status
const result = {
legal_status: 'unknown',
status_source: null,
status_indicators: []
};
const detectedIndicators = [];
let statusSource = null;
// Step 1: Check status-specific DOM elements
for (const selector of BDLAW_LEGAL_STATUS_SELECTORS) {
try {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
const text = element.textContent ?? '';
if (!text.trim()) continue;
// Check for repealed patterns in this element
const repealedFound = bdlawCheckForRepealedStatus(text);
if (repealedFound.found) {
detectedIndicators.push(...repealedFound.indicators);
if (!statusSource) {
statusSource = selector;
}
}
}
} catch (e) {
// Selector failed, continue with next
continue;
}
}
// Step 2: Check document title
if (document.title) {
const titleCheck = bdlawCheckForRepealedStatus(document.title);
if (titleCheck.found) {
detectedIndicators.push(...titleCheck.indicators);
if (!statusSource) {
statusSource = 'document.title';
}
}
}
// Step 3: Determine final status based on findings
if (detectedIndicators.length > 0) {
// Clear repealed indicators found
result.legal_status = 'repealed';
result.status_source = statusSource;
result.status_indicators = [...new Set(detectedIndicators)]; // Deduplicate
} else {
// No repealed indicators found - assume active
// Requirements: 6.2 - Default to "active" when no repealed markers found
result.legal_status = 'active';
result.status_source = 'no_repealed_indicators';
result.status_indicators = [];
}
return result;
}
/**
* Try selectors in order, return first non-empty match
*/
function bdlawTrySelectors(selectors) {
for (const selector of selectors) {
try {
const element = document.querySelector(selector);
if (element) {
const text = element.textContent ?? '';
const trimmed = text.trim();
if (trimmed) {
return trimmed;
}
}
} catch (e) {
console.warn('Selector failed:', selector, e);
}
}
return '';
}
/**
* Try selectors and combine all matches
*/
function bdlawTrySelectorsAll(selectors) {
const results = [];
for (const selector of selectors) {
try {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
const text = element.textContent ?? '';
const trimmed = text.trim();
if (trimmed) {
results.push(trimmed);
}
}
} catch (e) {
console.warn('Selector failed:', selector, e);
}
}
return results.join('\n\n');
}
/**
* Count section markers in text
*/
function bdlawCountSectionMarkers(text) {
if (!text || typeof text !== 'string') {
return { 'ধারা': 0, 'অধ্যায়': 0, 'তফসিল': 0 };
}
const counts = {};
for (const marker of BDLAW_SECTION_MARKERS) {
const regex = new RegExp(marker, 'g');
const matches = text.match(regex);
counts[marker] = matches ? matches.length : 0;
}
return counts;
}
/**
* Detect section markers with line numbers and positions
*/
function bdlawDetectSectionMarkers(text) {
if (!text || typeof text !== 'string') {
return [];
}
const markers = [];
const lines = text.split('\n');
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex];
const lineNumber = lineIndex + 1;
for (const marker of BDLAW_SECTION_MARKERS) {
let position = 0;
let searchStart = 0;
while ((position = line.indexOf(marker, searchStart)) !== -1) {
markers.push({
type: marker,
line: line,
lineNumber: lineNumber,
position: position
});
searchStart = position + marker.length;
}
}
}
return markers;
}
/**
* Detect amendment markers in legal text
* Requirements: 25.1, 25.2, 25.3, 25.4 - Amendment and Deletion Marker Detection
*
* @param {string} text - The text to analyze
* @returns {Array<Object>} Array of { type, line, lineNumber, position, context }
*/
function bdlawDetectAmendmentMarkers(text) {
if (!text || typeof text !== 'string') {
return [];
}
const markers = [];
const lines = text.split('\n');
lines.forEach((line, lineIndex) => {
const lineNumber = lineIndex + 1;
for (const marker of BDLAW_AMENDMENT_MARKERS) {
let position = 0;
let searchStart = 0;
while ((position = line.indexOf(marker, searchStart)) !== -1) {
// Extract surrounding context (20 chars before/after)
const contextStart = Math.max(0, position - 20);
const contextEnd = Math.min(line.length, position + marker.length + 20);
const context = line.substring(contextStart, contextEnd);
markers.push({
type: marker,
line: line,
lineNumber: lineNumber,
position: position,
context: context
});
searchStart = position + marker.length;
}
}
});
return markers;
}
/**
* Filter UI noise from extracted content
* Requirements: 28.1, 28.2, 28.3, 28.4, 28.5, 28.6 - Content Noise Filtering
*
* @param {string} text - The text to filter
* @returns {string} Filtered text with UI noise removed
*/
function bdlawFilterContentNoise(text) {
if (!text || typeof text !== 'string') {
return text;
}
let filtered = text;
for (const pattern of BDLAW_UI_NOISE_PATTERNS) {
if (typeof pattern === 'string') {
filtered = filtered.split(pattern).join('');
} else {
filtered = filtered.replace(pattern, '');
}
}
// Trim empty whitespace-only lines at beginning and end
filtered = filtered.replace(/^[\s\n]+/, '');
filtered = filtered.replace(/[\s\n]+$/, '');
return filtered;
}
/**
* Detect cross-references in legal text
* Requirements: 1.4, 1.5, 2.4, 2.5, 6.1 - Citation Detection and Component Extraction
*
* @param {string} text - The legal text content to analyze
* @returns {Array<Object>} Array of CrossReference objects
*/
function bdlawDetectCrossReferences(text) {
if (!text || typeof text !== 'string') {
return [];
}
const references = [];
const lines = text.split('\n');
let charOffset = 0;
lines.forEach((line, lineIndex) => {
// Check each pattern type
for (const [patternName, pattern] of Object.entries(BDLAW_CITATION_PATTERNS)) {
// Create a new regex instance to reset lastIndex for global patterns
const regex = new RegExp(pattern.source, pattern.flags);
let match;
while ((match = regex.exec(line)) !== null) {
const absolutePosition = charOffset + match.index;
const citation = {
citation_text: match[0],
pattern_type: patternName,
line_number: lineIndex + 1, // 1-based line numbers
position: absolutePosition,
// Extract components based on pattern type
...bdlawExtractCitationComponents(patternName, match)
};
// Add context (50 chars before and after)
citation.context_before = bdlawExtractContextBefore(text, absolutePosition, 50);
citation.context_after = bdlawExtractContextAfter(text, absolutePosition + match[0].length, 50);
// Classify reference type based on surrounding context
const fullContext = citation.context_before + ' ' + citation.citation_text + ' ' + citation.context_after;
citation.reference_type = bdlawClassifyReferenceType(fullContext);
references.push(citation);
}
}
charOffset += line.length + 1; // +1 for newline character
});
// Deduplicate overlapping matches (keep most specific)
return bdlawDeduplicateReferences(references);
}
/**
* Extract citation components based on pattern type
* Requirements: 1.4, 2.4, 2.5 - Component Extraction
*
* @param {string} patternName - The name of the matched pattern
* @param {Array} match - The regex match array
* @returns {Object} Extracted components
*/
function bdlawExtractCitationComponents(patternName, match) {
switch (patternName) {
case 'ENGLISH_ACT_FULL':
return {
act_name: match[1] ? match[1].trim() : null,
citation_year: match[2] || match[4],
citation_serial: match[3],
script: 'english'
};
case 'ENGLISH_ACT_SHORT':
return {
act_name: null,
citation_serial: match[1],
citation_year: match[2],
script: 'english'
};
case 'BENGALI_ACT_FULL':
return {
act_name: match[1] ? match[1].trim() : null,
citation_year: match[2] || match[3],
citation_serial: match[4],
script: 'bengali'
};
case 'BENGALI_ACT_SHORT':
return {
citation_year: match[1],
citation_serial: match[2],
act_type: match[3],
script: 'bengali'
};
case 'BENGALI_ORDINANCE':
return {
act_name: match[1] ? match[1].trim() : null,
citation_year: match[2] || match[4],
citation_serial: match[3],
script: 'bengali'
};
case 'PRESIDENTS_ORDER':
return {
act_name: null,
citation_serial: match[1],
citation_year: match[2],
script: 'english'
};
default:
return { script: 'unknown' };
}
}
/**
* Extract context before a citation
* Requirements: 4.1, 4.3 - Context Extraction
*
* @param {string} text - The full text
* @param {number} position - The citation start position
* @param {number} length - Maximum context length
* @returns {string} Context text before the citation
*/
function bdlawExtractContextBefore(text, position, length) {
if (!text || position <= 0) {
return '';
}
const start = Math.max(0, position - length);
return text.substring(start, position).trim();
}
/**
* Extract context after a citation
* Requirements: 4.2, 4.3 - Context Extraction
*
* @param {string} text - The full text
* @param {number} position - The position after the citation
* @param {number} length - Maximum context length
* @returns {string} Context text after the citation
*/
function bdlawExtractContextAfter(text, position, length) {
if (!text || position >= text.length) {
return '';
}
const end = Math.min(text.length, position + length);
return text.substring(position, end).trim();
}
/**
* Classify the type of reference based on surrounding context
* Requirements: 3.1, 3.2, 3.3, 3.4, 3.5 - Reference Type Classification
*
* @param {string} contextText - Text surrounding the citation
* @returns {string} Reference type classification
*/
function bdlawClassifyReferenceType(contextText) {
if (!contextText) {
return 'mention';
}
const lowerContext = contextText.toLowerCase();
// Check each reference type in priority order
for (const [refType, keywords] of Object.entries(BDLAW_REFERENCE_TYPE_KEYWORDS)) {
for (const keyword of keywords) {
if (contextText.includes(keyword) || lowerContext.includes(keyword.toLowerCase())) {
return refType;
}
}
}
return 'mention'; // Default type when no classification keyword found
}
/**
* Remove duplicate/overlapping references
* Keeps the most specific match (longest) when patterns overlap
*
* @param {Array} references - Array of detected references
* @returns {Array} Deduplicated references
*/
function bdlawDeduplicateReferences(references) {
if (!references || references.length === 0) {
return [];
}
// Sort by position, then by specificity (longer matches first)
const sorted = [...references].sort((a, b) => {
if (a.position !== b.position) {
return a.position - b.position;
}
return b.citation_text.length - a.citation_text.length;
});
const deduplicated = [];
let lastEnd = -1;
for (const ref of sorted) {
const refEnd = ref.position + ref.citation_text.length;
// Skip if this reference overlaps with the previous one
if (ref.position < lastEnd) {
continue;
}
deduplicated.push(ref);
lastEnd = refEnd;
}
return deduplicated;
}
/**
* Extract table data handling merged cells correctly using matrix-based algorithm
* Requirements: 24.1-24.7 - Table Parsing with Merged Cell Handling
*
* @param {HTMLTableElement} tableElement - The table element to extract
* @returns {Object} { data: string[][], hasMergedCells: boolean, rowCount: number, colCount: number }
*/
function bdlawExtractTableWithMergedCells(tableElement) {
if (!tableElement) {