docrev 0.10.1 → 0.10.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 (119) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +184 -173
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  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/anchor-match.d.ts +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +47 -17
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/sync.d.ts.map +1 -1
  16. package/dist/lib/commands/sync.js +78 -100
  17. package/dist/lib/commands/sync.js.map +1 -1
  18. package/dist/lib/commands/utilities.js +164 -164
  19. package/dist/lib/commands/word-tools.js +8 -8
  20. package/dist/lib/grammar.js +3 -3
  21. package/dist/lib/macro-filter.lua +201 -201
  22. package/dist/lib/pdf-comments.js +44 -44
  23. package/dist/lib/plugins.js +57 -57
  24. package/dist/lib/pptx-color-filter.lua +37 -37
  25. package/dist/lib/pptx-themes.js +115 -115
  26. package/dist/lib/sections.d.ts.map +1 -1
  27. package/dist/lib/sections.js +5 -2
  28. package/dist/lib/sections.js.map +1 -1
  29. package/dist/lib/spelling.js +2 -2
  30. package/dist/lib/templates.js +387 -387
  31. package/dist/lib/themes.js +51 -51
  32. package/eslint.config.js +27 -27
  33. package/issues.md +180 -0
  34. package/lib/anchor-match.ts +308 -276
  35. package/lib/annotations.ts +644 -644
  36. package/lib/build.ts +1766 -1766
  37. package/lib/citations.ts +160 -160
  38. package/lib/commands/build.ts +855 -855
  39. package/lib/commands/citations.ts +515 -515
  40. package/lib/commands/comments.ts +1050 -1050
  41. package/lib/commands/context.ts +176 -176
  42. package/lib/commands/core.ts +309 -309
  43. package/lib/commands/doi.ts +435 -435
  44. package/lib/commands/file-ops.ts +372 -372
  45. package/lib/commands/history.ts +320 -320
  46. package/lib/commands/index.ts +87 -87
  47. package/lib/commands/init.ts +259 -259
  48. package/lib/commands/merge-resolve.ts +378 -378
  49. package/lib/commands/preview.ts +178 -178
  50. package/lib/commands/project-info.ts +244 -244
  51. package/lib/commands/quality.ts +517 -517
  52. package/lib/commands/response.ts +454 -454
  53. package/lib/commands/section-boundaries.ts +82 -82
  54. package/lib/commands/sections.ts +451 -451
  55. package/lib/commands/sync.ts +676 -709
  56. package/lib/commands/text-ops.ts +449 -449
  57. package/lib/commands/utilities.ts +448 -448
  58. package/lib/commands/verify-anchors.ts +272 -272
  59. package/lib/commands/word-tools.ts +340 -340
  60. package/lib/comment-realign.ts +517 -517
  61. package/lib/config.ts +84 -84
  62. package/lib/crossref.ts +781 -781
  63. package/lib/csl.ts +191 -191
  64. package/lib/dependencies.ts +98 -98
  65. package/lib/diff-engine.ts +465 -465
  66. package/lib/doi-cache.ts +115 -115
  67. package/lib/doi.ts +897 -897
  68. package/lib/equations.ts +506 -506
  69. package/lib/errors.ts +346 -346
  70. package/lib/format.ts +541 -541
  71. package/lib/git.ts +326 -326
  72. package/lib/grammar.ts +303 -303
  73. package/lib/image-registry.ts +180 -180
  74. package/lib/import.ts +911 -911
  75. package/lib/journals.ts +543 -543
  76. package/lib/macro-filter.lua +201 -201
  77. package/lib/macros.ts +273 -273
  78. package/lib/merge.ts +633 -633
  79. package/lib/orcid.ts +144 -144
  80. package/lib/pdf-comments.ts +263 -263
  81. package/lib/pdf-import.ts +524 -524
  82. package/lib/plugins.ts +362 -362
  83. package/lib/postprocess.ts +188 -188
  84. package/lib/pptx-color-filter.lua +37 -37
  85. package/lib/pptx-template.ts +469 -469
  86. package/lib/pptx-themes.ts +483 -483
  87. package/lib/protect-restore.ts +520 -520
  88. package/lib/rate-limiter.ts +94 -94
  89. package/lib/response.ts +197 -197
  90. package/lib/restore-references.ts +240 -240
  91. package/lib/review.ts +327 -327
  92. package/lib/schema.ts +488 -488
  93. package/lib/scientific-words.ts +73 -73
  94. package/lib/sections.ts +428 -425
  95. package/lib/slides.ts +756 -756
  96. package/lib/spelling.ts +334 -334
  97. package/lib/templates.ts +526 -526
  98. package/lib/themes.ts +742 -742
  99. package/lib/trackchanges.ts +247 -247
  100. package/lib/tui.ts +450 -450
  101. package/lib/types.ts +550 -550
  102. package/lib/undo.ts +250 -250
  103. package/lib/utils.ts +69 -69
  104. package/lib/variables.ts +179 -179
  105. package/lib/word-extraction.ts +806 -806
  106. package/lib/word.ts +643 -643
  107. package/lib/wordcomments.ts +840 -840
  108. package/package.json +137 -137
  109. package/scripts/postbuild.js +47 -47
  110. package/site/assets/extra.css +208 -0
  111. package/site/commands.html +926 -0
  112. package/site/configuration.html +469 -0
  113. package/site/index.html +288 -0
  114. package/site/troubleshooting.html +461 -0
  115. package/site/workflow.html +518 -0
  116. package/skill/REFERENCE.md +539 -539
  117. package/skill/SKILL.md +295 -295
  118. package/tsconfig.json +26 -26
  119. package/types/index.d.ts +525 -525
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
+ }