docrev 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/dist/bin/rev.js +29 -21
  4. package/dist/bin/rev.js.map +1 -1
  5. package/dist/lib/annotations.d.ts.map +1 -1
  6. package/dist/lib/annotations.js +28 -0
  7. package/dist/lib/annotations.js.map +1 -1
  8. package/dist/lib/build.d.ts +43 -0
  9. package/dist/lib/build.d.ts.map +1 -1
  10. package/dist/lib/build.js +175 -5
  11. package/dist/lib/build.js.map +1 -1
  12. package/dist/lib/commands/build.d.ts.map +1 -1
  13. package/dist/lib/commands/build.js +39 -125
  14. package/dist/lib/commands/build.js.map +1 -1
  15. package/dist/lib/commands/comments.d.ts.map +1 -1
  16. package/dist/lib/commands/comments.js +61 -31
  17. package/dist/lib/commands/comments.js.map +1 -1
  18. package/dist/lib/commands/context.d.ts +12 -0
  19. package/dist/lib/commands/context.d.ts.map +1 -1
  20. package/dist/lib/commands/context.js +34 -0
  21. package/dist/lib/commands/context.js.map +1 -1
  22. package/dist/lib/commands/core.d.ts.map +1 -1
  23. package/dist/lib/commands/core.js +25 -8
  24. package/dist/lib/commands/core.js.map +1 -1
  25. package/dist/lib/commands/merge-resolve.js +1 -1
  26. package/dist/lib/commands/merge-resolve.js.map +1 -1
  27. package/dist/lib/commands/quality.js +2 -2
  28. package/dist/lib/commands/quality.js.map +1 -1
  29. package/dist/lib/commands/response.js +1 -1
  30. package/dist/lib/commands/response.js.map +1 -1
  31. package/dist/lib/commands/sections.js +1 -1
  32. package/dist/lib/commands/sections.js.map +1 -1
  33. package/dist/lib/commands/text-ops.js +1 -1
  34. package/dist/lib/commands/text-ops.js.map +1 -1
  35. package/dist/lib/commands/utilities.d.ts.map +1 -1
  36. package/dist/lib/commands/utilities.js +5 -2
  37. package/dist/lib/commands/utilities.js.map +1 -1
  38. package/dist/lib/commands/word-tools.js +2 -2
  39. package/dist/lib/commands/word-tools.js.map +1 -1
  40. package/dist/lib/crossref.d.ts.map +1 -1
  41. package/dist/lib/crossref.js +12 -41
  42. package/dist/lib/crossref.js.map +1 -1
  43. package/dist/lib/csl.d.ts.map +1 -1
  44. package/dist/lib/csl.js +14 -22
  45. package/dist/lib/csl.js.map +1 -1
  46. package/dist/lib/diff-engine.js +1 -1
  47. package/dist/lib/diff-engine.js.map +1 -1
  48. package/dist/lib/equations.d.ts.map +1 -1
  49. package/dist/lib/equations.js +12 -3
  50. package/dist/lib/equations.js.map +1 -1
  51. package/dist/lib/errors.d.ts.map +1 -1
  52. package/dist/lib/errors.js +1 -30
  53. package/dist/lib/errors.js.map +1 -1
  54. package/dist/lib/image-registry.d.ts.map +1 -1
  55. package/dist/lib/image-registry.js +4 -0
  56. package/dist/lib/image-registry.js.map +1 -1
  57. package/dist/lib/import.d.ts +15 -1
  58. package/dist/lib/import.d.ts.map +1 -1
  59. package/dist/lib/import.js +24 -1
  60. package/dist/lib/import.js.map +1 -1
  61. package/dist/lib/input.d.ts +56 -0
  62. package/dist/lib/input.d.ts.map +1 -0
  63. package/dist/lib/input.js +129 -0
  64. package/dist/lib/input.js.map +1 -0
  65. package/dist/lib/merge.d.ts.map +1 -1
  66. package/dist/lib/merge.js +9 -1
  67. package/dist/lib/merge.js.map +1 -1
  68. package/dist/lib/ooxml.d.ts +22 -0
  69. package/dist/lib/ooxml.d.ts.map +1 -1
  70. package/dist/lib/ooxml.js +130 -0
  71. package/dist/lib/ooxml.js.map +1 -1
  72. package/dist/lib/orcid.d.ts.map +1 -1
  73. package/dist/lib/orcid.js +16 -7
  74. package/dist/lib/orcid.js.map +1 -1
  75. package/dist/lib/plugins.d.ts.map +1 -1
  76. package/dist/lib/plugins.js +8 -4
  77. package/dist/lib/plugins.js.map +1 -1
  78. package/dist/lib/protect-restore.d.ts.map +1 -1
  79. package/dist/lib/protect-restore.js +7 -5
  80. package/dist/lib/protect-restore.js.map +1 -1
  81. package/dist/lib/response.d.ts +1 -1
  82. package/dist/lib/response.d.ts.map +1 -1
  83. package/dist/lib/response.js +5 -2
  84. package/dist/lib/response.js.map +1 -1
  85. package/dist/lib/restore-references.d.ts.map +1 -1
  86. package/dist/lib/restore-references.js +25 -3
  87. package/dist/lib/restore-references.js.map +1 -1
  88. package/dist/lib/schema.d.ts.map +1 -1
  89. package/dist/lib/schema.js +1 -19
  90. package/dist/lib/schema.js.map +1 -1
  91. package/dist/lib/slides.js +1 -1
  92. package/dist/lib/slides.js.map +1 -1
  93. package/dist/lib/spelling.js +1 -1
  94. package/dist/lib/spelling.js.map +1 -1
  95. package/dist/lib/tui.js +0 -1
  96. package/dist/lib/tui.js.map +1 -1
  97. package/dist/lib/utils.d.ts +14 -0
  98. package/dist/lib/utils.d.ts.map +1 -1
  99. package/dist/lib/utils.js +41 -0
  100. package/dist/lib/utils.js.map +1 -1
  101. package/dist/lib/word-extraction.d.ts +5 -5
  102. package/dist/lib/word-extraction.d.ts.map +1 -1
  103. package/dist/lib/word-extraction.js +25 -106
  104. package/dist/lib/word-extraction.js.map +1 -1
  105. package/dist/lib/word.d.ts +14 -38
  106. package/dist/lib/word.d.ts.map +1 -1
  107. package/dist/lib/word.js +24 -179
  108. package/dist/lib/word.js.map +1 -1
  109. package/dist/lib/wordcomments.d.ts.map +1 -1
  110. package/dist/lib/wordcomments.js +9 -7
  111. package/dist/lib/wordcomments.js.map +1 -1
  112. package/package.json +17 -6
  113. package/.gitattributes +0 -1
  114. package/PLAN-tables-and-postprocess.md +0 -850
  115. package/bin/rev.ts +0 -145
  116. package/docs-src/build.py +0 -113
  117. package/docs-src/extra.css +0 -208
  118. package/docs-src/md-to-html.lua +0 -6
  119. package/docs-src/template.html +0 -116
  120. package/eslint.config.js +0 -27
  121. package/lib/anchor-match.ts +0 -307
  122. package/lib/annotations.ts +0 -664
  123. package/lib/build.ts +0 -2047
  124. package/lib/citations.ts +0 -160
  125. package/lib/commands/build.ts +0 -885
  126. package/lib/commands/citations.ts +0 -515
  127. package/lib/commands/comments.ts +0 -1050
  128. package/lib/commands/context.ts +0 -176
  129. package/lib/commands/core.ts +0 -309
  130. package/lib/commands/doi.ts +0 -451
  131. package/lib/commands/file-ops.ts +0 -372
  132. package/lib/commands/history.ts +0 -320
  133. package/lib/commands/index.ts +0 -87
  134. package/lib/commands/init.ts +0 -259
  135. package/lib/commands/merge-resolve.ts +0 -378
  136. package/lib/commands/preview.ts +0 -178
  137. package/lib/commands/project-info.ts +0 -244
  138. package/lib/commands/quality.ts +0 -517
  139. package/lib/commands/response.ts +0 -454
  140. package/lib/commands/section-boundaries.ts +0 -82
  141. package/lib/commands/sections.ts +0 -451
  142. package/lib/commands/sync.ts +0 -689
  143. package/lib/commands/text-ops.ts +0 -449
  144. package/lib/commands/utilities.ts +0 -448
  145. package/lib/commands/verify-anchors.ts +0 -272
  146. package/lib/commands/word-tools.ts +0 -340
  147. package/lib/comment-realign.ts +0 -99
  148. package/lib/config.ts +0 -84
  149. package/lib/crossref.ts +0 -781
  150. package/lib/csl.ts +0 -191
  151. package/lib/dependencies.ts +0 -132
  152. package/lib/diff-engine.ts +0 -465
  153. package/lib/doi-cache.ts +0 -115
  154. package/lib/doi.ts +0 -879
  155. package/lib/equations.ts +0 -506
  156. package/lib/errors.ts +0 -350
  157. package/lib/format.ts +0 -541
  158. package/lib/git.ts +0 -326
  159. package/lib/grammar.ts +0 -303
  160. package/lib/image-registry.ts +0 -180
  161. package/lib/import.ts +0 -906
  162. package/lib/journals.ts +0 -543
  163. package/lib/macro-filter.lua +0 -201
  164. package/lib/macros.ts +0 -273
  165. package/lib/merge.ts +0 -633
  166. package/lib/ooxml.ts +0 -768
  167. package/lib/orcid.ts +0 -144
  168. package/lib/pdf-comments.ts +0 -263
  169. package/lib/pdf-import.ts +0 -524
  170. package/lib/plugins.ts +0 -362
  171. package/lib/postprocess.ts +0 -188
  172. package/lib/pptx-color-filter.lua +0 -37
  173. package/lib/pptx-template.ts +0 -469
  174. package/lib/pptx-themes/academic.pptx +0 -0
  175. package/lib/pptx-themes/corporate.pptx +0 -0
  176. package/lib/pptx-themes/dark.pptx +0 -0
  177. package/lib/pptx-themes/default.pptx +0 -0
  178. package/lib/pptx-themes/minimal.pptx +0 -0
  179. package/lib/pptx-themes/plant.pptx +0 -0
  180. package/lib/pptx-themes.ts +0 -483
  181. package/lib/protect-restore.ts +0 -520
  182. package/lib/rate-limiter.ts +0 -127
  183. package/lib/response.ts +0 -197
  184. package/lib/restore-references.ts +0 -240
  185. package/lib/review.ts +0 -327
  186. package/lib/schema.ts +0 -494
  187. package/lib/scientific-words.ts +0 -73
  188. package/lib/sections.ts +0 -428
  189. package/lib/slides.ts +0 -756
  190. package/lib/spelling.ts +0 -334
  191. package/lib/templates.ts +0 -526
  192. package/lib/themes.ts +0 -742
  193. package/lib/trackchanges.ts +0 -166
  194. package/lib/tui.ts +0 -450
  195. package/lib/types.ts +0 -546
  196. package/lib/undo.ts +0 -250
  197. package/lib/utils.ts +0 -69
  198. package/lib/variables.ts +0 -179
  199. package/lib/word-extraction.ts +0 -525
  200. package/lib/word.ts +0 -526
  201. package/lib/wordcomments.ts +0 -789
  202. package/mkdocs.yml +0 -64
  203. package/scripts/postbuild.js +0 -47
  204. package/tsconfig.json +0 -26
  205. package/types/index.d.ts +0 -531
