docrev 0.11.3 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/dist/bin/rev.js +29 -21
  4. package/dist/bin/rev.js.map +1 -1
  5. package/dist/lib/build.d.ts +43 -0
  6. package/dist/lib/build.d.ts.map +1 -1
  7. package/dist/lib/build.js +175 -5
  8. package/dist/lib/build.js.map +1 -1
  9. package/dist/lib/commands/build.d.ts.map +1 -1
  10. package/dist/lib/commands/build.js +39 -125
  11. package/dist/lib/commands/build.js.map +1 -1
  12. package/dist/lib/commands/comments.js +3 -3
  13. package/dist/lib/commands/comments.js.map +1 -1
  14. package/dist/lib/commands/context.d.ts +12 -1
  15. package/dist/lib/commands/context.d.ts.map +1 -1
  16. package/dist/lib/commands/context.js +34 -1
  17. package/dist/lib/commands/context.js.map +1 -1
  18. package/dist/lib/commands/merge-resolve.js +1 -1
  19. package/dist/lib/commands/merge-resolve.js.map +1 -1
  20. package/dist/lib/commands/quality.js +2 -2
  21. package/dist/lib/commands/quality.js.map +1 -1
  22. package/dist/lib/commands/sections.js +1 -1
  23. package/dist/lib/commands/sections.js.map +1 -1
  24. package/dist/lib/commands/text-ops.js +1 -1
  25. package/dist/lib/commands/text-ops.js.map +1 -1
  26. package/dist/lib/commands/utilities.d.ts.map +1 -1
  27. package/dist/lib/commands/utilities.js +5 -2
  28. package/dist/lib/commands/utilities.js.map +1 -1
  29. package/dist/lib/commands/word-tools.js +2 -2
  30. package/dist/lib/commands/word-tools.js.map +1 -1
  31. package/dist/lib/crossref.d.ts.map +1 -1
  32. package/dist/lib/crossref.js +12 -41
  33. package/dist/lib/crossref.js.map +1 -1
  34. package/dist/lib/csl.d.ts.map +1 -1
  35. package/dist/lib/csl.js +14 -22
  36. package/dist/lib/csl.js.map +1 -1
  37. package/dist/lib/diff-engine.js +1 -1
  38. package/dist/lib/diff-engine.js.map +1 -1
  39. package/dist/lib/equations.d.ts.map +1 -1
  40. package/dist/lib/equations.js +12 -3
  41. package/dist/lib/equations.js.map +1 -1
  42. package/dist/lib/errors.d.ts.map +1 -1
  43. package/dist/lib/errors.js +1 -30
  44. package/dist/lib/errors.js.map +1 -1
  45. package/dist/lib/image-registry.d.ts.map +1 -1
  46. package/dist/lib/image-registry.js +4 -0
  47. package/dist/lib/image-registry.js.map +1 -1
  48. package/dist/lib/import.d.ts +1 -1
  49. package/dist/lib/import.d.ts.map +1 -1
  50. package/dist/lib/import.js +1 -1
  51. package/dist/lib/import.js.map +1 -1
  52. package/dist/lib/input.d.ts +0 -11
  53. package/dist/lib/input.d.ts.map +1 -1
  54. package/dist/lib/input.js +0 -35
  55. package/dist/lib/input.js.map +1 -1
  56. package/dist/lib/merge.d.ts.map +1 -1
  57. package/dist/lib/merge.js +9 -1
  58. package/dist/lib/merge.js.map +1 -1
  59. package/dist/lib/ooxml.d.ts +22 -0
  60. package/dist/lib/ooxml.d.ts.map +1 -1
  61. package/dist/lib/ooxml.js +130 -0
  62. package/dist/lib/ooxml.js.map +1 -1
  63. package/dist/lib/orcid.d.ts.map +1 -1
  64. package/dist/lib/orcid.js +16 -7
  65. package/dist/lib/orcid.js.map +1 -1
  66. package/dist/lib/plugins.d.ts.map +1 -1
  67. package/dist/lib/plugins.js +8 -4
  68. package/dist/lib/plugins.js.map +1 -1
  69. package/dist/lib/protect-restore.d.ts.map +1 -1
  70. package/dist/lib/protect-restore.js +7 -5
  71. package/dist/lib/protect-restore.js.map +1 -1
  72. package/dist/lib/restore-references.d.ts.map +1 -1
  73. package/dist/lib/restore-references.js +25 -3
  74. package/dist/lib/restore-references.js.map +1 -1
  75. package/dist/lib/schema.d.ts.map +1 -1
  76. package/dist/lib/schema.js +1 -19
  77. package/dist/lib/schema.js.map +1 -1
  78. package/dist/lib/slides.js +1 -1
  79. package/dist/lib/slides.js.map +1 -1
  80. package/dist/lib/spelling.js +1 -1
  81. package/dist/lib/spelling.js.map +1 -1
  82. package/dist/lib/tui.js +0 -1
  83. package/dist/lib/tui.js.map +1 -1
  84. package/dist/lib/utils.d.ts +14 -0
  85. package/dist/lib/utils.d.ts.map +1 -1
  86. package/dist/lib/utils.js +41 -0
  87. package/dist/lib/utils.js.map +1 -1
  88. package/dist/lib/word-extraction.d.ts +5 -5
  89. package/dist/lib/word-extraction.d.ts.map +1 -1
  90. package/dist/lib/word-extraction.js +25 -106
  91. package/dist/lib/word-extraction.js.map +1 -1
  92. package/dist/lib/word.d.ts +14 -38
  93. package/dist/lib/word.d.ts.map +1 -1
  94. package/dist/lib/word.js +24 -179
  95. package/dist/lib/word.js.map +1 -1
  96. package/dist/lib/wordcomments.d.ts.map +1 -1
  97. package/dist/lib/wordcomments.js +9 -7
  98. package/dist/lib/wordcomments.js.map +1 -1
  99. package/package.json +17 -6
  100. package/.gitattributes +0 -1
  101. package/PLAN-tables-and-postprocess.md +0 -850
  102. package/bin/rev.ts +0 -145
  103. package/docs-src/build.py +0 -113
  104. package/docs-src/extra.css +0 -208
  105. package/docs-src/md-to-html.lua +0 -6
  106. package/docs-src/template.html +0 -116
  107. package/eslint.config.js +0 -27
  108. package/lib/anchor-match.ts +0 -307
  109. package/lib/annotations.ts +0 -695
  110. package/lib/build.ts +0 -2047
  111. package/lib/citations.ts +0 -160
  112. package/lib/commands/build.ts +0 -885
  113. package/lib/commands/citations.ts +0 -515
  114. package/lib/commands/comments.ts +0 -1077
  115. package/lib/commands/context.ts +0 -185
  116. package/lib/commands/core.ts +0 -328
  117. package/lib/commands/doi.ts +0 -451
  118. package/lib/commands/file-ops.ts +0 -372
  119. package/lib/commands/history.ts +0 -320
  120. package/lib/commands/index.ts +0 -87
  121. package/lib/commands/init.ts +0 -259
  122. package/lib/commands/merge-resolve.ts +0 -378
  123. package/lib/commands/preview.ts +0 -178
  124. package/lib/commands/project-info.ts +0 -244
  125. package/lib/commands/quality.ts +0 -517
  126. package/lib/commands/response.ts +0 -454
  127. package/lib/commands/section-boundaries.ts +0 -82
  128. package/lib/commands/sections.ts +0 -451
  129. package/lib/commands/sync.ts +0 -689
  130. package/lib/commands/text-ops.ts +0 -449
  131. package/lib/commands/utilities.ts +0 -448
  132. package/lib/commands/verify-anchors.ts +0 -272
  133. package/lib/commands/word-tools.ts +0 -340
  134. package/lib/comment-realign.ts +0 -99
  135. package/lib/config.ts +0 -84
  136. package/lib/crossref.ts +0 -781
  137. package/lib/csl.ts +0 -191
  138. package/lib/dependencies.ts +0 -132
  139. package/lib/diff-engine.ts +0 -465
  140. package/lib/doi-cache.ts +0 -115
  141. package/lib/doi.ts +0 -879
  142. package/lib/equations.ts +0 -506
  143. package/lib/errors.ts +0 -350
  144. package/lib/format.ts +0 -541
  145. package/lib/git.ts +0 -326
  146. package/lib/grammar.ts +0 -303
  147. package/lib/image-registry.ts +0 -180
  148. package/lib/import.ts +0 -932
  149. package/lib/input.ts +0 -174
  150. package/lib/journals.ts +0 -543
  151. package/lib/macro-filter.lua +0 -201
  152. package/lib/macros.ts +0 -273
  153. package/lib/merge.ts +0 -633
  154. package/lib/ooxml.ts +0 -768
  155. package/lib/orcid.ts +0 -144
  156. package/lib/pdf-comments.ts +0 -263
  157. package/lib/pdf-import.ts +0 -524
  158. package/lib/plugins.ts +0 -362
  159. package/lib/postprocess.ts +0 -188
  160. package/lib/pptx-color-filter.lua +0 -37
  161. package/lib/pptx-template.ts +0 -469
  162. package/lib/pptx-themes/academic.pptx +0 -0
  163. package/lib/pptx-themes/corporate.pptx +0 -0
  164. package/lib/pptx-themes/dark.pptx +0 -0
  165. package/lib/pptx-themes/default.pptx +0 -0
  166. package/lib/pptx-themes/minimal.pptx +0 -0
  167. package/lib/pptx-themes/plant.pptx +0 -0
  168. package/lib/pptx-themes.ts +0 -483
  169. package/lib/protect-restore.ts +0 -520
  170. package/lib/rate-limiter.ts +0 -127
  171. package/lib/response.ts +0 -200
  172. package/lib/restore-references.ts +0 -240
  173. package/lib/review.ts +0 -327
  174. package/lib/schema.ts +0 -494
  175. package/lib/scientific-words.ts +0 -73
  176. package/lib/sections.ts +0 -428
  177. package/lib/slides.ts +0 -756
  178. package/lib/spelling.ts +0 -334
  179. package/lib/templates.ts +0 -526
  180. package/lib/themes.ts +0 -742
  181. package/lib/trackchanges.ts +0 -166
  182. package/lib/tui.ts +0 -450
  183. package/lib/types.ts +0 -546
  184. package/lib/undo.ts +0 -250
  185. package/lib/utils.ts +0 -69
  186. package/lib/variables.ts +0 -179
  187. package/lib/word-extraction.ts +0 -525
  188. package/lib/word.ts +0 -526
  189. package/lib/wordcomments.ts +0 -789
  190. package/mkdocs.yml +0 -64
  191. package/scripts/postbuild.js +0 -47
  192. package/tsconfig.json +0 -26
  193. package/types/index.d.ts +0 -531
