qa360 2.1.0 → 2.1.1

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,5 @@
1
+ /**
2
+ * Scan Command - Discover UI elements from a web page
3
+ */
4
+ import { Command } from 'commander';
5
+ export declare const scanCommand: Command;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Scan Command - Discover UI elements from a web page
3
+ */
4
+ import { Command } from 'commander';
5
+ import { chromium } from '@playwright/test';
6
+ import { DOMScanner } from '../scanners/dom-scanner.js';
7
+ import { JSONReporter } from '../generators/json-reporter.js';
8
+ import { TestGenerator } from '../generators/test-generator.js';
9
+ import { resolve } from 'path';
10
+ import { mkdirSync } from 'fs';
11
+ export const scanCommand = new Command('scan');
12
+ scanCommand
13
+ .description('Scan a web page for UI elements and generate test configurations')
14
+ .argument('<url>', 'URL of the page to scan')
15
+ .option('-o, --output <file>', 'Output file path (default: ".qa360/discovery/elements.json")')
16
+ .option('-i, --include <types>', 'Element types to include: buttons,links,forms,inputs,images,headings,all (default: "all")')
17
+ .option('-e, --exclude <selectors>', 'CSS selectors to exclude (comma-separated)')
18
+ .option('-s, --screenshot', 'Capture screenshots of elements (not yet implemented)')
19
+ .option('-a, --auto-generate-test', 'Auto-generate QA360 test file')
20
+ .option('-t, --timeout <ms>', 'Navigation timeout in milliseconds', '30000')
21
+ .option('--headed', 'Run in headed mode (show browser)')
22
+ .action(async (url, options) => {
23
+ const startTime = Date.now();
24
+ // Validate URL
25
+ try {
26
+ new URL(url);
27
+ }
28
+ catch {
29
+ console.error(`❌ Invalid URL: ${url}`);
30
+ process.exit(1);
31
+ }
32
+ // Parse include types
33
+ const includeTypes = options.include || 'all';
34
+ const include = includeTypes
35
+ .split(',')
36
+ .map((t) => t.trim().toLowerCase());
37
+ // Validate element types
38
+ const validTypes = ['buttons', 'links', 'forms', 'inputs', 'images', 'headings', 'all'];
39
+ for (const type of include) {
40
+ if (!validTypes.includes(type)) {
41
+ console.error(`❌ Invalid element type: ${type}`);
42
+ console.error(` Valid types: ${validTypes.join(', ')}`);
43
+ process.exit(1);
44
+ }
45
+ }
46
+ // Parse exclude selectors
47
+ const exclude = options.exclude
48
+ ? options.exclude.split(',').map((s) => s.trim())
49
+ : [];
50
+ const scanOptions = {
51
+ url,
52
+ output: options.output || '.qa360/discovery/elements.json',
53
+ include,
54
+ exclude,
55
+ screenshot: options.screenshot || false,
56
+ autoGenerateTest: options.autoGenerateTest || false,
57
+ timeout: parseInt(options.timeout, 10) || 30000,
58
+ headless: !options.headed
59
+ };
60
+ console.log(`🔍 Scanning page: ${url}`);
61
+ console.log('━'.repeat(50));
62
+ let browser = null;
63
+ let context = null;
64
+ let page = null;
65
+ try {
66
+ // Launch browser
67
+ browser = await chromium.launch({
68
+ headless: scanOptions.headless
69
+ });
70
+ context = await browser.newContext({
71
+ viewport: { width: 1280, height: 720 }
72
+ });
73
+ page = await context.newPage();
74
+ // Navigate to URL
75
+ await page.goto(url, {
76
+ timeout: scanOptions.timeout,
77
+ waitUntil: 'networkidle'
78
+ });
79
+ // Run scan
80
+ const scanner = new DOMScanner(page, url);
81
+ const elements = await scanner.scan(scanOptions);
82
+ // Generate summary
83
+ const summary = {
84
+ totalElements: elements.length,
85
+ buttons: elements.filter(e => e.type === 'button').length,
86
+ links: elements.filter(e => e.type === 'link').length,
87
+ forms: elements.filter(e => e.type === 'form').length,
88
+ inputs: elements.filter(e => e.type === 'input').length,
89
+ images: elements.filter(e => e.type === 'image').length,
90
+ headings: elements.filter(e => e.type === 'heading').length
91
+ };
92
+ // Print summary
93
+ console.log(`✅ Buttons found: ${summary.buttons}`);
94
+ console.log(`✅ Links found: ${summary.links}`);
95
+ console.log(`✅ Forms found: ${summary.forms}`);
96
+ console.log(`✅ Inputs found: ${summary.inputs}`);
97
+ console.log(`✅ Images found: ${summary.images}`);
98
+ console.log(`✅ Headings found: ${summary.headings}`);
99
+ console.log('━'.repeat(50));
100
+ console.log(`📦 Total elements: ${summary.totalElements}`);
101
+ console.log();
102
+ // Create output directory
103
+ const outputPath = resolve(scanOptions.output);
104
+ const outputDir = outputPath.substring(0, outputPath.lastIndexOf('/'));
105
+ mkdirSync(outputDir, { recursive: true });
106
+ // Generate scan result
107
+ const result = {
108
+ scanDate: new Date().toISOString(),
109
+ url,
110
+ duration: Date.now() - startTime,
111
+ summary,
112
+ elements
113
+ };
114
+ // Generate JSON report
115
+ const reporter = new JSONReporter();
116
+ await reporter.generate(result, outputPath);
117
+ console.log(`💾 Saved to: ${outputPath}`);
118
+ // Auto-generate test if requested
119
+ if (options.autoGenerateTest) {
120
+ const testGenerator = new TestGenerator();
121
+ const testPath = outputPath.replace('.json', '.yml');
122
+ await testGenerator.generate(result, testPath);
123
+ console.log(`📄 Test generated: ${testPath}`);
124
+ }
125
+ // Screenshots (placeholder for future implementation)
126
+ if (options.screenshot) {
127
+ console.log(`📸 Screenshots: ${outputDir}/screenshots/ (not yet implemented)`);
128
+ }
129
+ // Cleanup
130
+ await page.close();
131
+ await context.close();
132
+ await browser.close();
133
+ console.log();
134
+ console.log(`✨ Scan completed in ${((Date.now() - startTime) / 1000).toFixed(1)}s`);
135
+ console.log();
136
+ console.log('💡 Next steps:');
137
+ console.log(` • Review the discovered elements`);
138
+ if (options.autoGenerateTest) {
139
+ console.log(` • Run the auto-generated test: qa360 run ${outputPath.replace('.json', '.yml')}`);
140
+ }
141
+ console.log(` • Edit the test to remove unwanted elements`);
142
+ }
143
+ catch (error) {
144
+ // Cleanup on error
145
+ if (page)
146
+ await page.close().catch(() => { });
147
+ if (context)
148
+ await context.close().catch(() => { });
149
+ if (browser)
150
+ await browser.close().catch(() => { });
151
+ const errorMessage = error instanceof Error ? error.message : String(error);
152
+ console.error(`❌ Scan failed: ${errorMessage}`);
153
+ process.exit(1);
154
+ }
155
+ });
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Coverage Analyzer
3
+ *
4
+ * Analyzes coverage data to provide insights, trends, and recommendations.
5
+ */
6
+ import type { FileCoverage, CoverageMetrics, CoverageResult, CoverageTrend, CoverageGap, CoverageComparison, CoverageThreshold, CoverageType, CoverageReport } from './types.js';
7
+ /**
8
+ * Historical coverage data point
9
+ */
10
+ interface HistoricalCoverage {
11
+ runId: string;
12
+ timestamp: number;
13
+ metrics: CoverageMetrics;
14
+ }
15
+ /**
16
+ * Coverage Analyzer class
17
+ */
18
+ export declare class CoverageAnalyzer {
19
+ private history;
20
+ /**
21
+ * Analyze coverage and generate insights
22
+ */
23
+ analyze(result: CoverageResult, threshold?: CoverageThreshold): CoverageReport;
24
+ /**
25
+ * Check if coverage meets thresholds
26
+ */
27
+ checkThresholds(metrics: CoverageMetrics, threshold?: CoverageThreshold): boolean;
28
+ /**
29
+ * Check if a single file meets thresholds
30
+ */
31
+ checkFileThresholds(file: FileCoverage, threshold?: CoverageThreshold): boolean;
32
+ /**
33
+ * Find coverage gaps
34
+ */
35
+ findGaps(files: Record<string, FileCoverage>, threshold?: CoverageThreshold): CoverageGap[];
36
+ /**
37
+ * Calculate priority for covering a file
38
+ */
39
+ private calculatePriority;
40
+ /**
41
+ * Estimate effort to cover a file
42
+ */
43
+ private estimateEffort;
44
+ /**
45
+ * Generate test suggestions for a file
46
+ */
47
+ private generateSuggestions;
48
+ /**
49
+ * Group consecutive numbers into ranges
50
+ */
51
+ private groupConsecutiveNumbers;
52
+ /**
53
+ * Get top and bottom files by coverage
54
+ */
55
+ getTopFiles(files: Record<string, FileCoverage>, limit?: number): Array<{
56
+ path: string;
57
+ coverage: number;
58
+ type: 'best' | 'worst';
59
+ }>;
60
+ /**
61
+ * Compare two coverage results
62
+ */
63
+ compare(baseResult: CoverageResult, compareResult: CoverageResult): CoverageComparison;
64
+ /**
65
+ * Add historical coverage data
66
+ */
67
+ addHistory(key: string, data: HistoricalCoverage): void;
68
+ /**
69
+ * Get coverage trends
70
+ */
71
+ getTrends(key: string, type?: CoverageType, limit?: number): CoverageTrend[];
72
+ /**
73
+ * Calculate trend direction
74
+ */
75
+ getTrendDirection(trends: CoverageTrend[]): 'improving' | 'stable' | 'declining';
76
+ /**
77
+ * Predict future coverage based on trends
78
+ */
79
+ predictCoverage(key: string, type: CoverageType | undefined, targetCoverage: number): {
80
+ predictedReach: number | null;
81
+ projectedCoverage: number;
82
+ confidence: 'high' | 'medium' | 'low';
83
+ };
84
+ /**
85
+ * Generate coverage summary text
86
+ */
87
+ generateSummary(metrics: CoverageMetrics): string;
88
+ /**
89
+ * Format coverage percentage with color indicator
90
+ */
91
+ formatCoverage(percentage: number, threshold?: number): string;
92
+ /**
93
+ * Clear history
94
+ */
95
+ clearHistory(key?: string): void;
96
+ }
97
+ /**
98
+ * Create a coverage analyzer
99
+ */
100
+ export declare function createCoverageAnalyzer(): CoverageAnalyzer;
101
+ export {};
@@ -0,0 +1,415 @@
1
+ /**
2
+ * Coverage Analyzer
3
+ *
4
+ * Analyzes coverage data to provide insights, trends, and recommendations.
5
+ */
6
+ /**
7
+ * Coverage Analyzer class
8
+ */
9
+ export class CoverageAnalyzer {
10
+ history = new Map();
11
+ /**
12
+ * Analyze coverage and generate insights
13
+ */
14
+ analyze(result, threshold) {
15
+ const thresholdsMet = this.checkThresholds(result.metrics, threshold);
16
+ const gaps = this.findGaps(result.files, threshold);
17
+ const topFiles = this.getTopFiles(result.files);
18
+ return {
19
+ runId: `run_${Date.now()}`,
20
+ timestamp: Date.now(),
21
+ metrics: result.metrics,
22
+ byGate: { [result.gate]: result.metrics },
23
+ topFiles,
24
+ gaps: gaps.slice(0, 10), // Top 10 gaps
25
+ thresholdsMet,
26
+ thresholdViolations: gaps.map(g => g.path)
27
+ };
28
+ }
29
+ /**
30
+ * Check if coverage meets thresholds
31
+ */
32
+ checkThresholds(metrics, threshold) {
33
+ if (!threshold) {
34
+ return true;
35
+ }
36
+ if (threshold.scope === 'per-file') {
37
+ // Per-file thresholds checked separately
38
+ return true;
39
+ }
40
+ if (threshold.line !== undefined && metrics.lineCoverage < threshold.line) {
41
+ return false;
42
+ }
43
+ if (threshold.branch !== undefined && metrics.branchCoverage < threshold.branch) {
44
+ return false;
45
+ }
46
+ if (threshold.function !== undefined && metrics.functionCoverage < threshold.function) {
47
+ return false;
48
+ }
49
+ if (threshold.statement !== undefined && metrics.statementCoverage < threshold.statement) {
50
+ return false;
51
+ }
52
+ return true;
53
+ }
54
+ /**
55
+ * Check if a single file meets thresholds
56
+ */
57
+ checkFileThresholds(file, threshold) {
58
+ if (!threshold) {
59
+ return true;
60
+ }
61
+ if (threshold.line !== undefined && file.lineCoverage < threshold.line) {
62
+ return false;
63
+ }
64
+ if (threshold.branch !== undefined && file.branchCoverage < threshold.branch) {
65
+ return false;
66
+ }
67
+ if (threshold.function !== undefined && file.functionCoverage < threshold.function) {
68
+ return false;
69
+ }
70
+ if (threshold.statement !== undefined && file.statementCoverage < threshold.statement) {
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ /**
76
+ * Find coverage gaps
77
+ */
78
+ findGaps(files, threshold) {
79
+ const gaps = [];
80
+ const targetLine = threshold?.line ?? 80;
81
+ const targetBranch = threshold?.branch ?? 70;
82
+ const targetFunction = threshold?.function ?? 75;
83
+ for (const [path, file] of Object.entries(files)) {
84
+ const minTarget = Math.min(targetLine, targetBranch, targetFunction);
85
+ const avgCoverage = (file.lineCoverage + file.branchCoverage + file.functionCoverage) / 3;
86
+ if (avgCoverage < minTarget) {
87
+ gaps.push({
88
+ path,
89
+ currentCoverage: avgCoverage,
90
+ targetCoverage: minTarget,
91
+ gap: minTarget - avgCoverage,
92
+ priority: this.calculatePriority(file, minTarget),
93
+ effort: this.estimateEffort(file),
94
+ uncoveredCount: file.uncoveredLines.length,
95
+ suggestions: this.generateSuggestions(file)
96
+ });
97
+ }
98
+ }
99
+ // Sort by gap size, then priority
100
+ gaps.sort((a, b) => {
101
+ if (a.priority !== b.priority) {
102
+ const priorityOrder = { high: 0, medium: 1, low: 2 };
103
+ return priorityOrder[a.priority] - priorityOrder[b.priority];
104
+ }
105
+ return b.gap - a.gap;
106
+ });
107
+ return gaps;
108
+ }
109
+ /**
110
+ * Calculate priority for covering a file
111
+ */
112
+ calculatePriority(file, target) {
113
+ const gap = target - file.lineCoverage;
114
+ // High priority: large gap in important files
115
+ if (gap > 30) {
116
+ return 'high';
117
+ }
118
+ // Medium priority: moderate gap
119
+ if (gap > 10) {
120
+ return 'medium';
121
+ }
122
+ return 'low';
123
+ }
124
+ /**
125
+ * Estimate effort to cover a file
126
+ */
127
+ estimateEffort(file) {
128
+ const complexity = file.totalBranches + file.totalFunctions;
129
+ const uncoveredRatio = file.uncoveredLines.length / Math.max(file.totalLines, 1);
130
+ if (complexity > 100 || uncoveredRatio > 0.5) {
131
+ return 'high';
132
+ }
133
+ if (complexity > 30 || uncoveredRatio > 0.2) {
134
+ return 'medium';
135
+ }
136
+ return 'low';
137
+ }
138
+ /**
139
+ * Generate test suggestions for a file
140
+ */
141
+ generateSuggestions(file) {
142
+ const suggestions = [];
143
+ if (file.uncoveredLines.length > 0) {
144
+ const lineRanges = this.groupConsecutiveNumbers(file.uncoveredLines);
145
+ suggestions.push(`Add tests covering lines: ${lineRanges.slice(0, 3).join(', ')}`);
146
+ }
147
+ if (file.branchCoverage < file.lineCoverage) {
148
+ suggestions.push('Add tests for all branch conditions (true/false paths)');
149
+ }
150
+ if (file.functionCoverage < 100) {
151
+ suggestions.push('Add tests for uncovered functions');
152
+ }
153
+ if (file.totalFunctions === 0) {
154
+ suggestions.push('Consider splitting large functions into smaller, testable units');
155
+ }
156
+ return suggestions;
157
+ }
158
+ /**
159
+ * Group consecutive numbers into ranges
160
+ */
161
+ groupConsecutiveNumbers(numbers) {
162
+ if (numbers.length === 0)
163
+ return [];
164
+ const sorted = [...numbers].sort((a, b) => a - b);
165
+ const ranges = [];
166
+ let start = sorted[0];
167
+ let prev = sorted[0];
168
+ for (let i = 1; i < sorted.length; i++) {
169
+ if (sorted[i] === prev + 1) {
170
+ prev = sorted[i];
171
+ }
172
+ else {
173
+ ranges.push(start === prev ? `${start}` : `${start}-${prev}`);
174
+ start = sorted[i];
175
+ prev = sorted[i];
176
+ }
177
+ }
178
+ ranges.push(start === prev ? `${start}` : `${start}-${prev}`);
179
+ return ranges;
180
+ }
181
+ /**
182
+ * Get top and bottom files by coverage
183
+ */
184
+ getTopFiles(files, limit = 5) {
185
+ const fileArray = Object.entries(files).map(([path, file]) => ({
186
+ path,
187
+ coverage: file.lineCoverage,
188
+ type: 'best'
189
+ }));
190
+ // Sort by coverage
191
+ fileArray.sort((a, b) => b.coverage - a.coverage);
192
+ const result = [];
193
+ // Best files
194
+ for (let i = 0; i < Math.min(limit, fileArray.length); i++) {
195
+ result.push({ ...fileArray[i], type: 'best' });
196
+ }
197
+ // Worst files
198
+ for (let i = fileArray.length - 1; i >= Math.max(fileArray.length - limit, 0); i--) {
199
+ result.push({ path: fileArray[i].path, coverage: fileArray[i].coverage, type: 'worst' });
200
+ }
201
+ return result;
202
+ }
203
+ /**
204
+ * Compare two coverage results
205
+ */
206
+ compare(baseResult, compareResult) {
207
+ const baseFiles = baseResult.files;
208
+ const compareFiles = compareResult.files;
209
+ const improved = [];
210
+ const regressed = [];
211
+ const newFiles = [];
212
+ const removedFiles = [];
213
+ // Check all files in base
214
+ for (const [path, baseFile] of Object.entries(baseFiles)) {
215
+ const compareFile = compareFiles[path];
216
+ if (!compareFile) {
217
+ removedFiles.push(path);
218
+ continue;
219
+ }
220
+ const delta = compareFile.lineCoverage - baseFile.lineCoverage;
221
+ if (delta > 0.5) {
222
+ improved.push({
223
+ path,
224
+ before: baseFile.lineCoverage,
225
+ after: compareFile.lineCoverage,
226
+ delta
227
+ });
228
+ }
229
+ else if (delta < -0.5) {
230
+ regressed.push({
231
+ path,
232
+ before: baseFile.lineCoverage,
233
+ after: compareFile.lineCoverage,
234
+ delta
235
+ });
236
+ }
237
+ }
238
+ // Find new files
239
+ for (const path of Object.keys(compareFiles)) {
240
+ if (!baseFiles[path]) {
241
+ newFiles.push(path);
242
+ }
243
+ }
244
+ // Calculate overall change
245
+ const overallChange = compareResult.metrics.lineCoverage - baseResult.metrics.lineCoverage;
246
+ return {
247
+ baseRunId: `base_${baseResult.timestamp}`,
248
+ compareRunId: `compare_${compareResult.timestamp}`,
249
+ improved,
250
+ regressed,
251
+ newFiles,
252
+ removedFiles,
253
+ overallChange
254
+ };
255
+ }
256
+ /**
257
+ * Add historical coverage data
258
+ */
259
+ addHistory(key, data) {
260
+ if (!this.history.has(key)) {
261
+ this.history.set(key, []);
262
+ }
263
+ const history = this.history.get(key);
264
+ history.push(data);
265
+ // Keep only last 100 entries
266
+ if (history.length > 100) {
267
+ history.shift();
268
+ }
269
+ }
270
+ /**
271
+ * Get coverage trends
272
+ */
273
+ getTrends(key, type = 'line', limit = 30) {
274
+ const history = this.history.get(key) || [];
275
+ const sorted = history
276
+ .sort((a, b) => a.timestamp - b.timestamp)
277
+ .slice(-limit);
278
+ const trends = [];
279
+ let previousValue = 0;
280
+ for (const entry of sorted) {
281
+ let value;
282
+ switch (type) {
283
+ case 'line':
284
+ value = entry.metrics.lineCoverage;
285
+ break;
286
+ case 'branch':
287
+ value = entry.metrics.branchCoverage;
288
+ break;
289
+ case 'function':
290
+ value = entry.metrics.functionCoverage;
291
+ break;
292
+ case 'statement':
293
+ value = entry.metrics.statementCoverage;
294
+ break;
295
+ }
296
+ trends.push({
297
+ runId: entry.runId,
298
+ timestamp: entry.timestamp,
299
+ coverage: value,
300
+ type,
301
+ change: value - previousValue
302
+ });
303
+ previousValue = value;
304
+ }
305
+ return trends;
306
+ }
307
+ /**
308
+ * Calculate trend direction
309
+ */
310
+ getTrendDirection(trends) {
311
+ if (trends.length < 3) {
312
+ return 'stable';
313
+ }
314
+ const recent = trends.slice(-5);
315
+ const avgChange = recent.reduce((sum, t) => sum + t.change, 0) / recent.length;
316
+ if (avgChange > 1)
317
+ return 'improving';
318
+ if (avgChange < -1)
319
+ return 'declining';
320
+ return 'stable';
321
+ }
322
+ /**
323
+ * Predict future coverage based on trends
324
+ */
325
+ predictCoverage(key, type = 'line', targetCoverage) {
326
+ const trends = this.getTrends(key, type, 20);
327
+ if (trends.length < 5) {
328
+ return {
329
+ predictedReach: null,
330
+ projectedCoverage: trends[trends.length - 1]?.coverage || 0,
331
+ confidence: 'low'
332
+ };
333
+ }
334
+ // Simple linear regression
335
+ const n = trends.length;
336
+ let sumX = 0;
337
+ let sumY = 0;
338
+ let sumXY = 0;
339
+ let sumXX = 0;
340
+ for (let i = 0; i < n; i++) {
341
+ const x = i;
342
+ const y = trends[i].coverage;
343
+ sumX += x;
344
+ sumY += y;
345
+ sumXY += x * y;
346
+ sumXX += x * x;
347
+ }
348
+ const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
349
+ const intercept = (sumY - slope * sumX) / n;
350
+ const currentCoverage = trends[n - 1].coverage;
351
+ const avgCoverage = sumY / n;
352
+ const variance = trends.reduce((sum, t) => sum + Math.pow(t.coverage - avgCoverage, 2), 0) / n;
353
+ // Determine confidence based on variance
354
+ let confidence;
355
+ if (variance < 25)
356
+ confidence = 'high';
357
+ else if (variance < 100)
358
+ confidence = 'medium';
359
+ else
360
+ confidence = 'low';
361
+ // Project coverage for next run
362
+ const projectedCoverage = currentCoverage + slope;
363
+ // Predict when target will be reached
364
+ let predictedReach = null;
365
+ if (slope > 0.1) {
366
+ const runsNeeded = (targetCoverage - currentCoverage) / slope;
367
+ if (runsNeeded > 0 && runsNeeded < 100) {
368
+ predictedReach = Date.now() + runsNeeded * 24 * 60 * 60 * 1000; // Assume daily runs
369
+ }
370
+ }
371
+ return { predictedReach, projectedCoverage, confidence };
372
+ }
373
+ /**
374
+ * Generate coverage summary text
375
+ */
376
+ generateSummary(metrics) {
377
+ const parts = [];
378
+ parts.push(`Line Coverage: ${metrics.lineCoverage.toFixed(1)}%`);
379
+ parts.push(`Branch Coverage: ${metrics.branchCoverage.toFixed(1)}%`);
380
+ parts.push(`Function Coverage: ${metrics.functionCoverage.toFixed(1)}%`);
381
+ if (metrics.totalFiles > 0) {
382
+ parts.push(`Files: ${metrics.filesWithCoverage}/${metrics.totalFiles}`);
383
+ }
384
+ return parts.join(' | ');
385
+ }
386
+ /**
387
+ * Format coverage percentage with color indicator
388
+ */
389
+ formatCoverage(percentage, threshold = 80) {
390
+ if (percentage >= threshold) {
391
+ return `✓ ${percentage.toFixed(1)}%`;
392
+ }
393
+ else if (percentage >= threshold - 10) {
394
+ return `⚠ ${percentage.toFixed(1)}%`;
395
+ }
396
+ return `✗ ${percentage.toFixed(1)}%`;
397
+ }
398
+ /**
399
+ * Clear history
400
+ */
401
+ clearHistory(key) {
402
+ if (key) {
403
+ this.history.delete(key);
404
+ }
405
+ else {
406
+ this.history.clear();
407
+ }
408
+ }
409
+ }
410
+ /**
411
+ * Create a coverage analyzer
412
+ */
413
+ export function createCoverageAnalyzer() {
414
+ return new CoverageAnalyzer();
415
+ }