@absolutejs/documents 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +14 -0
- package/LICENSE +88 -0
- package/README.md +41 -2
- package/changelog.json +20 -0
- package/dist/archive/containers.d.ts +5 -0
- package/dist/binary.d.ts +13 -0
- package/dist/define.d.ts +6 -0
- package/dist/email/body.d.ts +20 -0
- package/dist/email/headers.d.ts +20 -0
- package/dist/email/mailboxContainer.d.ts +19 -0
- package/dist/email/mailboxMetadata.d.ts +25 -0
- package/dist/email/maildir.d.ts +29 -0
- package/dist/email/mbox.d.ts +5 -0
- package/dist/email/message.d.ts +21 -0
- package/dist/email/mime.d.ts +24 -0
- package/dist/email/threads.d.ts +2 -0
- package/dist/epub.d.ts +2 -0
- package/dist/extractors/archive.d.ts +5 -0
- package/dist/extractors/email.d.ts +2 -0
- package/dist/extractors/epub.d.ts +2 -0
- package/dist/extractors/image.d.ts +2 -0
- package/dist/extractors/legacy.d.ts +2 -0
- package/dist/extractors/mailbox.d.ts +2 -0
- package/dist/extractors/media.d.ts +2 -0
- package/dist/extractors/office.d.ts +2 -0
- package/dist/extractors/pdf.d.ts +2 -0
- package/dist/extractors/pdfOCR.d.ts +2 -0
- package/dist/extractors/supports.d.ts +11 -0
- package/dist/extractors/text.d.ts +2 -0
- package/dist/formats.d.ts +37 -0
- package/dist/helpers.d.ts +11 -0
- package/dist/helpers.js +39 -0
- package/dist/html.d.ts +4 -0
- package/dist/identity.d.ts +3 -0
- package/dist/index-6cd9rbkj.js +3677 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +1126 -0
- package/dist/legacy.d.ts +3 -0
- package/dist/media.d.ts +22 -0
- package/dist/ocr.d.ts +22 -0
- package/dist/office/presentation.d.ts +10 -0
- package/dist/office/spreadsheet.d.ts +26 -0
- package/dist/office/word.d.ts +20 -0
- package/dist/pdf/bounded.d.ts +33 -0
- package/dist/pdf/checkpoint.d.ts +28 -0
- package/dist/pdf/native.d.ts +39 -0
- package/dist/pdf/paged.d.ts +17 -0
- package/dist/read.d.ts +25 -0
- package/dist/registry.d.ts +5 -0
- package/dist/structured.d.ts +2 -0
- package/dist/text.d.ts +1 -0
- package/dist/types.d.ts +123 -0
- package/package.json +55 -4
|
@@ -0,0 +1,3677 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/email/threads.ts
|
|
3
|
+
var collectEmailThreadParticipants = (documents) => {
|
|
4
|
+
const participants = new Set;
|
|
5
|
+
const participantAddresses = new Set;
|
|
6
|
+
const participantDisplayNames = new Set;
|
|
7
|
+
for (const document of documents) {
|
|
8
|
+
const parsedParticipantAddresses = Array.isArray(document.metadata?.participantAddresses) ? document.metadata.participantAddresses : [];
|
|
9
|
+
for (const address of parsedParticipantAddresses) {
|
|
10
|
+
if (typeof address === "string" && address.trim().length > 0) {
|
|
11
|
+
participantAddresses.add(address.trim());
|
|
12
|
+
participants.add(address.trim());
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const parsedParticipantDisplayNames = Array.isArray(document.metadata?.participantDisplayNames) ? document.metadata.participantDisplayNames : [];
|
|
16
|
+
for (const name of parsedParticipantDisplayNames) {
|
|
17
|
+
if (typeof name === "string" && name.trim().length > 0) {
|
|
18
|
+
participantDisplayNames.add(name.trim());
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const from = document.metadata?.from;
|
|
22
|
+
if (typeof from === "string" && from.trim().length > 0) {
|
|
23
|
+
participants.add(from.trim());
|
|
24
|
+
}
|
|
25
|
+
const to = document.metadata?.to;
|
|
26
|
+
if (typeof to === "string" && to.trim().length > 0) {
|
|
27
|
+
for (const recipient of to.split(",").map((entry) => entry.trim()).filter(Boolean)) {
|
|
28
|
+
participants.add(recipient);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
participantAddresses: [...participantAddresses],
|
|
34
|
+
participantDisplayNames: [...participantDisplayNames],
|
|
35
|
+
participants: [...participants]
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
var reconcileLoadedEmailThreads2 = (documents) => {
|
|
39
|
+
const messageDocuments = documents.filter((document) => document.metadata?.emailKind === "message");
|
|
40
|
+
if (messageDocuments.length === 0) {
|
|
41
|
+
return documents;
|
|
42
|
+
}
|
|
43
|
+
const parent = messageDocuments.map((_, index) => index);
|
|
44
|
+
const find = (index) => {
|
|
45
|
+
let current = index;
|
|
46
|
+
while (parent[current] !== current) {
|
|
47
|
+
parent[current] = parent[parent[current]];
|
|
48
|
+
current = parent[current];
|
|
49
|
+
}
|
|
50
|
+
return current;
|
|
51
|
+
};
|
|
52
|
+
const union = (left, right) => {
|
|
53
|
+
const leftRoot = find(left);
|
|
54
|
+
const rightRoot = find(right);
|
|
55
|
+
if (leftRoot !== rightRoot) {
|
|
56
|
+
parent[rightRoot] = leftRoot;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const messageIndexById = new Map;
|
|
60
|
+
const messageIndexBySource = new Map;
|
|
61
|
+
const messageIndexesByThreadKey = new Map;
|
|
62
|
+
for (const [index, document] of messageDocuments.entries()) {
|
|
63
|
+
const messageId = document.metadata?.messageId;
|
|
64
|
+
if (typeof messageId === "string" && messageId.length > 0) {
|
|
65
|
+
messageIndexById.set(messageId, index);
|
|
66
|
+
}
|
|
67
|
+
if (typeof document.source === "string" && document.source.length > 0) {
|
|
68
|
+
messageIndexBySource.set(document.source, index);
|
|
69
|
+
}
|
|
70
|
+
const threadKey = document.metadata?.threadKey;
|
|
71
|
+
if (typeof threadKey === "string" && threadKey.trim().length > 0) {
|
|
72
|
+
const normalizedThreadKey = threadKey.trim();
|
|
73
|
+
const current = messageIndexesByThreadKey.get(normalizedThreadKey);
|
|
74
|
+
if (current) {
|
|
75
|
+
current.push(index);
|
|
76
|
+
} else {
|
|
77
|
+
messageIndexesByThreadKey.set(normalizedThreadKey, [index]);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const indexes of messageIndexesByThreadKey.values()) {
|
|
82
|
+
for (let index = 1;index < indexes.length; index += 1) {
|
|
83
|
+
union(indexes[0], indexes[index]);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const [index, document] of messageDocuments.entries()) {
|
|
87
|
+
const inReplyTo = document.metadata?.inReplyTo;
|
|
88
|
+
if (typeof inReplyTo === "string" && inReplyTo.length > 0) {
|
|
89
|
+
const parentIndex = messageIndexById.get(inReplyTo);
|
|
90
|
+
if (typeof parentIndex === "number") {
|
|
91
|
+
union(index, parentIndex);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const threadMessageIds = Array.isArray(document.metadata?.threadMessageIds) ? document.metadata.threadMessageIds : [];
|
|
95
|
+
for (const relatedMessageId of threadMessageIds) {
|
|
96
|
+
if (typeof relatedMessageId !== "string" || relatedMessageId.length === 0) {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const relatedIndex = messageIndexById.get(relatedMessageId);
|
|
100
|
+
if (typeof relatedIndex === "number") {
|
|
101
|
+
union(index, relatedIndex);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const threadGroups = new Map;
|
|
106
|
+
for (const [index, document] of messageDocuments.entries()) {
|
|
107
|
+
const component = find(index);
|
|
108
|
+
const current = threadGroups.get(component);
|
|
109
|
+
if (current) {
|
|
110
|
+
current.push(document);
|
|
111
|
+
} else {
|
|
112
|
+
threadGroups.set(component, [document]);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const document of documents) {
|
|
116
|
+
if (document.metadata?.emailKind === "message") {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const messageSource = document.metadata?.emailMessageSource;
|
|
120
|
+
if (typeof messageSource === "string" && messageSource.length > 0) {
|
|
121
|
+
const messageIndex = messageIndexBySource.get(messageSource);
|
|
122
|
+
if (typeof messageIndex === "number") {
|
|
123
|
+
const component = find(messageIndex);
|
|
124
|
+
const current = threadGroups.get(component);
|
|
125
|
+
if (current) {
|
|
126
|
+
current.push(document);
|
|
127
|
+
} else {
|
|
128
|
+
threadGroups.set(component, [document]);
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const threadKey = document.metadata?.threadKey;
|
|
134
|
+
if (typeof threadKey === "string" && threadKey.trim().length > 0) {
|
|
135
|
+
const candidateIndexes = messageIndexesByThreadKey.get(threadKey.trim());
|
|
136
|
+
const candidateIndex = candidateIndexes?.[0];
|
|
137
|
+
if (typeof candidateIndex === "number") {
|
|
138
|
+
const component = find(candidateIndex);
|
|
139
|
+
const current = threadGroups.get(component);
|
|
140
|
+
if (current) {
|
|
141
|
+
current.push(document);
|
|
142
|
+
} else {
|
|
143
|
+
threadGroups.set(component, [document]);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const [, threadDocuments] of threadGroups.entries()) {
|
|
149
|
+
const componentMessages = threadDocuments.filter((document) => document.metadata?.emailKind === "message");
|
|
150
|
+
if (componentMessages.length === 0) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const threadKey = (() => {
|
|
154
|
+
const rootByReply = componentMessages.find((document) => typeof document.metadata?.inReplyTo !== "string" || document.metadata.inReplyTo.length === 0);
|
|
155
|
+
const rootCandidate = rootByReply ?? componentMessages[0];
|
|
156
|
+
return (typeof rootCandidate?.metadata?.threadKey === "string" && rootCandidate.metadata.threadKey.trim().length > 0 ? rootCandidate.metadata.threadKey.trim() : undefined) ?? componentMessages.map((document) => document.metadata?.threadKey).find((value) => typeof value === "string" && value.trim().length > 0)?.trim() ?? "email-thread";
|
|
157
|
+
})();
|
|
158
|
+
const knownThreadMessageIds = [];
|
|
159
|
+
const seenKnownThreadMessageIds = new Set;
|
|
160
|
+
for (const document of threadDocuments) {
|
|
161
|
+
const threadMessageIds = Array.isArray(document.metadata?.threadMessageIds) ? document.metadata?.threadMessageIds : [];
|
|
162
|
+
for (const messageId of threadMessageIds) {
|
|
163
|
+
if (typeof messageId === "string" && messageId.length > 0 && !seenKnownThreadMessageIds.has(messageId)) {
|
|
164
|
+
seenKnownThreadMessageIds.add(messageId);
|
|
165
|
+
knownThreadMessageIds.push(messageId);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const messageId = document.metadata?.messageId;
|
|
169
|
+
if (typeof messageId === "string" && messageId.length > 0 && !seenKnownThreadMessageIds.has(messageId)) {
|
|
170
|
+
seenKnownThreadMessageIds.add(messageId);
|
|
171
|
+
knownThreadMessageIds.push(messageId);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const loadedMessageIds = componentMessages.map((document) => document.metadata?.messageId).filter((value) => typeof value === "string" && value.length > 0);
|
|
175
|
+
const loadedMessageIdSet = new Set(loadedMessageIds);
|
|
176
|
+
const loadedMessageSourceById = new Map;
|
|
177
|
+
for (const document of componentMessages) {
|
|
178
|
+
const messageId = document.metadata?.messageId;
|
|
179
|
+
if (typeof messageId === "string" && messageId.length > 0 && typeof document.source === "string" && document.source.length > 0) {
|
|
180
|
+
loadedMessageSourceById.set(messageId, document.source);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const replySiblingGroups = new Map;
|
|
184
|
+
for (const document of componentMessages) {
|
|
185
|
+
const inReplyTo = document.metadata?.inReplyTo;
|
|
186
|
+
if (typeof inReplyTo !== "string" || inReplyTo.length === 0 || !loadedMessageIdSet.has(inReplyTo)) {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const current = replySiblingGroups.get(inReplyTo);
|
|
190
|
+
if (current) {
|
|
191
|
+
current.push(document);
|
|
192
|
+
} else {
|
|
193
|
+
replySiblingGroups.set(inReplyTo, [document]);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const replySiblingMetadataByMessageId = new Map;
|
|
197
|
+
for (const [parentMessageId, siblings] of replySiblingGroups.entries()) {
|
|
198
|
+
const orderedSiblings = [...siblings].sort((left, right) => {
|
|
199
|
+
const leftSource = typeof left.source === "string" ? left.source : "";
|
|
200
|
+
const rightSource = typeof right.source === "string" ? right.source : "";
|
|
201
|
+
if (leftSource !== rightSource) {
|
|
202
|
+
return leftSource.localeCompare(rightSource);
|
|
203
|
+
}
|
|
204
|
+
const leftMessageId = typeof left.metadata?.messageId === "string" ? left.metadata.messageId : "";
|
|
205
|
+
const rightMessageId = typeof right.metadata?.messageId === "string" ? right.metadata.messageId : "";
|
|
206
|
+
return leftMessageId.localeCompare(rightMessageId);
|
|
207
|
+
});
|
|
208
|
+
const siblingMessageIds = orderedSiblings.map((document) => document.metadata?.messageId).filter((value) => typeof value === "string" && value.length > 0);
|
|
209
|
+
const siblingSources = orderedSiblings.map((document) => document.source).filter((value) => typeof value === "string" && value.length > 0);
|
|
210
|
+
for (const [index, sibling] of orderedSiblings.entries()) {
|
|
211
|
+
const messageId = sibling.metadata?.messageId;
|
|
212
|
+
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
replySiblingMetadataByMessageId.set(messageId, {
|
|
216
|
+
count: orderedSiblings.length,
|
|
217
|
+
index,
|
|
218
|
+
messageIds: siblingMessageIds,
|
|
219
|
+
parentMessageId,
|
|
220
|
+
sources: siblingSources
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const threadParticipants = collectEmailThreadParticipants(threadDocuments);
|
|
225
|
+
const loadedMessageSources = messageDocuments.map((document) => document.source).filter((value) => typeof value === "string" && value.length > 0);
|
|
226
|
+
const loadedAttachmentCount = threadDocuments.filter((document) => document.metadata?.emailKind === "attachment").length;
|
|
227
|
+
const threadRootMessageId = (() => {
|
|
228
|
+
const existingRoot = threadDocuments.map((document) => document.metadata?.threadRootMessageId).find((value) => typeof value === "string" && value.length > 0);
|
|
229
|
+
return existingRoot ?? loadedMessageIds[0];
|
|
230
|
+
})();
|
|
231
|
+
for (const document of threadDocuments) {
|
|
232
|
+
const messageId = typeof document.metadata?.messageId === "string" ? document.metadata.messageId : undefined;
|
|
233
|
+
const replySiblingMetadata = messageId ? replySiblingMetadataByMessageId.get(messageId) : undefined;
|
|
234
|
+
document.metadata = {
|
|
235
|
+
...document.metadata ?? {},
|
|
236
|
+
...replySiblingMetadata ? {
|
|
237
|
+
emailReplySiblingCount: replySiblingMetadata.count,
|
|
238
|
+
emailReplySiblingIndex: replySiblingMetadata.index,
|
|
239
|
+
emailReplySiblingMessageIds: replySiblingMetadata.messageIds,
|
|
240
|
+
emailReplySiblingOrdinal: replySiblingMetadata.index + 1,
|
|
241
|
+
emailReplySiblingParentMessageId: replySiblingMetadata.parentMessageId,
|
|
242
|
+
emailReplySiblingSources: replySiblingMetadata.sources
|
|
243
|
+
} : {},
|
|
244
|
+
threadKey,
|
|
245
|
+
threadKnownMessageCount: knownThreadMessageIds.length,
|
|
246
|
+
threadKnownMessageIds: knownThreadMessageIds,
|
|
247
|
+
threadLoadedAttachmentCount: loadedAttachmentCount,
|
|
248
|
+
threadLoadedMessageCount: loadedMessageIds.length,
|
|
249
|
+
threadLoadedMessageIds: loadedMessageIds,
|
|
250
|
+
threadLoadedMessageSources: loadedMessageSources,
|
|
251
|
+
threadParticipantAddresses: threadParticipants.participantAddresses,
|
|
252
|
+
threadParticipantDisplayNames: threadParticipants.participantDisplayNames,
|
|
253
|
+
threadParticipants: threadParticipants.participants,
|
|
254
|
+
threadRootMessageId
|
|
255
|
+
};
|
|
256
|
+
const inReplyTo = document.metadata?.inReplyTo;
|
|
257
|
+
if (typeof inReplyTo === "string" && inReplyTo.length > 0 && loadedMessageIdSet.has(inReplyTo)) {
|
|
258
|
+
document.metadata = {
|
|
259
|
+
...document.metadata ?? {},
|
|
260
|
+
emailReplyParentLoaded: true,
|
|
261
|
+
emailReplyParentMessageId: inReplyTo,
|
|
262
|
+
emailReplyParentSource: loadedMessageSourceById.get(inReplyTo)
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return documents;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// src/binary.ts
|
|
271
|
+
var readUInt16LE = (data, offset) => data[offset] | data[offset + 1] << 8;
|
|
272
|
+
var readUInt32LE = (data, offset) => (data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16 | data[offset + 3] << 24) >>> 0;
|
|
273
|
+
var decodeUtf8 = (data) => Buffer.from(data).toString("utf8");
|
|
274
|
+
var decodeLatin1 = (data) => Buffer.from(data).toString("latin1");
|
|
275
|
+
|
|
276
|
+
// src/email/mbox.ts
|
|
277
|
+
var splitEmailMessage = (raw) => {
|
|
278
|
+
const normalized = raw.replace(/\r\n?/g, `
|
|
279
|
+
`);
|
|
280
|
+
const separator = normalized.indexOf(`
|
|
281
|
+
|
|
282
|
+
`);
|
|
283
|
+
if (separator < 0) {
|
|
284
|
+
return {
|
|
285
|
+
body: "",
|
|
286
|
+
headerBlock: normalized
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
body: normalized.slice(separator + 2),
|
|
291
|
+
headerBlock: normalized.slice(0, separator)
|
|
292
|
+
};
|
|
293
|
+
};
|
|
294
|
+
var EMAIL_MBOX_BOUNDARY_PATTERN = /^From [^\s]+ .+$/;
|
|
295
|
+
var looksLikeMboxBoundary = (lines, index) => {
|
|
296
|
+
const line = lines[index];
|
|
297
|
+
if (!EMAIL_MBOX_BOUNDARY_PATTERN.test(line ?? "")) {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
for (let offset = index + 1;offset < lines.length; offset += 1) {
|
|
301
|
+
const candidate = lines[offset]?.trim() ?? "";
|
|
302
|
+
if (!candidate) {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
if (/^[A-Za-z-]+:\s+\S+/.test(candidate)) {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
if (EMAIL_MBOX_BOUNDARY_PATTERN.test(candidate)) {
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return false;
|
|
313
|
+
};
|
|
314
|
+
var splitMboxMessages = (raw) => {
|
|
315
|
+
const normalized = raw.replace(/\r\n?/g, `
|
|
316
|
+
`);
|
|
317
|
+
const lines = normalized.split(`
|
|
318
|
+
`);
|
|
319
|
+
const messages = [];
|
|
320
|
+
let currentLines = [];
|
|
321
|
+
const pushCurrent = () => {
|
|
322
|
+
const text = currentLines.join(`
|
|
323
|
+
`).trim();
|
|
324
|
+
if (text) {
|
|
325
|
+
messages.push(text);
|
|
326
|
+
}
|
|
327
|
+
currentLines = [];
|
|
328
|
+
};
|
|
329
|
+
for (let index = 0;index < lines.length; index += 1) {
|
|
330
|
+
const line = lines[index] ?? "";
|
|
331
|
+
if (looksLikeMboxBoundary(lines, index)) {
|
|
332
|
+
pushCurrent();
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
currentLines.push(line.replace(/^>(>*From )/, "$1"));
|
|
336
|
+
}
|
|
337
|
+
pushCurrent();
|
|
338
|
+
return messages;
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// src/text.ts
|
|
342
|
+
var normalizeWhitespace2 = (value) => value.replace(/\r\n?/g, `
|
|
343
|
+
`).replace(/[ \t\f\v]+/g, " ").replace(/ *\n */g, `
|
|
344
|
+
`).replace(/\n{3,}/g, `
|
|
345
|
+
|
|
346
|
+
`).trim();
|
|
347
|
+
|
|
348
|
+
// src/email/mime.ts
|
|
349
|
+
var RFC2047_WORD = /=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g;
|
|
350
|
+
var decodeEncodedWord = (charset, encoding, text) => {
|
|
351
|
+
const bytes = encoding.toUpperCase() === "B" ? Buffer.from(text, "base64") : Buffer.from(decodeQuotedPrintable(text.replace(/_/g, " ")), "latin1");
|
|
352
|
+
try {
|
|
353
|
+
return new TextDecoder(charset.trim().toLowerCase()).decode(bytes);
|
|
354
|
+
} catch {
|
|
355
|
+
return bytes.toString("utf8");
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
var decodeRfc2047 = (value) => value.includes("=?") ? value.replace(/\?=\s+=\?/g, "?==?").replace(RFC2047_WORD, (_match, charset, enc, text) => decodeEncodedWord(charset, enc, text)) : value;
|
|
359
|
+
var parseHeaderBlock = (headerBlock) => {
|
|
360
|
+
const unfolded = headerBlock.replace(/\n[ \t]+/g, " ");
|
|
361
|
+
const headers = new Map;
|
|
362
|
+
for (const line of unfolded.split(`
|
|
363
|
+
`)) {
|
|
364
|
+
const separator = line.indexOf(":");
|
|
365
|
+
if (separator < 0) {
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
headers.set(line.slice(0, separator).trim().toLowerCase(), decodeRfc2047(line.slice(separator + 1).trim()));
|
|
369
|
+
}
|
|
370
|
+
return headers;
|
|
371
|
+
};
|
|
372
|
+
var decodeQuotedPrintable = (value) => value.replace(/=\r?\n/g, "").replace(/=([0-9A-F]{2})/gi, (_match, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
373
|
+
var decodeEmailPartBody = (body, encoding) => {
|
|
374
|
+
const normalizedEncoding = encoding?.toLowerCase();
|
|
375
|
+
const trimmed = body.trim();
|
|
376
|
+
if (normalizedEncoding === "base64") {
|
|
377
|
+
return new Uint8Array(Buffer.from(trimmed.replace(/\s+/g, ""), "base64"));
|
|
378
|
+
}
|
|
379
|
+
if (normalizedEncoding === "quoted-printable") {
|
|
380
|
+
return new Uint8Array(Buffer.from(decodeQuotedPrintable(body), "latin1"));
|
|
381
|
+
}
|
|
382
|
+
return new Uint8Array(Buffer.from(body, "latin1"));
|
|
383
|
+
};
|
|
384
|
+
var parseMimeCharset = (contentType) => contentType?.match(/charset\s*=\s*"?([^";\s]+)"?/i)?.[1];
|
|
385
|
+
var decodeWithCharset = (data, contentType) => {
|
|
386
|
+
const charset = parseMimeCharset(contentType)?.trim().toLowerCase();
|
|
387
|
+
if (!charset || charset === "utf-8" || charset === "utf8") {
|
|
388
|
+
return decodeUtf8(data);
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
return new TextDecoder(charset).decode(data);
|
|
392
|
+
} catch {
|
|
393
|
+
return decodeUtf8(data);
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
var parseMimeBoundary = (contentType) => {
|
|
397
|
+
const match = contentType?.match(/boundary="?([^";]+)"?/i);
|
|
398
|
+
return match?.[1];
|
|
399
|
+
};
|
|
400
|
+
var EMAIL_ATTACHMENT_EXTENSION_BY_CONTENT_TYPE = {
|
|
401
|
+
"application/gzip": ".gz",
|
|
402
|
+
"application/json": ".json",
|
|
403
|
+
"application/pdf": ".pdf",
|
|
404
|
+
"application/rtf": ".rtf",
|
|
405
|
+
"application/zip": ".zip",
|
|
406
|
+
"application/x-gzip": ".gz",
|
|
407
|
+
"application/xml": ".xml",
|
|
408
|
+
"image/gif": ".gif",
|
|
409
|
+
"image/jpeg": ".jpg",
|
|
410
|
+
"image/png": ".png",
|
|
411
|
+
"image/svg+xml": ".svg",
|
|
412
|
+
"message/rfc822": ".eml",
|
|
413
|
+
"text/csv": ".csv",
|
|
414
|
+
"text/html": ".html",
|
|
415
|
+
"text/markdown": ".md",
|
|
416
|
+
"text/plain": ".txt",
|
|
417
|
+
"text/tsv": ".tsv",
|
|
418
|
+
"text/xml": ".xml"
|
|
419
|
+
};
|
|
420
|
+
var normalizeEmailContentId = (value) => {
|
|
421
|
+
const normalized = normalizeWhitespace2(value ?? "").replace(/^cid:/i, "").replace(/^<|>$/g, "");
|
|
422
|
+
return normalized ? `<${normalized}>` : undefined;
|
|
423
|
+
};
|
|
424
|
+
var inferEmailAttachmentExtension = (contentType) => {
|
|
425
|
+
if (!contentType) {
|
|
426
|
+
return ".bin";
|
|
427
|
+
}
|
|
428
|
+
const normalized = contentType.split(";")[0]?.trim().toLowerCase();
|
|
429
|
+
return (normalized ? EMAIL_ATTACHMENT_EXTENSION_BY_CONTENT_TYPE[normalized] : undefined) ?? ".bin";
|
|
430
|
+
};
|
|
431
|
+
var inferEmailAttachmentName = ({
|
|
432
|
+
contentId,
|
|
433
|
+
contentLocation,
|
|
434
|
+
contentType,
|
|
435
|
+
filename
|
|
436
|
+
}) => {
|
|
437
|
+
if (filename) {
|
|
438
|
+
return filename;
|
|
439
|
+
}
|
|
440
|
+
if (contentLocation) {
|
|
441
|
+
const locationHead = contentLocation.split(/[?#]/)[0];
|
|
442
|
+
const normalizedLocation = locationHead?.split(/[/\\]/).pop()?.trim();
|
|
443
|
+
if (normalizedLocation) {
|
|
444
|
+
return normalizedLocation;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const contentIdToken = contentId?.replace(/^<|>$/g, "").replace(/[^a-z0-9._-]+/gi, "-").replace(/^-+|-+$/g, "");
|
|
448
|
+
if (contentIdToken) {
|
|
449
|
+
return `${contentIdToken}${inferEmailAttachmentExtension(contentType)}`;
|
|
450
|
+
}
|
|
451
|
+
return `email-attachment${inferEmailAttachmentExtension(contentType)}`;
|
|
452
|
+
};
|
|
453
|
+
var parseEmailEmbeddedResourceReferences = (bodyHtml) => {
|
|
454
|
+
if (!bodyHtml) {
|
|
455
|
+
return {
|
|
456
|
+
contentIds: [],
|
|
457
|
+
contentLocations: []
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
const contentIds = [
|
|
461
|
+
...new Set(Array.from(bodyHtml.matchAll(/cid:([^"'>\s)]+)/gi), (match) => normalizeEmailContentId(match[1])).filter((value) => Boolean(value)))
|
|
462
|
+
];
|
|
463
|
+
const contentLocations = [
|
|
464
|
+
...new Set(Array.from(bodyHtml.matchAll(/\b(?:src|href)=["']([^"'#][^"']*)["']/gi), (match) => normalizeWhitespace2(match[1] ?? "")).filter((value) => Boolean(value) && !/^(?:https?:|mailto:|data:|cid:)/i.test(value)))
|
|
465
|
+
];
|
|
466
|
+
return {
|
|
467
|
+
contentIds,
|
|
468
|
+
contentLocations
|
|
469
|
+
};
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
// src/email/maildir.ts
|
|
473
|
+
var decodeEmlxMessageData = (data) => {
|
|
474
|
+
if (data.length === 0) {
|
|
475
|
+
return {
|
|
476
|
+
hasTrailingMetadata: false,
|
|
477
|
+
messageByteLength: 0,
|
|
478
|
+
raw: ""
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
let lineEnd = data.indexOf(10);
|
|
482
|
+
if (lineEnd < 0) {
|
|
483
|
+
lineEnd = data.length;
|
|
484
|
+
}
|
|
485
|
+
const headerLine = Buffer.from(data.slice(0, lineEnd)).toString("utf8").replace(/\r$/, "").trim();
|
|
486
|
+
const messageByteLength = Number.parseInt(headerLine, 10);
|
|
487
|
+
if (!Number.isFinite(messageByteLength) || messageByteLength <= 0) {
|
|
488
|
+
return {
|
|
489
|
+
hasTrailingMetadata: false,
|
|
490
|
+
messageByteLength: undefined,
|
|
491
|
+
raw: decodeUtf8(data)
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
let messageOffset = lineEnd;
|
|
495
|
+
while (messageOffset < data.length && (data[messageOffset] === 10 || data[messageOffset] === 13)) {
|
|
496
|
+
messageOffset += 1;
|
|
497
|
+
}
|
|
498
|
+
const messageEnd = Math.min(data.length, messageOffset + messageByteLength);
|
|
499
|
+
return {
|
|
500
|
+
hasTrailingMetadata: messageEnd < data.length,
|
|
501
|
+
messageByteLength,
|
|
502
|
+
raw: decodeUtf8(data.slice(messageOffset, messageEnd))
|
|
503
|
+
};
|
|
504
|
+
};
|
|
505
|
+
var MAILDIR_FOLDER_NAMES = new Set(["cur", "new"]);
|
|
506
|
+
var isLikelyRawEmailData = (raw) => {
|
|
507
|
+
const { headerBlock } = splitEmailMessage(raw);
|
|
508
|
+
if (!headerBlock || !headerBlock.includes(":")) {
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
512
|
+
let score = 0;
|
|
513
|
+
for (const name of [
|
|
514
|
+
"from",
|
|
515
|
+
"to",
|
|
516
|
+
"subject",
|
|
517
|
+
"date",
|
|
518
|
+
"message-id",
|
|
519
|
+
"in-reply-to",
|
|
520
|
+
"references",
|
|
521
|
+
"content-type",
|
|
522
|
+
"return-path",
|
|
523
|
+
"delivered-to"
|
|
524
|
+
]) {
|
|
525
|
+
if (headers.has(name)) {
|
|
526
|
+
score += 1;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return score >= 2;
|
|
530
|
+
};
|
|
531
|
+
var parseMaildirMetadata2 = (source) => {
|
|
532
|
+
if (!source) {
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const normalized = source.replace(/\\/g, "/");
|
|
536
|
+
const segments = normalized.split("/").filter(Boolean);
|
|
537
|
+
const folderIndex = segments.findLastIndex((segment) => MAILDIR_FOLDER_NAMES.has(segment));
|
|
538
|
+
if (folderIndex < 0) {
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const folder = segments[folderIndex];
|
|
542
|
+
const fileName = segments.at(-1);
|
|
543
|
+
if (!folder || !fileName) {
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const [maildirKey, flagSuffix] = fileName.split(":2,");
|
|
547
|
+
const flags = flagSuffix ? [...new Set(flagSuffix.split("").filter(Boolean).sort())] : [];
|
|
548
|
+
const stateFlags = [
|
|
549
|
+
...flags.includes("D") ? ["draft"] : [],
|
|
550
|
+
...flags.includes("F") ? ["flagged"] : [],
|
|
551
|
+
...flags.includes("P") ? ["passed"] : [],
|
|
552
|
+
...flags.includes("R") ? ["replied"] : [],
|
|
553
|
+
...flags.includes("S") ? ["read"] : ["unread"],
|
|
554
|
+
...flags.includes("T") ? ["trashed"] : []
|
|
555
|
+
];
|
|
556
|
+
const pathSegments = segments.slice(0, folderIndex);
|
|
557
|
+
const containerSource = pathSegments.join("/");
|
|
558
|
+
const familyKey = pathSegments.map((segment) => segment.trim().toLowerCase()).filter(Boolean).join("/");
|
|
559
|
+
const leaf = pathSegments.at(-1);
|
|
560
|
+
return {
|
|
561
|
+
emailMailboxFormat: "maildir",
|
|
562
|
+
emailMailboxFolder: folder,
|
|
563
|
+
...familyKey ? { emailMailboxFamilyKey: familyKey } : {},
|
|
564
|
+
...leaf ? { emailMailboxLeaf: leaf } : {},
|
|
565
|
+
...pathSegments.length > 0 ? {
|
|
566
|
+
emailMailboxPathDepth: pathSegments.length,
|
|
567
|
+
emailMailboxPathSegments: pathSegments
|
|
568
|
+
} : {},
|
|
569
|
+
...containerSource ? { emailMailboxContainerSource: containerSource } : {},
|
|
570
|
+
...flags.length > 0 ? { emailMailboxFlags: flags } : {},
|
|
571
|
+
...stateFlags.length > 0 ? { emailMailboxStateFlags: stateFlags } : {},
|
|
572
|
+
emailMailboxIsDraft: flags.includes("D"),
|
|
573
|
+
emailMailboxIsFlagged: flags.includes("F"),
|
|
574
|
+
emailMailboxIsPassed: flags.includes("P"),
|
|
575
|
+
emailMailboxIsRead: flags.includes("S"),
|
|
576
|
+
emailMailboxIsReplied: flags.includes("R"),
|
|
577
|
+
emailMailboxIsTrashed: flags.includes("T"),
|
|
578
|
+
emailMailboxIsUnread: !flags.includes("S"),
|
|
579
|
+
...maildirKey ? { emailMailboxKey: maildirKey } : {}
|
|
580
|
+
};
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
// src/formats.ts
|
|
584
|
+
import { extname } from "path";
|
|
585
|
+
var DEFAULT_BINARY_NAME = "document";
|
|
586
|
+
var TEXT_FILE_EXTENSIONS = new Set([
|
|
587
|
+
".txt",
|
|
588
|
+
".md",
|
|
589
|
+
".mdx",
|
|
590
|
+
".html",
|
|
591
|
+
".htm",
|
|
592
|
+
".json",
|
|
593
|
+
".jsonl",
|
|
594
|
+
".ndjson",
|
|
595
|
+
".csv",
|
|
596
|
+
".tsv",
|
|
597
|
+
".xml",
|
|
598
|
+
".yaml",
|
|
599
|
+
".yml",
|
|
600
|
+
".log",
|
|
601
|
+
".ts",
|
|
602
|
+
".tsx",
|
|
603
|
+
".js",
|
|
604
|
+
".jsx"
|
|
605
|
+
]);
|
|
606
|
+
var OFFICE_MIME_EXTENSIONS = {
|
|
607
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
|
608
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
|
609
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
|
|
610
|
+
"application/vnd.oasis.opendocument.text": ".odt",
|
|
611
|
+
"application/vnd.oasis.opendocument.spreadsheet": ".ods",
|
|
612
|
+
"application/vnd.oasis.opendocument.presentation": ".odp"
|
|
613
|
+
};
|
|
614
|
+
var officeExtension = (input) => OFFICE_MIME_EXTENSIONS[(input.contentType ?? "").split(";", 1)[0].trim().toLowerCase()] ?? inferExtensionFromInput(input);
|
|
615
|
+
var OFFICE_FILE_EXTENSIONS = new Set([
|
|
616
|
+
".docx",
|
|
617
|
+
".xlsx",
|
|
618
|
+
".pptx",
|
|
619
|
+
".odt",
|
|
620
|
+
".ods",
|
|
621
|
+
".odp"
|
|
622
|
+
]);
|
|
623
|
+
var LEGACY_DOCUMENT_FILE_EXTENSIONS = new Set([
|
|
624
|
+
".rtf",
|
|
625
|
+
".doc",
|
|
626
|
+
".xls",
|
|
627
|
+
".ppt",
|
|
628
|
+
".msg"
|
|
629
|
+
]);
|
|
630
|
+
var MAILBOX_CONTAINER_FILE_EXTENSIONS = new Set([".pst", ".ost"]);
|
|
631
|
+
var EMAIL_FILE_EXTENSIONS = new Set([
|
|
632
|
+
".eml",
|
|
633
|
+
".emlx",
|
|
634
|
+
".mbox",
|
|
635
|
+
".mbx"
|
|
636
|
+
]);
|
|
637
|
+
var EPUB_FILE_EXTENSIONS = new Set([".epub"]);
|
|
638
|
+
var PDF_FILE_EXTENSIONS = new Set([".pdf"]);
|
|
639
|
+
var AUDIO_FILE_EXTENSIONS = new Set([
|
|
640
|
+
".mp3",
|
|
641
|
+
".wav",
|
|
642
|
+
".m4a",
|
|
643
|
+
".aac",
|
|
644
|
+
".flac",
|
|
645
|
+
".ogg",
|
|
646
|
+
".opus"
|
|
647
|
+
]);
|
|
648
|
+
var VIDEO_FILE_EXTENSIONS = new Set([
|
|
649
|
+
".mp4",
|
|
650
|
+
".mov",
|
|
651
|
+
".mkv",
|
|
652
|
+
".webm",
|
|
653
|
+
".avi",
|
|
654
|
+
".m4v"
|
|
655
|
+
]);
|
|
656
|
+
var IMAGE_FILE_EXTENSIONS = new Set([
|
|
657
|
+
".png",
|
|
658
|
+
".jpg",
|
|
659
|
+
".jpeg",
|
|
660
|
+
".webp",
|
|
661
|
+
".tiff",
|
|
662
|
+
".tif",
|
|
663
|
+
".bmp",
|
|
664
|
+
".gif",
|
|
665
|
+
".heic"
|
|
666
|
+
]);
|
|
667
|
+
var ARCHIVE_FILE_EXTENSIONS = new Set([
|
|
668
|
+
".zip",
|
|
669
|
+
".tar",
|
|
670
|
+
".gz",
|
|
671
|
+
".tgz",
|
|
672
|
+
".bz2",
|
|
673
|
+
".xz"
|
|
674
|
+
]);
|
|
675
|
+
var TAR_FILE_EXTENSIONS = new Set([".tar"]);
|
|
676
|
+
var GZIP_FILE_EXTENSIONS = new Set([".gz", ".tgz"]);
|
|
677
|
+
var inferFormatFromPath = (path) => {
|
|
678
|
+
const extension = extname(path).toLowerCase();
|
|
679
|
+
if (extension === ".jsonl" || extension === ".ndjson") {
|
|
680
|
+
return "jsonl";
|
|
681
|
+
}
|
|
682
|
+
if (extension === ".xml") {
|
|
683
|
+
return "xml";
|
|
684
|
+
}
|
|
685
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
686
|
+
return "yaml";
|
|
687
|
+
}
|
|
688
|
+
if (extension === ".csv") {
|
|
689
|
+
return "csv";
|
|
690
|
+
}
|
|
691
|
+
if (extension === ".tsv") {
|
|
692
|
+
return "tsv";
|
|
693
|
+
}
|
|
694
|
+
if (extension === ".md" || extension === ".mdx") {
|
|
695
|
+
return "markdown";
|
|
696
|
+
}
|
|
697
|
+
if (extension === ".html" || extension === ".htm") {
|
|
698
|
+
return "html";
|
|
699
|
+
}
|
|
700
|
+
return "text";
|
|
701
|
+
};
|
|
702
|
+
var inferFormatFromUrl2 = (input) => {
|
|
703
|
+
try {
|
|
704
|
+
return inferFormatFromPath(new URL(input).pathname);
|
|
705
|
+
} catch {
|
|
706
|
+
return "text";
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
var inferFormatFromName2 = (value) => {
|
|
710
|
+
if (!value) {
|
|
711
|
+
return "text";
|
|
712
|
+
}
|
|
713
|
+
return inferFormatFromPath(value);
|
|
714
|
+
};
|
|
715
|
+
var inferFormatFromContentType2 = (contentType) => {
|
|
716
|
+
const normalizedType = (contentType || "").split(";", 1)[0].trim().toLowerCase();
|
|
717
|
+
if (OFFICE_MIME_EXTENSIONS[normalizedType])
|
|
718
|
+
return;
|
|
719
|
+
if (normalizedType.includes("html")) {
|
|
720
|
+
return "html";
|
|
721
|
+
}
|
|
722
|
+
if (normalizedType.includes("xml")) {
|
|
723
|
+
return "xml";
|
|
724
|
+
}
|
|
725
|
+
if (normalizedType.includes("yaml") || normalizedType.includes("yml")) {
|
|
726
|
+
return "yaml";
|
|
727
|
+
}
|
|
728
|
+
if (normalizedType.includes("text/csv") || normalizedType.includes("application/csv") || normalizedType.includes("comma-separated-values")) {
|
|
729
|
+
return "csv";
|
|
730
|
+
}
|
|
731
|
+
if (normalizedType.includes("tab-separated-values") || normalizedType.includes("text/tsv") || normalizedType.includes("text/tab-separated-values")) {
|
|
732
|
+
return "tsv";
|
|
733
|
+
}
|
|
734
|
+
if (normalizedType.includes("x-ndjson") || normalizedType.includes("ndjson") || normalizedType.includes("jsonl")) {
|
|
735
|
+
return "jsonl";
|
|
736
|
+
}
|
|
737
|
+
if (normalizedType.includes("text/markdown")) {
|
|
738
|
+
return "markdown";
|
|
739
|
+
}
|
|
740
|
+
if (normalizedType.includes("text/html")) {
|
|
741
|
+
return "html";
|
|
742
|
+
}
|
|
743
|
+
if (normalizedType.startsWith("text/") || normalizedType.includes("json") || normalizedType.includes("xml") || normalizedType.includes("yaml")) {
|
|
744
|
+
return "text";
|
|
745
|
+
}
|
|
746
|
+
return;
|
|
747
|
+
};
|
|
748
|
+
var decodeUploadContent2 = (input) => {
|
|
749
|
+
if (input.encoding === "base64") {
|
|
750
|
+
return Buffer.from(input.content, "base64");
|
|
751
|
+
}
|
|
752
|
+
return Buffer.from(input.content, "utf8");
|
|
753
|
+
};
|
|
754
|
+
var inferNameFromInput = (input) => input.name ?? input.path?.split(/[\\/]/).at(-1) ?? input.source?.split("/").at(-1) ?? input.title ?? DEFAULT_BINARY_NAME;
|
|
755
|
+
var inferExtensionFromInput = (input) => {
|
|
756
|
+
const candidate = input.path ?? input.name ?? input.source ?? "";
|
|
757
|
+
return extname(candidate).toLowerCase();
|
|
758
|
+
};
|
|
759
|
+
var isLikelyTextData = (data) => {
|
|
760
|
+
if (data.length === 0) {
|
|
761
|
+
return true;
|
|
762
|
+
}
|
|
763
|
+
const sample = data.subarray(0, Math.min(512, data.length));
|
|
764
|
+
let suspicious = 0;
|
|
765
|
+
for (const byte of sample) {
|
|
766
|
+
if (byte === 9 || byte === 10 || byte === 13) {
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
if (byte < 32 || byte === 127) {
|
|
770
|
+
suspicious += 1;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return suspicious / sample.length < 0.1;
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
// src/html.ts
|
|
777
|
+
var HTML_ENTITY_REPLACEMENTS = [
|
|
778
|
+
[/ /gi, " "],
|
|
779
|
+
[/&/gi, "&"],
|
|
780
|
+
[/</gi, "<"],
|
|
781
|
+
[/>/gi, ">"],
|
|
782
|
+
[/"/gi, '"'],
|
|
783
|
+
[/'/gi, "'"],
|
|
784
|
+
[/'/gi, "'"],
|
|
785
|
+
[///gi, "/"]
|
|
786
|
+
];
|
|
787
|
+
var decodeHtmlEntities = (value) => {
|
|
788
|
+
let output = value;
|
|
789
|
+
for (const [pattern, replacement] of HTML_ENTITY_REPLACEMENTS) {
|
|
790
|
+
output = output.replace(pattern, replacement);
|
|
791
|
+
}
|
|
792
|
+
output = output.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)));
|
|
793
|
+
return output.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)));
|
|
794
|
+
};
|
|
795
|
+
var formatHtmlLinkContext = (href) => {
|
|
796
|
+
const decoded = decodeHtmlEntities(href.trim());
|
|
797
|
+
if (!decoded) {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (decoded.startsWith("#")) {
|
|
801
|
+
return decoded;
|
|
802
|
+
}
|
|
803
|
+
if (/^[a-z]+:/i.test(decoded)) {
|
|
804
|
+
try {
|
|
805
|
+
const url = new URL(decoded);
|
|
806
|
+
const path = url.pathname === "/" ? "" : url.pathname;
|
|
807
|
+
return `${url.hostname}${path}`;
|
|
808
|
+
} catch {
|
|
809
|
+
return decoded;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return decoded;
|
|
813
|
+
};
|
|
814
|
+
var stripHtmlTags2 = (value) => {
|
|
815
|
+
const withoutTags = value.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ").replace(/<a\b[^>]*href=(['"])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi, (_match, _quote, href, inner) => {
|
|
816
|
+
const label = normalizeWhitespace2(stripHtmlTags2(inner));
|
|
817
|
+
const context = formatHtmlLinkContext(href);
|
|
818
|
+
if (!label) {
|
|
819
|
+
return context ?? " ";
|
|
820
|
+
}
|
|
821
|
+
if (!context || context === label) {
|
|
822
|
+
return label;
|
|
823
|
+
}
|
|
824
|
+
return `${label} (${context})`;
|
|
825
|
+
}).replace(/<br\s*\/?>/gi, `
|
|
826
|
+
`).replace(/<\/(p|div|section|article|li|ul|ol|h[1-6]|table|tr)>/gi, `
|
|
827
|
+
`).replace(/<li\b[^>]*>/gi, "- ").replace(/<[^>]+>/g, " ");
|
|
828
|
+
return decodeHtmlEntities(withoutTags);
|
|
829
|
+
};
|
|
830
|
+
var stripHtmlNoiseBlocks = (value) => value.replace(/<!--[\s\S]*?-->/g, " ").replace(/<(script|style|template|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<([a-z0-9:_-]+)\b[^>]*\b(hidden|aria-hidden=(['"])true\3)[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<(nav|footer|header|aside|form|dialog)\b[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<([a-z0-9:_-]+)\b[^>]*\b(?:id|class)=(['"])[^'"]*(nav|menu|footer|header|sidebar|promo|banner|cookie|breadcrumb|share|social|subscribe|newsletter|modal)[^'"]*\2[^>]*>[\s\S]*?<\/\1>/gi, " ");
|
|
831
|
+
var collectHtmlContentCandidates = (value) => {
|
|
832
|
+
const patterns = [
|
|
833
|
+
{
|
|
834
|
+
contentGroup: 1,
|
|
835
|
+
pattern: /<main\b[^>]*>([\s\S]*?)<\/main>/gi
|
|
836
|
+
},
|
|
837
|
+
{
|
|
838
|
+
contentGroup: 1,
|
|
839
|
+
pattern: /<article\b[^>]*>([\s\S]*?)<\/article>/gi
|
|
840
|
+
},
|
|
841
|
+
{
|
|
842
|
+
contentGroup: 3,
|
|
843
|
+
pattern: /<([a-z0-9:_-]+)\b[^>]*\brole=(['"])main\2[^>]*>([\s\S]*?)<\/\1>/gi
|
|
844
|
+
},
|
|
845
|
+
{
|
|
846
|
+
contentGroup: 4,
|
|
847
|
+
pattern: /<([a-z0-9:_-]+)\b[^>]*\b(?:id|class)=(['"])[^'"]*(content|article|main|post|body)[^'"]*\2[^>]*>([\s\S]*?)<\/\1>/gi
|
|
848
|
+
}
|
|
849
|
+
];
|
|
850
|
+
const candidates = [];
|
|
851
|
+
for (const entry of patterns) {
|
|
852
|
+
for (const match of value.matchAll(entry.pattern)) {
|
|
853
|
+
const rawCandidate = match[entry.contentGroup];
|
|
854
|
+
const candidate = typeof rawCandidate === "string" ? rawCandidate : "";
|
|
855
|
+
if (candidate.trim()) {
|
|
856
|
+
candidates.push(candidate.trim());
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
return candidates;
|
|
861
|
+
};
|
|
862
|
+
var extractMainHtmlContent2 = (value) => {
|
|
863
|
+
const trimmed = value.trim();
|
|
864
|
+
if (!/<html\b|<body\b|<main\b|<article\b/i.test(trimmed)) {
|
|
865
|
+
return value;
|
|
866
|
+
}
|
|
867
|
+
const stripped = stripHtmlNoiseBlocks(trimmed);
|
|
868
|
+
const candidates = collectHtmlContentCandidates(stripped);
|
|
869
|
+
if (candidates.length > 0) {
|
|
870
|
+
const bestCandidate = candidates.map((candidate) => ({
|
|
871
|
+
candidate,
|
|
872
|
+
score: stripHtmlTags2(candidate).replace(/\s+/g, " ").trim().length
|
|
873
|
+
})).sort((left, right) => right.score - left.score)[0]?.candidate;
|
|
874
|
+
if (bestCandidate) {
|
|
875
|
+
return bestCandidate;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
const bodyMatch = stripped.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);
|
|
879
|
+
if (bodyMatch?.[1]) {
|
|
880
|
+
return bodyMatch[1];
|
|
881
|
+
}
|
|
882
|
+
return stripped;
|
|
883
|
+
};
|
|
884
|
+
var stripHtml2 = (value) => {
|
|
885
|
+
const focused = extractMainHtmlContent2(value);
|
|
886
|
+
return normalizeWhitespace2(stripHtmlTags2(focused));
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
// src/identity.ts
|
|
890
|
+
import { createHash } from "crypto";
|
|
891
|
+
var DOCUMENT_SLUG_MAX_LENGTH = 48;
|
|
892
|
+
var slugify2 = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, DOCUMENT_SLUG_MAX_LENGTH) || "document";
|
|
893
|
+
var documentIdentity2 = (value, page, region) => `${slugify2(value)}-${createHash("sha256").update(page === undefined ? value : JSON.stringify([value, page, region ?? null])).digest("hex")}`;
|
|
894
|
+
|
|
895
|
+
// src/pdf/native.ts
|
|
896
|
+
var PDF_CHROME_LINE_MAX_LENGTH = 80;
|
|
897
|
+
var PDF_LINK_CLUSTER_LINE_MAX_LENGTH = 120;
|
|
898
|
+
var PDF_FIGURE_LABEL_PATTERN = /^(?:figure|fig\.)\s*\d+[A-Za-z]?(?:\s*[:.-]\s*|\s+|$)/i;
|
|
899
|
+
var PDF_LINK_CLUSTER_HEADING_PATTERN = /^(?:related|quick|useful|reference|references|resources|links|see also)\b/i;
|
|
900
|
+
var PDF_PROMO_HEADING_PATTERN = /^(?:start|free trial|upgrade|subscribe|newsletter|contact sales|book demo|try|learn more)\b/i;
|
|
901
|
+
var PDF_PROMO_BODY_PATTERN = /\b(?:free trial|upgrade|subscribe|newsletter|contact sales|book demo|learn more|pricing|enterprise|demo)\b/i;
|
|
902
|
+
var OCR_SUMMARY_CONFIDENCE_THRESHOLD = 0.75;
|
|
903
|
+
var OCR_SUMMARY_MIN_STRONG_TEXT_RATIO = 0.6;
|
|
904
|
+
var buildPDFNativeTextBlockSeed = (lines, pageNumber) => {
|
|
905
|
+
const normalizedLines = lines.map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
906
|
+
if (normalizedLines.length === 0) {
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const text = normalizedLines.join(`
|
|
910
|
+
`);
|
|
911
|
+
const semanticRole = normalizedLines.length >= 2 && PDF_FIGURE_LABEL_PATTERN.test(normalizedLines[0] ?? "") ? "figure_caption" : undefined;
|
|
912
|
+
return {
|
|
913
|
+
lineCount: normalizedLines.length,
|
|
914
|
+
pageNumber,
|
|
915
|
+
...semanticRole ? { semanticRole } : {},
|
|
916
|
+
text,
|
|
917
|
+
textKind: normalizedLines.some((line) => line.includes(" | ")) ? "table_like" : "paragraph"
|
|
918
|
+
};
|
|
919
|
+
};
|
|
920
|
+
var inferPDFBlockHeading2 = (text) => {
|
|
921
|
+
const lines = text.split(`
|
|
922
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
923
|
+
const candidate = lines[0];
|
|
924
|
+
if (!candidate || candidate.length > 80 || candidate.includes(" | ") || /[.!?]$/.test(candidate)) {
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
return candidate;
|
|
928
|
+
};
|
|
929
|
+
var extractPDFFigureLabel2 = (text) => {
|
|
930
|
+
const lines = text.split(`
|
|
931
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
932
|
+
const candidate = lines[0];
|
|
933
|
+
return candidate && PDF_FIGURE_LABEL_PATTERN.test(candidate) ? candidate : undefined;
|
|
934
|
+
};
|
|
935
|
+
var splitPDFNativeTextBlocks = (text, pageNumber) => {
|
|
936
|
+
const lines = text.split(`
|
|
937
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
938
|
+
if (lines.length === 0) {
|
|
939
|
+
return [];
|
|
940
|
+
}
|
|
941
|
+
const blocks = [];
|
|
942
|
+
let currentLines = [];
|
|
943
|
+
let currentKind;
|
|
944
|
+
let currentSemanticRole;
|
|
945
|
+
const flush = () => {
|
|
946
|
+
if (currentLines.length === 0) {
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
const block = buildPDFNativeTextBlockSeed(currentLines, pageNumber);
|
|
950
|
+
if (block) {
|
|
951
|
+
blocks.push(block);
|
|
952
|
+
}
|
|
953
|
+
currentLines = [];
|
|
954
|
+
currentKind = undefined;
|
|
955
|
+
currentSemanticRole = undefined;
|
|
956
|
+
};
|
|
957
|
+
for (const [index, line] of lines.entries()) {
|
|
958
|
+
const lineKind = line.includes(" | ") ? "table_like" : "paragraph";
|
|
959
|
+
const isFigureLabel = PDF_FIGURE_LABEL_PATTERN.test(line);
|
|
960
|
+
if (isFigureLabel) {
|
|
961
|
+
flush();
|
|
962
|
+
currentKind = "paragraph";
|
|
963
|
+
currentSemanticRole = "figure_caption";
|
|
964
|
+
currentLines.push(line);
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
if (currentSemanticRole === "figure_caption") {
|
|
968
|
+
if (lineKind === "paragraph" && currentLines.length < 2) {
|
|
969
|
+
currentLines.push(line);
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
flush();
|
|
973
|
+
}
|
|
974
|
+
if (currentKind && lineKind !== currentKind) {
|
|
975
|
+
flush();
|
|
976
|
+
}
|
|
977
|
+
currentKind = lineKind;
|
|
978
|
+
currentLines.push(line);
|
|
979
|
+
}
|
|
980
|
+
flush();
|
|
981
|
+
return blocks;
|
|
982
|
+
};
|
|
983
|
+
var assignPDFBlockNumbers = (blocks) => blocks.map((block, index) => ({
|
|
984
|
+
...block,
|
|
985
|
+
blockNumber: index + 1
|
|
986
|
+
}));
|
|
987
|
+
var isLikelyPDFPageLabel = (value) => /^page\s+\d+(?:\s+of\s+\d+)?$/i.test(value.trim());
|
|
988
|
+
var isLikelyPDFChromeLine = (value) => {
|
|
989
|
+
const normalized = value.trim();
|
|
990
|
+
if (!normalized) {
|
|
991
|
+
return false;
|
|
992
|
+
}
|
|
993
|
+
return isLikelyPDFPageLabel(normalized) || /\b(?:header|footer)\s*$/i.test(normalized);
|
|
994
|
+
};
|
|
995
|
+
var isLikelyPDFLinkLine = (value) => {
|
|
996
|
+
const normalized = value.trim();
|
|
997
|
+
if (!normalized || normalized.length > PDF_LINK_CLUSTER_LINE_MAX_LENGTH) {
|
|
998
|
+
return false;
|
|
999
|
+
}
|
|
1000
|
+
return /^https?:\/\//i.test(normalized) || /^www\./i.test(normalized) || /^\/[A-Za-z0-9/_#?&=%.-]+$/.test(normalized) || /\((?:https?:\/\/|\/)[^)]+\)/i.test(normalized);
|
|
1001
|
+
};
|
|
1002
|
+
var isLikelyPDFLinkClusterBlock = (block) => {
|
|
1003
|
+
if (block.semanticRole || block.textKind !== "paragraph") {
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
const lines = block.text.split(`
|
|
1007
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
1008
|
+
if (lines.length === 1) {
|
|
1009
|
+
return isLikelyPDFLinkLine(lines[0] ?? "");
|
|
1010
|
+
}
|
|
1011
|
+
if (lines.length < 2) {
|
|
1012
|
+
return false;
|
|
1013
|
+
}
|
|
1014
|
+
const heading = lines[0] ?? "";
|
|
1015
|
+
const bodyLines = lines.slice(1);
|
|
1016
|
+
const linkLikeCount = bodyLines.filter((line) => isLikelyPDFLinkLine(line)).length;
|
|
1017
|
+
if (bodyLines.length > 0 && linkLikeCount === bodyLines.length && PDF_LINK_CLUSTER_HEADING_PATTERN.test(heading)) {
|
|
1018
|
+
return true;
|
|
1019
|
+
}
|
|
1020
|
+
return linkLikeCount >= 2 && linkLikeCount >= Math.ceil(lines.length * 0.6);
|
|
1021
|
+
};
|
|
1022
|
+
var isLikelyPDFPromoBlock = (block) => {
|
|
1023
|
+
if (block.semanticRole || block.textKind !== "paragraph") {
|
|
1024
|
+
return false;
|
|
1025
|
+
}
|
|
1026
|
+
const lines = block.text.split(`
|
|
1027
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
1028
|
+
if (lines.length === 1) {
|
|
1029
|
+
return PDF_PROMO_HEADING_PATTERN.test(lines[0] ?? "");
|
|
1030
|
+
}
|
|
1031
|
+
if (lines.length < 2 || lines.length > 4) {
|
|
1032
|
+
return false;
|
|
1033
|
+
}
|
|
1034
|
+
const heading = lines[0] ?? "";
|
|
1035
|
+
const bodyLines = lines.slice(1);
|
|
1036
|
+
const promoLikeCount = bodyLines.filter((line) => line.length <= PDF_LINK_CLUSTER_LINE_MAX_LENGTH && (PDF_PROMO_BODY_PATTERN.test(line) || isLikelyPDFLinkLine(line))).length;
|
|
1037
|
+
if (PDF_PROMO_HEADING_PATTERN.test(heading) && promoLikeCount >= Math.max(1, bodyLines.length - 1)) {
|
|
1038
|
+
return true;
|
|
1039
|
+
}
|
|
1040
|
+
return false;
|
|
1041
|
+
};
|
|
1042
|
+
var suppressRepeatedPDFChrome = (blocks) => {
|
|
1043
|
+
const linePages = new Map;
|
|
1044
|
+
for (const block of blocks) {
|
|
1045
|
+
for (const line of block.text.split(`
|
|
1046
|
+
`)) {
|
|
1047
|
+
const normalized = normalizeWhitespace2(line);
|
|
1048
|
+
if (!normalized || normalized.length > PDF_CHROME_LINE_MAX_LENGTH) {
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
const pages = linePages.get(normalized) ?? new Set;
|
|
1052
|
+
pages.add(block.pageNumber);
|
|
1053
|
+
linePages.set(normalized, pages);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
return blocks.map((block) => {
|
|
1057
|
+
const keptLines = block.text.split(`
|
|
1058
|
+
`).map((line) => normalizeWhitespace2(line)).filter((line) => {
|
|
1059
|
+
if (!line) {
|
|
1060
|
+
return false;
|
|
1061
|
+
}
|
|
1062
|
+
if (isLikelyPDFChromeLine(line)) {
|
|
1063
|
+
return false;
|
|
1064
|
+
}
|
|
1065
|
+
const repeatedPages = linePages.get(line);
|
|
1066
|
+
if (line.length <= PDF_CHROME_LINE_MAX_LENGTH && repeatedPages && repeatedPages.size > 1) {
|
|
1067
|
+
return false;
|
|
1068
|
+
}
|
|
1069
|
+
return true;
|
|
1070
|
+
});
|
|
1071
|
+
const text = keptLines.join(`
|
|
1072
|
+
`);
|
|
1073
|
+
if (!text) {
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
return {
|
|
1077
|
+
...block,
|
|
1078
|
+
lineCount: text.split(`
|
|
1079
|
+
`).filter(Boolean).length,
|
|
1080
|
+
text,
|
|
1081
|
+
textKind: text.includes(" | ") ? "table_like" : "paragraph"
|
|
1082
|
+
};
|
|
1083
|
+
}).filter((value) => Boolean(value));
|
|
1084
|
+
};
|
|
1085
|
+
var suppressNonContentPDFBlocks = (blocks) => blocks.filter((block) => !isLikelyPDFLinkClusterBlock(block) && !isLikelyPDFPromoBlock(block));
|
|
1086
|
+
var mergePDFHeadingContinuationBlocks = (blocks) => {
|
|
1087
|
+
const merged = [];
|
|
1088
|
+
for (let index = 0;index < blocks.length; index += 1) {
|
|
1089
|
+
const block = blocks[index];
|
|
1090
|
+
if (!block) {
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
const lines = block.text.split(`
|
|
1094
|
+
`).map((line) => normalizeWhitespace2(line)).filter(Boolean);
|
|
1095
|
+
const nextBlock = blocks[index + 1];
|
|
1096
|
+
const isHeadingOnlyBlock = !block.semanticRole && block.textKind === "paragraph" && lines.length === 1 && inferPDFBlockHeading2(block.text) === lines[0];
|
|
1097
|
+
const canMergeWithNext = isHeadingOnlyBlock && nextBlock && nextBlock.pageNumber === block.pageNumber && !nextBlock.semanticRole && nextBlock.textKind === "paragraph" && inferPDFBlockHeading2(nextBlock.text) === undefined;
|
|
1098
|
+
if (canMergeWithNext) {
|
|
1099
|
+
const text = [block.text, nextBlock.text].flatMap((value) => value.split(`
|
|
1100
|
+
`)).map((line) => normalizeWhitespace2(line)).filter(Boolean).join(`
|
|
1101
|
+
`);
|
|
1102
|
+
merged.push({
|
|
1103
|
+
...block,
|
|
1104
|
+
lineCount: text.split(`
|
|
1105
|
+
`).filter(Boolean).length,
|
|
1106
|
+
text
|
|
1107
|
+
});
|
|
1108
|
+
index += 1;
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
merged.push(block);
|
|
1112
|
+
}
|
|
1113
|
+
return merged;
|
|
1114
|
+
};
|
|
1115
|
+
var associatePDFNativeFigureBodies = (blocks) => blocks.map((block, index) => {
|
|
1116
|
+
if (block.semanticRole || block.textKind !== "paragraph" || inferPDFBlockHeading2(block.text)) {
|
|
1117
|
+
return block;
|
|
1118
|
+
}
|
|
1119
|
+
const previousBlock = index > 0 ? blocks[index - 1] : undefined;
|
|
1120
|
+
if (!previousBlock || previousBlock.pageNumber !== block.pageNumber || previousBlock.semanticRole !== "figure_caption") {
|
|
1121
|
+
return block;
|
|
1122
|
+
}
|
|
1123
|
+
return {
|
|
1124
|
+
...block,
|
|
1125
|
+
semanticRole: "figure_body"
|
|
1126
|
+
};
|
|
1127
|
+
});
|
|
1128
|
+
var extractNativePDFText = async (data) => {
|
|
1129
|
+
await import("pdfjs-dist/legacy/build/pdf.worker.mjs");
|
|
1130
|
+
const { getDocument } = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
|
1131
|
+
const task = getDocument({
|
|
1132
|
+
data: Uint8Array.from(data),
|
|
1133
|
+
disableFontFace: true,
|
|
1134
|
+
useSystemFonts: true,
|
|
1135
|
+
stopAtErrors: true
|
|
1136
|
+
});
|
|
1137
|
+
try {
|
|
1138
|
+
const pdf = await task.promise;
|
|
1139
|
+
const seeds = [];
|
|
1140
|
+
for (let pageNumber = 1;pageNumber <= pdf.numPages; pageNumber++) {
|
|
1141
|
+
const page = await pdf.getPage(pageNumber);
|
|
1142
|
+
try {
|
|
1143
|
+
const content = await page.getTextContent();
|
|
1144
|
+
let block = "";
|
|
1145
|
+
let previousY;
|
|
1146
|
+
let previousHeight = 0;
|
|
1147
|
+
const flush = () => {
|
|
1148
|
+
seeds.push(...splitPDFNativeTextBlocks(block, pageNumber));
|
|
1149
|
+
block = "";
|
|
1150
|
+
};
|
|
1151
|
+
for (const item of content.items) {
|
|
1152
|
+
if (!("str" in item))
|
|
1153
|
+
continue;
|
|
1154
|
+
const y = item.transform[5];
|
|
1155
|
+
const height = Math.abs(item.height) || previousHeight || 1;
|
|
1156
|
+
if (previousY !== undefined && Math.abs(y - previousY) > 0.5) {
|
|
1157
|
+
if (Math.abs(y - previousY) > Math.max(height, previousHeight) * 1.8) {
|
|
1158
|
+
flush();
|
|
1159
|
+
} else if (block && !block.endsWith(`
|
|
1160
|
+
`)) {
|
|
1161
|
+
block += `
|
|
1162
|
+
`;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
block += item.str;
|
|
1166
|
+
if (item.hasEOL)
|
|
1167
|
+
block += `
|
|
1168
|
+
`;
|
|
1169
|
+
previousY = y;
|
|
1170
|
+
previousHeight = height;
|
|
1171
|
+
}
|
|
1172
|
+
flush();
|
|
1173
|
+
} finally {
|
|
1174
|
+
page.cleanup();
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
const blocks = assignPDFBlockNumbers(seeds);
|
|
1178
|
+
const visibleBlocks = assignPDFBlockNumbers(associatePDFNativeFigureBodies(mergePDFHeadingContinuationBlocks(suppressNonContentPDFBlocks(suppressRepeatedPDFChrome(blocks)))));
|
|
1179
|
+
return {
|
|
1180
|
+
pageCount: pdf.numPages,
|
|
1181
|
+
text: normalizeWhitespace2(visibleBlocks.map((block) => block.text).join(`
|
|
1182
|
+
|
|
1183
|
+
`)),
|
|
1184
|
+
textBlockCount: visibleBlocks.length,
|
|
1185
|
+
textBlocks: visibleBlocks
|
|
1186
|
+
};
|
|
1187
|
+
} finally {
|
|
1188
|
+
await task.destroy();
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
|
|
1192
|
+
// src/archive/containers.ts
|
|
1193
|
+
import { gunzipSync, inflateRawSync } from "zlib";
|
|
1194
|
+
var isZipData = (data) => data.length >= 4 && data[0] === 80 && data[1] === 75 && data[2] === 3 && data[3] === 4;
|
|
1195
|
+
var zipDirectory = (data) => {
|
|
1196
|
+
for (let end = data.length - 22;end >= Math.max(0, data.length - 22 - 65535); end--) {
|
|
1197
|
+
if (readUInt32LE(data, end) !== 101010256 || end + 22 + readUInt16LE(data, end + 20) !== data.length)
|
|
1198
|
+
continue;
|
|
1199
|
+
const count = readUInt16LE(data, end + 10);
|
|
1200
|
+
const size = readUInt32LE(data, end + 12);
|
|
1201
|
+
let cursor = readUInt32LE(data, end + 16);
|
|
1202
|
+
if (count === 65535 || cursor === 4294967295 || size === 4294967295)
|
|
1203
|
+
throw new Error("ZIP64 archives are unsupported");
|
|
1204
|
+
if (readUInt16LE(data, end + 4) || readUInt16LE(data, end + 6) || readUInt16LE(data, end + 8) !== count)
|
|
1205
|
+
throw new Error("Multi-disk ZIP archives are unsupported");
|
|
1206
|
+
const limit = cursor + size;
|
|
1207
|
+
if (limit > end)
|
|
1208
|
+
throw new Error("Truncated ZIP central directory");
|
|
1209
|
+
const result = [];
|
|
1210
|
+
for (let index = 0;index < count; index++) {
|
|
1211
|
+
if (cursor + 46 > limit || readUInt32LE(data, cursor) !== 33639248)
|
|
1212
|
+
throw new Error("Invalid ZIP central directory");
|
|
1213
|
+
const offset = readUInt32LE(data, cursor + 42);
|
|
1214
|
+
const compressedSize = readUInt32LE(data, cursor + 20);
|
|
1215
|
+
if (offset === 4294967295 || compressedSize === 4294967295)
|
|
1216
|
+
throw new Error("ZIP64 entries are unsupported");
|
|
1217
|
+
if (offset + 30 > data.length || readUInt32LE(data, offset) !== 67324752)
|
|
1218
|
+
throw new Error("Invalid ZIP local header offset");
|
|
1219
|
+
result.push({ offset, size: compressedSize });
|
|
1220
|
+
cursor += 46 + readUInt16LE(data, cursor + 28) + readUInt16LE(data, cursor + 30) + readUInt16LE(data, cursor + 32);
|
|
1221
|
+
if (cursor > limit)
|
|
1222
|
+
throw new Error("Truncated ZIP directory entry");
|
|
1223
|
+
}
|
|
1224
|
+
return result;
|
|
1225
|
+
}
|
|
1226
|
+
return;
|
|
1227
|
+
};
|
|
1228
|
+
var unzipEntries = (data) => {
|
|
1229
|
+
const entries = [];
|
|
1230
|
+
const directory = zipDirectory(data);
|
|
1231
|
+
let entryIndex = 0;
|
|
1232
|
+
let offset = directory?.[0]?.offset ?? 0;
|
|
1233
|
+
while (offset + 30 <= data.length) {
|
|
1234
|
+
const signature = readUInt32LE(data, offset);
|
|
1235
|
+
if (signature !== 67324752) {
|
|
1236
|
+
break;
|
|
1237
|
+
}
|
|
1238
|
+
const compressionMethod = readUInt16LE(data, offset + 8);
|
|
1239
|
+
const flags = readUInt16LE(data, offset + 6);
|
|
1240
|
+
if (flags & 1)
|
|
1241
|
+
throw new Error("Encrypted ZIP entries are unsupported");
|
|
1242
|
+
if (flags & 8 && !directory)
|
|
1243
|
+
throw new Error("ZIP data descriptor requires a central directory");
|
|
1244
|
+
const compressedSize = directory?.[entryIndex]?.size ?? readUInt32LE(data, offset + 18);
|
|
1245
|
+
const fileNameLength = readUInt16LE(data, offset + 26);
|
|
1246
|
+
const extraFieldLength = readUInt16LE(data, offset + 28);
|
|
1247
|
+
const fileNameStart = offset + 30;
|
|
1248
|
+
const fileNameEnd = fileNameStart + fileNameLength;
|
|
1249
|
+
const fileName = decodeUtf8(data.subarray(fileNameStart, fileNameEnd));
|
|
1250
|
+
const dataStart = fileNameEnd + extraFieldLength;
|
|
1251
|
+
const dataEnd = dataStart + compressedSize;
|
|
1252
|
+
if (fileNameEnd > data.length || dataStart > data.length || dataEnd > data.length)
|
|
1253
|
+
throw new Error("Truncated ZIP entry");
|
|
1254
|
+
const raw = data.subarray(dataStart, dataEnd);
|
|
1255
|
+
let entryData;
|
|
1256
|
+
if (compressionMethod === 0) {
|
|
1257
|
+
entryData = raw;
|
|
1258
|
+
} else if (compressionMethod === 8) {
|
|
1259
|
+
entryData = inflateRawSync(Buffer.from(raw));
|
|
1260
|
+
} else {
|
|
1261
|
+
throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${fileName}`);
|
|
1262
|
+
}
|
|
1263
|
+
if (!fileName.endsWith("/")) {
|
|
1264
|
+
entries.push({
|
|
1265
|
+
data: entryData,
|
|
1266
|
+
path: fileName
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
if (directory) {
|
|
1270
|
+
entryIndex += 1;
|
|
1271
|
+
if (entryIndex === directory.length)
|
|
1272
|
+
break;
|
|
1273
|
+
offset = directory[entryIndex].offset;
|
|
1274
|
+
} else
|
|
1275
|
+
offset = dataEnd;
|
|
1276
|
+
}
|
|
1277
|
+
return entries;
|
|
1278
|
+
};
|
|
1279
|
+
var untarEntries = (data) => {
|
|
1280
|
+
const entries = [];
|
|
1281
|
+
let offset = 0;
|
|
1282
|
+
while (offset + 512 <= data.length) {
|
|
1283
|
+
const header = data.subarray(offset, offset + 512);
|
|
1284
|
+
if (header.every((byte) => byte === 0)) {
|
|
1285
|
+
break;
|
|
1286
|
+
}
|
|
1287
|
+
const name = decodeUtf8(header.subarray(0, 100)).replace(/\0.*$/, "");
|
|
1288
|
+
const sizeText = decodeUtf8(header.subarray(124, 136)).replace(/\0.*$/, "").trim();
|
|
1289
|
+
const size = sizeText ? parseInt(sizeText, 8) : 0;
|
|
1290
|
+
const typeFlag = header[156];
|
|
1291
|
+
const dataStart = offset + 512;
|
|
1292
|
+
const dataEnd = dataStart + size;
|
|
1293
|
+
if (typeFlag !== 53 && typeFlag !== 0 && typeFlag !== 48) {
|
|
1294
|
+
offset = dataStart + Math.ceil(size / 512) * 512;
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
if (name) {
|
|
1298
|
+
entries.push({
|
|
1299
|
+
data: data.subarray(dataStart, dataEnd),
|
|
1300
|
+
path: name
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
offset = dataStart + Math.ceil(size / 512) * 512;
|
|
1304
|
+
}
|
|
1305
|
+
return entries;
|
|
1306
|
+
};
|
|
1307
|
+
var decodeGzipEntries = (data, input) => {
|
|
1308
|
+
const ungzipped = gunzipSync(Buffer.from(data));
|
|
1309
|
+
const sourceName = inferNameFromInput(input);
|
|
1310
|
+
const stripped = sourceName.replace(/\.t?gz$/i, "").replace(/\.gz$/i, "");
|
|
1311
|
+
if (sourceName.toLowerCase().endsWith(".tgz") || sourceName.toLowerCase().endsWith(".tar.gz")) {
|
|
1312
|
+
return untarEntries(ungzipped);
|
|
1313
|
+
}
|
|
1314
|
+
return [
|
|
1315
|
+
{
|
|
1316
|
+
data: ungzipped,
|
|
1317
|
+
path: stripped || "archive-entry"
|
|
1318
|
+
}
|
|
1319
|
+
];
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
// src/extractors/supports.ts
|
|
1323
|
+
var textExtractorSupports = (input) => {
|
|
1324
|
+
const mediaType = (input.contentType ?? "").split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
1325
|
+
if (/^(image|audio|video)\//u.test(mediaType) || [
|
|
1326
|
+
"application/pdf",
|
|
1327
|
+
"application/zip",
|
|
1328
|
+
"application/gzip",
|
|
1329
|
+
"application/postscript",
|
|
1330
|
+
"application/vnd.ms-office"
|
|
1331
|
+
].includes(mediaType) || mediaType.startsWith("application/vnd.openxmlformats-officedocument.") || !isLikelyTextData(input.data))
|
|
1332
|
+
return false;
|
|
1333
|
+
if (input.format) {
|
|
1334
|
+
return true;
|
|
1335
|
+
}
|
|
1336
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1337
|
+
if (contentType.startsWith("text/") || contentType.includes("json") || contentType.includes("xml") || contentType.includes("yaml") || contentType.includes("javascript")) {
|
|
1338
|
+
return true;
|
|
1339
|
+
}
|
|
1340
|
+
if (TEXT_FILE_EXTENSIONS.has(inferExtensionFromInput(input))) {
|
|
1341
|
+
return true;
|
|
1342
|
+
}
|
|
1343
|
+
return isLikelyTextData(input.data);
|
|
1344
|
+
};
|
|
1345
|
+
var pdfExtractorSupports = (input) => {
|
|
1346
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1347
|
+
if (contentType.includes("application/pdf")) {
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
return PDF_FILE_EXTENSIONS.has(inferExtensionFromInput(input));
|
|
1351
|
+
};
|
|
1352
|
+
var mediaExtractorSupports = (input) => {
|
|
1353
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1354
|
+
if (contentType.startsWith("audio/") || contentType.startsWith("video/")) {
|
|
1355
|
+
return true;
|
|
1356
|
+
}
|
|
1357
|
+
const extension = inferExtensionFromInput(input);
|
|
1358
|
+
return AUDIO_FILE_EXTENSIONS.has(extension) || VIDEO_FILE_EXTENSIONS.has(extension);
|
|
1359
|
+
};
|
|
1360
|
+
var officeExtractorSupports = (input) => {
|
|
1361
|
+
const extension = officeExtension(input);
|
|
1362
|
+
return OFFICE_FILE_EXTENSIONS.has(extension);
|
|
1363
|
+
};
|
|
1364
|
+
var legacyExtractorSupports = (input) => LEGACY_DOCUMENT_FILE_EXTENSIONS.has(inferExtensionFromInput(input));
|
|
1365
|
+
var epubExtractorSupports = (input) => EPUB_FILE_EXTENSIONS.has(inferExtensionFromInput(input));
|
|
1366
|
+
var emailExtractorSupports = (input) => {
|
|
1367
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1368
|
+
if (contentType.includes("message/rfc822") || contentType.includes("application/eml") || contentType.includes("application/emlx") || contentType.includes("application/x-emlx") || contentType.includes("application/mbox") || contentType.includes("application/x-mbox")) {
|
|
1369
|
+
return true;
|
|
1370
|
+
}
|
|
1371
|
+
const extension = inferExtensionFromInput(input);
|
|
1372
|
+
if (EMAIL_FILE_EXTENSIONS.has(extension)) {
|
|
1373
|
+
return true;
|
|
1374
|
+
}
|
|
1375
|
+
if (parseMaildirMetadata2(input.source ?? input.path ?? input.name) && isLikelyRawEmailData(decodeUtf8(input.data))) {
|
|
1376
|
+
return true;
|
|
1377
|
+
}
|
|
1378
|
+
return false;
|
|
1379
|
+
};
|
|
1380
|
+
var mailboxContainerExtractorSupports = (input) => {
|
|
1381
|
+
const extension = inferExtensionFromInput(input);
|
|
1382
|
+
return MAILBOX_CONTAINER_FILE_EXTENSIONS.has(extension);
|
|
1383
|
+
};
|
|
1384
|
+
var imageExtractorSupports = (input) => {
|
|
1385
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1386
|
+
if (contentType.startsWith("image/")) {
|
|
1387
|
+
return true;
|
|
1388
|
+
}
|
|
1389
|
+
return IMAGE_FILE_EXTENSIONS.has(inferExtensionFromInput(input));
|
|
1390
|
+
};
|
|
1391
|
+
var archiveExtractorSupports = (input) => {
|
|
1392
|
+
const contentType = (input.contentType ?? "").toLowerCase();
|
|
1393
|
+
if (contentType.includes("zip") || contentType.includes("tar") || contentType.includes("gzip") || contentType.includes("x-gzip")) {
|
|
1394
|
+
return true;
|
|
1395
|
+
}
|
|
1396
|
+
return ARCHIVE_FILE_EXTENSIONS.has(inferExtensionFromInput(input));
|
|
1397
|
+
};
|
|
1398
|
+
|
|
1399
|
+
// src/extractors/archive.ts
|
|
1400
|
+
import { basename } from "path";
|
|
1401
|
+
var createBuiltinArchiveExpander2 = () => ({
|
|
1402
|
+
name: "builtin_archive",
|
|
1403
|
+
expand: (input) => {
|
|
1404
|
+
const extension = inferExtensionFromInput(input);
|
|
1405
|
+
if (isZipData(input.data) || extension === ".zip") {
|
|
1406
|
+
return {
|
|
1407
|
+
entries: unzipEntries(input.data),
|
|
1408
|
+
metadata: { archiveType: "zip" }
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
if (TAR_FILE_EXTENSIONS.has(extension)) {
|
|
1412
|
+
return {
|
|
1413
|
+
entries: untarEntries(input.data),
|
|
1414
|
+
metadata: { archiveType: "tar" }
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
if (GZIP_FILE_EXTENSIONS.has(extension)) {
|
|
1418
|
+
return {
|
|
1419
|
+
entries: decodeGzipEntries(input.data, input),
|
|
1420
|
+
metadata: {
|
|
1421
|
+
archiveType: extension === ".tgz" || (input.name ?? input.path ?? "").toLowerCase().endsWith(".tar.gz") ? "tgz" : "gzip"
|
|
1422
|
+
}
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
throw new Error(`Builtin archive expander does not support ${inferNameFromInput(input)}`);
|
|
1426
|
+
}
|
|
1427
|
+
});
|
|
1428
|
+
var expandArchiveEntry = async (entry, archiveInput, extractors, registry) => {
|
|
1429
|
+
const parentArchiveLineage = Array.isArray(archiveInput.metadata?.archiveLineage) ? archiveInput.metadata.archiveLineage.filter((value) => typeof value === "string" && value.trim().length > 0) : [];
|
|
1430
|
+
const entryArchiveLineage = entry.path.split(/[\\/]/).map((segment) => normalizeWhitespace2(segment)).filter(Boolean);
|
|
1431
|
+
const archiveLineage = [...parentArchiveLineage, ...entryArchiveLineage];
|
|
1432
|
+
const parentArchivePath = typeof archiveInput.metadata?.archivePath === "string" && archiveInput.metadata.archivePath.trim().length > 0 ? archiveInput.metadata.archivePath.trim() : undefined;
|
|
1433
|
+
const archiveFullPath = parentArchivePath ? `${parentArchivePath}!${entry.path}` : entry.path;
|
|
1434
|
+
const archiveRootName = (typeof archiveInput.metadata?.archiveRootName === "string" && archiveInput.metadata.archiveRootName.trim().length > 0 ? archiveInput.metadata.archiveRootName.trim() : undefined) ?? archiveInput.name ?? archiveInput.path?.split(/[/\\]/).pop() ?? archiveInput.source;
|
|
1435
|
+
const archiveRootSource = (typeof archiveInput.metadata?.archiveRootSource === "string" && archiveInput.metadata.archiveRootSource.trim().length > 0 ? archiveInput.metadata.archiveRootSource.trim() : undefined) ?? archiveInput.source ?? archiveInput.path ?? archiveInput.name;
|
|
1436
|
+
const documents = await extractDocuments2({
|
|
1437
|
+
contentType: entry.contentType,
|
|
1438
|
+
data: entry.data,
|
|
1439
|
+
extractorRegistry: archiveInput.extractorRegistry,
|
|
1440
|
+
format: entry.format,
|
|
1441
|
+
metadata: {
|
|
1442
|
+
...archiveInput.metadata ?? {},
|
|
1443
|
+
...entry.metadata ?? {},
|
|
1444
|
+
archiveEntryName: basename(entry.path),
|
|
1445
|
+
archiveParentName: archiveInput.name ?? archiveInput.path?.split(/[/\\]/).pop() ?? archiveInput.source,
|
|
1446
|
+
archiveParentSource: archiveInput.source ?? archiveInput.path ?? archiveInput.name,
|
|
1447
|
+
archiveContainerPath: parentArchivePath,
|
|
1448
|
+
archiveDepth: archiveLineage.length,
|
|
1449
|
+
archiveFullPath,
|
|
1450
|
+
archiveLineage,
|
|
1451
|
+
archivePath: entry.path,
|
|
1452
|
+
archiveRootName,
|
|
1453
|
+
archiveRootSource,
|
|
1454
|
+
archiveNestedDepth: parentArchiveLineage.length + 1,
|
|
1455
|
+
fileKind: "archive_entry"
|
|
1456
|
+
},
|
|
1457
|
+
name: basename(entry.path),
|
|
1458
|
+
source: archiveInput.source && !archiveInput.source.startsWith("http") ? `${archiveInput.source}#${entry.path}` : entry.path,
|
|
1459
|
+
title: basename(entry.path)
|
|
1460
|
+
}, extractors, registry);
|
|
1461
|
+
return documents;
|
|
1462
|
+
};
|
|
1463
|
+
var createArchiveFileExtractor2 = (expander, options = {}) => ({
|
|
1464
|
+
name: `absolute_archive:${expander.name}`,
|
|
1465
|
+
supports: archiveExtractorSupports,
|
|
1466
|
+
extract: async (input) => {
|
|
1467
|
+
const expanded = await expander.expand(input);
|
|
1468
|
+
const documents = await Promise.all(expanded.entries.map((entry) => expandArchiveEntry(entry, input, options.entryExtractors ?? DEFAULT_FILE_EXTRACTORS2)));
|
|
1469
|
+
return documents.flat().map((document) => ({
|
|
1470
|
+
...document,
|
|
1471
|
+
metadata: {
|
|
1472
|
+
...expanded.metadata ?? {},
|
|
1473
|
+
...document.metadata ?? {},
|
|
1474
|
+
fileKind: "archive"
|
|
1475
|
+
}
|
|
1476
|
+
}));
|
|
1477
|
+
}
|
|
1478
|
+
});
|
|
1479
|
+
|
|
1480
|
+
// src/email/headers.ts
|
|
1481
|
+
var parseEmailAddressList = (value) => {
|
|
1482
|
+
if (!value) {
|
|
1483
|
+
return {
|
|
1484
|
+
addresses: [],
|
|
1485
|
+
displayNames: [],
|
|
1486
|
+
entries: []
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
const tokens = value.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((entry) => normalizeWhitespace2(entry)).filter(Boolean);
|
|
1490
|
+
const entries = tokens.map((entry) => {
|
|
1491
|
+
const angleMatch = entry.match(/^(.*?)(?:<([^>]+)>)$/);
|
|
1492
|
+
if (angleMatch) {
|
|
1493
|
+
const address = normalizeWhitespace2(angleMatch[2]?.trim().toLowerCase() ?? "");
|
|
1494
|
+
if (!address) {
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
const displayName = normalizeWhitespace2((angleMatch[1] ?? "").trim().replace(/^"+|"+$/g, ""));
|
|
1498
|
+
return {
|
|
1499
|
+
address,
|
|
1500
|
+
...displayName ? { displayName } : {},
|
|
1501
|
+
raw: entry
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
const bareAddressMatch = entry.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i)?.[0] ?? "";
|
|
1505
|
+
const address = normalizeWhitespace2(bareAddressMatch.trim().toLowerCase());
|
|
1506
|
+
if (!address) {
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
const displayName = normalizeWhitespace2(entry.replace(bareAddressMatch, "").replace(/[()"]/g, ""));
|
|
1510
|
+
return {
|
|
1511
|
+
address,
|
|
1512
|
+
...displayName ? { displayName } : {},
|
|
1513
|
+
raw: entry
|
|
1514
|
+
};
|
|
1515
|
+
}).filter((entry) => Boolean(entry));
|
|
1516
|
+
return {
|
|
1517
|
+
addresses: entries.map((entry) => entry.address),
|
|
1518
|
+
displayNames: entries.map((entry) => entry.displayName).filter((value) => typeof value === "string"),
|
|
1519
|
+
entries
|
|
1520
|
+
};
|
|
1521
|
+
};
|
|
1522
|
+
var normalizeEmailTimestamp = (value) => {
|
|
1523
|
+
if (!value) {
|
|
1524
|
+
return;
|
|
1525
|
+
}
|
|
1526
|
+
const candidates = [
|
|
1527
|
+
value,
|
|
1528
|
+
value.replace(/\bat\b/gi, " ").replace(/\s+/g, " ").trim(),
|
|
1529
|
+
`${value.replace(/\bat\b/gi, " ").replace(/\s+/g, " ").trim()} UTC`
|
|
1530
|
+
];
|
|
1531
|
+
for (const candidate of candidates) {
|
|
1532
|
+
const timestamp = Date.parse(candidate);
|
|
1533
|
+
if (Number.isFinite(timestamp)) {
|
|
1534
|
+
return new Date(timestamp).toISOString();
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
return;
|
|
1538
|
+
};
|
|
1539
|
+
var parseEmailMessageLineage = (metadata) => {
|
|
1540
|
+
if (!Array.isArray(metadata?.emailMessageLineage)) {
|
|
1541
|
+
return [];
|
|
1542
|
+
}
|
|
1543
|
+
return metadata.emailMessageLineage.map((entry) => {
|
|
1544
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
const attachmentSource = typeof entry.attachmentSource === "string" && entry.attachmentSource.length > 0 ? entry.attachmentSource : undefined;
|
|
1548
|
+
const messageId = typeof entry.messageId === "string" && entry.messageId.length > 0 ? entry.messageId : undefined;
|
|
1549
|
+
const messageSource = typeof entry.messageSource === "string" && entry.messageSource.length > 0 ? entry.messageSource : undefined;
|
|
1550
|
+
const messageSourceKind = typeof entry.messageSourceKind === "string" && entry.messageSourceKind.length > 0 ? entry.messageSourceKind : undefined;
|
|
1551
|
+
const threadKey = typeof entry.threadKey === "string" && entry.threadKey.length > 0 ? entry.threadKey : undefined;
|
|
1552
|
+
if (!attachmentSource && !messageId && !messageSource && !messageSourceKind && !threadKey) {
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
return {
|
|
1556
|
+
...attachmentSource ? { attachmentSource } : {},
|
|
1557
|
+
...messageId ? { messageId } : {},
|
|
1558
|
+
...messageSource ? { messageSource } : {},
|
|
1559
|
+
...messageSourceKind ? { messageSourceKind } : {},
|
|
1560
|
+
...threadKey ? { threadKey } : {}
|
|
1561
|
+
};
|
|
1562
|
+
}).filter((entry) => Boolean(entry));
|
|
1563
|
+
};
|
|
1564
|
+
|
|
1565
|
+
// src/email/body.ts
|
|
1566
|
+
var EMAIL_FORWARDED_HEADER_PATTERN = /^(?:from|sent|to|cc|bcc|subject|date|reply-to):\s+/i;
|
|
1567
|
+
var EMAIL_FORWARDED_SEPARATOR_PATTERN = /^-{2,}\s*forwarded message\s*-{2,}$/i;
|
|
1568
|
+
var EMAIL_HTML_QUOTE_OPEN_TOKEN = "[[ABS_EMAIL_QUOTE_OPEN]]";
|
|
1569
|
+
var EMAIL_HTML_QUOTE_CLOSE_TOKEN = "[[ABS_EMAIL_QUOTE_CLOSE]]";
|
|
1570
|
+
var EMAIL_ATTRIBUTION_PATTERNS = [
|
|
1571
|
+
/^on\s.+\bwrote:$/iu,
|
|
1572
|
+
/^on\s.+\bat\s.+\bwrote:$/iu,
|
|
1573
|
+
/^-+\s*original message\s*-+$/iu,
|
|
1574
|
+
/^_{5,}$/u,
|
|
1575
|
+
/^el\s.+\bescribi\u00F3:$/iu,
|
|
1576
|
+
/^le\s.+\ba \u00E9crit\s*:$/iu
|
|
1577
|
+
];
|
|
1578
|
+
var EMAIL_SIGNATURE_DELIMITER = /^--\s?$/u;
|
|
1579
|
+
var classifyEmailBodyLine = (line, currentKind) => {
|
|
1580
|
+
const trimmed = line.trim();
|
|
1581
|
+
if (!trimmed) {
|
|
1582
|
+
return currentKind;
|
|
1583
|
+
}
|
|
1584
|
+
if (currentKind === "signature") {
|
|
1585
|
+
return "signature";
|
|
1586
|
+
}
|
|
1587
|
+
if (EMAIL_SIGNATURE_DELIMITER.test(line)) {
|
|
1588
|
+
return "signature";
|
|
1589
|
+
}
|
|
1590
|
+
if (/^>+/.test(trimmed)) {
|
|
1591
|
+
return "quoted_history";
|
|
1592
|
+
}
|
|
1593
|
+
if (EMAIL_ATTRIBUTION_PATTERNS.some((pattern) => pattern.test(trimmed))) {
|
|
1594
|
+
return "quoted_history";
|
|
1595
|
+
}
|
|
1596
|
+
if (EMAIL_FORWARDED_SEPARATOR_PATTERN.test(trimmed)) {
|
|
1597
|
+
return "forwarded_headers";
|
|
1598
|
+
}
|
|
1599
|
+
if (currentKind === "forwarded_headers" && (EMAIL_FORWARDED_HEADER_PATTERN.test(trimmed) || /^[A-Za-z-]+:\s+\S+/.test(trimmed))) {
|
|
1600
|
+
return "forwarded_headers";
|
|
1601
|
+
}
|
|
1602
|
+
if (EMAIL_FORWARDED_HEADER_PATTERN.test(trimmed)) {
|
|
1603
|
+
return "forwarded_headers";
|
|
1604
|
+
}
|
|
1605
|
+
return "authored_text";
|
|
1606
|
+
};
|
|
1607
|
+
var parseEmailForwardedHeaderFields = (lines) => {
|
|
1608
|
+
const fields = {};
|
|
1609
|
+
for (const line of lines) {
|
|
1610
|
+
const trimmed = line.trim();
|
|
1611
|
+
const match = trimmed.match(/^([A-Za-z-]+):\s*(.+)$/);
|
|
1612
|
+
if (!match) {
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
const key = normalizeWhitespace2(match[1] ?? "").toLowerCase();
|
|
1616
|
+
const value = normalizeWhitespace2(match[2] ?? "");
|
|
1617
|
+
if (!key || !value) {
|
|
1618
|
+
continue;
|
|
1619
|
+
}
|
|
1620
|
+
fields[key] = value;
|
|
1621
|
+
}
|
|
1622
|
+
return Object.keys(fields).length > 0 ? fields : undefined;
|
|
1623
|
+
};
|
|
1624
|
+
var parseForwardedHeaderMetadata = (lines) => {
|
|
1625
|
+
const forwardedHeaderFields = parseEmailForwardedHeaderFields(lines);
|
|
1626
|
+
const from = forwardedHeaderFields?.from;
|
|
1627
|
+
const to = forwardedHeaderFields?.to;
|
|
1628
|
+
const cc = forwardedHeaderFields?.cc;
|
|
1629
|
+
const bcc = forwardedHeaderFields?.bcc;
|
|
1630
|
+
const replyTo = forwardedHeaderFields?.["reply-to"];
|
|
1631
|
+
const fromParsed = parseEmailAddressList(from);
|
|
1632
|
+
const toParsed = parseEmailAddressList(to);
|
|
1633
|
+
const ccParsed = parseEmailAddressList(cc);
|
|
1634
|
+
const bccParsed = parseEmailAddressList(bcc);
|
|
1635
|
+
const replyToParsed = parseEmailAddressList(replyTo);
|
|
1636
|
+
const forwardedParticipantAddresses = [
|
|
1637
|
+
...new Set([
|
|
1638
|
+
...fromParsed.addresses,
|
|
1639
|
+
...toParsed.addresses,
|
|
1640
|
+
...ccParsed.addresses,
|
|
1641
|
+
...bccParsed.addresses,
|
|
1642
|
+
...replyToParsed.addresses
|
|
1643
|
+
])
|
|
1644
|
+
];
|
|
1645
|
+
return {
|
|
1646
|
+
...forwardedHeaderFields ? { forwardedHeaderFields } : {},
|
|
1647
|
+
...fromParsed.addresses[0] ? { forwardedFromAddress: fromParsed.addresses[0] } : {},
|
|
1648
|
+
...fromParsed.displayNames[0] ? { forwardedFromDisplayName: fromParsed.displayNames[0] } : {},
|
|
1649
|
+
...toParsed.addresses.length > 0 ? { forwardedToAddresses: toParsed.addresses } : {},
|
|
1650
|
+
...ccParsed.addresses.length > 0 ? { forwardedCcAddresses: ccParsed.addresses } : {},
|
|
1651
|
+
...bccParsed.addresses.length > 0 ? { forwardedBccAddresses: bccParsed.addresses } : {},
|
|
1652
|
+
...replyToParsed.addresses.length > 0 ? { forwardedReplyToAddresses: replyToParsed.addresses } : {},
|
|
1653
|
+
...forwardedParticipantAddresses.length > 0 ? { forwardedParticipantAddresses } : {},
|
|
1654
|
+
...forwardedHeaderFields?.subject ? { forwardedSubject: forwardedHeaderFields.subject } : {},
|
|
1655
|
+
...forwardedHeaderFields?.date ? { forwardedDate: forwardedHeaderFields.date } : {},
|
|
1656
|
+
...forwardedHeaderFields?.date ? {
|
|
1657
|
+
forwardedTimestamp: normalizeEmailTimestamp(forwardedHeaderFields.date)
|
|
1658
|
+
} : {}
|
|
1659
|
+
};
|
|
1660
|
+
};
|
|
1661
|
+
var getEmailQuotedDepth = (lines) => {
|
|
1662
|
+
let depth = 0;
|
|
1663
|
+
for (const line of lines) {
|
|
1664
|
+
const trimmed = line.trim();
|
|
1665
|
+
if (/^on .+wrote:$/i.test(trimmed)) {
|
|
1666
|
+
depth = Math.max(depth, 1);
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
const quoteDepth = (trimmed.match(/^>+/)?.[0].length ?? 0) || 0;
|
|
1670
|
+
depth = Math.max(depth, quoteDepth);
|
|
1671
|
+
}
|
|
1672
|
+
return depth || undefined;
|
|
1673
|
+
};
|
|
1674
|
+
var parseEmailBodySections = (text) => {
|
|
1675
|
+
const normalized = text.replace(/\r\n?/g, `
|
|
1676
|
+
`);
|
|
1677
|
+
const lines = normalized.split(`
|
|
1678
|
+
`);
|
|
1679
|
+
const sections = [];
|
|
1680
|
+
let currentKind;
|
|
1681
|
+
let currentLines = [];
|
|
1682
|
+
const pushCurrent = () => {
|
|
1683
|
+
if (!currentKind) {
|
|
1684
|
+
currentLines = [];
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
const sectionText = normalizeWhitespace2(currentLines.join(`
|
|
1688
|
+
`));
|
|
1689
|
+
if (sectionText) {
|
|
1690
|
+
sections.push({
|
|
1691
|
+
...currentKind === "quoted_history" ? {
|
|
1692
|
+
quotedDepth: getEmailQuotedDepth(currentLines)
|
|
1693
|
+
} : {},
|
|
1694
|
+
...currentKind === "forwarded_headers" ? parseForwardedHeaderMetadata(currentLines) : {},
|
|
1695
|
+
kind: currentKind,
|
|
1696
|
+
text: sectionText
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
currentKind = undefined;
|
|
1700
|
+
currentLines = [];
|
|
1701
|
+
};
|
|
1702
|
+
for (const line of lines) {
|
|
1703
|
+
const nextKind = classifyEmailBodyLine(line, currentKind);
|
|
1704
|
+
if (!nextKind) {
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
if (currentKind === "forwarded_headers" && nextKind === "forwarded_headers" && EMAIL_FORWARDED_SEPARATOR_PATTERN.test(line.trim()) && currentLines.some((entry) => normalizeWhitespace2(entry).length > 0)) {
|
|
1708
|
+
pushCurrent();
|
|
1709
|
+
currentKind = "forwarded_headers";
|
|
1710
|
+
currentLines.push(line);
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
if (!currentKind) {
|
|
1714
|
+
currentKind = nextKind;
|
|
1715
|
+
currentLines.push(line);
|
|
1716
|
+
continue;
|
|
1717
|
+
}
|
|
1718
|
+
if (nextKind !== currentKind) {
|
|
1719
|
+
pushCurrent();
|
|
1720
|
+
currentKind = nextKind;
|
|
1721
|
+
}
|
|
1722
|
+
currentLines.push(line);
|
|
1723
|
+
}
|
|
1724
|
+
pushCurrent();
|
|
1725
|
+
const merged = [];
|
|
1726
|
+
for (const section of sections) {
|
|
1727
|
+
const previous = merged.at(-1);
|
|
1728
|
+
if (previous && previous.kind === section.kind && section.kind !== "forwarded_headers") {
|
|
1729
|
+
previous.text = normalizeWhitespace2(`${previous.text}
|
|
1730
|
+
|
|
1731
|
+
${section.text}`);
|
|
1732
|
+
if (section.kind === "quoted_history" && typeof section.quotedDepth === "number") {
|
|
1733
|
+
previous.quotedDepth = Math.max(previous.quotedDepth ?? 0, section.quotedDepth);
|
|
1734
|
+
}
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
merged.push({ ...section });
|
|
1738
|
+
}
|
|
1739
|
+
return merged;
|
|
1740
|
+
};
|
|
1741
|
+
var stripEmailHtml = (value) => {
|
|
1742
|
+
const focused = extractMainHtmlContent2(value).replace(/<blockquote\b[^>]*>/gi, `
|
|
1743
|
+
${EMAIL_HTML_QUOTE_OPEN_TOKEN}
|
|
1744
|
+
`).replace(/<\/blockquote>/gi, `
|
|
1745
|
+
${EMAIL_HTML_QUOTE_CLOSE_TOKEN}
|
|
1746
|
+
`);
|
|
1747
|
+
const stripped = stripHtmlTags2(focused);
|
|
1748
|
+
const lines = stripped.replace(/\r\n?/g, `
|
|
1749
|
+
`).split(`
|
|
1750
|
+
`);
|
|
1751
|
+
const rendered = [];
|
|
1752
|
+
let quotedDepth = 0;
|
|
1753
|
+
for (const line of lines) {
|
|
1754
|
+
const trimmed = normalizeWhitespace2(line);
|
|
1755
|
+
if (!trimmed) {
|
|
1756
|
+
if (rendered.at(-1) !== "") {
|
|
1757
|
+
rendered.push("");
|
|
1758
|
+
}
|
|
1759
|
+
continue;
|
|
1760
|
+
}
|
|
1761
|
+
if (trimmed === EMAIL_HTML_QUOTE_OPEN_TOKEN) {
|
|
1762
|
+
quotedDepth += 1;
|
|
1763
|
+
continue;
|
|
1764
|
+
}
|
|
1765
|
+
if (trimmed === EMAIL_HTML_QUOTE_CLOSE_TOKEN) {
|
|
1766
|
+
quotedDepth = Math.max(quotedDepth - 1, 0);
|
|
1767
|
+
continue;
|
|
1768
|
+
}
|
|
1769
|
+
const prefixed = quotedDepth > 0 ? `${">".repeat(quotedDepth)} ${trimmed}` : trimmed;
|
|
1770
|
+
rendered.push(prefixed);
|
|
1771
|
+
}
|
|
1772
|
+
return normalizeWhitespace2(rendered.join(`
|
|
1773
|
+
`).replace(/\n{2,}/g, `
|
|
1774
|
+
`));
|
|
1775
|
+
};
|
|
1776
|
+
var scoreEmailBodyCandidate = (candidate) => {
|
|
1777
|
+
if (!candidate) {
|
|
1778
|
+
return Number.NEGATIVE_INFINITY;
|
|
1779
|
+
}
|
|
1780
|
+
const sections = parseEmailBodySections(candidate);
|
|
1781
|
+
const authoredChars = sections.filter((section) => section.kind === "authored_text").reduce((total, section) => total + section.text.trim().length, 0);
|
|
1782
|
+
return authoredChars * 10 + Math.min(candidate.length, 5000) / 1000;
|
|
1783
|
+
};
|
|
1784
|
+
var choosePreferredEmailBodyText = (htmlText, plainText) => {
|
|
1785
|
+
const htmlScore = scoreEmailBodyCandidate(htmlText);
|
|
1786
|
+
const plainScore = scoreEmailBodyCandidate(plainText);
|
|
1787
|
+
return htmlScore >= plainScore ? htmlText : plainText;
|
|
1788
|
+
};
|
|
1789
|
+
var chooseEmailBodyCandidate = (current, candidate) => {
|
|
1790
|
+
if (!candidate) {
|
|
1791
|
+
return current;
|
|
1792
|
+
}
|
|
1793
|
+
if (!current) {
|
|
1794
|
+
return candidate;
|
|
1795
|
+
}
|
|
1796
|
+
return candidate.length > current.length ? candidate : current;
|
|
1797
|
+
};
|
|
1798
|
+
|
|
1799
|
+
// src/email/message.ts
|
|
1800
|
+
var parseEmailMimeParts = (body, contentType, transferEncoding) => {
|
|
1801
|
+
const attachments = [];
|
|
1802
|
+
let bodyText;
|
|
1803
|
+
let bodyHtml;
|
|
1804
|
+
const collectMimeParts = (partBody, partContentType) => {
|
|
1805
|
+
const boundary = parseMimeBoundary(partContentType);
|
|
1806
|
+
if (!boundary) {
|
|
1807
|
+
const htmlMatch = partBody.match(/<html[\s\S]*<\/html>/i);
|
|
1808
|
+
bodyHtml = chooseEmailBodyCandidate(bodyHtml, htmlMatch?.[0]);
|
|
1809
|
+
bodyText = chooseEmailBodyCandidate(bodyText, htmlMatch ? undefined : partBody);
|
|
1810
|
+
return;
|
|
1811
|
+
}
|
|
1812
|
+
for (const rawPart of partBody.split(`--${boundary}`)) {
|
|
1813
|
+
const trimmed = rawPart.trim();
|
|
1814
|
+
if (!trimmed || trimmed === "--") {
|
|
1815
|
+
continue;
|
|
1816
|
+
}
|
|
1817
|
+
const { body: nestedBody, headerBlock } = splitEmailMessage(trimmed);
|
|
1818
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
1819
|
+
const nestedContentType = headers.get("content-type");
|
|
1820
|
+
const disposition = headers.get("content-disposition");
|
|
1821
|
+
const dispositionType = disposition?.split(";")[0]?.trim().toLowerCase();
|
|
1822
|
+
const transferEncoding = headers.get("content-transfer-encoding");
|
|
1823
|
+
const contentId = normalizeEmailContentId(headers.get("content-id"));
|
|
1824
|
+
const contentLocation = normalizeWhitespace2(headers.get("content-location") ?? "");
|
|
1825
|
+
const filename = disposition?.match(/filename="?([^";]+)"?/i)?.[1] ?? nestedContentType?.match(/name="?([^";]+)"?/i)?.[1];
|
|
1826
|
+
const decodedBytes = decodeEmailPartBody(nestedBody, transferEncoding);
|
|
1827
|
+
const decodedText = decodeWithCharset(decodedBytes, nestedContentType);
|
|
1828
|
+
const normalizedContentType = nestedContentType?.toLowerCase() ?? "";
|
|
1829
|
+
const isMultipart = normalizedContentType.startsWith("multipart/");
|
|
1830
|
+
const isHtml = normalizedContentType.includes("text/html");
|
|
1831
|
+
const isAttachedMessage = normalizedContentType.includes("message/rfc822");
|
|
1832
|
+
const isPlain = normalizedContentType.includes("text/plain");
|
|
1833
|
+
const isBodyLikeTextPart = (isHtml || isPlain) && !filename && dispositionType !== "attachment" && !contentId && !contentLocation;
|
|
1834
|
+
if (isMultipart) {
|
|
1835
|
+
collectMimeParts(decodedText, nestedContentType);
|
|
1836
|
+
continue;
|
|
1837
|
+
}
|
|
1838
|
+
if (isBodyLikeTextPart) {
|
|
1839
|
+
if (isHtml) {
|
|
1840
|
+
bodyHtml = chooseEmailBodyCandidate(bodyHtml, decodedText);
|
|
1841
|
+
continue;
|
|
1842
|
+
}
|
|
1843
|
+
if (isPlain) {
|
|
1844
|
+
bodyText = chooseEmailBodyCandidate(bodyText, decodedText);
|
|
1845
|
+
}
|
|
1846
|
+
continue;
|
|
1847
|
+
}
|
|
1848
|
+
if (filename || dispositionType === "attachment" || dispositionType === "inline" || contentId || contentLocation) {
|
|
1849
|
+
attachments.push({
|
|
1850
|
+
contentId,
|
|
1851
|
+
contentLocation: contentLocation || undefined,
|
|
1852
|
+
contentType: nestedContentType,
|
|
1853
|
+
data: decodedBytes,
|
|
1854
|
+
dispositionType,
|
|
1855
|
+
fileName: inferEmailAttachmentName({
|
|
1856
|
+
contentId,
|
|
1857
|
+
contentLocation: contentLocation || undefined,
|
|
1858
|
+
contentType: nestedContentType,
|
|
1859
|
+
filename
|
|
1860
|
+
}),
|
|
1861
|
+
role: isAttachedMessage ? "attached_message" : dispositionType === "inline" || contentId || contentLocation ? "inline_resource" : "file_attachment"
|
|
1862
|
+
});
|
|
1863
|
+
continue;
|
|
1864
|
+
}
|
|
1865
|
+
if (isHtml) {
|
|
1866
|
+
bodyHtml = chooseEmailBodyCandidate(bodyHtml, decodedText);
|
|
1867
|
+
continue;
|
|
1868
|
+
}
|
|
1869
|
+
if (isPlain) {
|
|
1870
|
+
bodyText = chooseEmailBodyCandidate(bodyText, decodedText);
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
};
|
|
1874
|
+
const topLevelBody = transferEncoding && !parseMimeBoundary(contentType) ? decodeWithCharset(decodeEmailPartBody(body, transferEncoding), contentType) : body;
|
|
1875
|
+
collectMimeParts(topLevelBody, contentType);
|
|
1876
|
+
return {
|
|
1877
|
+
attachments,
|
|
1878
|
+
bodyHtml,
|
|
1879
|
+
bodyText
|
|
1880
|
+
};
|
|
1881
|
+
};
|
|
1882
|
+
var authoredEmailText2 = (text) => {
|
|
1883
|
+
const authored = parseEmailBodySections(text).filter((section) => section.kind === "authored_text").map((section) => section.text.trim()).filter(Boolean).join(`
|
|
1884
|
+
|
|
1885
|
+
`).trim();
|
|
1886
|
+
return authored || text;
|
|
1887
|
+
};
|
|
1888
|
+
var extractEmailText = (raw) => {
|
|
1889
|
+
const { body, headerBlock } = splitEmailMessage(raw);
|
|
1890
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
1891
|
+
const parsed = parseEmailMimeParts(body, headers.get("content-type"), headers.get("content-transfer-encoding"));
|
|
1892
|
+
const htmlText = parsed.bodyHtml ? stripEmailHtml(parsed.bodyHtml) : undefined;
|
|
1893
|
+
const plainText = parsed.bodyText ? normalizeWhitespace2(parsed.bodyText) : undefined;
|
|
1894
|
+
const preferredBodyText = choosePreferredEmailBodyText(htmlText, plainText);
|
|
1895
|
+
if (preferredBodyText) {
|
|
1896
|
+
return preferredBodyText;
|
|
1897
|
+
}
|
|
1898
|
+
if (!body) {
|
|
1899
|
+
return normalizeWhitespace2(raw.replace(/\r\n?/g, `
|
|
1900
|
+
`));
|
|
1901
|
+
}
|
|
1902
|
+
const htmlMatch = body.match(/<html[\s\S]*<\/html>/i);
|
|
1903
|
+
if (htmlMatch) {
|
|
1904
|
+
return stripEmailHtml(htmlMatch[0]);
|
|
1905
|
+
}
|
|
1906
|
+
return normalizeWhitespace2(body);
|
|
1907
|
+
};
|
|
1908
|
+
var parseEmailHeaders = (raw) => {
|
|
1909
|
+
const { headerBlock } = splitEmailMessage(raw);
|
|
1910
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
1911
|
+
const getHeader = (name) => headers.get(name.toLowerCase());
|
|
1912
|
+
const from = getHeader("From");
|
|
1913
|
+
const to = getHeader("To");
|
|
1914
|
+
const cc = getHeader("Cc");
|
|
1915
|
+
const bcc = getHeader("Bcc");
|
|
1916
|
+
const replyTo = getHeader("Reply-To");
|
|
1917
|
+
const fromParsed = parseEmailAddressList(from);
|
|
1918
|
+
const toParsed = parseEmailAddressList(to);
|
|
1919
|
+
const ccParsed = parseEmailAddressList(cc);
|
|
1920
|
+
const bccParsed = parseEmailAddressList(bcc);
|
|
1921
|
+
const replyToParsed = parseEmailAddressList(replyTo);
|
|
1922
|
+
const participantAddresses = [
|
|
1923
|
+
...new Set([
|
|
1924
|
+
...fromParsed.addresses,
|
|
1925
|
+
...toParsed.addresses,
|
|
1926
|
+
...ccParsed.addresses,
|
|
1927
|
+
...bccParsed.addresses,
|
|
1928
|
+
...replyToParsed.addresses
|
|
1929
|
+
])
|
|
1930
|
+
];
|
|
1931
|
+
const participantDisplayNames = [
|
|
1932
|
+
...new Set([
|
|
1933
|
+
...fromParsed.displayNames,
|
|
1934
|
+
...toParsed.displayNames,
|
|
1935
|
+
...ccParsed.displayNames,
|
|
1936
|
+
...bccParsed.displayNames,
|
|
1937
|
+
...replyToParsed.displayNames
|
|
1938
|
+
])
|
|
1939
|
+
];
|
|
1940
|
+
return {
|
|
1941
|
+
bcc,
|
|
1942
|
+
bccAddressEntries: bccParsed.entries,
|
|
1943
|
+
bccAddresses: bccParsed.addresses,
|
|
1944
|
+
cc,
|
|
1945
|
+
ccAddressEntries: ccParsed.entries,
|
|
1946
|
+
ccAddresses: ccParsed.addresses,
|
|
1947
|
+
contentType: getHeader("Content-Type"),
|
|
1948
|
+
contentTransferEncoding: getHeader("Content-Transfer-Encoding"),
|
|
1949
|
+
from,
|
|
1950
|
+
fromAddress: fromParsed.addresses[0],
|
|
1951
|
+
fromAddressEntries: fromParsed.entries,
|
|
1952
|
+
fromDisplayName: fromParsed.displayNames[0],
|
|
1953
|
+
inReplyTo: getHeader("In-Reply-To"),
|
|
1954
|
+
messageId: getHeader("Message-ID"),
|
|
1955
|
+
conversationId: getHeader("Conversation-ID"),
|
|
1956
|
+
participantAddresses,
|
|
1957
|
+
participantDisplayNames,
|
|
1958
|
+
replyTo,
|
|
1959
|
+
replyToAddressEntries: replyToParsed.entries,
|
|
1960
|
+
replyToAddresses: replyToParsed.addresses,
|
|
1961
|
+
references: getHeader("References"),
|
|
1962
|
+
subject: getHeader("Subject"),
|
|
1963
|
+
threadIndex: getHeader("Thread-Index"),
|
|
1964
|
+
threadTopic: getHeader("Thread-Topic") ?? getHeader("Subject"),
|
|
1965
|
+
to,
|
|
1966
|
+
toAddressEntries: toParsed.entries,
|
|
1967
|
+
toAddresses: toParsed.addresses
|
|
1968
|
+
};
|
|
1969
|
+
};
|
|
1970
|
+
var extractEmailDocumentsFromRawMessage = async (input, raw, options) => {
|
|
1971
|
+
const headers = parseEmailHeaders(raw);
|
|
1972
|
+
const { body } = splitEmailMessage(raw);
|
|
1973
|
+
const parsed = parseEmailMimeParts(body, headers.contentType, headers.contentTransferEncoding);
|
|
1974
|
+
const source = options?.source ?? input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}.eml`;
|
|
1975
|
+
const maildirMetadata = parseMaildirMetadata2(source);
|
|
1976
|
+
const mergedMetadata = {
|
|
1977
|
+
...input.metadata ?? {},
|
|
1978
|
+
...options?.metadata ?? {}
|
|
1979
|
+
};
|
|
1980
|
+
const referenceChain = parseEmailReferenceChain(headers.references);
|
|
1981
|
+
const messageId = normalizeEmailMessageId(headers.messageId);
|
|
1982
|
+
const inReplyTo = normalizeEmailMessageId(headers.inReplyTo);
|
|
1983
|
+
const threadMessageIds = [
|
|
1984
|
+
...new Set([
|
|
1985
|
+
...referenceChain.map((entry) => normalizeEmailMessageId(entry)),
|
|
1986
|
+
messageId
|
|
1987
|
+
].filter((value) => typeof value === "string"))
|
|
1988
|
+
];
|
|
1989
|
+
const replyDepth = Math.max(referenceChain.length, headers.inReplyTo ? 1 : 0);
|
|
1990
|
+
const threadIndex = headers.threadIndex;
|
|
1991
|
+
const threadTopic = headers.threadTopic ?? headers.subject;
|
|
1992
|
+
const conversationId = headers.conversationId ?? (typeof mergedMetadata.emailConversationId === "string" && mergedMetadata.emailConversationId.length > 0 ? mergedMetadata.emailConversationId : undefined);
|
|
1993
|
+
const threadRootMessageId = normalizeEmailMessageId(referenceChain[0]) ?? inReplyTo ?? messageId;
|
|
1994
|
+
const threadKey = normalizeEmailThreadKey(threadTopic) ?? normalizeEmailThreadKey(conversationId) ?? normalizeEmailThreadKey(messageId) ?? normalizeEmailThreadKey(headers.subject);
|
|
1995
|
+
const parentMessageId = normalizeEmailMessageId(typeof options?.metadata?.messageId === "string" ? options.metadata.messageId : typeof input.metadata?.messageId === "string" ? input.metadata.messageId : undefined);
|
|
1996
|
+
const parentMessageSource = typeof options?.metadata?.emailMessageSource === "string" && options.metadata.emailMessageSource.length > 0 ? options.metadata.emailMessageSource : typeof input.metadata?.emailMessageSource === "string" && input.metadata.emailMessageSource.length > 0 ? input.metadata.emailMessageSource : undefined;
|
|
1997
|
+
const parentThreadKey = typeof options?.metadata?.threadKey === "string" && options.metadata.threadKey.length > 0 ? options.metadata.threadKey : typeof input.metadata?.threadKey === "string" && input.metadata.threadKey.length > 0 ? input.metadata.threadKey : undefined;
|
|
1998
|
+
const parentAttachmentSource = typeof options?.metadata?.emailAttachmentSource === "string" && options.metadata.emailAttachmentSource.length > 0 ? options.metadata.emailAttachmentSource : typeof input.metadata?.emailAttachmentSource === "string" && input.metadata.emailAttachmentSource.length > 0 ? input.metadata.emailAttachmentSource : undefined;
|
|
1999
|
+
const parentMessageLineage = parseEmailMessageLineage(mergedMetadata);
|
|
2000
|
+
const parentAncestorMessageIds = Array.isArray(mergedMetadata.emailAncestorMessageIds) ? mergedMetadata.emailAncestorMessageIds.filter((value) => typeof value === "string" && value.length > 0) : [];
|
|
2001
|
+
const parentAncestorMessageSources = Array.isArray(mergedMetadata.emailAncestorMessageSources) ? mergedMetadata.emailAncestorMessageSources.filter((value) => typeof value === "string" && value.length > 0) : [];
|
|
2002
|
+
const emailMessageLineage = parentAttachmentSource ? [
|
|
2003
|
+
...parentMessageLineage,
|
|
2004
|
+
{
|
|
2005
|
+
attachmentSource: parentAttachmentSource,
|
|
2006
|
+
...parentMessageId ? { messageId: parentMessageId } : {},
|
|
2007
|
+
...parentMessageSource ? { messageSource: parentMessageSource } : {},
|
|
2008
|
+
...typeof mergedMetadata.emailMessageSourceKind === "string" && mergedMetadata.emailMessageSourceKind.length > 0 ? {
|
|
2009
|
+
messageSourceKind: mergedMetadata.emailMessageSourceKind
|
|
2010
|
+
} : {},
|
|
2011
|
+
...parentThreadKey ? { threadKey: parentThreadKey } : {}
|
|
2012
|
+
}
|
|
2013
|
+
] : parentMessageLineage;
|
|
2014
|
+
const emailMessageLineageMessageIds = emailMessageLineage.map((entry) => entry.messageId).filter((value) => typeof value === "string");
|
|
2015
|
+
const emailMessageLineageSources = emailMessageLineage.map((entry) => entry.messageSource).filter((value) => typeof value === "string");
|
|
2016
|
+
const emailMessageLineageAttachmentSources = emailMessageLineage.map((entry) => entry.attachmentSource).filter((value) => typeof value === "string");
|
|
2017
|
+
const emailMessageDepth = emailMessageLineage.length;
|
|
2018
|
+
const emailAncestorMessageIds = [
|
|
2019
|
+
...new Set([...parentAncestorMessageIds, ...emailMessageLineageMessageIds])
|
|
2020
|
+
];
|
|
2021
|
+
const emailAncestorMessageSources = [
|
|
2022
|
+
...new Set([
|
|
2023
|
+
...parentAncestorMessageSources,
|
|
2024
|
+
...emailMessageLineageSources
|
|
2025
|
+
])
|
|
2026
|
+
];
|
|
2027
|
+
const embeddedResourceReferences = parseEmailEmbeddedResourceReferences(parsed.bodyHtml);
|
|
2028
|
+
const messageText = extractEmailText(raw);
|
|
2029
|
+
const emailBodySections = parseEmailBodySections(messageText);
|
|
2030
|
+
const forwardedSections = emailBodySections.filter((section) => section.kind === "forwarded_headers");
|
|
2031
|
+
const primaryForwardedSection = emailBodySections.find((section) => section.kind === "forwarded_headers");
|
|
2032
|
+
const forwardedHeaderFieldNames = [
|
|
2033
|
+
...new Set(emailBodySections.flatMap((section) => Object.keys(section.forwardedHeaderFields ?? {})))
|
|
2034
|
+
];
|
|
2035
|
+
const quotedDepths = emailBodySections.map((section) => typeof section.quotedDepth === "number" ? section.quotedDepth : undefined).filter((value) => typeof value === "number");
|
|
2036
|
+
const inheritedAttachmentNames = Array.isArray(mergedMetadata.attachmentNames) ? mergedMetadata.attachmentNames.filter((value) => typeof value === "string" && value.length > 0) : [];
|
|
2037
|
+
const attachmentNames = parsed.attachments.length > 0 ? parsed.attachments.map((attachment) => attachment.fileName) : inheritedAttachmentNames;
|
|
2038
|
+
const attachmentCount = parsed.attachments.length > 0 ? parsed.attachments.length : typeof mergedMetadata.attachmentCount === "number" && Number.isFinite(mergedMetadata.attachmentCount) ? mergedMetadata.attachmentCount : attachmentNames.length;
|
|
2039
|
+
const messageMetadata = {
|
|
2040
|
+
...mergedMetadata,
|
|
2041
|
+
...maildirMetadata ?? {},
|
|
2042
|
+
attachmentCount,
|
|
2043
|
+
attachmentNames,
|
|
2044
|
+
emailKind: "message",
|
|
2045
|
+
fileKind: "email",
|
|
2046
|
+
...typeof conversationId === "string" && conversationId.trim().length > 0 ? { emailConversationId: normalizeWhitespace2(conversationId) } : {},
|
|
2047
|
+
from: headers.from,
|
|
2048
|
+
fromAddress: headers.fromAddress,
|
|
2049
|
+
fromAddressEntries: headers.fromAddressEntries,
|
|
2050
|
+
fromDisplayName: headers.fromDisplayName,
|
|
2051
|
+
inReplyTo,
|
|
2052
|
+
messageId,
|
|
2053
|
+
emailAncestorMessageIds,
|
|
2054
|
+
emailAncestorMessageSources,
|
|
2055
|
+
emailContainerAttachmentSource: parentAttachmentSource,
|
|
2056
|
+
emailContainerMessageId: parentAttachmentSource ? parentMessageId : undefined,
|
|
2057
|
+
emailContainerMessageSource: parentAttachmentSource ? parentMessageSource : undefined,
|
|
2058
|
+
emailContainerThreadKey: parentAttachmentSource ? parentThreadKey : undefined,
|
|
2059
|
+
emailMessageLineage,
|
|
2060
|
+
emailMessageLineageAttachmentSources,
|
|
2061
|
+
emailMessageLineageCount: emailMessageLineage.length,
|
|
2062
|
+
emailMessageLineageMessageIds,
|
|
2063
|
+
emailMessageLineageSources,
|
|
2064
|
+
emailMessageDepth,
|
|
2065
|
+
emailMessageSourceKind: parentAttachmentSource ? "attached_message" : "root_message",
|
|
2066
|
+
references: headers.references,
|
|
2067
|
+
replyDepth,
|
|
2068
|
+
replyReferenceCount: referenceChain.length,
|
|
2069
|
+
threadMessageCount: threadMessageIds.length,
|
|
2070
|
+
threadMessageIds,
|
|
2071
|
+
...typeof threadIndex === "string" && threadIndex.trim().length > 0 ? { threadIndex: normalizeWhitespace2(threadIndex) } : {},
|
|
2072
|
+
threadKey,
|
|
2073
|
+
threadRootMessageId,
|
|
2074
|
+
threadTopic,
|
|
2075
|
+
to: headers.to,
|
|
2076
|
+
toAddressEntries: headers.toAddressEntries,
|
|
2077
|
+
toAddresses: headers.toAddresses,
|
|
2078
|
+
hasAttachments: attachmentCount > 0,
|
|
2079
|
+
hasInlineResources: parsed.attachments.some((attachment) => attachment.role === "inline_resource"),
|
|
2080
|
+
embeddedResourceCount: embeddedResourceReferences.contentIds.length + embeddedResourceReferences.contentLocations.length,
|
|
2081
|
+
embeddedResourceContentIds: embeddedResourceReferences.contentIds,
|
|
2082
|
+
embeddedResourceContentLocations: embeddedResourceReferences.contentLocations,
|
|
2083
|
+
bcc: headers.bcc,
|
|
2084
|
+
bccAddressEntries: headers.bccAddressEntries,
|
|
2085
|
+
bccAddresses: headers.bccAddresses,
|
|
2086
|
+
cc: headers.cc,
|
|
2087
|
+
ccAddressEntries: headers.ccAddressEntries,
|
|
2088
|
+
ccAddresses: headers.ccAddresses,
|
|
2089
|
+
emailAuthoredSectionCount: emailBodySections.filter((section) => section.kind === "authored_text").length,
|
|
2090
|
+
emailBodySectionCount: emailBodySections.length,
|
|
2091
|
+
emailBodySections,
|
|
2092
|
+
emailForwardedChainCount: forwardedSections.length,
|
|
2093
|
+
emailForwardedChains: forwardedSections.map((section, index) => ({
|
|
2094
|
+
...Array.isArray(section.forwardedBccAddresses) && section.forwardedBccAddresses.length > 0 ? { forwardedBccAddresses: section.forwardedBccAddresses } : {},
|
|
2095
|
+
...Array.isArray(section.forwardedCcAddresses) && section.forwardedCcAddresses.length > 0 ? { forwardedCcAddresses: section.forwardedCcAddresses } : {},
|
|
2096
|
+
...typeof section.forwardedDate === "string" ? { forwardedDate: section.forwardedDate } : {},
|
|
2097
|
+
...typeof section.forwardedFromAddress === "string" ? { forwardedFromAddress: section.forwardedFromAddress } : {},
|
|
2098
|
+
...typeof section.forwardedFromDisplayName === "string" ? {
|
|
2099
|
+
forwardedFromDisplayName: section.forwardedFromDisplayName
|
|
2100
|
+
} : {},
|
|
2101
|
+
...section.forwardedHeaderFields ? { forwardedHeaderFields: section.forwardedHeaderFields } : {},
|
|
2102
|
+
...Array.isArray(section.forwardedParticipantAddresses) && section.forwardedParticipantAddresses.length > 0 ? {
|
|
2103
|
+
forwardedParticipantAddresses: section.forwardedParticipantAddresses
|
|
2104
|
+
} : {},
|
|
2105
|
+
...Array.isArray(section.forwardedReplyToAddresses) && section.forwardedReplyToAddresses.length > 0 ? {
|
|
2106
|
+
forwardedReplyToAddresses: section.forwardedReplyToAddresses
|
|
2107
|
+
} : {},
|
|
2108
|
+
...typeof section.forwardedSubject === "string" ? { forwardedSubject: section.forwardedSubject } : {},
|
|
2109
|
+
...typeof section.forwardedTimestamp === "string" ? { forwardedTimestamp: section.forwardedTimestamp } : {},
|
|
2110
|
+
...Array.isArray(section.forwardedToAddresses) && section.forwardedToAddresses.length > 0 ? { forwardedToAddresses: section.forwardedToAddresses } : {},
|
|
2111
|
+
ordinal: index + 1,
|
|
2112
|
+
text: section.text
|
|
2113
|
+
})),
|
|
2114
|
+
emailForwardedBccAddresses: primaryForwardedSection?.forwardedBccAddresses,
|
|
2115
|
+
emailForwardedCcAddresses: primaryForwardedSection?.forwardedCcAddresses,
|
|
2116
|
+
emailForwardedDate: primaryForwardedSection?.forwardedDate,
|
|
2117
|
+
emailForwardedFromAddress: primaryForwardedSection?.forwardedFromAddress,
|
|
2118
|
+
emailForwardedFromDisplayName: primaryForwardedSection?.forwardedFromDisplayName,
|
|
2119
|
+
emailForwardedHeaderSectionCount: emailBodySections.filter((section) => section.kind === "forwarded_headers").length,
|
|
2120
|
+
emailForwardedHeaderFieldCount: forwardedHeaderFieldNames.length,
|
|
2121
|
+
emailForwardedHeaderFieldNames: forwardedHeaderFieldNames,
|
|
2122
|
+
emailForwardedHeaderFields: primaryForwardedSection?.forwardedHeaderFields,
|
|
2123
|
+
emailForwardedParticipantAddresses: primaryForwardedSection?.forwardedParticipantAddresses,
|
|
2124
|
+
emailForwardedReplyToAddresses: primaryForwardedSection?.forwardedReplyToAddresses,
|
|
2125
|
+
emailForwardedSubject: primaryForwardedSection?.forwardedSubject,
|
|
2126
|
+
emailForwardedTimestamp: primaryForwardedSection?.forwardedTimestamp,
|
|
2127
|
+
emailForwardedToAddresses: primaryForwardedSection?.forwardedToAddresses,
|
|
2128
|
+
emailQuotedMaxDepth: quotedDepths.length > 0 ? Math.max(...quotedDepths) : undefined,
|
|
2129
|
+
emailQuotedSectionCount: emailBodySections.filter((section) => section.kind === "quoted_history").length,
|
|
2130
|
+
emailMessageSource: source,
|
|
2131
|
+
participantAddresses: headers.participantAddresses,
|
|
2132
|
+
participantDisplayNames: headers.participantDisplayNames,
|
|
2133
|
+
replyTo: headers.replyTo,
|
|
2134
|
+
replyToAddressEntries: headers.replyToAddressEntries,
|
|
2135
|
+
replyToAddresses: headers.replyToAddresses
|
|
2136
|
+
};
|
|
2137
|
+
const attachmentDocuments = await Promise.all(parsed.attachments.map(async (attachment, index) => {
|
|
2138
|
+
const attachmentSource = `${source}#attachments/${attachment.fileName}`;
|
|
2139
|
+
const matchesEmbeddedReference = (attachment.contentId ? embeddedResourceReferences.contentIds.includes(attachment.contentId) : false) || (attachment.contentLocation ? embeddedResourceReferences.contentLocations.includes(attachment.contentLocation) : false);
|
|
2140
|
+
const documents = await extractDocuments2({
|
|
2141
|
+
contentType: attachment.contentType,
|
|
2142
|
+
data: attachment.data,
|
|
2143
|
+
extractorRegistry: input.extractorRegistry,
|
|
2144
|
+
format: inferFormatFromContentType2(attachment.contentType ?? null) ?? inferFormatFromName2(attachment.fileName),
|
|
2145
|
+
metadata: {
|
|
2146
|
+
...messageMetadata,
|
|
2147
|
+
attachmentIndex: index,
|
|
2148
|
+
attachmentContentId: attachment.contentId,
|
|
2149
|
+
attachmentContentLocation: attachment.contentLocation,
|
|
2150
|
+
attachmentDisposition: attachment.dispositionType ?? "attachment",
|
|
2151
|
+
attachmentEmbeddedReferenceMatched: matchesEmbeddedReference,
|
|
2152
|
+
attachmentName: attachment.fileName,
|
|
2153
|
+
emailAttachmentRole: attachment.role,
|
|
2154
|
+
emailAttachmentSource: attachmentSource,
|
|
2155
|
+
emailKind: "attachment"
|
|
2156
|
+
},
|
|
2157
|
+
name: attachment.fileName,
|
|
2158
|
+
source: attachmentSource,
|
|
2159
|
+
title: headers.subject ? `${headers.subject} \xB7 ${attachment.fileName}` : attachment.fileName
|
|
2160
|
+
});
|
|
2161
|
+
return documents;
|
|
2162
|
+
}));
|
|
2163
|
+
const messageDocument = {
|
|
2164
|
+
contentType: input.contentType,
|
|
2165
|
+
format: "text",
|
|
2166
|
+
metadata: messageMetadata,
|
|
2167
|
+
source,
|
|
2168
|
+
text: messageText,
|
|
2169
|
+
title: options?.title ?? input.title ?? headers.subject
|
|
2170
|
+
};
|
|
2171
|
+
return [messageDocument, ...attachmentDocuments.flat()];
|
|
2172
|
+
};
|
|
2173
|
+
var normalizeEmailThreadKey = (value) => {
|
|
2174
|
+
const normalized = normalizeWhitespace2(value?.replace(/^(?:(?:re|fw|fwd|aw|sv|vs|antw)\s*:\s*)+/i, "")?.replace(/[<>]/g, "")?.toLowerCase() ?? "");
|
|
2175
|
+
return normalized || undefined;
|
|
2176
|
+
};
|
|
2177
|
+
var normalizeEmailMessageId = (value) => {
|
|
2178
|
+
const normalized = normalizeWhitespace2(value ?? "");
|
|
2179
|
+
return normalized || undefined;
|
|
2180
|
+
};
|
|
2181
|
+
var parseEmailReferenceChain = (references) => (references?.match(/<[^>]+>/g) ?? []).map((entry) => normalizeWhitespace2(entry)).filter(Boolean);
|
|
2182
|
+
|
|
2183
|
+
// src/extractors/email.ts
|
|
2184
|
+
var createEmailExtractor2 = () => ({
|
|
2185
|
+
name: "absolute_email",
|
|
2186
|
+
supports: emailExtractorSupports,
|
|
2187
|
+
extract: async (input) => {
|
|
2188
|
+
const source = input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}.eml`;
|
|
2189
|
+
const extension = inferExtensionFromInput(input);
|
|
2190
|
+
const emlx = extension === ".emlx" ? decodeEmlxMessageData(input.data) : undefined;
|
|
2191
|
+
const raw = emlx?.raw ?? decodeLatin1(input.data);
|
|
2192
|
+
if (extension === ".emlx") {
|
|
2193
|
+
return extractEmailDocumentsFromRawMessage(input, raw, {
|
|
2194
|
+
metadata: {
|
|
2195
|
+
emailMailboxContainerSource: source,
|
|
2196
|
+
emailMailboxFormat: "emlx",
|
|
2197
|
+
emailMailboxMessageCount: 1,
|
|
2198
|
+
emailMailboxMessageIndex: 0,
|
|
2199
|
+
emailMailboxMessageOrdinal: 1,
|
|
2200
|
+
...typeof emlx?.messageByteLength === "number" ? {
|
|
2201
|
+
emailMailboxMessageByteLength: emlx.messageByteLength
|
|
2202
|
+
} : {},
|
|
2203
|
+
...emlx?.hasTrailingMetadata ? { emailMailboxHasTrailingMetadata: true } : {}
|
|
2204
|
+
},
|
|
2205
|
+
source
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
if (extension === ".mbox" || extension === ".mbx") {
|
|
2209
|
+
const messages = splitMboxMessages(raw);
|
|
2210
|
+
const documents = await Promise.all(messages.map((messageRaw, index) => extractEmailDocumentsFromRawMessage(input, messageRaw, {
|
|
2211
|
+
metadata: {
|
|
2212
|
+
emailMailboxContainerSource: source,
|
|
2213
|
+
emailMailboxFormat: "mbox",
|
|
2214
|
+
emailMailboxMessageCount: messages.length,
|
|
2215
|
+
emailMailboxMessageIndex: index,
|
|
2216
|
+
emailMailboxMessageOrdinal: index + 1
|
|
2217
|
+
},
|
|
2218
|
+
source: `${source}#messages/${index + 1}`
|
|
2219
|
+
})));
|
|
2220
|
+
return documents.flat();
|
|
2221
|
+
}
|
|
2222
|
+
return extractEmailDocumentsFromRawMessage(input, raw, { source });
|
|
2223
|
+
}
|
|
2224
|
+
});
|
|
2225
|
+
|
|
2226
|
+
// src/epub.ts
|
|
2227
|
+
var epubText = (entries) => {
|
|
2228
|
+
const htmlEntries = entries.filter((entry) => /\.(xhtml|html|htm)$/i.test(entry.path));
|
|
2229
|
+
return normalizeWhitespace2(htmlEntries.map((entry) => stripHtml2(decodeUtf8(entry.data))).join(`
|
|
2230
|
+
|
|
2231
|
+
`));
|
|
2232
|
+
};
|
|
2233
|
+
|
|
2234
|
+
// src/extractors/epub.ts
|
|
2235
|
+
var createEPUBExtractor2 = () => ({
|
|
2236
|
+
name: "absolute_epub",
|
|
2237
|
+
supports: epubExtractorSupports,
|
|
2238
|
+
extract: (input) => {
|
|
2239
|
+
const text = epubText(unzipEntries(input.data));
|
|
2240
|
+
if (!text) {
|
|
2241
|
+
throw new Error(`AbsoluteJS could not extract readable text from ${inferNameFromInput(input)}`);
|
|
2242
|
+
}
|
|
2243
|
+
return {
|
|
2244
|
+
contentType: input.contentType,
|
|
2245
|
+
format: "text",
|
|
2246
|
+
metadata: {
|
|
2247
|
+
...input.metadata ?? {},
|
|
2248
|
+
fileKind: "epub"
|
|
2249
|
+
},
|
|
2250
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}.epub`,
|
|
2251
|
+
text,
|
|
2252
|
+
title: input.title
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
});
|
|
2256
|
+
|
|
2257
|
+
// src/legacy.ts
|
|
2258
|
+
var stripRTF = (value) => {
|
|
2259
|
+
const withoutBinary = value.replace(/\\bin\d+ [\s\S]*?(?=[\\}])/g, " ");
|
|
2260
|
+
const withoutControls = withoutBinary.replace(/\\par[d]?/g, `
|
|
2261
|
+
`).replace(/\\tab/g, "\t").replace(/\\'[0-9a-fA-F]{2}/g, (match) => String.fromCharCode(parseInt(match.slice(2), 16))).replace(/\\[a-zA-Z]+\d* ?/g, " ").replace(/[{}]/g, " ");
|
|
2262
|
+
return normalizeWhitespace2(withoutControls);
|
|
2263
|
+
};
|
|
2264
|
+
var extractOrderedPrintableStrings = (data) => {
|
|
2265
|
+
const text = Buffer.from(data).toString("latin1");
|
|
2266
|
+
const asciiMatches = text.match(/[A-Za-z0-9][A-Za-z0-9 ,.;:!?@#$%^&*()[\]_\-+/\\'"`~|=<>]{3,}/g) ?? [];
|
|
2267
|
+
const utf16Matches = Buffer.from(data).toString("utf16le").match(/[A-Za-z0-9][A-Za-z0-9 ,.;:!?@#$%^&*()[\]_\-+/\\'"`~|=<>]{3,}/g) ?? [];
|
|
2268
|
+
const values = [...asciiMatches, ...utf16Matches].map((entry) => normalizeWhitespace2(entry));
|
|
2269
|
+
return values.filter((entry) => entry.length >= 4).join(`
|
|
2270
|
+
`);
|
|
2271
|
+
};
|
|
2272
|
+
var extractPrintableStrings = (data) => {
|
|
2273
|
+
const values = extractOrderedPrintableStrings(data).split(`
|
|
2274
|
+
`).filter(Boolean);
|
|
2275
|
+
const unique = [...new Set(values)].filter((entry) => entry.length >= 4);
|
|
2276
|
+
return unique.join(`
|
|
2277
|
+
`);
|
|
2278
|
+
};
|
|
2279
|
+
|
|
2280
|
+
// src/extractors/legacy.ts
|
|
2281
|
+
var createLegacyDocumentExtractor2 = () => ({
|
|
2282
|
+
name: "absolute_legacy_document",
|
|
2283
|
+
supports: legacyExtractorSupports,
|
|
2284
|
+
extract: (input) => {
|
|
2285
|
+
const extension = inferExtensionFromInput(input);
|
|
2286
|
+
const raw = extension === ".rtf" ? stripRTF(Buffer.from(input.data).toString("latin1")) : extractPrintableStrings(input.data);
|
|
2287
|
+
if (!raw) {
|
|
2288
|
+
throw new Error(`AbsoluteJS could not extract readable text from ${inferNameFromInput(input)}`);
|
|
2289
|
+
}
|
|
2290
|
+
const fileKind = extension === ".msg" ? "email" : extension === ".rtf" ? "rtf" : "legacy_office";
|
|
2291
|
+
return {
|
|
2292
|
+
contentType: input.contentType,
|
|
2293
|
+
format: "text",
|
|
2294
|
+
metadata: {
|
|
2295
|
+
...input.metadata ?? {},
|
|
2296
|
+
fileKind,
|
|
2297
|
+
legacyFormat: extension.replace(/^\./, "")
|
|
2298
|
+
},
|
|
2299
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}${extension || ".legacy"}`,
|
|
2300
|
+
text: raw,
|
|
2301
|
+
title: input.title
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
});
|
|
2305
|
+
|
|
2306
|
+
// src/email/mailboxMetadata.ts
|
|
2307
|
+
var buildMailboxStateMetadata = (stateFlags) => ({
|
|
2308
|
+
...stateFlags.length > 0 ? { emailMailboxStateFlags: stateFlags } : {},
|
|
2309
|
+
emailMailboxIsDraft: stateFlags.includes("draft"),
|
|
2310
|
+
emailMailboxIsFlagged: stateFlags.includes("flagged"),
|
|
2311
|
+
emailMailboxIsPassed: stateFlags.includes("passed"),
|
|
2312
|
+
emailMailboxIsRead: stateFlags.includes("read"),
|
|
2313
|
+
emailMailboxIsReplied: stateFlags.includes("replied"),
|
|
2314
|
+
emailMailboxIsTrashed: stateFlags.includes("trashed"),
|
|
2315
|
+
emailMailboxIsUnread: stateFlags.includes("unread")
|
|
2316
|
+
});
|
|
2317
|
+
var parseMailboxAttachmentNames = (value) => {
|
|
2318
|
+
if (!value) {
|
|
2319
|
+
return [];
|
|
2320
|
+
}
|
|
2321
|
+
return value.split(/[;,|]+/g).map((entry) => normalizeWhitespace2(entry)).filter(Boolean);
|
|
2322
|
+
};
|
|
2323
|
+
var parseMailboxStateFlags = (value) => {
|
|
2324
|
+
if (!value) {
|
|
2325
|
+
return [];
|
|
2326
|
+
}
|
|
2327
|
+
const tokens = value.toLowerCase().split(/[^a-z0-9]+/g).map((token) => token.trim()).filter(Boolean);
|
|
2328
|
+
const flags = new Set;
|
|
2329
|
+
const add = (flag) => flags.add(flag);
|
|
2330
|
+
for (const token of tokens) {
|
|
2331
|
+
switch (token) {
|
|
2332
|
+
case "read":
|
|
2333
|
+
case "seen":
|
|
2334
|
+
add("read");
|
|
2335
|
+
break;
|
|
2336
|
+
case "unread":
|
|
2337
|
+
case "unseen":
|
|
2338
|
+
case "new":
|
|
2339
|
+
add("unread");
|
|
2340
|
+
break;
|
|
2341
|
+
case "flagged":
|
|
2342
|
+
case "starred":
|
|
2343
|
+
case "important":
|
|
2344
|
+
add("flagged");
|
|
2345
|
+
break;
|
|
2346
|
+
case "replied":
|
|
2347
|
+
case "answered":
|
|
2348
|
+
add("replied");
|
|
2349
|
+
break;
|
|
2350
|
+
case "draft":
|
|
2351
|
+
add("draft");
|
|
2352
|
+
break;
|
|
2353
|
+
case "trashed":
|
|
2354
|
+
case "trash":
|
|
2355
|
+
case "deleted":
|
|
2356
|
+
add("trashed");
|
|
2357
|
+
break;
|
|
2358
|
+
case "passed":
|
|
2359
|
+
case "forwarded":
|
|
2360
|
+
add("passed");
|
|
2361
|
+
break;
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
if (!flags.has("read") && !flags.has("unread")) {
|
|
2365
|
+
flags.add("unread");
|
|
2366
|
+
}
|
|
2367
|
+
return [...flags];
|
|
2368
|
+
};
|
|
2369
|
+
var parseMailboxFolderMetadata = (value) => {
|
|
2370
|
+
if (!value) {
|
|
2371
|
+
return {};
|
|
2372
|
+
}
|
|
2373
|
+
const pathSegments = value.split(/[\\/]+/).map((segment) => normalizeWhitespace2(segment)).filter(Boolean);
|
|
2374
|
+
if (pathSegments.length === 0) {
|
|
2375
|
+
return {};
|
|
2376
|
+
}
|
|
2377
|
+
const familyKey = pathSegments.map((segment) => segment.toLowerCase()).join("/");
|
|
2378
|
+
const leaf = pathSegments.at(-1);
|
|
2379
|
+
return {
|
|
2380
|
+
emailMailboxFamilyKey: familyKey,
|
|
2381
|
+
emailMailboxFolder: leaf,
|
|
2382
|
+
emailMailboxLeaf: leaf,
|
|
2383
|
+
emailMailboxPathDepth: pathSegments.length,
|
|
2384
|
+
emailMailboxPathSegments: pathSegments
|
|
2385
|
+
};
|
|
2386
|
+
};
|
|
2387
|
+
|
|
2388
|
+
// src/email/mailboxContainer.ts
|
|
2389
|
+
var MAILBOX_CONTAINER_DECORATOR_KEYS = new Set([
|
|
2390
|
+
"folder",
|
|
2391
|
+
"mailbox",
|
|
2392
|
+
"flags",
|
|
2393
|
+
"sender",
|
|
2394
|
+
"sender-name",
|
|
2395
|
+
"sender-email",
|
|
2396
|
+
"recipients",
|
|
2397
|
+
"to-recipients",
|
|
2398
|
+
"cc-recipients",
|
|
2399
|
+
"bcc-recipients",
|
|
2400
|
+
"reply-to-recipients",
|
|
2401
|
+
"sent",
|
|
2402
|
+
"received",
|
|
2403
|
+
"internet-message-id",
|
|
2404
|
+
"client-submit-time",
|
|
2405
|
+
"delivery-time",
|
|
2406
|
+
"creation-time",
|
|
2407
|
+
"last-modified-time",
|
|
2408
|
+
"parent-message-id",
|
|
2409
|
+
"reference-chain",
|
|
2410
|
+
"message-class",
|
|
2411
|
+
"attachment",
|
|
2412
|
+
"attachment-content-id",
|
|
2413
|
+
"attachment-content-location",
|
|
2414
|
+
"attachment-content-type",
|
|
2415
|
+
"attachment-data",
|
|
2416
|
+
"attachment-disposition",
|
|
2417
|
+
"attachment-transfer-encoding",
|
|
2418
|
+
"attachments",
|
|
2419
|
+
"categories",
|
|
2420
|
+
"conversation-index",
|
|
2421
|
+
"conversation-topic",
|
|
2422
|
+
"has-attachments",
|
|
2423
|
+
"importance",
|
|
2424
|
+
"normalized-subject",
|
|
2425
|
+
"read",
|
|
2426
|
+
"unread",
|
|
2427
|
+
"flagged",
|
|
2428
|
+
"replied",
|
|
2429
|
+
"answered",
|
|
2430
|
+
"draft",
|
|
2431
|
+
"passed",
|
|
2432
|
+
"forwarded",
|
|
2433
|
+
"sensitivity",
|
|
2434
|
+
"thread-topic",
|
|
2435
|
+
"trashed",
|
|
2436
|
+
"deleted"
|
|
2437
|
+
]);
|
|
2438
|
+
var MAILBOX_CONTAINER_EMAIL_HEADER_KEYS = new Set([
|
|
2439
|
+
"subject",
|
|
2440
|
+
"from",
|
|
2441
|
+
"to",
|
|
2442
|
+
"cc",
|
|
2443
|
+
"bcc",
|
|
2444
|
+
"reply-to",
|
|
2445
|
+
"thread-topic",
|
|
2446
|
+
"date",
|
|
2447
|
+
"message-id",
|
|
2448
|
+
"in-reply-to",
|
|
2449
|
+
"references",
|
|
2450
|
+
"content-type"
|
|
2451
|
+
]);
|
|
2452
|
+
var buildMailboxContainerSenderHeader = (leadingMetadata) => {
|
|
2453
|
+
const explicitSender = normalizeWhitespace2(leadingMetadata.sender ?? "");
|
|
2454
|
+
if (explicitSender) {
|
|
2455
|
+
return explicitSender;
|
|
2456
|
+
}
|
|
2457
|
+
const senderEmail = normalizeWhitespace2(leadingMetadata["sender-email"] ?? "");
|
|
2458
|
+
const senderName = normalizeWhitespace2(leadingMetadata["sender-name"] ?? "");
|
|
2459
|
+
if (senderEmail && senderName) {
|
|
2460
|
+
return `${senderName} <${senderEmail}>`;
|
|
2461
|
+
}
|
|
2462
|
+
return senderEmail || senderName || undefined;
|
|
2463
|
+
};
|
|
2464
|
+
var buildMailboxContainerSyntheticHeaders = (messageRaw, leadingMetadata) => {
|
|
2465
|
+
const { headerBlock, body } = splitEmailMessage(messageRaw);
|
|
2466
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
2467
|
+
const syntheticHeaderLines = [];
|
|
2468
|
+
const senderHeader = buildMailboxContainerSenderHeader(leadingMetadata);
|
|
2469
|
+
const toHeader = normalizeWhitespace2(leadingMetadata["to-recipients"] ?? leadingMetadata.recipients ?? "");
|
|
2470
|
+
const ccHeader = normalizeWhitespace2(leadingMetadata["cc-recipients"] ?? "");
|
|
2471
|
+
const bccHeader = normalizeWhitespace2(leadingMetadata["bcc-recipients"] ?? "");
|
|
2472
|
+
const replyToHeader = normalizeWhitespace2(leadingMetadata["reply-to-recipients"] ?? "");
|
|
2473
|
+
const threadTopicHeader = normalizeWhitespace2(leadingMetadata["conversation-topic"] ?? leadingMetadata["thread-topic"] ?? "");
|
|
2474
|
+
const subjectHeader = normalizeWhitespace2(leadingMetadata["normalized-subject"] ?? "");
|
|
2475
|
+
const conversationIdHeader = normalizeWhitespace2(leadingMetadata["conversation-id"] ?? "");
|
|
2476
|
+
const threadIndexHeader = normalizeWhitespace2(leadingMetadata["conversation-index"] ?? "");
|
|
2477
|
+
const inReplyToHeader = normalizeWhitespace2(leadingMetadata["parent-message-id"] ?? "");
|
|
2478
|
+
const referencesHeader = normalizeWhitespace2(leadingMetadata["reference-chain"] ?? "");
|
|
2479
|
+
const sentHeader = normalizeWhitespace2(leadingMetadata.sent ?? leadingMetadata["client-submit-time"] ?? leadingMetadata["creation-time"] ?? "");
|
|
2480
|
+
const messageIdHeader = normalizeWhitespace2(leadingMetadata["internet-message-id"] ?? "");
|
|
2481
|
+
if (!headers.has("from") && senderHeader) {
|
|
2482
|
+
syntheticHeaderLines.push(`From: ${senderHeader}`);
|
|
2483
|
+
}
|
|
2484
|
+
if (!headers.has("to") && toHeader) {
|
|
2485
|
+
syntheticHeaderLines.push(`To: ${toHeader}`);
|
|
2486
|
+
}
|
|
2487
|
+
if (!headers.has("cc") && ccHeader) {
|
|
2488
|
+
syntheticHeaderLines.push(`Cc: ${ccHeader}`);
|
|
2489
|
+
}
|
|
2490
|
+
if (!headers.has("bcc") && bccHeader) {
|
|
2491
|
+
syntheticHeaderLines.push(`Bcc: ${bccHeader}`);
|
|
2492
|
+
}
|
|
2493
|
+
if (!headers.has("reply-to") && replyToHeader) {
|
|
2494
|
+
syntheticHeaderLines.push(`Reply-To: ${replyToHeader}`);
|
|
2495
|
+
}
|
|
2496
|
+
if (!headers.has("thread-topic") && threadTopicHeader) {
|
|
2497
|
+
syntheticHeaderLines.push(`Thread-Topic: ${threadTopicHeader}`);
|
|
2498
|
+
}
|
|
2499
|
+
if (!headers.has("subject") && subjectHeader) {
|
|
2500
|
+
syntheticHeaderLines.push(`Subject: ${subjectHeader}`);
|
|
2501
|
+
}
|
|
2502
|
+
if (!headers.has("conversation-id") && conversationIdHeader) {
|
|
2503
|
+
syntheticHeaderLines.push(`Conversation-ID: ${conversationIdHeader}`);
|
|
2504
|
+
}
|
|
2505
|
+
if (!headers.has("thread-index") && threadIndexHeader) {
|
|
2506
|
+
syntheticHeaderLines.push(`Thread-Index: ${threadIndexHeader}`);
|
|
2507
|
+
}
|
|
2508
|
+
if (!headers.has("in-reply-to") && inReplyToHeader) {
|
|
2509
|
+
syntheticHeaderLines.push(`In-Reply-To: ${inReplyToHeader}`);
|
|
2510
|
+
}
|
|
2511
|
+
if (!headers.has("references") && referencesHeader) {
|
|
2512
|
+
syntheticHeaderLines.push(`References: ${referencesHeader}`);
|
|
2513
|
+
}
|
|
2514
|
+
if (!headers.has("date") && sentHeader) {
|
|
2515
|
+
syntheticHeaderLines.push(`Date: ${sentHeader}`);
|
|
2516
|
+
}
|
|
2517
|
+
if (!headers.has("message-id") && messageIdHeader) {
|
|
2518
|
+
syntheticHeaderLines.push(`Message-ID: ${messageIdHeader}`);
|
|
2519
|
+
}
|
|
2520
|
+
if (syntheticHeaderLines.length === 0) {
|
|
2521
|
+
return messageRaw;
|
|
2522
|
+
}
|
|
2523
|
+
const normalizedHeaderBlock = normalizeWhitespace2(headerBlock);
|
|
2524
|
+
const normalizedBody = normalizeWhitespace2(body);
|
|
2525
|
+
return [
|
|
2526
|
+
...syntheticHeaderLines,
|
|
2527
|
+
...normalizedHeaderBlock ? [normalizedHeaderBlock] : [],
|
|
2528
|
+
"",
|
|
2529
|
+
...normalizedBody ? [normalizedBody] : []
|
|
2530
|
+
].join(`
|
|
2531
|
+
`).trim();
|
|
2532
|
+
};
|
|
2533
|
+
var decodeMailboxContainerAttachmentData = (value, encoding) => {
|
|
2534
|
+
const normalized = normalizeWhitespace2(value);
|
|
2535
|
+
if (!normalized) {
|
|
2536
|
+
return;
|
|
2537
|
+
}
|
|
2538
|
+
const format = normalizeWhitespace2(encoding ?? "").toLowerCase();
|
|
2539
|
+
try {
|
|
2540
|
+
if (format === "base64") {
|
|
2541
|
+
return Uint8Array.from(Buffer.from(normalized, "base64"));
|
|
2542
|
+
}
|
|
2543
|
+
if (format === "hex") {
|
|
2544
|
+
return Uint8Array.from(Buffer.from(normalized, "hex"));
|
|
2545
|
+
}
|
|
2546
|
+
return Uint8Array.from(Buffer.from(value, "utf8"));
|
|
2547
|
+
} catch {
|
|
2548
|
+
return;
|
|
2549
|
+
}
|
|
2550
|
+
};
|
|
2551
|
+
var extractMailboxRecoveredEmbeddedReferences = (raw) => {
|
|
2552
|
+
const { body } = splitEmailMessage(raw);
|
|
2553
|
+
const normalizedBody = body.replace(/\r\n?/g, `
|
|
2554
|
+
`);
|
|
2555
|
+
const contentIds = [
|
|
2556
|
+
...new Set(Array.from(normalizedBody.matchAll(/cid:([A-Za-z0-9._%+\-@:$]+)/gi), (match) => normalizeEmailContentId(match[1])).filter((value) => typeof value === "string"))
|
|
2557
|
+
];
|
|
2558
|
+
return {
|
|
2559
|
+
contentIds,
|
|
2560
|
+
contentLocations: normalizedBody.split(/\s+/).map((token) => normalizeWhitespace2(token.replace(/^[("'`<]+|[)"'`>,.;:!?]+$/g, ""))).filter((token) => token.includes("/") || token.includes("."))
|
|
2561
|
+
};
|
|
2562
|
+
};
|
|
2563
|
+
var splitMailboxContainerMessages = (raw) => {
|
|
2564
|
+
const normalized = raw.replace(/\r\n?/g, `
|
|
2565
|
+
`);
|
|
2566
|
+
const lines = normalized.split(`
|
|
2567
|
+
`);
|
|
2568
|
+
const segments = [];
|
|
2569
|
+
let currentLines = [];
|
|
2570
|
+
let sawBody = false;
|
|
2571
|
+
let seenEmailHeaders = new Set;
|
|
2572
|
+
const pushCurrent = () => {
|
|
2573
|
+
const segment = normalizeWhitespace2(currentLines.join(`
|
|
2574
|
+
`));
|
|
2575
|
+
if (segment) {
|
|
2576
|
+
segments.push(segment);
|
|
2577
|
+
}
|
|
2578
|
+
currentLines = [];
|
|
2579
|
+
sawBody = false;
|
|
2580
|
+
seenEmailHeaders = new Set;
|
|
2581
|
+
};
|
|
2582
|
+
for (const line of lines) {
|
|
2583
|
+
const headerMatch = line.match(/^([A-Za-z-]+):\s*(.*)$/);
|
|
2584
|
+
const key = headerMatch?.[1]?.toLowerCase() ?? "";
|
|
2585
|
+
const isDecorator = MAILBOX_CONTAINER_DECORATOR_KEYS.has(key);
|
|
2586
|
+
const isEmailHeader = MAILBOX_CONTAINER_EMAIL_HEADER_KEYS.has(key);
|
|
2587
|
+
const startsNewDecoratedMessage = isDecorator && currentLines.length > 0 && (seenEmailHeaders.size > 0 || sawBody);
|
|
2588
|
+
const startsNewSubjectMessage = key === "subject" && currentLines.length > 0 && (sawBody || seenEmailHeaders.has("subject") && (seenEmailHeaders.has("message-id") || seenEmailHeaders.has("from")));
|
|
2589
|
+
if (startsNewDecoratedMessage || startsNewSubjectMessage) {
|
|
2590
|
+
pushCurrent();
|
|
2591
|
+
}
|
|
2592
|
+
currentLines.push(line);
|
|
2593
|
+
if (isEmailHeader) {
|
|
2594
|
+
seenEmailHeaders.add(key);
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
if (line.trim().length === 0) {
|
|
2598
|
+
if (seenEmailHeaders.size > 0) {
|
|
2599
|
+
sawBody = true;
|
|
2600
|
+
}
|
|
2601
|
+
continue;
|
|
2602
|
+
}
|
|
2603
|
+
if (seenEmailHeaders.size > 0 && !isDecorator) {
|
|
2604
|
+
sawBody = true;
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
pushCurrent();
|
|
2608
|
+
return segments.map((segment) => {
|
|
2609
|
+
const lines = segment.split(`
|
|
2610
|
+
`);
|
|
2611
|
+
const leadingMetadata = {};
|
|
2612
|
+
const attachmentDescriptorNames = [];
|
|
2613
|
+
const recoverableAttachments = [];
|
|
2614
|
+
let currentAttachment;
|
|
2615
|
+
const pushCurrentAttachment = () => {
|
|
2616
|
+
if (!currentAttachment?.fileName || !currentAttachment.dataValue) {
|
|
2617
|
+
currentAttachment = undefined;
|
|
2618
|
+
return;
|
|
2619
|
+
}
|
|
2620
|
+
const data = decodeMailboxContainerAttachmentData(currentAttachment.dataValue, currentAttachment.transferEncoding);
|
|
2621
|
+
if (!data || data.length === 0) {
|
|
2622
|
+
currentAttachment = undefined;
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2625
|
+
const normalizedContentType = normalizeWhitespace2(currentAttachment.contentType ?? "").toLowerCase();
|
|
2626
|
+
const role = normalizedContentType.includes("message/rfc822") ? "attached_message" : currentAttachment.dispositionType === "inline" || typeof currentAttachment.contentId === "string" || typeof currentAttachment.contentLocation === "string" ? "inline_resource" : "file_attachment";
|
|
2627
|
+
recoverableAttachments.push({
|
|
2628
|
+
contentId: currentAttachment.contentId,
|
|
2629
|
+
contentLocation: currentAttachment.contentLocation,
|
|
2630
|
+
contentType: currentAttachment.contentType,
|
|
2631
|
+
data,
|
|
2632
|
+
dispositionType: currentAttachment.dispositionType,
|
|
2633
|
+
fileName: currentAttachment.fileName,
|
|
2634
|
+
role
|
|
2635
|
+
});
|
|
2636
|
+
currentAttachment = undefined;
|
|
2637
|
+
};
|
|
2638
|
+
let startIndex = 0;
|
|
2639
|
+
for (;startIndex < lines.length; startIndex += 1) {
|
|
2640
|
+
const line = lines[startIndex] ?? "";
|
|
2641
|
+
const headerMatch = line.match(/^([A-Za-z-]+):\s*(.*)$/);
|
|
2642
|
+
if (!headerMatch) {
|
|
2643
|
+
continue;
|
|
2644
|
+
}
|
|
2645
|
+
const key = headerMatch[1]?.toLowerCase() ?? "";
|
|
2646
|
+
if (key === "subject" || key === "from" || key === "to" || key === "cc" || key === "bcc" || key === "reply-to" || key === "thread-topic" || key === "date" || key === "message-id" || key === "in-reply-to" || key === "references" || key === "content-type") {
|
|
2647
|
+
pushCurrentAttachment();
|
|
2648
|
+
break;
|
|
2649
|
+
}
|
|
2650
|
+
if (key === "attachment") {
|
|
2651
|
+
const names = parseMailboxAttachmentNames(headerMatch[2]);
|
|
2652
|
+
attachmentDescriptorNames.push(...names);
|
|
2653
|
+
if (names.length === 1) {
|
|
2654
|
+
pushCurrentAttachment();
|
|
2655
|
+
currentAttachment = { fileName: names[0] };
|
|
2656
|
+
}
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
if (key === "attachments") {
|
|
2660
|
+
attachmentDescriptorNames.push(...parseMailboxAttachmentNames(headerMatch[2]));
|
|
2661
|
+
leadingMetadata[key] = headerMatch[2] ?? "";
|
|
2662
|
+
continue;
|
|
2663
|
+
}
|
|
2664
|
+
if (key === "attachment-content-type") {
|
|
2665
|
+
if (currentAttachment) {
|
|
2666
|
+
currentAttachment.contentType = headerMatch[2] ?? "";
|
|
2667
|
+
}
|
|
2668
|
+
continue;
|
|
2669
|
+
}
|
|
2670
|
+
if (key === "attachment-transfer-encoding") {
|
|
2671
|
+
if (currentAttachment) {
|
|
2672
|
+
currentAttachment.transferEncoding = headerMatch[2] ?? "";
|
|
2673
|
+
}
|
|
2674
|
+
continue;
|
|
2675
|
+
}
|
|
2676
|
+
if (key === "attachment-data") {
|
|
2677
|
+
if (currentAttachment) {
|
|
2678
|
+
currentAttachment.dataValue = headerMatch[2] ?? "";
|
|
2679
|
+
}
|
|
2680
|
+
continue;
|
|
2681
|
+
}
|
|
2682
|
+
if (key === "attachment-disposition") {
|
|
2683
|
+
if (currentAttachment) {
|
|
2684
|
+
currentAttachment.dispositionType = normalizeWhitespace2(headerMatch[2] ?? "").toLowerCase();
|
|
2685
|
+
}
|
|
2686
|
+
continue;
|
|
2687
|
+
}
|
|
2688
|
+
if (key === "attachment-content-id") {
|
|
2689
|
+
if (currentAttachment) {
|
|
2690
|
+
currentAttachment.contentId = normalizeWhitespace2(headerMatch[2] ?? "");
|
|
2691
|
+
}
|
|
2692
|
+
continue;
|
|
2693
|
+
}
|
|
2694
|
+
if (key === "attachment-content-location") {
|
|
2695
|
+
if (currentAttachment) {
|
|
2696
|
+
currentAttachment.contentLocation = normalizeWhitespace2(headerMatch[2] ?? "");
|
|
2697
|
+
}
|
|
2698
|
+
continue;
|
|
2699
|
+
}
|
|
2700
|
+
if (key === "folder" || key === "mailbox" || key === "sender" || key === "sender-name" || key === "sender-email" || key === "recipients" || key === "to-recipients" || key === "cc-recipients" || key === "bcc-recipients" || key === "reply-to-recipients" || key === "sent" || key === "received" || key === "internet-message-id" || key === "client-submit-time" || key === "delivery-time" || key === "creation-time" || key === "last-modified-time" || key === "parent-message-id" || key === "reference-chain" || key === "message-class" || key === "categories" || key === "conversation-id" || key === "conversation-index" || key === "conversation-topic" || key === "flags" || key === "has-attachments" || key === "importance" || key === "normalized-subject" || key === "read" || key === "sensitivity" || key === "thread-topic" || key === "unread" || key === "flagged" || key === "replied" || key === "answered" || key === "draft" || key === "passed" || key === "forwarded" || key === "trashed" || key === "deleted") {
|
|
2701
|
+
leadingMetadata[key] = headerMatch[2] ?? "";
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
pushCurrentAttachment();
|
|
2705
|
+
const messageRaw = buildMailboxContainerSyntheticHeaders(normalizeWhitespace2(lines.slice(startIndex).join(`
|
|
2706
|
+
`)), leadingMetadata);
|
|
2707
|
+
const mailboxFolderValue = leadingMetadata.folder ?? leadingMetadata.mailbox;
|
|
2708
|
+
const attachmentNames = [
|
|
2709
|
+
...new Set([
|
|
2710
|
+
...attachmentDescriptorNames,
|
|
2711
|
+
...parseMailboxAttachmentNames(leadingMetadata.attachments)
|
|
2712
|
+
])
|
|
2713
|
+
];
|
|
2714
|
+
const categories = parseMailboxAttachmentNames(leadingMetadata.categories);
|
|
2715
|
+
const explicitStateFlags = parseMailboxStateFlags(leadingMetadata.flags);
|
|
2716
|
+
const booleanStateFlags = parseMailboxStateFlags([
|
|
2717
|
+
leadingMetadata.read === "true" ? "read" : undefined,
|
|
2718
|
+
leadingMetadata.unread === "true" ? "unread" : undefined,
|
|
2719
|
+
leadingMetadata.flagged === "true" ? "flagged" : undefined,
|
|
2720
|
+
leadingMetadata.replied === "true" || leadingMetadata.answered === "true" ? "replied" : undefined,
|
|
2721
|
+
leadingMetadata.draft === "true" ? "draft" : undefined,
|
|
2722
|
+
leadingMetadata.passed === "true" || leadingMetadata.forwarded === "true" ? "passed" : undefined,
|
|
2723
|
+
leadingMetadata.trashed === "true" || leadingMetadata.deleted === "true" ? "trashed" : undefined
|
|
2724
|
+
].filter((value) => typeof value === "string").join(" "));
|
|
2725
|
+
const stateFlags = [
|
|
2726
|
+
...new Set([...explicitStateFlags, ...booleanStateFlags])
|
|
2727
|
+
];
|
|
2728
|
+
return {
|
|
2729
|
+
metadata: {
|
|
2730
|
+
...parseMailboxFolderMetadata(mailboxFolderValue),
|
|
2731
|
+
...buildMailboxStateMetadata(stateFlags),
|
|
2732
|
+
...attachmentNames.length > 0 ? {
|
|
2733
|
+
attachmentCount: attachmentNames.length,
|
|
2734
|
+
attachmentNames,
|
|
2735
|
+
hasAttachments: true
|
|
2736
|
+
} : leadingMetadata["has-attachments"] === "true" ? {
|
|
2737
|
+
attachmentCount: 1,
|
|
2738
|
+
hasAttachments: true
|
|
2739
|
+
} : {},
|
|
2740
|
+
...categories.length > 0 ? { emailCategories: categories } : {},
|
|
2741
|
+
...typeof leadingMetadata.importance === "string" && leadingMetadata.importance.trim().length > 0 ? {
|
|
2742
|
+
emailImportance: normalizeWhitespace2(leadingMetadata.importance)
|
|
2743
|
+
} : {},
|
|
2744
|
+
...typeof leadingMetadata["normalized-subject"] === "string" && leadingMetadata["normalized-subject"].trim().length > 0 ? {
|
|
2745
|
+
emailNormalizedSubject: normalizeWhitespace2(leadingMetadata["normalized-subject"])
|
|
2746
|
+
} : {},
|
|
2747
|
+
...typeof leadingMetadata.sensitivity === "string" && leadingMetadata.sensitivity.trim().length > 0 ? {
|
|
2748
|
+
emailSensitivity: normalizeWhitespace2(leadingMetadata.sensitivity)
|
|
2749
|
+
} : {},
|
|
2750
|
+
...typeof leadingMetadata["conversation-topic"] === "string" && leadingMetadata["conversation-topic"].trim().length > 0 ? {
|
|
2751
|
+
emailConversationTopic: normalizeWhitespace2(leadingMetadata["conversation-topic"]),
|
|
2752
|
+
threadTopic: normalizeWhitespace2(leadingMetadata["conversation-topic"])
|
|
2753
|
+
} : typeof leadingMetadata["thread-topic"] === "string" && leadingMetadata["thread-topic"].trim().length > 0 ? {
|
|
2754
|
+
threadTopic: normalizeWhitespace2(leadingMetadata["thread-topic"])
|
|
2755
|
+
} : {},
|
|
2756
|
+
...typeof leadingMetadata["conversation-id"] === "string" && leadingMetadata["conversation-id"].trim().length > 0 ? {
|
|
2757
|
+
emailConversationId: normalizeWhitespace2(leadingMetadata["conversation-id"])
|
|
2758
|
+
} : {},
|
|
2759
|
+
...typeof leadingMetadata["conversation-index"] === "string" && leadingMetadata["conversation-index"].trim().length > 0 ? {
|
|
2760
|
+
emailConversationIndex: normalizeWhitespace2(leadingMetadata["conversation-index"])
|
|
2761
|
+
} : {},
|
|
2762
|
+
...typeof leadingMetadata.sent === "string" && leadingMetadata.sent.trim().length > 0 ? {
|
|
2763
|
+
emailSentAt: normalizeWhitespace2(leadingMetadata.sent)
|
|
2764
|
+
} : typeof leadingMetadata["client-submit-time"] === "string" && leadingMetadata["client-submit-time"].trim().length > 0 ? {
|
|
2765
|
+
emailSentAt: normalizeWhitespace2(leadingMetadata["client-submit-time"])
|
|
2766
|
+
} : typeof leadingMetadata["creation-time"] === "string" && leadingMetadata["creation-time"].trim().length > 0 ? {
|
|
2767
|
+
emailSentAt: normalizeWhitespace2(leadingMetadata["creation-time"])
|
|
2768
|
+
} : {},
|
|
2769
|
+
...typeof leadingMetadata.received === "string" && leadingMetadata.received.trim().length > 0 ? {
|
|
2770
|
+
emailReceivedAt: normalizeWhitespace2(leadingMetadata.received)
|
|
2771
|
+
} : typeof leadingMetadata["delivery-time"] === "string" && leadingMetadata["delivery-time"].trim().length > 0 ? {
|
|
2772
|
+
emailReceivedAt: normalizeWhitespace2(leadingMetadata["delivery-time"])
|
|
2773
|
+
} : {},
|
|
2774
|
+
...typeof leadingMetadata["internet-message-id"] === "string" && leadingMetadata["internet-message-id"].trim().length > 0 ? {
|
|
2775
|
+
emailInternetMessageId: normalizeWhitespace2(leadingMetadata["internet-message-id"])
|
|
2776
|
+
} : {},
|
|
2777
|
+
...typeof leadingMetadata["client-submit-time"] === "string" && leadingMetadata["client-submit-time"].trim().length > 0 ? {
|
|
2778
|
+
emailClientSubmitTime: normalizeWhitespace2(leadingMetadata["client-submit-time"])
|
|
2779
|
+
} : {},
|
|
2780
|
+
...typeof leadingMetadata["delivery-time"] === "string" && leadingMetadata["delivery-time"].trim().length > 0 ? {
|
|
2781
|
+
emailDeliveryTime: normalizeWhitespace2(leadingMetadata["delivery-time"])
|
|
2782
|
+
} : {},
|
|
2783
|
+
...typeof leadingMetadata["creation-time"] === "string" && leadingMetadata["creation-time"].trim().length > 0 ? {
|
|
2784
|
+
emailCreationTime: normalizeWhitespace2(leadingMetadata["creation-time"])
|
|
2785
|
+
} : {},
|
|
2786
|
+
...typeof leadingMetadata["last-modified-time"] === "string" && leadingMetadata["last-modified-time"].trim().length > 0 ? {
|
|
2787
|
+
emailLastModifiedTime: normalizeWhitespace2(leadingMetadata["last-modified-time"])
|
|
2788
|
+
} : {},
|
|
2789
|
+
...typeof leadingMetadata["message-class"] === "string" && leadingMetadata["message-class"].trim().length > 0 ? {
|
|
2790
|
+
emailMessageClass: normalizeWhitespace2(leadingMetadata["message-class"])
|
|
2791
|
+
} : {}
|
|
2792
|
+
},
|
|
2793
|
+
...recoverableAttachments.length > 0 ? { attachments: recoverableAttachments } : {},
|
|
2794
|
+
raw: messageRaw
|
|
2795
|
+
};
|
|
2796
|
+
}).filter((segment) => {
|
|
2797
|
+
const { headerBlock } = splitEmailMessage(segment.raw);
|
|
2798
|
+
const headers = parseHeaderBlock(headerBlock);
|
|
2799
|
+
return headers.size >= 3 && (headers.has("subject") || headers.has("message-id")) && (headers.has("from") || headers.has("to") || headers.has("date"));
|
|
2800
|
+
});
|
|
2801
|
+
};
|
|
2802
|
+
|
|
2803
|
+
// src/extractors/mailbox.ts
|
|
2804
|
+
var createMailboxContainerExtractor2 = () => ({
|
|
2805
|
+
name: "absolute_mailbox_container",
|
|
2806
|
+
supports: mailboxContainerExtractorSupports,
|
|
2807
|
+
extract: async (input) => {
|
|
2808
|
+
const extension = inferExtensionFromInput(input);
|
|
2809
|
+
const format = extension.replace(/^\./, "") || "mailbox";
|
|
2810
|
+
const source = input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}${extension || ".mailbox"}`;
|
|
2811
|
+
const raw = extractOrderedPrintableStrings(input.data);
|
|
2812
|
+
if (!raw) {
|
|
2813
|
+
throw new Error(`AbsoluteJS could not extract readable text from ${inferNameFromInput(input)}`);
|
|
2814
|
+
}
|
|
2815
|
+
const messages = splitMailboxContainerMessages(raw);
|
|
2816
|
+
if (messages.length > 0) {
|
|
2817
|
+
const documents = await Promise.all(messages.map(async (message, index) => {
|
|
2818
|
+
const messageSource = `${source}#messages/${index + 1}`;
|
|
2819
|
+
const extractedDocuments = await extractEmailDocumentsFromRawMessage(input, message.raw, {
|
|
2820
|
+
metadata: {
|
|
2821
|
+
...message.metadata,
|
|
2822
|
+
emailMailboxContainerSource: source,
|
|
2823
|
+
emailMailboxFormat: format,
|
|
2824
|
+
emailMailboxMessageCount: messages.length,
|
|
2825
|
+
emailMailboxMessageIndex: index,
|
|
2826
|
+
emailMailboxMessageOrdinal: index + 1
|
|
2827
|
+
},
|
|
2828
|
+
source: messageSource
|
|
2829
|
+
});
|
|
2830
|
+
if (!message.attachments || message.attachments.length === 0) {
|
|
2831
|
+
return extractedDocuments;
|
|
2832
|
+
}
|
|
2833
|
+
const embeddedReferences = extractMailboxRecoveredEmbeddedReferences(message.raw);
|
|
2834
|
+
const messageDocument = extractedDocuments.find((document) => document.metadata?.emailKind === "message");
|
|
2835
|
+
const baseMetadata = {
|
|
2836
|
+
...messageDocument?.metadata ?? {},
|
|
2837
|
+
emailMailboxContainerSource: source,
|
|
2838
|
+
emailMailboxFormat: format,
|
|
2839
|
+
emailMailboxMessageCount: messages.length,
|
|
2840
|
+
emailMailboxMessageIndex: index,
|
|
2841
|
+
emailMailboxMessageOrdinal: index + 1
|
|
2842
|
+
};
|
|
2843
|
+
const mailboxAttachmentDocuments = await Promise.all(message.attachments.map(async (attachment, attachmentIndex) => extractDocuments2({
|
|
2844
|
+
contentType: attachment.contentType,
|
|
2845
|
+
data: attachment.data,
|
|
2846
|
+
extractorRegistry: input.extractorRegistry,
|
|
2847
|
+
format: inferFormatFromContentType2(attachment.contentType ?? null) ?? inferFormatFromName2(attachment.fileName),
|
|
2848
|
+
metadata: {
|
|
2849
|
+
...baseMetadata,
|
|
2850
|
+
attachmentIndex,
|
|
2851
|
+
attachmentContentId: attachment.contentId,
|
|
2852
|
+
attachmentContentLocation: attachment.contentLocation,
|
|
2853
|
+
attachmentDisposition: attachment.dispositionType ?? "attachment",
|
|
2854
|
+
attachmentEmbeddedReferenceMatched: (attachment.contentId ? embeddedReferences.contentIds.includes(attachment.contentId) : false) || (attachment.contentLocation ? embeddedReferences.contentLocations.includes(attachment.contentLocation) || message.raw.includes(attachment.contentLocation) : false),
|
|
2855
|
+
attachmentName: attachment.fileName,
|
|
2856
|
+
attachmentRecoveredFromMailboxContainer: true,
|
|
2857
|
+
emailAttachmentRole: attachment.role,
|
|
2858
|
+
emailAttachmentSource: `${messageSource}#attachments/${attachment.fileName}`,
|
|
2859
|
+
emailKind: "attachment"
|
|
2860
|
+
},
|
|
2861
|
+
name: attachment.fileName,
|
|
2862
|
+
source: `${messageSource}#attachments/${attachment.fileName}`,
|
|
2863
|
+
title: messageDocument?.title ? `${messageDocument.title} \xB7 ${attachment.fileName}` : attachment.fileName
|
|
2864
|
+
})));
|
|
2865
|
+
return [...extractedDocuments, ...mailboxAttachmentDocuments.flat()];
|
|
2866
|
+
}));
|
|
2867
|
+
return documents.flat();
|
|
2868
|
+
}
|
|
2869
|
+
return {
|
|
2870
|
+
contentType: input.contentType,
|
|
2871
|
+
format: "text",
|
|
2872
|
+
metadata: {
|
|
2873
|
+
...input.metadata ?? {},
|
|
2874
|
+
emailMailboxContainerSource: source,
|
|
2875
|
+
emailMailboxFormat: format,
|
|
2876
|
+
fileKind: "email_mailbox"
|
|
2877
|
+
},
|
|
2878
|
+
source,
|
|
2879
|
+
text: raw,
|
|
2880
|
+
title: input.title
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
});
|
|
2884
|
+
|
|
2885
|
+
// src/office/word.ts
|
|
2886
|
+
var extractXmlText = (value) => normalizeWhitespace2(decodeHtmlEntities(value.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ")));
|
|
2887
|
+
var extractOfficeParagraphText = (value) => normalizeWhitespace2(decodeHtmlEntities(value.replace(/<w:tab\b[^>]*\/>/gi, "\t").replace(/<w:br\b[^>]*\/>/gi, `
|
|
2888
|
+
`).replace(/<[^>]+>/g, " ")));
|
|
2889
|
+
var officeDocumentBlocks = (entries) => {
|
|
2890
|
+
const documentEntry = entries.find((entry) => entry.path === "word/document.xml");
|
|
2891
|
+
if (!documentEntry) {
|
|
2892
|
+
return [];
|
|
2893
|
+
}
|
|
2894
|
+
const xml = decodeUtf8(documentEntry.data);
|
|
2895
|
+
const bodyMatch = xml.match(/<w:body\b[^>]*>([\s\S]*?)<\/w:body>/i);
|
|
2896
|
+
const body = bodyMatch?.[1] ?? xml;
|
|
2897
|
+
const blocks = [];
|
|
2898
|
+
const blockPattern = /<(w:p|w:tbl)\b[\s\S]*?<\/\1>/g;
|
|
2899
|
+
for (const match of body.matchAll(blockPattern)) {
|
|
2900
|
+
const blockXml = match[0] ?? "";
|
|
2901
|
+
if (blockXml.startsWith("<w:tbl")) {
|
|
2902
|
+
const tableRows = [...blockXml.matchAll(/<w:tr\b[\s\S]*?<\/w:tr>/g)].map((rowMatch) => [...(rowMatch[0] ?? "").matchAll(/<w:tc\b[\s\S]*?<\/w:tc>/g)].map((cellMatch) => extractOfficeParagraphText(cellMatch[0] ?? "")).filter(Boolean)).filter((cells) => cells.length > 0);
|
|
2903
|
+
const rows = tableRows.map((cells, rowIndex) => {
|
|
2904
|
+
return `Row ${rowIndex + 1}. ${cells.map((cell, cellIndex) => `${String.fromCharCode(65 + cellIndex)}: ${cell}`).join(" | ")}`;
|
|
2905
|
+
}).filter(Boolean);
|
|
2906
|
+
const text = normalizeWhitespace2(rows.join(`
|
|
2907
|
+
`));
|
|
2908
|
+
if (!text) {
|
|
2909
|
+
continue;
|
|
2910
|
+
}
|
|
2911
|
+
const tableHeaders = tableRows[0];
|
|
2912
|
+
const tableRowCount = tableRows.length;
|
|
2913
|
+
const tableBodyRowCount = tableRowCount > 0 ? Math.max(0, tableRowCount - 1) : undefined;
|
|
2914
|
+
const tableColumnCount = Array.isArray(tableHeaders) && tableHeaders.length > 0 ? tableHeaders.length : tableRows.reduce((max, row) => Math.max(max, row.length), 0) || undefined;
|
|
2915
|
+
const tableHeaderText = Array.isArray(tableHeaders) && tableHeaders.length > 0 ? tableHeaders.join(" | ") : undefined;
|
|
2916
|
+
const tableSignature = Array.isArray(tableHeaders) && tableHeaders.length > 0 ? tableHeaders.join(" | ") : undefined;
|
|
2917
|
+
blocks.push({
|
|
2918
|
+
blockKind: "table",
|
|
2919
|
+
blockNumber: blocks.length + 1,
|
|
2920
|
+
...typeof tableBodyRowCount === "number" ? { tableBodyRowCount } : {},
|
|
2921
|
+
...typeof tableColumnCount === "number" ? { tableColumnCount } : {},
|
|
2922
|
+
...typeof tableHeaderText === "string" ? { tableHeaderText } : {},
|
|
2923
|
+
...Array.isArray(tableHeaders) && tableHeaders.length > 0 ? { tableHeaders } : {},
|
|
2924
|
+
...typeof tableRowCount === "number" ? { tableRowCount } : {},
|
|
2925
|
+
...typeof tableSignature === "string" ? { tableSignature } : {},
|
|
2926
|
+
text
|
|
2927
|
+
});
|
|
2928
|
+
continue;
|
|
2929
|
+
}
|
|
2930
|
+
const text = extractOfficeParagraphText(blockXml);
|
|
2931
|
+
if (!text) {
|
|
2932
|
+
continue;
|
|
2933
|
+
}
|
|
2934
|
+
const styleMatch = blockXml.match(/<w:pStyle\b[^>]*w:val="([^"]+)"[^>]*\/?>/i);
|
|
2935
|
+
const style = (styleMatch?.[1] ?? "").toLowerCase();
|
|
2936
|
+
const headingMatch = style.match(/^heading([1-6])$/);
|
|
2937
|
+
const isListParagraph = /<w:numPr\b/i.test(blockXml) || style.includes("list") || style.includes("bullet");
|
|
2938
|
+
const listLevelMatch = blockXml.match(/<w:ilvl\b[^>]*w:val="(\d+)"[^>]*\/?>/i);
|
|
2939
|
+
const listLevel = listLevelMatch ? Number.parseInt(listLevelMatch[1] ?? "0", 10) : undefined;
|
|
2940
|
+
const blockKind = style === "title" ? "title" : headingMatch ? "heading" : isListParagraph ? "list" : "paragraph";
|
|
2941
|
+
const listPrefix = blockKind === "list" ? `${" ".repeat(Math.max(0, listLevel ?? 0))}- ` : "";
|
|
2942
|
+
const decoratedText = blockKind === "list" && !/^[-*]\s/.test(text) ? `${listPrefix}${text}` : text;
|
|
2943
|
+
blocks.push({
|
|
2944
|
+
blockKind,
|
|
2945
|
+
blockNumber: blocks.length + 1,
|
|
2946
|
+
headingLevel: headingMatch ? Number.parseInt(headingMatch[1] ?? "1", 10) : undefined,
|
|
2947
|
+
listLevel: blockKind === "list" && Number.isFinite(listLevel ?? NaN) ? listLevel : undefined,
|
|
2948
|
+
style: style || undefined,
|
|
2949
|
+
text: decoratedText
|
|
2950
|
+
});
|
|
2951
|
+
}
|
|
2952
|
+
return blocks;
|
|
2953
|
+
};
|
|
2954
|
+
var officeDocumentText = (entries) => {
|
|
2955
|
+
const blocks = officeDocumentBlocks(entries);
|
|
2956
|
+
if (blocks.length > 0) {
|
|
2957
|
+
return normalizeWhitespace2(blocks.map((block) => block.text).join(`
|
|
2958
|
+
|
|
2959
|
+
`));
|
|
2960
|
+
}
|
|
2961
|
+
const documentEntry = entries.find((entry) => entry.path === "word/document.xml");
|
|
2962
|
+
if (!documentEntry) {
|
|
2963
|
+
return "";
|
|
2964
|
+
}
|
|
2965
|
+
return extractXmlText(decodeUtf8(documentEntry.data));
|
|
2966
|
+
};
|
|
2967
|
+
var officeDocumentSectionCount = (entries) => {
|
|
2968
|
+
const count = officeDocumentBlocks(entries).length;
|
|
2969
|
+
return count > 0 ? count : undefined;
|
|
2970
|
+
};
|
|
2971
|
+
|
|
2972
|
+
// src/office/presentation.ts
|
|
2973
|
+
var presentationNotesByIndex = (entries) => new Map(entries.filter((entry) => entry.path.startsWith("ppt/notesSlides/") && entry.path.endsWith(".xml")).sort((left, right) => left.path.localeCompare(right.path)).map((entry) => {
|
|
2974
|
+
const indexMatch = entry.path.match(/notesSlide(\d+)\.xml$/i);
|
|
2975
|
+
const index = Number(indexMatch?.[1] ?? "0") - 1;
|
|
2976
|
+
return [
|
|
2977
|
+
index,
|
|
2978
|
+
normalizeWhitespace2(extractXmlText(decodeUtf8(entry.data)))
|
|
2979
|
+
];
|
|
2980
|
+
}).filter((entry) => entry[0] >= 0 && Boolean(entry[1])));
|
|
2981
|
+
var presentationSlides = (entries) => {
|
|
2982
|
+
const notesByIndex = presentationNotesByIndex(entries);
|
|
2983
|
+
return entries.filter((entry) => entry.path.startsWith("ppt/slides/") && entry.path.endsWith(".xml")).sort((left, right) => left.path.localeCompare(right.path, undefined, { numeric: true })).map((entry, index) => {
|
|
2984
|
+
const textRuns = [
|
|
2985
|
+
...decodeUtf8(entry.data).matchAll(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/gi)
|
|
2986
|
+
].map((match) => normalizeWhitespace2(decodeHtmlEntities(match[1] ?? ""))).filter(Boolean);
|
|
2987
|
+
const slideTitle = textRuns[0];
|
|
2988
|
+
const slideBodyText = normalizeWhitespace2(textRuns.slice(1).join(`
|
|
2989
|
+
`));
|
|
2990
|
+
const slideText = normalizeWhitespace2([slideTitle, slideBodyText].filter(Boolean).join(`
|
|
2991
|
+
`));
|
|
2992
|
+
const notesText = notesByIndex.get(index);
|
|
2993
|
+
const text = normalizeWhitespace2([slideText, notesText ? `Speaker notes: ${notesText}` : ""].filter(Boolean).join(`
|
|
2994
|
+
`));
|
|
2995
|
+
return {
|
|
2996
|
+
index,
|
|
2997
|
+
slideBodyText,
|
|
2998
|
+
slideTitle,
|
|
2999
|
+
notesText,
|
|
3000
|
+
text
|
|
3001
|
+
};
|
|
3002
|
+
}).filter((slide) => Boolean(slide.text));
|
|
3003
|
+
};
|
|
3004
|
+
var presentationText = (entries) => normalizeWhitespace2(presentationSlides(entries).map((slide) => slide.text).join(`
|
|
3005
|
+
|
|
3006
|
+
`));
|
|
3007
|
+
var presentationSlideCount = (entries) => entries.filter((entry) => entry.path.startsWith("ppt/slides/") && entry.path.endsWith(".xml")).length;
|
|
3008
|
+
|
|
3009
|
+
// src/office/spreadsheet.ts
|
|
3010
|
+
var spreadsheetSharedStrings = (entries) => entries.filter((entry) => entry.path === "xl/sharedStrings.xml").flatMap((entry) => [...decodeUtf8(entry.data).matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map((match) => decodeHtmlEntities(match[1] ?? "")));
|
|
3011
|
+
var spreadsheetColumnLabel = (reference) => {
|
|
3012
|
+
const match = reference?.match(/([A-Z]+)/i);
|
|
3013
|
+
return match?.[1]?.toUpperCase() ?? "";
|
|
3014
|
+
};
|
|
3015
|
+
var spreadsheetColumnIndex = (label) => {
|
|
3016
|
+
if (typeof label !== "string" || label.length === 0) {
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
let index = 0;
|
|
3020
|
+
for (const character of label.toUpperCase()) {
|
|
3021
|
+
const code = character.charCodeAt(0);
|
|
3022
|
+
if (code < 65 || code > 90) {
|
|
3023
|
+
return;
|
|
3024
|
+
}
|
|
3025
|
+
index = index * 26 + (code - 64);
|
|
3026
|
+
}
|
|
3027
|
+
return index > 0 ? index : undefined;
|
|
3028
|
+
};
|
|
3029
|
+
var spreadsheetColumnLabelFromIndex = (index) => {
|
|
3030
|
+
if (typeof index !== "number" || !Number.isFinite(index) || index < 1) {
|
|
3031
|
+
return;
|
|
3032
|
+
}
|
|
3033
|
+
let remaining = Math.floor(index);
|
|
3034
|
+
let label = "";
|
|
3035
|
+
while (remaining > 0) {
|
|
3036
|
+
const offset = (remaining - 1) % 26;
|
|
3037
|
+
label = String.fromCharCode(65 + offset) + label;
|
|
3038
|
+
remaining = Math.floor((remaining - 1) / 26);
|
|
3039
|
+
}
|
|
3040
|
+
return label || undefined;
|
|
3041
|
+
};
|
|
3042
|
+
var spreadsheetColumnRange = (rows) => {
|
|
3043
|
+
let spreadsheetColumnStart;
|
|
3044
|
+
let spreadsheetColumnEnd;
|
|
3045
|
+
let startIndex;
|
|
3046
|
+
let endIndex;
|
|
3047
|
+
for (const row of rows) {
|
|
3048
|
+
for (const cell of row) {
|
|
3049
|
+
const columnIndex = spreadsheetColumnIndex(cell.column);
|
|
3050
|
+
if (typeof columnIndex !== "number" || !Number.isFinite(columnIndex)) {
|
|
3051
|
+
continue;
|
|
3052
|
+
}
|
|
3053
|
+
if (typeof startIndex !== "number" || columnIndex < startIndex) {
|
|
3054
|
+
startIndex = columnIndex;
|
|
3055
|
+
spreadsheetColumnStart = cell.column;
|
|
3056
|
+
}
|
|
3057
|
+
if (typeof endIndex !== "number" || columnIndex > endIndex) {
|
|
3058
|
+
endIndex = columnIndex;
|
|
3059
|
+
spreadsheetColumnEnd = cell.column;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
return {
|
|
3064
|
+
spreadsheetColumnEnd,
|
|
3065
|
+
spreadsheetColumnStart
|
|
3066
|
+
};
|
|
3067
|
+
};
|
|
3068
|
+
var sortSpreadsheetCellsByColumn = (cells) => [...cells].sort((left, right) => {
|
|
3069
|
+
const leftIndex = spreadsheetColumnIndex(left.column);
|
|
3070
|
+
const rightIndex = spreadsheetColumnIndex(right.column);
|
|
3071
|
+
if (typeof leftIndex === "number" && Number.isFinite(leftIndex) && typeof rightIndex === "number" && Number.isFinite(rightIndex) && leftIndex !== rightIndex) {
|
|
3072
|
+
return leftIndex - rightIndex;
|
|
3073
|
+
}
|
|
3074
|
+
return (left.reference ?? left.column).localeCompare(right.reference ?? right.column);
|
|
3075
|
+
});
|
|
3076
|
+
var spreadsheetResolveCellValue = (cellXml, sharedStrings) => {
|
|
3077
|
+
const inlineMatch = cellXml.match(/<is\b[^>]*>[\s\S]*?<t[^>]*>([\s\S]*?)<\/t>[\s\S]*?<\/is>/i);
|
|
3078
|
+
if (inlineMatch?.[1]) {
|
|
3079
|
+
return normalizeWhitespace2(decodeHtmlEntities(inlineMatch[1]));
|
|
3080
|
+
}
|
|
3081
|
+
const valueMatch = cellXml.match(/<v>([\s\S]*?)<\/v>/i);
|
|
3082
|
+
if (!valueMatch?.[1]) {
|
|
3083
|
+
return "";
|
|
3084
|
+
}
|
|
3085
|
+
const rawValue = decodeHtmlEntities(valueMatch[1]);
|
|
3086
|
+
const typeMatch = cellXml.match(/\bt="([^"]+)"/i);
|
|
3087
|
+
if (typeMatch?.[1] === "s") {
|
|
3088
|
+
const index = Number(rawValue);
|
|
3089
|
+
return Number.isInteger(index) && sharedStrings[index] ? sharedStrings[index] : rawValue;
|
|
3090
|
+
}
|
|
3091
|
+
return normalizeWhitespace2(rawValue);
|
|
3092
|
+
};
|
|
3093
|
+
var spreadsheetWorksheetRows = (worksheetXml, sharedStrings) => [...worksheetXml.matchAll(/<row\b([^>]*)>([\s\S]*?)<\/row>/gi)].map((rowMatch) => {
|
|
3094
|
+
const rowAttributes = rowMatch[1] ?? "";
|
|
3095
|
+
const rowXml = rowMatch[2] ?? "";
|
|
3096
|
+
const cells = sortSpreadsheetCellsByColumn([...rowXml.matchAll(/<c\b([^>]*)>([\s\S]*?)<\/c>/gi)].map((cellMatch) => {
|
|
3097
|
+
const attributes = cellMatch[1] ?? "";
|
|
3098
|
+
const cellBody = cellMatch[2] ?? "";
|
|
3099
|
+
const referenceMatch = attributes.match(/\br="([^"]+)"/i);
|
|
3100
|
+
const reference = referenceMatch?.[1];
|
|
3101
|
+
const value = spreadsheetResolveCellValue(`<c${attributes}>${cellBody}</c>`, sharedStrings);
|
|
3102
|
+
return {
|
|
3103
|
+
column: spreadsheetColumnLabel(reference),
|
|
3104
|
+
reference,
|
|
3105
|
+
value
|
|
3106
|
+
};
|
|
3107
|
+
}).filter((cell) => cell.value));
|
|
3108
|
+
const explicitRowNumber = Number.parseInt(rowAttributes.match(/\br="(\d+)"/i)?.[1] ?? "", 10);
|
|
3109
|
+
const fallbackRowNumber = Number.parseInt(cells[0]?.reference?.match(/\d+/)?.[0] ?? "", 10);
|
|
3110
|
+
return {
|
|
3111
|
+
cells,
|
|
3112
|
+
rowNumber: Number.isInteger(explicitRowNumber) ? explicitRowNumber : Number.isInteger(fallbackRowNumber) ? fallbackRowNumber : 0
|
|
3113
|
+
};
|
|
3114
|
+
}).filter((row) => row.cells.length > 0).map((row, index) => ({
|
|
3115
|
+
...row,
|
|
3116
|
+
rowNumber: row.rowNumber > 0 ? row.rowNumber : index + 1
|
|
3117
|
+
}));
|
|
3118
|
+
var spreadsheetRowText = (row, headers, headerColumns) => {
|
|
3119
|
+
const entries = row.map((cell, index) => {
|
|
3120
|
+
const exactHeaderIndex = Array.isArray(headerColumns) ? headerColumns.findIndex((column) => column === cell.column) : -1;
|
|
3121
|
+
const headerIndex = exactHeaderIndex >= 0 ? exactHeaderIndex : index;
|
|
3122
|
+
const header = headers[headerIndex];
|
|
3123
|
+
if (header) {
|
|
3124
|
+
return `${header}: ${cell.value}`;
|
|
3125
|
+
}
|
|
3126
|
+
return cell.column ? `${cell.column}: ${cell.value}` : cell.value;
|
|
3127
|
+
});
|
|
3128
|
+
return normalizeWhitespace2(entries.join(" | "));
|
|
3129
|
+
};
|
|
3130
|
+
var normalizeSpreadsheetHeaderValue = (value) => normalizeWhitespace2(value).toLowerCase();
|
|
3131
|
+
var isSpreadsheetHeaderRow = (row, headers) => row.length === headers.length && row.every((cell, index) => normalizeSpreadsheetHeaderValue(cell.value) === normalizeSpreadsheetHeaderValue(headers[index] ?? ""));
|
|
3132
|
+
var isSpreadsheetHeaderLikeRow = (row) => row.length > 0 && row.every((cell) => {
|
|
3133
|
+
const normalized = normalizeSpreadsheetHeaderValue(cell.value);
|
|
3134
|
+
return normalized.length > 0 && /[a-z]/i.test(normalized) && !/^\d+(?:\.\d+)?$/.test(normalized);
|
|
3135
|
+
});
|
|
3136
|
+
var isSpreadsheetWeakHeaderRestartRow = (row, headers) => {
|
|
3137
|
+
if (row.length === 0 || row.length !== headers.length) {
|
|
3138
|
+
return false;
|
|
3139
|
+
}
|
|
3140
|
+
const normalizedRow = row.map((cell) => normalizeSpreadsheetHeaderValue(cell.value));
|
|
3141
|
+
const normalizedHeaders = headers.map((value) => normalizeSpreadsheetHeaderValue(value));
|
|
3142
|
+
if (normalizedRow.every((value, index) => value === (normalizedHeaders[index] ?? ""))) {
|
|
3143
|
+
return false;
|
|
3144
|
+
}
|
|
3145
|
+
const overlappingHeaderCount = normalizedRow.filter((value, index) => {
|
|
3146
|
+
const currentHeader = normalizedHeaders[index] ?? "";
|
|
3147
|
+
return value.length > 0 && value === currentHeader;
|
|
3148
|
+
}).length;
|
|
3149
|
+
const alphaishCellCount = normalizedRow.filter((value) => value.length > 0 && /[a-z]/i.test(value)).length;
|
|
3150
|
+
return overlappingHeaderCount > 0 && alphaishCellCount > 0 && overlappingHeaderCount + alphaishCellCount >= Math.max(1, Math.ceil(row.length / 2));
|
|
3151
|
+
};
|
|
3152
|
+
var isSpreadsheetSparseHeaderRestartRow = (row, headers, headerColumns) => {
|
|
3153
|
+
if (row.length === 0 || row.length >= headers.length || headerColumns.length !== headers.length) {
|
|
3154
|
+
return false;
|
|
3155
|
+
}
|
|
3156
|
+
const headerColumnSet = new Set(headerColumns);
|
|
3157
|
+
if (!row.every((cell) => headerColumnSet.has(cell.column))) {
|
|
3158
|
+
return false;
|
|
3159
|
+
}
|
|
3160
|
+
return row.every((cell) => {
|
|
3161
|
+
const normalized = normalizeSpreadsheetHeaderValue(cell.value);
|
|
3162
|
+
return normalized.length > 0 && /[a-z]/i.test(normalized) && !/^\d+(?:\.\d+)?$/.test(normalized);
|
|
3163
|
+
});
|
|
3164
|
+
};
|
|
3165
|
+
var isSpreadsheetSparseShiftedHeaderRestartRow = (row, headers) => {
|
|
3166
|
+
if (row.length === 0 || row.length >= headers.length) {
|
|
3167
|
+
return false;
|
|
3168
|
+
}
|
|
3169
|
+
return row.every((cell) => {
|
|
3170
|
+
const normalized = normalizeSpreadsheetHeaderValue(cell.value);
|
|
3171
|
+
return normalized.length > 0 && /[a-z]/i.test(normalized) && !/^\d+(?:\.\d+)?$/.test(normalized);
|
|
3172
|
+
});
|
|
3173
|
+
};
|
|
3174
|
+
var buildSpreadsheetShiftedHeaderColumns = (row, headerWidth) => {
|
|
3175
|
+
const startIndex = spreadsheetColumnIndex(row[0]?.column);
|
|
3176
|
+
if (typeof startIndex !== "number" || !Number.isFinite(startIndex) || headerWidth < 1) {
|
|
3177
|
+
return row.map((cell) => cell.column);
|
|
3178
|
+
}
|
|
3179
|
+
return Array.from({ length: headerWidth }, (_, index) => spreadsheetColumnLabelFromIndex(startIndex + index)).filter((value) => typeof value === "string");
|
|
3180
|
+
};
|
|
3181
|
+
var mergeSpreadsheetRestartHeaders = (row, previousHeaders, previousHeaderColumns) => previousHeaderColumns.map((column, index) => {
|
|
3182
|
+
const currentCell = row.find((cell) => cell.column === column);
|
|
3183
|
+
const normalized = normalizeSpreadsheetHeaderValue(currentCell?.value ?? "");
|
|
3184
|
+
if (normalized.length > 0) {
|
|
3185
|
+
return currentCell.value;
|
|
3186
|
+
}
|
|
3187
|
+
return previousHeaders[index] ?? currentCell?.value ?? "";
|
|
3188
|
+
});
|
|
3189
|
+
var spreadsheetSheetTexts = (entries) => {
|
|
3190
|
+
const sharedStrings = spreadsheetSharedStrings(entries);
|
|
3191
|
+
const sheetNames = spreadsheetSheetNames(entries);
|
|
3192
|
+
const sheetEntries = entries.filter((entry) => entry.path.startsWith("xl/worksheets/") && entry.path.endsWith(".xml")).sort((left, right) => left.path.localeCompare(right.path));
|
|
3193
|
+
const sheets = sheetEntries.map((entry, index) => {
|
|
3194
|
+
const rows = spreadsheetWorksheetRows(decodeUtf8(entry.data), sharedStrings);
|
|
3195
|
+
if (rows.length === 0) {
|
|
3196
|
+
return null;
|
|
3197
|
+
}
|
|
3198
|
+
const headers = rows[0].cells.map((cell) => cell.value);
|
|
3199
|
+
const { spreadsheetColumnEnd, spreadsheetColumnStart } = spreadsheetColumnRange(rows.map((row) => row.cells));
|
|
3200
|
+
const repeatedHeaderRowNumbers = [];
|
|
3201
|
+
const sheetTableHeaders = [];
|
|
3202
|
+
let tableCount = 1;
|
|
3203
|
+
const tableRows = [];
|
|
3204
|
+
let currentTableRows;
|
|
3205
|
+
let currentTableIndex = 1;
|
|
3206
|
+
let currentTableHeaders = headers;
|
|
3207
|
+
let currentTableHeaderColumns = rows[0].cells.map((cell) => cell.column);
|
|
3208
|
+
let currentTableColumnStart = spreadsheetColumnRange([
|
|
3209
|
+
rows[0].cells
|
|
3210
|
+
]).spreadsheetColumnStart;
|
|
3211
|
+
let currentTableColumnEnd = spreadsheetColumnRange([
|
|
3212
|
+
rows[0].cells
|
|
3213
|
+
]).spreadsheetColumnEnd;
|
|
3214
|
+
const rowTexts = rows.map((rowEntry, rowIndex) => {
|
|
3215
|
+
const row = rowEntry.cells;
|
|
3216
|
+
const rowNumber = rowEntry.rowNumber;
|
|
3217
|
+
const rowColumnRange = spreadsheetColumnRange([row]);
|
|
3218
|
+
const previousRowNumber = rows[rowIndex - 1]?.rowNumber;
|
|
3219
|
+
const hasBlankRowGap = typeof previousRowNumber === "number" && rowNumber > previousRowNumber + 1;
|
|
3220
|
+
const isShiftedHeaderRow = rowIndex > 0 && row.length === currentTableHeaders.length && isSpreadsheetHeaderLikeRow(row) && (rowColumnRange.spreadsheetColumnStart !== currentTableColumnStart || rowColumnRange.spreadsheetColumnEnd !== currentTableColumnEnd);
|
|
3221
|
+
const isBlankGapShiftedTableRestart = rowIndex > 0 && hasBlankRowGap && (rowColumnRange.spreadsheetColumnStart !== currentTableColumnStart || rowColumnRange.spreadsheetColumnEnd !== currentTableColumnEnd);
|
|
3222
|
+
const isBlankGapHeaderRestart = rowIndex > 0 && hasBlankRowGap && rowColumnRange.spreadsheetColumnStart === currentTableColumnStart && rowColumnRange.spreadsheetColumnEnd === currentTableColumnEnd && (isSpreadsheetHeaderLikeRow(row) && !isSpreadsheetHeaderRow(row, currentTableHeaders) || isSpreadsheetWeakHeaderRestartRow(row, currentTableHeaders));
|
|
3223
|
+
const isBlankGapSparseHeaderRestart = rowIndex > 0 && hasBlankRowGap && isSpreadsheetSparseHeaderRestartRow(row, currentTableHeaders, currentTableHeaderColumns);
|
|
3224
|
+
const isShiftedSparseHeaderRestart = rowIndex > 0 && hasBlankRowGap && (rowColumnRange.spreadsheetColumnStart !== currentTableColumnStart || rowColumnRange.spreadsheetColumnEnd !== currentTableColumnEnd) && isSpreadsheetSparseShiftedHeaderRestartRow(row, currentTableHeaders);
|
|
3225
|
+
const isAnySparseHeaderRestart = isBlankGapSparseHeaderRestart || isShiftedSparseHeaderRestart;
|
|
3226
|
+
const isHeaderRow = rowIndex === 0 || isSpreadsheetHeaderRow(row, currentTableHeaders) || isShiftedHeaderRow || isBlankGapShiftedTableRestart || isBlankGapHeaderRestart || isAnySparseHeaderRestart;
|
|
3227
|
+
if (rowIndex > 0 && isHeaderRow) {
|
|
3228
|
+
repeatedHeaderRowNumbers.push(rowNumber);
|
|
3229
|
+
tableCount += 1;
|
|
3230
|
+
if (currentTableRows && currentTableRows.length > 0) {
|
|
3231
|
+
tableRows.push({
|
|
3232
|
+
rows: currentTableRows,
|
|
3233
|
+
tableIndex: currentTableIndex
|
|
3234
|
+
});
|
|
3235
|
+
sheetTableHeaders.push({
|
|
3236
|
+
spreadsheetHeaders: currentTableHeaders,
|
|
3237
|
+
tableIndex: currentTableIndex
|
|
3238
|
+
});
|
|
3239
|
+
}
|
|
3240
|
+
currentTableIndex = tableCount;
|
|
3241
|
+
const nextTableHeaderColumns = isShiftedSparseHeaderRestart ? buildSpreadsheetShiftedHeaderColumns(row, currentTableHeaderColumns.length) : isBlankGapSparseHeaderRestart ? currentTableHeaderColumns : row.map((cell) => cell.column);
|
|
3242
|
+
currentTableHeaders = isAnySparseHeaderRestart ? mergeSpreadsheetRestartHeaders(row, currentTableHeaders, nextTableHeaderColumns) : row.map((cell) => cell.value);
|
|
3243
|
+
currentTableHeaderColumns = nextTableHeaderColumns;
|
|
3244
|
+
currentTableColumnStart = isShiftedSparseHeaderRestart ? nextTableHeaderColumns[0] : isBlankGapSparseHeaderRestart ? currentTableColumnStart : rowColumnRange.spreadsheetColumnStart;
|
|
3245
|
+
currentTableColumnEnd = isShiftedSparseHeaderRestart ? nextTableHeaderColumns.at(-1) : isBlankGapSparseHeaderRestart ? currentTableColumnEnd : rowColumnRange.spreadsheetColumnEnd;
|
|
3246
|
+
currentTableRows = [row];
|
|
3247
|
+
} else {
|
|
3248
|
+
currentTableRows = [...currentTableRows ?? [], row];
|
|
3249
|
+
}
|
|
3250
|
+
return normalizeWhitespace2(`Row ${rowNumber}. ${spreadsheetRowText(row, isHeaderRow ? [] : currentTableHeaders, isHeaderRow ? [] : currentTableHeaderColumns)}`);
|
|
3251
|
+
});
|
|
3252
|
+
if (currentTableRows && currentTableRows.length > 0) {
|
|
3253
|
+
tableRows.push({
|
|
3254
|
+
rows: currentTableRows,
|
|
3255
|
+
tableIndex: currentTableIndex
|
|
3256
|
+
});
|
|
3257
|
+
sheetTableHeaders.push({
|
|
3258
|
+
spreadsheetHeaders: currentTableHeaders,
|
|
3259
|
+
tableIndex: currentTableIndex
|
|
3260
|
+
});
|
|
3261
|
+
}
|
|
3262
|
+
const sheetTableColumnRanges = tableRows.map(({ rows, tableIndex }) => ({
|
|
3263
|
+
tableIndex,
|
|
3264
|
+
...spreadsheetColumnRange(rows)
|
|
3265
|
+
}));
|
|
3266
|
+
const text = normalizeWhitespace2(rowTexts.join(`
|
|
3267
|
+
`));
|
|
3268
|
+
if (!text) {
|
|
3269
|
+
return null;
|
|
3270
|
+
}
|
|
3271
|
+
return {
|
|
3272
|
+
headers,
|
|
3273
|
+
name: sheetNames[index] ?? `Sheet ${index + 1}`,
|
|
3274
|
+
repeatedHeaderRowNumbers,
|
|
3275
|
+
rowCount: rowTexts.length,
|
|
3276
|
+
sheetTableHeaders,
|
|
3277
|
+
sheetTableColumnRanges,
|
|
3278
|
+
spreadsheetColumnEnd,
|
|
3279
|
+
spreadsheetColumnStart,
|
|
3280
|
+
tableCount,
|
|
3281
|
+
text
|
|
3282
|
+
};
|
|
3283
|
+
});
|
|
3284
|
+
return sheets.filter((entry) => entry !== null);
|
|
3285
|
+
};
|
|
3286
|
+
var spreadsheetText = (entries) => normalizeWhitespace2(spreadsheetSheetTexts(entries).map((sheet) => `Sheet ${sheet.name}
|
|
3287
|
+
${sheet.text}`).join(`
|
|
3288
|
+
|
|
3289
|
+
`));
|
|
3290
|
+
var spreadsheetSheetNames = (entries) => entries.filter((entry) => entry.path === "xl/workbook.xml").flatMap((entry) => [...decodeUtf8(entry.data).matchAll(/<sheet[^>]*name="([^"]+)"/g)].map((match) => match[1] ?? "")).filter(Boolean);
|
|
3291
|
+
|
|
3292
|
+
// src/extractors/office.ts
|
|
3293
|
+
var createOfficeDocumentExtractor2 = () => ({
|
|
3294
|
+
name: "absolute_office_document",
|
|
3295
|
+
supports: officeExtractorSupports,
|
|
3296
|
+
extract: (input) => {
|
|
3297
|
+
const extension = officeExtension(input);
|
|
3298
|
+
const entries = unzipEntries(input.data);
|
|
3299
|
+
let text = "";
|
|
3300
|
+
let officeMetadata = {};
|
|
3301
|
+
let structuredDocuments = [];
|
|
3302
|
+
if (extension === ".docx" || extension === ".odt") {
|
|
3303
|
+
const officeBlocks = officeDocumentBlocks(entries);
|
|
3304
|
+
text = officeDocumentText(entries);
|
|
3305
|
+
officeMetadata = {
|
|
3306
|
+
officeBlocks,
|
|
3307
|
+
sectionCount: officeDocumentSectionCount(entries)
|
|
3308
|
+
};
|
|
3309
|
+
} else if (extension === ".xlsx" || extension === ".ods") {
|
|
3310
|
+
text = spreadsheetText(entries);
|
|
3311
|
+
const sheets = spreadsheetSheetTexts(entries);
|
|
3312
|
+
const workbookLabel = input.title ?? input.name ?? input.path ?? input.source ?? DEFAULT_BINARY_NAME;
|
|
3313
|
+
officeMetadata = {
|
|
3314
|
+
sheetNames: spreadsheetSheetNames(entries)
|
|
3315
|
+
};
|
|
3316
|
+
structuredDocuments = sheets.map((sheet, index) => ({
|
|
3317
|
+
contentType: input.contentType,
|
|
3318
|
+
format: "text",
|
|
3319
|
+
metadata: {
|
|
3320
|
+
...input.metadata ?? {},
|
|
3321
|
+
fileKind: "office",
|
|
3322
|
+
...officeMetadata,
|
|
3323
|
+
repeatedHeaderRowNumbers: sheet.repeatedHeaderRowNumbers,
|
|
3324
|
+
sheetColumnEnd: sheet.spreadsheetColumnEnd,
|
|
3325
|
+
sheetColumnStart: sheet.spreadsheetColumnStart,
|
|
3326
|
+
sheetHeaders: sheet.headers,
|
|
3327
|
+
sheetTableHeaders: sheet.sheetTableHeaders,
|
|
3328
|
+
sheetTableColumnRanges: sheet.sheetTableColumnRanges,
|
|
3329
|
+
sourceNativeKind: "spreadsheet_sheet",
|
|
3330
|
+
sheetIndex: index,
|
|
3331
|
+
sheetName: sheet.name,
|
|
3332
|
+
sheetRowCount: sheet.rowCount,
|
|
3333
|
+
sheetTableCount: sheet.tableCount
|
|
3334
|
+
},
|
|
3335
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}${extension || ".office"}`,
|
|
3336
|
+
text: normalizeWhitespace2(`Spreadsheet workbook ${workbookLabel}. ` + `Worksheet ${index + 1}. ` + `Workbook sheet named ${sheet.name}. ` + `Sheet ${sheet.name} from spreadsheet workbook ${workbookLabel}.` + `
|
|
3337
|
+
${sheet.text}`),
|
|
3338
|
+
title: input.title ? `${input.title} \xB7 Sheet ${sheet.name}` : `Sheet ${sheet.name}`
|
|
3339
|
+
}));
|
|
3340
|
+
} else if (extension === ".pptx" || extension === ".odp") {
|
|
3341
|
+
text = presentationText(entries);
|
|
3342
|
+
const slides = presentationSlides(entries);
|
|
3343
|
+
officeMetadata = {
|
|
3344
|
+
slideCount: presentationSlideCount(entries)
|
|
3345
|
+
};
|
|
3346
|
+
structuredDocuments = slides.map((slide) => ({
|
|
3347
|
+
contentType: input.contentType,
|
|
3348
|
+
format: "text",
|
|
3349
|
+
metadata: {
|
|
3350
|
+
...input.metadata ?? {},
|
|
3351
|
+
fileKind: "office",
|
|
3352
|
+
...officeMetadata,
|
|
3353
|
+
...slide.slideBodyText ? { slideBodyText: slide.slideBodyText } : {},
|
|
3354
|
+
...slide.notesText ? { slideNotesText: slide.notesText } : {},
|
|
3355
|
+
...slide.slideTitle ? { slideTitle: slide.slideTitle } : {},
|
|
3356
|
+
sourceNativeKind: "presentation_slide",
|
|
3357
|
+
slideIndex: slide.index,
|
|
3358
|
+
slideNumber: slide.index + 1
|
|
3359
|
+
},
|
|
3360
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}${extension || ".office"}`,
|
|
3361
|
+
text: normalizeWhitespace2(`Presentation slide ${slide.index + 1} from ${input.title ?? input.name ?? input.path ?? DEFAULT_BINARY_NAME}.
|
|
3362
|
+
${slide.text}`),
|
|
3363
|
+
title: input.title ? `${input.title} \xB7 Slide ${slide.index + 1}` : `Slide ${slide.index + 1}`
|
|
3364
|
+
}));
|
|
3365
|
+
}
|
|
3366
|
+
if (!text) {
|
|
3367
|
+
throw new Error(`AbsoluteJS could not extract readable text from ${inferNameFromInput(input)}`);
|
|
3368
|
+
}
|
|
3369
|
+
const summaryDocument = {
|
|
3370
|
+
contentType: input.contentType,
|
|
3371
|
+
format: "text",
|
|
3372
|
+
metadata: {
|
|
3373
|
+
...input.metadata ?? {},
|
|
3374
|
+
fileKind: "office",
|
|
3375
|
+
...officeMetadata
|
|
3376
|
+
},
|
|
3377
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}${extension || ".office"}`,
|
|
3378
|
+
text,
|
|
3379
|
+
title: input.title
|
|
3380
|
+
};
|
|
3381
|
+
return [summaryDocument, ...structuredDocuments];
|
|
3382
|
+
}
|
|
3383
|
+
});
|
|
3384
|
+
|
|
3385
|
+
// src/extractors/pdf.ts
|
|
3386
|
+
var createPDFFileExtractor2 = () => ({
|
|
3387
|
+
name: "absolute_pdf",
|
|
3388
|
+
supports: pdfExtractorSupports,
|
|
3389
|
+
extract: async (input) => {
|
|
3390
|
+
const extracted = await extractNativePDFText(input.data);
|
|
3391
|
+
if (!extracted.text) {
|
|
3392
|
+
throw new Error("AbsoluteJS could not extract readable text from this PDF. Supply a custom extractor for scanned or image-only PDFs.");
|
|
3393
|
+
}
|
|
3394
|
+
return {
|
|
3395
|
+
contentType: input.contentType ?? "application/pdf",
|
|
3396
|
+
format: "text",
|
|
3397
|
+
metadata: {
|
|
3398
|
+
...input.metadata ?? {},
|
|
3399
|
+
fileKind: "pdf",
|
|
3400
|
+
pageCount: extracted.pageCount,
|
|
3401
|
+
pdfEvidenceMode: "native",
|
|
3402
|
+
pdfEvidenceOrigin: "native",
|
|
3403
|
+
pdfTextBlockCount: extracted.textBlockCount,
|
|
3404
|
+
pdfTextBlocks: extracted.textBlocks
|
|
3405
|
+
},
|
|
3406
|
+
source: input.source ?? input.path ?? input.name ?? `${slugify2(input.title ?? DEFAULT_BINARY_NAME)}.pdf`,
|
|
3407
|
+
text: extracted.text,
|
|
3408
|
+
title: input.title
|
|
3409
|
+
};
|
|
3410
|
+
}
|
|
3411
|
+
});
|
|
3412
|
+
|
|
3413
|
+
// src/structured.ts
|
|
3414
|
+
var validateJSONLText = (value) => {
|
|
3415
|
+
const lines = value.replace(/\r\n?/g, `
|
|
3416
|
+
`).split(`
|
|
3417
|
+
`);
|
|
3418
|
+
for (const [index, line] of lines.entries()) {
|
|
3419
|
+
const trimmed = line.trim();
|
|
3420
|
+
if (!trimmed) {
|
|
3421
|
+
continue;
|
|
3422
|
+
}
|
|
3423
|
+
try {
|
|
3424
|
+
JSON.parse(trimmed);
|
|
3425
|
+
} catch (error) {
|
|
3426
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3427
|
+
throw new Error(`AbsoluteJS detected malformed JSONL at line ${index + 1}: ${reason}`);
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
};
|
|
3431
|
+
var validateDelimitedText = (value, formatLabel, delimiter) => {
|
|
3432
|
+
const lines = value.replace(/\r\n?/g, `
|
|
3433
|
+
`).split(`
|
|
3434
|
+
`);
|
|
3435
|
+
for (const [index, line] of lines.entries()) {
|
|
3436
|
+
if (!line.trim()) {
|
|
3437
|
+
continue;
|
|
3438
|
+
}
|
|
3439
|
+
let inQuotes = false;
|
|
3440
|
+
for (let characterIndex = 0;characterIndex < line.length; characterIndex += 1) {
|
|
3441
|
+
const char = line[characterIndex];
|
|
3442
|
+
const next = characterIndex + 1 < line.length ? line[characterIndex + 1] : "";
|
|
3443
|
+
if (char === '"') {
|
|
3444
|
+
if (inQuotes && next === '"') {
|
|
3445
|
+
characterIndex += 1;
|
|
3446
|
+
continue;
|
|
3447
|
+
}
|
|
3448
|
+
inQuotes = !inQuotes;
|
|
3449
|
+
continue;
|
|
3450
|
+
}
|
|
3451
|
+
if (char === delimiter && !inQuotes) {
|
|
3452
|
+
continue;
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
if (inQuotes) {
|
|
3456
|
+
throw new Error(`AbsoluteJS detected malformed ${formatLabel} at line ${index + 1}: unclosed quoted field`);
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
};
|
|
3460
|
+
var validateXMLText = (value) => {
|
|
3461
|
+
const normalized = value.replace(/<\?xml[\s\S]*?\?>/gi, "").replace(/<!DOCTYPE[\s\S]*?>/gi, "").replace(/<!--[\s\S]*?-->/g, "");
|
|
3462
|
+
const tokenPattern = /<\/?([A-Za-z_][\w:.-]*)\b[^>]*\/?>/g;
|
|
3463
|
+
const stack = [];
|
|
3464
|
+
for (const match of normalized.matchAll(tokenPattern)) {
|
|
3465
|
+
const token = match[0] ?? "";
|
|
3466
|
+
const name = match[1] ?? "";
|
|
3467
|
+
if (!name) {
|
|
3468
|
+
continue;
|
|
3469
|
+
}
|
|
3470
|
+
const selfClosing = token.endsWith("/>") || token.startsWith("<?") || token.startsWith("<!");
|
|
3471
|
+
if (selfClosing) {
|
|
3472
|
+
continue;
|
|
3473
|
+
}
|
|
3474
|
+
if (token.startsWith("</")) {
|
|
3475
|
+
const expected = stack.pop();
|
|
3476
|
+
if (expected !== name) {
|
|
3477
|
+
throw new Error(`AbsoluteJS detected malformed XML: expected closing tag for <${expected ?? "none"}> but found </${name}>`);
|
|
3478
|
+
}
|
|
3479
|
+
continue;
|
|
3480
|
+
}
|
|
3481
|
+
stack.push(name);
|
|
3482
|
+
}
|
|
3483
|
+
if (stack.length > 0) {
|
|
3484
|
+
throw new Error(`AbsoluteJS detected malformed XML: unclosed tag <${stack[stack.length - 1]}>`);
|
|
3485
|
+
}
|
|
3486
|
+
};
|
|
3487
|
+
var validateYAMLText = (value) => {
|
|
3488
|
+
const lines = value.replace(/\r\n?/g, `
|
|
3489
|
+
`).split(`
|
|
3490
|
+
`);
|
|
3491
|
+
let seenTopLevelKey = false;
|
|
3492
|
+
for (const [index, line] of lines.entries()) {
|
|
3493
|
+
if (!line.trim() || line.trim().startsWith("#")) {
|
|
3494
|
+
continue;
|
|
3495
|
+
}
|
|
3496
|
+
if (/^\t+/.test(line)) {
|
|
3497
|
+
throw new Error(`AbsoluteJS detected malformed YAML at line ${index + 1}: tab indentation is not supported`);
|
|
3498
|
+
}
|
|
3499
|
+
if (/^\s+/.test(line) && !seenTopLevelKey) {
|
|
3500
|
+
throw new Error(`AbsoluteJS detected malformed YAML at line ${index + 1}: nested content appears before any top-level key`);
|
|
3501
|
+
}
|
|
3502
|
+
if (/^[A-Za-z0-9_.-]+:\s*(.*)?$/.test(line)) {
|
|
3503
|
+
seenTopLevelKey = true;
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
};
|
|
3507
|
+
var validateStructuredTextInput = (value, format) => {
|
|
3508
|
+
switch (format) {
|
|
3509
|
+
case "jsonl":
|
|
3510
|
+
validateJSONLText(value);
|
|
3511
|
+
return;
|
|
3512
|
+
case "csv":
|
|
3513
|
+
validateDelimitedText(value, "CSV", ",");
|
|
3514
|
+
return;
|
|
3515
|
+
case "tsv":
|
|
3516
|
+
validateDelimitedText(value, "TSV", "\t");
|
|
3517
|
+
return;
|
|
3518
|
+
case "xml":
|
|
3519
|
+
validateXMLText(value);
|
|
3520
|
+
return;
|
|
3521
|
+
case "yaml":
|
|
3522
|
+
validateYAMLText(value);
|
|
3523
|
+
return;
|
|
3524
|
+
default:
|
|
3525
|
+
return;
|
|
3526
|
+
}
|
|
3527
|
+
};
|
|
3528
|
+
|
|
3529
|
+
// src/extractors/text.ts
|
|
3530
|
+
var createTextFileExtractor2 = () => ({
|
|
3531
|
+
name: "absolute_text",
|
|
3532
|
+
supports: textExtractorSupports,
|
|
3533
|
+
extract: (input) => {
|
|
3534
|
+
const format = input.format ?? inferFormatFromContentType2(input.contentType ?? null) ?? inferFormatFromName2(input.path ?? input.source ?? input.name ?? input.title);
|
|
3535
|
+
const text = Buffer.from(input.data).toString("utf8");
|
|
3536
|
+
validateStructuredTextInput(text, format);
|
|
3537
|
+
return {
|
|
3538
|
+
contentType: input.contentType,
|
|
3539
|
+
format,
|
|
3540
|
+
metadata: input.metadata,
|
|
3541
|
+
source: input.source ?? input.path ?? input.name,
|
|
3542
|
+
text,
|
|
3543
|
+
title: input.title
|
|
3544
|
+
};
|
|
3545
|
+
}
|
|
3546
|
+
});
|
|
3547
|
+
|
|
3548
|
+
// src/registry.ts
|
|
3549
|
+
var DEFAULT_FILE_EXTRACTORS2 = [
|
|
3550
|
+
createOfficeDocumentExtractor2(),
|
|
3551
|
+
createMailboxContainerExtractor2(),
|
|
3552
|
+
createLegacyDocumentExtractor2(),
|
|
3553
|
+
createEPUBExtractor2(),
|
|
3554
|
+
createEmailExtractor2(),
|
|
3555
|
+
createArchiveFileExtractor2(createBuiltinArchiveExpander2()),
|
|
3556
|
+
createPDFFileExtractor2(),
|
|
3557
|
+
createTextFileExtractor2()
|
|
3558
|
+
];
|
|
3559
|
+
var resolveExtractorRegistry = (registry) => {
|
|
3560
|
+
if (!registry) {
|
|
3561
|
+
return {
|
|
3562
|
+
defaultOrder: "registry_first",
|
|
3563
|
+
includeDefaults: true,
|
|
3564
|
+
registrations: []
|
|
3565
|
+
};
|
|
3566
|
+
}
|
|
3567
|
+
if (Array.isArray(registry)) {
|
|
3568
|
+
return {
|
|
3569
|
+
defaultOrder: "registry_first",
|
|
3570
|
+
includeDefaults: true,
|
|
3571
|
+
registrations: registry
|
|
3572
|
+
};
|
|
3573
|
+
}
|
|
3574
|
+
return {
|
|
3575
|
+
defaultOrder: registry.defaultOrder ?? "registry_first",
|
|
3576
|
+
includeDefaults: registry.includeDefaults ?? true,
|
|
3577
|
+
registrations: registry.registrations
|
|
3578
|
+
};
|
|
3579
|
+
};
|
|
3580
|
+
var createExtractorRegistryInput = (input) => ({
|
|
3581
|
+
...input,
|
|
3582
|
+
inferredContentType: input.contentType ?? null,
|
|
3583
|
+
inferredExtension: inferExtensionFromInput(input) || null,
|
|
3584
|
+
inferredFormat: input.format ?? inferFormatFromContentType2(input.contentType ?? null) ?? inferFormatFromName2(input.path ?? input.source ?? input.name ?? input.title)
|
|
3585
|
+
});
|
|
3586
|
+
var registrationMatches = async (registration, input) => {
|
|
3587
|
+
const normalizedContentType = input.inferredContentType?.toLowerCase();
|
|
3588
|
+
const normalizedExtension = input.inferredExtension?.toLowerCase();
|
|
3589
|
+
const normalizedName = (input.path ?? input.source ?? input.name ?? input.title ?? "").toLowerCase();
|
|
3590
|
+
if (registration.contentTypes?.length && !registration.contentTypes.some((entry) => normalizedContentType === entry.toLowerCase())) {
|
|
3591
|
+
return false;
|
|
3592
|
+
}
|
|
3593
|
+
if (registration.extensions?.length && !registration.extensions.some((entry) => normalizedExtension === entry.toLowerCase())) {
|
|
3594
|
+
return false;
|
|
3595
|
+
}
|
|
3596
|
+
if (registration.formats?.length && (!input.inferredFormat || !registration.formats.includes(input.inferredFormat))) {
|
|
3597
|
+
return false;
|
|
3598
|
+
}
|
|
3599
|
+
if (registration.names?.length && !registration.names.some((entry) => normalizedName.includes(entry.toLowerCase()))) {
|
|
3600
|
+
return false;
|
|
3601
|
+
}
|
|
3602
|
+
if (registration.match) {
|
|
3603
|
+
return registration.match(input);
|
|
3604
|
+
}
|
|
3605
|
+
return true;
|
|
3606
|
+
};
|
|
3607
|
+
var dedupeResolvedExtractors = (extractors) => {
|
|
3608
|
+
const seen = new Set;
|
|
3609
|
+
const ordered = [];
|
|
3610
|
+
for (const entry of extractors) {
|
|
3611
|
+
if (seen.has(entry.extractor.name)) {
|
|
3612
|
+
continue;
|
|
3613
|
+
}
|
|
3614
|
+
seen.add(entry.extractor.name);
|
|
3615
|
+
ordered.push(entry);
|
|
3616
|
+
}
|
|
3617
|
+
return ordered;
|
|
3618
|
+
};
|
|
3619
|
+
var resolveFileExtractors = async (input, extractors, registry) => {
|
|
3620
|
+
const explicit = extractors ?? [];
|
|
3621
|
+
const resolvedRegistry = resolveExtractorRegistry(registry);
|
|
3622
|
+
const registryInput = createExtractorRegistryInput(input);
|
|
3623
|
+
const matchedRegistrations = (await Promise.all(resolvedRegistry.registrations.map(async (registration) => ({
|
|
3624
|
+
matches: await registrationMatches(registration, registryInput),
|
|
3625
|
+
priority: registration.priority ?? 0,
|
|
3626
|
+
registration
|
|
3627
|
+
})))).filter((entry) => entry.matches).sort((left, right) => right.priority - left.priority).map((entry) => ({
|
|
3628
|
+
extractor: entry.registration.extractor,
|
|
3629
|
+
registryMatchName: entry.registration.name ?? entry.registration.extractor.name
|
|
3630
|
+
}));
|
|
3631
|
+
const defaults = resolvedRegistry.includeDefaults ? DEFAULT_FILE_EXTRACTORS2.map((extractor) => ({ extractor })) : [];
|
|
3632
|
+
const explicitResolved = explicit.map((extractor) => ({ extractor }));
|
|
3633
|
+
return dedupeResolvedExtractors(resolvedRegistry.defaultOrder === "defaults_first" ? [...explicitResolved, ...defaults, ...matchedRegistrations] : [...explicitResolved, ...matchedRegistrations, ...defaults]);
|
|
3634
|
+
};
|
|
3635
|
+
var applyExtractorDefaults = (document, input, extractorName, registryMatchName) => {
|
|
3636
|
+
const {
|
|
3637
|
+
contentType: _contentType,
|
|
3638
|
+
extractor: _extractor,
|
|
3639
|
+
...extra
|
|
3640
|
+
} = document;
|
|
3641
|
+
return {
|
|
3642
|
+
...extra,
|
|
3643
|
+
format: document.format ?? input.format ?? inferFormatFromContentType2(document.contentType ?? input.contentType ?? null) ?? inferFormatFromName2(document.source ?? input.source ?? input.path ?? input.name),
|
|
3644
|
+
id: document.id,
|
|
3645
|
+
metadata: {
|
|
3646
|
+
...input.metadata ?? {},
|
|
3647
|
+
...document.metadata ?? {},
|
|
3648
|
+
contentType: document.contentType ?? input.contentType,
|
|
3649
|
+
extractor: document.extractor ?? extractorName,
|
|
3650
|
+
...registryMatchName ? { extractorRegistryMatch: registryMatchName } : {}
|
|
3651
|
+
},
|
|
3652
|
+
source: document.source ?? input.source ?? input.path ?? input.name,
|
|
3653
|
+
text: document.text,
|
|
3654
|
+
title: document.title ?? input.title
|
|
3655
|
+
};
|
|
3656
|
+
};
|
|
3657
|
+
var extractDocuments2 = async (input, extractors, registry) => {
|
|
3658
|
+
for (const resolvedExtractor of await resolveFileExtractors(input, extractors, registry)) {
|
|
3659
|
+
const { extractor, registryMatchName } = resolvedExtractor;
|
|
3660
|
+
if (!await extractor.supports(input)) {
|
|
3661
|
+
continue;
|
|
3662
|
+
}
|
|
3663
|
+
const extracted = await extractor.extract(input);
|
|
3664
|
+
const documents = Array.isArray(extracted) ? extracted : [extracted];
|
|
3665
|
+
return documents.map((document) => applyExtractorDefaults(document, input, extractor.name, registryMatchName));
|
|
3666
|
+
}
|
|
3667
|
+
throw new Error(`No document extractor matched ${inferNameFromInput(input)}. Register a custom extractor for this file type.`);
|
|
3668
|
+
};
|
|
3669
|
+
var getFirstExtractedDocument2 = (documents, label) => {
|
|
3670
|
+
const document = documents[0];
|
|
3671
|
+
if (!document) {
|
|
3672
|
+
throw new Error(`Document extractor ${label} did not return a document`);
|
|
3673
|
+
}
|
|
3674
|
+
return document;
|
|
3675
|
+
};
|
|
3676
|
+
|
|
3677
|
+
export { DEFAULT_BINARY_NAME, inferFormatFromUrl2, inferFormatFromName2, inferFormatFromContentType2, decodeUploadContent2, slugify2, documentIdentity2, normalizeWhitespace2, parseMaildirMetadata2, pdfExtractorSupports, mediaExtractorSupports, imageExtractorSupports, createBuiltinArchiveExpander2, createArchiveFileExtractor2, createEmailExtractor2, stripHtmlTags2, extractMainHtmlContent2, stripHtml2, createEPUBExtractor2, createLegacyDocumentExtractor2, createMailboxContainerExtractor2, createOfficeDocumentExtractor2, OCR_SUMMARY_CONFIDENCE_THRESHOLD, OCR_SUMMARY_MIN_STRONG_TEXT_RATIO, inferPDFBlockHeading2, extractPDFFigureLabel2, extractNativePDFText, createPDFFileExtractor2, createTextFileExtractor2, DEFAULT_FILE_EXTRACTORS2, extractDocuments2, getFirstExtractedDocument2, authoredEmailText2, reconcileLoadedEmailThreads2 };
|