docrev 0.2.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.
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Equation extraction and conversion utilities
3
+ * Handle LaTeX math in Markdown ↔ Word workflows
4
+ */
5
+
6
+ import * as fs from 'fs';
7
+ import * as path from 'path';
8
+ import { exec } from 'child_process';
9
+ import { promisify } from 'util';
10
+
11
+ const execAsync = promisify(exec);
12
+
13
+ /**
14
+ * Extract all equations from markdown text
15
+ * @param {string} text
16
+ * @param {string} file - Source file name
17
+ * @returns {Array<{type: 'inline'|'display', content: string, line: number, file: string}>}
18
+ */
19
+ export function extractEquations(text, file = '') {
20
+ const equations = [];
21
+ const lines = text.split('\n');
22
+
23
+ let inDisplayMath = false;
24
+ let displayMathStart = 0;
25
+ let displayMathContent = '';
26
+
27
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
28
+ const line = lines[lineNum];
29
+
30
+ // Skip code blocks
31
+ if (line.trim().startsWith('```')) continue;
32
+
33
+ // Handle display math blocks ($$...$$)
34
+ if (line.includes('$$')) {
35
+ const parts = line.split('$$');
36
+
37
+ if (!inDisplayMath && parts.length >= 3) {
38
+ // Single-line display math: $$content$$
39
+ for (let i = 1; i < parts.length; i += 2) {
40
+ if (parts[i].trim()) {
41
+ equations.push({
42
+ type: 'display',
43
+ content: parts[i].trim(),
44
+ line: lineNum + 1,
45
+ file,
46
+ });
47
+ }
48
+ }
49
+ } else if (!inDisplayMath) {
50
+ // Start of multi-line display math
51
+ inDisplayMath = true;
52
+ displayMathStart = lineNum + 1;
53
+ displayMathContent = parts[1] || '';
54
+ } else {
55
+ // End of multi-line display math
56
+ inDisplayMath = false;
57
+ displayMathContent += '\n' + (parts[0] || '');
58
+ if (displayMathContent.trim()) {
59
+ equations.push({
60
+ type: 'display',
61
+ content: displayMathContent.trim(),
62
+ line: displayMathStart,
63
+ file,
64
+ });
65
+ }
66
+ displayMathContent = '';
67
+ }
68
+ continue;
69
+ }
70
+
71
+ if (inDisplayMath) {
72
+ displayMathContent += '\n' + line;
73
+ continue;
74
+ }
75
+
76
+ // Handle inline math ($...$)
77
+ // Careful not to match $$ or escaped \$
78
+ const inlinePattern = /(?<!\$)\$(?!\$)([^$\n]+)\$(?!\$)/g;
79
+ let match;
80
+ while ((match = inlinePattern.exec(line)) !== null) {
81
+ equations.push({
82
+ type: 'inline',
83
+ content: match[1].trim(),
84
+ line: lineNum + 1,
85
+ file,
86
+ });
87
+ }
88
+ }
89
+
90
+ return equations;
91
+ }
92
+
93
+ /**
94
+ * Generate a markdown document with numbered equations
95
+ * Useful for creating an equation reference sheet
96
+ * @param {Array} equations
97
+ * @returns {string}
98
+ */
99
+ export function generateEquationSheet(equations) {
100
+ const lines = [];
101
+ lines.push('# Equations');
102
+ lines.push('');
103
+
104
+ let displayNum = 0;
105
+ let inlineNum = 0;
106
+
107
+ // Group by file
108
+ const byFile = new Map();
109
+ for (const eq of equations) {
110
+ if (!byFile.has(eq.file)) {
111
+ byFile.set(eq.file, []);
112
+ }
113
+ byFile.get(eq.file).push(eq);
114
+ }
115
+
116
+ for (const [file, fileEqs] of byFile) {
117
+ if (file) {
118
+ lines.push(`## ${file}`);
119
+ lines.push('');
120
+ }
121
+
122
+ for (const eq of fileEqs) {
123
+ if (eq.type === 'display') {
124
+ displayNum++;
125
+ lines.push(`### Equation ${displayNum} (line ${eq.line})`);
126
+ lines.push('');
127
+ lines.push('```latex');
128
+ lines.push(eq.content);
129
+ lines.push('```');
130
+ lines.push('');
131
+ lines.push('$$' + eq.content + '$$');
132
+ lines.push('');
133
+ } else {
134
+ inlineNum++;
135
+ lines.push(`- **Inline ${inlineNum}** (line ${eq.line}): \`$${eq.content}$\` → $${eq.content}$`);
136
+ }
137
+ }
138
+ lines.push('');
139
+ }
140
+
141
+ lines.push('---');
142
+ lines.push(`Total: ${displayNum} display equations, ${inlineNum} inline equations`);
143
+
144
+ return lines.join('\n');
145
+ }
146
+
147
+ /**
148
+ * Convert markdown with equations to Word using pandoc
149
+ * @param {string} inputPath - Input markdown file
150
+ * @param {string} outputPath - Output docx file
151
+ * @param {object} options
152
+ * @returns {Promise<{success: boolean, message: string}>}
153
+ */
154
+ export async function convertToWord(inputPath, outputPath, options = {}) {
155
+ const { preserveLatex = false } = options;
156
+
157
+ // Check pandoc is available
158
+ try {
159
+ await execAsync('pandoc --version');
160
+ } catch {
161
+ return { success: false, message: 'Pandoc not found. Install pandoc first.' };
162
+ }
163
+
164
+ // Build pandoc command
165
+ // Use --mathml for better equation rendering in Word
166
+ const args = [
167
+ 'pandoc',
168
+ `"${inputPath}"`,
169
+ '-o', `"${outputPath}"`,
170
+ '--mathml', // Better equation support in Word
171
+ ];
172
+
173
+ if (preserveLatex) {
174
+ // Keep raw LaTeX (less compatible but preserves source)
175
+ args.push('--wrap=preserve');
176
+ }
177
+
178
+ try {
179
+ await execAsync(args.join(' '));
180
+ return { success: true, message: `Created ${outputPath}` };
181
+ } catch (err) {
182
+ return { success: false, message: err.message };
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Create a simple equations-only document
188
+ * @param {string} inputPath - Source markdown
189
+ * @param {string} outputPath - Output path (md or docx)
190
+ * @returns {Promise<{success: boolean, message: string, stats: object}>}
191
+ */
192
+ export async function createEquationsDoc(inputPath, outputPath) {
193
+ if (!fs.existsSync(inputPath)) {
194
+ return { success: false, message: `File not found: ${inputPath}`, stats: null };
195
+ }
196
+
197
+ const text = fs.readFileSync(inputPath, 'utf-8');
198
+ const equations = extractEquations(text, path.basename(inputPath));
199
+
200
+ if (equations.length === 0) {
201
+ return { success: false, message: 'No equations found', stats: { display: 0, inline: 0 } };
202
+ }
203
+
204
+ const sheet = generateEquationSheet(equations);
205
+ const stats = {
206
+ display: equations.filter(e => e.type === 'display').length,
207
+ inline: equations.filter(e => e.type === 'inline').length,
208
+ };
209
+
210
+ const ext = path.extname(outputPath).toLowerCase();
211
+
212
+ if (ext === '.docx') {
213
+ // Write temp md, convert to docx
214
+ const tempMd = outputPath.replace('.docx', '.tmp.md');
215
+ fs.writeFileSync(tempMd, sheet, 'utf-8');
216
+ const result = await convertToWord(tempMd, outputPath);
217
+ fs.unlinkSync(tempMd);
218
+ return { ...result, stats };
219
+ } else {
220
+ // Write as markdown
221
+ fs.writeFileSync(outputPath, sheet, 'utf-8');
222
+ return { success: true, message: `Created ${outputPath}`, stats };
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Get equation statistics for a file or directory
228
+ * @param {string[]} files
229
+ * @returns {object}
230
+ */
231
+ export function getEquationStats(files) {
232
+ let totalDisplay = 0;
233
+ let totalInline = 0;
234
+ const byFile = [];
235
+
236
+ for (const file of files) {
237
+ if (!fs.existsSync(file)) continue;
238
+ const text = fs.readFileSync(file, 'utf-8');
239
+ const equations = extractEquations(text, path.basename(file));
240
+
241
+ const display = equations.filter(e => e.type === 'display').length;
242
+ const inline = equations.filter(e => e.type === 'inline').length;
243
+
244
+ totalDisplay += display;
245
+ totalInline += inline;
246
+
247
+ if (display > 0 || inline > 0) {
248
+ byFile.push({ file: path.basename(file), display, inline });
249
+ }
250
+ }
251
+
252
+ return {
253
+ total: totalDisplay + totalInline,
254
+ display: totalDisplay,
255
+ inline: totalInline,
256
+ byFile,
257
+ };
258
+ }
package/lib/format.js ADDED
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Formatting utilities for CLI output
3
+ * Tables, boxes, spinners, progress bars
4
+ */
5
+
6
+ import chalk from 'chalk';
7
+
8
+ /**
9
+ * Format a table with borders and alignment
10
+ * @param {string[]} headers - Column headers
11
+ * @param {string[][]} rows - Row data
12
+ * @param {object} options - Formatting options
13
+ * @returns {string}
14
+ */
15
+ export function table(headers, rows, options = {}) {
16
+ const {
17
+ align = headers.map(() => 'left'), // 'left', 'right', 'center'
18
+ headerStyle = chalk.bold.cyan,
19
+ borderStyle = chalk.dim,
20
+ cellStyle = null, // function(value, colIndex, rowIndex) => styled string
21
+ } = options;
22
+
23
+ // Calculate column widths
24
+ const widths = headers.map((h, i) => {
25
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')).length);
26
+ return Math.max(stripAnsi(h).length, ...cellWidths);
27
+ });
28
+
29
+ // Border characters
30
+ const border = {
31
+ topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
32
+ horizontal: '─', vertical: '│',
33
+ leftT: '├', rightT: '┤', topT: '┬', bottomT: '┴', cross: '┼',
34
+ };
35
+
36
+ // Build lines
37
+ const lines = [];
38
+
39
+ // Top border
40
+ const topBorder = border.topLeft +
41
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.topT) +
42
+ border.topRight;
43
+ lines.push(borderStyle(topBorder));
44
+
45
+ // Header row
46
+ const headerRow = border.vertical +
47
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i], align[i]) + ' ').join(border.vertical) +
48
+ border.vertical;
49
+ lines.push(borderStyle(border.vertical) +
50
+ headers.map((h, i) => ' ' + pad(headerStyle(h), widths[i], align[i], stripAnsi(h).length) + ' ').join(borderStyle(border.vertical)) +
51
+ borderStyle(border.vertical));
52
+
53
+ // Header separator
54
+ const headerSep = border.leftT +
55
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.cross) +
56
+ border.rightT;
57
+ lines.push(borderStyle(headerSep));
58
+
59
+ // Data rows
60
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
61
+ const row = rows[rowIdx];
62
+ const cells = row.map((cell, colIdx) => {
63
+ let value = String(cell || '');
64
+ if (cellStyle) {
65
+ value = cellStyle(value, colIdx, rowIdx);
66
+ }
67
+ const plainLen = stripAnsi(String(cell || '')).length;
68
+ return ' ' + pad(value, widths[colIdx], align[colIdx], plainLen) + ' ';
69
+ });
70
+ lines.push(borderStyle(border.vertical) + cells.join(borderStyle(border.vertical)) + borderStyle(border.vertical));
71
+ }
72
+
73
+ // Bottom border
74
+ const bottomBorder = border.bottomLeft +
75
+ widths.map(w => border.horizontal.repeat(w + 2)).join(border.bottomT) +
76
+ border.bottomRight;
77
+ lines.push(borderStyle(bottomBorder));
78
+
79
+ return lines.join('\n');
80
+ }
81
+
82
+ /**
83
+ * Simple table without borders (compact)
84
+ */
85
+ export function simpleTable(headers, rows, options = {}) {
86
+ const { headerStyle = chalk.dim, indent = ' ' } = options;
87
+
88
+ const widths = headers.map((h, i) => {
89
+ const cellWidths = rows.map(row => stripAnsi(String(row[i] || '')).length);
90
+ return Math.max(stripAnsi(h).length, ...cellWidths);
91
+ });
92
+
93
+ const lines = [];
94
+ lines.push(indent + headers.map((h, i) => headerStyle(pad(h, widths[i], 'left'))).join(' '));
95
+ lines.push(indent + widths.map(w => chalk.dim('─'.repeat(w))).join(' '));
96
+
97
+ for (const row of rows) {
98
+ lines.push(indent + row.map((cell, i) => pad(String(cell || ''), widths[i], 'left')).join(' '));
99
+ }
100
+
101
+ return lines.join('\n');
102
+ }
103
+
104
+ /**
105
+ * Format a box around content
106
+ */
107
+ export function box(content, options = {}) {
108
+ const {
109
+ title = null,
110
+ padding = 1,
111
+ borderStyle = chalk.dim,
112
+ titleStyle = chalk.bold.cyan,
113
+ } = options;
114
+
115
+ const lines = content.split('\n');
116
+ const maxWidth = Math.max(...lines.map(l => stripAnsi(l).length), title ? stripAnsi(title).length + 4 : 0);
117
+
118
+ const border = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
119
+ const result = [];
120
+
121
+ // Top border with optional title
122
+ if (title) {
123
+ const titlePart = ` ${titleStyle(title)} `;
124
+ const remaining = maxWidth + 2 - stripAnsi(titlePart).length;
125
+ result.push(borderStyle(border.tl + border.h) + titlePart + borderStyle(border.h.repeat(remaining) + border.tr));
126
+ } else {
127
+ result.push(borderStyle(border.tl + border.h.repeat(maxWidth + 2) + border.tr));
128
+ }
129
+
130
+ // Padding top
131
+ for (let i = 0; i < padding; i++) {
132
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
133
+ }
134
+
135
+ // Content
136
+ for (const line of lines) {
137
+ const plainLen = stripAnsi(line).length;
138
+ const padded = line + ' '.repeat(maxWidth - plainLen);
139
+ result.push(borderStyle(border.v) + ' ' + padded + ' ' + borderStyle(border.v));
140
+ }
141
+
142
+ // Padding bottom
143
+ for (let i = 0; i < padding; i++) {
144
+ result.push(borderStyle(border.v) + ' '.repeat(maxWidth + 2) + borderStyle(border.v));
145
+ }
146
+
147
+ // Bottom border
148
+ result.push(borderStyle(border.bl + border.h.repeat(maxWidth + 2) + border.br));
149
+
150
+ return result.join('\n');
151
+ }
152
+
153
+ /**
154
+ * Summary stats in a nice format
155
+ */
156
+ export function stats(data, options = {}) {
157
+ const { title = null } = options;
158
+
159
+ const lines = [];
160
+ if (title) {
161
+ lines.push(chalk.bold.cyan(title));
162
+ lines.push('');
163
+ }
164
+
165
+ const maxKeyLen = Math.max(...Object.keys(data).map(k => k.length));
166
+
167
+ for (const [key, value] of Object.entries(data)) {
168
+ const label = chalk.dim(key.padEnd(maxKeyLen) + ':');
169
+ lines.push(` ${label} ${value}`);
170
+ }
171
+
172
+ return lines.join('\n');
173
+ }
174
+
175
+ /**
176
+ * Progress indicator
177
+ */
178
+ export function progress(current, total, options = {}) {
179
+ const { width = 30, label = '' } = options;
180
+ const pct = Math.round((current / total) * 100);
181
+ const filled = Math.round((current / total) * width);
182
+ const empty = width - filled;
183
+
184
+ const bar = chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
185
+ return `${label}${bar} ${pct}% (${current}/${total})`;
186
+ }
187
+
188
+ // Global setting for emoji usage
189
+ let useEmoji = false;
190
+
191
+ export function setEmoji(enabled) {
192
+ useEmoji = enabled;
193
+ }
194
+
195
+ /**
196
+ * Status line with icon
197
+ */
198
+ export function status(type, message) {
199
+ const textIcons = {
200
+ success: chalk.green('✓'),
201
+ error: chalk.red('✗'),
202
+ warning: chalk.yellow('!'),
203
+ info: chalk.blue('i'),
204
+ comment: chalk.blue('#'),
205
+ file: chalk.cyan('·'),
206
+ folder: chalk.cyan('>'),
207
+ build: chalk.magenta('*'),
208
+ import: chalk.cyan('<'),
209
+ export: chalk.cyan('>'),
210
+ };
211
+
212
+ const emojiIcons = {
213
+ success: chalk.green('✓'),
214
+ error: chalk.red('✗'),
215
+ warning: chalk.yellow('⚠'),
216
+ info: chalk.blue('ℹ'),
217
+ comment: chalk.blue('💬'),
218
+ file: chalk.cyan('📄'),
219
+ folder: chalk.cyan('📁'),
220
+ build: chalk.magenta('🔨'),
221
+ import: chalk.cyan('📥'),
222
+ export: chalk.cyan('📤'),
223
+ };
224
+
225
+ const icons = useEmoji ? emojiIcons : textIcons;
226
+ const icon = icons[type] || chalk.dim('•');
227
+ return `${icon} ${message}`;
228
+ }
229
+
230
+ /**
231
+ * Spinner frames for async operations
232
+ */
233
+ const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
234
+
235
+ /**
236
+ * Create a spinner for async operations
237
+ */
238
+ export function spinner(message) {
239
+ let frameIndex = 0;
240
+ let interval = null;
241
+
242
+ const spin = {
243
+ start() {
244
+ process.stdout.write('\x1B[?25l'); // Hide cursor
245
+ interval = setInterval(() => {
246
+ const frame = chalk.cyan(spinnerFrames[frameIndex]);
247
+ process.stdout.write(`\r${frame} ${message}`);
248
+ frameIndex = (frameIndex + 1) % spinnerFrames.length;
249
+ }, 80);
250
+ return spin;
251
+ },
252
+ stop(finalMessage = null) {
253
+ if (interval) {
254
+ clearInterval(interval);
255
+ interval = null;
256
+ }
257
+ process.stdout.write('\r\x1B[K'); // Clear line
258
+ process.stdout.write('\x1B[?25h'); // Show cursor
259
+ if (finalMessage) {
260
+ console.log(finalMessage);
261
+ }
262
+ return spin;
263
+ },
264
+ success(msg) {
265
+ return spin.stop(status('success', msg || message));
266
+ },
267
+ error(msg) {
268
+ return spin.stop(status('error', msg || message));
269
+ },
270
+ };
271
+
272
+ return spin;
273
+ }
274
+
275
+ /**
276
+ * Diff display with inline highlighting
277
+ */
278
+ export function diff(insertions, deletions, substitutions) {
279
+ const lines = [];
280
+
281
+ if (insertions > 0) {
282
+ lines.push(chalk.green(` + ${insertions} insertion${insertions !== 1 ? 's' : ''}`));
283
+ }
284
+ if (deletions > 0) {
285
+ lines.push(chalk.red(` - ${deletions} deletion${deletions !== 1 ? 's' : ''}`));
286
+ }
287
+ if (substitutions > 0) {
288
+ lines.push(chalk.yellow(` ~ ${substitutions} substitution${substitutions !== 1 ? 's' : ''}`));
289
+ }
290
+
291
+ return lines.join('\n');
292
+ }
293
+
294
+ /**
295
+ * Show inline diff preview for CriticMarkup changes
296
+ * @param {string} text - Text with CriticMarkup annotations
297
+ * @param {object} options
298
+ * @returns {string}
299
+ */
300
+ export function inlineDiffPreview(text, options = {}) {
301
+ const { maxLines = 10, contextChars = 40 } = options;
302
+ const lines = [];
303
+
304
+ // Find all changes
305
+ const changes = [];
306
+
307
+ // Insertions: {++text++}
308
+ const insertPattern = /\{\+\+([^+]*)\+\+\}/g;
309
+ let match;
310
+ while ((match = insertPattern.exec(text)) !== null) {
311
+ changes.push({
312
+ type: 'insert',
313
+ content: match[1],
314
+ index: match.index,
315
+ fullMatch: match[0],
316
+ });
317
+ }
318
+
319
+ // Deletions: {--text--}
320
+ const deletePattern = /\{--([^-]*)--\}/g;
321
+ while ((match = deletePattern.exec(text)) !== null) {
322
+ changes.push({
323
+ type: 'delete',
324
+ content: match[1],
325
+ index: match.index,
326
+ fullMatch: match[0],
327
+ });
328
+ }
329
+
330
+ // Substitutions: {~~old~>new~~}
331
+ const subPattern = /\{~~([^~]*)~>([^~]*)~~\}/g;
332
+ while ((match = subPattern.exec(text)) !== null) {
333
+ changes.push({
334
+ type: 'substitute',
335
+ oldContent: match[1],
336
+ newContent: match[2],
337
+ index: match.index,
338
+ fullMatch: match[0],
339
+ });
340
+ }
341
+
342
+ // Sort by position
343
+ changes.sort((a, b) => a.index - b.index);
344
+
345
+ // Show preview for each change (up to maxLines)
346
+ const shown = changes.slice(0, maxLines);
347
+
348
+ for (const change of shown) {
349
+ // Get context
350
+ const before = text.slice(Math.max(0, change.index - contextChars), change.index)
351
+ .replace(/\n/g, ' ').trim();
352
+ const afterIdx = change.index + change.fullMatch.length;
353
+ const after = text.slice(afterIdx, afterIdx + contextChars)
354
+ .replace(/\n/g, ' ').trim();
355
+
356
+ let preview = '';
357
+ if (change.type === 'insert') {
358
+ preview = chalk.dim(before) + chalk.green.bold('+' + change.content) + chalk.dim(after);
359
+ lines.push(chalk.green(' + ') + truncate(preview, 80));
360
+ } else if (change.type === 'delete') {
361
+ preview = chalk.dim(before) + chalk.red.bold('-' + change.content) + chalk.dim(after);
362
+ lines.push(chalk.red(' - ') + truncate(preview, 80));
363
+ } else if (change.type === 'substitute') {
364
+ preview = chalk.dim(before) +
365
+ chalk.red.strikethrough(change.oldContent) +
366
+ chalk.green.bold(change.newContent) +
367
+ chalk.dim(after);
368
+ lines.push(chalk.yellow(' ~ ') + truncate(preview, 80));
369
+ }
370
+ }
371
+
372
+ if (changes.length > maxLines) {
373
+ lines.push(chalk.dim(` ... and ${changes.length - maxLines} more changes`));
374
+ }
375
+
376
+ return lines.join('\n');
377
+ }
378
+
379
+ /**
380
+ * Truncate string to max length
381
+ */
382
+ function truncate(str, maxLen) {
383
+ const plain = stripAnsi(str);
384
+ if (plain.length <= maxLen) return str;
385
+ // This is approximate since we have ANSI codes
386
+ return str.slice(0, maxLen + (str.length - plain.length)) + chalk.dim('...');
387
+ }
388
+
389
+ /**
390
+ * Section header
391
+ */
392
+ export function header(text, options = {}) {
393
+ const { style = chalk.bold.cyan, width = 60 } = options;
394
+ const padding = Math.max(0, width - text.length - 4);
395
+ return style(`── ${text} ${'─'.repeat(padding)}`);
396
+ }
397
+
398
+ /**
399
+ * Strip ANSI codes for length calculation
400
+ */
401
+ function stripAnsi(str) {
402
+ return str.replace(/\x1b\[[0-9;]*m/g, '');
403
+ }
404
+
405
+ /**
406
+ * Pad string with alignment
407
+ */
408
+ function pad(str, width, align, strLen = null) {
409
+ const len = strLen !== null ? strLen : stripAnsi(str).length;
410
+ const padding = Math.max(0, width - len);
411
+
412
+ if (align === 'right') {
413
+ return ' '.repeat(padding) + str;
414
+ } else if (align === 'center') {
415
+ const left = Math.floor(padding / 2);
416
+ const right = padding - left;
417
+ return ' '.repeat(left) + str + ' '.repeat(right);
418
+ }
419
+ return str + ' '.repeat(padding);
420
+ }