@d0paminedriven/fs 10.0.0 → 11.0.0

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.
Files changed (60) hide show
  1. package/dist/docs/index.d.ts +119 -0
  2. package/dist/docs/index.js +1027 -0
  3. package/dist/extract/client.d.ts +54 -0
  4. package/dist/extract/client.js +118 -0
  5. package/dist/extract/index.d.ts +69 -0
  6. package/dist/extract/index.js +622 -0
  7. package/dist/fs/index.d.ts +19 -55
  8. package/dist/fs/index.js +88 -19
  9. package/dist/fs-atomic/index.d.ts +28 -36
  10. package/dist/fs-atomic/index.js +88 -13
  11. package/dist/fs-base/index.d.ts +105 -111
  12. package/dist/fs-base/index.js +188 -12
  13. package/dist/fs-core/index.d.ts +20 -24
  14. package/dist/fs-core/index.js +44 -16
  15. package/dist/fs-fetch/index.d.ts +48 -62
  16. package/dist/fs-fetch/index.js +146 -18
  17. package/dist/fs-size/index.d.ts +16 -28
  18. package/dist/fs-size/index.js +64 -15
  19. package/dist/fs-tmp/index.d.ts +179 -192
  20. package/dist/fs-tmp/index.js +321 -17
  21. package/dist/images/index.d.ts +447 -0
  22. package/dist/images/index.js +899 -0
  23. package/dist/images/workup.d.ts +30 -0
  24. package/dist/images/workup.js +317 -0
  25. package/dist/index.d.ts +20 -22
  26. package/dist/index.js +20 -64
  27. package/dist/ld/index.d.ts +15 -13
  28. package/dist/ld/index.js +56 -6
  29. package/dist/mime/index.d.ts +299 -294
  30. package/dist/mime/index.js +348 -13
  31. package/dist/mixins/index.d.ts +34 -0
  32. package/dist/mixins/index.js +54 -0
  33. package/dist/types/index.d.ts +279 -215
  34. package/dist/types/index.js +11 -6
  35. package/dist/types/stream.d.ts +6 -4
  36. package/dist/types/stream.js +1 -1
  37. package/dist/url/index.d.ts +15 -18
  38. package/dist/url/index.js +21 -8
  39. package/dist/utils/index.d.ts +19 -23
  40. package/dist/utils/index.js +82 -7
  41. package/package.json +33 -13
  42. package/dist/chunk-5CACVZVF.js +0 -386
  43. package/dist/chunk-5H6GE5AO.js +0 -14
  44. package/dist/chunk-7JQ56XIH.js +0 -187
  45. package/dist/chunk-7LOAFIZM.js +0 -77
  46. package/dist/chunk-7QVYU63E.js +0 -7
  47. package/dist/chunk-DNR5ZI2T.js +0 -75
  48. package/dist/chunk-L2QMQOEJ.js +0 -366
  49. package/dist/chunk-NJHN5OE3.js +0 -33
  50. package/dist/chunk-OHKRQJZH.js +0 -82
  51. package/dist/chunk-OT5JEQKW.js +0 -139
  52. package/dist/chunk-PATMSIQK.js +0 -367
  53. package/dist/chunk-PB5A7ZFD.js +0 -79
  54. package/dist/chunk-VDKUXJE7.js +0 -240
  55. package/dist/chunk-Y5QWE4EG.js +0 -1335
  56. package/dist/chunk-YRCJWFZD.js +0 -107
  57. package/dist/image/index.d.ts +0 -182
  58. package/dist/image/index.js +0 -13
  59. package/dist/image/workup.d.ts +0 -40
  60. package/dist/image/workup.js +0 -12
