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
package/lib/format.ts CHANGED
@@ -1,541 +1,541 @@
1
- /**
2
- * Formatting utilities for CLI output
3
- * Tables, boxes, spinners, progress bars
4
- */
5
-
6
- import chalk from 'chalk';
7
-
8
- // Type definitions for function parameters
9
- interface TableOptions {
10
- align?: Array<'left' | 'right' | 'center'>;
11
- headerStyle?: (text: string) => string;
12
- borderStyle?: (text: string) => string;
13
- cellStyle?: ((value: string, colIndex: number, rowIndex: number) => string) | null;
14
- }
15
-
16
- interface SimpleTableOptions {
17
- headerStyle?: (text: string) => string;
18
- indent?: string;
19
- }
20
-
21
- interface BoxOptions {
22
- title?: string | null;
23
- padding?: number;
24
- borderStyle?: (text: string) => string;
25
- titleStyle?: (text: string) => string;
26
- }
27
-
28
- interface StatsOptions {
29
- title?: string | null;
30
- }
31
-
32
- interface ProgressOptions {
33
- width?: number;
34
- label?: string;
35
- }
36
-
37
- interface InlineDiffPreviewOptions {
38
- maxLines?: number;
39
- contextChars?: number;
40
- }
41
-
42
- interface HeaderOptions {
43
- style?: (text: string) => string;
44
- width?: number;
45
- }
46
-
47
- interface Spinner {
48
- text: string;
49
- start: () => Spinner;
50
- stop: (finalMessage?: string | null) => Spinner;
51
- success: (msg?: string) => Spinner;
52
- error: (msg?: string) => Spinner;
53
- }
54
-
55
- interface ProgressBar {
56
- update: (n: number) => ProgressBar;
57
- increment: () => ProgressBar;
58
- done: (message?: string) => ProgressBar;
59
- }
60
-
61
- /**
62
- * Format a table with borders and alignment
63
- * @param headers - Column headers
64
- * @param rows - Row data
65
- * @param options - Formatting options
66
- * @returns Formatted table string
67
- */
68
- export function table(headers: string[], rows: string[][], options: TableOptions = {}): string {
69
- const {
70
- align = headers.map(() => 'left'), // 'left', 'right', 'center'
71
- headerStyle = chalk.bold.cyan,
72
- borderStyle = chalk.dim,
73
- cellStyle = null, // function(value, colIndex, rowIndex) => styled string
74
- } = options;
75
-
76
- // Calculate column widths
77
- const widths = headers.map((h, i) => {
78
- const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
79
- return Math.max(stripAnsi(h), ...cellWidths);
80
- });
81
-
82
- // Border characters
83
- const border = {
84
- topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
85
- horizontal: '─', vertical: '│',
86
- leftT: '├', rightT: '┤', topT: '┬', bottomT: '┴', cross: '┼',
87
- };
88
-
89
- // Build lines
90
- const lines: string[] = [];
91
-
92
- // Top border
93
- const topBorder = border.topLeft +
94
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.topT) +
95
- border.topRight;
96
- lines.push(borderStyle(topBorder));
97
-
98
- // Header row
99
- const headerRow = border.vertical +
100
- headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left') + ' ').join(border.vertical) +
101
- border.vertical;
102
- lines.push(borderStyle(border.vertical) +
103
- headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left', stripAnsi(h)) + ' ').join(borderStyle(border.vertical)) +
104
- borderStyle(border.vertical));
105
-
106
- // Header separator
107
- const headerSep = border.leftT +
108
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.cross) +
109
- border.rightT;
110
- lines.push(borderStyle(headerSep));
111
-
112
- // Data rows
113
- for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
114
- const row = rows[rowIdx];
115
- if (!row) continue;
116
- const cells = row.map((cell, colIdx) => {
117
- let value = String(cell || '');
118
- if (cellStyle) {
119
- value = cellStyle(value, colIdx, rowIdx);
120
- }
121
- const plainLen = stripAnsi(String(cell || ''));
122
- return ' ' + pad(value, widths[colIdx] || 0, align[colIdx] || 'left', plainLen) + ' ';
123
- });
124
- lines.push(borderStyle(border.vertical) + cells.join(borderStyle(border.vertical)) + borderStyle(border.vertical));
125
- }
126
-
127
- // Bottom border
128
- const bottomBorder = border.bottomLeft +
129
- widths.map(w => border.horizontal.repeat(w + 2)).join(border.bottomT) +
130
- border.bottomRight;
131
- lines.push(borderStyle(bottomBorder));
132
-
133
- return lines.join('\n');
134
- }
135
-
136
- /**
137
- * Simple table without borders (compact)
138
- */
139
- export function simpleTable(headers: string[], rows: string[][], options: SimpleTableOptions = {}): string {
140
- const { headerStyle = chalk.dim, indent = ' ' } = options;
141
-
142
- const widths = headers.map((h, i) => {
143
- const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
144
- return Math.max(stripAnsi(h), ...cellWidths);
145
- });
146
-
147
- const lines: string[] = [];
148
- lines.push(indent + headers.map((h, i) => headerStyle(pad(h, widths[i] || 0, 'left'))).join(' '));
149
- lines.push(indent + widths.map(w => chalk.dim('─'.repeat(w))).join(' '));
150
-
151
- for (const row of rows) {
152
- lines.push(indent + row.map((cell, i) => pad(String(cell || ''), widths[i] || 0, 'left')).join(' '));
153
- }
154
-
155
- return lines.join('\n');
156
- }
157
-
158
- /**
159
- * Format a box around content
160
- */
161
- export function box(content: string, options: BoxOptions = {}): string {
162
- const {
163
- title = null,
164
- padding = 1,
165
- borderStyle = chalk.dim,
166
- titleStyle = chalk.bold.cyan,
167
- } = options;
168
-
169
- const lines = content.split('\n');
170
- const maxWidth = Math.max(...lines.map(l => stripAnsi(l)), title ? stripAnsi(title) + 4 : 0);
171
-
172
- const border = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
173
- const result: string[] = [];
174
-
175
- // Top border with optional title
176
- if (title) {
177
- const titlePart = ` ${titleStyle(title)} `;
178
- const remaining = maxWidth + 2 - stripAnsi(titlePart);
179
- result.push(borderStyle(border.tl + border.h) + titlePart + borderStyle(border.h.repeat(remaining) + border.tr));
180
- } else {
181
- result.push(borderStyle(border.tl + border.h.repeat(maxWidth + 2) + border.tr));
182
- }
183
-
184
- // Padding top
185
- for (let i = 0; i < padding; i++) {
186
- result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
187
- }
188
-
189
- // Content
190
- for (const line of lines) {
191
- const plainLen = stripAnsi(line);
192
- const padded = line + ' '.repeat(maxWidth - plainLen);
193
- result.push(borderStyle(border.v) + ' ' + padded + ' ' + borderStyle(border.v));
194
- }
195
-
196
- // Padding bottom
197
- for (let i = 0; i < padding; i++) {
198
- result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
199
- }
200
-
201
- // Bottom border
202
- result.push(borderStyle(border.bl + border.h.repeat(maxWidth + 2) + border.br));
203
-
204
- return result.join('\n');
205
- }
206
-
207
- /**
208
- * Summary stats in a nice format
209
- */
210
- export function stats(data: Record<string, string | number>, options: StatsOptions = {}): string {
211
- const { title = null } = options;
212
-
213
- const lines: string[] = [];
214
- if (title) {
215
- lines.push(chalk.bold.cyan(title));
216
- lines.push('');
217
- }
218
-
219
- const keys = Object.keys(data);
220
- const maxKeyLen = keys.length > 0 ? Math.max(...keys.map(k => k.length)) : 0;
221
-
222
- for (const [key, value] of Object.entries(data)) {
223
- const label = chalk.dim(key.padEnd(maxKeyLen) + ':');
224
- lines.push(` ${label} ${value}`);
225
- }
226
-
227
- return lines.join('\n');
228
- }
229
-
230
- /**
231
- * Progress indicator
232
- */
233
- export function progress(current: number, total: number, options: ProgressOptions = {}): string {
234
- const { width = 30, label = '' } = options;
235
- const pct = Math.round((current / total) * 100);
236
- const filled = Math.round((current / total) * width);
237
- const empty = width - filled;
238
-
239
- const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
240
- return `${label}${bar} ${pct}% (${current}/${total})`;
241
- }
242
-
243
- // Global setting for emoji usage
244
- let useEmoji = false;
245
-
246
- export function setEmoji(enabled: boolean): void {
247
- useEmoji = enabled;
248
- }
249
-
250
- /**
251
- * Status line with icon
252
- */
253
- export function status(type: string, message: string): string {
254
- const textIcons: Record<string, string> = {
255
- success: chalk.green('✓'),
256
- error: chalk.red('✗'),
257
- warning: chalk.yellow('!'),
258
- info: chalk.blue('i'),
259
- comment: chalk.blue('#'),
260
- file: chalk.cyan('·'),
261
- folder: chalk.cyan('>'),
262
- build: chalk.magenta('*'),
263
- import: chalk.cyan('<'),
264
- export: chalk.cyan('>'),
265
- };
266
-
267
- const emojiIcons: Record<string, string> = {
268
- success: chalk.green('✓'),
269
- error: chalk.red('✗'),
270
- warning: chalk.yellow('⚠'),
271
- info: chalk.blue('ℹ'),
272
- comment: chalk.blue('💬'),
273
- file: chalk.cyan('📄'),
274
- folder: chalk.cyan('📁'),
275
- build: chalk.magenta('🔨'),
276
- import: chalk.cyan('📥'),
277
- export: chalk.cyan('📤'),
278
- };
279
-
280
- const icons = useEmoji ? emojiIcons : textIcons;
281
- const icon = icons[type] || chalk.dim('•');
282
- return `${icon} ${message}`;
283
- }
284
-
285
- /**
286
- * Pulsing star spinner frames (Claude-style)
287
- * Cycles through star brightness using unicode stars
288
- */
289
- const starFrames = ['✦', '✧', '✦', '✧', '⋆', '✧', '✦', '✧'];
290
- const starColors = [
291
- chalk.yellow,
292
- chalk.yellow.dim,
293
- chalk.white,
294
- chalk.yellow.dim,
295
- chalk.dim,
296
- chalk.yellow.dim,
297
- chalk.white,
298
- chalk.yellow.dim,
299
- ];
300
-
301
- /**
302
- * Create a pulsing star spinner for async operations
303
- */
304
- export function spinner(message: string): Spinner {
305
- let frameIndex = 0;
306
- let interval: NodeJS.Timeout | null = null;
307
-
308
- const spin: Spinner = {
309
- text: message,
310
- start() {
311
- process.stdout.write('\x1B[?25l'); // Hide cursor
312
- interval = setInterval(() => {
313
- const colorFn = starColors[frameIndex];
314
- const frameChr = starFrames[frameIndex];
315
- if (colorFn && frameChr) {
316
- const frame = colorFn(frameChr);
317
- process.stdout.write(`\r${frame} ${spin.text}`);
318
- }
319
- frameIndex = (frameIndex + 1) % starFrames.length;
320
- }, 120);
321
- return spin;
322
- },
323
- stop(finalMessage: string | null = null) {
324
- if (interval) {
325
- clearInterval(interval);
326
- interval = null;
327
- }
328
- process.stdout.write('\r\x1B[K'); // Clear line
329
- process.stdout.write('\x1B[?25h'); // Show cursor
330
- if (finalMessage) {
331
- console.log(finalMessage);
332
- }
333
- return spin;
334
- },
335
- success(msg?: string) {
336
- return spin.stop(status('success', msg || message));
337
- },
338
- error(msg?: string) {
339
- return spin.stop(status('error', msg || message));
340
- },
341
- };
342
-
343
- return spin;
344
- }
345
-
346
- /**
347
- * Create a progress bar for batch operations
348
- * @param total - Total number of items
349
- * @param label - Label for the progress bar
350
- * @returns Progress bar controller with update(), increment(), and done()
351
- */
352
- export function progressBar(total: number, label: string = 'Progress'): ProgressBar {
353
- let current = 0;
354
- const barWidth = 30;
355
-
356
- const bar: ProgressBar = {
357
- update(n: number) {
358
- current = Math.min(n, total);
359
- const percent = Math.floor((current / total) * 100);
360
- const filled = Math.floor((current / total) * barWidth);
361
- const empty = barWidth - filled;
362
- const filledBar = chalk.cyan('█'.repeat(filled));
363
- const emptyBar = chalk.dim('░'.repeat(empty));
364
- process.stdout.write(`\r${label} [${filledBar}${emptyBar}] ${percent}% (${current}/${total})`);
365
- return bar;
366
- },
367
- increment() {
368
- return bar.update(current + 1);
369
- },
370
- done(message?: string) {
371
- process.stdout.write('\r\x1B[K'); // Clear line
372
- if (message) {
373
- console.log(status('success', message));
374
- }
375
- return bar;
376
- },
377
- };
378
-
379
- return bar;
380
- }
381
-
382
- /**
383
- * Diff display with inline highlighting
384
- */
385
- export function diff(insertions: number, deletions: number, substitutions: number): string {
386
- const lines: string[] = [];
387
-
388
- if (insertions > 0) {
389
- lines.push(chalk.green(` + ${insertions} insertion${insertions !== 1 ? 's' : ''}`));
390
- }
391
- if (deletions > 0) {
392
- lines.push(chalk.red(` - ${deletions} deletion${deletions !== 1 ? 's' : ''}`));
393
- }
394
- if (substitutions > 0) {
395
- lines.push(chalk.yellow(` ~ ${substitutions} substitution${substitutions !== 1 ? 's' : ''}`));
396
- }
397
-
398
- return lines.join('\n');
399
- }
400
-
401
- /**
402
- * Show inline diff preview for CriticMarkup changes
403
- * @param text - Text with CriticMarkup annotations
404
- * @param options - Display options
405
- * @returns Formatted preview string
406
- */
407
- export function inlineDiffPreview(text: string, options: InlineDiffPreviewOptions = {}): string {
408
- const { maxLines = 10, contextChars = 40 } = options;
409
- const lines: string[] = [];
410
-
411
- // Find all changes
412
- const changes: Array<{
413
- type: 'insert' | 'delete' | 'substitute';
414
- content?: string;
415
- oldContent?: string;
416
- newContent?: string;
417
- index: number;
418
- fullMatch: string;
419
- }> = [];
420
-
421
- // Insertions: {++text++}
422
- const insertPattern = /\{\+\+([^+]*)\+\+\}/g;
423
- let match: RegExpExecArray | null;
424
- while ((match = insertPattern.exec(text)) !== null) {
425
- changes.push({
426
- type: 'insert',
427
- content: match[1],
428
- index: match.index,
429
- fullMatch: match[0],
430
- });
431
- }
432
-
433
- // Deletions: {--text--}
434
- const deletePattern = /\{--([^-]*)--\}/g;
435
- while ((match = deletePattern.exec(text)) !== null) {
436
- changes.push({
437
- type: 'delete',
438
- content: match[1],
439
- index: match.index,
440
- fullMatch: match[0],
441
- });
442
- }
443
-
444
- // Substitutions: {~~old~>new~~}
445
- const subPattern = /\{~~([^~]*)~>([^~]*)~~\}/g;
446
- while ((match = subPattern.exec(text)) !== null) {
447
- changes.push({
448
- type: 'substitute',
449
- oldContent: match[1],
450
- newContent: match[2],
451
- index: match.index,
452
- fullMatch: match[0],
453
- });
454
- }
455
-
456
- // Sort by position
457
- changes.sort((a, b) => a.index - b.index);
458
-
459
- // Show preview for each change (up to maxLines)
460
- const shown = changes.slice(0, maxLines);
461
-
462
- for (const change of shown) {
463
- // Get context
464
- const before = text.slice(Math.max(0, change.index - contextChars), change.index)
465
- .replace(/\n/g, ' ').trim();
466
- const afterIdx = change.index + change.fullMatch.length;
467
- const after = text.slice(afterIdx, afterIdx + contextChars)
468
- .replace(/\n/g, ' ').trim();
469
-
470
- let preview = '';
471
- if (change.type === 'insert') {
472
- preview = chalk.dim(before) + chalk.green.bold('+' + change.content) + chalk.dim(after);
473
- lines.push(chalk.green(' + ') + truncate(preview, 80));
474
- } else if (change.type === 'delete') {
475
- preview = chalk.dim(before) + chalk.red.bold('-' + change.content) + chalk.dim(after);
476
- lines.push(chalk.red(' - ') + truncate(preview, 80));
477
- } else if (change.type === 'substitute') {
478
- preview = chalk.dim(before) +
479
- chalk.red.strikethrough(change.oldContent || '') +
480
- chalk.green.bold(change.newContent || '') +
481
- chalk.dim(after);
482
- lines.push(chalk.yellow(' ~ ') + truncate(preview, 80));
483
- }
484
- }
485
-
486
- if (changes.length > maxLines) {
487
- lines.push(chalk.dim(` ... and ${changes.length - maxLines} more changes`));
488
- }
489
-
490
- return lines.join('\n');
491
- }
492
-
493
- /**
494
- * Truncate string to max length
495
- */
496
- function truncate(str: string, maxLen: number): string {
497
- const plain = stripAnsiStr(str);
498
- if (plain.length <= maxLen) return str;
499
- // This is approximate since we have ANSI codes
500
- return str.slice(0, maxLen + (str.length - plain.length)) + chalk.dim('...');
501
- }
502
-
503
- /**
504
- * Section header
505
- */
506
- export function header(text: string, options: HeaderOptions = {}): string {
507
- const { style = chalk.bold.cyan, width = 60 } = options;
508
- const padding = Math.max(0, width - text.length - 4);
509
- return style(`── ${text} ${'─'.repeat(padding)}`);
510
- }
511
-
512
- /**
513
- * Strip ANSI codes for length calculation
514
- */
515
- function stripAnsi(str: string): number {
516
- return str.replace(/\x1b\[[0-9;]*m/g, '').length;
517
- }
518
-
519
- /**
520
- * Strip ANSI codes and return string
521
- */
522
- function stripAnsiStr(str: string): string {
523
- return str.replace(/\x1b\[[0-9;]*m/g, '');
524
- }
525
-
526
- /**
527
- * Pad string with alignment
528
- */
529
- function pad(str: string, width: number, align: 'left' | 'right' | 'center', strLen: number | null = null): string {
530
- const len = strLen !== null ? strLen : stripAnsi(str);
531
- const padding = Math.max(0, width - len);
532
-
533
- if (align === 'right') {
534
- return ' '.repeat(padding) + str;
535
- } else if (align === 'center') {
536
- const left = Math.floor(padding / 2);
537
- const right = padding - left;
538
- return ' '.repeat(left) + str + ' '.repeat(right);
539
- }
540
- return str + ' '.repeat(padding);
541
- }
1
+ /**
2
+ * Formatting utilities for CLI output
3
+ * Tables, boxes, spinners, progress bars
4
+ */
5
+
6
+ import chalk from 'chalk';
7
+
8
+ // Type definitions for function parameters
9
+ interface TableOptions {
10
+ align?: Array<'left' | 'right' | 'center'>;
11
+ headerStyle?: (text: string) => string;
12
+ borderStyle?: (text: string) => string;
13
+ cellStyle?: ((value: string, colIndex: number, rowIndex: number) => string) | null;
14
+ }
15
+
16
+ interface SimpleTableOptions {
17
+ headerStyle?: (text: string) => string;
18
+ indent?: string;
19
+ }
20
+
21
+ interface BoxOptions {
22
+ title?: string | null;
23
+ padding?: number;
24
+ borderStyle?: (text: string) => string;
25
+ titleStyle?: (text: string) => string;
26
+ }
27
+
28
+ interface StatsOptions {
29
+ title?: string | null;
30
+ }
31
+
32
+ interface ProgressOptions {
33
+ width?: number;
34
+ label?: string;
35
+ }
36
+
37
+ interface InlineDiffPreviewOptions {
38
+ maxLines?: number;
39
+ contextChars?: number;
40
+ }
41
+
42
+ interface HeaderOptions {
43
+ style?: (text: string) => string;
44
+ width?: number;
45
+ }
46
+
47
+ interface Spinner {
48
+ text: string;
49
+ start: () => Spinner;
50
+ stop: (finalMessage?: string | null) => Spinner;
51
+ success: (msg?: string) => Spinner;
52
+ error: (msg?: string) => Spinner;
53
+ }
54
+
55
+ interface ProgressBar {
56
+ update: (n: number) => ProgressBar;
57
+ increment: () => ProgressBar;
58
+ done: (message?: string) => ProgressBar;
59
+ }
60
+
61
+ /**
62
+ * Format a table with borders and alignment
63
+ * @param headers - Column headers
64
+ * @param rows - Row data
65
+ * @param options - Formatting options
66
+ * @returns Formatted table string
67
+ */
68
+ export function table(headers: string[], rows: string[][], options: TableOptions = {}): string {
69
+ const {
70
+ align = headers.map(() => 'left'), // 'left', 'right', 'center'
71
+ headerStyle = chalk.bold.cyan,
72
+ borderStyle = chalk.dim,
73
+ cellStyle = null, // function(value, colIndex, rowIndex) => styled string
74
+ } = options;
75
+
76
+ // Calculate column widths
77
+ const widths = headers.map((h, i) => {
78
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
79
+ return Math.max(stripAnsi(h), ...cellWidths);
80
+ });
81
+
82
+ // Border characters
83
+ const border = {
84
+ topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
85
+ horizontal: '─', vertical: '│',
86
+ leftT: '├', rightT: '┤', topT: '┬', bottomT: '┴', cross: '┼',
87
+ };
88
+
89
+ // Build lines
90
+ const lines: string[] = [];
91
+
92
+ // Top border
93
+ const topBorder = border.topLeft +
94
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.topT) +
95
+ border.topRight;
96
+ lines.push(borderStyle(topBorder));
97
+
98
+ // Header row
99
+ const headerRow = border.vertical +
100
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left') + ' ').join(border.vertical) +
101
+ border.vertical;
102
+ lines.push(borderStyle(border.vertical) +
103
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i] || 0, align[i] || 'left', stripAnsi(h)) + ' ').join(borderStyle(border.vertical)) +
104
+ borderStyle(border.vertical));
105
+
106
+ // Header separator
107
+ const headerSep = border.leftT +
108
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.cross) +
109
+ border.rightT;
110
+ lines.push(borderStyle(headerSep));
111
+
112
+ // Data rows
113
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
114
+ const row = rows[rowIdx];
115
+ if (!row) continue;
116
+ const cells = row.map((cell, colIdx) => {
117
+ let value = String(cell || '');
118
+ if (cellStyle) {
119
+ value = cellStyle(value, colIdx, rowIdx);
120
+ }
121
+ const plainLen = stripAnsi(String(cell || ''));
122
+ return ' ' + pad(value, widths[colIdx] || 0, align[colIdx] || 'left', plainLen) + ' ';
123
+ });
124
+ lines.push(borderStyle(border.vertical) + cells.join(borderStyle(border.vertical)) + borderStyle(border.vertical));
125
+ }
126
+
127
+ // Bottom border
128
+ const bottomBorder = border.bottomLeft +
129
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.bottomT) +
130
+ border.bottomRight;
131
+ lines.push(borderStyle(bottomBorder));
132
+
133
+ return lines.join('\n');
134
+ }
135
+
136
+ /**
137
+ * Simple table without borders (compact)
138
+ */
139
+ export function simpleTable(headers: string[], rows: string[][], options: SimpleTableOptions = {}): string {
140
+ const { headerStyle = chalk.dim, indent = ' ' } = options;
141
+
142
+ const widths = headers.map((h, i) => {
143
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')));
144
+ return Math.max(stripAnsi(h), ...cellWidths);
145
+ });
146
+
147
+ const lines: string[] = [];
148
+ lines.push(indent + headers.map((h, i) => headerStyle(pad(h, widths[i] || 0, 'left'))).join(' '));
149
+ lines.push(indent + widths.map(w => chalk.dim('─'.repeat(w))).join(' '));
150
+
151
+ for (const row of rows) {
152
+ lines.push(indent + row.map((cell, i) => pad(String(cell || ''), widths[i] || 0, 'left')).join(' '));
153
+ }
154
+
155
+ return lines.join('\n');
156
+ }
157
+
158
+ /**
159
+ * Format a box around content
160
+ */
161
+ export function box(content: string, options: BoxOptions = {}): string {
162
+ const {
163
+ title = null,
164
+ padding = 1,
165
+ borderStyle = chalk.dim,
166
+ titleStyle = chalk.bold.cyan,
167
+ } = options;
168
+
169
+ const lines = content.split('\n');
170
+ const maxWidth = Math.max(...lines.map(l => stripAnsi(l)), title ? stripAnsi(title) + 4 : 0);
171
+
172
+ const border = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
173
+ const result: string[] = [];
174
+
175
+ // Top border with optional title
176
+ if (title) {
177
+ const titlePart = ` ${titleStyle(title)} `;
178
+ const remaining = maxWidth + 2 - stripAnsi(titlePart);
179
+ result.push(borderStyle(border.tl + border.h) + titlePart + borderStyle(border.h.repeat(remaining) + border.tr));
180
+ } else {
181
+ result.push(borderStyle(border.tl + border.h.repeat(maxWidth + 2) + border.tr));
182
+ }
183
+
184
+ // Padding top
185
+ for (let i = 0; i < padding; i++) {
186
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
187
+ }
188
+
189
+ // Content
190
+ for (const line of lines) {
191
+ const plainLen = stripAnsi(line);
192
+ const padded = line + ' '.repeat(maxWidth - plainLen);
193
+ result.push(borderStyle(border.v) + ' ' + padded + ' ' + borderStyle(border.v));
194
+ }
195
+
196
+ // Padding bottom
197
+ for (let i = 0; i < padding; i++) {
198
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
199
+ }
200
+
201
+ // Bottom border
202
+ result.push(borderStyle(border.bl + border.h.repeat(maxWidth + 2) + border.br));
203
+
204
+ return result.join('\n');
205
+ }
206
+
207
+ /**
208
+ * Summary stats in a nice format
209
+ */
210
+ export function stats(data: Record<string, string | number>, options: StatsOptions = {}): string {
211
+ const { title = null } = options;
212
+
213
+ const lines: string[] = [];
214
+ if (title) {
215
+ lines.push(chalk.bold.cyan(title));
216
+ lines.push('');
217
+ }
218
+
219
+ const keys = Object.keys(data);
220
+ const maxKeyLen = keys.length > 0 ? Math.max(...keys.map(k => k.length)) : 0;
221
+
222
+ for (const [key, value] of Object.entries(data)) {
223
+ const label = chalk.dim(key.padEnd(maxKeyLen) + ':');
224
+ lines.push(` ${label} ${value}`);
225
+ }
226
+
227
+ return lines.join('\n');
228
+ }
229
+
230
+ /**
231
+ * Progress indicator
232
+ */
233
+ export function progress(current: number, total: number, options: ProgressOptions = {}): string {
234
+ const { width = 30, label = '' } = options;
235
+ const pct = Math.round((current / total) * 100);
236
+ const filled = Math.round((current / total) * width);
237
+ const empty = width - filled;
238
+
239
+ const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
240
+ return `${label}${bar} ${pct}% (${current}/${total})`;
241
+ }
242
+
243
+ // Global setting for emoji usage
244
+ let useEmoji = false;
245
+
246
+ export function setEmoji(enabled: boolean): void {
247
+ useEmoji = enabled;
248
+ }
249
+
250
+ /**
251
+ * Status line with icon
252
+ */
253
+ export function status(type: string, message: string): string {
254
+ const textIcons: Record<string, string> = {
255
+ success: chalk.green('✓'),
256
+ error: chalk.red('✗'),
257
+ warning: chalk.yellow('!'),
258
+ info: chalk.blue('i'),
259
+ comment: chalk.blue('#'),
260
+ file: chalk.cyan('·'),
261
+ folder: chalk.cyan('>'),
262
+ build: chalk.magenta('*'),
263
+ import: chalk.cyan('<'),
264
+ export: chalk.cyan('>'),
265
+ };
266
+
267
+ const emojiIcons: Record<string, string> = {
268
+ success: chalk.green('✓'),
269
+ error: chalk.red('✗'),
270
+ warning: chalk.yellow('⚠'),
271
+ info: chalk.blue('ℹ'),
272
+ comment: chalk.blue('💬'),
273
+ file: chalk.cyan('📄'),
274
+ folder: chalk.cyan('📁'),
275
+ build: chalk.magenta('🔨'),
276
+ import: chalk.cyan('📥'),
277
+ export: chalk.cyan('📤'),
278
+ };
279
+
280
+ const icons = useEmoji ? emojiIcons : textIcons;
281
+ const icon = icons[type] || chalk.dim('•');
282
+ return `${icon} ${message}`;
283
+ }
284
+
285
+ /**
286
+ * Pulsing star spinner frames (Claude-style)
287
+ * Cycles through star brightness using unicode stars
288
+ */
289
+ const starFrames = ['✦', '✧', '✦', '✧', '⋆', '✧', '✦', '✧'];
290
+ const starColors = [
291
+ chalk.yellow,
292
+ chalk.yellow.dim,
293
+ chalk.white,
294
+ chalk.yellow.dim,
295
+ chalk.dim,
296
+ chalk.yellow.dim,
297
+ chalk.white,
298
+ chalk.yellow.dim,
299
+ ];
300
+
301
+ /**
302
+ * Create a pulsing star spinner for async operations
303
+ */
304
+ export function spinner(message: string): Spinner {
305
+ let frameIndex = 0;
306
+ let interval: NodeJS.Timeout | null = null;
307
+
308
+ const spin: Spinner = {
309
+ text: message,
310
+ start() {
311
+ process.stdout.write('\x1B[?25l'); // Hide cursor
312
+ interval = setInterval(() => {
313
+ const colorFn = starColors[frameIndex];
314
+ const frameChr = starFrames[frameIndex];
315
+ if (colorFn && frameChr) {
316
+ const frame = colorFn(frameChr);
317
+ process.stdout.write(`\r${frame} ${spin.text}`);
318
+ }
319
+ frameIndex = (frameIndex + 1) % starFrames.length;
320
+ }, 120);
321
+ return spin;
322
+ },
323
+ stop(finalMessage: string | null = null) {
324
+ if (interval) {
325
+ clearInterval(interval);
326
+ interval = null;
327
+ }
328
+ process.stdout.write('\r\x1B[K'); // Clear line
329
+ process.stdout.write('\x1B[?25h'); // Show cursor
330
+ if (finalMessage) {
331
+ console.log(finalMessage);
332
+ }
333
+ return spin;
334
+ },
335
+ success(msg?: string) {
336
+ return spin.stop(status('success', msg || message));
337
+ },
338
+ error(msg?: string) {
339
+ return spin.stop(status('error', msg || message));
340
+ },
341
+ };
342
+
343
+ return spin;
344
+ }
345
+
346
+ /**
347
+ * Create a progress bar for batch operations
348
+ * @param total - Total number of items
349
+ * @param label - Label for the progress bar
350
+ * @returns Progress bar controller with update(), increment(), and done()
351
+ */
352
+ export function progressBar(total: number, label: string = 'Progress'): ProgressBar {
353
+ let current = 0;
354
+ const barWidth = 30;
355
+
356
+ const bar: ProgressBar = {
357
+ update(n: number) {
358
+ current = Math.min(n, total);
359
+ const percent = Math.floor((current / total) * 100);
360
+ const filled = Math.floor((current / total) * barWidth);
361
+ const empty = barWidth - filled;
362
+ const filledBar = chalk.cyan('█'.repeat(filled));
363
+ const emptyBar = chalk.dim('░'.repeat(empty));
364
+ process.stdout.write(`\r${label} [${filledBar}${emptyBar}] ${percent}% (${current}/${total})`);
365
+ return bar;
366
+ },
367
+ increment() {
368
+ return bar.update(current + 1);
369
+ },
370
+ done(message?: string) {
371
+ process.stdout.write('\r\x1B[K'); // Clear line
372
+ if (message) {
373
+ console.log(status('success', message));
374
+ }
375
+ return bar;
376
+ },
377
+ };
378
+
379
+ return bar;
380
+ }
381
+
382
+ /**
383
+ * Diff display with inline highlighting
384
+ */
385
+ export function diff(insertions: number, deletions: number, substitutions: number): string {
386
+ const lines: string[] = [];
387
+
388
+ if (insertions > 0) {
389
+ lines.push(chalk.green(` + ${insertions} insertion${insertions !== 1 ? 's' : ''}`));
390
+ }
391
+ if (deletions > 0) {
392
+ lines.push(chalk.red(` - ${deletions} deletion${deletions !== 1 ? 's' : ''}`));
393
+ }
394
+ if (substitutions > 0) {
395
+ lines.push(chalk.yellow(` ~ ${substitutions} substitution${substitutions !== 1 ? 's' : ''}`));
396
+ }
397
+
398
+ return lines.join('\n');
399
+ }
400
+
401
+ /**
402
+ * Show inline diff preview for CriticMarkup changes
403
+ * @param text - Text with CriticMarkup annotations
404
+ * @param options - Display options
405
+ * @returns Formatted preview string
406
+ */
407
+ export function inlineDiffPreview(text: string, options: InlineDiffPreviewOptions = {}): string {
408
+ const { maxLines = 10, contextChars = 40 } = options;
409
+ const lines: string[] = [];
410
+
411
+ // Find all changes
412
+ const changes: Array<{
413
+ type: 'insert' | 'delete' | 'substitute';
414
+ content?: string;
415
+ oldContent?: string;
416
+ newContent?: string;
417
+ index: number;
418
+ fullMatch: string;
419
+ }> = [];
420
+
421
+ // Insertions: {++text++}
422
+ const insertPattern = /\{\+\+([^+]*)\+\+\}/g;
423
+ let match: RegExpExecArray | null;
424
+ while ((match = insertPattern.exec(text)) !== null) {
425
+ changes.push({
426
+ type: 'insert',
427
+ content: match[1],
428
+ index: match.index,
429
+ fullMatch: match[0],
430
+ });
431
+ }
432
+
433
+ // Deletions: {--text--}
434
+ const deletePattern = /\{--([^-]*)--\}/g;
435
+ while ((match = deletePattern.exec(text)) !== null) {
436
+ changes.push({
437
+ type: 'delete',
438
+ content: match[1],
439
+ index: match.index,
440
+ fullMatch: match[0],
441
+ });
442
+ }
443
+
444
+ // Substitutions: {~~old~>new~~}
445
+ const subPattern = /\{~~([^~]*)~>([^~]*)~~\}/g;
446
+ while ((match = subPattern.exec(text)) !== null) {
447
+ changes.push({
448
+ type: 'substitute',
449
+ oldContent: match[1],
450
+ newContent: match[2],
451
+ index: match.index,
452
+ fullMatch: match[0],
453
+ });
454
+ }
455
+
456
+ // Sort by position
457
+ changes.sort((a, b) => a.index - b.index);
458
+
459
+ // Show preview for each change (up to maxLines)
460
+ const shown = changes.slice(0, maxLines);
461
+
462
+ for (const change of shown) {
463
+ // Get context
464
+ const before = text.slice(Math.max(0, change.index - contextChars), change.index)
465
+ .replace(/\n/g, ' ').trim();
466
+ const afterIdx = change.index + change.fullMatch.length;
467
+ const after = text.slice(afterIdx, afterIdx + contextChars)
468
+ .replace(/\n/g, ' ').trim();
469
+
470
+ let preview = '';
471
+ if (change.type === 'insert') {
472
+ preview = chalk.dim(before) + chalk.green.bold('+' + change.content) + chalk.dim(after);
473
+ lines.push(chalk.green(' + ') + truncate(preview, 80));
474
+ } else if (change.type === 'delete') {
475
+ preview = chalk.dim(before) + chalk.red.bold('-' + change.content) + chalk.dim(after);
476
+ lines.push(chalk.red(' - ') + truncate(preview, 80));
477
+ } else if (change.type === 'substitute') {
478
+ preview = chalk.dim(before) +
479
+ chalk.red.strikethrough(change.oldContent || '') +
480
+ chalk.green.bold(change.newContent || '') +
481
+ chalk.dim(after);
482
+ lines.push(chalk.yellow(' ~ ') + truncate(preview, 80));
483
+ }
484
+ }
485
+
486
+ if (changes.length > maxLines) {
487
+ lines.push(chalk.dim(` ... and ${changes.length - maxLines} more changes`));
488
+ }
489
+
490
+ return lines.join('\n');
491
+ }
492
+
493
+ /**
494
+ * Truncate string to max length
495
+ */
496
+ function truncate(str: string, maxLen: number): string {
497
+ const plain = stripAnsiStr(str);
498
+ if (plain.length <= maxLen) return str;
499
+ // This is approximate since we have ANSI codes
500
+ return str.slice(0, maxLen + (str.length - plain.length)) + chalk.dim('...');
501
+ }
502
+
503
+ /**
504
+ * Section header
505
+ */
506
+ export function header(text: string, options: HeaderOptions = {}): string {
507
+ const { style = chalk.bold.cyan, width = 60 } = options;
508
+ const padding = Math.max(0, width - text.length - 4);
509
+ return style(`── ${text} ${'─'.repeat(padding)}`);
510
+ }
511
+
512
+ /**
513
+ * Strip ANSI codes for length calculation
514
+ */
515
+ function stripAnsi(str: string): number {
516
+ return str.replace(/\x1b\[[0-9;]*m/g, '').length;
517
+ }
518
+
519
+ /**
520
+ * Strip ANSI codes and return string
521
+ */
522
+ function stripAnsiStr(str: string): string {
523
+ return str.replace(/\x1b\[[0-9;]*m/g, '');
524
+ }
525
+
526
+ /**
527
+ * Pad string with alignment
528
+ */
529
+ function pad(str: string, width: number, align: 'left' | 'right' | 'center', strLen: number | null = null): string {
530
+ const len = strLen !== null ? strLen : stripAnsi(str);
531
+ const padding = Math.max(0, width - len);
532
+
533
+ if (align === 'right') {
534
+ return ' '.repeat(padding) + str;
535
+ } else if (align === 'center') {
536
+ const left = Math.floor(padding / 2);
537
+ const right = padding - left;
538
+ return ' '.repeat(left) + str + ' '.repeat(right);
539
+ }
540
+ return str + ' '.repeat(padding);
541
+ }