@@ -1,272 +0,0 @@
1
- /**
2
- * VERIFY-ANCHORS command: report drift between Word comment anchors
3
- * and the current markdown.
4
- *
5
- * Useful when prose has been revised between sending the docx out for
6
- * review and receiving it back. Each comment is classified by how well
7
- * its anchor still matches the current section prose:
8
- *
9
- * clean – exact or whitespace-normalized hit
10
- * drift – anchor only matches via stripped/partial fallbacks
11
- * context-only – anchor text is gone, only surrounding context survives
12
- * ambiguous – multiple matches, can't pick one without context
13
- * unmatched – nothing maps; user must place the comment manually
14
- */
15
-
16
- import {
17
- chalk,
18
- fs,
19
- path,
20
- fmt,
21
- resolveSectionsConfig,
22
- jsonMode,
23
- jsonOutput,
24
- } from './context.js';
25
- import type { Command } from 'commander';
26
- import { findAnchorInText, classifyStrategy, scoreContextAt, type AnchorMatchQuality } from '../anchor-match.js';
27
- import type { CommentAnchorData } from '../word-extraction.js';
28
- import { computeSectionBoundaries } from './section-boundaries.js';
29
-
30
- interface VerifyOptions {
31
- config: string;
32
- dir: string;
33
- json?: boolean;
34
- }
35
-
36
- interface CommentReport {
37
- id: string;
38
- author: string;
39
- text: string;
40
- section: string | null;
41
- quality: AnchorMatchQuality | 'ambiguous';
42
- strategy: string;
43
- anchor: string;
44
- occurrences: number;
45
- }
46
-
47
- export function register(program: Command): void {
48
- program
49
- .command('verify-anchors')
50
- .description('Report drift between Word comment anchors and current markdown')
51
- .argument('<file>', 'Word document with reviewer comments (.docx)')
52
- .option('-c, --config <file>', 'Sections config file', 'sections.yaml')
53
- .option('-d, --dir <directory>', 'Directory with section files', '.')
54
- .option('--json', 'Output JSON report (for scripting)')
55
- .action(async (docxPath: string, options: VerifyOptions) => {
56
- if (!fs.existsSync(docxPath)) {
57
- console.error(fmt.status('error', `File not found: ${docxPath}`));
58
- process.exit(1);
59
- }
60
-
61
- const resolved = resolveSectionsConfig(options.dir, options.config);
62
- if (!resolved) {
63
- console.error(fmt.status('error', `No section config found in ${path.resolve(options.dir)}`));
64
- console.error(chalk.dim(' Add a `sections:` list to rev.yaml, or run "rev init" to generate sections.yaml.'));
65
- process.exit(1);
66
- }
67
-
68
- const config = resolved.config;
69
- const { extractWordComments, extractCommentAnchors, extractHeadings } = await import('../import.js');
70
-
71
- let comments;
72
- let anchors;
73
- let headings;
74
- let fullDocText = '';
75
- try {
76
- comments = await extractWordComments(docxPath);
77
- const result = await extractCommentAnchors(docxPath);
78
- anchors = result.anchors;
79
- fullDocText = result.fullDocText;
80
- headings = await extractHeadings(docxPath);
81
- } catch (err) {
82
- const error = err as Error;
83
- console.error(fmt.status('error', `Failed to read ${path.basename(docxPath)}: ${error.message}`));
84
- if (process.env.DEBUG) console.error(error.stack);
85
- process.exit(1);
86
- }
87
-
88
- if (comments.length === 0) {
89
- console.log(fmt.status('info', 'No comments found in document.'));
90
- return;
91
- }
92
-
93
- const boundaries = computeSectionBoundaries(config.sections, headings, fullDocText.length);
94
-
95
- // Cache section markdown contents on first read
96
- const sectionCache = new Map<string, string>();
97
- function loadSection(file: string): string | null {
98
- if (sectionCache.has(file)) return sectionCache.get(file)!;
99
- const sectionPath = path.join(options.dir, file);
100
- if (!fs.existsSync(sectionPath)) return null;
101
- const content = fs.readFileSync(sectionPath, 'utf-8');
102
- sectionCache.set(file, content);
103
- return content;
104
- }
105
-
106
- const firstBoundaryStart = boundaries.length > 0 ? boundaries[0].start : 0;
107
- const reports: CommentReport[] = [];
108
-
109
- for (const c of comments) {
110
- const anchor: CommentAnchorData | undefined = anchors.get(c.id);
111
- const anchorText = anchor?.anchor || '';
112
- if (!anchor) {
113
- reports.push({
114
- id: c.id,
115
- author: c.author,
116
- text: c.text,
117
- section: null,
118
- quality: 'unmatched',
119
- strategy: 'no-anchor',
120
- anchor: '',
121
- occurrences: 0,
122
- });
123
- continue;
124
- }
125
-
126
- // Determine which section file this comment lives in
127
- let sectionFile: string | null = null;
128
- for (const b of boundaries) {
129
- if (anchor.docPosition >= b.start && anchor.docPosition < b.end) {
130
- sectionFile = b.file;
131
- break;
132
- }
133
- }
134
- if (!sectionFile && boundaries.length > 0 && anchor.docPosition < firstBoundaryStart) {
135
- sectionFile = boundaries[0].file;
136
- }
137
-
138
- if (!sectionFile) {
139
- reports.push({
140
- id: c.id,
141
- author: c.author,
142
- text: c.text,
143
- section: null,
144
- quality: 'unmatched',
145
- strategy: 'no-section',
146
- anchor: anchorText,
147
- occurrences: 0,
148
- });
149
- continue;
150
- }
151
-
152
- const md = loadSection(sectionFile);
153
- if (md === null) {
154
- reports.push({
155
- id: c.id,
156
- author: c.author,
157
- text: c.text,
158
- section: sectionFile,
159
- quality: 'unmatched',
160
- strategy: 'missing-file',
161
- anchor: anchorText,
162
- occurrences: 0,
163
- });
164
- continue;
165
- }
166
-
167
- const search = findAnchorInText(anchor.anchor, md, anchor.before, anchor.after);
168
- let quality: AnchorMatchQuality | 'ambiguous' = classifyStrategy(search.strategy, search.occurrences.length);
169
- if (quality === 'clean' && search.occurrences.length > 1) {
170
- // Multiple direct hits — only flag as ambiguous when before/after
171
- // context can't pick a clear winner. If one candidate scores
172
- // strictly higher than the others, sync will place it correctly.
173
- const anchorLen = anchor.anchor.length;
174
- const scores = search.occurrences.map(p => scoreContextAt(p, md, anchor.before, anchor.after, anchorLen));
175
- const max = Math.max(...scores);
176
- const winners = scores.filter(s => s === max).length;
177
- if (max === 0 || winners > 1) {
178
- quality = 'ambiguous';
179
- }
180
- }
181
-
182
- reports.push({
183
- id: c.id,
184
- author: c.author,
185
- text: c.text,
186
- section: sectionFile,
187
- quality,
188
- strategy: search.strategy,
189
- anchor: anchorText,
190
- occurrences: search.occurrences.length,
191
- });
192
- }
193
-
194
- if (options.json || jsonMode) {
195
- jsonOutput({
196
- file: docxPath,
197
- totalComments: comments.length,
198
- summary: tally(reports),
199
- comments: reports,
200
- });
201
- return;
202
- }
203
-
204
- printReport(docxPath, reports);
205
- });
206
- }
207
-
208
- function tally(reports: CommentReport[]): Record<string, number> {
209
- const out: Record<string, number> = { clean: 0, drift: 0, 'context-only': 0, ambiguous: 0, unmatched: 0 };
210
- for (const r of reports) out[r.quality] = (out[r.quality] || 0) + 1;
211
- return out;
212
- }
213
-
214
- function printReport(docxPath: string, reports: CommentReport[]): void {
215
- console.log(fmt.header(`Anchor Verification: ${path.basename(docxPath)}`));
216
- console.log();
217
-
218
- const totals = tally(reports);
219
- const summaryLines: string[] = [];
220
- summaryLines.push(`${chalk.green(totals.clean)} clean (anchor still matches)`);
221
- if (totals.drift) summaryLines.push(`${chalk.cyan(totals.drift)} drifted (matched via fallback strategies)`);
222
- if (totals['context-only']) summaryLines.push(`${chalk.yellow(totals['context-only'])} context-only (anchor text gone, neighbors survive)`);
223
- if (totals.ambiguous) summaryLines.push(`${chalk.magenta(totals.ambiguous)} ambiguous (multiple candidate positions)`);
224
- if (totals.unmatched) summaryLines.push(`${chalk.red(totals.unmatched)} unmatched (manual placement needed)`);
225
- console.log(fmt.box(summaryLines.join('\n'), { title: 'Summary', padding: 0 }));
226
- console.log();
227
-
228
- // Per-comment table for everything that isn't a clean direct hit
229
- const problems = reports.filter(r => r.quality !== 'clean');
230
- if (problems.length === 0) {
231
- console.log(fmt.status('success', 'All comment anchors match the current markdown.'));
232
- return;
233
- }
234
-
235
- const rows = problems.map(r => [
236
- chalk.dim(`#${r.id}`),
237
- qualityColor(r.quality),
238
- r.section ? chalk.bold(r.section) : chalk.dim('—'),
239
- chalk.dim(r.strategy),
240
- truncate(r.anchor, 35),
241
- truncate(r.text, 35),
242
- ]);
243
-
244
- console.log(fmt.table(
245
- ['ID', 'Quality', 'Section', 'Strategy', 'Anchor (Word)', 'Comment'],
246
- rows,
247
- { align: ['right', 'left', 'left', 'left', 'left', 'left'] },
248
- ));
249
-
250
- if (totals.unmatched > 0 || totals.ambiguous > 0) {
251
- console.log();
252
- console.log(chalk.dim('Comments flagged "unmatched" or "ambiguous" need manual placement.'));
253
- console.log(chalk.dim('Run "rev sync --comments-only" to import the matched ones without touching prose.'));
254
- }
255
- }
256
-
257
- function qualityColor(q: string): string {
258
- switch (q) {
259
- case 'clean': return chalk.green('clean');
260
- case 'drift': return chalk.cyan('drift');
261
- case 'context-only': return chalk.yellow('context');
262
- case 'ambiguous': return chalk.magenta('ambiguous');
263
- case 'unmatched': return chalk.red('unmatched');
264
- default: return q;
265
- }
266
- }
267
-
268
- function truncate(s: string, max: number): string {
269
- if (!s) return chalk.dim('—');
270
- const flat = s.replace(/\s+/g, ' ').trim();
271
- return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
272
- }
@@ -1,340 +0,0 @@
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
- }