docrev 0.11.1 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +202 -197
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -433
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/build.d.ts +28 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +81 -4
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/utilities.js +164 -164
  15. package/dist/lib/commands/word-tools.js +8 -8
  16. package/dist/lib/grammar.js +3 -3
  17. package/dist/lib/macro-filter.lua +201 -201
  18. package/dist/lib/pdf-comments.js +44 -44
  19. package/dist/lib/plugins.js +57 -57
  20. package/dist/lib/pptx-color-filter.lua +37 -37
  21. package/dist/lib/pptx-themes.js +115 -115
  22. package/dist/lib/schema.d.ts.map +1 -1
  23. package/dist/lib/schema.js +8 -2
  24. package/dist/lib/schema.js.map +1 -1
  25. package/dist/lib/spelling.js +2 -2
  26. package/dist/lib/templates.js +387 -387
  27. package/dist/lib/themes.js +51 -51
  28. package/eslint.config.js +27 -27
  29. package/lib/anchor-match.ts +307 -307
  30. package/lib/annotations.ts +664 -664
  31. package/lib/build.ts +2047 -1956
  32. package/lib/citations.ts +160 -160
  33. package/lib/commands/build.ts +885 -885
  34. package/lib/commands/citations.ts +515 -515
  35. package/lib/commands/comments.ts +1050 -1050
  36. package/lib/commands/context.ts +176 -176
  37. package/lib/commands/core.ts +309 -309
  38. package/lib/commands/doi.ts +451 -451
  39. package/lib/commands/file-ops.ts +372 -372
  40. package/lib/commands/history.ts +320 -320
  41. package/lib/commands/index.ts +87 -87
  42. package/lib/commands/init.ts +259 -259
  43. package/lib/commands/merge-resolve.ts +378 -378
  44. package/lib/commands/preview.ts +178 -178
  45. package/lib/commands/project-info.ts +244 -244
  46. package/lib/commands/quality.ts +517 -517
  47. package/lib/commands/response.ts +454 -454
  48. package/lib/commands/section-boundaries.ts +82 -82
  49. package/lib/commands/sections.ts +451 -451
  50. package/lib/commands/sync.ts +689 -689
  51. package/lib/commands/text-ops.ts +449 -449
  52. package/lib/commands/utilities.ts +448 -448
  53. package/lib/commands/verify-anchors.ts +272 -272
  54. package/lib/commands/word-tools.ts +340 -340
  55. package/lib/comment-realign.ts +99 -99
  56. package/lib/config.ts +84 -84
  57. package/lib/crossref.ts +781 -781
  58. package/lib/csl.ts +191 -191
  59. package/lib/dependencies.ts +132 -132
  60. package/lib/diff-engine.ts +465 -465
  61. package/lib/doi-cache.ts +115 -115
  62. package/lib/doi.ts +879 -879
  63. package/lib/equations.ts +506 -506
  64. package/lib/errors.ts +350 -350
  65. package/lib/format.ts +541 -541
  66. package/lib/git.ts +326 -326
  67. package/lib/grammar.ts +303 -303
  68. package/lib/image-registry.ts +180 -180
  69. package/lib/import.ts +906 -906
  70. package/lib/journals.ts +543 -543
  71. package/lib/macro-filter.lua +201 -201
  72. package/lib/macros.ts +273 -273
  73. package/lib/merge.ts +633 -633
  74. package/lib/ooxml.ts +768 -768
  75. package/lib/orcid.ts +144 -144
  76. package/lib/pdf-comments.ts +263 -263
  77. package/lib/pdf-import.ts +524 -524
  78. package/lib/plugins.ts +362 -362
  79. package/lib/postprocess.ts +188 -188
  80. package/lib/pptx-color-filter.lua +37 -37
  81. package/lib/pptx-template.ts +469 -469
  82. package/lib/pptx-themes.ts +483 -483
  83. package/lib/protect-restore.ts +520 -520
  84. package/lib/rate-limiter.ts +127 -127
  85. package/lib/response.ts +197 -197
  86. package/lib/restore-references.ts +240 -240
  87. package/lib/review.ts +327 -327
  88. package/lib/schema.ts +494 -488
  89. package/lib/scientific-words.ts +73 -73
  90. package/lib/sections.ts +428 -428
  91. package/lib/slides.ts +756 -756
  92. package/lib/spelling.ts +334 -334
  93. package/lib/templates.ts +526 -526
  94. package/lib/themes.ts +742 -742
  95. package/lib/trackchanges.ts +166 -166
  96. package/lib/tui.ts +450 -450
  97. package/lib/types.ts +546 -546
  98. package/lib/undo.ts +250 -250
  99. package/lib/utils.ts +69 -69
  100. package/lib/variables.ts +179 -179
  101. package/lib/word-extraction.ts +525 -525
  102. package/lib/word.ts +526 -526
  103. package/lib/wordcomments.ts +789 -789
  104. package/package.json +1 -1
  105. package/scripts/postbuild.js +47 -47
  106. package/skill/REFERENCE.md +550 -550
  107. package/skill/SKILL.md +302 -302
  108. package/tsconfig.json +26 -26
  109. package/types/index.d.ts +531 -531
  110. package/issues.md +0 -180
  111. package/site/assets/extra.css +0 -208
  112. package/site/commands.html +0 -926
  113. package/site/configuration.html +0 -469
  114. package/site/index.html +0 -288
  115. package/site/troubleshooting.html +0 -461
  116. package/site/workflow.html +0 -518
