All files / src/cli/output formatters.ts

81.74% Statements 103/126
73.91% Branches 68/92
80.64% Functions 25/31
84.25% Lines 91/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339                  58x                     53x 25x               97x 16x   81x 81x 74x   74x 73x     8x 8x 8x 3x 3x   8x 5x   3x                           6x     6x 6x 6x                 25x                   12x 12x             14x 14x             22x           25x                     5x 4x 4x               17x 1x   16x 2x   14x                                       45x   15x 3x     12x 12x 12x 12x   12x             168x   56x 28x     28x 28x 28x 28x   28x             1x                                             7x 4x   3x 2x   1x             3x 2x   1x             175x           175x 124x     175x             37x             74x 74x 17x             52x     52x 15x   37x             1x 1x 1x 1x             2x 2x 2x 2x             13x                                     89x   89x 9x     89x 10x   10x 10x     89x    
import chalk from 'chalk';
import figures from 'figures';
import type { Severity, Confidence, Finding, FileChange, UsageStats, AuxiliaryUsageMap } from '../../types/index.js';
 
/**
 * Capitalize the first letter of a string.
 * @example capitalize('critical') // 'Critical'
 */
export function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
 
/**
 * Pluralize a word based on count.
 * @example pluralize(1, 'file') // 'file'
 * @example pluralize(2, 'file') // 'files'
 * @example pluralize(1, 'fix', 'fixes') // 'fix'
 * @example pluralize(2, 'fix', 'fixes') // 'fixes'
 */
export function pluralize(count: number, singular: string, plural?: string): string {
  if (count === 1) return singular;
  return plural ?? `${singular}s`;
}
 
/**
 * Format a duration in milliseconds to a human-readable string.
 * Under 1s: "50ms". Under 60s: "3.2s". Over 60s: "5m 3s".
 */
export function formatDuration(ms: number): string {
  if (ms < 1000) {
    return `${Math.round(ms)}ms`;
  }
  const totalSeconds = ms / 1000;
  if (totalSeconds < 60) {
    const formatted = totalSeconds.toFixed(1);
    // toFixed(1) can round 59.95 to "60.0" — fall through to minutes format
    if (formatted !== '60.0') {
      return `${formatted}s`;
    }
  }
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = Math.round(totalSeconds % 60);
  if (seconds === 60) {
    minutes += 1;
    seconds = 0;
  }
  if (seconds === 0) {
    return `${minutes}m`;
  }
  return `${minutes}m ${seconds}s`;
}
 
/**
 * Format an elapsed time for display (e.g., "+0.8s", "+2m 3s").
 */
export function formatElapsed(ms: number): string {
  return `+${formatDuration(ms)}`;
}
 
/**
 * Format bytes into a compact human-readable size.
 */
export function formatBytes(bytes: number): string {
  Iif (bytes < 1024) {
    return `${bytes.toLocaleString()} B`;
  }
  const kb = bytes / 1024;
  Eif (kb < 1024) {
    return `${kb.toFixed(kb < 10 ? 1 : 0)} KB`;
  }
  const mb = kb / 1024;
  return `${mb.toFixed(mb < 10 ? 1 : 0)} MB`;
}
 
/**
 * Severity configuration for display.
 */
const SEVERITY_CONFIG: Record<Severity, { color: typeof chalk.red; symbol: string }> = {
  high: { color: chalk.red, symbol: figures.bullet },
  medium: { color: chalk.yellow, symbol: figures.bullet },
  low: { color: chalk.green, symbol: figures.bullet },
};
 
/**
 * Format a severity dot for terminal output.
 */
export function formatSeverityDot(severity: Severity): string {
  const config = SEVERITY_CONFIG[severity];
  return config.color(config.symbol);
}
 
/**
 * Format a severity badge for terminal output (colored dot + severity text).
 */
export function formatSeverityBadge(severity: Severity): string {
  const config = SEVERITY_CONFIG[severity];
  return `${config.color(config.symbol)} ${config.color(`(${severity})`)}`;
}
 
/**
 * Format a severity for plain text (CI mode).
 */