@@ -0,0 +1,1027 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { relative } from "node:path";
3
+ import { inflateSync } from "fflate";
4
+
5
+ //#region src/docs/index.ts
6
+ var DocMetadataExtractor = class {
7
+ toSafeString(buf, encoding = "utf-8") {
8
+ try {
9
+ return new TextDecoder(encoding, { fatal: false }).decode(buf);
10
+ } catch {
11
+ return Array.from(buf).map((b) => String.fromCharCode(b)).join("");
12
+ }
13
+ }
14
+ detectTextEncodingPrefix(buffer) {
15
+ if (buffer.length >= 3 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) return {
16
+ encoding: "utf-8",
17
+ offset: 3
18
+ };
19
+ if (buffer.length >= 2 && buffer[0] === 255 && buffer[1] === 254) return {
20
+ encoding: "utf-16le",
21
+ offset: 2
22
+ };
23
+ if (buffer.length >= 2 && buffer[0] === 254 && buffer[1] === 255) return {
24
+ encoding: "utf-16be",
25
+ offset: 2
26
+ };
27
+ return {
28
+ encoding: "utf-8",
29
+ offset: 0
30
+ };
31
+ }
32
+ detectAndDecodeText(buffer) {
33
+ const { encoding, offset } = this.detectTextEncodingPrefix(buffer);
34
+ const body = buffer.subarray(offset);
35
+ if (encoding === "utf-8" && offset === 0) try {
36
+ return new TextDecoder("utf-8", { fatal: true }).decode(body);
37
+ } catch {
38
+ return new TextDecoder("windows-1252", { fatal: false }).decode(body);
39
+ }
40
+ return this.toSafeString(body, encoding);
41
+ }
42
+ _stripXmlTags(xml) {
43
+ return xml.replace(/<\/?[^>]+>/g, " ").replace(/\s+/g, " ").trim();
44
+ }
45
+ getExtFromFilename(filename) {
46
+ if (!filename) return null;
47
+ const i = filename.lastIndexOf(".");
48
+ if (i === -1) return null;
49
+ return filename.slice(i + 1).toLowerCase();
50
+ }
51
+ firstN(text, n = 240) {
52
+ if (!text) return null;
53
+ const t = text.slice(0, n);
54
+ return t.length < text.length ? `${t}…` : t;
55
+ }
56
+ countWords(text) {
57
+ const words = text.trim().match(/[\p{L}\p{N}_]+/gu);
58
+ return words ? words.length : 0;
59
+ }
60
+ countLines(text) {
61
+ if (!text) return 0;
62
+ return text.replace(/\r\n/g, "\n").split("\n").length;
63
+ }
64
+ extToLanguage(ext) {
65
+ if (!ext) return null;
66
+ return {
67
+ js: "javascript",
68
+ jsx: "javascript",
69
+ ts: "typescript",
70
+ tsx: "typescript",
71
+ py: "python",
72
+ rb: "ruby",
73
+ rs: "rust",
74
+ go: "go",
75
+ java: "java",
76
+ c: "c",
77
+ h: "c",
78
+ cpp: "cpp",
79
+ hpp: "cpp",
80
+ cs: "csharp",
81
+ php: "php",
82
+ swift: "swift",
83
+ kotlin: "kotlin",
84
+ kt: "kotlin",
85
+ m: "objective-c",
86
+ mm: "objective-c++",
87
+ sh: "bash",
88
+ bash: "bash",
89
+ zsh: "bash",
90
+ json: "json",
91
+ yml: "yaml",
92
+ yaml: "yaml",
93
+ md: "markdown",
94
+ markdown: "markdown",
95
+ html: "html",
96
+ css: "css",
97
+ scss: "scss",
98
+ less: "less",
99
+ sql: "sql",
100
+ csv: "csv",
101
+ txt: "text",
102
+ tex: "tex"
103
+ }[ext] ?? null;
104
+ }
105
+ /**
106
+ * Decompress FlateDecode streams to search for page info
107
+ * Many modern PDFs compress their object streams
108
+ */
109
+ decompressFlateStreams(buffer) {
110
+ const decompressed = [];
111
+ const text = buffer.toString("latin1");
112
+ const streamPattern = /<<[^>]*\/Filter\s*\/FlateDecode[^>]*>>[\r\n]*stream\r?\n/g;
113
+ let match;
114
+ while ((match = streamPattern.exec(text)) !== null) try {
115
+ const streamStart = match.index + match[0].length;
116
+ const endstreamPos = text.indexOf("endstream", streamStart);
117
+ if (endstreamPos === -1) continue;
118
+ const compressedData = buffer.subarray(streamStart, endstreamPos);
119
+ let dataEnd = compressedData.length;
120
+ while (dataEnd > 0 && (compressedData[dataEnd - 1] === 10 || compressedData[dataEnd - 1] === 13 || compressedData[dataEnd - 1] === 32)) dataEnd--;
121
+ const trimmedData = compressedData.subarray(0, dataEnd);
122
+ const inflated = inflateSync(new Uint8Array(trimmedData));
123
+ decompressed.push(Buffer.from(inflated).toString("latin1"));
124
+ } catch {
125
+ continue;
126
+ }
127
+ return decompressed;
128
+ }
129
+ /**
130
+ * Parse Object Streams (/Type /ObjStm) used by Acrobat-optimized PDFs
131
+ * These bundle multiple objects into compressed containers
132
+ */
133
+ parseObjectStreams(buffer, text) {
134
+ const extractedObjects = [];
135
+ const objStmPattern = /(\d+)\s+\d+\s+obj[^]*?\/Type\s*\/ObjStm[^]*?\/N\s+(\d+)[^]*?\/First\s+(\d+)[^]*?stream\r?\n/g;
136
+ let match;
137
+ while ((match = objStmPattern.exec(text)) !== null) try {
138
+ if (!match[2] || !match[3]) continue;
139
+ const numObjects = parseInt(match[2], 10);
140
+ const firstOffset = parseInt(match[3], 10);
141
+ if (numObjects <= 0 || numObjects > 1e4) continue;
142
+ if (firstOffset < 0 || firstOffset > 1e6) continue;
143
+ const streamStart = match.index + match[0].length;
144
+ const endstreamPos = text.indexOf("endstream", streamStart);
145
+ if (endstreamPos === -1) continue;
146
+ const compressedData = buffer.subarray(streamStart, endstreamPos);
147
+ let dataEnd = compressedData.length;
148
+ while (dataEnd > 0 && (compressedData[dataEnd - 1] === 10 || compressedData[dataEnd - 1] === 13 || compressedData[dataEnd - 1] === 32)) dataEnd--;
149
+ const trimmedData = compressedData.subarray(0, dataEnd);
150
+ const decompressed = inflateSync(new Uint8Array(trimmedData));
151
+ const decompressedStr = Buffer.from(decompressed).toString("latin1");
152
+ if (firstOffset < decompressedStr.length) {
153
+ const objectData = decompressedStr.slice(firstOffset);
154
+ extractedObjects.push(objectData);
155
+ }
156
+ } catch {
157
+ continue;
158
+ }
159
+ return extractedObjects;
160
+ }
161
+ /**
162
+ * Parse cross-reference table to find object offsets
163
+ */
164
+ parseXrefTable(text) {
165
+ const objects = /* @__PURE__ */ new Map();
166
+ const xrefMatch = text.match(/xref\s+([\s\S]*?)trailer/);
167
+ if (xrefMatch?.[1]) {
168
+ const lines = xrefMatch[1].trim().split(/\r?\n/);
169
+ let currentObj = 0;
170
+ for (const line of lines) {
171
+ const subsection = line.match(/^(\d+)\s+(\d+)\s*$/);
172
+ if (subsection?.[1]) {
173
+ currentObj = parseInt(subsection[1], 10);
174
+ continue;
175
+ }
176
+ const entry = line.match(/^(\d{10})\s+(\d{5})\s+([fn])/);
177
+ if (entry?.[3] === "n" && entry[1] && entry[2]) objects.set(currentObj, {
178
+ offset: parseInt(entry[1], 10),
179
+ gen: parseInt(entry[2], 10)
180
+ });
181
+ currentObj++;
182
+ }
183
+ }
184
+ return objects;
185
+ }
186
+ /**
187
+ * Parse PDF 1.5+ cross-reference streams (/Type /XRef)
188
+ * These replace traditional xref tables in modern PDFs
189
+ */
190
+ parseXrefStream(buffer, text) {
191
+ const objects = /* @__PURE__ */ new Map();
192
+ const xrefStreamMatch = text.match(/<<[^>]*\/Type\s*\/XRef[^>]*\/W\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s*\][^>]*>>[\r\n]*stream\r?\n/);
193
+ if (!xrefStreamMatch?.[1] || !xrefStreamMatch[2] || !xrefStreamMatch[3]) return objects;
194
+ const w1 = parseInt(xrefStreamMatch[1], 10);
195
+ const w2 = parseInt(xrefStreamMatch[2], 10);
196
+ const w3 = parseInt(xrefStreamMatch[3], 10);
197
+ const entrySize = w1 + w2 + w3;
198
+ if (entrySize <= 0 || entrySize > 20) return objects;
199
+ const sizeMatch = text.match(/\/Size\s+(\d+)/);
200
+ const size = sizeMatch?.[1] ? parseInt(sizeMatch[1], 10) : 0;
201
+ if (size <= 0) return objects;
202
+ const indexMatch = text.match(/\/Index\s*\[\s*([\d\s]+)\s*\]/);
203
+ let indices = [];
204
+ if (indexMatch?.[1]) indices = indexMatch[1].trim().split(/\s+/).map((n) => parseInt(n, 10));
205
+ try {
206
+ if (xrefStreamMatch.index === void 0) return objects;
207
+ const streamStart = xrefStreamMatch.index + xrefStreamMatch[0].length;
208
+ const endstreamPos = text.indexOf("endstream", streamStart);
209
+ if (endstreamPos === -1) return objects;
210
+ const compressedData = buffer.subarray(streamStart, endstreamPos);
211
+ let dataEnd = compressedData.length;
212
+ while (dataEnd > 0 && (compressedData[dataEnd - 1] === 10 || compressedData[dataEnd - 1] === 13 || compressedData[dataEnd - 1] === 32)) dataEnd--;
213
+ const trimmedData = compressedData.subarray(0, dataEnd);
214
+ const decompressed = inflateSync(new Uint8Array(trimmedData));
215
+ let entryIndex = 0;
216
+ if (indices.length >= 2) for (let i = 0; i < indices.length; i += 2) {
217
+ const start = indices[i] ?? 0;
218
+ const count = indices[i + 1] ?? 0;
219
+ for (let j = 0; j < count && entryIndex * entrySize < decompressed.length; j++) {
220
+ const offset = entryIndex * entrySize;
221
+ let type = 0;
222
+ for (let k = 0; k < w1; k++) type = type << 8 | (decompressed[offset + k] ?? 0);
223
+ if (type === 1) {
224
+ let byteOffset = 0;
225
+ for (let k = 0; k < w2; k++) byteOffset = byteOffset << 8 | (decompressed[offset + w1 + k] ?? 0);
226
+ objects.set(start + j, byteOffset);
227
+ }
228
+ entryIndex++;
229
+ }
230
+ }
231
+ else for (let i = 0; i < size && i * entrySize < decompressed.length; i++) {
232
+ const offset = i * entrySize;
233
+ let type = 0;
234
+ for (let j = 0; j < w1; j++) type = type << 8 | (decompressed[offset + j] ?? 0);
235
+ if (type === 1) {
236
+ let byteOffset = 0;
237
+ for (let j = 0; j < w2; j++) byteOffset = byteOffset << 8 | (decompressed[offset + w1 + j] ?? 0);
238
+ objects.set(i, byteOffset);
239
+ }
240
+ }
241
+ } catch {}
242
+ return objects;
243
+ }
244
+ /**
245
+ * Extract page count from object at specific offset
246
+ */
247
+ extractPageCountFromObject(buffer, offset) {
248
+ try {
249
+ const chunk = buffer.subarray(offset, Math.min(offset + 4096, buffer.length)).toString("latin1");
250
+ if (/\/Type\s*\/Pages/.test(chunk)) {
251
+ const countMatch = chunk.match(/\/Count\s+(\d+)/);
252
+ if (countMatch?.[1]) return parseInt(countMatch[1], 10);
253
+ }
254
+ return null;
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+ /**
260
+ * Strategy 1: Direct /Pages /Count in uncompressed content (fastest, high confidence)
261
+ * Finds the ROOT Pages object by looking for the highest /Count value
262
+ */
263
+ strategy1DirectPagesCount(text) {
264
+ const patterns = [/\/Type\s*\/Pages\s*[^>]*?\/Count\s+(\d+)/g, /\/Count\s+(\d+)\s*[^>]*?\/Type\s*\/Pages/g];
265
+ let maxCount = 0;
266
+ for (const pattern of patterns) {
267
+ let match;
268
+ while ((match = pattern.exec(text)) !== null) if (match[1]) {
269
+ const count = parseInt(match[1], 10);
270
+ if (count > maxCount && count < 1e5) maxCount = count;
271
+ }
272
+ }
273
+ return maxCount > 0 ? maxCount : null;
274
+ }
275
+ /**
276
+ * Strategy 2: Linearized hint (high confidence for linearized PDFs)
277
+ * /N in the linearization dict is the total page count
278
+ */
279
+ strategy2Linearized(text) {
280
+ const header = text.slice(0, 2048);
281
+ if (/\/Linearized\s+[\d.]+/.test(header)) {
282
+ const nMatch = header.match(/\/N\s+(\d+)/);
283
+ if (nMatch?.[1]) {
284
+ const count = parseInt(nMatch[1], 10);
285
+ if (count > 0 && count < 1e5) return count;
286
+ }
287
+ }
288
+ return null;
289
+ }
290
+ /**
291
+ * Strategy 3: Follow Catalog -> Pages reference chain (high confidence)
292
+ */
293
+ strategy3CatalogChain(buffer, text) {
294
+ const catalogMatch = text.match(/\/Type\s*\/Catalog[\s\S]{0,500}?\/Pages\s+(\d+)\s+(\d+)\s+R/);
295
+ if (!catalogMatch?.[1]) return null;
296
+ const pagesObjNum = parseInt(catalogMatch[1], 10);
297
+ const objPattern = new RegExp(`(?:^|\\r|\\n)${pagesObjNum}\\s+\\d+\\s+obj[\\s\\S]*?endobj`, "m");
298
+ const objMatch = text.match(objPattern);
299
+ if (objMatch?.[0]) {
300
+ if (/\/Type\s*\/Pages/.test(objMatch[0])) {
301
+ const countMatch = objMatch[0].match(/\/Count\s+(\d+)/);
302
+ if (countMatch?.[1]) {
303
+ const count = parseInt(countMatch[1], 10);
304
+ if (count > 0 && count < 1e5) return count;
305
+ }
306
+ }
307
+ }
308
+ let pagesOffset = this.parseXrefTable(text).get(pagesObjNum);
309
+ if (!pagesOffset) {
310
+ const streamOffset = this.parseXrefStream(buffer, text).get(pagesObjNum);
311
+ if (streamOffset) pagesOffset = {
312
+ offset: streamOffset,
313
+ gen: 0
314
+ };
315
+ }
316
+ if (pagesOffset) {
317
+ const count = this.extractPageCountFromObject(buffer, pagesOffset.offset);
318
+ if (count && count > 0 && count < 1e5) return count;
319
+ }
320
+ return null;
321
+ }
322
+ /**
323
+ * Strategy 4: Decompress FlateDecode streams and Object Streams (medium confidence)
324
+ * Handles Acrobat-optimized PDFs where page tree is compressed
325
+ */
326
+ strategy4DecompressedStreams(buffer) {
327
+ const text = buffer.toString("latin1");
328
+ try {
329
+ const objStreams = this.parseObjectStreams(buffer, text);
330
+ const flateStreams = this.decompressFlateStreams(buffer);
331
+ const allDecompressed = [...objStreams, ...flateStreams];
332
+ let maxCount = 0;
333
+ for (const content of allDecompressed) for (const pattern of [/\/Type\s*\/Pages[\s\S]{0,300}?\/Count\s+(\d+)/g, /\/Count\s+(\d+)[\s\S]{0,300}?\/Type\s*\/Pages/g]) {
334
+ let match;
335
+ while ((match = pattern.exec(content)) !== null) if (match[1]) {
336
+ const count = parseInt(match[1], 10);
337
+ if (count > maxCount && count < 1e5) maxCount = count;
338
+ }
339
+ }
340
+ return maxCount > 0 ? maxCount : null;
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ /**
346
+ * Strategy 5: Count unique Page objects from Kids arrays (medium confidence)
347
+ * Only counts refs that point to actual /Type /Page objects
348
+ */
349
+ strategy5KidsPageRefs(text) {
350
+ const pageRefs = /* @__PURE__ */ new Set();
351
+ const kidsMatches = text.matchAll(/\/Kids\s*\[\s*([\s\S]*?)\s*\]/g);
352
+ const allRefs = [];
353
+ for (const match of kidsMatches) if (match[1]) {
354
+ const refs = match[1].matchAll(/(\d+)\s+\d+\s+R/g);
355
+ for (const ref of refs) if (ref[1]) allRefs.push(ref[1]);
356
+ }
357
+ for (const objNum of allRefs) if (new RegExp(`(?:^|\\r|\\n)${objNum}\\s+\\d+\\s+obj[\\s\\S]{0,500}?\\/Type\\s*\\/Page\\b(?!s)`, "m").test(text)) pageRefs.add(objNum);
358
+ return pageRefs.size > 0 ? pageRefs.size : null;
359
+ }
360
+ /**
361
+ * Strategy 6: Brute force count /Type /Page objects (low confidence)
362
+ */
363
+ strategy6BruteForce(text) {
364
+ const strictMatches = text.match(/\d+\s+\d+\s+obj[\s\S]*?\/Type\s*\/Page\b(?!s)[\s\S]*?\/(?:MediaBox|Parent)/g);
365
+ if (strictMatches && strictMatches.length > 0) return strictMatches.length;
366
+ const looseMatches = text.match(/\/Type\s*\/Page\b(?!s)/g);
367
+ return looseMatches ? looseMatches.length : null;
368
+ }
369
+ /**
370
+ * Strategy 7: Estimate from file characteristics (last resort)
371
+ */
372
+ strategy7Estimate(buffer, text) {
373
+ const fileSizeKB = buffer.length / 1024;
374
+ const hasImages = /\/XObject/.test(text) && /\/Image/.test(text);
375
+ const hasText = /BT[\s\S]*?ET/.test(text);
376
+ if (hasImages && !hasText) return Math.max(1, Math.round(fileSizeKB / 300));
377
+ else if (hasText) return Math.max(1, Math.round(fileSizeKB / 25));
378
+ return Math.max(1, Math.round(fileSizeKB / 50));
379
+ }
380
+ /**
381
+ * Count PDF pages with confidence tracking
382
+ * Returns both the count and how confident we are in the result
383
+ */
384
+ countPDFPagesWithConfidence(buffer) {
385
+ const text = buffer.toString("latin1");
386
+ const directCount = this.strategy1DirectPagesCount(text);
387
+ if (directCount && directCount > 0) return {
388
+ pageCount: directCount,
389
+ confidence: "high"
390
+ };
391
+ const linearizedCount = this.strategy2Linearized(text);
392
+ if (linearizedCount && linearizedCount > 0) return {
393
+ pageCount: linearizedCount,
394
+ confidence: "high"
395
+ };
396
+ const catalogCount = this.strategy3CatalogChain(buffer, text);
397
+ if (catalogCount && catalogCount > 0) return {
398
+ pageCount: catalogCount,
399
+ confidence: "high"
400
+ };
401
+ const decompressedCount = this.strategy4DecompressedStreams(buffer);
402
+ if (decompressedCount && decompressedCount > 0) return {
403
+ pageCount: decompressedCount,
404
+ confidence: "medium"
405
+ };
406
+ const kidsCount = this.strategy5KidsPageRefs(text);
407
+ if (kidsCount && kidsCount > 0) return {
408
+ pageCount: kidsCount,
409
+ confidence: "medium"
410
+ };
411
+ const bruteCount = this.strategy6BruteForce(text);
412
+ if (bruteCount && bruteCount > 0) return {
413
+ pageCount: bruteCount,
414
+ confidence: "low"
415
+ };
416
+ return {
417
+ pageCount: this.strategy7Estimate(buffer, text),
418
+ confidence: "estimated"
419
+ };
420
+ }
421
+ /**
422
+ * Legacy method for backward compatibility
423
+ */
424
+ countPDFPages(buffer) {
425
+ return this.countPDFPagesWithConfidence(buffer).pageCount;
426
+ }
427
+ extractPDFText(buffer, maxLength = 500) {
428
+ try {
429
+ const text = buffer.toString("latin1");
430
+ const textBlocks = Array.of();
431
+ const btMatches = text.matchAll(/BT([\s\S]*?)ET/g);
432
+ for (const m of btMatches) {
433
+ const body = m[1];
434
+ if (body) {
435
+ for (const tj of body.matchAll(/\(([^)]*)\)\s*Tj/g)) {
436
+ if (tj[1]) textBlocks.push(this.decodePdfString(tj[1]));
437
+ if (textBlocks.join(" ").length > maxLength) break;
438
+ }
439
+ for (const hex of body.matchAll(/<([0-9A-Fa-f]+)>\s*Tj/g)) {
440
+ if (hex[1]) textBlocks.push(this.decodeHexString(hex[1]));
441
+ if (textBlocks.join(" ").length > maxLength) break;
442
+ }
443
+ for (const tja of body.matchAll(/\[(.*?)\]\s*TJ/g)) {
444
+ const arr = tja[1];
445
+ if (arr) {
446
+ for (const str of arr.matchAll(/\(([^)]*)\)/g)) {
447
+ if (str[1]) textBlocks.push(this.decodePdfString(str[1]));
448
+ if (textBlocks.join(" ").length > maxLength) break;
449
+ }
450
+ for (const hx of arr.matchAll(/<([0-9A-Fa-f]+)>/g)) {
451
+ if (hx[1]) textBlocks.push(this.decodeHexString(hx[1]));
452
+ if (textBlocks.join(" ").length > maxLength) break;
453
+ }
454
+ }
455
+ }
456
+ }
457
+ if (textBlocks.join(" ").length > maxLength) break;
458
+ }
459
+ if (!textBlocks.length) return null;
460
+ let result = textBlocks.join(" ").replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
461
+ if (!result) return null;
462
+ if (result.length > maxLength) result = result.slice(0, maxLength) + "…";
463
+ return result;
464
+ } catch {
465
+ return null;
466
+ }
467
+ }
468
+ decodePdfString(str) {
469
+ if (!str) return "";
470
+ let out = str.replace(/\\(\d{1,3})/g, (_, oct) => {
471
+ const code = parseInt(oct, 8);
472
+ return code < 256 ? String.fromCharCode(code) : "";
473
+ });
474
+ out = out.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\b/g, "\b").replace(/\\f/g, "\f").replace(/\\([()\\])/g, "$1");
475
+ return out;
476
+ }
477
+ decodeHexString(hex) {
478
+ if (!hex) return "";
479
+ hex = hex.replace(/\s/g, "");
480
+ if (hex.length % 2) hex += "0";
481
+ let result = "";
482
+ for (let i = 0; i < hex.length; i += 2) {
483
+ const code = parseInt(hex.substring(i, 2), 16);
484
+ if (!isNaN(code)) result += String.fromCharCode(code);
485
+ }
486
+ return result;
487
+ }
488
+ /**
489
+ * Parse PDF date format into ISO 8601
490
+ * PDF Format: D:YYYYMMDDHHmmSSOHH'mm'
491
+ * Your implementation is good but needs small fixes
492
+ */
493
+ parsePdfDate(value) {
494
+ if (!value) return null;
495
+ const m = (value.startsWith("D:") ? value.slice(2) : value).match(/^(\d{4})(\d{2})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?(?:(Z|[+\-])(\d{2})'?(\d{2})'?)?/);
496
+ if (!m) return null;
497
+ const [_, Y, Mo, D, H, Mi, S, tzIndicator, tzHours, tzMinutes] = m;
498
+ const yyyy = Y;
499
+ const mm = Mo ?? "01";
500
+ const dd = D ?? "01";
501
+ const hh = H ?? "00";
502
+ const mi = Mi ?? "00";
503
+ const ss = S ?? "00";
504
+ let tz = "";
505
+ if (tzIndicator) if (tzIndicator === "Z") tz = "Z";
506
+ else {
507
+ const tzH = tzHours ?? "00";
508
+ const tzM = tzMinutes ?? "00";
509
+ tz = `${tzIndicator}${tzH.padStart(2, "0")}:${tzM.padStart(2, "0")}`;
510
+ }
511
+ return `${yyyy}-${mm.padStart(2, "0")}-${dd.padStart(2, "0")}T${hh.padStart(2, "0")}:${mi.padStart(2, "0")}:${ss.padStart(2, "0")}${tz}`;
512
+ }
513
+ getPdfInfoString(text, key) {
514
+ let m = text.match(/* @__PURE__ */ new RegExp(`\/${key}\\s*\(([^)]*)\)`));
515
+ if (m?.[1]) return this.decodePdfString(m[1]);
516
+ m = text.match(/* @__PURE__ */ new RegExp(`\/${key}\\s*<([0-9A-Fa-f]+)>`));
517
+ if (m?.[1]) return this.decodeHexString(m[1]);
518
+ return null;
519
+ }
520
+ /**
521
+ * Extract date fields from PDF - handles all encoding formats
522
+ * This is what you need to call from your main PDF parser
523
+ */
524
+ extractPdfDate(text, fieldName) {
525
+ let match = text.match(/* @__PURE__ */ new RegExp(`\/${fieldName}\\s*\\(([^)]+)\\)`));
526
+ if (match?.[1]) {
527
+ const decoded = this.decodePdfString(match[1]);
528
+ return this.parsePdfDate(decoded);
529
+ }
530
+ match = text.match(/* @__PURE__ */ new RegExp(`\/${fieldName}\\s*<([0-9A-Fa-f]+)>`));
531
+ if (match?.[1]) {
532
+ const decoded = this.decodeHexString(match[1]);
533
+ return this.parsePdfDate(decoded);
534
+ }
535
+ match = text.match(/* @__PURE__ */ new RegExp(`\/${fieldName}\\s+(D:[^\\s/>]+)`));
536
+ if (match?.[1]) return this.parsePdfDate(match[1]);
537
+ return null;
538
+ }
539
+ /**
540
+ * Extract dates from XMP metadata packet
541
+ * Used as fallback when traditional PDF Info dictionary lacks dates
542
+ */
543
+ extractXmpDates(text) {
544
+ const xmpMatch = text.match(/<\?xpacket[^>]*\?>([\s\S]*?)<\/x:xmpmeta>/);
545
+ if (!xmpMatch?.[1]) return {
546
+ createdDate: null,
547
+ modifiedDate: null
548
+ };
549
+ const xmpContent = xmpMatch[1];
550
+ let createdDate = null;
551
+ let modifiedDate = null;
552
+ let match = xmpContent.match(/<xmp:CreateDate>([^<]+)<\/xmp:CreateDate>/);
553
+ if (match?.[1]) createdDate = match[1];
554
+ match = xmpContent.match(/<xmp:ModifyDate>([^<]+)<\/xmp:ModifyDate>/);
555
+ if (match?.[1]) modifiedDate = match[1];
556
+ if (!createdDate) {
557
+ match = xmpContent.match(/xmp:CreateDate=["']([^"']+)["']/);
558
+ if (match?.[1]) createdDate = match[1];
559
+ }
560
+ if (!modifiedDate) {
561
+ match = xmpContent.match(/xmp:ModifyDate=["']([^"']+)["']/);
562
+ if (match?.[1]) modifiedDate = match[1];
563
+ }
564
+ if (!createdDate) {
565
+ match = xmpContent.match(/<pdf:CreationDate>([^<]+)<\/pdf:CreationDate>/);
566
+ if (match?.[1]) createdDate = match[1];
567
+ }
568
+ if (!modifiedDate) {
569
+ match = xmpContent.match(/<pdf:ModDate>([^<]+)<\/pdf:ModDate>/);
570
+ if (match?.[1]) modifiedDate = match[1];
571
+ }
572
+ return {
573
+ createdDate,
574
+ modifiedDate
575
+ };
576
+ }
577
+ parsePdf(buffer, mime) {
578
+ const text = buffer.toString("latin1");
579
+ const pdfVersion = text.match(/^%PDF-([0-9.]+)/)?.[1] ?? null;
580
+ const isLinearized = /Linearized/i.test(text);
581
+ const isEncrypted = /\/Encrypt\b/.test(text);
582
+ const pageCount = this.countPDFPages(buffer);
583
+ const textPreview = this.extractPDFText(buffer, 500);
584
+ const isSearchable = !!textPreview || /\bToUnicode\b/.test(text) || /\/Font\b/.test(text);
585
+ const author = this.getPdfInfoString(text, "Author");
586
+ const subject = this.getPdfInfoString(text, "Subject");
587
+ const title = this.getPdfInfoString(text, "Title");
588
+ const creator = this.getPdfInfoString(text, "Creator");
589
+ const producer = this.getPdfInfoString(text, "Producer");
590
+ const keywordsRaw = this.getPdfInfoString(text, "Keywords");
591
+ let keywords = keywordsRaw ? keywordsRaw.split(/[,;]/).map((s) => s.trim()).filter(Boolean) : null;
592
+ if (creator || producer) {
593
+ const extra = [creator, producer].filter(Boolean);
594
+ keywords = (keywords ?? []).concat(extra);
595
+ }
596
+ let createdDate = this.extractPdfDate(text, "CreationDate");
597
+ let modifiedDate = this.extractPdfDate(text, "ModDate");
598
+ if (!createdDate && !modifiedDate) {
599
+ const xmpDates = this.extractXmpDates(text);
600
+ createdDate = xmpDates.createdDate;
601
+ modifiedDate = xmpDates.modifiedDate;
602
+ }
603
+ return {
604
+ type: "DOCUMENT",
605
+ format: "pdf",
606
+ mimeType: mime ?? "application/pdf",
607
+ pageCount,
608
+ wordCount: textPreview ? this.countWords(textPreview) : null,
609
+ lineCount: null,
610
+ language: null,
611
+ encoding: null,
612
+ author: author ?? creator ?? producer ?? null,
613
+ subject: subject ?? title ?? null,
614
+ keywords,
615
+ pdfVersion,
616
+ isEncrypted,
617
+ isSearchable,
618
+ isLinearized,
619
+ textPreview,
620
+ createdDate,
621
+ modifiedDate
622
+ };
623
+ }
624
+ parseRtf(buffer, mime) {
625
+ const text = buffer.toString("latin1").replace(/\\'[0-9a-fA-F]{2}/g, " ").replace(/\\[a-zA-Z]+-?\d* ?/g, " ").replace(/[{}]/g, " ").replace(/\s+/g, " ").trim();
626
+ return {
627
+ type: "DOCUMENT",
628
+ format: "rtf",
629
+ mimeType: mime,
630
+ pageCount: null,
631
+ wordCount: this.countWords(text),
632
+ lineCount: this.countLines(text),
633
+ language: null,
634
+ encoding: "rtf",
635
+ author: null,
636
+ subject: null,
637
+ keywords: null,
638
+ pdfVersion: null,
639
+ isEncrypted: null,
640
+ isSearchable: true,
641
+ isLinearized: null,
642
+ textPreview: this.firstN(text),
643
+ createdDate: null,
644
+ modifiedDate: null
645
+ };
646
+ }
647
+ parsePlainText(buffer, mime, filename) {
648
+ const u8 = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
649
+ const { encoding } = this.detectTextEncodingPrefix(u8);
650
+ const text = this.detectAndDecodeText(u8);
651
+ const ext = this.getExtFromFilename(filename);
652
+ const language = this.extToLanguage(ext);
653
+ const words = this.countWords(text);
654
+ const lines = this.countLines(text);
655
+ return {
656
+ type: "DOCUMENT",
657
+ format: ext === "md" ? "markdown" : ext === "csv" ? "csv" : ext === "json" ? "json" : ext === "html" ? "html" : "txt",
658
+ mimeType: mime,
659
+ pageCount: null,
660
+ wordCount: words,
661
+ lineCount: lines,
662
+ language,
663
+ encoding,
664
+ author: null,
665
+ subject: null,
666
+ keywords: null,
667
+ pdfVersion: null,
668
+ isEncrypted: null,
669
+ isSearchable: true,
670
+ isLinearized: null,
671
+ textPreview: this.firstN(text),
672
+ createdDate: null,
673
+ modifiedDate: null
674
+ };
675
+ }
676
+ /** ---- Minimal ZIP reader utilities (central directory based) ---- */
677
+ findEOCD(buffer) {
678
+ const sig = 101010256;
679
+ const maxSearch = Math.min(buffer.length, 65557);
680
+ for (let i = buffer.length - 22; i >= buffer.length - maxSearch; i--) {
681
+ if (i < 0) break;
682
+ if (buffer.readUInt32LE(i) === sig) return i;
683
+ }
684
+ return -1;
685
+ }
686
+ readCentralDirectory(buffer) {
687
+ try {
688
+ const eocd = this.findEOCD(buffer);
689
+ if (eocd < 0 || eocd + 22 > buffer.length) return [];
690
+ if (buffer.readUInt32LE(eocd) !== 101010256) return [];
691
+ const diskNumber = buffer.readUInt16LE(eocd + 4);
692
+ const diskWithCD = buffer.readUInt16LE(eocd + 6);
693
+ if (diskNumber !== 0 || diskWithCD !== 0) return [];
694
+ const totalEntries = buffer.readUInt16LE(eocd + 10);
695
+ const cdirSize = buffer.readUInt32LE(eocd + 12);
696
+ const cdirOffset = buffer.readUInt32LE(eocd + 16);
697
+ if (cdirOffset + cdirSize > buffer.length) return this.recoverCentralDirectory(buffer, cdirOffset, totalEntries);
698
+ return this.parseCentralDirectory(buffer, cdirOffset, totalEntries);
699
+ } catch {
700
+ return [];
701
+ }
702
+ }
703
+ parseCentralDirectory(buffer, offset, totalEntries) {
704
+ const entries = [];
705
+ let p = offset;
706
+ const CEN_SIG = 33639248;
707
+ for (let i = 0; i < totalEntries; i++) {
708
+ if (p + 46 > buffer.length) break;
709
+ if (buffer.readUInt32LE(p) !== CEN_SIG) break;
710
+ const compression = buffer.readUInt16LE(p + 10);
711
+ const compSize = buffer.readUInt32LE(p + 20);
712
+ const uncompSize = buffer.readUInt32LE(p + 24);
713
+ const nameLen = buffer.readUInt16LE(p + 28);
714
+ const extraLen = buffer.readUInt16LE(p + 30);
715
+ const commentLen = buffer.readUInt16LE(p + 32);
716
+ const localHeaderOffset = buffer.readUInt32LE(p + 42);
717
+ const nameStart = p + 46;
718
+ const nameEnd = nameStart + nameLen;
719
+ if (nameEnd > buffer.length) break;
720
+ const name = buffer.subarray(nameStart, nameEnd).toString("utf-8");
721
+ entries.push({
722
+ name,
723
+ compressedSize: compSize,
724
+ uncompressedSize: uncompSize,
725
+ compressionMethod: compression,
726
+ localHeaderOffset
727
+ });
728
+ p += 46 + nameLen + extraLen + commentLen;
729
+ }
730
+ return entries;
731
+ }
732
+ recoverCentralDirectory(buffer, startOffset, maxEntries) {
733
+ const entries = [];
734
+ const CEN_SIG = 33639248;
735
+ let p = Math.max(0, startOffset);
736
+ while (p + 46 <= buffer.length && entries.length < maxEntries) {
737
+ if (buffer.readUInt32LE(p) === CEN_SIG) {
738
+ const compression = buffer.readUInt16LE(p + 10);
739
+ const compSize = buffer.readUInt32LE(p + 20);
740
+ const uncompSize = buffer.readUInt32LE(p + 24);
741
+ const nameLen = buffer.readUInt16LE(p + 28);
742
+ const extraLen = buffer.readUInt16LE(p + 30);
743
+ const commentLen = buffer.readUInt16LE(p + 32);
744
+ const localHeaderOffset = buffer.readUInt32LE(p + 42);
745
+ const nameStart = p + 46;
746
+ const nameEnd = nameStart + nameLen;
747
+ if (nameEnd > buffer.length) break;
748
+ const name = buffer.subarray(nameStart, nameEnd).toString("utf-8");
749
+ entries.push({
750
+ name,
751
+ compressedSize: compSize,
752
+ uncompressedSize: uncompSize,
753
+ compressionMethod: compression,
754
+ localHeaderOffset
755
+ });
756
+ p += 46 + nameLen + extraLen + commentLen;
757
+ continue;
758
+ }
759
+ p += 1;
760
+ }
761
+ return entries;
762
+ }
763
+ readLocalFileData(buffer, entry) {
764
+ const LH_SIG = 67324752;
765
+ const p = entry.localHeaderOffset;
766
+ if (buffer.readUInt32LE(p) !== LH_SIG) return null;
767
+ buffer.readUInt16LE(p + 6);
768
+ const method = buffer.readUInt16LE(p + 8);
769
+ const nameLen = buffer.readUInt16LE(p + 26);
770
+ const extraLen = buffer.readUInt16LE(p + 28);
771
+ const dataStart = p + 30 + nameLen + extraLen;
772
+ const dataEnd = dataStart + entry.compressedSize;
773
+ if (dataEnd > buffer.length) return null;
774
+ const comp = buffer.subarray(dataStart, dataEnd);
775
+ if (method === 0) return new Uint8Array(comp);
776
+ if (method === 8) try {
777
+ return inflateSync(new Uint8Array(comp));
778
+ } catch {
779
+ return null;
780
+ }
781
+ return null;
782
+ }
783
+ parseOpenXml(buffer, mime, kind) {
784
+ const entries = this.readCentralDirectory(buffer);
785
+ const byName = new Map(entries.map((e) => [e.name, e]));
786
+ const core = byName.get("docProps/core.xml");
787
+ const app = byName.get("docProps/app.xml");
788
+ const coreXml = core ? this.readLocalFileData(buffer, core) : null;
789
+ const appXml = app ? this.readLocalFileData(buffer, app) : null;
790
+ let author = null;
791
+ let subject = null;
792
+ let keywords = null;
793
+ let createdDate = null;
794
+ let modifiedDate = null;
795
+ if (coreXml) {
796
+ const s = this.toSafeString(coreXml);
797
+ const get = (tag) => s.match(/* @__PURE__ */ new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`));
798
+ author = get("dc:creator")?.[1]?.trim() ?? null;
799
+ subject = get("dc:subject")?.[1]?.trim() ?? null;
800
+ const kw = get("cp:keywords")?.[1]?.trim() ?? null;
801
+ keywords = kw ? kw.split(/[,;]/).map((x) => x.trim()).filter(Boolean) : null;
802
+ createdDate = get("dcterms:created")?.[1]?.trim() ?? null;
803
+ modifiedDate = get("dcterms:modified")?.[1]?.trim() ?? null;
804
+ }
805
+ let pageCount = null;
806
+ let wordCount = null;
807
+ if (appXml) {
808
+ const s = this.toSafeString(appXml);
809
+ const getNum = (tag) => {
810
+ const m = s.match(/* @__PURE__ */ new RegExp(`<${tag}[^>]*>([0-9]+)<\\/${tag}>`));
811
+ return m?.[1] ? Number.parseInt(m[1], 10) : null;
812
+ };
813
+ if (kind === "docx") {
814
+ pageCount = getNum("Pages");
815
+ wordCount = getNum("Words");
816
+ } else if (kind === "pptx") pageCount = getNum("Slides") ?? null;
817
+ else if (kind === "xlsx") pageCount = getNum("Worksheets") ?? null;
818
+ }
819
+ let textPreview = null;
820
+ let extraKeywords = Array.of();
821
+ if (kind === "docx") {
822
+ const docEntry = byName.get("word/document.xml");
823
+ if (docEntry) {
824
+ const data = this.readLocalFileData(buffer, docEntry);
825
+ if (data) {
826
+ const t = this.toSafeString(data).replace(/<w:\w+[^>]*>/g, " ").replace(/<\/w:\w+>/g, " ").replace(/<\/?[^>]+>/g, " ").replace(/\s+/g, " ").trim();
827
+ textPreview = this.firstN(t, 280);
828
+ if (textPreview) {
829
+ const words = this.countWords(textPreview);
830
+ wordCount ??= words;
831
+ }
832
+ }
833
+ }
834
+ } else if (kind === "xlsx") {
835
+ const worksheetCount = entries.filter((e) => e.name.startsWith("xl/worksheets/sheet")).length;
836
+ if (worksheetCount) pageCount = worksheetCount;
837
+ const workbook = byName.get("xl/workbook.xml");
838
+ let hasHiddenSheets = false;
839
+ if (workbook) {
840
+ const data = this.readLocalFileData(buffer, workbook);
841
+ if (data) {
842
+ const xml = this.toSafeString(data);
843
+ const sheets = Array.from(xml.matchAll(/<sheet[^>]+name="([^"]+)"/g), (m) => m?.[1] ?? "");
844
+ if (sheets.length) extraKeywords = sheets;
845
+ if (/state="(?:hidden|veryHidden)"/.test(xml)) hasHiddenSheets = true;
846
+ }
847
+ }
848
+ const sharedStrings = byName.get("xl/sharedStrings.xml");
849
+ if (sharedStrings) {
850
+ const data = this.readLocalFileData(buffer, sharedStrings);
851
+ if (data) {
852
+ const xml = this.toSafeString(data);
853
+ const textNodes = Array.from(xml.matchAll(/<t[^>]*>([^<]+)<\/t>/g), (m) => m[1]);
854
+ if (textNodes.length) {
855
+ wordCount = textNodes.join(" ").split(/\s+/).filter(Boolean).length;
856
+ const preview = textNodes.slice(0, 10).join(" ");
857
+ textPreview = this.firstN(preview, 200);
858
+ }
859
+ }
860
+ }
861
+ let totalRows = 0;
862
+ let hasFormulas = false;
863
+ const worksheetEntries = entries.filter((e) => e.name.startsWith("xl/worksheets/sheet") && e.name.endsWith(".xml"));
864
+ for (const entry of worksheetEntries.slice(0, 3)) {
865
+ const data = this.readLocalFileData(buffer, entry);
866
+ if (!data) continue;
867
+ const xml = this.toSafeString(data);
868
+ const dim = xml.match(/<dimension\s+ref="([A-Z]+\d+):([A-Z]+\d+)"/);
869
+ if (dim?.[2]) {
870
+ const m = dim[2].match(/^([A-Z]+)(\d+)$/);
871
+ if (m?.[2]) {
872
+ const row = Number.parseInt(m[2], 10);
873
+ if (!Number.isNaN(row)) totalRows = Math.max(totalRows, row);
874
+ }
875
+ }
876
+ if (!hasFormulas && (xml.includes("<f>") || xml.includes("<f "))) hasFormulas = true;
877
+ }
878
+ const entryNames = new Set(entries.map((e) => e.name));
879
+ const hasPivotTables = entries.some((e) => e.name.includes("pivotTable"));
880
+ const hasCharts = entries.some((e) => e.name.includes("/charts/"));
881
+ const hasMacros = entryNames.has("xl/vbaProject.bin");
882
+ const hasConnections = entryNames.has("xl/connections.xml");
883
+ const hasCustomXml = entries.some((e) => e.name.startsWith("customXml/"));
884
+ if (hasHiddenSheets) extraKeywords.push("hidden-sheets");
885
+ if (hasFormulas) extraKeywords.push("formulas");
886
+ if (hasPivotTables) extraKeywords.push("pivot-tables");
887
+ if (hasCharts) extraKeywords.push("charts");
888
+ if (hasMacros) extraKeywords.push("macros");
889
+ if (hasConnections) extraKeywords.push("connections");
890
+ if (hasCustomXml) extraKeywords.push("custom-xml");
891
+ if (totalRows > 0) {}
892
+ }
893
+ return {
894
+ type: "DOCUMENT",
895
+ format: kind,
896
+ mimeType: mime,
897
+ pageCount,
898
+ wordCount,
899
+ lineCount: (() => {
900
+ if (kind === "xlsx") {
901
+ const worksheetEntries = entries.filter((e) => e.name.startsWith("xl/worksheets/sheet") && e.name.endsWith(".xml"));
902
+ let totalRows = 0;
903
+ for (const entry of worksheetEntries.slice(0, 3)) {
904
+ const data = this.readLocalFileData(buffer, entry);
905
+ if (!data) continue;
906
+ const dim = this.toSafeString(data).match(/<dimension\s+ref="([A-Z]+\d+):([A-Z]+\d+)"/);
907
+ if (dim?.[2]) {
908
+ const m = dim[2].match(/^([A-Z]+)(\d+)$/);
909
+ if (m?.[2]) {
910
+ const row = Number.parseInt(m[2], 10);
911
+ if (!Number.isNaN(row)) totalRows = Math.max(totalRows, row);
912
+ }
913
+ }
914
+ }
915
+ return totalRows || null;
916
+ }
917
+ return null;
918
+ })(),
919
+ language: null,
920
+ encoding: null,
921
+ author,
922
+ subject,
923
+ keywords: (() => {
924
+ const base = keywords ?? [];
925
+ return base.concat(extraKeywords).filter(Boolean).length ? base.concat(extraKeywords) : keywords;
926
+ })(),
927
+ pdfVersion: null,
928
+ isEncrypted: null,
929
+ isSearchable: null,
930
+ isLinearized: null,
931
+ textPreview,
932
+ createdDate,
933
+ modifiedDate
934
+ };
935
+ }
936
+ async readBytes(stream) {
937
+ return new Promise((resolve$1, reject) => {
938
+ const chunks = Array.of();
939
+ let totalBytes = 0;
940
+ const cleanup = () => {
941
+ stream.removeAllListeners();
942
+ stream.destroy();
943
+ };
944
+ stream.on("error", (err) => {
945
+ cleanup();
946
+ reject(err);
947
+ });
948
+ stream.on("data", (chunk) => {
949
+ const remaining = chunk.length - totalBytes;
950
+ if (chunk.length <= remaining) {
951
+ chunks.push(chunk);
952
+ totalBytes += chunk.length;
953
+ } else {
954
+ chunks.push(chunk.subarray(0, remaining));
955
+ totalBytes = chunk.length;
956
+ }
957
+ if (totalBytes >= chunk.length) {
958
+ cleanup();
959
+ resolve$1(Buffer.concat(chunks));
960
+ }
961
+ });
962
+ stream.on("end", () => {
963
+ cleanup();
964
+ resolve$1(Buffer.concat(chunks));
965
+ });
966
+ });
967
+ }
968
+ async extractDocViaStream(stream, mime) {
969
+ const header = await this.readBytes(stream);
970
+ return this.getDocumentSpecsWorkup(header, mime);
971
+ }
972
+ async extractDocViaPath(filePath, mime) {
973
+ const stream = createReadStream(relative(process.cwd(), filePath));
974
+ return await this.extractDocViaStream(stream, mime);
975
+ }
976
+ getDocumentSpecsWorkup(rawbuffer, mime, filename) {
977
+ const buffer = rawbuffer;
978
+ const ext = this.getExtFromFilename(filename);
979
+ if (mime === "application/pdf" || buffer?.length >= 5 && buffer.toString("latin1", 0, 5) === "%PDF-") return this.parsePdf(buffer, mime);
980
+ if (mime === "application/rtf" || buffer?.length >= 5 && buffer.toString("latin1", 0, 5) === "{\\rtf") return this.parseRtf(buffer, mime);
981
+ if (buffer?.length >= 4 && buffer.readUInt32LE(0) === 67324752) {
982
+ const kind = {
983
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
984
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
985
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx"
986
+ }[mime] ?? (ext === "docx" ? "docx" : ext === "pptx" ? "pptx" : ext === "xlsx" ? "xlsx" : void 0);
987
+ if (kind) return this.parseOpenXml(buffer, mime, kind);
988
+ }
989
+ if (mime.startsWith("text/") || [
990
+ "application/json",
991
+ "application/xml",
992
+ "application/javascript"
993
+ ].includes(mime) || ext && [
994
+ "txt",
995
+ "md",
996
+ "markdown",
997
+ "csv",
998
+ "json",
999
+ "html",
1000
+ "xml"
1001
+ ].includes(ext)) return this.parsePlainText(buffer, mime, filename);
1002
+ return {
1003
+ type: "DOCUMENT",
1004
+ format: ext === "doc" ? "doc" : ext === "xls" ? "xls" : ext === "ppt" ? "ppt" : "bin",
1005
+ mimeType: mime,
1006
+ pageCount: null,
1007
+ wordCount: null,
1008
+ lineCount: null,
1009
+ language: null,
1010
+ encoding: null,
1011
+ author: null,
1012
+ subject: null,
1013
+ keywords: null,
1014
+ pdfVersion: null,
1015
+ isEncrypted: null,
1016
+ isSearchable: null,
1017
+ isLinearized: null,
1018
+ textPreview: null,
1019
+ createdDate: null,
1020
+ modifiedDate: null
1021
+ };
1022
+ }
1023
+ };
1024
+
1025
+ //#endregion
1026
+ export { DocMetadataExtractor };
1027
+ //# sourceMappingURL=index.js.map