@@ -1,340 +1,340 @@
1
- /**
2
- * Word document tool commands: annotate, apply, comment
3
- *
4
- * Commands for working with Word documents directly (comments, track changes).
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- getUserName,
14
- parseAnnotations,
15
- } from './context.js';
16
-
17
- // Options interfaces
18
- interface AnnotateOptions {
19
- message?: string;
20
- search?: string;
21
- author?: string;
22
- }
23
-
24
- interface ApplyOptions {
25
- author?: string;
26
- }
27
-
28
- interface CommentOptions {
29
- author?: string;
30
- }
31
-
32
- /**
33
- * Register word-tools commands with the program
34
- */
35
- export function register(program: Command): void {
36
- // ==========================================================================
37
- // ANNOTATE command - Add comments to Word document
38
- // ==========================================================================
39
-
40
- program
41
- .command('annotate')
42
- .description('Add comment to Word document')
43
- .argument('<docx>', 'Word document')
44
- .option('-m, --message <text>', 'Comment text')
45
- .option('-s, --search <text>', 'Text to attach comment to')
46
- .option('-a, --author <name>', 'Comment author')
47
- .action(async (docxPath: string, options: AnnotateOptions) => {
48
- if (!fs.existsSync(docxPath)) {
49
- console.error(chalk.red(`File not found: ${docxPath}`));
50
- process.exit(1);
51
- }
52
-
53
- if (!options.message) {
54
- console.error(chalk.red('Comment message required (-m)'));
55
- process.exit(1);
56
- }
57
-
58
- const { default: AdmZip } = await import('adm-zip');
59
- const zip = new AdmZip(docxPath);
60
-
61
- // Read document.xml
62
- const docEntry = zip.getEntry('word/document.xml');
63
- if (!docEntry) {
64
- console.error(chalk.red('Invalid Word document'));
65
- process.exit(1);
66
- }
67
-
68
- let docXml = zip.readAsText(docEntry);
69
-
70
- // Read or create comments.xml
71
- let commentsEntry = zip.getEntry('word/comments.xml');
72
- let commentsXml: string;
73
- let nextCommentId = 1;
74
-
75
- if (commentsEntry) {
76
- commentsXml = zip.readAsText(commentsEntry);
77
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
- for (const m of idMatches) {
79
- const id = parseInt(m.match(/\d+/)![0]);
80
- if (id >= nextCommentId) nextCommentId = id + 1;
81
- }
82
- } else {
83
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
- </w:comments>`;
86
- }
87
-
88
- const author = options.author || getUserName() || 'Claude';
89
- const date = new Date().toISOString();
90
- const commentId = nextCommentId;
91
-
92
- // Add comment to comments.xml
93
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
- <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
- </w:comment>`;
96
-
97
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
-
99
- // Find text and add comment markers
100
- if (options.search) {
101
- const searchText = options.search;
102
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
-
104
- if (textPattern.test(docXml)) {
105
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
- });
108
- } else {
109
- console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
- }
111
- }
112
-
113
- // Update zip
114
- zip.updateFile('word/document.xml', Buffer.from(docXml));
115
-
116
- if (commentsEntry) {
117
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
- } else {
119
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
-
121
- // Update [Content_Types].xml
122
- const ctEntry = zip.getEntry('[Content_Types].xml');
123
- if (ctEntry) {
124
- let ctXml = zip.readAsText(ctEntry);
125
- if (!ctXml.includes('comments.xml')) {
126
- ctXml = ctXml.replace('</Types>',
127
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
- }
130
- }
131
-
132
- // Update document.xml.rels
133
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
- if (relsEntry) {
135
- let relsXml = zip.readAsText(relsEntry);
136
- if (!relsXml.includes('comments.xml')) {
137
- const newRelId = `rId${Date.now()}`;
138
- relsXml = relsXml.replace('</Relationships>',
139
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
- }
142
- }
143
- }
144
-
145
- // Write back
146
- zip.writeZip(docxPath);
147
- console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
- });
149
-
150
- // ==========================================================================
151
- // APPLY command - Apply MD annotations as Word track changes
152
- // ==========================================================================
153
-
154
- program
155
- .command('apply')
156
- .description('Apply markdown annotations to Word document as track changes')
157
- .argument('<md>', 'Markdown file with annotations')
158
- .argument('<docx>', 'Output Word document')
159
- .option('-a, --author <name>', 'Author name for track changes')
160
- .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
- if (!fs.existsSync(mdPath)) {
162
- console.error(chalk.red(`File not found: ${mdPath}`));
163
- process.exit(1);
164
- }
165
-
166
- const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
- const annotations = parseAnnotations(mdContent);
168
-
169
- if (annotations.length === 0) {
170
- console.log(chalk.yellow('No annotations found in markdown file'));
171
- }
172
-
173
- const author = options.author || getUserName() || 'Author';
174
-
175
- // Build document with track changes
176
- const { buildWithTrackChanges } = await import('../trackchanges.js');
177
-
178
- try {
179
- const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
-
181
- if (result.success) {
182
- console.log(fmt.status('success', result.message));
183
- console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
- } else {
185
- console.error(chalk.red(result.message));
186
- process.exit(1);
187
- }
188
- } catch (err) {
189
- console.error(chalk.red(`Error: ${(err as Error).message}`));
190
- process.exit(1);
191
- }
192
- });
193
-
194
- // ==========================================================================
195
- // COMMENT command - Interactive comment addition to DOCX
196
- // ==========================================================================
197
-
198
- program
199
- .command('comment')
200
- .description('Add comments to Word document interactively')
201
- .argument('<docx>', 'Word document')
202
- .option('-a, --author <name>', 'Comment author')
203
- .action(async (docxPath: string, options: CommentOptions) => {
204
- if (!fs.existsSync(docxPath)) {
205
- console.error(chalk.red(`File not found: ${docxPath}`));
206
- process.exit(1);
207
- }
208
-
209
- const { default: AdmZip } = await import('adm-zip');
210
- const readline = await import('readline');
211
- const rl = readline.createInterface({
212
- input: process.stdin,
213
- output: process.stdout,
214
- });
215
-
216
- const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
-
218
- const author = options.author || getUserName() || 'Reviewer';
219
-
220
- console.log(fmt.header('Interactive Comment Mode'));
221
- console.log(chalk.dim(` Document: ${docxPath}`));
222
- console.log(chalk.dim(` Author: ${author}`));
223
- console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
- console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
-
226
- let commentsAdded = 0;
227
-
228
- while (true) {
229
- const message = await ask(chalk.cyan('Comment: '));
230
-
231
- if (!message.trim()) {
232
- break;
233
- }
234
-
235
- const searchText = await ask(chalk.cyan('Attach to text: '));
236
-
237
- // Load document fresh each time
238
- const zip = new AdmZip(docxPath);
239
- const docEntry = zip.getEntry('word/document.xml');
240
-
241
- if (!docEntry) {
242
- console.error(chalk.red('Invalid Word document'));
243
- rl.close();
244
- process.exit(1);
245
- }
246
-
247
- let docXml = zip.readAsText(docEntry);
248
-
249
- // Read or create comments.xml
250
- let commentsEntry = zip.getEntry('word/comments.xml');
251
- let commentsXml: string;
252
- let nextCommentId = 1;
253
-
254
- if (commentsEntry) {
255
- commentsXml = zip.readAsText(commentsEntry);
256
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
- for (const m of idMatches) {
258
- const id = parseInt(m.match(/\d+/)![0]);
259
- if (id >= nextCommentId) nextCommentId = id + 1;
260
- }
261
- } else {
262
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
- </w:comments>`;
265
- }
266
-
267
- const date = new Date().toISOString();
268
- const commentId = nextCommentId;
269
-
270
- // Add comment to comments.xml
271
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
- <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
- </w:comment>`;
274
-
275
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
-
277
- // Find text and add comment markers
278
- if (searchText.trim()) {
279
- const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
-
282
- if (textPattern.test(docXml)) {
283
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
- });
286
- console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
- } else {
288
- console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
- }
290
- } else {
291
- console.log(chalk.dim(` Comment added without anchor.`));
292
- }
293
-
294
- // Update zip
295
- zip.updateFile('word/document.xml', Buffer.from(docXml));
296
-
297
- if (commentsEntry) {
298
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
- } else {
300
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
-
302
- // Update [Content_Types].xml
303
- const ctEntry = zip.getEntry('[Content_Types].xml');
304
- if (ctEntry) {
305
- let ctXml = zip.readAsText(ctEntry);
306
- if (!ctXml.includes('comments.xml')) {
307
- ctXml = ctXml.replace('</Types>',
308
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
- }
311
- }
312
-
313
- // Update document.xml.rels
314
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
- if (relsEntry) {
316
- let relsXml = zip.readAsText(relsEntry);
317
- if (!relsXml.includes('comments.xml')) {
318
- const newRelId = `rId${Date.now()}`;
319
- relsXml = relsXml.replace('</Relationships>',
320
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
- }
323
- }
324
- }
325
-
326
- zip.writeZip(docxPath);
327
- commentsAdded++;
328
- console.log();
329
- }
330
-
331
- rl.close();
332
- console.log();
333
-
334
- if (commentsAdded > 0) {
335
- console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
- } else {
337
- console.log(chalk.dim('No comments added.'));
338
- }
339
- });
340
- }
1
+ /**
2
+ * Word document tool commands: annotate, apply, comment
3
+ *
4
+ * Commands for working with Word documents directly (comments, track changes).
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ getUserName,
14
+ parseAnnotations,
15
+ } from './context.js';
16
+
17
+ // Options interfaces
18
+ interface AnnotateOptions {
19
+ message?: string;
20
+ search?: string;
21
+ author?: string;
22
+ }
23
+
24
+ interface ApplyOptions {
25
+ author?: string;
26
+ }
27
+
28
+ interface CommentOptions {
29
+ author?: string;
30
+ }
31
+
32
+ /**
33
+ * Register word-tools commands with the program
34
+ */
35
+ export function register(program: Command): void {
36
+ // ==========================================================================
37
+ // ANNOTATE command - Add comments to Word document
38
+ // ==========================================================================
39
+
40
+ program
41
+ .command('annotate')
42
+ .description('Add comment to Word document')
43
+ .argument('<docx>', 'Word document')
44
+ .option('-m, --message <text>', 'Comment text')
45
+ .option('-s, --search <text>', 'Text to attach comment to')
46
+ .option('-a, --author <name>', 'Comment author')
47
+ .action(async (docxPath: string, options: AnnotateOptions) => {
48
+ if (!fs.existsSync(docxPath)) {
49
+ console.error(chalk.red(`File not found: ${docxPath}`));
50
+ process.exit(1);
51
+ }
52
+
53
+ if (!options.message) {
54
+ console.error(chalk.red('Comment message required (-m)'));
55
+ process.exit(1);
56
+ }
57
+
58
+ const { default: AdmZip } = await import('adm-zip');
59
+ const zip = new AdmZip(docxPath);
60
+
61
+ // Read document.xml
62
+ const docEntry = zip.getEntry('word/document.xml');
63
+ if (!docEntry) {
64
+ console.error(chalk.red('Invalid Word document'));
65
+ process.exit(1);
66
+ }
67
+
68
+ let docXml = zip.readAsText(docEntry);
69
+
70
+ // Read or create comments.xml
71
+ let commentsEntry = zip.getEntry('word/comments.xml');
72
+ let commentsXml: string;
73
+ let nextCommentId = 1;
74
+
75
+ if (commentsEntry) {
76
+ commentsXml = zip.readAsText(commentsEntry);
77
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
+ for (const m of idMatches) {
79
+ const id = parseInt(m.match(/\d+/)![0]);
80
+ if (id >= nextCommentId) nextCommentId = id + 1;
81
+ }
82
+ } else {
83
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
+ </w:comments>`;
86
+ }
87
+
88
+ const author = options.author || getUserName() || 'Claude';
89
+ const date = new Date().toISOString();
90
+ const commentId = nextCommentId;
91
+
92
+ // Add comment to comments.xml
93
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
+ <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
+ </w:comment>`;
96
+
97
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
+
99
+ // Find text and add comment markers
100
+ if (options.search) {
101
+ const searchText = options.search;
102
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
+
104
+ if (textPattern.test(docXml)) {
105
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
+ });
108
+ } else {
109
+ console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
+ }
111
+ }
112
+
113
+ // Update zip
114
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
115
+
116
+ if (commentsEntry) {
117
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
+ } else {
119
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
+
121
+ // Update [Content_Types].xml
122
+ const ctEntry = zip.getEntry('[Content_Types].xml');
123
+ if (ctEntry) {
124
+ let ctXml = zip.readAsText(ctEntry);
125
+ if (!ctXml.includes('comments.xml')) {
126
+ ctXml = ctXml.replace('</Types>',
127
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
+ }
130
+ }
131
+
132
+ // Update document.xml.rels
133
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
+ if (relsEntry) {
135
+ let relsXml = zip.readAsText(relsEntry);
136
+ if (!relsXml.includes('comments.xml')) {
137
+ const newRelId = `rId${Date.now()}`;
138
+ relsXml = relsXml.replace('</Relationships>',
139
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
+ }
142
+ }
143
+ }
144
+
145
+ // Write back
146
+ zip.writeZip(docxPath);
147
+ console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
+ });
149
+
150
+ // ==========================================================================
151
+ // APPLY command - Apply MD annotations as Word track changes
152
+ // ==========================================================================
153
+
154
+ program
155
+ .command('apply')
156
+ .description('Apply markdown annotations to Word document as track changes')
157
+ .argument('<md>', 'Markdown file with annotations')
158
+ .argument('<docx>', 'Output Word document')
159
+ .option('-a, --author <name>', 'Author name for track changes')
160
+ .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
+ if (!fs.existsSync(mdPath)) {
162
+ console.error(chalk.red(`File not found: ${mdPath}`));
163
+ process.exit(1);
164
+ }
165
+
166
+ const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
+ const annotations = parseAnnotations(mdContent);
168
+
169
+ if (annotations.length === 0) {
170
+ console.log(chalk.yellow('No annotations found in markdown file'));
171
+ }
172
+
173
+ const author = options.author || getUserName() || 'Author';
174
+
175
+ // Build document with track changes
176
+ const { buildWithTrackChanges } = await import('../trackchanges.js');
177
+
178
+ try {
179
+ const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
+
181
+ if (result.success) {
182
+ console.log(fmt.status('success', result.message));
183
+ console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
+ } else {
185
+ console.error(chalk.red(result.message));
186
+ process.exit(1);
187
+ }
188
+ } catch (err) {
189
+ console.error(chalk.red(`Error: ${(err as Error).message}`));
190
+ process.exit(1);
191
+ }
192
+ });
193
+
194
+ // ==========================================================================
195
+ // COMMENT command - Interactive comment addition to DOCX
196
+ // ==========================================================================
197
+
198
+ program
199
+ .command('comment')
200
+ .description('Add comments to Word document interactively')
201
+ .argument('<docx>', 'Word document')
202
+ .option('-a, --author <name>', 'Comment author')
203
+ .action(async (docxPath: string, options: CommentOptions) => {
204
+ if (!fs.existsSync(docxPath)) {
205
+ console.error(chalk.red(`File not found: ${docxPath}`));
206
+ process.exit(1);
207
+ }
208
+
209
+ const { default: AdmZip } = await import('adm-zip');
210
+ const readline = await import('readline');
211
+ const rl = readline.createInterface({
212
+ input: process.stdin,
213
+ output: process.stdout,
214
+ });
215
+
216
+ const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
+
218
+ const author = options.author || getUserName() || 'Reviewer';
219
+
220
+ console.log(fmt.header('Interactive Comment Mode'));
221
+ console.log(chalk.dim(` Document: ${docxPath}`));
222
+ console.log(chalk.dim(` Author: ${author}`));
223
+ console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
+ console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
+
226
+ let commentsAdded = 0;
227
+
228
+ while (true) {
229
+ const message = await ask(chalk.cyan('Comment: '));
230
+
231
+ if (!message.trim()) {
232
+ break;
233
+ }
234
+
235
+ const searchText = await ask(chalk.cyan('Attach to text: '));
236
+
237
+ // Load document fresh each time
238
+ const zip = new AdmZip(docxPath);
239
+ const docEntry = zip.getEntry('word/document.xml');
240
+
241
+ if (!docEntry) {
242
+ console.error(chalk.red('Invalid Word document'));
243
+ rl.close();
244
+ process.exit(1);
245
+ }
246
+
247
+ let docXml = zip.readAsText(docEntry);
248
+
249
+ // Read or create comments.xml
250
+ let commentsEntry = zip.getEntry('word/comments.xml');
251
+ let commentsXml: string;
252
+ let nextCommentId = 1;
253
+
254
+ if (commentsEntry) {
255
+ commentsXml = zip.readAsText(commentsEntry);
256
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
+ for (const m of idMatches) {
258
+ const id = parseInt(m.match(/\d+/)![0]);
259
+ if (id >= nextCommentId) nextCommentId = id + 1;
260
+ }
261
+ } else {
262
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
+ </w:comments>`;
265
+ }
266
+
267
+ const date = new Date().toISOString();
268
+ const commentId = nextCommentId;
269
+
270
+ // Add comment to comments.xml
271
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
+ <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
+ </w:comment>`;
274
+
275
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
+
277
+ // Find text and add comment markers
278
+ if (searchText.trim()) {
279
+ const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
+
282
+ if (textPattern.test(docXml)) {
283
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
+ });
286
+ console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
+ } else {
288
+ console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
+ }
290
+ } else {
291
+ console.log(chalk.dim(` Comment added without anchor.`));
292
+ }
293
+
294
+ // Update zip
295
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
296
+
297
+ if (commentsEntry) {
298
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
+ } else {
300
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
+
302
+ // Update [Content_Types].xml
303
+ const ctEntry = zip.getEntry('[Content_Types].xml');
304
+ if (ctEntry) {
305
+ let ctXml = zip.readAsText(ctEntry);
306
+ if (!ctXml.includes('comments.xml')) {
307
+ ctXml = ctXml.replace('</Types>',
308
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
+ }
311
+ }
312
+
313
+ // Update document.xml.rels
314
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
+ if (relsEntry) {
316
+ let relsXml = zip.readAsText(relsEntry);
317
+ if (!relsXml.includes('comments.xml')) {
318
+ const newRelId = `rId${Date.now()}`;
319
+ relsXml = relsXml.replace('</Relationships>',
320
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
+ }
323
+ }
324
+ }
325
+
326
+ zip.writeZip(docxPath);
327
+ commentsAdded++;
328
+ console.log();
329
+ }
330
+
331
+ rl.close();
332
+ console.log();
333
+
334
+ if (commentsAdded > 0) {
335
+ console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
+ } else {
337
+ console.log(chalk.dim('No comments added.'));
338
+ }
339
+ });
340
+ }