export function formatSeverityPlain(severity: Severity): string {
  return `[${severity}]`;
}
 
/**
 * Confidence configuration for display.
 */
const CONFIDENCE_CONFIG: Record<Confidence, { color: typeof chalk.dim }> = {
  high: { color: chalk.green },
  medium: { color: chalk.yellow },
  low: { color: chalk.red },
};
 
/**
 * Format a confidence badge for terminal output.
 * Returns empty string if confidence is undefined.
 */
export function formatConfidenceBadge(confidence: Confidence | undefined): string {
  if (!confidence) return '';
  const config = CONFIDENCE_CONFIG[confidence];
  return config.color(`[${confidence} confidence]`);
}
 
 
/**
 * Format a file location string.
 */
export function formatLocation(path: string, startLine?: number, endLine?: number): string {
  if (!startLine) {
    return path;
  }
  if (endLine && endLine !== startLine) {
    return `${path}:${startLine}-${endLine}`;
  }
  return `${path}:${startLine}`;
}
 
/**
 * Format a finding for terminal display.
 */
export function formatFindingCompact(finding: Finding): string {
  const badge = formatSeverityBadge(finding.severity);
  const id = chalk.dim(`[${finding.id}]`);
  const location = finding.location
    ? chalk.dim(formatLocation(finding.location.path, finding.location.startLine, finding.location.endLine))
    : '';
 
  return `${badge} ${id} ${finding.title}${location ? ` ${location}` : ''}`;
}
 
/**
 * Format finding counts for display (with colored dots).
 */
export function formatFindingCounts(counts: Record<Severity, number>): string {
  const total = Object.values(counts).reduce((a, b) => a + b, 0);
 
  if (total === 0) {
    return chalk.green('No findings');
  }
 
  const parts: string[] = [];
  if (counts.high > 0) parts.push(`${formatSeverityDot('high')} ${counts.high} high`);
  if (counts.medium > 0) parts.push(`${formatSeverityDot('medium')} ${counts.medium} medium`);
  Iif (counts.low > 0) parts.push(`${formatSeverityDot('low')} ${counts.low} low`);
 
  return `${total} finding${total === 1 ? '' : 's'}: ${parts.join('  ')}`;
}
 
/**
 * Format finding counts for plain text.
 */
export function formatFindingCountsPlain(counts: Record<Severity, number>): string {
  const total = Object.values(counts).reduce((a, b) => a + b, 0);
 
  if (total === 0) {
    return 'No findings';
  }
 
  const parts: string[] = [];
  if (counts.high > 0) parts.push(`${counts.high} high`);
  if (counts.medium > 0) parts.push(`${counts.medium} medium`);
  if (counts.low > 0) parts.push(`${counts.low} low`);
 
  return `${total} finding${total === 1 ? '' : 's'} (${parts.join(', ')})`;
}
 
/**
 * Format a progress indicator like [1/3].
 */
export function formatProgress(current: number, total: number): string {
  return chalk.dim(`[${current}/${total}]`);
}
 
/**
 * Format file change summary.
 */
export function formatFileStats(files: FileChange[]): string {
  const added = files.filter((f) => f.status === 'added').length;
  const modified = files.filter((f) => f.status === 'modified').length;
  const removed = files.filter((f) => f.status === 'removed').length;
 
  const parts: string[] = [];
  if (added > 0) parts.push(chalk.green(`+${added}`));
  if (modified > 0) parts.push(chalk.yellow(`~${modified}`));
  if (removed > 0) parts.push(chalk.red(`-${removed}`));
 
  return parts.length > 0 ? parts.join(' ') : '';
}
 
/**
 * Truncate a string to fit within a width, adding ellipsis if needed.
 */
export function truncate(str: string, maxWidth: number): string {
  if (str.length <= maxWidth) {
    return str;
  }
  if (maxWidth <= 3) {
    return str.slice(0, maxWidth);
  }
  return str.slice(0, maxWidth - 1) + figures.ellipsis;
}
 
/**
 * Pad a string on the right to reach a certain width.
 */
