docrev 0.8.1 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/PLAN-tables-and-postprocess.md +850 -0
  3. package/README.md +33 -0
  4. package/bin/rev.js +12 -131
  5. package/bin/rev.ts +145 -0
  6. package/dist/bin/rev.d.ts +9 -0
  7. package/dist/bin/rev.d.ts.map +1 -0
  8. package/dist/bin/rev.js +118 -0
  9. package/dist/bin/rev.js.map +1 -0
  10. package/dist/lib/annotations.d.ts +91 -0
  11. package/dist/lib/annotations.d.ts.map +1 -0
  12. package/dist/lib/annotations.js +554 -0
  13. package/dist/lib/annotations.js.map +1 -0
  14. package/dist/lib/build.d.ts +171 -0
  15. package/dist/lib/build.d.ts.map +1 -0
  16. package/dist/lib/build.js +755 -0
  17. package/dist/lib/build.js.map +1 -0
  18. package/dist/lib/citations.d.ts +34 -0
  19. package/dist/lib/citations.d.ts.map +1 -0
  20. package/dist/lib/citations.js +140 -0
  21. package/dist/lib/citations.js.map +1 -0
  22. package/dist/lib/commands/build.d.ts +13 -0
  23. package/dist/lib/commands/build.d.ts.map +1 -0
  24. package/dist/lib/commands/build.js +678 -0
  25. package/dist/lib/commands/build.js.map +1 -0
  26. package/dist/lib/commands/citations.d.ts +11 -0
  27. package/dist/lib/commands/citations.d.ts.map +1 -0
  28. package/dist/lib/commands/citations.js +428 -0
  29. package/dist/lib/commands/citations.js.map +1 -0
  30. package/dist/lib/commands/comments.d.ts +11 -0
  31. package/dist/lib/commands/comments.d.ts.map +1 -0
  32. package/dist/lib/commands/comments.js +883 -0
  33. package/dist/lib/commands/comments.js.map +1 -0
  34. package/dist/lib/commands/context.d.ts +35 -0
  35. package/dist/lib/commands/context.d.ts.map +1 -0
  36. package/dist/lib/commands/context.js +59 -0
  37. package/dist/lib/commands/context.js.map +1 -0
  38. package/dist/lib/commands/core.d.ts +11 -0
  39. package/dist/lib/commands/core.d.ts.map +1 -0
  40. package/dist/lib/commands/core.js +246 -0
  41. package/dist/lib/commands/core.js.map +1 -0
  42. package/dist/lib/commands/doi.d.ts +11 -0
  43. package/dist/lib/commands/doi.d.ts.map +1 -0
  44. package/dist/lib/commands/doi.js +373 -0
  45. package/dist/lib/commands/doi.js.map +1 -0
  46. package/dist/lib/commands/history.d.ts +11 -0
  47. package/dist/lib/commands/history.d.ts.map +1 -0
  48. package/dist/lib/commands/history.js +245 -0
  49. package/dist/lib/commands/history.js.map +1 -0
  50. package/dist/lib/commands/index.d.ts +28 -0
  51. package/dist/lib/commands/index.d.ts.map +1 -0
  52. package/dist/lib/commands/index.js +35 -0
  53. package/dist/lib/commands/index.js.map +1 -0
  54. package/dist/lib/commands/init.d.ts +11 -0
  55. package/dist/lib/commands/init.d.ts.map +1 -0
  56. package/dist/lib/commands/init.js +209 -0
  57. package/dist/lib/commands/init.js.map +1 -0
  58. package/dist/lib/commands/response.d.ts +11 -0
  59. package/dist/lib/commands/response.d.ts.map +1 -0
  60. package/dist/lib/commands/response.js +317 -0
  61. package/dist/lib/commands/response.js.map +1 -0
  62. package/dist/lib/commands/sections.d.ts +11 -0
  63. package/dist/lib/commands/sections.d.ts.map +1 -0
  64. package/dist/lib/commands/sections.js +1071 -0
  65. package/dist/lib/commands/sections.js.map +1 -0
  66. package/dist/lib/commands/utilities.d.ts +19 -0
  67. package/dist/lib/commands/utilities.d.ts.map +1 -0
  68. package/dist/lib/commands/utilities.js +2009 -0
  69. package/dist/lib/commands/utilities.js.map +1 -0
  70. package/dist/lib/comment-realign.d.ts +50 -0
  71. package/dist/lib/comment-realign.d.ts.map +1 -0
  72. package/dist/lib/comment-realign.js +372 -0
  73. package/dist/lib/comment-realign.js.map +1 -0
  74. package/dist/lib/config.d.ts +41 -0
  75. package/dist/lib/config.d.ts.map +1 -0
  76. package/dist/lib/config.js +76 -0
  77. package/dist/lib/config.js.map +1 -0
  78. package/dist/lib/crossref.d.ts +108 -0
  79. package/dist/lib/crossref.d.ts.map +1 -0
  80. package/dist/lib/crossref.js +597 -0
  81. package/dist/lib/crossref.js.map +1 -0
  82. package/dist/lib/dependencies.d.ts +30 -0
  83. package/dist/lib/dependencies.d.ts.map +1 -0
  84. package/dist/lib/dependencies.js +95 -0
  85. package/dist/lib/dependencies.js.map +1 -0
  86. package/dist/lib/doi-cache.d.ts +29 -0
  87. package/dist/lib/doi-cache.d.ts.map +1 -0
  88. package/dist/lib/doi-cache.js +104 -0
  89. package/dist/lib/doi-cache.js.map +1 -0
  90. package/dist/lib/doi.d.ts +65 -0
  91. package/dist/lib/doi.d.ts.map +1 -0
  92. package/dist/lib/doi.js +710 -0
  93. package/dist/lib/doi.js.map +1 -0
  94. package/dist/lib/equations.d.ts +61 -0
  95. package/dist/lib/equations.d.ts.map +1 -0
  96. package/dist/lib/equations.js +445 -0
  97. package/dist/lib/equations.js.map +1 -0
  98. package/dist/lib/errors.d.ts +60 -0
  99. package/dist/lib/errors.d.ts.map +1 -0
  100. package/dist/lib/errors.js +303 -0
  101. package/dist/lib/errors.js.map +1 -0
  102. package/dist/lib/format.d.ts +104 -0
  103. package/dist/lib/format.d.ts.map +1 -0
  104. package/dist/lib/format.js +416 -0
  105. package/dist/lib/format.js.map +1 -0
  106. package/dist/lib/git.d.ts +88 -0
  107. package/dist/lib/git.d.ts.map +1 -0
  108. package/dist/lib/git.js +304 -0
  109. package/dist/lib/git.js.map +1 -0
  110. package/dist/lib/grammar.d.ts +62 -0
  111. package/dist/lib/grammar.d.ts.map +1 -0
  112. package/dist/lib/grammar.js +244 -0
  113. package/dist/lib/grammar.js.map +1 -0
  114. package/dist/lib/image-registry.d.ts +68 -0
  115. package/dist/lib/image-registry.d.ts.map +1 -0
  116. package/dist/lib/image-registry.js +112 -0
  117. package/dist/lib/image-registry.js.map +1 -0
  118. package/dist/lib/import.d.ts +184 -0
  119. package/dist/lib/import.d.ts.map +1 -0
  120. package/dist/lib/import.js +1581 -0
  121. package/dist/lib/import.js.map +1 -0
  122. package/dist/lib/journals.d.ts +55 -0
  123. package/dist/lib/journals.d.ts.map +1 -0
  124. package/dist/lib/journals.js +417 -0
  125. package/dist/lib/journals.js.map +1 -0
  126. package/dist/lib/merge.d.ts +138 -0
  127. package/dist/lib/merge.d.ts.map +1 -0
  128. package/dist/lib/merge.js +603 -0
  129. package/dist/lib/merge.js.map +1 -0
  130. package/dist/lib/orcid.d.ts +36 -0
  131. package/dist/lib/orcid.d.ts.map +1 -0
  132. package/dist/lib/orcid.js +117 -0
  133. package/dist/lib/orcid.js.map +1 -0
  134. package/dist/lib/pdf-comments.d.ts +95 -0
  135. package/dist/lib/pdf-comments.d.ts.map +1 -0
  136. package/dist/lib/pdf-comments.js +192 -0
  137. package/dist/lib/pdf-comments.js.map +1 -0
  138. package/dist/lib/pdf-import.d.ts +118 -0
  139. package/dist/lib/pdf-import.d.ts.map +1 -0
  140. package/dist/lib/pdf-import.js +397 -0
  141. package/dist/lib/pdf-import.js.map +1 -0
  142. package/dist/lib/plugins.d.ts +76 -0
  143. package/dist/lib/plugins.d.ts.map +1 -0
  144. package/dist/lib/plugins.js +235 -0
  145. package/dist/lib/plugins.js.map +1 -0
  146. package/dist/lib/postprocess.d.ts +42 -0
  147. package/dist/lib/postprocess.d.ts.map +1 -0
  148. package/dist/lib/postprocess.js +138 -0
  149. package/dist/lib/postprocess.js.map +1 -0
  150. package/dist/lib/pptx-template.d.ts +59 -0
  151. package/dist/lib/pptx-template.d.ts.map +1 -0
  152. package/dist/lib/pptx-template.js +613 -0
  153. package/dist/lib/pptx-template.js.map +1 -0
  154. package/dist/lib/pptx-themes.d.ts +80 -0
  155. package/dist/lib/pptx-themes.d.ts.map +1 -0
  156. package/dist/lib/pptx-themes.js +818 -0
  157. package/dist/lib/pptx-themes.js.map +1 -0
  158. package/dist/lib/protect-restore.d.ts +137 -0
  159. package/dist/lib/protect-restore.d.ts.map +1 -0
  160. package/dist/lib/protect-restore.js +394 -0
  161. package/dist/lib/protect-restore.js.map +1 -0
  162. package/dist/lib/rate-limiter.d.ts +27 -0
  163. package/dist/lib/rate-limiter.d.ts.map +1 -0
  164. package/dist/lib/rate-limiter.js +79 -0
  165. package/dist/lib/rate-limiter.js.map +1 -0
  166. package/dist/lib/response.d.ts +41 -0
  167. package/dist/lib/response.d.ts.map +1 -0
  168. package/dist/lib/response.js +150 -0
  169. package/dist/lib/response.js.map +1 -0
  170. package/dist/lib/review.d.ts +35 -0
  171. package/dist/lib/review.d.ts.map +1 -0
  172. package/dist/lib/review.js +263 -0
  173. package/dist/lib/review.js.map +1 -0
  174. package/dist/lib/schema.d.ts +66 -0
  175. package/dist/lib/schema.d.ts.map +1 -0
  176. package/dist/lib/schema.js +339 -0
  177. package/dist/lib/schema.js.map +1 -0
  178. package/dist/lib/scientific-words.d.ts +6 -0
  179. package/dist/lib/scientific-words.d.ts.map +1 -0
  180. package/dist/lib/scientific-words.js +66 -0
  181. package/dist/lib/scientific-words.js.map +1 -0
  182. package/dist/lib/sections.d.ts +40 -0
  183. package/dist/lib/sections.d.ts.map +1 -0
  184. package/dist/lib/sections.js +288 -0
  185. package/dist/lib/sections.js.map +1 -0
  186. package/dist/lib/slides.d.ts +86 -0
  187. package/dist/lib/slides.d.ts.map +1 -0
  188. package/dist/lib/slides.js +676 -0
  189. package/dist/lib/slides.js.map +1 -0
  190. package/dist/lib/spelling.d.ts +76 -0
  191. package/dist/lib/spelling.d.ts.map +1 -0
  192. package/dist/lib/spelling.js +272 -0
  193. package/dist/lib/spelling.js.map +1 -0
  194. package/dist/lib/templates.d.ts +30 -0
  195. package/dist/lib/templates.d.ts.map +1 -0
  196. package/dist/lib/templates.js +504 -0
  197. package/dist/lib/templates.js.map +1 -0
  198. package/dist/lib/themes.d.ts +85 -0
  199. package/dist/lib/themes.d.ts.map +1 -0
  200. package/dist/lib/themes.js +652 -0
  201. package/dist/lib/themes.js.map +1 -0
  202. package/dist/lib/trackchanges.d.ts +51 -0
  203. package/dist/lib/trackchanges.d.ts.map +1 -0
  204. package/dist/lib/trackchanges.js +202 -0
  205. package/dist/lib/trackchanges.js.map +1 -0
  206. package/dist/lib/tui.d.ts +76 -0
  207. package/dist/lib/tui.d.ts.map +1 -0
  208. package/dist/lib/tui.js +377 -0
  209. package/dist/lib/tui.js.map +1 -0
  210. package/dist/lib/types.d.ts +447 -0
  211. package/dist/lib/types.d.ts.map +1 -0
  212. package/dist/lib/types.js +6 -0
  213. package/dist/lib/types.js.map +1 -0
  214. package/dist/lib/undo.d.ts +57 -0
  215. package/dist/lib/undo.d.ts.map +1 -0
  216. package/dist/lib/undo.js +185 -0
  217. package/dist/lib/undo.js.map +1 -0
  218. package/dist/lib/utils.d.ts +16 -0
  219. package/dist/lib/utils.d.ts.map +1 -0
  220. package/dist/lib/utils.js +40 -0
  221. package/dist/lib/utils.js.map +1 -0
  222. package/dist/lib/variables.d.ts +42 -0
  223. package/dist/lib/variables.d.ts.map +1 -0
  224. package/dist/lib/variables.js +141 -0
  225. package/dist/lib/variables.js.map +1 -0
  226. package/dist/lib/word.d.ts +80 -0
  227. package/dist/lib/word.d.ts.map +1 -0
  228. package/dist/lib/word.js +360 -0
  229. package/dist/lib/word.js.map +1 -0
  230. package/dist/lib/wordcomments.d.ts +51 -0
  231. package/dist/lib/wordcomments.d.ts.map +1 -0
  232. package/dist/lib/wordcomments.js +587 -0
  233. package/dist/lib/wordcomments.js.map +1 -0
  234. package/eslint.config.js +27 -0
  235. package/lib/annotations.ts +622 -0
  236. package/lib/apply-buildup-colors.py +88 -0
  237. package/lib/build.ts +1013 -0
  238. package/lib/{citations.js → citations.ts} +38 -27
  239. package/lib/commands/{build.js → build.ts} +80 -27
  240. package/lib/commands/{citations.js → citations.ts} +36 -18
  241. package/lib/commands/{comments.js → comments.ts} +187 -54
  242. package/lib/commands/{context.js → context.ts} +18 -8
  243. package/lib/commands/{core.js → core.ts} +34 -20
  244. package/lib/commands/{doi.js → doi.ts} +32 -16
  245. package/lib/commands/{history.js → history.ts} +25 -12
  246. package/lib/commands/{index.js → index.ts} +9 -5
  247. package/lib/commands/{init.js → init.ts} +20 -8
  248. package/lib/commands/{response.js → response.ts} +47 -20
  249. package/lib/commands/{sections.js → sections.ts} +273 -68
  250. package/lib/commands/{utilities.js → utilities.ts} +338 -158
  251. package/lib/{comment-realign.js → comment-realign.ts} +117 -45
  252. package/lib/config.ts +84 -0
  253. package/lib/{crossref.js → crossref.ts} +213 -138
  254. package/lib/dependencies.ts +106 -0
  255. package/lib/doi-cache.ts +115 -0
  256. package/lib/{doi.js → doi.ts} +115 -281
  257. package/lib/{equations.js → equations.ts} +60 -64
  258. package/lib/{errors.js → errors.ts} +56 -48
  259. package/lib/{format.js → format.ts} +137 -63
  260. package/lib/{git.js → git.ts} +66 -63
  261. package/lib/{grammar.js → grammar.ts} +45 -32
  262. package/lib/image-registry.ts +180 -0
  263. package/lib/import.ts +2060 -0
  264. package/lib/journals.ts +505 -0
  265. package/lib/{merge.js → merge.ts} +185 -135
  266. package/lib/{orcid.js → orcid.ts} +17 -22
  267. package/lib/{pdf-comments.js → pdf-comments.ts} +76 -18
  268. package/lib/{pdf-import.js → pdf-import.ts} +148 -70
  269. package/lib/{plugins.js → plugins.ts} +82 -39
  270. package/lib/postprocess.ts +188 -0
  271. package/lib/pptx-color-filter.lua +37 -0
  272. package/lib/pptx-template.ts +625 -0
  273. package/lib/pptx-themes/academic.pptx +0 -0
  274. package/lib/pptx-themes/corporate.pptx +0 -0
  275. package/lib/pptx-themes/dark.pptx +0 -0
  276. package/lib/pptx-themes/default.pptx +0 -0
  277. package/lib/pptx-themes/minimal.pptx +0 -0
  278. package/lib/pptx-themes/plant.pptx +0 -0
  279. package/lib/pptx-themes.ts +896 -0
  280. package/lib/protect-restore.ts +516 -0
  281. package/lib/rate-limiter.ts +94 -0
  282. package/lib/{response.js → response.ts} +36 -21
  283. package/lib/{review.js → review.ts} +53 -43
  284. package/lib/{schema.js → schema.ts} +70 -25
  285. package/lib/{sections.js → sections.ts} +71 -76
  286. package/lib/slides.ts +793 -0
  287. package/lib/{spelling.js → spelling.ts} +43 -59
  288. package/lib/{templates.js → templates.ts} +20 -17
  289. package/lib/themes.ts +742 -0
  290. package/lib/{trackchanges.js → trackchanges.ts} +52 -23
  291. package/lib/types.ts +509 -0
  292. package/lib/{undo.js → undo.ts} +75 -52
  293. package/lib/utils.ts +41 -0
  294. package/lib/{variables.js → variables.ts} +60 -54
  295. package/lib/word.ts +428 -0
  296. package/lib/{wordcomments.js → wordcomments.ts} +94 -40
  297. package/package.json +15 -5
  298. package/skill/REFERENCE.md +67 -0
  299. package/tsconfig.json +26 -0
  300. package/lib/annotations.js +0 -414
  301. package/lib/build.js +0 -639
  302. package/lib/config.js +0 -79
  303. package/lib/import.js +0 -1145
  304. package/lib/journals.js +0 -629
  305. package/lib/word.js +0 -225
  306. /package/lib/{scientific-words.js → scientific-words.ts} +0 -0
