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,515 +0,0 @@
1
- /**
2
- * Citation commands: citations, figures, equations, pdf-comments
3
- *
4
- * Commands for validating citations, managing figures/tables, and equation handling.
5
- */
6
-
7
- import {
8
- chalk,
9
- fs,
10
- path,
11
- fmt,
12
- } from './context.js';
13
- import type { Command } from 'commander';
14
-
15
- interface CitationsOptions {
16
- bib: string;
17
- }
18
-
19
- interface EquationsOptions {
20
- output?: string;
21
- }
22
-
23
- interface PdfCommentsOptions {
24
- append?: string;
25
- json?: boolean;
26
- byPage?: boolean;
27
- byAuthor?: boolean;
28
- withText?: boolean;
29
- }
30
-
31
- /**
32
- * Register citation commands with the program
33
- */
34
- export function register(program: Command): void {
35
- // ==========================================================================
36
- // CITATIONS command - Validate citations against .bib file
37
- // ==========================================================================
38
-
39
- program
40
- .command('citations')
41
- .alias('cite')
42
- .description('Validate citations against bibliography')
43
- .argument('[files...]', 'Markdown files to check (default: all section files)')
44
- .option('-b, --bib <file>', 'Bibliography file', 'references.bib')
45
- .action(async (files: string[], options: CitationsOptions) => {
46
- const { getCitationStats } = await import('../citations.js');
47
-
48
- // If no files specified, find all .md files
49
- let mdFiles = files;
50
- if (!mdFiles || mdFiles.length === 0) {
51
- mdFiles = fs.readdirSync('.').filter(f =>
52
- f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f)
53
- );
54
- }
55
-
56
- if (!fs.existsSync(options.bib)) {
57
- console.error(fmt.status('error', `Bibliography not found: ${options.bib}`));
58
- process.exit(1);
59
- }
60
-
61
- const stats = getCitationStats(mdFiles, options.bib);
62
-
63
- console.log(fmt.header('Citation Check'));
64
- console.log();
65
-
66
- // Summary table
67
- const rows: string[][] = [
68
- ['Total citations', stats.totalCitations.toString()],
69
- ['Unique keys cited', stats.uniqueCited.toString()],
70
- ['Bib entries', stats.bibEntries.toString()],
71
- [chalk.green('Valid'), chalk.green(stats.valid.toString())],
72
- [stats.missing > 0 ? chalk.red('Missing') : 'Missing', stats.missing > 0 ? chalk.red(stats.missing.toString()) : '0'],
73
- [chalk.dim('Unused in bib'), chalk.dim(stats.unused.toString())],
74
- ];
75
- console.log(fmt.table(['Metric', 'Count'], rows));
76
-
77
- // Show missing keys
78
- if (stats.missingKeys.length > 0) {
79
- console.log();
80
- console.log(fmt.status('error', 'Missing citations:'));
81
- for (const key of stats.missingKeys) {
82
- console.log(chalk.red(` - ${key}`));
83
- }
84
- }
85
-
86
- // Show unused (if verbose)
87
- if (stats.unusedKeys.length > 0 && stats.unusedKeys.length <= 10) {
88
- console.log();
89
- console.log(chalk.dim('Unused bib entries:'));
90
- for (const key of stats.unusedKeys.slice(0, 10)) {
91
- console.log(chalk.dim(` - ${key}`));
92
- }
93
- if (stats.unusedKeys.length > 10) {
94
- console.log(chalk.dim(` ... and ${stats.unusedKeys.length - 10} more`));
95
- }
96
- }
97
-
98
- console.log();
99
- if (stats.missing === 0) {
100
- console.log(fmt.status('success', 'All citations valid'));
101
- } else {
102
- console.log(fmt.status('warning', `${stats.missing} citation(s) missing from ${options.bib}`));
103
- process.exit(1);
104
- }
105
- });
106
-
107
- // ==========================================================================
108
- // FIGURES command - Figure/table inventory
109
- // ==========================================================================
110
-
111
- program
112
- .command('figures')
113
- .alias('figs')
114
- .description('List all figures and tables with reference counts')
115
- .argument('[files...]', 'Markdown files to scan')
116
- .action(async (files: string[]) => {
117
- const { buildRegistry } = await import('../crossref.js');
118
-
119
- // If no files specified, find all .md files
120
- let mdFiles = files;
121
- if (!mdFiles || mdFiles.length === 0) {
122
- mdFiles = fs.readdirSync('.').filter(f =>
123
- f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f)
124
- );
125
- }
126
-
127
- // Build registry
128
- const registry = buildRegistry('.');
129
-
130
- // Count references in files
131
- const refCounts = new Map<string, number>();
132
- for (const file of mdFiles) {
133
- if (!fs.existsSync(file)) continue;
134
- const text = fs.readFileSync(file, 'utf-8');
135
-
136
- // Count @fig: and @tbl: references
137
- const figRefs = text.matchAll(/@fig:([a-zA-Z0-9_-]+)/g);
138
- for (const match of figRefs) {
139
- const key = `fig:${match[1]}`;
140
- refCounts.set(key, (refCounts.get(key) || 0) + 1);
141
- }
142
-
143
- const tblRefs = text.matchAll(/@tbl:([a-zA-Z0-9_-]+)/g);
144
- for (const match of tblRefs) {
145
- const key = `tbl:${match[1]}`;
146
- refCounts.set(key, (refCounts.get(key) || 0) + 1);
147
- }
148
- }
149
-
150
- console.log(fmt.header('Figure & Table Inventory'));
151
- console.log();
152
-
153
- // Figures
154
- if (registry.figures.size > 0) {
155
- const figRows = [...registry.figures.entries()].map(([label, info]) => {
156
- const key = `fig:${label}`;
157
- const refs = refCounts.get(key) || 0;
158
- const num = info.isSupp ? `S${info.num}` : info.num.toString();
159
- return [
160
- `Figure ${num}`,
161
- chalk.cyan(`@fig:${label}`),
162
- info.file,
163
- refs > 0 ? chalk.green(refs.toString()) : chalk.yellow('0'),
164
- ];
165
- });
166
- console.log(fmt.table(['#', 'Label', 'File', 'Refs'], figRows));
167
- console.log();
168
- }
169
-
170
- // Tables
171
- if (registry.tables.size > 0) {
172
- const tblRows = [...registry.tables.entries()].map(([label, info]) => {
173
- const key = `tbl:${label}`;
174
- const refs = refCounts.get(key) || 0;
175
- const num = info.isSupp ? `S${info.num}` : info.num.toString();
176
- return [
177
- `Table ${num}`,
178
- chalk.cyan(`@tbl:${label}`),
179
- info.file,
180
- refs > 0 ? chalk.green(refs.toString()) : chalk.yellow('0'),
181
- ];
182
- });
183
- console.log(fmt.table(['#', 'Label', 'File', 'Refs'], tblRows));
184
- console.log();
185
- }
186
-
187
- if (registry.figures.size === 0 && registry.tables.size === 0) {
188
- console.log(chalk.dim('No figures or tables found.'));
189
- console.log(chalk.dim('Add anchors like {#fig:label} to your figures.'));
190
- }
191
-
192
- // Warn about unreferenced
193
- const unreferenced: string[] = [];
194
- for (const [label] of registry.figures) {
195
- if (!refCounts.get(`fig:${label}`)) unreferenced.push(`@fig:${label}`);
196
- }
197
- for (const [label] of registry.tables) {
198
- if (!refCounts.get(`tbl:${label}`)) unreferenced.push(`@tbl:${label}`);
199
- }
200
-
201
- if (unreferenced.length > 0) {
202
- console.log(fmt.status('warning', `${unreferenced.length} unreferenced figure(s)/table(s)`));
203
- }
204
- });
205
-
206
- // ==========================================================================
207
- // EQUATIONS command - Extract and convert equations
208
- // ==========================================================================
209
-
210
- program
211
- .command('equations')
212
- .alias('eq')
213
- .description('Extract equations or convert to Word')
214
- .argument('<action>', 'Action: list, extract, convert, from-word')
215
- .argument('[input]', 'Input file (.md for extract/convert, .docx for from-word)')
216
- .option('-o, --output <file>', 'Output file')
217
- .action(async (action: string, input: string | undefined, options: EquationsOptions) => {
218
- const { extractEquations, getEquationStats, createEquationsDoc, extractEquationsFromWord, getWordEquationStats } = await import('../equations.js');
219
-
220
- if (action === 'from-word') {
221
- // Extract equations from Word document
222
- if (!input) {
223
- console.error(fmt.status('error', 'Word document required'));
224
- process.exit(1);
225
- }
226
-
227
- if (!input.endsWith('.docx')) {
228
- console.error(fmt.status('error', 'Input must be a .docx file'));
229
- process.exit(1);
230
- }
231
-
232
- const spin = fmt.spinner(`Extracting equations from ${path.basename(input)}...`).start();
233
-
234
- const result = await extractEquationsFromWord(input);
235
-
236
- if (!result.success) {
237
- spin.error(result.error!);
238
- process.exit(1);
239
- }
240
-
241
- spin.stop();
242
- console.log(fmt.header('Equations from Word'));
243
- console.log();
244
-
245
- if (result.equations.length === 0) {
246
- console.log(chalk.dim('No equations found in document.'));
247
- return;
248
- }
249
-
250
- const display = result.equations.filter(e => e.type === 'display');
251
- const inline = result.equations.filter(e => e.type === 'inline');
252
-
253
- console.log(chalk.dim(`Found ${result.equations.length} equations (${display.length} display, ${inline.length} inline)`));
254
- console.log();
255
-
256
- // Show equations
257
- for (let i = 0; i < result.equations.length; i++) {
258
- const eq = result.equations[i];
259
- const typeLabel = eq.type === 'display' ? chalk.cyan('[display]') : chalk.yellow('[inline]');
260
-
261
- if (eq.latex) {
262
- console.log(`${chalk.bold((i + 1).toString())}. ${typeLabel}`);
263
- console.log(chalk.dim(' LaTeX:'), eq.latex.length > 80 ? eq.latex.substring(0, 77) + '...' : eq.latex);
264
- } else {
265
- console.log(`${chalk.bold((i + 1).toString())}. ${typeLabel} ${chalk.red('[conversion failed]')}`);
266
- }
267
- }
268
-
269
- // Optionally save to file
270
- if (options.output) {
271
- const latex = result.equations
272
- .filter(e => e.latex)
273
- .map((e, i) => `%% Equation ${i + 1} (${e.type})\n${e.type === 'display' ? '$$' : '$'}${e.latex}${e.type === 'display' ? '$$' : '$'}`)
274
- .join('\n\n');
275
-
276
- fs.writeFileSync(options.output, latex, 'utf-8');
277
- console.log();
278
- console.log(fmt.status('success', `Saved ${result.equations.filter(e => e.latex).length} equations to ${options.output}`));
279
- }
280
-
281
- } else if (action === 'list') {
282
- // List equations in all section files
283
- const mdFiles = fs.readdirSync('.').filter(f =>
284
- f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f)
285
- );
286
-
287
- const stats = getEquationStats(mdFiles);
288
-
289
- console.log(fmt.header('Equations'));
290
- console.log();
291
-
292
- if (stats.byFile.length === 0) {
293
- console.log(chalk.dim('No equations found.'));
294
- return;
295
- }
296
-
297
- const rows = stats.byFile.map(f => [
298
- f.file,
299
- f.display > 0 ? chalk.cyan(f.display.toString()) : chalk.dim('-'),
300
- f.inline > 0 ? chalk.yellow(f.inline.toString()) : chalk.dim('-'),
301
- ]);
302
- rows.push([
303
- chalk.bold('Total'),
304
- chalk.bold.cyan(stats.display.toString()),
305
- chalk.bold.yellow(stats.inline.toString()),
306
- ]);
307
-
308
- console.log(fmt.table(['File', 'Display', 'Inline'], rows));
309
-
310
- } else if (action === 'extract') {
311
- if (!input) {
312
- console.error(fmt.status('error', 'Input file required'));
313
- process.exit(1);
314
- }
315
-
316
- const output = options.output || input.replace('.md', '-equations.md');
317
- const result = await createEquationsDoc(input, output);
318
-
319
- if (result.success) {
320
- console.log(fmt.status('success', result.message));
321
- console.log(chalk.dim(` ${result.stats!.display} display, ${result.stats!.inline} inline equations`));
322
- } else {
323
- console.error(fmt.status('error', result.message));
324
- process.exit(1);
325
- }
326
-
327
- } else if (action === 'convert') {
328
- if (!input) {
329
- console.error(fmt.status('error', 'Input file required'));
330
- process.exit(1);
331
- }
332
-
333
- const output = options.output || input.replace('.md', '.docx');
334
-
335
- const spin = fmt.spinner(`Converting ${path.basename(input)} to Word...`).start();
336
-
337
- try {
338
- const { exec } = await import('child_process');
339
- const { promisify } = await import('util');
340
- const execAsync = promisify(exec);
341
-
342
- await execAsync(`pandoc "${input}" -o "${output}" --mathml`);
343
- spin.success(`Created ${output}`);
344
- } catch (err) {
345
- const error = err as Error;
346
- spin.error(error.message);
347
- process.exit(1);
348
- }
349
- } else {
350
- console.error(fmt.status('error', `Unknown action: ${action}`));
351
- console.log(chalk.dim('Actions: list, extract, convert, from-word'));
352
- process.exit(1);
353
- }
354
- });
355
-
356
- // ==========================================================================
357
- // PDF-COMMENTS command - Extract comments from PDF
358
- // ==========================================================================
359
-
360
- program
361
- .command('pdf-comments')
362
- .alias('pdf')
363
- .description('Extract and manage comments from annotated PDFs')
364
- .argument('<pdf>', 'PDF file with annotations')
365
- .option('-a, --append <file>', 'Append comments to markdown file')
366
- .option('--json', 'Output as JSON')
367
- .option('--by-page', 'Group comments by page')
368
- .option('--by-author', 'Group comments by author')
369
- .option('--with-text', 'Extract highlighted text (slower but shows what was highlighted)')
370
- .action(async (pdf: string, options: PdfCommentsOptions) => {
371
- if (!fs.existsSync(pdf)) {
372
- console.error(fmt.status('error', `File not found: ${pdf}`));
373
- process.exit(1);
374
- }
375
-
376
- if (!pdf.toLowerCase().endsWith('.pdf')) {
377
- console.error(fmt.status('error', 'File must be a PDF'));
378
- process.exit(1);
379
- }
380
-
381
- const {
382
- extractPdfComments,
383
- extractPdfAnnotationsWithText,
384
- formatPdfComments,
385
- getPdfCommentStats,
386
- insertPdfCommentsIntoMarkdown,
387
- formatAnnotationWithText,
388
- } = await import('../pdf-import.js');
389
-
390
- const spin = fmt.spinner(`Extracting comments from ${path.basename(pdf)}...`).start();
391
-
392
- try {
393
- let comments: any[];
394
-
395
- if (options.withText) {
396
- // Use the new text extraction feature
397
- const annotations = await extractPdfAnnotationsWithText(pdf);
398
- spin.stop();
399
-
400
- if (annotations.length === 0) {
401
- console.log(fmt.status('info', 'No annotations found in PDF.'));
402
- return;
403
- }
404
-
405
- // Convert to comment format with highlighted text
406
- comments = annotations.map(a => ({
407
- author: a.author || 'Reviewer',
408
- text: a.highlightedText
409
- ? `"${a.highlightedText}"${a.contents ? ' → ' + a.contents : ''}`
410
- : a.contents,
411
- page: a.page,
412
- type: a.type,
413
- date: a.date,
414
- highlightedText: a.highlightedText,
415
- })).filter(c => c.text);
416
- } else {
417
- comments = await extractPdfComments(pdf);
418
- spin.stop();
419
- }
420
-
421
- if (comments.length === 0) {
422
- console.log(fmt.status('info', 'No comments found in PDF.'));
423
- return;
424
- }
425
-
426
- const stats = getPdfCommentStats(comments);
427
-
428
- // JSON output
429
- if (options.json) {
430
- console.log(JSON.stringify({ comments, stats }, null, 2));
431
- return;
432
- }
433
-
434
- // Append to markdown file
435
- if (options.append) {
436
- if (!fs.existsSync(options.append)) {
437
- console.error(fmt.status('error', `Markdown file not found: ${options.append}`));
438
- process.exit(1);
439
- }
440
-
441
- const markdown = fs.readFileSync(options.append, 'utf-8');
442
- const updated = insertPdfCommentsIntoMarkdown(markdown, comments);
443
- fs.writeFileSync(options.append, updated, 'utf-8');
444
-
445
- console.log(fmt.status('success', `Added ${comments.length} comments to ${options.append}`));
446
- return;
447
- }
448
-
449
- // Display comments
450
- console.log(fmt.header(`PDF Comments: ${path.basename(pdf)}`));
451
- console.log();
452
-
453
- if (options.byAuthor) {
454
- // Group by author
455
- const byAuthor: Record<string, any[]> = {};
456
- for (const c of comments) {
457
- const author = c.author || 'Unknown';
458
- if (!byAuthor[author]) byAuthor[author] = [];
459
- byAuthor[author].push(c);
460
- }
461
-
462
- for (const [author, authorComments] of Object.entries(byAuthor)) {
463
- console.log(chalk.bold(`${author} (${authorComments.length}):`));
464
- for (const c of authorComments) {
465
- if (c.highlightedText) {
466
- console.log(` [p.${c.page}] ${chalk.yellow(`"${c.highlightedText}"`)}${c.text !== c.highlightedText ? ` → ${c.text.replace(`"${c.highlightedText}" → `, '')}` : ''}`);
467
- } else {
468
- console.log(` [p.${c.page}] ${c.text}`);
469
- }
470
- }
471
- console.log();
472
- }
473
- } else {
474
- // Default: by page
475
- if (options.withText) {
476
- let currentPage = 0;
477
- for (const c of comments) {
478
- if (c.page !== currentPage) {
479
- if (currentPage > 0) console.log();
480
- console.log(`Page ${c.page}:`);
481
- currentPage = c.page;
482
- }
483
- if (c.highlightedText) {
484
- console.log(` ${chalk.yellow(`"${c.highlightedText}"`)} → ${c.text.replace(`"${c.highlightedText}" → `, '')}`);
485
- } else {
486
- console.log(` ${c.text}`);
487
- }
488
- }
489
- console.log();
490
- } else {
491
- console.log(formatPdfComments(comments));
492
- console.log();
493
- }
494
- }
495
-
496
- // Summary
497
- const authorList = Object.entries(stats.byAuthor)
498
- .map(([author, count]) => `${author} (${count})`)
499
- .join(', ');
500
- console.log(chalk.dim(`Total: ${stats.total} comments from ${authorList}`));
501
- console.log();
502
- if (!options.withText) {
503
- console.log(chalk.dim(`Tip: Use --with-text to extract the highlighted text content`));
504
- }
505
- console.log(chalk.dim(`Tip: Use --append <file.md> to add comments to your markdown`));
506
-
507
- } catch (err) {
508
- spin.stop();
509
- const error = err as Error;
510
- console.error(fmt.status('error', `Failed to extract PDF comments: ${error.message}`));
511
- if (process.env.DEBUG) console.error(error.stack);
512
- process.exit(1);
513
- }
514
- });
515
- }