export function padRight(str: string, width: number): string {
  if (str.length >= width) {
    return str;
  }
  return str + ' '.repeat(width - str.length);
}
 
/**
 * Count findings by severity.
 */
export function countBySeverity(findings: Finding[]): Record<Severity, number> {
  const counts: Record<Severity, number> = {
    high: 0,
    medium: 0,
    low: 0,
  };
 
  for (const finding of findings) {
    counts[finding.severity]++;
  }
 
  return counts;
}
 
/**
 * Format a USD cost for display.
 */
export function formatCost(costUSD: number): string {
  return `$${costUSD.toFixed(2)}`;
}
 
/**
 * Calculate total cost across primary and auxiliary usage.
 */
export function totalUsageCost(usage?: UsageStats, auxiliaryUsage?: AuxiliaryUsageMap): number | undefined {
  const hasAuxiliaryUsage = auxiliaryUsage !== undefined && Object.keys(auxiliaryUsage).length > 0;
  if (!usage && !hasAuxiliaryUsage) return undefined;
  return (usage?.costUSD ?? 0) + (auxiliaryUsage ? totalAuxiliaryCost(auxiliaryUsage) : 0);
}
 
/**
 * Format token counts for display.
 */
export function formatTokens(tokens: number): string {
  Iif (tokens >= 1_000_000) {
    return `${(tokens / 1_000_000).toFixed(1)}M`;
  }
  if (tokens >= 1_000) {
    return `${(tokens / 1_000).toFixed(1)}k`;
  }
  return String(tokens);
}
 
/**
 * Format usage stats for terminal display.
 */
export function formatUsage(usage: UsageStats, auxiliaryUsage?: AuxiliaryUsageMap): string {
  const inputStr = formatTokens(usage.inputTokens);
  const outputStr = formatTokens(usage.outputTokens);
  const costStr = formatCost(totalUsageCost(usage, auxiliaryUsage) ?? 0);
  return `${inputStr} in / ${outputStr} out · ${costStr}`;
}
 
/**
 * Format usage stats for plain text display.
 */
export function formatUsagePlain(usage: UsageStats, auxiliaryUsage?: AuxiliaryUsageMap): string {
  const inputStr = formatTokens(usage.inputTokens);
  const outputStr = formatTokens(usage.outputTokens);
  const costStr = formatCost(totalUsageCost(usage, auxiliaryUsage) ?? 0);
  return `${inputStr} input, ${outputStr} output, ${costStr}`;
}
 
/**
 * Calculate total auxiliary cost from an AuxiliaryUsageMap.
 */
export function totalAuxiliaryCost(auxiliaryUsage: AuxiliaryUsageMap): number {
  return Object.values(auxiliaryUsage).reduce((sum, u) => sum + u.costUSD, 0);
}
 
 
 
/**
 * Format stats (duration, tokens, cost) into a compact single-line format.
 * Used for markdown footers in PR comments and check annotations.
 *
 * When auxiliaryUsage is provided, the cost shown is primary + auxiliary total,
 * with a breakdown suffix showing per-agent auxiliary costs.
 *
 * @example formatStatsCompact(15800, { inputTokens: 3000, outputTokens: 680, costUSD: 0.0048 })
 * // Returns: "⏱ 15.8s · 3.0k in / 680 out · $0.00"
 *
 * @example formatStatsCompact(15800, usage, { extraction: { ... costUSD: 0.001 } })
 * // Returns: "⏱ 15.8s · 3.0k in / 680 out · $0.01 (+extraction: $0.00)"
 */
export function formatStatsCompact(durationMs?: number, usage?: UsageStats, auxiliaryUsage?: AuxiliaryUsageMap): string {
  const parts: string[] = [];
 
  if (durationMs !== undefined) {
    parts.push(`⏱ ${formatDuration(durationMs)}`);
  }
 
  if (usage) {
    parts.push(`${formatTokens(usage.inputTokens)} in / ${formatTokens(usage.outputTokens)} out`);
 
    const costStr = formatCost(totalUsageCost(usage, auxiliaryUsage) ?? 0);
    parts.push(`${costStr}`);
  }
 
  return parts.join(' · ');
}