od-temp 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1552 @@
1
+
2
+ //#region src/document/OCRProcessor.ts
3
+ /**
4
+ * OCR processor with optional Tesseract.js support
5
+ * Requires peer dependency: tesseract.js
6
+ */
7
+ var OCRProcessor = class {
8
+ constructor() {
9
+ try {
10
+ this.tesseract = require("tesseract.js");
11
+ } catch {}
12
+ }
13
+ /**
14
+ * Extract text from image buffer using OCR
15
+ */
16
+ async recognizeText(buffer, options) {
17
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
18
+ const startTime = performance.now();
19
+ try {
20
+ const language = Array.isArray(options?.language) ? options.language.join("+") : options?.language || "eng";
21
+ const worker = await this.tesseract.createWorker(language, options?.oem || 3);
22
+ if (options?.psm !== void 0) await worker.setParameters({ tessedit_pageseg_mode: options.psm });
23
+ const result = await worker.recognize(buffer);
24
+ await worker.terminate();
25
+ const endTime = performance.now();
26
+ const processingTime = Math.round((endTime - startTime) * 100) / 100;
27
+ return {
28
+ text: result.data.text || "",
29
+ confidence: result.data.confidence || 0,
30
+ processingTime
31
+ };
32
+ } catch (error) {
33
+ throw new Error(`[OCRProcessor] OCR recognition failed: ${error.message}`);
34
+ }
35
+ }
36
+ /**
37
+ * Check if OCR is available (tesseract.js installed)
38
+ */
39
+ isAvailable() {
40
+ return !!this.tesseract;
41
+ }
42
+ /**
43
+ * Create a scheduler for batch OCR processing
44
+ * More efficient for processing multiple images
45
+ */
46
+ async createScheduler(workerCount = 4) {
47
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
48
+ if (this.scheduler) await this.scheduler.terminate();
49
+ this.scheduler = this.tesseract.createScheduler();
50
+ const workers = [];
51
+ for (let i = 0; i < workerCount; i++) {
52
+ const worker = await this.tesseract.createWorker("eng");
53
+ this.scheduler.addWorker(worker);
54
+ workers.push(worker);
55
+ }
56
+ return this.scheduler;
57
+ }
58
+ /**
59
+ * Batch process multiple images
60
+ */
61
+ async recognizeBatch(buffers, _options) {
62
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
63
+ const scheduler = await this.createScheduler();
64
+ try {
65
+ const results = await Promise.all(buffers.map(async (buffer) => {
66
+ const startTime = performance.now();
67
+ const result = await scheduler.addJob("recognize", buffer);
68
+ const endTime = performance.now();
69
+ return {
70
+ text: result.data.text || "",
71
+ confidence: result.data.confidence || 0,
72
+ processingTime: Math.round((endTime - startTime) * 100) / 100
73
+ };
74
+ }));
75
+ await scheduler.terminate();
76
+ this.scheduler = void 0;
77
+ return results;
78
+ } catch (error) {
79
+ if (scheduler) {
80
+ await scheduler.terminate();
81
+ this.scheduler = void 0;
82
+ }
83
+ throw new Error(`[OCRProcessor] Batch OCR failed: ${error.message}`);
84
+ }
85
+ }
86
+ /**
87
+ * Terminate any running scheduler
88
+ */
89
+ async cleanup() {
90
+ if (this.scheduler) {
91
+ await this.scheduler.terminate();
92
+ this.scheduler = void 0;
93
+ }
94
+ }
95
+ };
96
+ /**
97
+ * Create an OCR processor instance
98
+ */
99
+ function createOCRProcessor() {
100
+ return new OCRProcessor();
101
+ }
102
+
103
+ //#endregion
104
+ //#region src/document/JsonProcessor.ts
105
+ /**
106
+ * Processor for JSON documents
107
+ */
108
+ var JsonProcessor = class {
109
+ constructor() {
110
+ this.defaultOptions = {
111
+ maxDepth: 100,
112
+ scanKeys: false,
113
+ alwaysRedact: [],
114
+ skipPaths: [],
115
+ piiIndicatorKeys: [
116
+ "email",
117
+ "e-mail",
118
+ "mail",
119
+ "phone",
120
+ "tel",
121
+ "telephone",
122
+ "mobile",
123
+ "ssn",
124
+ "social_security",
125
+ "address",
126
+ "street",
127
+ "city",
128
+ "zip",
129
+ "postal",
130
+ "name",
131
+ "firstname",
132
+ "lastname",
133
+ "fullname",
134
+ "password",
135
+ "pwd",
136
+ "secret",
137
+ "token",
138
+ "key",
139
+ "card",
140
+ "credit_card",
141
+ "creditcard",
142
+ "account",
143
+ "iban",
144
+ "swift",
145
+ "passport",
146
+ "license",
147
+ "licence"
148
+ ],
149
+ preserveStructure: true
150
+ };
151
+ }
152
+ /**
153
+ * Parse JSON from buffer or string
154
+ */
155
+ parse(input) {
156
+ try {
157
+ const text = typeof input === "string" ? input : input.toString("utf-8");
158
+ return JSON.parse(text);
159
+ } catch (error) {
160
+ throw new Error(`[JsonProcessor] Invalid JSON: ${error.message}`);
161
+ }
162
+ }
163
+ /**
164
+ * Detect PII in JSON data
165
+ */
166
+ async detect(data, detector, options) {
167
+ const opts = {
168
+ ...this.defaultOptions,
169
+ ...options
170
+ };
171
+ const pathsDetected = [];
172
+ const matchesByPath = {};
173
+ const allDetections = [];
174
+ const promises = [];
175
+ this.traverse(data, "", opts, (path, value, key) => {
176
+ promises.push((async () => {
177
+ if (this.shouldSkip(path, opts.skipPaths)) return;
178
+ if (this.shouldAlwaysRedact(path, opts.alwaysRedact)) {
179
+ const detection = {
180
+ type: "SENSITIVE_FIELD",
181
+ value: String(value),
182
+ placeholder: `[SENSITIVE_FIELD]`,
183
+ position: [0, String(value).length],
184
+ severity: "high",
185
+ confidence: 1
186
+ };
187
+ matchesByPath[path] = [detection];
188
+ pathsDetected.push(path);
189
+ allDetections.push(detection);
190
+ return;
191
+ }
192
+ if (opts.scanKeys && key) {
193
+ const keyResult = await detector.detect(key);
194
+ if (keyResult.detections.length > 0) {
195
+ const keyPath = `${path}.__key__`;
196
+ matchesByPath[keyPath] = keyResult.detections;
197
+ pathsDetected.push(keyPath);
198
+ allDetections.push(...keyResult.detections);
199
+ }
200
+ }
201
+ const valueStr = String(value);
202
+ const result = await detector.detect(valueStr);
203
+ if (result.detections.length > 0) {
204
+ const boostedDetections = this.boostConfidenceFromKey(result.detections, key, opts.piiIndicatorKeys);
205
+ matchesByPath[path] = boostedDetections;
206
+ pathsDetected.push(path);
207
+ allDetections.push(...boostedDetections);
208
+ }
209
+ })());
210
+ });
211
+ await Promise.all(promises);
212
+ const original = JSON.stringify(data);
213
+ const redacted = this.redact(data, {
214
+ original,
215
+ redacted: original,
216
+ detections: allDetections,
217
+ redactionMap: {},
218
+ stats: { piiCount: allDetections.length },
219
+ pathsDetected,
220
+ matchesByPath
221
+ }, opts);
222
+ const redactionMap = {};
223
+ allDetections.forEach((det) => {
224
+ redactionMap[det.placeholder] = det.value;
225
+ });
226
+ return {
227
+ original,
228
+ redacted: typeof redacted === "string" ? redacted : JSON.stringify(redacted),
229
+ detections: allDetections,
230
+ redactionMap,
231
+ stats: { piiCount: allDetections.length },
232
+ pathsDetected,
233
+ matchesByPath
234
+ };
235
+ }
236
+ /**
237
+ * Redact PII in JSON data
238
+ */
239
+ redact(data, detectionResult, options) {
240
+ if (!{
241
+ ...this.defaultOptions,
242
+ ...options
243
+ }.preserveStructure) return this.parse(this.redactText(JSON.stringify(data, null, 2), detectionResult));
244
+ return this.redactPreservingStructure(data, detectionResult.pathsDetected);
245
+ }
246
+ /**
247
+ * Redact specific paths in JSON while preserving structure
248
+ */
249
+ redactPreservingStructure(data, pathsToRedact) {
250
+ const pathSet = new Set(pathsToRedact);
251
+ const redactValue = (value, currentPath) => {
252
+ if (pathSet.has(currentPath)) {
253
+ if (typeof value === "string") return "[REDACTED]";
254
+ else if (typeof value === "number") return 0;
255
+ else if (typeof value === "boolean") return false;
256
+ else if (value === null) return null;
257
+ else if (Array.isArray(value)) return [];
258
+ else if (typeof value === "object") return {};
259
+ return "[REDACTED]";
260
+ }
261
+ if (Array.isArray(value)) return value.map((item, index) => redactValue(item, `${currentPath}[${index}]`));
262
+ if (value !== null && typeof value === "object") {
263
+ const result = {};
264
+ for (const [key, val] of Object.entries(value)) result[key] = redactValue(val, currentPath ? `${currentPath}.${key}` : key);
265
+ return result;
266
+ }
267
+ return value;
268
+ };
269
+ return redactValue(data, "");
270
+ }
271
+ /**
272
+ * Simple text-based redaction (fallback)
273
+ */
274
+ redactText(text, detectionResult) {
275
+ let redacted = text;
276
+ const sortedDetections = [...detectionResult.detections].sort((a, b) => b.position[0] - a.position[0]);
277
+ for (const detection of sortedDetections) {
278
+ const [start, end] = detection.position;
279
+ redacted = redacted.slice(0, start) + detection.placeholder + redacted.slice(end);
280
+ }
281
+ return redacted;
282
+ }
283
+ /**
284
+ * Traverse JSON structure and call callback for each value
285
+ */
286
+ traverse(obj, path, options, callback, depth = 0) {
287
+ if (depth > options.maxDepth) throw new Error(`[JsonProcessor] Maximum depth (${options.maxDepth}) exceeded`);
288
+ if (obj === null || obj === void 0) return;
289
+ if (Array.isArray(obj)) {
290
+ obj.forEach((item, index) => {
291
+ const itemPath = path ? `${path}[${index}]` : `[${index}]`;
292
+ if (this.isPrimitive(item)) callback(itemPath, item);
293
+ this.traverse(item, itemPath, options, callback, depth + 1);
294
+ });
295
+ return;
296
+ }
297
+ if (typeof obj === "object") {
298
+ for (const [key, value] of Object.entries(obj)) {
299
+ const valuePath = path ? `${path}.${key}` : key;
300
+ if (this.isPrimitive(value)) callback(valuePath, value, key);
301
+ this.traverse(value, valuePath, options, callback, depth + 1);
302
+ }
303
+ return;
304
+ }
305
+ if (this.isPrimitive(obj)) callback(path, obj);
306
+ }
307
+ /**
308
+ * Check if value is primitive (string, number, boolean)
309
+ */
310
+ isPrimitive(value) {
311
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
312
+ }
313
+ /**
314
+ * Check if path should be skipped
315
+ */
316
+ shouldSkip(path, skipPaths) {
317
+ return skipPaths.some((skipPath) => {
318
+ if (path === skipPath) return true;
319
+ return new RegExp("^" + skipPath.replace(/\*/g, "[^.]+") + "$").test(path);
320
+ });
321
+ }
322
+ /**
323
+ * Check if path should always be redacted
324
+ */
325
+ shouldAlwaysRedact(path, alwaysRedact) {
326
+ return alwaysRedact.some((redactPath) => {
327
+ if (path === redactPath) return true;
328
+ return new RegExp("^" + redactPath.replace(/\*/g, "[^.]+") + "$").test(path);
329
+ });
330
+ }
331
+ /**
332
+ * Boost confidence if key name indicates PII
333
+ */
334
+ boostConfidenceFromKey(detections, key, piiIndicatorKeys) {
335
+ if (!key) return detections;
336
+ const keyLower = key.toLowerCase();
337
+ if (!piiIndicatorKeys.some((indicator) => keyLower.includes(indicator.toLowerCase()))) return detections;
338
+ return detections.map((detection) => ({
339
+ ...detection,
340
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
341
+ }));
342
+ }
343
+ /**
344
+ * Extract all text values from JSON for simple text-based detection
345
+ */
346
+ extractText(data, options) {
347
+ const opts = {
348
+ ...this.defaultOptions,
349
+ ...options
350
+ };
351
+ const textParts = [];
352
+ this.traverse(data, "", opts, (_path, value, key) => {
353
+ if (opts.scanKeys && key) textParts.push(key);
354
+ if (typeof value === "string") textParts.push(value);
355
+ });
356
+ return textParts.join(" ");
357
+ }
358
+ /**
359
+ * Validate JSON buffer/string
360
+ */
361
+ isValid(input) {
362
+ try {
363
+ this.parse(input);
364
+ return true;
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
369
+ /**
370
+ * Get JSON Lines (JSONL) support - split by newlines and parse each line
371
+ */
372
+ parseJsonLines(input) {
373
+ return (typeof input === "string" ? input : input.toString("utf-8")).split("\n").filter((line) => line.trim().length > 0).map((line, index) => {
374
+ try {
375
+ return JSON.parse(line);
376
+ } catch (error) {
377
+ throw new Error(`[JsonProcessor] Invalid JSON at line ${index + 1}: ${error.message}`);
378
+ }
379
+ });
380
+ }
381
+ /**
382
+ * Detect PII in JSON Lines format
383
+ */
384
+ async detectJsonLines(input, detector, options) {
385
+ const documents = this.parseJsonLines(input);
386
+ return Promise.all(documents.map((doc) => this.detect(doc, detector, options)));
387
+ }
388
+ };
389
+ /**
390
+ * Create a JSON processor instance
391
+ */
392
+ function createJsonProcessor() {
393
+ return new JsonProcessor();
394
+ }
395
+
396
+ //#endregion
397
+ //#region src/document/CsvProcessor.ts
398
+ /**
399
+ * CSV processor for tabular data
400
+ */
401
+ var CsvProcessor = class {
402
+ constructor() {
403
+ this.defaultOptions = {
404
+ quote: "\"",
405
+ escape: "\"",
406
+ skipEmptyLines: true,
407
+ piiIndicatorNames: [
408
+ "email",
409
+ "e-mail",
410
+ "mail",
411
+ "email_address",
412
+ "phone",
413
+ "tel",
414
+ "telephone",
415
+ "mobile",
416
+ "phone_number",
417
+ "ssn",
418
+ "social_security",
419
+ "social_security_number",
420
+ "address",
421
+ "street",
422
+ "street_address",
423
+ "city",
424
+ "zip",
425
+ "zipcode",
426
+ "postal",
427
+ "postcode",
428
+ "name",
429
+ "firstname",
430
+ "first_name",
431
+ "lastname",
432
+ "last_name",
433
+ "fullname",
434
+ "full_name",
435
+ "password",
436
+ "pwd",
437
+ "secret",
438
+ "token",
439
+ "api_key",
440
+ "card",
441
+ "credit_card",
442
+ "creditcard",
443
+ "card_number",
444
+ "account",
445
+ "account_number",
446
+ "iban",
447
+ "swift",
448
+ "passport",
449
+ "passport_number",
450
+ "license",
451
+ "licence",
452
+ "driver_license",
453
+ "dob",
454
+ "date_of_birth",
455
+ "birth_date",
456
+ "birthdate"
457
+ ],
458
+ treatFirstRowAsHeader: true
459
+ };
460
+ }
461
+ /**
462
+ * Parse CSV from buffer or string
463
+ */
464
+ parse(input, options) {
465
+ const opts = {
466
+ ...this.defaultOptions,
467
+ ...options
468
+ };
469
+ const text = typeof input === "string" ? input : input.toString("utf-8");
470
+ const delimiter = opts.delimiter || this.detectDelimiter(text);
471
+ const lines = text.split(/\r?\n/);
472
+ const rows = [];
473
+ let rowIndex = 0;
474
+ for (let i = 0; i < lines.length; i++) {
475
+ const line = lines[i];
476
+ if (opts.skipEmptyLines && line.trim().length === 0) continue;
477
+ if (opts.maxRows !== void 0 && rowIndex >= opts.maxRows) break;
478
+ const values = this.parseRow(line, delimiter, opts.quote, opts.escape);
479
+ rows.push({
480
+ index: rowIndex,
481
+ values
482
+ });
483
+ rowIndex++;
484
+ }
485
+ return rows;
486
+ }
487
+ /**
488
+ * Detect PII in CSV data
489
+ */
490
+ async detect(input, detector, options) {
491
+ const opts = {
492
+ ...this.defaultOptions,
493
+ ...options
494
+ };
495
+ const rows = this.parse(input, options);
496
+ if (rows.length === 0) {
497
+ const original = typeof input === "string" ? input : input.toString("utf-8");
498
+ return {
499
+ original,
500
+ redacted: original,
501
+ detections: [],
502
+ redactionMap: {},
503
+ stats: { piiCount: 0 },
504
+ rowCount: 0,
505
+ columnCount: 0,
506
+ columnStats: {},
507
+ matchesByCell: []
508
+ };
509
+ }
510
+ const hasHeader = opts.hasHeader !== void 0 ? opts.hasHeader : this.detectHeader(rows);
511
+ const headers = hasHeader && rows.length > 0 ? rows[0].values : void 0;
512
+ const dataRows = hasHeader ? rows.slice(1) : rows;
513
+ const columnCount = rows[0].values.length;
514
+ const columnNameToIndex = /* @__PURE__ */ new Map();
515
+ if (headers) headers.forEach((header, index) => {
516
+ columnNameToIndex.set(header.toLowerCase().trim(), index);
517
+ });
518
+ const alwaysRedactCols = new Set(opts.alwaysRedactColumns || []);
519
+ if (opts.alwaysRedactColumnNames && headers) opts.alwaysRedactColumnNames.forEach((name) => {
520
+ const index = columnNameToIndex.get(name.toLowerCase().trim());
521
+ if (index !== void 0) alwaysRedactCols.add(index);
522
+ });
523
+ const skipCols = new Set(opts.skipColumns || []);
524
+ const columnStats = {};
525
+ const matchesByCell = [];
526
+ const allDetections = [];
527
+ for (let col = 0; col < columnCount; col++) columnStats[col] = {
528
+ columnIndex: col,
529
+ columnName: headers?.[col],
530
+ piiCount: 0,
531
+ piiPercentage: 0,
532
+ piiTypes: []
533
+ };
534
+ for (const row of dataRows) for (let col = 0; col < row.values.length; col++) {
535
+ if (skipCols.has(col)) continue;
536
+ const cellValue = row.values[col];
537
+ if (alwaysRedactCols.has(col)) {
538
+ const detection = {
539
+ type: "SENSITIVE_COLUMN",
540
+ value: cellValue,
541
+ placeholder: `[SENSITIVE_COLUMN_${col}]`,
542
+ position: [0, cellValue.length],
543
+ severity: "high",
544
+ confidence: 1
545
+ };
546
+ matchesByCell.push({
547
+ row: row.index,
548
+ column: col,
549
+ columnName: headers?.[col],
550
+ value: cellValue,
551
+ matches: [detection]
552
+ });
553
+ allDetections.push(detection);
554
+ columnStats[col].piiCount++;
555
+ continue;
556
+ }
557
+ const result = await detector.detect(cellValue);
558
+ if (result.detections.length > 0) {
559
+ const boostedDetections = this.boostConfidenceFromColumnName(result.detections, headers?.[col], opts.piiIndicatorNames || []);
560
+ matchesByCell.push({
561
+ row: row.index,
562
+ column: col,
563
+ columnName: headers?.[col],
564
+ value: cellValue,
565
+ matches: boostedDetections
566
+ });
567
+ allDetections.push(...boostedDetections);
568
+ columnStats[col].piiCount += boostedDetections.length;
569
+ const columnTypes = new Set(columnStats[col].piiTypes);
570
+ boostedDetections.forEach((d) => columnTypes.add(d.type));
571
+ columnStats[col].piiTypes = Array.from(columnTypes);
572
+ }
573
+ }
574
+ for (let col = 0; col < columnCount; col++) {
575
+ const rowsWithPii = matchesByCell.filter((m) => m.column === col).length;
576
+ columnStats[col].piiPercentage = dataRows.length > 0 ? rowsWithPii / dataRows.length * 100 : 0;
577
+ }
578
+ const original = typeof input === "string" ? input : input.toString("utf-8");
579
+ const redacted = this.redact(original, {
580
+ original,
581
+ redacted: original,
582
+ detections: allDetections,
583
+ redactionMap: {},
584
+ stats: { piiCount: allDetections.length },
585
+ rowCount: dataRows.length,
586
+ columnCount,
587
+ headers,
588
+ columnStats,
589
+ matchesByCell
590
+ }, opts);
591
+ const redactionMap = {};
592
+ allDetections.forEach((det) => {
593
+ redactionMap[det.placeholder] = det.value;
594
+ });
595
+ return {
596
+ original,
597
+ redacted,
598
+ detections: allDetections,
599
+ redactionMap,
600
+ stats: { piiCount: allDetections.length },
601
+ rowCount: dataRows.length,
602
+ columnCount,
603
+ headers: headers?.filter((h) => h !== void 0),
604
+ columnStats,
605
+ matchesByCell
606
+ };
607
+ }
608
+ /**
609
+ * Redact PII in CSV data
610
+ */
611
+ redact(input, detectionResult, options) {
612
+ const opts = {
613
+ ...this.defaultOptions,
614
+ ...options
615
+ };
616
+ const rows = this.parse(input, options);
617
+ if (rows.length === 0) return "";
618
+ const delimiter = opts.delimiter || this.detectDelimiter(typeof input === "string" ? input : input.toString("utf-8"));
619
+ const hasHeader = detectionResult.headers !== void 0;
620
+ const redactionMap = /* @__PURE__ */ new Map();
621
+ for (const cellMatch of detectionResult.matchesByCell) {
622
+ if (!redactionMap.has(cellMatch.row)) redactionMap.set(cellMatch.row, /* @__PURE__ */ new Map());
623
+ redactionMap.get(cellMatch.row).set(cellMatch.column, "[REDACTED]");
624
+ }
625
+ const outputRows = [];
626
+ for (let i = 0; i < rows.length; i++) {
627
+ const row = rows[i];
628
+ if (hasHeader && i === 0) outputRows.push(this.formatRow(row.values, delimiter, opts.quote));
629
+ else {
630
+ const rowIndex = hasHeader ? i - 1 : i;
631
+ const redactedValues = row.values.map((value, colIndex) => {
632
+ return redactionMap.get(rowIndex)?.get(colIndex) || value;
633
+ });
634
+ outputRows.push(this.formatRow(redactedValues, delimiter, opts.quote));
635
+ }
636
+ }
637
+ return outputRows.join("\n");
638
+ }
639
+ /**
640
+ * Parse a single CSV row
641
+ */
642
+ parseRow(line, delimiter, quote, _escape) {
643
+ const values = [];
644
+ let current = "";
645
+ let inQuotes = false;
646
+ let i = 0;
647
+ while (i < line.length) {
648
+ const char = line[i];
649
+ const nextChar = line[i + 1];
650
+ if (char === quote) if (inQuotes && nextChar === quote) {
651
+ current += quote;
652
+ i += 2;
653
+ } else {
654
+ inQuotes = !inQuotes;
655
+ i++;
656
+ }
657
+ else if (char === delimiter && !inQuotes) {
658
+ values.push(current);
659
+ current = "";
660
+ i++;
661
+ } else {
662
+ current += char;
663
+ i++;
664
+ }
665
+ }
666
+ values.push(current);
667
+ return values;
668
+ }
669
+ /**
670
+ * Format a row as CSV
671
+ */
672
+ formatRow(values, delimiter, quote) {
673
+ return values.map((value) => {
674
+ if (value.includes(delimiter) || value.includes(quote) || value.includes("\n")) return `${quote}${value.replace(new RegExp(quote, "g"), quote + quote)}${quote}`;
675
+ return value;
676
+ }).join(delimiter);
677
+ }
678
+ /**
679
+ * Auto-detect CSV delimiter
680
+ */
681
+ detectDelimiter(text) {
682
+ const delimiters = [
683
+ ",",
684
+ " ",
685
+ ";",
686
+ "|"
687
+ ];
688
+ const lines = text.split(/\r?\n/).slice(0, 5);
689
+ let bestDelimiter = ",";
690
+ let bestScore = 0;
691
+ for (const delimiter of delimiters) {
692
+ const counts = lines.map((line) => {
693
+ let count = 0;
694
+ let inQuotes = false;
695
+ for (const char of line) {
696
+ if (char === "\"") inQuotes = !inQuotes;
697
+ if (char === delimiter && !inQuotes) count++;
698
+ }
699
+ return count;
700
+ });
701
+ if (counts.length > 0 && counts[0] > 0) {
702
+ const avg = counts.reduce((a, b) => a + b, 0) / counts.length;
703
+ const score = avg / (counts.reduce((sum, c) => sum + Math.pow(c - avg, 2), 0) / counts.length + 1);
704
+ if (score > bestScore) {
705
+ bestScore = score;
706
+ bestDelimiter = delimiter;
707
+ }
708
+ }
709
+ }
710
+ return bestDelimiter;
711
+ }
712
+ /**
713
+ * Detect if first row is likely a header
714
+ */
715
+ detectHeader(rows) {
716
+ if (rows.length < 2) return false;
717
+ const firstRow = rows[0].values;
718
+ const secondRow = rows[1].values;
719
+ if (firstRow.reduce((sum, v) => sum + v.length, 0) / firstRow.length > secondRow.reduce((sum, v) => sum + v.length, 0) / secondRow.length * 1.5) return false;
720
+ const firstRowNumeric = firstRow.filter((v) => !isNaN(Number(v)) && v.trim() !== "").length;
721
+ return firstRow.length - firstRowNumeric >= firstRowNumeric;
722
+ }
723
+ /**
724
+ * Boost confidence if column name indicates PII
725
+ */
726
+ boostConfidenceFromColumnName(detections, columnName, piiIndicatorNames) {
727
+ if (!columnName) return detections;
728
+ const nameLower = columnName.toLowerCase().trim();
729
+ if (!piiIndicatorNames.some((indicator) => nameLower.includes(indicator.toLowerCase()))) return detections;
730
+ return detections.map((detection) => ({
731
+ ...detection,
732
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
733
+ }));
734
+ }
735
+ /**
736
+ * Extract all cell values as text
737
+ */
738
+ extractText(input, options) {
739
+ const rows = this.parse(input, options);
740
+ const textParts = [];
741
+ for (const row of rows) for (const value of row.values) if (value.trim().length > 0) textParts.push(value);
742
+ return textParts.join(" ");
743
+ }
744
+ /**
745
+ * Get column statistics without full PII detection
746
+ */
747
+ getColumnInfo(input, options) {
748
+ const rows = this.parse(input, options);
749
+ if (rows.length === 0) return {
750
+ columnCount: 0,
751
+ rowCount: 0,
752
+ sampleRows: []
753
+ };
754
+ const opts = {
755
+ ...this.defaultOptions,
756
+ ...options
757
+ };
758
+ const hasHeader = opts.hasHeader !== void 0 ? opts.hasHeader : this.detectHeader(rows);
759
+ const headers = hasHeader && rows.length > 0 ? rows[0].values : void 0;
760
+ const dataRows = hasHeader ? rows.slice(1) : rows;
761
+ const sampleRows = dataRows.slice(0, 5).map((r) => r.values);
762
+ return {
763
+ columnCount: rows[0].values.length,
764
+ rowCount: dataRows.length,
765
+ headers,
766
+ sampleRows
767
+ };
768
+ }
769
+ };
770
+ /**
771
+ * Create a CSV processor instance
772
+ */
773
+ function createCsvProcessor() {
774
+ return new CsvProcessor();
775
+ }
776
+
777
+ //#endregion
778
+ //#region src/document/XlsxProcessor.ts
779
+ /**
780
+ * XLSX processor for spreadsheet data
781
+ */
782
+ var XlsxProcessor = class {
783
+ constructor() {
784
+ this.defaultOptions = {
785
+ piiIndicatorNames: [
786
+ "email",
787
+ "e-mail",
788
+ "mail",
789
+ "email_address",
790
+ "phone",
791
+ "tel",
792
+ "telephone",
793
+ "mobile",
794
+ "phone_number",
795
+ "ssn",
796
+ "social_security",
797
+ "social_security_number",
798
+ "address",
799
+ "street",
800
+ "street_address",
801
+ "city",
802
+ "zip",
803
+ "zipcode",
804
+ "postal",
805
+ "postcode",
806
+ "name",
807
+ "firstname",
808
+ "first_name",
809
+ "lastname",
810
+ "last_name",
811
+ "fullname",
812
+ "full_name",
813
+ "password",
814
+ "pwd",
815
+ "secret",
816
+ "token",
817
+ "api_key",
818
+ "card",
819
+ "credit_card",
820
+ "creditcard",
821
+ "card_number",
822
+ "account",
823
+ "account_number",
824
+ "iban",
825
+ "swift",
826
+ "passport",
827
+ "passport_number",
828
+ "license",
829
+ "licence",
830
+ "driver_license",
831
+ "dob",
832
+ "date_of_birth",
833
+ "birth_date",
834
+ "birthdate"
835
+ ],
836
+ preserveFormatting: true,
837
+ preserveFormulas: true
838
+ };
839
+ try {
840
+ this.xlsx = require("xlsx");
841
+ } catch {}
842
+ }
843
+ /**
844
+ * Check if XLSX support is available
845
+ */
846
+ isAvailable() {
847
+ return !!this.xlsx;
848
+ }
849
+ /**
850
+ * Parse XLSX from buffer
851
+ */
852
+ parse(buffer) {
853
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
854
+ try {
855
+ return this.xlsx.read(buffer, {
856
+ type: "buffer",
857
+ cellFormula: true,
858
+ cellStyles: true
859
+ });
860
+ } catch (error) {
861
+ throw new Error(`[XlsxProcessor] Failed to parse XLSX: ${error.message}`);
862
+ }
863
+ }
864
+ /**
865
+ * Detect PII in XLSX data
866
+ */
867
+ async detect(buffer, detector, options) {
868
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
869
+ const opts = {
870
+ ...this.defaultOptions,
871
+ ...options
872
+ };
873
+ const workbook = this.parse(buffer);
874
+ const sheetNames = this.getSheetNamesToProcess(workbook, opts);
875
+ const sheetResults = [];
876
+ const allDetections = [];
877
+ const allTypes = /* @__PURE__ */ new Set();
878
+ for (let sheetIndex = 0; sheetIndex < sheetNames.length; sheetIndex++) {
879
+ const sheetName = sheetNames[sheetIndex];
880
+ const sheet = workbook.Sheets[sheetName];
881
+ const sheetResult = await this.detectSheet(sheet, sheetName, sheetIndex, detector, opts);
882
+ sheetResults.push(sheetResult);
883
+ allDetections.push(...sheetResult.matchesByCell.flatMap((c) => c.matches));
884
+ sheetResult.matchesByCell.forEach((cell) => {
885
+ cell.matches.forEach((det) => allTypes.add(det.type));
886
+ });
887
+ }
888
+ const original = this.extractText(buffer, options);
889
+ const redactedBuffer = this.redact(buffer, {
890
+ original,
891
+ redacted: original,
892
+ detections: allDetections,
893
+ redactionMap: {},
894
+ stats: { piiCount: allDetections.length },
895
+ sheetResults,
896
+ sheetCount: sheetResults.length
897
+ }, options);
898
+ const redacted = this.extractText(redactedBuffer, options);
899
+ const redactionMap = {};
900
+ allDetections.forEach((det) => {
901
+ redactionMap[det.placeholder] = det.value;
902
+ });
903
+ return {
904
+ original,
905
+ redacted,
906
+ detections: allDetections,
907
+ redactionMap,
908
+ stats: { piiCount: allDetections.length },
909
+ sheetResults,
910
+ sheetCount: sheetResults.length
911
+ };
912
+ }
913
+ /**
914
+ * Detect PII in a single sheet
915
+ */
916
+ async detectSheet(sheet, sheetName, sheetIndex, detector, options) {
917
+ const range = this.xlsx.utils.decode_range(sheet["!ref"] || "A1");
918
+ const startRow = range.s.r;
919
+ const endRow = options.maxRows !== void 0 ? Math.min(range.e.r, startRow + options.maxRows - 1) : range.e.r;
920
+ const startCol = range.s.c;
921
+ const endCol = range.e.c;
922
+ const columnCount = endCol - startCol + 1;
923
+ const hasHeader = options.hasHeader !== void 0 ? options.hasHeader : this.detectHeader(sheet, range);
924
+ const headers = hasHeader ? this.getRowValues(sheet, startRow, startCol, endCol) : void 0;
925
+ const dataStartRow = hasHeader ? startRow + 1 : startRow;
926
+ const columnNameToIndex = /* @__PURE__ */ new Map();
927
+ if (headers) headers.forEach((header, index) => {
928
+ if (header) columnNameToIndex.set(header.toLowerCase().trim(), index);
929
+ });
930
+ const alwaysRedactCols = new Set(options.alwaysRedactColumns || []);
931
+ if (options.alwaysRedactColumnNames && headers) options.alwaysRedactColumnNames.forEach((name) => {
932
+ const index = columnNameToIndex.get(name.toLowerCase().trim());
933
+ if (index !== void 0) alwaysRedactCols.add(index);
934
+ });
935
+ const skipCols = new Set(options.skipColumns || []);
936
+ const columnStats = {};
937
+ for (let col = 0; col <= endCol - startCol; col++) columnStats[col] = {
938
+ columnIndex: col,
939
+ columnLetter: this.columnToLetter(col),
940
+ columnName: headers?.[col],
941
+ piiCount: 0,
942
+ piiPercentage: 0,
943
+ piiTypes: []
944
+ };
945
+ const matchesByCell = [];
946
+ for (let row = dataStartRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) {
947
+ const colIndex = col - startCol;
948
+ if (skipCols.has(colIndex)) continue;
949
+ const cellRef = this.xlsx.utils.encode_cell({
950
+ r: row,
951
+ c: col
952
+ });
953
+ const cell = sheet[cellRef];
954
+ if (!cell) continue;
955
+ const cellValue = this.getCellValue(cell);
956
+ if (!cellValue) continue;
957
+ const cellFormula = cell.f;
958
+ if (alwaysRedactCols.has(colIndex)) {
959
+ const detection = {
960
+ type: "SENSITIVE_COLUMN",
961
+ value: cellValue,
962
+ placeholder: `[SENSITIVE_COLUMN_${colIndex}]`,
963
+ position: [0, cellValue.length],
964
+ severity: "high",
965
+ confidence: 1
966
+ };
967
+ matchesByCell.push({
968
+ cell: cellRef,
969
+ row: row + 1,
970
+ column: colIndex,
971
+ columnLetter: this.columnToLetter(colIndex),
972
+ columnName: headers?.[colIndex],
973
+ value: cellValue,
974
+ formula: cellFormula,
975
+ matches: [detection]
976
+ });
977
+ columnStats[colIndex].piiCount++;
978
+ continue;
979
+ }
980
+ const result = await detector.detect(cellValue);
981
+ if (result.detections.length > 0) {
982
+ const boostedDetections = this.boostConfidenceFromColumnName(result.detections, headers?.[colIndex], options.piiIndicatorNames || []);
983
+ matchesByCell.push({
984
+ cell: cellRef,
985
+ row: row + 1,
986
+ column: colIndex,
987
+ columnLetter: this.columnToLetter(colIndex),
988
+ columnName: headers?.[colIndex],
989
+ value: cellValue,
990
+ formula: cellFormula,
991
+ matches: boostedDetections
992
+ });
993
+ columnStats[colIndex].piiCount += boostedDetections.length;
994
+ const columnTypes = new Set(columnStats[colIndex].piiTypes);
995
+ boostedDetections.forEach((d) => columnTypes.add(d.type));
996
+ columnStats[colIndex].piiTypes = Array.from(columnTypes);
997
+ }
998
+ }
999
+ const dataRowCount = endRow - dataStartRow + 1;
1000
+ for (let col = 0; col <= endCol - startCol; col++) {
1001
+ const rowsWithPii = matchesByCell.filter((m) => m.column === col).length;
1002
+ columnStats[col].piiPercentage = dataRowCount > 0 ? rowsWithPii / dataRowCount * 100 : 0;
1003
+ }
1004
+ return {
1005
+ sheetName,
1006
+ sheetIndex,
1007
+ rowCount: dataRowCount,
1008
+ columnCount,
1009
+ headers: headers?.filter((h) => h !== void 0),
1010
+ columnStats,
1011
+ matchesByCell
1012
+ };
1013
+ }
1014
+ /**
1015
+ * Redact PII in XLSX data
1016
+ */
1017
+ redact(buffer, detectionResult, options) {
1018
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1019
+ const opts = {
1020
+ ...this.defaultOptions,
1021
+ ...options
1022
+ };
1023
+ const workbook = this.parse(buffer);
1024
+ for (const sheetResult of detectionResult.sheetResults) {
1025
+ const sheet = workbook.Sheets[sheetResult.sheetName];
1026
+ for (const cellMatch of sheetResult.matchesByCell) {
1027
+ const cell = sheet[cellMatch.cell];
1028
+ if (!cell) continue;
1029
+ cell.v = "[REDACTED]";
1030
+ cell.w = "[REDACTED]";
1031
+ if (!opts.preserveFormulas) delete cell.f;
1032
+ cell.t = "s";
1033
+ }
1034
+ }
1035
+ return this.xlsx.write(workbook, {
1036
+ type: "buffer",
1037
+ bookType: "xlsx"
1038
+ });
1039
+ }
1040
+ /**
1041
+ * Get cell value as string
1042
+ */
1043
+ getCellValue(cell) {
1044
+ if (!cell) return "";
1045
+ if (cell.w !== void 0) return String(cell.w);
1046
+ if (cell.v !== void 0) return String(cell.v);
1047
+ return "";
1048
+ }
1049
+ /**
1050
+ * Get row values
1051
+ */
1052
+ getRowValues(sheet, row, startCol, endCol) {
1053
+ const values = [];
1054
+ for (let col = startCol; col <= endCol; col++) {
1055
+ const cell = sheet[this.xlsx.utils.encode_cell({
1056
+ r: row,
1057
+ c: col
1058
+ })];
1059
+ values.push(cell ? this.getCellValue(cell) : void 0);
1060
+ }
1061
+ return values;
1062
+ }
1063
+ /**
1064
+ * Detect if first row is likely a header
1065
+ */
1066
+ detectHeader(sheet, range) {
1067
+ const firstRow = this.getRowValues(sheet, range.s.r, range.s.c, range.e.c);
1068
+ const secondRow = range.s.r + 1 <= range.e.r ? this.getRowValues(sheet, range.s.r + 1, range.s.c, range.e.c) : null;
1069
+ if (!secondRow) return false;
1070
+ const firstRowValues = firstRow.filter((v) => v !== void 0);
1071
+ const secondRowValues = secondRow.filter((v) => v !== void 0);
1072
+ if (firstRowValues.length === 0 || secondRowValues.length === 0) return false;
1073
+ if (firstRowValues.reduce((sum, v) => sum + v.length, 0) / firstRowValues.length > secondRowValues.reduce((sum, v) => sum + v.length, 0) / secondRowValues.length * 1.5) return false;
1074
+ const firstRowNumeric = firstRowValues.filter((v) => !isNaN(Number(v)) && v.trim() !== "").length;
1075
+ return firstRowValues.length - firstRowNumeric >= firstRowNumeric;
1076
+ }
1077
+ /**
1078
+ * Convert column index to letter (0 = A, 25 = Z, 26 = AA)
1079
+ */
1080
+ columnToLetter(col) {
1081
+ let letter = "";
1082
+ while (col >= 0) {
1083
+ letter = String.fromCharCode(col % 26 + 65) + letter;
1084
+ col = Math.floor(col / 26) - 1;
1085
+ }
1086
+ return letter;
1087
+ }
1088
+ /**
1089
+ * Get sheet names to process based on options
1090
+ */
1091
+ getSheetNamesToProcess(workbook, options) {
1092
+ const allSheetNames = workbook.SheetNames;
1093
+ if (options.sheets && options.sheets.length > 0) return options.sheets.filter((name) => allSheetNames.includes(name));
1094
+ if (options.sheetIndices && options.sheetIndices.length > 0) return options.sheetIndices.filter((index) => index >= 0 && index < allSheetNames.length).map((index) => allSheetNames[index]);
1095
+ return allSheetNames;
1096
+ }
1097
+ /**
1098
+ * Boost confidence if column name indicates PII
1099
+ */
1100
+ boostConfidenceFromColumnName(detections, columnName, piiIndicatorNames) {
1101
+ if (!columnName) return detections;
1102
+ const nameLower = columnName.toLowerCase().trim();
1103
+ if (!piiIndicatorNames.some((indicator) => nameLower.includes(indicator.toLowerCase()))) return detections;
1104
+ return detections.map((detection) => ({
1105
+ ...detection,
1106
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
1107
+ }));
1108
+ }
1109
+ /**
1110
+ * Extract all cell values as text
1111
+ */
1112
+ extractText(buffer, options) {
1113
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1114
+ const workbook = this.parse(buffer);
1115
+ const opts = {
1116
+ ...this.defaultOptions,
1117
+ ...options
1118
+ };
1119
+ const sheetNames = this.getSheetNamesToProcess(workbook, opts);
1120
+ const textParts = [];
1121
+ for (const sheetName of sheetNames) {
1122
+ const sheet = workbook.Sheets[sheetName];
1123
+ const range = this.xlsx.utils.decode_range(sheet["!ref"] || "A1");
1124
+ for (let row = range.s.r; row <= range.e.r; row++) for (let col = range.s.c; col <= range.e.c; col++) {
1125
+ const cell = sheet[this.xlsx.utils.encode_cell({
1126
+ r: row,
1127
+ c: col
1128
+ })];
1129
+ if (cell) {
1130
+ const value = this.getCellValue(cell);
1131
+ if (value.trim().length > 0) textParts.push(value);
1132
+ }
1133
+ }
1134
+ }
1135
+ return textParts.join(" ");
1136
+ }
1137
+ /**
1138
+ * Get workbook metadata
1139
+ */
1140
+ getMetadata(buffer) {
1141
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1142
+ const workbook = this.parse(buffer);
1143
+ return {
1144
+ sheetNames: workbook.SheetNames,
1145
+ sheetCount: workbook.SheetNames.length
1146
+ };
1147
+ }
1148
+ };
1149
+ /**
1150
+ * Create an XLSX processor instance
1151
+ */
1152
+ function createXlsxProcessor() {
1153
+ return new XlsxProcessor();
1154
+ }
1155
+
1156
+ //#endregion
1157
+ //#region src/document/DocumentProcessor.ts
1158
+ /**
1159
+ * Document processor with optional PDF, DOCX, OCR, JSON, CSV, and XLSX support
1160
+ * Requires peer dependencies:
1161
+ * - pdf-parse (for PDF)
1162
+ * - mammoth (for DOCX)
1163
+ * - tesseract.js (for OCR/images)
1164
+ * - xlsx (for Excel/XLSX)
1165
+ */
1166
+ var DocumentProcessor = class {
1167
+ constructor() {
1168
+ try {
1169
+ this.pdfParse = require("pdf-parse");
1170
+ } catch {}
1171
+ try {
1172
+ this.mammoth = require("mammoth");
1173
+ } catch {}
1174
+ this.ocrProcessor = new OCRProcessor();
1175
+ this.jsonProcessor = new JsonProcessor();
1176
+ this.csvProcessor = new CsvProcessor();
1177
+ this.xlsxProcessor = new XlsxProcessor();
1178
+ }
1179
+ /**
1180
+ * Extract text from document buffer
1181
+ */
1182
+ async extractText(buffer, options) {
1183
+ const format = options?.format || this.detectFormat(buffer);
1184
+ if (!format) throw new Error("[DocumentProcessor] Unable to detect document format. Supported: PDF, DOCX, TXT, images (with OCR)");
1185
+ const maxSize = options?.maxSize || 50 * 1024 * 1024;
1186
+ if (buffer.length > maxSize) throw new Error(`[DocumentProcessor] Document size (${buffer.length} bytes) exceeds maximum (${maxSize} bytes)`);
1187
+ switch (format) {
1188
+ case "pdf": return this.extractPdfText(buffer, options);
1189
+ case "docx": return this.extractDocxText(buffer, options);
1190
+ case "txt": return buffer.toString("utf-8");
1191
+ case "image": return this.extractImageText(buffer, options);
1192
+ case "json": return this.extractJsonText(buffer, options);
1193
+ case "csv": return this.extractCsvText(buffer, options);
1194
+ case "xlsx": return this.extractXlsxText(buffer, options);
1195
+ default: throw new Error(`[DocumentProcessor] Unsupported format: ${format}`);
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Get document metadata
1200
+ */
1201
+ async getMetadata(buffer, options) {
1202
+ const format = options?.format || this.detectFormat(buffer);
1203
+ if (!format) throw new Error("[DocumentProcessor] Unable to detect document format");
1204
+ switch (format) {
1205
+ case "pdf": return this.getPdfMetadata(buffer, options);
1206
+ case "docx": return this.getDocxMetadata(buffer, options);
1207
+ case "txt": return {
1208
+ format: "txt",
1209
+ pages: void 0
1210
+ };
1211
+ case "image": return this.getImageMetadata(buffer, options);
1212
+ case "json": return this.getJsonMetadata(buffer, options);
1213
+ case "csv": return this.getCsvMetadata(buffer, options);
1214
+ case "xlsx": return this.getXlsxMetadata(buffer, options);
1215
+ default: throw new Error(`[DocumentProcessor] Unsupported format: ${format}`);
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Detect document format from buffer
1220
+ */
1221
+ detectFormat(buffer) {
1222
+ if (buffer.length < 4) return null;
1223
+ if (buffer.toString("utf-8", 0, 4) === "%PDF") return "pdf";
1224
+ if (buffer.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71) return "image";
1225
+ if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return "image";
1226
+ if (buffer[0] === 73 && buffer[1] === 73 && buffer[2] === 42 && buffer[3] === 0 || buffer[0] === 77 && buffer[1] === 77 && buffer[2] === 0 && buffer[3] === 42) return "image";
1227
+ if (buffer[0] === 66 && buffer[1] === 77) return "image";
1228
+ if (buffer.length >= 12 && buffer[0] === 82 && buffer[1] === 73 && buffer[2] === 70 && buffer[3] === 70 && buffer[8] === 87 && buffer[9] === 69 && buffer[10] === 66 && buffer[11] === 80) return "image";
1229
+ if (buffer[0] === 80 && buffer[1] === 75) {
1230
+ const zipHeader = buffer.toString("utf-8", 0, Math.min(500, buffer.length));
1231
+ if (zipHeader.includes("word/") || zipHeader.includes("[Content_Types].xml")) return "docx";
1232
+ if (zipHeader.includes("xl/")) return "xlsx";
1233
+ }
1234
+ const text = buffer.toString("utf-8");
1235
+ const trimmed = text.trim();
1236
+ if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
1237
+ if (this.jsonProcessor.isValid(buffer)) return "json";
1238
+ }
1239
+ const lines = text.split(/\r?\n/).slice(0, 5);
1240
+ if (lines.length >= 2) for (const delimiter of [
1241
+ ",",
1242
+ " ",
1243
+ ";",
1244
+ "|"
1245
+ ]) {
1246
+ const counts = lines.map((line) => (line.match(new RegExp(delimiter, "g")) || []).length);
1247
+ if (counts[0] > 0 && counts.every((c) => c === counts[0])) return "csv";
1248
+ }
1249
+ const sample = buffer.slice(0, Math.min(1e3, buffer.length));
1250
+ if (sample.filter((byte) => byte < 32 && byte !== 9 && byte !== 10 && byte !== 13).length < sample.length * .1) return "txt";
1251
+ return null;
1252
+ }
1253
+ /**
1254
+ * Check if format is supported
1255
+ */
1256
+ isFormatSupported(format) {
1257
+ switch (format) {
1258
+ case "pdf": return !!this.pdfParse;
1259
+ case "docx": return !!this.mammoth;
1260
+ case "txt": return true;
1261
+ case "image": return this.ocrProcessor.isAvailable();
1262
+ case "json": return true;
1263
+ case "csv": return true;
1264
+ case "xlsx": return this.xlsxProcessor.isAvailable();
1265
+ default: return false;
1266
+ }
1267
+ }
1268
+ /**
1269
+ * Extract text from PDF
1270
+ */
1271
+ async extractPdfText(buffer, options) {
1272
+ if (!this.pdfParse) throw new Error("[DocumentProcessor] PDF support requires pdf-parse. Install with: npm install pdf-parse");
1273
+ try {
1274
+ const data = await this.pdfParse(buffer, {
1275
+ password: options?.password,
1276
+ max: options?.pages ? Math.max(...options.pages) : void 0
1277
+ });
1278
+ if (options?.pages) return data.text;
1279
+ return data.text || "";
1280
+ } catch (error) {
1281
+ throw new Error(`[DocumentProcessor] PDF extraction failed: ${error.message}`);
1282
+ }
1283
+ }
1284
+ /**
1285
+ * Extract text from DOCX
1286
+ */
1287
+ async extractDocxText(buffer, _options) {
1288
+ if (!this.mammoth) throw new Error("[DocumentProcessor] DOCX support requires mammoth. Install with: npm install mammoth");
1289
+ try {
1290
+ return (await this.mammoth.extractRawText({ buffer })).value || "";
1291
+ } catch (error) {
1292
+ throw new Error(`[DocumentProcessor] DOCX extraction failed: ${error.message}`);
1293
+ }
1294
+ }
1295
+ /**
1296
+ * Get PDF metadata
1297
+ */
1298
+ async getPdfMetadata(buffer, _options) {
1299
+ if (!this.pdfParse) throw new Error("[DocumentProcessor] PDF support requires pdf-parse. Install with: npm install pdf-parse");
1300
+ try {
1301
+ const data = await this.pdfParse(buffer, { password: _options?.password });
1302
+ return {
1303
+ format: "pdf",
1304
+ pages: data.numpages,
1305
+ title: data.info?.Title,
1306
+ author: data.info?.Author,
1307
+ creationDate: data.info?.CreationDate ? new Date(data.info.CreationDate) : void 0,
1308
+ modifiedDate: data.info?.ModDate ? new Date(data.info.ModDate) : void 0,
1309
+ custom: data.info
1310
+ };
1311
+ } catch (error) {
1312
+ throw new Error(`[DocumentProcessor] PDF metadata extraction failed: ${error.message}`);
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Get DOCX metadata
1317
+ */
1318
+ async getDocxMetadata(_buffer, _options) {
1319
+ return {
1320
+ format: "docx",
1321
+ pages: void 0
1322
+ };
1323
+ }
1324
+ /**
1325
+ * Extract text from image using OCR
1326
+ */
1327
+ async extractImageText(buffer, options) {
1328
+ if (!this.ocrProcessor.isAvailable()) throw new Error("[DocumentProcessor] Image/OCR support requires tesseract.js. Install with: npm install tesseract.js");
1329
+ try {
1330
+ return (await this.ocrProcessor.recognizeText(buffer, options?.ocrOptions)).text;
1331
+ } catch (error) {
1332
+ throw new Error(`[DocumentProcessor] Image text extraction failed: ${error.message}`);
1333
+ }
1334
+ }
1335
+ /**
1336
+ * Get image metadata
1337
+ */
1338
+ async getImageMetadata(buffer, options) {
1339
+ if (!this.ocrProcessor.isAvailable()) return {
1340
+ format: "image",
1341
+ pages: void 0,
1342
+ usedOCR: false
1343
+ };
1344
+ try {
1345
+ return {
1346
+ format: "image",
1347
+ pages: void 0,
1348
+ usedOCR: true,
1349
+ ocrConfidence: (await this.ocrProcessor.recognizeText(buffer, options?.ocrOptions)).confidence
1350
+ };
1351
+ } catch {
1352
+ return {
1353
+ format: "image",
1354
+ pages: void 0,
1355
+ usedOCR: false
1356
+ };
1357
+ }
1358
+ }
1359
+ /**
1360
+ * Extract text from JSON
1361
+ */
1362
+ async extractJsonText(buffer, _options) {
1363
+ try {
1364
+ return this.jsonProcessor.extractText(buffer);
1365
+ } catch (error) {
1366
+ throw new Error(`[DocumentProcessor] JSON extraction failed: ${error.message}`);
1367
+ }
1368
+ }
1369
+ /**
1370
+ * Extract text from CSV
1371
+ */
1372
+ async extractCsvText(buffer, _options) {
1373
+ try {
1374
+ return this.csvProcessor.extractText(buffer);
1375
+ } catch (error) {
1376
+ throw new Error(`[DocumentProcessor] CSV extraction failed: ${error.message}`);
1377
+ }
1378
+ }
1379
+ /**
1380
+ * Extract text from XLSX
1381
+ */
1382
+ async extractXlsxText(buffer, _options) {
1383
+ if (!this.xlsxProcessor.isAvailable()) throw new Error("[DocumentProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1384
+ try {
1385
+ return this.xlsxProcessor.extractText(buffer);
1386
+ } catch (error) {
1387
+ throw new Error(`[DocumentProcessor] XLSX extraction failed: ${error.message}`);
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Get JSON metadata
1392
+ */
1393
+ async getJsonMetadata(buffer, _options) {
1394
+ try {
1395
+ const data = this.jsonProcessor.parse(buffer);
1396
+ const isArray = Array.isArray(data);
1397
+ return {
1398
+ format: "json",
1399
+ pages: void 0,
1400
+ custom: {
1401
+ isArray,
1402
+ itemCount: isArray ? data.length : Object.keys(data).length
1403
+ }
1404
+ };
1405
+ } catch {
1406
+ return {
1407
+ format: "json",
1408
+ pages: void 0
1409
+ };
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Get CSV metadata
1414
+ */
1415
+ async getCsvMetadata(buffer, _options) {
1416
+ try {
1417
+ const info = this.csvProcessor.getColumnInfo(buffer);
1418
+ return {
1419
+ format: "csv",
1420
+ pages: void 0,
1421
+ custom: {
1422
+ rowCount: info.rowCount,
1423
+ columnCount: info.columnCount,
1424
+ headers: info.headers
1425
+ }
1426
+ };
1427
+ } catch {
1428
+ return {
1429
+ format: "csv",
1430
+ pages: void 0
1431
+ };
1432
+ }
1433
+ }
1434
+ /**
1435
+ * Get XLSX metadata
1436
+ */
1437
+ async getXlsxMetadata(buffer, _options) {
1438
+ if (!this.xlsxProcessor.isAvailable()) return {
1439
+ format: "xlsx",
1440
+ pages: void 0
1441
+ };
1442
+ try {
1443
+ const metadata = this.xlsxProcessor.getMetadata(buffer);
1444
+ return {
1445
+ format: "xlsx",
1446
+ pages: void 0,
1447
+ custom: {
1448
+ sheetNames: metadata.sheetNames,
1449
+ sheetCount: metadata.sheetCount
1450
+ }
1451
+ };
1452
+ } catch {
1453
+ return {
1454
+ format: "xlsx",
1455
+ pages: void 0
1456
+ };
1457
+ }
1458
+ }
1459
+ /**
1460
+ * Get OCR processor instance
1461
+ */
1462
+ getOCRProcessor() {
1463
+ return this.ocrProcessor;
1464
+ }
1465
+ /**
1466
+ * Get JSON processor instance
1467
+ */
1468
+ getJsonProcessor() {
1469
+ return this.jsonProcessor;
1470
+ }
1471
+ /**
1472
+ * Get CSV processor instance
1473
+ */
1474
+ getCsvProcessor() {
1475
+ return this.csvProcessor;
1476
+ }
1477
+ /**
1478
+ * Get XLSX processor instance
1479
+ */
1480
+ getXlsxProcessor() {
1481
+ return this.xlsxProcessor;
1482
+ }
1483
+ };
1484
+ /**
1485
+ * Create a document processor instance
1486
+ */
1487
+ function createDocumentProcessor() {
1488
+ return new DocumentProcessor();
1489
+ }
1490
+
1491
+ //#endregion
1492
+ Object.defineProperty(exports, 'CsvProcessor', {
1493
+ enumerable: true,
1494
+ get: function () {
1495
+ return CsvProcessor;
1496
+ }
1497
+ });
1498
+ Object.defineProperty(exports, 'DocumentProcessor', {
1499
+ enumerable: true,
1500
+ get: function () {
1501
+ return DocumentProcessor;
1502
+ }
1503
+ });
1504
+ Object.defineProperty(exports, 'JsonProcessor', {
1505
+ enumerable: true,
1506
+ get: function () {
1507
+ return JsonProcessor;
1508
+ }
1509
+ });
1510
+ Object.defineProperty(exports, 'OCRProcessor', {
1511
+ enumerable: true,
1512
+ get: function () {
1513
+ return OCRProcessor;
1514
+ }
1515
+ });
1516
+ Object.defineProperty(exports, 'XlsxProcessor', {
1517
+ enumerable: true,
1518
+ get: function () {
1519
+ return XlsxProcessor;
1520
+ }
1521
+ });
1522
+ Object.defineProperty(exports, 'createCsvProcessor', {
1523
+ enumerable: true,
1524
+ get: function () {
1525
+ return createCsvProcessor;
1526
+ }
1527
+ });
1528
+ Object.defineProperty(exports, 'createDocumentProcessor', {
1529
+ enumerable: true,
1530
+ get: function () {
1531
+ return createDocumentProcessor;
1532
+ }
1533
+ });
1534
+ Object.defineProperty(exports, 'createJsonProcessor', {
1535
+ enumerable: true,
1536
+ get: function () {
1537
+ return createJsonProcessor;
1538
+ }
1539
+ });
1540
+ Object.defineProperty(exports, 'createOCRProcessor', {
1541
+ enumerable: true,
1542
+ get: function () {
1543
+ return createOCRProcessor;
1544
+ }
1545
+ });
1546
+ Object.defineProperty(exports, 'createXlsxProcessor', {
1547
+ enumerable: true,
1548
+ get: function () {
1549
+ return createXlsxProcessor;
1550
+ }
1551
+ });
1552
+ //# sourceMappingURL=document-C4T2JLdu.js.map