@@ -1,525 +0,0 @@
1
- /**
2
- * Word document data extraction - raw extraction from .docx files
3
- */
4
-
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
- import { exec } from 'child_process';
8
- import { promisify } from 'util';
9
- import { buildDocTextModel, buildCommentAnchorModel, extractComments, openDocx, readPartText } from './ooxml.js';
10
-
11
- const execAsync = promisify(exec);
12
-
13
- // ============================================
14
- // Type Definitions
15
- // ============================================
16
-
17
- export interface WordComment {
18
- id: string;
19
- author: string;
20
- date: string;
21
- text: string;
22
- /**
23
- * Parent comment id when this is a reply in a Word comment thread.
24
- * Resolved from `commentsExtended.xml`'s `w15:paraIdParent` field.
25
- * `undefined` for top-level comments.
26
- */
27
- parentId?: string;
28
- }
29
-
30
- export interface TextNode {
31
- xmlStart: number;
32
- xmlEnd: number;
33
- textStart: number;
34
- textEnd: number;
35
- text: string;
36
- }
37
-
38
- export interface CommentAnchorData {
39
- anchor: string;
40
- before: string;
41
- after: string;
42
- docPosition: number;
43
- docLength: number;
44
- isEmpty: boolean;
45
- }
46
-
47
- export interface CommentAnchorsResult {
48
- anchors: Map<string, CommentAnchorData>;
49
- fullDocText: string;
50
- }
51
-
52
- export interface DocxHeading {
53
- /** Heading style name from `<w:pStyle>`, e.g. "Heading1" */
54
- style: string;
55
- /** Heading depth: 1, 2, 3, ... (parsed from style name; 0 if unknown) */
56
- level: number;
57
- /** Concatenated text content of the heading paragraph */
58
- text: string;
59
- /** Position in fullDocText (same coordinate system as CommentAnchorData.docPosition) */
60
- docPosition: number;
61
- }
62
-
63
- export interface WordTable {
64
- markdown: string;
65
- rowCount: number;
66
- colCount: number;
67
- }
68
-
69
- export interface ParsedRow {
70
- cells: string[];
71
- colSpans: number[];
72
- }
73
-
74
- export interface ExtractFromWordOptions {
75
- mediaDir?: string;
76
- skipMediaExtraction?: boolean;
77
- }
78
-
79
- export interface ExtractMessage {
80
- type: 'info' | 'warning';
81
- message: string;
82
- }
83
-
84
- export interface ExtractFromWordResult {
85
- text: string;
86
- comments: WordComment[];
87
- anchors: Map<string, CommentAnchorData>;
88
- messages: ExtractMessage[];
89
- extractedMedia: string[];
90
- tables: WordTable[];
91
- hasTrackChanges: boolean;
92
- trackChangeStats: { insertions: number; deletions: number };
93
- }
94
-
95
- // ============================================
96
- // Functions
97
- // ============================================
98
-
99
- /**
100
- * Extract comments directly from Word docx comments.xml
101
- */
102
- export async function extractWordComments(docxPath: string): Promise<WordComment[]> {
103
- if (!fs.existsSync(docxPath)) {
104
- throw new Error(`File not found: ${docxPath}`);
105
- }
106
-
107
- const zip = openDocx(docxPath);
108
- // Word truncates the stored date to its day for display; keep that contract.
109
- return extractComments(zip).map((c) => ({
110
- id: c.id,
111
- author: c.author,
112
- date: c.date.slice(0, 10),
113
- text: c.text,
114
- parentId: c.parentId,
115
- }));
116
- }
117
-
118
- /**
119
- * Extract comment anchor texts from document.xml with surrounding context
120
- * Returns map of comment ID -> {anchor, before, after, docPosition, isEmpty} for better matching
121
- * Also returns fullDocText for section boundary matching
122
- */
123
- export async function extractCommentAnchors(docxPath: string): Promise<CommentAnchorsResult> {
124
- const anchors = new Map<string, CommentAnchorData>();
125
-
126
- const zip = openDocx(docxPath);
127
- const { fullDocText, comments } = buildCommentAnchorModel(zip);
128
- if (!fullDocText && comments.length === 0) {
129
- return { anchors, fullDocText: '' };
130
- }
131
-
132
- // Context surrounding the anchor, taken from the same plain-text coordinate
133
- // system as docPosition so the placement engine can compare like with like.
134
- function getContextBefore(position: number, maxLength: number = 150): string {
135
- const beforeText = fullDocText.slice(Math.max(0, position - maxLength), position);
136
- const sentenceStart = beforeText.search(/[.!?]\s+[A-Z][^.!?]*$/);
137
- return sentenceStart >= 0
138
- ? beforeText.slice(sentenceStart + 2).trim()
139
- : beforeText.slice(-80).trim();
140
- }
141
-
142
- function getContextAfter(position: number, maxLength: number = 150): string {
143
- const afterText = fullDocText.slice(position, position + maxLength);
144
- const sentenceEnd = afterText.search(/[.!?]\s/);
145
- return sentenceEnd >= 0
146
- ? afterText.slice(0, sentenceEnd + 1).trim()
147
- : afterText.slice(0, 80).trim();
148
- }
149
-
150
- for (const range of comments) {
151
- anchors.set(range.id, {
152
- anchor: range.anchor,
153
- before: getContextBefore(range.start),
154
- after: getContextAfter(range.end),
155
- docPosition: range.start,
156
- docLength: fullDocText.length,
157
- isEmpty: range.isEmpty,
158
- });
159
- }
160
-
161
- return { anchors, fullDocText };
162
- }
163
-
164
- /**
165
- * Extract heading paragraphs from a docx, with their text positions in the
166
- * same coordinate system as `extractCommentAnchors`'s `fullDocText` and
167
- * `CommentAnchorData.docPosition`.
168
- *
169
- * Headings are paragraphs whose `<w:pStyle>` is a Heading style. Reading
170
- * styles directly is more reliable than keyword-matching the concatenated
171
- * body text — there, paragraph boundaries are gone, so the literal string
172
- * "Methods" can appear inside prose ("results across countries") and the
173
- * structured-abstract label "Methods:" loses its colon when text runs are
174
- * concatenated.
175
- */
176
- export async function extractHeadings(docxPath: string): Promise<DocxHeading[]> {
177
- if (!fs.existsSync(docxPath)) {
178
- throw new Error(`File not found: ${docxPath}`);
179
- }
180
-
181
- const zip = openDocx(docxPath);
182
- const docXml = readPartText(zip, 'word/document.xml');
183
- if (docXml === null) return [];
184
-
185
- return buildDocTextModel(docXml).headings.map((h) => ({
186
- style: h.style,
187
- level: h.level,
188
- text: h.text,
189
- docPosition: h.position,
190
- }));
191
- }
192
-
193
- /**
194
- * Decode XML entities in text
195
- */
196
- function decodeXmlEntities(text: string): string {
197
- return text
198
- .replace(/&amp;/g, '&')
199
- .replace(/&lt;/g, '<')
200
- .replace(/&gt;/g, '>')
201
- .replace(/&quot;/g, '"')
202
- .replace(/&apos;/g, "'")
203
- .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)))
204
- .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
205
- }
206
-
207
- /**
208
- * Extract text content from a Word XML cell
209
- */
210
- function extractCellText(cellXml: string): string {
211
- const parts: string[] = [];
212
-
213
- // Check for OMML math - replace with [math] placeholder
214
- if (cellXml.includes('<m:oMath')) {
215
- // Try to extract the text representation of math
216
- const mathTextMatches = cellXml.match(/<m:t>([^<]*)<\/m:t>/g) || [];
217
- if (mathTextMatches.length > 0) {
218
- const mathText = mathTextMatches.map((t) => t.replace(/<[^>]+>/g, '')).join('');
219
- parts.push(mathText);
220
- } else {
221
- parts.push('[math]');
222
- }
223
- }
224
-
225
- // Extract regular text from w:t elements
226
- const textMatches = cellXml.match(/<w:t[^>]*>([^<]*)<\/w:t>/g) || [];
227
- for (const match of textMatches) {
228
- const text = match.replace(/<[^>]+>/g, '');
229
- if (text) {
230
- parts.push(text);
231
- }
232
- }
233
-
234
- let result = parts.join('').trim();
235
- result = decodeXmlEntities(result);
236
-
237
- // Escape pipe characters in cell content (would break table)
238
- result = result.replace(/\|/g, '\\|');
239
-
240
- return result;
241
- }
242
-
243
- /**
244
- * Parse a table row, handling merged cells (gridSpan)
245
- */
246
- function parseTableRow(rowXml: string, expectedCols: number): ParsedRow {
247
- // Match cells - handle both <w:tc> and <w:tc ...>
248
- const cellMatches = rowXml.match(/<w:tc(?:\s[^>]*)?>[\s\S]*?<\/w:tc>/g) || [];
249
- const cells: string[] = [];
250
- const colSpans: number[] = [];
251
-
252
- for (const cellXml of cellMatches) {
253
- // Check for horizontal merge (gridSpan)
254
- const gridSpanMatch = cellXml.match(/<w:gridSpan\s+w:val="(\d+)"/);
255
- const span = gridSpanMatch ? parseInt(gridSpanMatch[1], 10) : 1;
256
-
257
- // Check for vertical merge continuation (vMerge without restart)
258
- // If vMerge is present without w:val="restart", it's a continuation - use empty
259
- const vMergeMatch = cellXml.match(/<w:vMerge(?:\s+w:val="([^"]+)")?/);
260
- const isVMergeContinuation = vMergeMatch && vMergeMatch[1] !== 'restart';
261
-
262
- const cellText = isVMergeContinuation ? '' : extractCellText(cellXml);
263
-
264
- // Add the cell content
265
- cells.push(cellText);
266
- colSpans.push(span);
267
-
268
- // For gridSpan > 1, add empty cells to maintain column alignment
269
- for (let i = 1; i < span; i++) {
270
- cells.push('');
271
- colSpans.push(0); // 0 indicates this is a spanned cell
272
- }
273
- }
274
-
275
- return { cells, colSpans };
276
- }
277
-
278
- /**
279
- * Determine table grid column count from table XML
280
- */
281
- function getTableGridCols(tableXml: string): number {
282
- // Try to get from tblGrid
283
- const gridColMatches = tableXml.match(/<w:gridCol/g) || [];
284
- if (gridColMatches.length > 0) {
285
- return gridColMatches.length;
286
- }
287
-
288
- // Fallback: count max cells in any row
289
- const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
290
- let maxCols = 0;
291
- for (const rowXml of rowMatches) {
292
- const { cells } = parseTableRow(rowXml, 0);
293
- maxCols = Math.max(maxCols, cells.length);
294
- }
295
- return maxCols;
296
- }
297
-
298
- /**
299
- * Extract tables directly from Word document XML and convert to markdown pipe tables
300
- */
301
- export async function extractWordTables(docxPath: string): Promise<WordTable[]> {
302
- const AdmZip = (await import('adm-zip')).default;
303
- const tables: WordTable[] = [];
304
-
305
- try {
306
- const zip = new AdmZip(docxPath);
307
- const docEntry = zip.getEntry('word/document.xml');
308
-
309
- if (!docEntry) {
310
- return tables;
311
- }
312
-
313
- const xml = docEntry.getData().toString('utf8');
314
-
315
- // Find all table elements
316
- const tableMatches = xml.match(/<w:tbl>[\s\S]*?<\/w:tbl>/g) || [];
317
-
318
- for (const tableXml of tableMatches) {
319
- // Determine expected column count from grid
320
- const expectedCols = getTableGridCols(tableXml);
321
-
322
- // Extract rows
323
- const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
324
- const rows: string[][] = [];
325
-
326
- for (const rowXml of rowMatches) {
327
- const { cells } = parseTableRow(rowXml, expectedCols);
328
- if (cells.length > 0) {
329
- rows.push(cells);
330
- }
331
- }
332
-
333
- if (rows.length > 0) {
334
- // Convert to markdown pipe table
335
- const markdown = convertRowsToMarkdownTable(rows);
336
- tables.push({ markdown, rowCount: rows.length, colCount: expectedCols || rows[0]?.length || 0 });
337
- }
338
- }
339
- } catch (err: any) {
340
- console.error('Error extracting tables from Word:', err.message);
341
- }
342
-
343
- return tables;
344
- }
345
-
346
- /**
347
- * Convert array of rows (each row is array of cell strings) to markdown pipe table
348
- */
349
- function convertRowsToMarkdownTable(rows: string[][]): string {
350
- if (rows.length === 0) return '';
351
-
352
- // Normalize column count (use max across all rows)
353
- const colCount = Math.max(...rows.map((r) => r.length));
354
-
355
- // Pad rows to have consistent column count
356
- const normalizedRows = rows.map((row) => {
357
- while (row.length < colCount) {
358
- row.push('');
359
- }
360
- return row;
361
- });
362
-
363
- // Build markdown table
364
- const lines: string[] = [];
365
-
366
- // Header row
367
- const header = normalizedRows[0];
368
- lines.push('| ' + header.join(' | ') + ' |');
369
-
370
- // Separator row
371
- lines.push('|' + header.map(() => '---').join('|') + '|');
372
-
373
- // Data rows
374
- for (let i = 1; i < normalizedRows.length; i++) {
375
- lines.push('| ' + normalizedRows[i].join(' | ') + ' |');
376
- }
377
-
378
- return lines.join('\n');
379
- }
380
-
381
- /**
382
- * Extract text from Word document using pandoc with track changes preserved
383
- */
384
- export async function extractFromWord(
385
- docxPath: string,
386
- options: ExtractFromWordOptions = {}
387
- ): Promise<ExtractFromWordResult> {
388
- let text: string;
389
- let messages: ExtractMessage[] = [];
390
- let extractedMedia: string[] = [];
391
- let hasTrackChanges = false;
392
- let trackChangeStats = { insertions: 0, deletions: 0 };
393
-
394
- // Determine media extraction directory
395
- const docxDir = path.dirname(docxPath);
396
- const mediaDir = options.mediaDir || path.join(docxDir, 'media');
397
-
398
- // Skip media extraction if figures already exist (e.g., when re-importing with existing source)
399
- const skipMediaExtraction = options.skipMediaExtraction || false;
400
-
401
- // Extract tables directly from Word XML (reliable, no heuristics)
402
- const wordTables = await extractWordTables(docxPath);
403
-
404
- // Try pandoc first with --track-changes=all to preserve reviewer edits
405
- try {
406
- // Build pandoc command
407
- let pandocCmd = `pandoc "${docxPath}" -t markdown --wrap=none --track-changes=all`;
408
- if (!skipMediaExtraction) {
409
- pandocCmd += ` --extract-media="${mediaDir}"`;
410
- }
411
-
412
- const { stdout } = await execAsync(pandocCmd, { maxBuffer: 50 * 1024 * 1024 });
413
- text = stdout;
414
-
415
- // Convert pandoc's track change format to CriticMarkup
416
- const origLength = text.length;
417
-
418
- // Use a more robust pattern that handles nested content
419
- text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.insertion[^}]*\}/g, (match, content) => {
420
- if (content.trim()) {
421
- trackChangeStats.insertions++;
422
- return `{++${content}++}`;
423
- }
424
- return ''; // Empty insertions are removed
425
- });
426
-
427
- text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.deletion[^}]*\}/g, (match, content) => {
428
- if (content.trim()) {
429
- trackChangeStats.deletions++;
430
- return `{--${content}--}`;
431
- }
432
- return ''; // Empty deletions are removed
433
- });
434
-
435
- // Handle any remaining pandoc track change patterns
436
- let prevText;
437
- do {
438
- prevText = text;
439
- text = text.replace(/\[([^\]]*)\]\{\.insertion[^}]*\}/g, (match, content) => {
440
- if (content.trim()) {
441
- trackChangeStats.insertions++;
442
- return `{++${content}++}`;
443
- }
444
- return '';
445
- });
446
- text = text.replace(/\[([^\]]*)\]\{\.deletion[^}]*\}/g, (match, content) => {
447
- if (content.trim()) {
448
- trackChangeStats.deletions++;
449
- return `{--${content}--}`;
450
- }
451
- return '';
452
- });
453
- } while (text !== prevText);
454
-
455
- // Handle pandoc comment patterns - remove comment text from body
456
- text = text.replace(/\[[^\]]*\]\{\.comment-start[^}]*\}/g, '');
457
- text = text.replace(/\[\]\{\.comment-end[^}]*\}/g, '');
458
-
459
- // Also handle {.mark} spans
460
- text = text.replace(/\[([^\]]*)\]\{\.mark\}/g, '$1');
461
-
462
- hasTrackChanges = trackChangeStats.insertions > 0 || trackChangeStats.deletions > 0;
463
-
464
- if (hasTrackChanges) {
465
- messages.push({
466
- type: 'info',
467
- message: `Found ${trackChangeStats.insertions} insertion(s) and ${trackChangeStats.deletions} deletion(s) from track changes`
468
- });
469
- }
470
-
471
- // Find extracted media files
472
- const mediaSubdir = path.join(mediaDir, 'media');
473
- if (fs.existsSync(mediaSubdir)) {
474
- extractedMedia = fs.readdirSync(mediaSubdir)
475
- .filter(f => /\.(png|jpg|jpeg|gif|svg|emf|wmf|tiff?)$/i.test(f))
476
- .map(f => path.join(mediaSubdir, f));
477
-
478
- if (extractedMedia.length > 0) {
479
- messages.push({
480
- type: 'info',
481
- message: `Extracted ${extractedMedia.length} image(s) to ${mediaSubdir}`
482
- });
483
- }
484
- }
485
- } catch (pandocErr: any) {
486
- // Pandoc not available — use XML-based extraction with track change support
487
- const { extractPlainTextWithTrackChanges } = await import('./word.js');
488
- const { getInstallInstructions } = await import('./dependencies.js');
489
- const installCmd = getInstallInstructions('pandoc');
490
-
491
- const xmlResult = await extractPlainTextWithTrackChanges(docxPath);
492
- text = xmlResult.text;
493
- hasTrackChanges = xmlResult.hasTrackChanges;
494
- trackChangeStats = xmlResult.stats;
495
-
496
- if (hasTrackChanges) {
497
- messages.push({
498
- type: 'warning',
499
- message: `Pandoc not installed. Using built-in XML extractor (${trackChangeStats.insertions} insertions, ${trackChangeStats.deletions} deletions preserved). Formatting may differ. Install pandoc for best results: ${installCmd}`
500
- });
501
- } else {
502
- messages.push({
503
- type: 'warning',
504
- message: `Pandoc not installed. Using built-in XML extractor (no track changes found). Install pandoc for better formatting: ${installCmd}`
505
- });
506
- }
507
- }
508
-
509
- // Extract comments directly from docx XML
510
- const comments = await extractWordComments(docxPath);
511
-
512
- // Extract comment anchor texts
513
- const { anchors } = await extractCommentAnchors(docxPath);
514
-
515
- return {
516
- text,
517
- comments,
518
- anchors,
519
- messages,
520
- extractedMedia,
521
- tables: wordTables,
522
- hasTrackChanges,
523
- trackChangeStats,
524
- };
525
- }