@@ -0,0 +1,1581 @@
1
+ /**
2
+ * Import functionality - convert Word docs to annotated Markdown
3
+ */
4
+ import * as fs from 'fs';
5
+ import * as path from 'path';
6
+ import { diffWords } from 'diff';
7
+ import { stripAnnotations } from './annotations.js';
8
+ import { readImageRegistry } from './image-registry.js';
9
+ import { exec } from 'child_process';
10
+ import { promisify } from 'util';
11
+ import { extractMarkdownPrefix, protectAnchors, restoreAnchors, protectCrossrefs, restoreCrossrefs, protectMath, restoreMath, replaceRenderedMath, protectCitations, restoreCitations, replaceRenderedCitations, protectImages, restoreImages, matchWordImagesToOriginal, protectTables, restoreTables, } from './protect-restore.js';
12
+ const execAsync = promisify(exec);
13
+ // ============================================
14
+ // Functions
15
+ // ============================================
16
+ /**
17
+ * Extract comments directly from Word docx comments.xml
18
+ */
19
+ export async function extractWordComments(docxPath) {
20
+ const AdmZip = (await import('adm-zip')).default;
21
+ const { parseStringPromise } = await import('xml2js');
22
+ const comments = [];
23
+ // Validate file exists
24
+ if (!fs.existsSync(docxPath)) {
25
+ throw new Error(`File not found: ${docxPath}`);
26
+ }
27
+ try {
28
+ let zip;
29
+ try {
30
+ zip = new AdmZip(docxPath);
31
+ }
32
+ catch (err) {
33
+ throw new Error(`Invalid Word document (not a valid .docx file): ${err.message}`);
34
+ }
35
+ const commentsEntry = zip.getEntry('word/comments.xml');
36
+ if (!commentsEntry) {
37
+ return comments;
38
+ }
39
+ let commentsXml;
40
+ try {
41
+ commentsXml = commentsEntry.getData().toString('utf8');
42
+ }
43
+ catch (err) {
44
+ throw new Error(`Failed to read comments from document: ${err.message}`);
45
+ }
46
+ const parsed = await parseStringPromise(commentsXml, { explicitArray: false });
47
+ const ns = 'w:';
48
+ const commentsRoot = parsed['w:comments'];
49
+ if (!commentsRoot || !commentsRoot['w:comment']) {
50
+ return comments;
51
+ }
52
+ // Ensure it's an array
53
+ const commentNodes = Array.isArray(commentsRoot['w:comment'])
54
+ ? commentsRoot['w:comment']
55
+ : [commentsRoot['w:comment']];
56
+ for (const comment of commentNodes) {
57
+ const id = comment.$?.['w:id'] || '';
58
+ const author = comment.$?.['w:author'] || 'Unknown';
59
+ const date = comment.$?.['w:date'] || '';
60
+ // Extract text from nested w:p/w:r/w:t elements
61
+ let text = '';
62
+ const extractText = (node) => {
63
+ if (!node)
64
+ return;
65
+ if (typeof node === 'string') {
66
+ text += node;
67
+ return;
68
+ }
69
+ if (node['w:t']) {
70
+ const t = node['w:t'];
71
+ text += typeof t === 'string' ? t : (t._ || t);
72
+ }
73
+ if (node['w:r']) {
74
+ const runs = Array.isArray(node['w:r']) ? node['w:r'] : [node['w:r']];
75
+ runs.forEach(extractText);
76
+ }
77
+ if (node['w:p']) {
78
+ const paras = Array.isArray(node['w:p']) ? node['w:p'] : [node['w:p']];
79
+ paras.forEach(extractText);
80
+ }
81
+ };
82
+ extractText(comment);
83
+ comments.push({ id, author, date: date.slice(0, 10), text: text.trim() });
84
+ }
85
+ }
86
+ catch (err) {
87
+ // Re-throw with more context if it's already an Error we created
88
+ if (err.message.includes('Invalid Word document') || err.message.includes('File not found')) {
89
+ throw err;
90
+ }
91
+ throw new Error(`Error extracting comments from ${path.basename(docxPath)}: ${err.message}`);
92
+ }
93
+ return comments;
94
+ }
95
+ /**
96
+ * Extract comment anchor texts from document.xml with surrounding context
97
+ * Returns map of comment ID -> {anchor, before, after, docPosition, isEmpty} for better matching
98
+ * Also returns fullDocText for section boundary matching
99
+ */
100
+ export async function extractCommentAnchors(docxPath) {
101
+ const AdmZip = (await import('adm-zip')).default;
102
+ const anchors = new Map();
103
+ let fullDocText = '';
104
+ try {
105
+ const zip = new AdmZip(docxPath);
106
+ const docEntry = zip.getEntry('word/document.xml');
107
+ if (!docEntry) {
108
+ return { anchors, fullDocText };
109
+ }
110
+ const docXml = docEntry.getData().toString('utf8');
111
+ // ========================================
112
+ // STEP 1: Build text position mapping
113
+ // ========================================
114
+ const textNodePattern = /<w:t[^>]*>([^<]*)<\/w:t>/g;
115
+ const textNodes = [];
116
+ let textPosition = 0;
117
+ let nodeMatch;
118
+ while ((nodeMatch = textNodePattern.exec(docXml)) !== null) {
119
+ const rawText = nodeMatch[1] ?? '';
120
+ const decodedText = decodeXmlEntities(rawText);
121
+ textNodes.push({
122
+ xmlStart: nodeMatch.index,
123
+ xmlEnd: nodeMatch.index + nodeMatch[0].length,
124
+ textStart: textPosition,
125
+ textEnd: textPosition + decodedText.length,
126
+ text: decodedText
127
+ });
128
+ textPosition += decodedText.length;
129
+ }
130
+ fullDocText = textNodes.map(n => n.text).join('');
131
+ // Helper: convert XML position to text position
132
+ function xmlPosToTextPos(xmlPos) {
133
+ for (let i = 0; i < textNodes.length; i++) {
134
+ const node = textNodes[i];
135
+ if (!node)
136
+ continue;
137
+ if (xmlPos >= node.xmlStart && xmlPos < node.xmlEnd) {
138
+ return node.textStart;
139
+ }
140
+ if (xmlPos < node.xmlStart) {
141
+ return node.textStart;
142
+ }
143
+ }
144
+ const lastNode = textNodes[textNodes.length - 1];
145
+ return lastNode ? lastNode.textEnd : 0;
146
+ }
147
+ // Helper: extract context before a position
148
+ function getContextBefore(position, maxLength = 150) {
149
+ const beforeText = fullDocText.slice(Math.max(0, position - maxLength), position);
150
+ const sentenceStart = beforeText.search(/[.!?]\s+[A-Z][^.!?]*$/);
151
+ return sentenceStart >= 0
152
+ ? beforeText.slice(sentenceStart + 2).trim()
153
+ : beforeText.slice(-80).trim();
154
+ }
155
+ // Helper: extract context after a position
156
+ function getContextAfter(position, maxLength = 150) {
157
+ const afterText = fullDocText.slice(position, position + maxLength);
158
+ const sentenceEnd = afterText.search(/[.!?]\s/);
159
+ return sentenceEnd >= 0
160
+ ? afterText.slice(0, sentenceEnd + 1).trim()
161
+ : afterText.slice(0, 80).trim();
162
+ }
163
+ // ========================================
164
+ // STEP 2: Collect all start/end markers separately
165
+ // ========================================
166
+ const startPattern = /<w:commentRangeStart[^>]*w:id="(\d+)"[^>]*\/?>/g;
167
+ const endPattern = /<w:commentRangeEnd[^>]*w:id="(\d+)"[^>]*\/?>/g;
168
+ const starts = new Map(); // id -> position after start tag
169
+ const ends = new Map(); // id -> position before end tag
170
+ let match;
171
+ while ((match = startPattern.exec(docXml)) !== null) {
172
+ const id = match[1];
173
+ if (!starts.has(id)) {
174
+ starts.set(id, match.index + match[0].length);
175
+ }
176
+ }
177
+ while ((match = endPattern.exec(docXml)) !== null) {
178
+ const id = match[1];
179
+ if (!ends.has(id)) {
180
+ ends.set(id, match.index);
181
+ }
182
+ }
183
+ // ========================================
184
+ // STEP 3: Process each comment range by ID
185
+ // ========================================
186
+ for (const [id, startXmlPos] of starts) {
187
+ const endXmlPos = ends.get(id);
188
+ // Missing end marker - skip with warning
189
+ if (endXmlPos === undefined) {
190
+ console.warn(`Comment ${id}: missing end marker`);
191
+ continue;
192
+ }
193
+ // Calculate text position
194
+ const docPosition = xmlPosToTextPos(startXmlPos);
195
+ // Handle empty or inverted ranges
196
+ if (endXmlPos <= startXmlPos) {
197
+ anchors.set(id, {
198
+ anchor: '',
199
+ before: getContextBefore(docPosition),
200
+ after: getContextAfter(docPosition),
201
+ docPosition,
202
+ docLength: fullDocText.length,
203
+ isEmpty: true
204
+ });
205
+ continue;
206
+ }
207
+ // Extract XML segment between markers
208
+ const segment = docXml.slice(startXmlPos, endXmlPos);
209
+ // Extract text from w:t (regular) AND w:delText (deleted text in track changes)
210
+ const textInRangePattern = /<w:t[^>]*>([^<]*)<\/w:t>|<w:delText[^>]*>([^<]*)<\/w:delText>/g;
211
+ let anchorText = '';
212
+ let tm;
213
+ while ((tm = textInRangePattern.exec(segment)) !== null) {
214
+ anchorText += tm[1] || tm[2] || '';
215
+ }
216
+ anchorText = decodeXmlEntities(anchorText);
217
+ // Get context
218
+ const anchorLength = anchorText.length;
219
+ const before = getContextBefore(docPosition);
220
+ const after = getContextAfter(docPosition + anchorLength);
221
+ // ALWAYS add entry (even if anchor is empty)
222
+ anchors.set(id, {
223
+ anchor: anchorText.trim(),
224
+ before,
225
+ after,
226
+ docPosition,
227
+ docLength: fullDocText.length,
228
+ isEmpty: !anchorText.trim()
229
+ });
230
+ }
231
+ }
232
+ catch (err) {
233
+ console.error('Error extracting comment anchors:', err.message);
234
+ return { anchors, fullDocText: '' };
235
+ }
236
+ return { anchors, fullDocText };
237
+ }
238
+ /**
239
+ * Decode XML entities in text
240
+ */
241
+ function decodeXmlEntities(text) {
242
+ return text
243
+ .replace(/&amp;/g, '&')
244
+ .replace(/&lt;/g, '<')
245
+ .replace(/&gt;/g, '>')
246
+ .replace(/&quot;/g, '"')
247
+ .replace(/&apos;/g, "'")
248
+ .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)))
249
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
250
+ }
251
+ /**
252
+ * Extract text content from a Word XML cell
253
+ */
254
+ function extractCellText(cellXml) {
255
+ const parts = [];
256
+ // Check for OMML math - replace with [math] placeholder
257
+ if (cellXml.includes('<m:oMath')) {
258
+ // Try to extract the text representation of math
259
+ const mathTextMatches = cellXml.match(/<m:t>([^<]*)<\/m:t>/g) || [];
260
+ if (mathTextMatches.length > 0) {
261
+ const mathText = mathTextMatches.map((t) => t.replace(/<[^>]+>/g, '')).join('');
262
+ parts.push(mathText);
263
+ }
264
+ else {
265
+ parts.push('[math]');
266
+ }
267
+ }
268
+ // Extract regular text from w:t elements
269
+ const textMatches = cellXml.match(/<w:t[^>]*>([^<]*)<\/w:t>/g) || [];
270
+ for (const match of textMatches) {
271
+ const text = match.replace(/<[^>]+>/g, '');
272
+ if (text) {
273
+ parts.push(text);
274
+ }
275
+ }
276
+ let result = parts.join('').trim();
277
+ result = decodeXmlEntities(result);
278
+ // Escape pipe characters in cell content (would break table)
279
+ result = result.replace(/\|/g, '\\|');
280
+ return result;
281
+ }
282
+ /**
283
+ * Parse a table row, handling merged cells (gridSpan)
284
+ */
285
+ function parseTableRow(rowXml, expectedCols) {
286
+ // Match cells - handle both <w:tc> and <w:tc ...>
287
+ const cellMatches = rowXml.match(/<w:tc(?:\s[^>]*)?>[\s\S]*?<\/w:tc>/g) || [];
288
+ const cells = [];
289
+ const colSpans = [];
290
+ for (const cellXml of cellMatches) {
291
+ // Check for horizontal merge (gridSpan)
292
+ const gridSpanMatch = cellXml.match(/<w:gridSpan\s+w:val="(\d+)"/);
293
+ const span = gridSpanMatch ? parseInt(gridSpanMatch[1], 10) : 1;
294
+ // Check for vertical merge continuation (vMerge without restart)
295
+ // If vMerge is present without w:val="restart", it's a continuation - use empty
296
+ const vMergeMatch = cellXml.match(/<w:vMerge(?:\s+w:val="([^"]+)")?/);
297
+ const isVMergeContinuation = vMergeMatch && vMergeMatch[1] !== 'restart';
298
+ const cellText = isVMergeContinuation ? '' : extractCellText(cellXml);
299
+ // Add the cell content
300
+ cells.push(cellText);
301
+ colSpans.push(span);
302
+ // For gridSpan > 1, add empty cells to maintain column alignment
303
+ for (let i = 1; i < span; i++) {
304
+ cells.push('');
305
+ colSpans.push(0); // 0 indicates this is a spanned cell
306
+ }
307
+ }
308
+ return { cells, colSpans };
309
+ }
310
+ /**
311
+ * Determine table grid column count from table XML
312
+ */
313
+ function getTableGridCols(tableXml) {
314
+ // Try to get from tblGrid
315
+ const gridColMatches = tableXml.match(/<w:gridCol/g) || [];
316
+ if (gridColMatches.length > 0) {
317
+ return gridColMatches.length;
318
+ }
319
+ // Fallback: count max cells in any row
320
+ const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
321
+ let maxCols = 0;
322
+ for (const rowXml of rowMatches) {
323
+ const { cells } = parseTableRow(rowXml, 0);
324
+ maxCols = Math.max(maxCols, cells.length);
325
+ }
326
+ return maxCols;
327
+ }
328
+ /**
329
+ * Extract tables directly from Word document XML and convert to markdown pipe tables
330
+ */
331
+ export async function extractWordTables(docxPath) {
332
+ const AdmZip = (await import('adm-zip')).default;
333
+ const tables = [];
334
+ try {
335
+ const zip = new AdmZip(docxPath);
336
+ const docEntry = zip.getEntry('word/document.xml');
337
+ if (!docEntry) {
338
+ return tables;
339
+ }
340
+ const xml = docEntry.getData().toString('utf8');
341
+ // Find all table elements
342
+ const tableMatches = xml.match(/<w:tbl>[\s\S]*?<\/w:tbl>/g) || [];
343
+ for (const tableXml of tableMatches) {
344
+ // Determine expected column count from grid
345
+ const expectedCols = getTableGridCols(tableXml);
346
+ // Extract rows
347
+ const rowMatches = tableXml.match(/<w:tr[\s\S]*?<\/w:tr>/g) || [];
348
+ const rows = [];
349
+ for (const rowXml of rowMatches) {
350
+ const { cells } = parseTableRow(rowXml, expectedCols);
351
+ if (cells.length > 0) {
352
+ rows.push(cells);
353
+ }
354
+ }
355
+ if (rows.length > 0) {
356
+ // Convert to markdown pipe table
357
+ const markdown = convertRowsToMarkdownTable(rows);
358
+ tables.push({ markdown, rowCount: rows.length, colCount: expectedCols || rows[0]?.length || 0 });
359
+ }
360
+ }
361
+ }
362
+ catch (err) {
363
+ console.error('Error extracting tables from Word:', err.message);
364
+ }
365
+ return tables;
366
+ }
367
+ /**
368
+ * Convert array of rows (each row is array of cell strings) to markdown pipe table
369
+ */
370
+ function convertRowsToMarkdownTable(rows) {
371
+ if (rows.length === 0)
372
+ return '';
373
+ // Normalize column count (use max across all rows)
374
+ const colCount = Math.max(...rows.map((r) => r.length));
375
+ // Pad rows to have consistent column count
376
+ const normalizedRows = rows.map((row) => {
377
+ while (row.length < colCount) {
378
+ row.push('');
379
+ }
380
+ return row;
381
+ });
382
+ // Build markdown table
383
+ const lines = [];
384
+ // Header row
385
+ const header = normalizedRows[0];
386
+ lines.push('| ' + header.join(' | ') + ' |');
387
+ // Separator row
388
+ lines.push('|' + header.map(() => '---').join('|') + '|');
389
+ // Data rows
390
+ for (let i = 1; i < normalizedRows.length; i++) {
391
+ lines.push('| ' + normalizedRows[i].join(' | ') + ' |');
392
+ }
393
+ return lines.join('\n');
394
+ }
395
+ /**
396
+ * Extract text from Word document using pandoc with track changes preserved
397
+ */
398
+ export async function extractFromWord(docxPath, options = {}) {
399
+ let text;
400
+ let messages = [];
401
+ let extractedMedia = [];
402
+ let hasTrackChanges = false;
403
+ let trackChangeStats = { insertions: 0, deletions: 0 };
404
+ // Determine media extraction directory
405
+ const docxDir = path.dirname(docxPath);
406
+ const mediaDir = options.mediaDir || path.join(docxDir, 'media');
407
+ // Skip media extraction if figures already exist (e.g., when re-importing with existing source)
408
+ const skipMediaExtraction = options.skipMediaExtraction || false;
409
+ // Extract tables directly from Word XML (reliable, no heuristics)
410
+ const wordTables = await extractWordTables(docxPath);
411
+ // Try pandoc first with --track-changes=all to preserve reviewer edits
412
+ try {
413
+ // Build pandoc command
414
+ let pandocCmd = `pandoc "${docxPath}" -t markdown --wrap=none --track-changes=all`;
415
+ if (!skipMediaExtraction) {
416
+ pandocCmd += ` --extract-media="${mediaDir}"`;
417
+ }
418
+ const { stdout } = await execAsync(pandocCmd, { maxBuffer: 50 * 1024 * 1024 });
419
+ text = stdout;
420
+ // Convert pandoc's track change format to CriticMarkup
421
+ const origLength = text.length;
422
+ // Use a more robust pattern that handles nested content
423
+ text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.insertion[^}]*\}/g, (match, content) => {
424
+ if (content.trim()) {
425
+ trackChangeStats.insertions++;
426
+ return `{++${content}++}`;
427
+ }
428
+ return ''; // Empty insertions are removed
429
+ });
430
+ text = text.replace(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]\{\.deletion[^}]*\}/g, (match, content) => {
431
+ if (content.trim()) {
432
+ trackChangeStats.deletions++;
433
+ return `{--${content}--}`;
434
+ }
435
+ return ''; // Empty deletions are removed
436
+ });
437
+ // Handle any remaining pandoc track change patterns
438
+ let prevText;
439
+ do {
440
+ prevText = text;
441
+ text = text.replace(/\[([^\]]*)\]\{\.insertion[^}]*\}/g, (match, content) => {
442
+ if (content.trim()) {
443
+ trackChangeStats.insertions++;
444
+ return `{++${content}++}`;
445
+ }
446
+ return '';
447
+ });
448
+ text = text.replace(/\[([^\]]*)\]\{\.deletion[^}]*\}/g, (match, content) => {
449
+ if (content.trim()) {
450
+ trackChangeStats.deletions++;
451
+ return `{--${content}--}`;
452
+ }
453
+ return '';
454
+ });
455
+ } while (text !== prevText);
456
+ // Handle pandoc comment patterns - remove comment text from body
457
+ text = text.replace(/\[[^\]]*\]\{\.comment-start[^}]*\}/g, '');
458
+ text = text.replace(/\[\]\{\.comment-end[^}]*\}/g, '');
459
+ // Also handle {.mark} spans
460
+ text = text.replace(/\[([^\]]*)\]\{\.mark\}/g, '$1');
461
+ hasTrackChanges = trackChangeStats.insertions > 0 || trackChangeStats.deletions > 0;
462
+ if (hasTrackChanges) {
463
+ messages.push({
464
+ type: 'info',
465
+ message: `Found ${trackChangeStats.insertions} insertion(s) and ${trackChangeStats.deletions} deletion(s) from track changes`
466
+ });
467
+ }
468
+ // Find extracted media files
469
+ const mediaSubdir = path.join(mediaDir, 'media');
470
+ if (fs.existsSync(mediaSubdir)) {
471
+ extractedMedia = fs.readdirSync(mediaSubdir)
472
+ .filter(f => /\.(png|jpg|jpeg|gif|svg|emf|wmf|tiff?)$/i.test(f))
473
+ .map(f => path.join(mediaSubdir, f));
474
+ if (extractedMedia.length > 0) {
475
+ messages.push({
476
+ type: 'info',
477
+ message: `Extracted ${extractedMedia.length} image(s) to ${mediaSubdir}`
478
+ });
479
+ }
480
+ }
481
+ }
482
+ catch (pandocErr) {
483
+ // Fall back to mammoth if pandoc fails
484
+ messages.push({ type: 'warning', message: 'Pandoc failed, using mammoth (equations and images may not be preserved)' });
485
+ const mammoth = await import('mammoth');
486
+ const textResult = await mammoth.extractRawText({ path: docxPath });
487
+ const htmlResult = await mammoth.convertToHtml({ path: docxPath });
488
+ text = textResult.value;
489
+ messages = [...textResult.messages, ...htmlResult.messages].map(m => ({ type: 'warning', message: String(m) }));
490
+ }
491
+ // Extract comments directly from docx XML
492
+ const comments = await extractWordComments(docxPath);
493
+ // Extract comment anchor texts
494
+ const { anchors } = await extractCommentAnchors(docxPath);
495
+ return {
496
+ text,
497
+ comments,
498
+ anchors,
499
+ messages,
500
+ extractedMedia,
501
+ tables: wordTables,
502
+ hasTrackChanges,
503
+ trackChangeStats,
504
+ };
505
+ }
506
+ /**
507
+ * Insert comments into markdown text based on anchor texts with context
508
+ */
509
+ export function insertCommentsIntoMarkdown(markdown, comments, anchors, options = {}) {
510
+ const { quiet = false, sectionBoundary = null } = options;
511
+ let result = markdown;
512
+ let unmatchedCount = 0;
513
+ const duplicateWarnings = [];
514
+ const usedPositions = new Set(); // For tie-breaking: track used positions
515
+ // Helper: Strip CriticMarkup from text to get "clean" version for matching
516
+ function stripCriticMarkup(text) {
517
+ return text
518
+ .replace(/\{\+\+([^+]*)\+\+\}/g, '$1') // insertions: keep inserted text
519
+ .replace(/\{--([^-]*)--\}/g, '') // deletions: remove deleted text
520
+ .replace(/\{~~([^~]*)~>([^~]*)~~\}/g, '$2') // substitutions: keep new text
521
+ .replace(/\{>>[^<]*<<\}/g, '') // comments: remove
522
+ .replace(/\[([^\]]*)\]\{\.mark\}/g, '$1'); // marked text: keep text
523
+ }
524
+ // Helper: Find anchor in text with multiple fallback strategies
525
+ function findAnchorInText(anchor, text, before = '', after = '') {
526
+ // If anchor is empty, skip directly to context-based matching
527
+ if (!anchor || anchor.trim().length === 0) {
528
+ // Jump to context-based strategies (Strategy 5)
529
+ if (before || after) {
530
+ const beforeLower = (before || '').toLowerCase();
531
+ const afterLower = (after || '').toLowerCase();
532
+ const textLower = text.toLowerCase();
533
+ if (before && after) {
534
+ const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
535
+ if (beforeIdx !== -1) {
536
+ const searchStart = beforeIdx + beforeLower.slice(-50).length;
537
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
538
+ if (afterIdx !== -1 && afterIdx - searchStart < 500) {
539
+ return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
540
+ }
541
+ }
542
+ }
543
+ if (before) {
544
+ const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
545
+ if (beforeIdx !== -1) {
546
+ return { occurrences: [beforeIdx + beforeLower.slice(-30).length], matchedAnchor: null, strategy: 'context-before' };
547
+ }
548
+ }
549
+ if (after) {
550
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
551
+ if (afterIdx !== -1) {
552
+ return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
553
+ }
554
+ }
555
+ }
556
+ return { occurrences: [], matchedAnchor: null, strategy: 'empty-anchor' };
557
+ }
558
+ const anchorLower = anchor.toLowerCase();
559
+ const textLower = text.toLowerCase();
560
+ // Strategy 1: Direct match
561
+ let occurrences = findAllOccurrences(textLower, anchorLower);
562
+ if (occurrences.length > 0) {
563
+ return { occurrences, matchedAnchor: anchor, strategy: 'direct' };
564
+ }
565
+ // Strategy 2: Normalized whitespace
566
+ const normalizedAnchor = anchor.replace(/\s+/g, ' ').toLowerCase();
567
+ const normalizedText = text.replace(/\s+/g, ' ').toLowerCase();
568
+ let idx = normalizedText.indexOf(normalizedAnchor);
569
+ if (idx !== -1) {
570
+ return { occurrences: [idx], matchedAnchor: anchor, strategy: 'normalized' };
571
+ }
572
+ // Strategy 3: Try matching in stripped CriticMarkup version
573
+ const strippedText = stripCriticMarkup(text);
574
+ const strippedLower = strippedText.toLowerCase();
575
+ occurrences = findAllOccurrences(strippedLower, anchorLower);
576
+ if (occurrences.length > 0) {
577
+ return { occurrences, matchedAnchor: anchor, strategy: 'stripped', stripped: true };
578
+ }
579
+ // Strategy 4: First N words of anchor (for long anchors)
580
+ const words = anchor.split(/\s+/);
581
+ if (words.length > 3) {
582
+ for (let n = Math.min(6, words.length); n >= 3; n--) {
583
+ const partialAnchor = words.slice(0, n).join(' ').toLowerCase();
584
+ if (partialAnchor.length >= 15) {
585
+ occurrences = findAllOccurrences(textLower, partialAnchor);
586
+ if (occurrences.length > 0) {
587
+ return { occurrences, matchedAnchor: words.slice(0, n).join(' '), strategy: 'partial-start' };
588
+ }
589
+ occurrences = findAllOccurrences(strippedLower, partialAnchor);
590
+ if (occurrences.length > 0) {
591
+ return { occurrences, matchedAnchor: words.slice(0, n).join(' '), strategy: 'partial-start-stripped', stripped: true };
592
+ }
593
+ }
594
+ }
595
+ }
596
+ // Strategy 5: Use context (before/after) to find approximate position
597
+ if (before || after) {
598
+ const beforeLower = before.toLowerCase();
599
+ const afterLower = after.toLowerCase();
600
+ if (before && after) {
601
+ const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
602
+ if (beforeIdx !== -1) {
603
+ const searchStart = beforeIdx + beforeLower.slice(-50).length;
604
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
605
+ if (afterIdx !== -1 && afterIdx - searchStart < 500) {
606
+ return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
607
+ }
608
+ }
609
+ }
610
+ if (before) {
611
+ const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
612
+ if (beforeIdx !== -1) {
613
+ return { occurrences: [beforeIdx + beforeLower.slice(-30).length], matchedAnchor: null, strategy: 'context-before' };
614
+ }
615
+ }
616
+ if (after) {
617
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
618
+ if (afterIdx !== -1) {
619
+ return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
620
+ }
621
+ }
622
+ }
623
+ // Strategy 6: Try splitting anchor on common transition words
624
+ const splitPatterns = [' ', ', ', '. ', ' - ', ' – '];
625
+ for (const sep of splitPatterns) {
626
+ if (anchor.includes(sep)) {
627
+ const parts = anchor.split(sep).filter(p => p.length >= 4);
628
+ for (const part of parts) {
629
+ const partLower = part.toLowerCase();
630
+ occurrences = findAllOccurrences(textLower, partLower);
631
+ if (occurrences.length > 0 && occurrences.length < 5) {
632
+ return { occurrences, matchedAnchor: part, strategy: 'split-match' };
633
+ }
634
+ }
635
+ }
636
+ }
637
+ return { occurrences: [], matchedAnchor: null, strategy: 'failed' };
638
+ }
639
+ // Helper: Find all occurrences of needle in haystack
640
+ function findAllOccurrences(haystack, needle) {
641
+ if (!needle || needle.length === 0) {
642
+ return [];
643
+ }
644
+ const occurrences = [];
645
+ let idx = 0;
646
+ while ((idx = haystack.indexOf(needle, idx)) !== -1) {
647
+ occurrences.push(idx);
648
+ idx += 1;
649
+ }
650
+ return occurrences;
651
+ }
652
+ // Get all positions in order (for sequential tie-breaking)
653
+ const commentsWithPositions = comments.map((c) => {
654
+ const anchorData = anchors.get(c.id);
655
+ if (!anchorData) {
656
+ unmatchedCount++;
657
+ return { ...c, pos: -1, anchorText: null };
658
+ }
659
+ // Support both old format (string) and new format ({anchor, before, after})
660
+ const anchor = typeof anchorData === 'string' ? anchorData : anchorData.anchor;
661
+ const before = typeof anchorData === 'object' ? anchorData.before : '';
662
+ const after = typeof anchorData === 'object' ? anchorData.after : '';
663
+ const isEmpty = typeof anchorData === 'object' && anchorData.isEmpty;
664
+ const docPosition = typeof anchorData === 'object' ? anchorData.docPosition : undefined;
665
+ // Position-based insertion (most reliable)
666
+ if (sectionBoundary && docPosition !== undefined) {
667
+ const sectionLength = sectionBoundary.end - sectionBoundary.start;
668
+ if (sectionLength > 0) {
669
+ let relativePos;
670
+ if (docPosition < sectionBoundary.start) {
671
+ relativePos = 0;
672
+ }
673
+ else {
674
+ relativePos = docPosition - sectionBoundary.start;
675
+ }
676
+ const proportion = Math.min(relativePos / sectionLength, 1.0);
677
+ const markdownPos = Math.floor(proportion * result.length);
678
+ let insertPos = markdownPos;
679
+ // Look for nearby word boundary
680
+ const searchWindow = result.slice(Math.max(0, markdownPos - 25), Math.min(result.length, markdownPos + 25));
681
+ const spaceIdx = searchWindow.indexOf(' ', 25);
682
+ if (spaceIdx !== -1 && spaceIdx < 50) {
683
+ insertPos = Math.max(0, markdownPos - 25) + spaceIdx;
684
+ }
685
+ // If we have anchor text, try to find it near this position
686
+ if (anchor && !isEmpty) {
687
+ const searchStart = Math.max(0, insertPos - 200);
688
+ const searchEnd = Math.min(result.length, insertPos + 200);
689
+ const localSearch = result.slice(searchStart, searchEnd).toLowerCase();
690
+ const anchorLower = anchor.toLowerCase();
691
+ const localIdx = localSearch.indexOf(anchorLower);
692
+ if (localIdx !== -1) {
693
+ return { ...c, pos: searchStart + localIdx, anchorText: anchor, anchorEnd: searchStart + localIdx + anchor.length, strategy: 'position+text' };
694
+ }
695
+ // Try first few words
696
+ const words = anchor.split(/\s+/).slice(0, 4).join(' ').toLowerCase();
697
+ if (words.length >= 10) {
698
+ const partialIdx = localSearch.indexOf(words);
699
+ if (partialIdx !== -1) {
700
+ return { ...c, pos: searchStart + partialIdx, anchorText: words, anchorEnd: searchStart + partialIdx + words.length, strategy: 'position+partial' };
701
+ }
702
+ }
703
+ }
704
+ return { ...c, pos: insertPos, anchorText: null, strategy: 'position-only' };
705
+ }
706
+ }
707
+ // Handle empty anchors
708
+ if (!anchor || isEmpty) {
709
+ if (before || after) {
710
+ const { occurrences } = findAnchorInText('', result, before, after);
711
+ if (occurrences.length > 0) {
712
+ return { ...c, pos: occurrences[0], anchorText: null, isEmpty: true };
713
+ }
714
+ }
715
+ unmatchedCount++;
716
+ return { ...c, pos: -1, anchorText: null, isEmpty: true };
717
+ }
718
+ // Text-based matching strategies
719
+ const { occurrences, matchedAnchor, strategy, stripped } = findAnchorInText(anchor, result, before, after);
720
+ if (occurrences.length === 0) {
721
+ unmatchedCount++;
722
+ return { ...c, pos: -1, anchorText: null };
723
+ }
724
+ const anchorLen = matchedAnchor ? matchedAnchor.length : 0;
725
+ if (occurrences.length === 1) {
726
+ if (matchedAnchor) {
727
+ return { ...c, pos: occurrences[0], anchorText: matchedAnchor, anchorEnd: occurrences[0] + anchorLen };
728
+ }
729
+ else {
730
+ return { ...c, pos: occurrences[0], anchorText: null };
731
+ }
732
+ }
733
+ // Multiple occurrences - use context for disambiguation
734
+ if (matchedAnchor) {
735
+ duplicateWarnings.push(`"${matchedAnchor.slice(0, 40)}${matchedAnchor.length > 40 ? '...' : ''}" appears ${occurrences.length} times`);
736
+ }
737
+ let bestIdx = occurrences.find(p => !usedPositions.has(p)) ?? occurrences[0];
738
+ let bestScore = -1;
739
+ for (const pos of occurrences) {
740
+ if (usedPositions.has(pos))
741
+ continue;
742
+ let score = 0;
743
+ if (before) {
744
+ const contextBefore = result.slice(Math.max(0, pos - before.length - 20), pos).toLowerCase();
745
+ const beforeLower = before.toLowerCase();
746
+ const beforeWords = beforeLower.split(/\s+/).filter(w => w.length > 3);
747
+ for (const word of beforeWords) {
748
+ if (contextBefore.includes(word))
749
+ score += 2;
750
+ }
751
+ if (contextBefore.includes(beforeLower.slice(-30)))
752
+ score += 5;
753
+ }
754
+ if (after) {
755
+ const contextAfter = result.slice(pos + anchorLen, pos + anchorLen + after.length + 20).toLowerCase();
756
+ const afterLower = after.toLowerCase();
757
+ const afterWords = afterLower.split(/\s+/).filter(w => w.length > 3);
758
+ for (const word of afterWords) {
759
+ if (contextAfter.includes(word))
760
+ score += 2;
761
+ }
762
+ if (contextAfter.includes(afterLower.slice(0, 30)))
763
+ score += 5;
764
+ }
765
+ if (score > bestScore || (score === bestScore && pos < bestIdx)) {
766
+ bestScore = score;
767
+ bestIdx = pos;
768
+ }
769
+ }
770
+ usedPositions.add(bestIdx);
771
+ if (matchedAnchor) {
772
+ return { ...c, pos: bestIdx, anchorText: matchedAnchor, anchorEnd: bestIdx + anchorLen };
773
+ }
774
+ else {
775
+ return { ...c, pos: bestIdx, anchorText: null };
776
+ }
777
+ });
778
+ // Log any unmatched comments for debugging
779
+ const unmatched = commentsWithPositions.filter((c) => c.pos < 0);
780
+ if (process.env.DEBUG) {
781
+ console.log(`[DEBUG] insertComments: ${comments.length} input, ${commentsWithPositions.length} processed, ${unmatched.length} unmatched`);
782
+ if (unmatched.length > 0) {
783
+ unmatched.forEach(c => console.log(`[DEBUG] Unmatched ID=${c.id}: anchor="${(c.anchorText || 'none').slice(0, 30)}"`));
784
+ }
785
+ }
786
+ const matched = commentsWithPositions.filter((c) => c.pos >= 0);
787
+ // Sort by position descending (insert from end to avoid offset issues)
788
+ matched.sort((a, b) => b.pos - a.pos);
789
+ // Insert each comment with anchor marking
790
+ for (const c of matched) {
791
+ const comment = `{>>${c.author}: ${c.text}<<}`;
792
+ if (c.anchorText && c.anchorEnd) {
793
+ // Replace anchor text with: {>>comment<<}[anchor]{.mark}
794
+ const before = result.slice(0, c.pos);
795
+ const anchor = result.slice(c.pos, c.anchorEnd);
796
+ const after = result.slice(c.anchorEnd);
797
+ result = before + comment + `[${anchor}]{.mark}` + after;
798
+ }
799
+ else {
800
+ // No anchor - just insert comment at position
801
+ result = result.slice(0, c.pos) + ` ${comment}` + result.slice(c.pos);
802
+ }
803
+ }
804
+ // Log warnings unless quiet mode
805
+ if (!quiet) {
806
+ if (unmatchedCount > 0) {
807
+ console.warn(`Warning: ${unmatchedCount} comment(s) could not be matched to anchor text`);
808
+ }
809
+ if (duplicateWarnings.length > 0) {
810
+ console.warn(`Warning: Duplicate anchor text found (using context & tie-breaks for placement):`);
811
+ for (const w of duplicateWarnings) {
812
+ console.warn(` - ${w}`);
813
+ }
814
+ }
815
+ }
816
+ return result;
817
+ }
818
+ /**
819
+ * Normalize text for comparison (handle whitespace differences)
820
+ */
821
+ function normalizeWhitespace(text) {
822
+ return text
823
+ .replace(/\r\n/g, '\n') // Normalize line endings
824
+ .replace(/\t/g, ' ') // Tabs to spaces
825
+ .replace(/ +/g, ' ') // Collapse multiple spaces
826
+ .trim();
827
+ }
828
+ /**
829
+ * Fix citation and math annotations by preserving original markdown syntax
830
+ */
831
+ function fixCitationAnnotations(text, originalMd) {
832
+ // Fix math annotations - preserve inline and display math
833
+ text = text.replace(/\{--(\$[^$]+\$)--\}/g, '$1');
834
+ text = text.replace(/\{--(\$\$[^$]+\$\$)--\}/g, '$1');
835
+ text = text.replace(/\{~~(\$[^$]+\$)~>[^~]+~~\}/g, '$1');
836
+ text = text.replace(/\{~~(\$\$[^$]+\$\$)~>[^~]+~~\}/g, '$1');
837
+ // Extract all citations from original markdown
838
+ const citationPattern = /\[@[^\]]+\]/g;
839
+ const originalCitations = [...originalMd.matchAll(citationPattern)].map(m => m[0]);
840
+ // Fix substitutions where left side has markdown citation
841
+ text = text.replace(/\{~~(\[@[^\]]+\])~>[^~]+~~\}/g, '$1');
842
+ // Fix substitutions where left side STARTS with markdown citation
843
+ text = text.replace(/\{~~(\[@[^\]]+\])\s*([^~]*)~>([^~]*)~~\}/g, (match, cite, oldText, newText) => {
844
+ if (oldText.trim() === '' && newText.trim() === '') {
845
+ return cite;
846
+ }
847
+ if (oldText.trim() || newText.trim()) {
848
+ return cite + (oldText.trim() !== newText.trim() ? ` {~~${oldText.trim()}~>${newText.trim()}~~}` : ` ${newText}`);
849
+ }
850
+ return cite;
851
+ });
852
+ // Fix deletions of markdown citations
853
+ text = text.replace(/\{--(\[@[^\]]+\])--\}/g, '$1');
854
+ // Fix insertions of rendered citations
855
+ text = text.replace(/\{\+\+\([A-Z][^)]*\d{4}[^)]*\)\+\+\}/g, '');
856
+ // Clean up broken multi-part substitutions
857
+ text = text.replace(/\{~~(@[A-Za-z]+\d{4})~>[^~]+~~\}/g, '[$1]');
858
+ // Fix citations split across substitution boundaries
859
+ text = text.replace(/\{~~\[@~>[^~]*~~\}([A-Za-z]+\d{4})\]/g, '[@$1]');
860
+ // Clean up any remaining partial citations
861
+ text = text.replace(/\{~~;\s*@([A-Za-z]+\d{4})\]~>[^~]*~~\}/g, '; [@$1]');
862
+ // Remove rendered citation insertions (with Unicode support)
863
+ text = text.replace(/\{\+\+\(\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?(?:[;,]\s*\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?)*\)\+\+\}/gu, '');
864
+ text = text.replace(/\{\+\+\(\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?(?:[;,]\s*\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?)*\)\.\s*\+\+\}/gu, '');
865
+ // Trailing citation fragments
866
+ text = text.replace(/\{\+\+\d{4}[a-z]?(?:[;,]\s*(?:\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+)?\d{4}[a-z]?)*\)\.\s*\+\+\}/gu, '');
867
+ text = text.replace(/\{\+\+\d{4}[a-z]?(?:[;,]\s*(?:\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+)?\d{4}[a-z]?)*\)\s*\+\+\}/gu, '');
868
+ // Just year with closing paren
869
+ text = text.replace(/\{\+\+\d{4}[a-z]?\)\.\s*\+\+\}/g, '');
870
+ text = text.replace(/\{\+\+\d{4}[a-z]?\)\s*\+\+\}/g, '');
871
+ // Leading citation fragments
872
+ text = text.replace(/\{\+\+\(?\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s*\+\+\}/gu, '');
873
+ // Semicolon-separated fragments
874
+ text = text.replace(/\{\+\+[;,]\s*\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?\+\+\}/gu, '');
875
+ // Year ranges with authors
876
+ text = text.replace(/\{\+\+\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?(?:[;,]\s*\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?)*\)\s*\+\+\}/gu, '');
877
+ text = text.replace(/\{\+\+\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?(?:[;,]\s*\p{Lu}\p{L}*(?:\s+et\s+al\.?)?\s+\d{4}[a-z]?)*\)\.\s*\+\+\}/gu, '');
878
+ // Clean up double spaces and orphaned punctuation
879
+ text = text.replace(/ +/g, ' ');
880
+ text = text.replace(/\s+\./g, '.');
881
+ text = text.replace(/\s+,/g, ',');
882
+ // Final cleanup - remove empty annotations
883
+ text = text.replace(/\{~~\s*~>\s*~~\}/g, '');
884
+ text = text.replace(/\{\+\+\s*\+\+\}/g, '');
885
+ text = text.replace(/\{--\s*--\}/g, '');
886
+ return text;
887
+ }
888
+ /**
889
+ * Strip markdown syntax to get plain text
890
+ */
891
+ function stripMarkdownSyntax(md) {
892
+ return md
893
+ .replace(/^---[\s\S]*?---\n*/m, '')
894
+ .replace(/^#{1,6}\s+/gm, '')
895
+ .replace(/(\*\*|__)(.*?)\1/g, '$2')
896
+ .replace(/(\*|_)(.*?)\1/g, '$2')
897
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
898
+ .replace(/!\[([^\]]*)\]\([^)]+\)/g, '')
899
+ .replace(/`([^`]+)`/g, '$1')
900
+ .replace(/```[\s\S]*?```/g, '')
901
+ .replace(/^>\s*/gm, '')
902
+ .replace(/^[-*_]{3,}\s*$/gm, '')
903
+ .replace(/^[\s]*[-*+]\s+/gm, '')
904
+ .replace(/^[\s]*\d+\.\s+/gm, '')
905
+ .replace(/\|/g, ' ')
906
+ .replace(/^[-:]+$/gm, '')
907
+ .replace(/\n{3,}/g, '\n\n')
908
+ .trim();
909
+ }
910
+ /**
911
+ * Generate annotated markdown by diffing original MD against Word text
912
+ */
913
+ export function generateAnnotatedDiff(originalMd, wordText, author = 'Reviewer') {
914
+ const normalizedOriginal = normalizeWhitespace(originalMd);
915
+ const normalizedWord = normalizeWhitespace(wordText);
916
+ const changes = diffWords(normalizedOriginal, normalizedWord);
917
+ let result = '';
918
+ for (const part of changes) {
919
+ if (part.added) {
920
+ result += `{++${part.value}++}`;
921
+ }
922
+ else if (part.removed) {
923
+ result += `{--${part.value}--}`;
924
+ }
925
+ else {
926
+ result += part.value;
927
+ }
928
+ }
929
+ return result;
930
+ }
931
+ /**
932
+ * Inject Word tables (extracted from XML) into pandoc text output
933
+ */
934
+ function injectWordTables(pandocText, wordTables) {
935
+ if (!wordTables || wordTables.length === 0) {
936
+ return pandocText;
937
+ }
938
+ let result = pandocText;
939
+ for (const table of wordTables) {
940
+ const firstLine = table.markdown.split('\n')[0];
941
+ const headerCells = firstLine
942
+ .split('|')
943
+ .map((c) => c.trim())
944
+ .filter((c) => c.length > 0);
945
+ if (headerCells.length === 0)
946
+ continue;
947
+ const firstCell = headerCells[0];
948
+ const startIdx = result.indexOf(firstCell);
949
+ if (startIdx === -1)
950
+ continue;
951
+ const lastLine = table.markdown.split('\n').pop();
952
+ const lastCells = lastLine
953
+ .split('|')
954
+ .map((c) => c.trim())
955
+ .filter((c) => c.length > 0);
956
+ const lastCell = lastCells[lastCells.length - 1] || lastCells[0];
957
+ const endIdx = result.indexOf(lastCell, startIdx);
958
+ if (endIdx === -1)
959
+ continue;
960
+ let regionStart = result.lastIndexOf('\n\n', startIdx);
961
+ if (regionStart === -1)
962
+ regionStart = 0;
963
+ else
964
+ regionStart += 2;
965
+ let regionEnd = result.indexOf('\n\n', endIdx + lastCell.length);
966
+ if (regionEnd === -1)
967
+ regionEnd = result.length;
968
+ result = result.slice(0, regionStart) + table.markdown + '\n\n' + result.slice(regionEnd);
969
+ }
970
+ return result;
971
+ }
972
+ /**
973
+ * Smart paragraph-level diff that preserves markdown structure
974
+ */
975
+ export function generateSmartDiff(originalMd, wordText, author = 'Reviewer', options = {}) {
976
+ const { wordTables = [], imageRegistry = null } = options;
977
+ // Inject Word tables into pandoc output
978
+ let wordTextWithTables = injectWordTables(wordText, wordTables);
979
+ // Protect markdown tables
980
+ const { text: mdWithTablesProtected, tables } = protectTables(originalMd);
981
+ // Also protect tables in Word text
982
+ const { text: wordWithTablesProtected, tables: wordTableBlocks } = protectTables(wordTextWithTables);
983
+ // Protect images
984
+ const { text: mdWithImagesProtected, images: origImages } = protectImages(mdWithTablesProtected, imageRegistry);
985
+ const { text: wordWithImagesProtected, images: wordImages } = protectImages(wordWithTablesProtected, imageRegistry);
986
+ // Match Word images to original images
987
+ const imageMapping = matchWordImagesToOriginal(origImages, wordImages, imageRegistry);
988
+ // Replace Word image placeholders with matching original placeholders
989
+ let wordWithMappedImages = wordWithImagesProtected;
990
+ for (const [wordPlaceholder, origPlaceholder] of imageMapping) {
991
+ wordWithMappedImages = wordWithMappedImages.split(wordPlaceholder).join(origPlaceholder);
992
+ }
993
+ // Protect figure/table anchors
994
+ const { text: mdWithAnchorsProtected, anchors: figAnchors } = protectAnchors(mdWithImagesProtected);
995
+ // Protect cross-references
996
+ const { text: mdWithXrefsProtected, crossrefs } = protectCrossrefs(mdWithAnchorsProtected);
997
+ // Protect math
998
+ const { text: mdWithMathProtected, mathBlocks } = protectMath(mdWithXrefsProtected);
999
+ // Protect citations
1000
+ const { text: mdProtected, citations } = protectCitations(mdWithMathProtected);
1001
+ // Replace rendered elements in Word text
1002
+ let wordProtected = wordWithMappedImages;
1003
+ wordProtected = replaceRenderedMath(wordProtected, mathBlocks);
1004
+ wordProtected = replaceRenderedCitations(wordProtected, citations.length);
1005
+ // Split into paragraphs
1006
+ const originalParas = mdProtected.split(/\n\n+/);
1007
+ const wordParas = wordProtected.split(/\n\n+/);
1008
+ const result = [];
1009
+ // Try to match paragraphs intelligently
1010
+ let wordIdx = 0;
1011
+ for (let i = 0; i < originalParas.length; i++) {
1012
+ const orig = originalParas[i] || '';
1013
+ const { prefix: mdPrefix, content: origContent } = extractMarkdownPrefix(orig.split('\n')[0]);
1014
+ // Find best matching word paragraph
1015
+ let bestMatch = -1;
1016
+ let bestScore = 0;
1017
+ for (let j = wordIdx; j < Math.min(wordIdx + 3, wordParas.length); j++) {
1018
+ const wordPara = wordParas[j] || '';
1019
+ const origWords = new Set(origContent.toLowerCase().split(/\s+/));
1020
+ const wordWords = wordPara.toLowerCase().split(/\s+/);
1021
+ const common = wordWords.filter((w) => origWords.has(w)).length;
1022
+ const score = common / Math.max(origWords.size, wordWords.length);
1023
+ if (score > bestScore && score > 0.3) {
1024
+ bestScore = score;
1025
+ bestMatch = j;
1026
+ }
1027
+ }
1028
+ if (bestMatch === -1) {
1029
+ if (mdPrefix && wordIdx < wordParas.length) {
1030
+ const wordPara = wordParas[wordIdx];
1031
+ if (wordPara.toLowerCase().includes(origContent.toLowerCase().slice(0, 20))) {
1032
+ bestMatch = wordIdx;
1033
+ }
1034
+ }
1035
+ }
1036
+ if (bestMatch >= 0) {
1037
+ const word = wordParas[bestMatch];
1038
+ const origStripped = stripMarkdownSyntax(orig);
1039
+ const wordNormalized = normalizeWhitespace(word);
1040
+ if (origStripped === wordNormalized) {
1041
+ result.push(orig);
1042
+ }
1043
+ else {
1044
+ const changes = diffWords(origStripped, wordNormalized);
1045
+ let annotated = mdPrefix;
1046
+ for (const part of changes) {
1047
+ if (part.added) {
1048
+ annotated += `{++${part.value}++}`;
1049
+ }
1050
+ else if (part.removed) {
1051
+ annotated += `{--${part.value}--}`;
1052
+ }
1053
+ else {
1054
+ annotated += part.value;
1055
+ }
1056
+ }
1057
+ result.push(annotated);
1058
+ }
1059
+ wordIdx = bestMatch + 1;
1060
+ }
1061
+ else {
1062
+ // Paragraph deleted entirely
1063
+ if (mdPrefix && mdPrefix.match(/^#{1,6}\s+/)) {
1064
+ result.push(orig);
1065
+ }
1066
+ else {
1067
+ result.push(`{--${orig}--}`);
1068
+ }
1069
+ }
1070
+ }
1071
+ // Any remaining word paragraphs are additions
1072
+ for (let j = wordIdx; j < wordParas.length; j++) {
1073
+ const word = wordParas[j];
1074
+ if (word.trim()) {
1075
+ result.push(`{++${word}++}`);
1076
+ }
1077
+ }
1078
+ // Restore protected content
1079
+ let finalResult = result.join('\n\n');
1080
+ finalResult = restoreCitations(finalResult, citations);
1081
+ finalResult = restoreMath(finalResult, mathBlocks);
1082
+ finalResult = restoreCrossrefs(finalResult, crossrefs);
1083
+ finalResult = restoreAnchors(finalResult, figAnchors);
1084
+ finalResult = restoreImages(finalResult, origImages);
1085
+ finalResult = restoreImages(finalResult, wordImages);
1086
+ finalResult = restoreTables(finalResult, tables);
1087
+ finalResult = restoreTables(finalResult, wordTableBlocks);
1088
+ return finalResult;
1089
+ }
1090
+ /**
1091
+ * Clean up redundant adjacent annotations
1092
+ */
1093
+ export function cleanupAnnotations(text) {
1094
+ // Convert adjacent delete+insert to substitution
1095
+ text = text.replace(/\{--(.+?)--\}\s*\{\+\+(.+?)\+\+\}/g, '{~~$1~>$2~~}');
1096
+ // Also handle insert+delete
1097
+ text = text.replace(/\{\+\+(.+?)\+\+\}\s*\{--(.+?)--\}/g, '{~~$2~>$1~~}');
1098
+ // Fix malformed patterns
1099
+ text = text.replace(/\{--([^}]+?)~>([^}]+?)~~\}/g, '{~~$1~>$2~~}');
1100
+ // Fix malformed substitutions that got split
1101
+ text = text.replace(/\{~~([^~]+)\s*--\}/g, '{--$1--}');
1102
+ text = text.replace(/\{\+\+([^+]+)~~\}/g, '{++$1++}');
1103
+ // Clean up empty annotations
1104
+ text = text.replace(/\{--\s*--\}/g, '');
1105
+ text = text.replace(/\{\+\+\s*\+\+\}/g, '');
1106
+ // Clean up double spaces in prose, but preserve table formatting
1107
+ const lines = text.split('\n');
1108
+ let inTable = false;
1109
+ const processedLines = lines.map((line, idx) => {
1110
+ const isSeparator = /^[-]+(\s+[-]+)+\s*$/.test(line.trim());
1111
+ const looksLikeTableRow = /\S+\s{2,}\S+/.test(line);
1112
+ if (isSeparator) {
1113
+ if (!inTable) {
1114
+ inTable = true;
1115
+ }
1116
+ return line;
1117
+ }
1118
+ if (inTable) {
1119
+ if (line.trim() === '') {
1120
+ let lookAhead = idx + 1;
1121
+ let foundTableContent = false;
1122
+ let foundEndSeparator = false;
1123
+ while (lookAhead < lines.length && lookAhead < idx + 20) {
1124
+ const nextLine = lines[lookAhead].trim();
1125
+ if (nextLine === '') {
1126
+ lookAhead++;
1127
+ continue;
1128
+ }
1129
+ if (/^[-]+(\s+[-]+)+\s*$/.test(nextLine)) {
1130
+ foundEndSeparator = true;
1131
+ break;
1132
+ }
1133
+ if (/\S+\s{2,}\S+/.test(nextLine)) {
1134
+ foundTableContent = true;
1135
+ break;
1136
+ }
1137
+ if (/^\*[^*]+\*\s*$/.test(nextLine)) {
1138
+ foundTableContent = true;
1139
+ break;
1140
+ }
1141
+ if (lines[lookAhead].startsWith(' ')) {
1142
+ lookAhead++;
1143
+ continue;
1144
+ }
1145
+ break;
1146
+ }
1147
+ if (foundTableContent || foundEndSeparator) {
1148
+ return line;
1149
+ }
1150
+ inTable = false;
1151
+ return line;
1152
+ }
1153
+ return line;
1154
+ }
1155
+ if (looksLikeTableRow) {
1156
+ let nextIdx = idx + 1;
1157
+ while (nextIdx < lines.length && lines[nextIdx].trim() === '') {
1158
+ nextIdx++;
1159
+ }
1160
+ if (nextIdx < lines.length && /^[-]+(\s+[-]+)+\s*$/.test(lines[nextIdx].trim())) {
1161
+ return line;
1162
+ }
1163
+ }
1164
+ if (line.trim().startsWith('|')) {
1165
+ return line;
1166
+ }
1167
+ return line.replace(/ +/g, ' ');
1168
+ });
1169
+ text = processedLines.join('\n');
1170
+ return text;
1171
+ }
1172
+ /**
1173
+ * Parse visible comment markers from Word text
1174
+ */
1175
+ export function parseVisibleComments(text) {
1176
+ const comments = [];
1177
+ const pattern = /\[([^\]:]+):\s*([^\]]+)\]/g;
1178
+ let match;
1179
+ while ((match = pattern.exec(text)) !== null) {
1180
+ comments.push({
1181
+ author: match[1].trim(),
1182
+ text: match[2].trim(),
1183
+ position: match.index,
1184
+ });
1185
+ }
1186
+ return comments;
1187
+ }
1188
+ /**
1189
+ * Convert visible comments to CriticMarkup format
1190
+ */
1191
+ export function convertVisibleComments(text) {
1192
+ return text.replace(/\[([^\]:]+):\s*([^\]]+)\]/g, '{>>$1: $2<<}');
1193
+ }
1194
+ /**
1195
+ * Restore pandoc-crossref figure/table references from Word-rendered format
1196
+ */
1197
+ export function restoreCrossrefFromWord(text, projectDir, restoredLabels = null) {
1198
+ const messages = [];
1199
+ let restored = 0;
1200
+ let result = text;
1201
+ const registry = readImageRegistry(projectDir);
1202
+ if (!restoredLabels) {
1203
+ restoredLabels = new Set();
1204
+ }
1205
+ // Pattern 1: [Figure]{.mark} [N]{.mark}
1206
+ result = result.replace(/\[(Figure|Table|Fig\.?)\]\{\.mark\}\s*\[(\d+|S\d+)\]\{\.mark\}/gi, (match, type, num) => {
1207
+ const prefix = type.toLowerCase().startsWith('tab') ? 'tbl' : 'fig';
1208
+ if (registry) {
1209
+ const entry = registry.byNumber?.get(`${prefix}:${num}`);
1210
+ if (entry && entry.label) {
1211
+ restored++;
1212
+ return `@${prefix}:${entry.label}`;
1213
+ }
1214
+ }
1215
+ restored++;
1216
+ messages.push(`Restored ${type} ${num} (no label found, using placeholder)`);
1217
+ return `@${prefix}:fig${num}`;
1218
+ });
1219
+ // Pattern 2: Plain "Figure N" or "Fig. N"
1220
+ result = result.replace(/(?<!!)\b(Figure|Fig\.?|Table|Tbl\.?)\s+(\d+|S\d+)\b(?!\s*:)/gi, (match, type, num) => {
1221
+ const prefix = type.toLowerCase().startsWith('tab') ? 'tbl' : 'fig';
1222
+ if (registry) {
1223
+ const entry = registry.byNumber?.get(`${prefix}:${num}`);
1224
+ if (entry && entry.label) {
1225
+ restored++;
1226
+ return `@${prefix}:${entry.label}`;
1227
+ }
1228
+ }
1229
+ return match;
1230
+ });
1231
+ // Pattern 3: Remove duplicate plain-text captions
1232
+ result = result.replace(/(\!\[[^\]]+\]\([^)]+\)(?:\{[^}]*\})?)\s*\n+\s*(?:Figure|Fig\.?|Table|Tbl\.?)\s+\d+[:\.]?\s*[^\n]+/gi, '$1');
1233
+ // Pattern 4: Clean up image captions that start with "Figure N: "
1234
+ result = result.replace(/!\[(Figure|Fig\.?|Table|Tbl\.?)\s+(\d+|S\d+)[:\.]?\s*([^\]]*)\]\(([^)]+)\)(?:\{[^}]*\})?/gi, (match, type, num, caption, imgPath) => {
1235
+ const prefix = type.toLowerCase().startsWith('tab') ? 'tbl' : 'fig';
1236
+ const labelKey = `${prefix}:${num}`;
1237
+ if (registry) {
1238
+ const entry = registry.byNumber?.get(labelKey);
1239
+ if (entry) {
1240
+ if (restoredLabels.has(labelKey)) {
1241
+ messages.push(`Skipped duplicate ${prefix}:${entry.label} (already restored)`);
1242
+ return `![${entry.caption}](${entry.path})`;
1243
+ }
1244
+ restoredLabels.add(labelKey);
1245
+ restored++;
1246
+ messages.push(`Restored image ${prefix}:${entry.label} from Figure ${num}`);
1247
+ return `![${entry.caption}](${entry.path}){#${prefix}:${entry.label}}`;
1248
+ }
1249
+ }
1250
+ const cleanCaption = caption.trim();
1251
+ return `![${cleanCaption}](${imgPath})`;
1252
+ });
1253
+ return { text: result, restored, messages, restoredLabels };
1254
+ }
1255
+ /**
1256
+ * Restore proper markdown image syntax from Word-extracted text using image registry
1257
+ */
1258
+ export function restoreImagesFromRegistry(text, projectDir, restoredLabels = null) {
1259
+ const messages = [];
1260
+ let restored = 0;
1261
+ const registry = readImageRegistry(projectDir);
1262
+ if (!registry || !registry.figures || registry.figures.length === 0) {
1263
+ return { text, restored: 0, messages: ['No image registry found'] };
1264
+ }
1265
+ if (!restoredLabels) {
1266
+ restoredLabels = new Set();
1267
+ }
1268
+ let result = text;
1269
+ // Pattern 1: Caption-like text
1270
+ const captionPatterns = [
1271
+ /@(fig|tbl):([a-zA-Z0-9_-]+):\s*([^\n]+)/gi,
1272
+ /^(Figure|Fig\.?)\s+(\d+|S\d+)[.:]\s*([^\n]+)/gim,
1273
+ /\|\s*@(fig|tbl):([a-zA-Z0-9_-]+):\s*([^|]+)\s*\|/gi,
1274
+ ];
1275
+ // Fix @fig:label: caption patterns
1276
+ result = result.replace(captionPatterns[0], (match, type, label, caption) => {
1277
+ const key = `${type}:${label}`;
1278
+ const entry = registry.byLabel.get(key);
1279
+ if (entry) {
1280
+ if (restoredLabels.has(key)) {
1281
+ messages.push(`Skipped duplicate ${key} (already restored)`);
1282
+ return `![${entry.caption}](${entry.path})`;
1283
+ }
1284
+ restoredLabels.add(key);
1285
+ restored++;
1286
+ messages.push(`Restored ${type}:${label} from registry`);
1287
+ return `![${entry.caption}](${entry.path}){#${type}:${label}}`;
1288
+ }
1289
+ return match;
1290
+ });
1291
+ // Fix table-wrapped captions
1292
+ result = result.replace(captionPatterns[2], (match, type, label, caption) => {
1293
+ const key = `${type}:${label}`;
1294
+ const entry = registry.byLabel.get(key);
1295
+ if (entry) {
1296
+ if (restoredLabels.has(key)) {
1297
+ messages.push(`Skipped duplicate ${key} from table wrapper`);
1298
+ return `![${entry.caption}](${entry.path})`;
1299
+ }
1300
+ restoredLabels.add(key);
1301
+ restored++;
1302
+ messages.push(`Restored ${type}:${label} from table wrapper`);
1303
+ return `![${entry.caption}](${entry.path}){#${type}:${label}}`;
1304
+ }
1305
+ return match;
1306
+ });
1307
+ // Clean up empty table structures
1308
+ result = result.replace(/\|\s*\|\s*\n\|:--:\|\s*\n/g, '');
1309
+ // Fix "Figure N:" standalone lines
1310
+ result = result.replace(captionPatterns[1], (match, prefix, num, caption) => {
1311
+ const numKey = `fig:${num}`;
1312
+ const entry = registry.byNumber.get(numKey);
1313
+ if (entry) {
1314
+ const labelKey = `fig:${entry.label}`;
1315
+ if (restoredLabels.has(labelKey)) {
1316
+ messages.push(`Skipped duplicate Figure ${num} (already restored)`);
1317
+ return `![${entry.caption}](${entry.path})`;
1318
+ }
1319
+ restoredLabels.add(labelKey);
1320
+ restored++;
1321
+ messages.push(`Restored Figure ${num} by number lookup`);
1322
+ return `![${entry.caption}](${entry.path}){#fig:${entry.label}}`;
1323
+ }
1324
+ return match;
1325
+ });
1326
+ // Fix generic media paths by matching caption text
1327
+ const genericImagePattern = /!\[([^\]]*)\]\(media\/[^)]+\)/g;
1328
+ result = result.replace(genericImagePattern, (match, caption) => {
1329
+ if (!caption || caption.trim() === '') {
1330
+ return match;
1331
+ }
1332
+ const captionKey = caption.slice(0, 50).toLowerCase().trim();
1333
+ const entry = registry.byCaption.get(captionKey);
1334
+ if (entry) {
1335
+ const labelKey = entry.label ? `${entry.type}:${entry.label}` : null;
1336
+ if (labelKey && restoredLabels.has(labelKey)) {
1337
+ messages.push(`Skipped duplicate by caption match: ${captionKey.slice(0, 30)}...`);
1338
+ return `![${entry.caption}](${entry.path})`;
1339
+ }
1340
+ if (labelKey) {
1341
+ restoredLabels.add(labelKey);
1342
+ }
1343
+ restored++;
1344
+ messages.push(`Restored image by caption match: ${captionKey.slice(0, 30)}...`);
1345
+ const anchor = (entry.label && !restoredLabels.has(labelKey)) ? `{#${entry.type}:${entry.label}}` : '';
1346
+ return `![${entry.caption}](${entry.path})${anchor}`;
1347
+ }
1348
+ return match;
1349
+ });
1350
+ return { text: result, restored, messages };
1351
+ }
1352
+ /**
1353
+ * Import Word document with track changes directly as CriticMarkup
1354
+ */
1355
+ export async function importWordWithTrackChanges(docxPath, options = {}) {
1356
+ const { mediaDir, projectDir } = options;
1357
+ const docxDir = path.dirname(docxPath);
1358
+ const targetMediaDir = mediaDir || path.join(docxDir, 'media');
1359
+ const targetProjectDir = projectDir || docxDir;
1360
+ const registry = readImageRegistry(targetProjectDir);
1361
+ const hasRegistry = registry && registry.figures && registry.figures.length > 0;
1362
+ // First pass: count images
1363
+ const { stdout: rawText } = await execAsync(`pandoc "${docxPath}" -t markdown --wrap=none --track-changes=all`, { maxBuffer: 50 * 1024 * 1024 });
1364
+ const wordImageCount = (rawText.match(/!\[[^\]]*\]\(media\/[^)]+\)/g) || []).length;
1365
+ const registryCount = hasRegistry ? registry.figures.length : 0;
1366
+ const needsMediaExtraction = wordImageCount > registryCount;
1367
+ if (hasRegistry) {
1368
+ console.log(`Registry has ${registryCount} figures, Word doc has ${wordImageCount} images`);
1369
+ if (needsMediaExtraction) {
1370
+ console.log(`Extracting media (${wordImageCount - registryCount} new image(s) detected)`);
1371
+ }
1372
+ else {
1373
+ console.log(`Using existing figures from registry`);
1374
+ }
1375
+ }
1376
+ // Extract from Word
1377
+ const extracted = await extractFromWord(docxPath, {
1378
+ mediaDir: targetMediaDir,
1379
+ skipMediaExtraction: !needsMediaExtraction,
1380
+ });
1381
+ let text = extracted.text;
1382
+ const extractedMedia = extracted.extractedMedia || [];
1383
+ const comments = extracted.comments || [];
1384
+ const anchors = extracted.anchors || new Map();
1385
+ // Log messages
1386
+ for (const msg of extracted.messages || []) {
1387
+ if (msg.type === 'info') {
1388
+ console.log(msg.message);
1389
+ }
1390
+ else if (msg.type === 'warning') {
1391
+ console.warn(`Warning: ${msg.message}`);
1392
+ }
1393
+ }
1394
+ // Restore crossref
1395
+ const crossrefResult = restoreCrossrefFromWord(text, targetProjectDir);
1396
+ text = crossrefResult.text;
1397
+ if (crossrefResult.restored > 0) {
1398
+ console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
1399
+ }
1400
+ // Restore images
1401
+ const imageRestoreResult = restoreImagesFromRegistry(text, targetProjectDir, crossrefResult.restoredLabels);
1402
+ text = imageRestoreResult.text;
1403
+ if (imageRestoreResult.restored > 0) {
1404
+ console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
1405
+ }
1406
+ // Insert comments
1407
+ if (comments.length > 0) {
1408
+ text = insertCommentsIntoMarkdown(text, comments, anchors);
1409
+ console.log(`Inserted ${comments.length} comment(s)`);
1410
+ }
1411
+ // Clean up
1412
+ text = cleanupAnnotations(text);
1413
+ // Count final changes
1414
+ const insertions = (text.match(/\{\+\+/g) || []).length;
1415
+ const deletions = (text.match(/\{--/g) || []).length;
1416
+ const substitutions = (text.match(/\{~~/g) || []).length;
1417
+ const commentCount = (text.match(/\{>>/g) || []).length;
1418
+ return {
1419
+ text,
1420
+ stats: {
1421
+ insertions,
1422
+ deletions,
1423
+ substitutions,
1424
+ comments: commentCount,
1425
+ total: insertions + deletions + substitutions + commentCount,
1426
+ hasTrackChanges: extracted.hasTrackChanges,
1427
+ trackChangeStats: extracted.trackChangeStats,
1428
+ },
1429
+ extractedMedia,
1430
+ comments,
1431
+ };
1432
+ }
1433
+ /**
1434
+ * Legacy import function: Word doc → annotated MD via diff
1435
+ */
1436
+ export async function importFromWord(docxPath, originalMdPath, options = {}) {
1437
+ const { author = 'Reviewer', sectionContent, figuresDir } = options;
1438
+ const projectDir = path.dirname(originalMdPath);
1439
+ let wordText;
1440
+ let extractedMedia = [];
1441
+ let wordTables = options.wordTables || [];
1442
+ let hasTrackChanges = false;
1443
+ if (sectionContent !== undefined) {
1444
+ let annotated = cleanupAnnotations(sectionContent);
1445
+ const insertions = (annotated.match(/\{\+\+/g) || []).length;
1446
+ const deletions = (annotated.match(/\{--/g) || []).length;
1447
+ const substitutions = (annotated.match(/\{~~/g) || []).length;
1448
+ const commentCount = (annotated.match(/\{>>/g) || []).length;
1449
+ return {
1450
+ annotated,
1451
+ stats: {
1452
+ insertions,
1453
+ deletions,
1454
+ substitutions,
1455
+ comments: commentCount,
1456
+ total: insertions + deletions + substitutions + commentCount,
1457
+ },
1458
+ extractedMedia: [],
1459
+ };
1460
+ }
1461
+ else {
1462
+ const docxDir = path.dirname(docxPath);
1463
+ const mediaDir = figuresDir || docxDir;
1464
+ const extracted = await extractFromWord(docxPath, { mediaDir });
1465
+ wordText = extracted.text;
1466
+ extractedMedia = extracted.extractedMedia || [];
1467
+ wordTables = extracted.tables || [];
1468
+ hasTrackChanges = extracted.hasTrackChanges || false;
1469
+ for (const msg of extracted.messages || []) {
1470
+ if (msg.type === 'info') {
1471
+ console.log(msg.message);
1472
+ }
1473
+ else if (msg.type === 'warning') {
1474
+ console.warn(`Warning: ${msg.message}`);
1475
+ }
1476
+ }
1477
+ if (hasTrackChanges) {
1478
+ const crossrefResult = restoreCrossrefFromWord(wordText, projectDir);
1479
+ wordText = crossrefResult.text;
1480
+ if (crossrefResult.restored > 0) {
1481
+ console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
1482
+ }
1483
+ const imageRestoreResult = restoreImagesFromRegistry(wordText, projectDir, crossrefResult.restoredLabels);
1484
+ wordText = imageRestoreResult.text;
1485
+ if (imageRestoreResult.restored > 0) {
1486
+ console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
1487
+ }
1488
+ const comments = extracted.comments || [];
1489
+ const anchors = extracted.anchors || new Map();
1490
+ if (comments.length > 0) {
1491
+ wordText = insertCommentsIntoMarkdown(wordText, comments, anchors);
1492
+ console.log(`Inserted ${comments.length} comment(s)`);
1493
+ }
1494
+ wordText = cleanupAnnotations(wordText);
1495
+ const insertions = (wordText.match(/\{\+\+/g) || []).length;
1496
+ const deletions = (wordText.match(/\{--/g) || []).length;
1497
+ const substitutions = (wordText.match(/\{~~/g) || []).length;
1498
+ const commentCount = (wordText.match(/\{>>/g) || []).length;
1499
+ return {
1500
+ annotated: wordText,
1501
+ stats: {
1502
+ insertions,
1503
+ deletions,
1504
+ substitutions,
1505
+ comments: commentCount,
1506
+ total: insertions + deletions + substitutions + commentCount,
1507
+ },
1508
+ extractedMedia,
1509
+ };
1510
+ }
1511
+ console.warn('Warning: No track changes detected in Word document.');
1512
+ console.warn(' For best results, reviewers should use Track Changes in Word.');
1513
+ console.warn(' Falling back to diff-based import (comparing against original MD).');
1514
+ console.warn(' This approach may produce less accurate change annotations.');
1515
+ const crossrefResult = restoreCrossrefFromWord(wordText, projectDir);
1516
+ wordText = crossrefResult.text;
1517
+ if (crossrefResult.restored > 0) {
1518
+ console.log(`Restored ${crossrefResult.restored} crossref reference(s)`);
1519
+ }
1520
+ const imageRestoreResult = restoreImagesFromRegistry(wordText, projectDir, crossrefResult.restoredLabels);
1521
+ wordText = imageRestoreResult.text;
1522
+ if (imageRestoreResult.restored > 0) {
1523
+ console.log(`Restored ${imageRestoreResult.restored} image(s) from registry`);
1524
+ }
1525
+ }
1526
+ // Read original markdown
1527
+ let originalMd = fs.readFileSync(originalMdPath, 'utf-8');
1528
+ // Strip existing annotations
1529
+ originalMd = stripAnnotations(originalMd, { keepComments: false });
1530
+ // Load image registry
1531
+ const imageRegistry = readImageRegistry(projectDir);
1532
+ // Generate diff
1533
+ let annotated = generateSmartDiff(originalMd, wordText, author, { wordTables, imageRegistry });
1534
+ // Clean up
1535
+ annotated = cleanupAnnotations(annotated);
1536
+ // Fix citation annotations
1537
+ annotated = fixCitationAnnotations(annotated, originalMd);
1538
+ // Convert visible comments
1539
+ annotated = convertVisibleComments(annotated);
1540
+ // Count changes
1541
+ const insertions = (annotated.match(/\{\+\+/g) || []).length;
1542
+ const deletions = (annotated.match(/\{--/g) || []).length;
1543
+ const substitutions = (annotated.match(/\{~~/g) || []).length;
1544
+ const comments = (annotated.match(/\{>>/g) || []).length;
1545
+ return {
1546
+ annotated,
1547
+ stats: {
1548
+ insertions,
1549
+ deletions,
1550
+ substitutions,
1551
+ comments,
1552
+ total: insertions + deletions + substitutions + comments,
1553
+ },
1554
+ extractedMedia,
1555
+ };
1556
+ }
1557
+ /**
1558
+ * Move extracted media files to a figures directory with better names
1559
+ */
1560
+ export function moveExtractedMedia(mediaFiles, figuresDir, prefix = 'figure') {
1561
+ const moved = [];
1562
+ const errors = [];
1563
+ if (!fs.existsSync(figuresDir)) {
1564
+ fs.mkdirSync(figuresDir, { recursive: true });
1565
+ }
1566
+ for (let i = 0; i < mediaFiles.length; i++) {
1567
+ const src = mediaFiles[i];
1568
+ const ext = path.extname(src).toLowerCase();
1569
+ const newName = `${prefix}${i + 1}${ext}`;
1570
+ const dest = path.join(figuresDir, newName);
1571
+ try {
1572
+ fs.copyFileSync(src, dest);
1573
+ moved.push({ from: src, to: dest, name: newName });
1574
+ }
1575
+ catch (err) {
1576
+ errors.push(`Failed to copy ${src}: ${err.message}`);
1577
+ }
1578
+ }
1579
+ return { moved, errors };
1580
+ }
1581
+ //# sourceMappingURL=import.js.map