officeparser 5.2.2 → 6.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1641 @@
1
+ "use strict";
2
+ /**
3
+ * RTF (Rich Text Format) Parser
4
+ *
5
+ * **RTF Format Overview:**
6
+ * RTF is a proprietary document format developed by Microsoft in 1987.
7
+ * Unlike OOXML formats (DOCX), RTF is a plain text format using control words and groups.
8
+ *
9
+ * **Basic RTF Structure:**
10
+ * ```rtf
11
+ * {\rtf1\ansi
12
+ * {\fonttbl{\f0 Arial;}{\f1 Times;}}
13
+ * {\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
14
+ * \f0\fs24 This is \b bold\b0 and \i italic\i0 text.\par
15
+ * }
16
+ * ```
17
+ *
18
+ * **RTF Elements:**
19
+ * 1. **Control Words**: Backslash followed by letters and optional parameter (e.g., `\fs24`, `\b`, `\par`)
20
+ * 2. **Control Symbols**: Backslash followed by single special char (e.g., `\'xx` for hex char, `\{`, `\}`, `\\`)
21
+ * 3. **Groups**: Content enclosed in `{...}` - creates formatting scope
22
+ * 4. **Text**: Plain text characters
23
+ *
24
+ * **Key Control Words:**
25
+ * - `\rtf1` - RTF version 1
26
+ * - `\fs24` - Font size in half-points (24 = 12pt)
27
+ * - `\b`,`\i`,`\ul`,`\strike` - Bold, italic, underline, strikethrough
28
+ * - `\par` - Paragraph break
29
+ * - `\f0` - Switch to font 0 from font table
30
+ * - `\cf1` - Text color from color table
31
+ * - `\cb2` - Background color from color table
32
+ * - `\sub`,`\super` - Subscript, superscript
33
+ *
34
+ * **Parser Architecture:**
35
+ * This module uses a two-phase approach:
36
+ * 1. **Lexical Phase** (`SimpleRtfParser`): Tokenizes RTF into groups, control words, and text
37
+ * 2. **Semantic Phase** (`parseRtf`): Traverses the token tree to build the AST
38
+ *
39
+ * @module RtfParser
40
+ * @see https://www.biblioscape.com/rtf15_spec.htm RTF 1.5 Specification
41
+ * @see https://latex2rtf.sourceforge.net/RTF-Spec-1.2.pdf RTF 1.2 Specification
42
+ */
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.parseRtf = exports.SimpleRtfParser = void 0;
45
+ const errorUtils_1 = require("../utils/errorUtils");
46
+ const ocrUtils_1 = require("../utils/ocrUtils");
47
+ /**
48
+ * Lookup table mapping RTF control words to internal formats.
49
+ * Fully typed: if a key maps to an unsupported format, TypeScript throws an error.
50
+ */
51
+ const RTF_BLIP_MAP = {
52
+ // Raster formats
53
+ pngblip: 'png',
54
+ jpegblip: 'jpeg',
55
+ gifblip: 'gif',
56
+ tiffblip: 'tiff',
57
+ dibitmap: 'bmp',
58
+ wbitmap: 'bmp',
59
+ };
60
+ /**
61
+ * Lookup table mapping internal formats to MIME types.
62
+ * Again fully typed: if a format is missing from this map, TS errors.
63
+ */
64
+ const IMAGE_MIME_MAP = {
65
+ png: 'image/png',
66
+ jpeg: 'image/jpeg',
67
+ gif: 'image/gif',
68
+ tiff: 'image/tiff',
69
+ bmp: 'image/bmp',
70
+ };
71
+ /**
72
+ * Low-level RTF tokenizer that parses RTF syntax into a tree structure.
73
+ *
74
+ * This class performs lexical analysis on RTF content, breaking it down into:
75
+ * - Groups (enclosed in braces)
76
+ * - Control words (e.g., `\fs24`, `\b`)
77
+ * - Control symbols (e.g., `\'xx`, `\{`)
78
+ * - Plain text
79
+ *
80
+ * The parser uses a byte-level approach and maintains a stack to track nested groups.
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const buffer = Buffer.from('{\\rtf1 Hello \\b world\\b0}');
85
+ * const parser = new SimpleRtfParser(buffer);
86
+ * const tree = parser.parse();
87
+ * // tree.content contains parsed RTF nodes
88
+ * ```
89
+ */
90
+ class SimpleRtfParser {
91
+ /**
92
+ * Creates a new RTF parser.
93
+ * @param buffer - The RTF file content as a Buffer
94
+ */
95
+ constructor(buffer) {
96
+ /** Current position in the buffer */
97
+ this.index = 0;
98
+ this.buffer = buffer;
99
+ this.length = buffer.length;
100
+ }
101
+ parse() {
102
+ const root = { type: 'group', content: [] };
103
+ const stack = [root];
104
+ while (this.index < this.length) {
105
+ const char = this.buffer[this.index];
106
+ const currentGroup = stack[stack.length - 1];
107
+ if (char === 0x7B) { // '{'
108
+ this.index++;
109
+ const newGroup = { type: 'group', content: [] };
110
+ currentGroup.content.push(newGroup);
111
+ stack.push(newGroup);
112
+ }
113
+ else if (char === 0x7D) { // '}'
114
+ this.index++;
115
+ if (stack.length > 1) {
116
+ stack.pop();
117
+ }
118
+ // If stack is 1 (root), we ignore extra closing braces or just stop?
119
+ // RTF should be balanced, but let's be robust.
120
+ }
121
+ else if (char === 0x5C) { // '\'
122
+ this.index++;
123
+ this.parseControl(currentGroup);
124
+ }
125
+ else if (char === 0x0D || char === 0x0A) { // CR or LF
126
+ this.index++; // Ignore newlines in RTF source
127
+ }
128
+ else {
129
+ this.parseText(currentGroup);
130
+ }
131
+ }
132
+ return root;
133
+ }
134
+ parseControl(group) {
135
+ if (this.index >= this.length)
136
+ return;
137
+ const char = this.buffer[this.index];
138
+ // Special control symbols
139
+ if (char === 0x7B || char === 0x7D || char === 0x5C) { // \{ \} \\
140
+ group.content.push({ type: 'text', value: String.fromCharCode(char) });
141
+ this.index++;
142
+ return;
143
+ }
144
+ if (char === 0x27) { // \'xx (hex)
145
+ this.index++;
146
+ if (this.index + 1 < this.length) {
147
+ const hex = this.buffer.toString('utf8', this.index, this.index + 2);
148
+ const code = parseInt(hex, 16);
149
+ if (!isNaN(code)) {
150
+ // RTF hex escapes represent bytes in the document's code page (usually Windows-1252)
151
+ // Characters 0x80-0x9F in Windows-1252 don't map directly to Unicode
152
+ // We need to convert them properly
153
+ const windows1252ToUnicode = {
154
+ 0x80: 0x20AC,
155
+ 0x82: 0x201A,
156
+ 0x83: 0x0192,
157
+ 0x84: 0x201E,
158
+ 0x85: 0x2026,
159
+ 0x86: 0x2020,
160
+ 0x87: 0x2021,
161
+ 0x88: 0x02C6,
162
+ 0x89: 0x2030,
163
+ 0x8A: 0x0160,
164
+ 0x8B: 0x2039,
165
+ 0x8C: 0x0152,
166
+ 0x8E: 0x017D,
167
+ 0x91: 0x2018,
168
+ 0x92: 0x2019,
169
+ 0x93: 0x201C,
170
+ 0x94: 0x201D,
171
+ 0x95: 0x2022,
172
+ 0x96: 0x2013,
173
+ 0x97: 0x2014,
174
+ 0x98: 0x02DC,
175
+ 0x99: 0x2122,
176
+ 0x9A: 0x0161,
177
+ 0x9B: 0x203A,
178
+ 0x9C: 0x0153,
179
+ 0x9E: 0x017E,
180
+ 0x9F: 0x0178 // Ÿ
181
+ };
182
+ const unicodeCode = windows1252ToUnicode[code] || code;
183
+ group.content.push({ type: 'text', value: String.fromCharCode(unicodeCode) });
184
+ }
185
+ this.index += 2;
186
+ }
187
+ return;
188
+ }
189
+ if (char === 0x2A) { // \* (ignorable destination)
190
+ // We treat this as a control word named '*'
191
+ group.content.push({ type: 'control', value: '*' });
192
+ this.index++;
193
+ return;
194
+ }
195
+ // Control word
196
+ let name = '';
197
+ while (this.index < this.length) {
198
+ const c = this.buffer[this.index];
199
+ if ((c >= 0x61 && c <= 0x7A) || (c >= 0x41 && c <= 0x5A)) { // a-z or A-Z
200
+ name += String.fromCharCode(c);
201
+ this.index++;
202
+ }
203
+ else {
204
+ break;
205
+ }
206
+ }
207
+ let param = undefined;
208
+ let hasParam = false;
209
+ let paramStr = '';
210
+ // Check for parameter (digits, potentially negative)
211
+ if (this.index < this.length && this.buffer[this.index] === 0x2D) { // -
212
+ paramStr += '-';
213
+ this.index++;
214
+ }
215
+ while (this.index < this.length) {
216
+ const c = this.buffer[this.index];
217
+ if (c >= 0x30 && c <= 0x39) { // 0-9
218
+ paramStr += String.fromCharCode(c);
219
+ this.index++;
220
+ hasParam = true;
221
+ }
222
+ else {
223
+ break;
224
+ }
225
+ }
226
+ if (hasParam) {
227
+ param = parseInt(paramStr, 10);
228
+ }
229
+ // Space after control word is consumed
230
+ if (this.index < this.length && this.buffer[this.index] === 0x20) {
231
+ this.index++;
232
+ }
233
+ // Handle \binN
234
+ if (name === 'bin' && param !== undefined && param > 0) {
235
+ // Skip N bytes of binary data
236
+ this.index += param;
237
+ // \binN is not added to content as we want to ignore it
238
+ return;
239
+ }
240
+ group.content.push({ type: 'control', value: name, param });
241
+ // If this is the first control word in the group, it might be the destination
242
+ if (group.content.length === 1 && group.type === 'group') {
243
+ group.destination = name;
244
+ }
245
+ else if (group.content.length === 2 && group.content[0].type === 'control' && group.content[0].value === '*') {
246
+ // If first was *, second is destination
247
+ group.destination = name;
248
+ }
249
+ }
250
+ parseText(group) {
251
+ let text = '';
252
+ while (this.index < this.length) {
253
+ const char = this.buffer[this.index];
254
+ if (char === 0x7B || char === 0x7D || char === 0x5C || char === 0x0D || char === 0x0A) {
255
+ break;
256
+ }
257
+ // Basic ASCII text.
258
+ text += String.fromCharCode(char);
259
+ this.index++;
260
+ }
261
+ if (text.length > 0) {
262
+ group.content.push({ type: 'text', value: text });
263
+ }
264
+ }
265
+ }
266
+ exports.SimpleRtfParser = SimpleRtfParser;
267
+ /**
268
+ * Parses an RTF file and returns the AST.
269
+ *
270
+ * **RTF Format Limitations:**
271
+ * The following features are NOT supported due to RTF format constraints:
272
+ *
273
+ * 1. **Images/Attachments**: RTF `\pict` contains device-dependent metafile data
274
+ * (WMF/EMF/DIB). Extracting as portable images requires complex metafile parsing.
275
+ *
276
+ * 2. **StyleMap**: RTF uses inline formatting rather than named style definitions.
277
+ * There is no direct equivalent to DOCX's style.xml.
278
+ *
279
+ * 3. **Endnotes**: RTF uses `\footnote` for both footnotes and endnotes.
280
+ * No separate endnote support exists in the format.
281
+ *
282
+ * @param buffer The file buffer.
283
+ * @param config The parser configuration.
284
+ * @returns The parsed AST.
285
+ */
286
+ const parseRtf = async (buffer, config) => {
287
+ try {
288
+ const parser = new SimpleRtfParser(buffer);
289
+ const doc = parser.parse();
290
+ // Extract font and color tables
291
+ const fontTable = extractFontTable(doc);
292
+ const colorTable = extractColorTable(doc);
293
+ const content = [];
294
+ const notes = [];
295
+ const attachments = [];
296
+ // State for paragraph construction
297
+ let currentParagraphText = '';
298
+ let currentParagraphChildren = [];
299
+ let currentParagraphRaw = '';
300
+ // State for text run construction
301
+ let currentRunText = '';
302
+ let currentFormatting = {};
303
+ // Target for content (main body or notes)
304
+ let currentTarget = content;
305
+ // Paragraph-level state
306
+ let paragraphIndent = 0;
307
+ let paragraphAlignment = 'left';
308
+ let isListItem = false;
309
+ let listType;
310
+ let headingLevel;
311
+ let currentListId;
312
+ // Persistent list state for listtext/pntext detection
313
+ // These persist across paragraphs to allow list items without explicit \ls
314
+ let lastKnownListId;
315
+ let lastKnownListType;
316
+ let tableStack = [];
317
+ let currentFootnoteId = 0;
318
+ // Helper to get current table context
319
+ const getCurrentTable = () => tableStack.length > 0 ? tableStack[tableStack.length - 1] : undefined;
320
+ // Helper to ensure a table context exists (for top-level tables)
321
+ const ensureTableContext = () => {
322
+ if (tableStack.length === 0) {
323
+ tableStack.push({
324
+ rows: [],
325
+ currentCells: [],
326
+ currentCellContent: [],
327
+ rowIndex: 0
328
+ });
329
+ }
330
+ };
331
+ let inTable = false;
332
+ let paragraphInTable = false;
333
+ let tableId = 0;
334
+ let rowCellProps = [];
335
+ let currentCellDefinitionProps = { isMergedContinuation: false };
336
+ let cellContentIndex = 0;
337
+ // ═══════════════════════════════════════════════════════════════════
338
+ // List state tracking (Word 97+ uses \ls for list style ID)
339
+ // ═══════════════════════════════════════════════════════════════════
340
+ let listIdCounter = 0;
341
+ const listStyleIdMap = {};
342
+ // List definition state for parsing \listtable
343
+ let parsingListTable = false;
344
+ let parsingListDefinition = false;
345
+ let currentDefinedListId;
346
+ let currentDefinedListType;
347
+ const listTypeMap = {};
348
+ // List override state for parsing \listoverridetable
349
+ let parsingListOverrideTable = false;
350
+ let currentListOverrideListId;
351
+ let currentListOverrideLs;
352
+ const listOverrideMap = {}; // Maps \ls ID to \listid
353
+ // List counters for itemIndex tracking
354
+ // Map: listId -> indentation level -> count
355
+ const listCounters = {};
356
+ // ═══════════════════════════════════════════════════════════════════
357
+ // Hyperlink state (RTF uses \field{\*\fldinst HYPERLINK "url"})
358
+ // ═══════════════════════════════════════════════════════════════════
359
+ let currentLinkUrl;
360
+ // Helper to check if formatting changed
361
+ const formattingChanged = (a, b) => {
362
+ return a.bold !== b.bold ||
363
+ a.italic !== b.italic ||
364
+ a.underline !== b.underline ||
365
+ a.strikethrough !== b.strikethrough ||
366
+ a.size !== b.size ||
367
+ a.font !== b.font ||
368
+ a.color !== b.color ||
369
+ a.backgroundColor !== b.backgroundColor ||
370
+ a.subscript !== b.subscript ||
371
+ a.superscript !== b.superscript;
372
+ };
373
+ // Helper to flush current run to paragraph children
374
+ const flushRun = () => {
375
+ if (currentRunText) {
376
+ const node = {
377
+ type: 'text',
378
+ text: currentRunText,
379
+ formatting: { ...currentFormatting }
380
+ };
381
+ // Use TextMetadata.link for hyperlinks
382
+ if (currentLinkUrl) {
383
+ node.metadata = {
384
+ link: currentLinkUrl,
385
+ linkType: classifyLinkType(currentLinkUrl)
386
+ };
387
+ }
388
+ currentParagraphChildren.push(node);
389
+ currentParagraphText += currentRunText;
390
+ currentRunText = '';
391
+ }
392
+ };
393
+ let isFlushingTable = false;
394
+ // Helper to flush current paragraph
395
+ const flushParagraph = () => {
396
+ flushRun(); // Ensure last run is added
397
+ // Check if we need to end the table
398
+ // If we were in a table, but this paragraph is NOT marked as in-table,
399
+ // and we have content, then the table has ended.
400
+ const hasContent = currentParagraphText || currentParagraphChildren.length > 0;
401
+ if (inTable && !paragraphInTable && !isFlushingTable && hasContent) {
402
+ // CRITICAL: Save current paragraph content before flushing table
403
+ // because flushTable() -> flushRow() -> flushCell() -> flushParagraph()
404
+ // would otherwise process this content during the table flush
405
+ const savedParagraphText = currentParagraphText;
406
+ const savedParagraphChildren = [...currentParagraphChildren];
407
+ const savedParagraphRaw = currentParagraphRaw;
408
+ // Clear buffers so nested flushParagraph() doesn't process them
409
+ currentParagraphText = '';
410
+ currentParagraphChildren = [];
411
+ currentParagraphRaw = '';
412
+ flushTable();
413
+ // Restore the saved content for processing after the table
414
+ currentParagraphText = savedParagraphText;
415
+ currentParagraphChildren = savedParagraphChildren;
416
+ currentParagraphRaw = savedParagraphRaw;
417
+ }
418
+ if (hasContent) {
419
+ let nodeType = 'paragraph';
420
+ let metadata = undefined;
421
+ if (headingLevel !== undefined && headingLevel > 0) {
422
+ nodeType = 'heading';
423
+ metadata = { level: headingLevel };
424
+ // Reset list context when we encounter a heading
425
+ lastKnownListId = undefined;
426
+ lastKnownListType = undefined;
427
+ }
428
+ else if (isListItem) {
429
+ nodeType = 'list';
430
+ // Use lastKnownListId if currentListId is not set
431
+ // (happens when list item is detected via listtext/pntext)
432
+ const effectiveListId = currentListId || lastKnownListId;
433
+ const effectiveListType = listType || lastKnownListType || 'unordered';
434
+ // Calculate itemIndex
435
+ let itemIndex = 0;
436
+ if (effectiveListId) {
437
+ if (!listCounters[effectiveListId]) {
438
+ listCounters[effectiveListId] = {};
439
+ }
440
+ if (listCounters[effectiveListId][paragraphIndent] === undefined) {
441
+ listCounters[effectiveListId][paragraphIndent] = 0;
442
+ }
443
+ else {
444
+ listCounters[effectiveListId][paragraphIndent]++;
445
+ }
446
+ itemIndex = listCounters[effectiveListId][paragraphIndent];
447
+ }
448
+ metadata = {
449
+ listType: effectiveListType,
450
+ indentation: paragraphIndent,
451
+ listId: effectiveListId || '',
452
+ itemIndex: itemIndex,
453
+ alignment: paragraphAlignment,
454
+ };
455
+ // Save for next listtext detection
456
+ if (effectiveListId) {
457
+ lastKnownListId = effectiveListId;
458
+ }
459
+ if (effectiveListType) {
460
+ lastKnownListType = effectiveListType;
461
+ }
462
+ }
463
+ const node = {
464
+ type: nodeType,
465
+ text: currentParagraphText,
466
+ children: currentParagraphChildren,
467
+ formatting: undefined,
468
+ metadata: metadata
469
+ };
470
+ if (config.includeRawContent && currentParagraphRaw) {
471
+ node.rawContent = currentParagraphRaw;
472
+ }
473
+ // If we're building a table, add to current cell
474
+ // but ONLY if this paragraph was actually marked as in-table
475
+ if (inTable && paragraphInTable) {
476
+ ensureTableContext();
477
+ getCurrentTable().currentCellContent.push(node);
478
+ }
479
+ else {
480
+ currentTarget.push(node);
481
+ }
482
+ currentParagraphText = '';
483
+ currentParagraphChildren = [];
484
+ currentParagraphRaw = '';
485
+ // Reset paragraph-level state
486
+ paragraphIndent = 0;
487
+ isListItem = false;
488
+ listType = undefined;
489
+ headingLevel = undefined;
490
+ currentListId = undefined;
491
+ }
492
+ };
493
+ // Helper to flush current cell
494
+ const flushCell = (tableCtx) => {
495
+ flushParagraph();
496
+ const ctx = tableCtx || getCurrentTable();
497
+ if (!ctx)
498
+ return undefined;
499
+ // Always return a cell node, even if empty, to preserve table structure (grid)
500
+ const cellNode = {
501
+ type: 'cell',
502
+ text: ctx.currentCellContent.map(c => c.text).join('\n'),
503
+ children: [...ctx.currentCellContent],
504
+ metadata: {
505
+ row: ctx.rowIndex,
506
+ col: ctx.currentCells.length
507
+ }
508
+ };
509
+ ctx.currentCellContent = [];
510
+ return cellNode;
511
+ };
512
+ // Helper to flush current row - creates a row node from collected cells
513
+ const flushRow = (tableCtx) => {
514
+ const ctx = tableCtx || getCurrentTable();
515
+ if (!ctx)
516
+ return;
517
+ const cell = flushCell(ctx);
518
+ // Only add cell if it has content (prevents phantom empty cells during cleanup)
519
+ if (cell && (cell.children && cell.children.length > 0 || cell.text)) {
520
+ ctx.currentCells.push(cell);
521
+ }
522
+ if (ctx.currentCells.length > 0) {
523
+ const rowNode = {
524
+ type: 'row',
525
+ text: ctx.currentCells.map(c => c.text).filter(t => t !== '').join(config.newlineDelimiter ?? '\n'),
526
+ children: [...ctx.currentCells]
527
+ };
528
+ ctx.rows.push(rowNode);
529
+ ctx.currentCells = [];
530
+ ctx.rowIndex++;
531
+ }
532
+ };
533
+ // Helper to flush table
534
+ const flushTable = () => {
535
+ if (isFlushingTable)
536
+ return;
537
+ isFlushingTable = true;
538
+ const ctx = getCurrentTable();
539
+ if (!ctx) {
540
+ isFlushingTable = false;
541
+ return;
542
+ }
543
+ flushRow(ctx);
544
+ if (ctx.rows.length > 0) {
545
+ tableId++;
546
+ const tableNode = {
547
+ type: 'table',
548
+ text: ctx.rows.map(r => r.text).join('\n'),
549
+ children: [...ctx.rows]
550
+ };
551
+ // If we have a parent table, add this table to the parent's current cell
552
+ if (tableStack.length > 1) {
553
+ const parentCtx = tableStack[tableStack.length - 2];
554
+ parentCtx.currentCellContent.push(tableNode);
555
+ }
556
+ else {
557
+ currentTarget.push(tableNode);
558
+ }
559
+ }
560
+ // Pop the table from stack
561
+ tableStack.pop();
562
+ // If stack is empty, we are out of table mode
563
+ if (tableStack.length === 0) {
564
+ inTable = false;
565
+ paragraphInTable = false;
566
+ }
567
+ isFlushingTable = false;
568
+ };
569
+ // Extract hyperlink URL from field instruction group
570
+ // Recursively searches for HYPERLINK "url" pattern in nested groups
571
+ const extractHyperlinkUrl = (group) => {
572
+ let url;
573
+ // Helper to recursively find hyperlink URL
574
+ const findUrl = (node) => {
575
+ if (node.type === 'text') {
576
+ // Check for HYPERLINK "url" pattern
577
+ const text = node.value;
578
+ const match = text.match(/HYPERLINK\s+"([^"]+)"/i);
579
+ if (match) {
580
+ return match[1];
581
+ }
582
+ // Also check for URL after HYPERLINK on same or separate text node
583
+ const urlOnlyMatch = text.match(/"(https?:\/\/[^"]+|mailto:[^"]+|#[^"]+)"/);
584
+ if (urlOnlyMatch) {
585
+ return urlOnlyMatch[1];
586
+ }
587
+ }
588
+ else if (node.type === 'group') {
589
+ // Check if this is a fldinst group (contains field instruction)
590
+ let foundHyperlink = false;
591
+ let foundUrl;
592
+ for (const child of node.content) {
593
+ if (child.type === 'text') {
594
+ const text = child.value.toUpperCase();
595
+ if (text.includes('HYPERLINK')) {
596
+ foundHyperlink = true;
597
+ }
598
+ // Look for quoted URL
599
+ const urlMatch = child.value.match(/"([^"]+)"/);
600
+ if (urlMatch && foundHyperlink) {
601
+ foundUrl = urlMatch[1];
602
+ }
603
+ }
604
+ else if (child.type === 'group') {
605
+ const nestedUrl = findUrl(child);
606
+ if (nestedUrl) {
607
+ foundUrl = nestedUrl;
608
+ }
609
+ }
610
+ }
611
+ if (foundUrl)
612
+ return foundUrl;
613
+ }
614
+ return undefined;
615
+ };
616
+ // Search the field group for fldinst
617
+ for (const child of group.content) {
618
+ if (child.type === 'group') {
619
+ const foundUrl = findUrl(child);
620
+ if (foundUrl)
621
+ return foundUrl;
622
+ }
623
+ }
624
+ return url;
625
+ };
626
+ /**
627
+ * Determines whether a hyperlink URL is internal or external.
628
+ * Internal = bookmark references (no scheme or starts with "#").
629
+ * External = any scheme like http, https, mailto, ftp, file, etc.
630
+ */
631
+ const classifyLinkType = (url) => {
632
+ // Trim whitespace
633
+ const clean = url.trim();
634
+ // Internal pattern 1: starts with "#"
635
+ if (clean.startsWith('#')) {
636
+ return 'internal';
637
+ }
638
+ // Internal pattern 2: no scheme at all (pure bookmark)
639
+ // Detect schemes by checking "something:" prefix
640
+ if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(clean)) {
641
+ return 'internal';
642
+ }
643
+ // Everything else is external
644
+ return 'external';
645
+ };
646
+ // Helper to extract text content from a group (for list marker detection)
647
+ // Recursively collects all text content from a group
648
+ const extractTextFromGroup = (group) => {
649
+ let text = '';
650
+ const collectText = (node) => {
651
+ if (node.type === 'text') {
652
+ text += node.value;
653
+ }
654
+ else if (node.type === 'group') {
655
+ for (const child of node.content) {
656
+ collectText(child);
657
+ }
658
+ }
659
+ };
660
+ for (const child of group.content) {
661
+ collectText(child);
662
+ }
663
+ return text;
664
+ };
665
+ /**
666
+ * Extracts an image attachment from an RTF \pict group.
667
+ * Uses lookup tables for clean and safe handling of all formats.
668
+ *
669
+ * @param pictGroup The RtfGroup node that represents a \pict group.
670
+ * @returns An OfficeAttachment or undefined when unsupported or invalid.
671
+ */
672
+ const extractPictAttachment = (pictGroup) => {
673
+ /** Internal format detected from the RTF pict group */
674
+ let imageFormat;
675
+ /** Hexadecimal string extracted from the pict binary section */
676
+ let hexData = '';
677
+ // -------------------------------------------------------------
678
+ // Walk through pict group content to detect the blip type and gather hex data
679
+ // -------------------------------------------------------------
680
+ for (const child of pictGroup.content) {
681
+ // If the node is a control word, we try to resolve it from lookup map
682
+ if (child.type === 'control') {
683
+ // Lookup directly instead of if/else
684
+ const mapped = RTF_BLIP_MAP[child.value];
685
+ if (mapped) {
686
+ imageFormat = mapped;
687
+ }
688
+ }
689
+ else if (child.type === 'text') {
690
+ // Append only valid hex characters
691
+ hexData += child.value.replace(/[^0-9a-fA-F]/g, '');
692
+ }
693
+ else if (child.type === 'group') {
694
+ // Skip nested structures like picprop or blipuid
695
+ }
696
+ }
697
+ // Missing or unknown format → stop
698
+ if (!imageFormat || hexData.length === 0) {
699
+ return undefined;
700
+ }
701
+ // Map internal format to MIME
702
+ const mimeType = IMAGE_MIME_MAP[imageFormat];
703
+ if (!mimeType) {
704
+ return undefined;
705
+ }
706
+ // -------------------------------------------------------------
707
+ // Convert hex → binary and construct the attachment object
708
+ // -------------------------------------------------------------
709
+ try {
710
+ // Convert hex into a raw buffer
711
+ const buffer = Buffer.from(hexData, 'hex');
712
+ // Derive file extension directly from format
713
+ const extension = imageFormat;
714
+ // Generate a stable incremental filename
715
+ const name = `image_${attachments.length + 1}.${extension}`;
716
+ // Build and return final attachment
717
+ return {
718
+ type: 'image',
719
+ mimeType: mimeType,
720
+ data: buffer.toString('base64'),
721
+ name: name,
722
+ extension: extension
723
+ };
724
+ }
725
+ catch {
726
+ // If conversion fails, ignore this image
727
+ return undefined;
728
+ }
729
+ };
730
+ // Helper to serialize RTF control word
731
+ const serializeRtfControl = (node) => {
732
+ // Symbol control words (non-alpha)
733
+ if (!/^[a-zA-Z]/.test(node.value)) {
734
+ return `\\${node.value}`;
735
+ }
736
+ // Alpha control words
737
+ let res = `\\${node.value}`;
738
+ if (node.param !== undefined) {
739
+ res += node.param;
740
+ }
741
+ // Add space delimiter for safety
742
+ res += ' ';
743
+ return res;
744
+ };
745
+ // Helper to serialize RTF text
746
+ const serializeRtfText = (node) => {
747
+ // Escape special characters: \, {, }
748
+ return node.value.replace(/([\\{}])/g, '\\$1');
749
+ };
750
+ // Recursive function to traverse the RTF tree
751
+ const traverse = (node, formatting, depth = 0) => {
752
+ if (node.type === 'group') {
753
+ const ignoreList = [
754
+ 'fonttbl', 'colortbl', 'stylesheet', 'info', 'macpict',
755
+ 'pmmetafile', 'wmetafile', 'dibitmap', 'bitmap', 'object',
756
+ 'nextGenerator', 'header', 'footer', 'nonshppict', 'xml', 'private',
757
+ 'upnp', 'ud', 'filetbl', 'operator', 'author', 'creatim', 'revtim', 'printim', 'comment',
758
+ 'fldinst', 'listtext', 'pntext' // Ignore list marker text (handled separately)
759
+ ];
760
+ let isIgnored = false;
761
+ let isFootnote = false;
762
+ let isHyperlinkField = false;
763
+ let isPict = false;
764
+ // Add group start to raw content
765
+ // Note: We don't add ignored groups to rawContent to keep it clean
766
+ // But we might want to if we want full fidelity.
767
+ // For now, let's include everything in rawContent except truly skipped stuff?
768
+ // The user asked for "raw content which is probably the rtf group".
769
+ // If we skip 'fonttbl', it's fine as it's not part of the content.
770
+ // But 'listtext' IS part of the content structure even if we parse it separately.
771
+ // Let's stick to the plan: if ignored, we might skip it in rawContent too,
772
+ // OR we include it.
773
+ // If I include it, `currentParagraphRaw` might get huge with font tables if they were inside the paragraph (unlikely).
774
+ // Usually font tables are at document root.
775
+ // `traverse` is called on `doc`.
776
+ // `currentParagraphRaw` is reset on `flushParagraph`.
777
+ // So if we are at root level, `currentParagraphRaw` accumulates everything until the first paragraph ends.
778
+ // This might include the header/fonttbl if they are before the first \par.
779
+ // That seems correct for "raw content" of the first node?
780
+ // Actually, `fonttbl` is usually before any text.
781
+ // If we include it, the first paragraph node will contain the entire font table in its rawContent.
782
+ // That might be annoying.
783
+ // Let's ONLY add to `currentParagraphRaw` if NOT ignored.
784
+ if (node.destination) {
785
+ if (node.destination === 'footnote') {
786
+ isFootnote = true;
787
+ }
788
+ else if (node.destination === 'field') {
789
+ // Check if this is a hyperlink field
790
+ const url = extractHyperlinkUrl(node);
791
+ if (url) {
792
+ // Flush any pending text before starting the link context
793
+ // This prevents previous text from inheriting the link
794
+ flushRun();
795
+ isHyperlinkField = true;
796
+ currentLinkUrl = url;
797
+ }
798
+ }
799
+ else if (node.destination === 'listtable') {
800
+ // We want to parse list definitions
801
+ parsingListTable = true;
802
+ }
803
+ else if (parsingListTable && node.destination === 'list') {
804
+ parsingListDefinition = true;
805
+ currentDefinedListId = undefined;
806
+ currentDefinedListType = undefined;
807
+ }
808
+ else if (node.destination === 'listoverridetable') {
809
+ parsingListOverrideTable = true;
810
+ }
811
+ else if (parsingListOverrideTable && node.destination === 'listoverride') {
812
+ // Reset per override group
813
+ currentListOverrideListId = undefined;
814
+ currentListOverrideLs = undefined;
815
+ }
816
+ else if (node.destination === 'pict') {
817
+ // Handle picture extraction
818
+ if (config.extractAttachments) {
819
+ isPict = true;
820
+ }
821
+ else {
822
+ isIgnored = true;
823
+ }
824
+ }
825
+ else if (ignoreList.includes(node.destination)) {
826
+ isIgnored = true;
827
+ }
828
+ else if (node.content.length > 0 && node.content[0].type === 'control' && node.content[0].value === '*') {
829
+ // Ignorable destination, but allow certain ones for:
830
+ // - fldinst: hyperlinks
831
+ // - nesttableprops: nested tables
832
+ // - shppict: shape pictures (contain pict groups)
833
+ const allowedIgnorable = ['fldinst', 'nesttableprops'];
834
+ if (config.extractAttachments) {
835
+ allowedIgnorable.push('shppict', 'listpicture');
836
+ }
837
+ if (!allowedIgnorable.includes(node.destination || '')) {
838
+ isIgnored = true;
839
+ }
840
+ }
841
+ }
842
+ // ═══════════════════════════════════════════════════════════
843
+ // Handle listtext and pntext: These indicate the current paragraph
844
+ // is a list item. We extract list type info before ignoring content.
845
+ // ═══════════════════════════════════════════════════════════
846
+ if (node.destination === 'listtext' || node.destination === 'pntext') {
847
+ // If this is the first list item, reset the indent
848
+ if (!isListItem)
849
+ paragraphIndent = 0;
850
+ isListItem = true;
851
+ // Try to determine list type from the marker content
852
+ // Bullets (unordered): '·', '•', 'o', '§', etc.
853
+ // Numbers (ordered): '1.', '2.', 'i.', 'ii.', 'a.', 'A.', etc.
854
+ const markerText = extractTextFromGroup(node);
855
+ if (markerText) {
856
+ const trimmed = markerText.trim();
857
+ // Check for common bullet characters
858
+ const bulletChars = ['·', '•', 'o', '§', '■', '□', '●', '○', '◆', '◇', '►', '▸', '\u00b7', '\u2022', '\u25cf', '\u25cb'];
859
+ const isBullet = bulletChars.some(b => trimmed.includes(b)) ||
860
+ // Font symbol bullets often use characters from Symbol font
861
+ (trimmed.length === 1 && !/[0-9a-zA-Z]/.test(trimmed));
862
+ if (isBullet) {
863
+ listType = 'unordered';
864
+ }
865
+ else if (/^[0-9ivxlcdm]+[\.\)]/i.test(trimmed) || /^[a-z][\.\)]/i.test(trimmed)) {
866
+ // Matches: 1., 2), i., ii., a., A), etc.
867
+ listType = 'ordered';
868
+ }
869
+ // If we can't determine, leave listType as is (might be set by \ls/\levelnfc)
870
+ }
871
+ // Still mark as ignored to skip the marker text content
872
+ isIgnored = true;
873
+ }
874
+ if (isIgnored)
875
+ return;
876
+ // Append group start to raw content
877
+ currentParagraphRaw += '{';
878
+ // Handle pict group: extract image and add to content tree
879
+ if (isPict) {
880
+ const attachment = extractPictAttachment(node);
881
+ if (attachment) {
882
+ attachments.push(attachment);
883
+ // Only add image node to content if this is NOT a list definition picture
884
+ // List pictures (bullets) should not appear in content, only as attachments
885
+ if (!parsingListTable && !parsingListDefinition) {
886
+ // Also add an image node to the content tree (like DOCX)
887
+ flushParagraph();
888
+ currentTarget.push({
889
+ type: 'image',
890
+ text: '',
891
+ metadata: {
892
+ attachmentName: attachment.name || `image_${attachments.length}`
893
+ }
894
+ });
895
+ }
896
+ }
897
+ // We still traverse pict content to reconstruct raw RTF?
898
+ // No, extractPictAttachment consumes it.
899
+ // But we want it in rawContent?
900
+ // If we return here, we miss the closing '}'.
901
+ // And we miss the content in rawContent.
902
+ // Let's traverse it purely for rawContent if needed, but `extractPictAttachment` doesn't modify the tree.
903
+ // But `extractPictAttachment` does not return the raw string.
904
+ // So we should probably continue traversal but suppress text extraction?
905
+ // The original code returned here: `return; // Don't traverse pict content as text`
906
+ // So we should do the same, but we need to append the content to `currentParagraphRaw`.
907
+ // We can manually serialize the group content here.
908
+ for (const child of node.content) {
909
+ if (child.type === 'control')
910
+ currentParagraphRaw += serializeRtfControl(child);
911
+ else if (child.type === 'text')
912
+ currentParagraphRaw += serializeRtfText(child);
913
+ else if (child.type === 'group') {
914
+ // Recursive serialization for nested groups in pict (e.g. blipuid)
915
+ // We can't easily recurse `traverse` because it has side effects (text extraction).
916
+ // We need a pure serializer or just let `traverse` run but with a flag?
917
+ // Or just ignore the raw content of the image binary data?
918
+ // Image binary data can be huge.
919
+ // Maybe we shouldn't include the full hex dump in `rawContent`?
920
+ // The user said "raw content which is probably the rtf group".
921
+ // Including 5MB of hex data in the JSON AST might be bad.
922
+ // But for consistency, it is the raw content.
923
+ // Let's include it for now.
924
+ // To do this without side effects, we need a separate serialize function?
925
+ // Or just call traverse and ensure `isPict` logic prevents text extraction.
926
+ // Wait, `isPict` is true for this node.
927
+ // If we recurse, `isPict` will be false for children (unless they are also pict).
928
+ // But we want to suppress text extraction for children of pict.
929
+ // The original code did `return`.
930
+ // So we should manually serialize children here.
931
+ // Let's define a simple recursive serializer.
932
+ const serializeGroupContent = (g) => {
933
+ for (const c of g.content) {
934
+ if (c.type === 'control')
935
+ currentParagraphRaw += serializeRtfControl(c);
936
+ else if (c.type === 'text')
937
+ currentParagraphRaw += serializeRtfText(c);
938
+ else if (c.type === 'group') {
939
+ currentParagraphRaw += '{';
940
+ serializeGroupContent(c);
941
+ currentParagraphRaw += '}';
942
+ }
943
+ }
944
+ };
945
+ serializeGroupContent(node);
946
+ }
947
+ }
948
+ currentParagraphRaw += '}';
949
+ return;
950
+ }
951
+ // Handle footnote: switch target to notes
952
+ const previousTarget = currentTarget;
953
+ if (isFootnote) {
954
+ if (config.ignoreNotes) {
955
+ return; // Skip footnote content entirely
956
+ }
957
+ flushParagraph();
958
+ currentFootnoteId++;
959
+ const noteNode = {
960
+ type: 'note',
961
+ children: [],
962
+ metadata: {
963
+ noteId: currentFootnoteId.toString(),
964
+ noteType: 'footnote'
965
+ }
966
+ };
967
+ notes.push(noteNode);
968
+ currentTarget = noteNode.children;
969
+ }
970
+ // Create a new formatting context for the group
971
+ const groupFormatting = { ...formatting };
972
+ for (const child of node.content) {
973
+ // Skip fldinst groups (we already extracted the URL)
974
+ if (child.type === 'group' && child.destination === 'fldinst') {
975
+ // We still want it in rawContent!
976
+ // So we should traverse it but suppress text extraction?
977
+ // Or just serialize it?
978
+ // `fldinst` contains the URL.
979
+ // If we skip it in `traverse`, we miss it in `rawContent`.
980
+ // Let's traverse it but maybe the `fldinst` logic inside `traverse` handles it?
981
+ // The original code:
982
+ // if (child.type === 'group' && child.destination === 'fldinst') { continue; }
983
+ // This skips the child entirely.
984
+ // So we need to manually serialize it if we want it in rawContent.
985
+ currentParagraphRaw += '{';
986
+ // We need to serialize the content of fldinst
987
+ const serializeGroupContent = (g) => {
988
+ for (const c of g.content) {
989
+ if (c.type === 'control')
990
+ currentParagraphRaw += serializeRtfControl(c);
991
+ else if (c.type === 'text')
992
+ currentParagraphRaw += serializeRtfText(c);
993
+ else if (c.type === 'group') {
994
+ currentParagraphRaw += '{';
995
+ serializeGroupContent(c);
996
+ currentParagraphRaw += '}';
997
+ }
998
+ }
999
+ };
1000
+ serializeGroupContent(child);
1001
+ currentParagraphRaw += '}';
1002
+ continue;
1003
+ }
1004
+ traverse(child, groupFormatting, depth + 1);
1005
+ }
1006
+ if (node.destination === 'listtable') {
1007
+ parsingListTable = false;
1008
+ }
1009
+ else if (node.destination === 'list') {
1010
+ parsingListDefinition = false;
1011
+ if (currentDefinedListId !== undefined && currentDefinedListType !== undefined) {
1012
+ listTypeMap[currentDefinedListId] = currentDefinedListType;
1013
+ }
1014
+ }
1015
+ else if (node.destination === 'listoverridetable') {
1016
+ parsingListOverrideTable = false;
1017
+ }
1018
+ else if (parsingListOverrideTable && node.destination === 'listoverride') {
1019
+ // End of listoverride group - populate map
1020
+ if (currentListOverrideLs !== undefined && currentListOverrideListId !== undefined) {
1021
+ listOverrideMap[currentListOverrideLs] = currentListOverrideListId;
1022
+ }
1023
+ }
1024
+ if (isFootnote) {
1025
+ flushParagraph();
1026
+ currentTarget = previousTarget;
1027
+ }
1028
+ // Clear link URL after processing the field group
1029
+ if (isHyperlinkField) {
1030
+ flushRun();
1031
+ currentLinkUrl = undefined;
1032
+ }
1033
+ // Append group end to raw content
1034
+ currentParagraphRaw += '}';
1035
+ }
1036
+ else if (node.type === 'text') {
1037
+ if (parsingListTable || parsingListOverrideTable) {
1038
+ // Even if we don't extract text, we might want it in rawContent?
1039
+ // Yes, rawContent should reflect the source.
1040
+ currentParagraphRaw += serializeRtfText(node);
1041
+ return;
1042
+ }
1043
+ if (formattingChanged(currentFormatting, formatting)) {
1044
+ flushRun();
1045
+ currentFormatting = { ...formatting };
1046
+ }
1047
+ currentRunText += node.value;
1048
+ currentParagraphRaw += serializeRtfText(node);
1049
+ }
1050
+ else if (node.type === 'control') {
1051
+ // Append control to raw content
1052
+ currentParagraphRaw += serializeRtfControl(node);
1053
+ // Handle list definition control words
1054
+ if (parsingListTable) {
1055
+ if (node.value === 'listid') {
1056
+ currentDefinedListId = node.param;
1057
+ }
1058
+ else if (node.value === 'levelnfc' || node.value === 'levelnfcn') {
1059
+ // 0 = Arabic, 1 = Upper Roman, 2 = Lower Roman, 3 = Upper Alpha, 4 = Lower Alpha -> Ordered
1060
+ // 23 = Bullet, 255 = None -> Unordered
1061
+ const isOrdered = node.param !== undefined && (node.param === 0 || (node.param >= 0 && node.param <= 4));
1062
+ // Only set if not already set (or prioritize ordered if mixed?)
1063
+ // We'll assume if any level is ordered, it's ordered.
1064
+ // Or if we haven't set it yet.
1065
+ if (!currentDefinedListType || (currentDefinedListType === 'unordered' && isOrdered)) {
1066
+ currentDefinedListType = isOrdered ? 'ordered' : 'unordered';
1067
+ }
1068
+ }
1069
+ return;
1070
+ }
1071
+ // Handle list override control words
1072
+ if (parsingListOverrideTable) {
1073
+ if (node.value === 'listid') {
1074
+ currentListOverrideListId = node.param;
1075
+ }
1076
+ else if (node.value === 'ls') {
1077
+ currentListOverrideLs = node.param;
1078
+ }
1079
+ return;
1080
+ }
1081
+ // Paragraph control words
1082
+ if (node.value === 'par') {
1083
+ flushParagraph();
1084
+ currentFormatting = { ...formatting };
1085
+ }
1086
+ // Table control words
1087
+ else if (node.value === 'trowd') {
1088
+ // Table row definition - start of a new row
1089
+ // Check if we are starting a nested table
1090
+ // If we are already in a table, and we have content in the current cell,
1091
+ // then this trowd implies a nested table start.
1092
+ const ctx = getCurrentTable();
1093
+ if (inTable && ctx && ctx.currentCellContent.length > 0) {
1094
+ // Start nested table
1095
+ ensureTableContext(); // Should already exist if inTable is true
1096
+ // Push new table context
1097
+ tableStack.push({
1098
+ rows: [],
1099
+ currentCells: [],
1100
+ currentCellContent: [],
1101
+ rowIndex: 0
1102
+ });
1103
+ }
1104
+ else {
1105
+ if (!inTable) {
1106
+ inTable = true;
1107
+ ensureTableContext();
1108
+ }
1109
+ }
1110
+ // After \trowd we are inside a table row, so content should go to table cells.
1111
+ // Many RTF files don't use \intbl, relying solely on \trowd...\cell...\row structure.
1112
+ paragraphInTable = true;
1113
+ // Reset cell properties for the new row definition
1114
+ rowCellProps = [];
1115
+ currentCellDefinitionProps = { isMergedContinuation: false };
1116
+ cellContentIndex = 0;
1117
+ }
1118
+ else if (node.value === 'clvmrg') {
1119
+ // Vertical merge continuation
1120
+ currentCellDefinitionProps.isMergedContinuation = true;
1121
+ }
1122
+ else if (node.value === 'clmgf') {
1123
+ // Vertical merge first cell (reset continuation flag if set, though usually mutually exclusive)
1124
+ currentCellDefinitionProps.isMergedContinuation = false;
1125
+ }
1126
+ else if (node.value === 'cellx') {
1127
+ // End of cell definition
1128
+ rowCellProps.push({ ...currentCellDefinitionProps });
1129
+ // Reset for next cell
1130
+ currentCellDefinitionProps = { isMergedContinuation: false };
1131
+ }
1132
+ else if (node.value === 'cell') {
1133
+ // End of cell - add it to current row
1134
+ // Force paragraphInTable = true because \cell implies we are in a table cell
1135
+ paragraphInTable = true;
1136
+ // Check if this cell is a merged continuation
1137
+ let isMergedContinuation = false;
1138
+ if (cellContentIndex < rowCellProps.length) {
1139
+ isMergedContinuation = rowCellProps[cellContentIndex].isMergedContinuation;
1140
+ }
1141
+ cellContentIndex++;
1142
+ const cell = flushCell();
1143
+ // Only add if not a merged continuation
1144
+ if (cell) {
1145
+ if (!isMergedContinuation) {
1146
+ const ctx = getCurrentTable();
1147
+ if (ctx)
1148
+ ctx.currentCells.push(cell);
1149
+ }
1150
+ }
1151
+ currentFormatting = { ...formatting };
1152
+ }
1153
+ else if (node.value === 'nestcell') {
1154
+ // End of cell in outer table (nested context)
1155
+ // If we are in an inner table, we need to close it and return to outer
1156
+ // First, flush the current cell of the inner table (if any pending)
1157
+ // Actually, nestcell ends the OUTER cell.
1158
+ // So the inner table should have been finished by now?
1159
+ // Usually inner table ends with \row.
1160
+ // If we are in a nested table (stack > 1), we should pop until we are at the outer table?
1161
+ // Or maybe just pop one level?
1162
+ if (tableStack.length > 1) {
1163
+ // Flush the inner table if it has pending rows
1164
+ const innerCtx = getCurrentTable();
1165
+ if (innerCtx && (innerCtx.rows.length > 0 || innerCtx.currentCells.length > 0)) {
1166
+ flushTable(); // This pops the stack
1167
+ }
1168
+ }
1169
+ // Now we are (hopefully) at the outer table level
1170
+ // Treat as a regular cell end for the outer table
1171
+ paragraphInTable = true;
1172
+ const cell = flushCell();
1173
+ if (cell) {
1174
+ const ctx = getCurrentTable();
1175
+ if (ctx)
1176
+ ctx.currentCells.push(cell);
1177
+ }
1178
+ currentFormatting = { ...formatting };
1179
+ }
1180
+ else if (node.value === 'row') {
1181
+ // End of row
1182
+ flushRow();
1183
+ currentFormatting = { ...formatting };
1184
+ // Reset content index for safety (though trowd usually does it)
1185
+ cellContentIndex = 0;
1186
+ // Critical: Reset paragraphInTable after row ends.
1187
+ // Subsequent paragraphs must explicitly use \intbl to be part of the table.
1188
+ // Without this, content after the last \row gets incorrectly merged.
1189
+ paragraphInTable = false;
1190
+ }
1191
+ else if (node.value === 'nestrow') {
1192
+ // End of row in outer table
1193
+ // If we are still in inner table context, flush it
1194
+ if (tableStack.length > 1) {
1195
+ flushTable();
1196
+ }
1197
+ flushRow();
1198
+ currentFormatting = { ...formatting };
1199
+ cellContentIndex = 0;
1200
+ }
1201
+ else if (node.value === 'intbl') {
1202
+ // Paragraph is in a table
1203
+ inTable = true;
1204
+ paragraphInTable = true;
1205
+ ensureTableContext();
1206
+ }
1207
+ else if (node.value === 'pard') {
1208
+ // Reset paragraph properties
1209
+ paragraphInTable = false;
1210
+ // Reset other props...
1211
+ paragraphIndent = 0;
1212
+ paragraphAlignment = 'left';
1213
+ isListItem = false;
1214
+ listType = undefined;
1215
+ headingLevel = undefined;
1216
+ currentListId = undefined;
1217
+ // Reset paragraph-level background (cbpat) to prevent leaking to next paragraph
1218
+ formatting.backgroundColor = undefined;
1219
+ }
1220
+ // Text flow control
1221
+ else if (node.value === 'tab') {
1222
+ if (formattingChanged(currentFormatting, formatting)) {
1223
+ flushRun();
1224
+ currentFormatting = { ...formatting };
1225
+ }
1226
+ currentRunText += '\t';
1227
+ }
1228
+ else if (node.value === 'line') {
1229
+ if (formattingChanged(currentFormatting, formatting)) {
1230
+ flushRun();
1231
+ currentFormatting = { ...formatting };
1232
+ }
1233
+ currentRunText += '\n';
1234
+ }
1235
+ // Quote characters
1236
+ else if (node.value === 'lquote') {
1237
+ // Left single quotation mark (U+2018)
1238
+ if (formattingChanged(currentFormatting, formatting)) {
1239
+ flushRun();
1240
+ currentFormatting = { ...formatting };
1241
+ }
1242
+ currentRunText += '\u2018';
1243
+ }
1244
+ else if (node.value === 'rquote') {
1245
+ // Right single quotation mark (U+2019)
1246
+ if (formattingChanged(currentFormatting, formatting)) {
1247
+ flushRun();
1248
+ currentFormatting = { ...formatting };
1249
+ }
1250
+ currentRunText += '\u2019';
1251
+ }
1252
+ else if (node.value === 'ldblquote') {
1253
+ // Left double quotation mark (U+201C)
1254
+ if (formattingChanged(currentFormatting, formatting)) {
1255
+ flushRun();
1256
+ currentFormatting = { ...formatting };
1257
+ }
1258
+ currentRunText += '\u201C';
1259
+ }
1260
+ else if (node.value === 'rdblquote') {
1261
+ // Right double quotation mark (U+201D)
1262
+ if (formattingChanged(currentFormatting, formatting)) {
1263
+ flushRun();
1264
+ currentFormatting = { ...formatting };
1265
+ }
1266
+ currentRunText += '\u201D';
1267
+ }
1268
+ // Unicode character
1269
+ else if (node.value === 'u') {
1270
+ if (node.param !== undefined) {
1271
+ let code = node.param;
1272
+ if (code < 0)
1273
+ code += 65536;
1274
+ if (formattingChanged(currentFormatting, formatting)) {
1275
+ flushRun();
1276
+ currentFormatting = { ...formatting };
1277
+ }
1278
+ currentRunText += String.fromCharCode(code);
1279
+ }
1280
+ }
1281
+ // Character formatting
1282
+ else if (node.value === 'b') {
1283
+ formatting.bold = (node.param !== 0);
1284
+ }
1285
+ else if (node.value === 'i') {
1286
+ formatting.italic = (node.param !== 0);
1287
+ }
1288
+ else if (node.value === 'ul') {
1289
+ formatting.underline = (node.param !== 0);
1290
+ }
1291
+ else if (node.value === 'ulnone') {
1292
+ formatting.underline = false;
1293
+ }
1294
+ else if (node.value === 'strike') {
1295
+ formatting.strikethrough = (node.param !== 0);
1296
+ }
1297
+ else if (node.value === 'plain') {
1298
+ // Reset all character formatting
1299
+ formatting.bold = false;
1300
+ formatting.italic = false;
1301
+ formatting.underline = false;
1302
+ formatting.strikethrough = false;
1303
+ formatting.subscript = false;
1304
+ formatting.superscript = false;
1305
+ formatting.size = undefined;
1306
+ formatting.font = undefined;
1307
+ formatting.color = undefined;
1308
+ formatting.backgroundColor = undefined;
1309
+ }
1310
+ // Font size (\fs - in half-points)
1311
+ else if (node.value === 'fs') {
1312
+ if (node.param !== undefined) {
1313
+ formatting.size = (node.param / 2).toString() + 'pt';
1314
+ }
1315
+ }
1316
+ // Font family (\f)
1317
+ else if (node.value === 'f') {
1318
+ if (node.param !== undefined && fontTable[node.param]) {
1319
+ formatting.font = fontTable[node.param];
1320
+ }
1321
+ }
1322
+ // Text color (\cf)
1323
+ else if (node.value === 'cf') {
1324
+ if (node.param !== undefined && colorTable[node.param]) {
1325
+ formatting.color = colorTable[node.param];
1326
+ }
1327
+ }
1328
+ // Background/highlight color (\cb, \highlight, \chcbpat, \cbpat)
1329
+ // \chcbpat = character background pattern color (used for shading)
1330
+ // \cbpat = paragraph background pattern color
1331
+ else if (node.value === 'cb' || node.value === 'highlight' || node.value === 'chcbpat' || node.value === 'cbpat') {
1332
+ if (node.param !== undefined && colorTable[node.param]) {
1333
+ formatting.backgroundColor = colorTable[node.param];
1334
+ }
1335
+ }
1336
+ // Subscript
1337
+ else if (node.value === 'sub') {
1338
+ formatting.subscript = true;
1339
+ formatting.superscript = false;
1340
+ }
1341
+ // Superscript
1342
+ else if (node.value === 'super') {
1343
+ formatting.superscript = true;
1344
+ formatting.subscript = false;
1345
+ }
1346
+ // No subscript/superscript
1347
+ else if (node.value === 'nosupersub') {
1348
+ formatting.subscript = false;
1349
+ formatting.superscript = false;
1350
+ }
1351
+ // ═══════════════════════════════════════════════════════════
1352
+ // List control words
1353
+ // ═══════════════════════════════════════════════════════════
1354
+ // Paragraph indentation (\li - left indent in twips)
1355
+ else if (node.value === 'li') {
1356
+ if (node.param !== undefined) {
1357
+ // Convert twips to a simpler unit (720 twips = 1 inch, ~0.5 inch per level)
1358
+ paragraphIndent = Math.floor(node.param / 360);
1359
+ }
1360
+ }
1361
+ // List style ID (Word 97+)
1362
+ else if (node.value === 'ls') {
1363
+ if (node.param !== undefined) {
1364
+ // If this is the first list item, reset the indent
1365
+ if (!isListItem)
1366
+ paragraphIndent = 0;
1367
+ isListItem = true;
1368
+ // Generate or retrieve list ID
1369
+ if (!listStyleIdMap[node.param]) {
1370
+ listIdCounter++;
1371
+ listStyleIdMap[node.param] = `rtf-list-${listIdCounter}`;
1372
+ }
1373
+ currentListId = listStyleIdMap[node.param];
1374
+ // Look up type from list definition
1375
+ // First check override map to get real list ID
1376
+ const realListId = listOverrideMap[node.param] !== undefined ? listOverrideMap[node.param] : node.param;
1377
+ if (listTypeMap[realListId]) {
1378
+ listType = listTypeMap[realListId];
1379
+ }
1380
+ }
1381
+ }
1382
+ // List indent level (Word 97+)
1383
+ else if (node.value === 'ilvl') {
1384
+ if (node.param !== undefined) {
1385
+ isListItem = true;
1386
+ paragraphIndent = node.param;
1387
+ }
1388
+ }
1389
+ // List numbering level (\pnlvl)
1390
+ else if (node.value === 'pnlvl') {
1391
+ isListItem = true;
1392
+ if (node.param !== undefined) {
1393
+ paragraphIndent = node.param;
1394
+ }
1395
+ }
1396
+ // List numbering format
1397
+ else if (node.value === 'levelnfc' || node.value === 'pnf') {
1398
+ // 0 = Arabic (1, 2, 3), 1 = Roman upper, 2 = Roman lower,
1399
+ // 3 = Letter upper, 4 = Letter lower, 23 = Bullet
1400
+ if (node.param !== undefined) {
1401
+ isListItem = true;
1402
+ if (node.param === 23) {
1403
+ listType = 'unordered';
1404
+ }
1405
+ else {
1406
+ listType = 'ordered';
1407
+ }
1408
+ }
1409
+ }
1410
+ // Ordered list indicator
1411
+ else if (node.value === 'pndec' || node.value === 'pnord' || node.value === 'pnlcltr' || node.value === 'pnucltr') {
1412
+ // If this is the first list item, reset the indent
1413
+ if (!isListItem)
1414
+ paragraphIndent = 0;
1415
+ isListItem = true;
1416
+ listType = 'ordered';
1417
+ }
1418
+ // Unordered list indicator
1419
+ else if (node.value === 'pnbullet' || node.value === 'pncard') {
1420
+ // If this is the first list item, reset the indent
1421
+ if (!isListItem)
1422
+ paragraphIndent = 0;
1423
+ isListItem = true;
1424
+ listType = 'unordered';
1425
+ }
1426
+ // Style-based heading detection (\s)
1427
+ else if (node.value === 's') {
1428
+ if (node.param !== undefined) {
1429
+ // Common heading styles: s1-s9 (though this varies by document)
1430
+ if (node.param >= 1 && node.param <= 9) {
1431
+ headingLevel = node.param;
1432
+ }
1433
+ }
1434
+ }
1435
+ // Paragraph alignment
1436
+ else if (node.value === 'ql') {
1437
+ paragraphAlignment = 'left';
1438
+ }
1439
+ else if (node.value === 'qc') {
1440
+ paragraphAlignment = 'center';
1441
+ }
1442
+ else if (node.value === 'qr') {
1443
+ paragraphAlignment = 'right';
1444
+ }
1445
+ else if (node.value === 'qj') {
1446
+ paragraphAlignment = 'justify';
1447
+ }
1448
+ }
1449
+ };
1450
+ traverse(doc, {});
1451
+ // Flush any remaining table
1452
+ const finalCtx = getCurrentTable();
1453
+ if (inTable || (finalCtx && (finalCtx.rows.length > 0 || finalCtx.currentCells.length > 0))) {
1454
+ flushTable();
1455
+ }
1456
+ flushParagraph();
1457
+ // Notes handling:
1458
+ // - If putNotesAtLast is false, notes should be added inline during traversal
1459
+ // (currently they go to 'notes' array, then we append them here - this is wrong)
1460
+ // - If putNotesAtLast is true, notes are appended at the very end (see below)
1461
+ //
1462
+ // For now, when putNotesAtLast is false, we append notes immediately after content
1463
+ // This isn't truly "inline" but it's better than at the end
1464
+ // TODO: Implement true inline placement during traversal
1465
+ if (!config.putNotesAtLast && notes.length > 0) {
1466
+ content.push(...notes);
1467
+ notes.length = 0; // Clear so they don't get appended again
1468
+ }
1469
+ // Perform OCR if enabled
1470
+ if (config.ocr && config.extractAttachments) {
1471
+ for (const attachment of attachments) {
1472
+ if (attachment.mimeType.startsWith('image/')) {
1473
+ try {
1474
+ // Convert base64 data back to Buffer for Tesseract.js
1475
+ // Passing base64 string directly would be interpreted as a file path,
1476
+ // causing ENAMETOOLONG error for large images.
1477
+ const imageBuffer = Buffer.from(attachment.data, 'base64');
1478
+ attachment.ocrText = (await (0, ocrUtils_1.performOcr)(imageBuffer, config.ocrLanguage)).trim();
1479
+ }
1480
+ catch (e) {
1481
+ (0, errorUtils_1.logWarning)(`OCR failed for ${attachment.name}:`, config, e);
1482
+ }
1483
+ }
1484
+ }
1485
+ // Link OCR text and altText to image nodes in content
1486
+ const assignOcr = (nodes) => {
1487
+ for (const node of nodes) {
1488
+ if (node.type === 'image' && node.metadata && 'attachmentName' in node.metadata) {
1489
+ const meta = node.metadata;
1490
+ const attachment = attachments.find(a => a.name === meta.attachmentName);
1491
+ if (attachment) {
1492
+ // Propagate OCR text to image node
1493
+ if (attachment.ocrText) {
1494
+ node.text = attachment.ocrText;
1495
+ }
1496
+ // Propagate altText if available
1497
+ if (attachment.altText) {
1498
+ meta.altText = attachment.altText;
1499
+ }
1500
+ }
1501
+ }
1502
+ if (node.children) {
1503
+ assignOcr(node.children);
1504
+ }
1505
+ }
1506
+ };
1507
+ assignOcr(content);
1508
+ }
1509
+ // Final pass to ensure all 'note' nodes have their 'text' property populated
1510
+ // (This supports the simple toText implementation)
1511
+ const populateNoteText = (nodes) => {
1512
+ for (const node of nodes) {
1513
+ if (node.type === 'note' && node.children) {
1514
+ const getText = (n) => {
1515
+ if (n.children && n.children.length > 0)
1516
+ return n.children.map(getText).join('');
1517
+ return n.text || '';
1518
+ };
1519
+ node.text = node.children.map(getText).join('').trim();
1520
+ }
1521
+ if (node.children) {
1522
+ populateNoteText(node.children);
1523
+ }
1524
+ }
1525
+ };
1526
+ populateNoteText(content);
1527
+ populateNoteText(notes);
1528
+ const result = {
1529
+ type: 'rtf',
1530
+ metadata: {
1531
+ // RTF Limitation: No style map available (RTF uses inline styles)
1532
+ // RTF Limitation: No endnote support (uses footnotes for both)
1533
+ },
1534
+ content: content,
1535
+ attachments: attachments,
1536
+ toText: () => {
1537
+ let text = content.map(c => c.text).join(config.newlineDelimiter ?? '\n');
1538
+ if (config.putNotesAtLast && notes.length > 0) {
1539
+ text += (config.newlineDelimiter ?? '\n') + notes.map(c => c.text).join(config.newlineDelimiter ?? '\n');
1540
+ }
1541
+ return text;
1542
+ }
1543
+ };
1544
+ // If putNotesAtLast is true, append notes to the end of the content array
1545
+ if (config.putNotesAtLast && notes.length > 0) {
1546
+ content.push(...notes);
1547
+ }
1548
+ return result;
1549
+ }
1550
+ catch (err) {
1551
+ throw err;
1552
+ }
1553
+ };
1554
+ exports.parseRtf = parseRtf;
1555
+ // Helper function to extract font table from RTF document
1556
+ function extractFontTable(doc) {
1557
+ const fontTable = {};
1558
+ // Recursive helper to find the font table group at any depth
1559
+ const findAndParseFontTable = (group) => {
1560
+ for (const node of group.content) {
1561
+ if (node.type === 'group') {
1562
+ if (node.destination === 'fonttbl') {
1563
+ // Iterate through font definitions
1564
+ for (const fontNode of node.content) {
1565
+ if (fontNode.type === 'group') {
1566
+ let fontIndex;
1567
+ let fontName = '';
1568
+ for (const item of fontNode.content) {
1569
+ if (item.type === 'control' && item.value === 'f') {
1570
+ fontIndex = item.param;
1571
+ }
1572
+ else if (item.type === 'text') {
1573
+ // Font name (may have trailing semicolon)
1574
+ fontName += item.value;
1575
+ }
1576
+ }
1577
+ if (fontIndex !== undefined && fontName) {
1578
+ // Remove trailing semicolon and whitespace
1579
+ fontName = fontName.replace(/;$/, '').trim();
1580
+ fontTable[fontIndex] = fontName;
1581
+ }
1582
+ }
1583
+ }
1584
+ return true; // Found and parsed
1585
+ }
1586
+ // Recurse into child groups
1587
+ if (findAndParseFontTable(node)) {
1588
+ return true;
1589
+ }
1590
+ }
1591
+ }
1592
+ return false;
1593
+ };
1594
+ findAndParseFontTable(doc);
1595
+ return fontTable;
1596
+ }
1597
+ // Helper function to extract color table from RTF document
1598
+ function extractColorTable(doc) {
1599
+ const colorTable = {};
1600
+ // Recursive helper to find the color table group at any depth
1601
+ const findAndParseColorTable = (group) => {
1602
+ for (const node of group.content) {
1603
+ if (node.type === 'group') {
1604
+ if (node.destination === 'colortbl') {
1605
+ let colorIndex = 0;
1606
+ let red = 0, green = 0, blue = 0;
1607
+ for (const item of node.content) {
1608
+ if (item.type === 'control') {
1609
+ if (item.value === 'red' && item.param !== undefined) {
1610
+ red = item.param;
1611
+ }
1612
+ else if (item.value === 'green' && item.param !== undefined) {
1613
+ green = item.param;
1614
+ }
1615
+ else if (item.value === 'blue' && item.param !== undefined) {
1616
+ blue = item.param;
1617
+ }
1618
+ }
1619
+ else if (item.type === 'text' && item.value === ';') {
1620
+ // Semicolon marks end of color definition
1621
+ const hex = `#${red.toString(16).padStart(2, '0')}${green.toString(16).padStart(2, '0')}${blue.toString(16).padStart(2, '0')}`;
1622
+ colorTable[colorIndex] = hex;
1623
+ colorIndex++;
1624
+ red = 0;
1625
+ green = 0;
1626
+ blue = 0;
1627
+ }
1628
+ }
1629
+ return true; // Found and parsed
1630
+ }
1631
+ // Recurse into child groups
1632
+ if (findAndParseColorTable(node)) {
1633
+ return true;
1634
+ }
1635
+ }
1636
+ }
1637
+ return false;
1638
+ };
1639
+ findAndParseColorTable(doc);
1640
+ return colorTable;
1641
+ }