import { AxeBuilder } from '@axe-core/playwright';
import { AxeResults } from 'axe-core';
import { Browser, chromium, Page } from 'playwright';
import { FileOutputManager } from '../utils/fileOutput.js';
import { v4 as uuidv4 } from 'uuid';
export class AccessibilityTester {
private browser: Browser | null = null;
private fileOutputManager: FileOutputManager;
constructor() {
this.fileOutputManager = new FileOutputManager();
}
public async initialize() {
this.browser = await chromium.launch();
}
public async run(url: string, wcagLevel?: string, criticality?: string[]): Promise<AxeResults> {
if (!this.browser) {
await this.initialize();
}
const context = await this.browser!.newContext();
const page = await context.newPage();
try {
await page.goto(url);
const axeBuilder = new AxeBuilder({ page });
if (wcagLevel) {
axeBuilder.withTags([wcagLevel]);
}
let results = await axeBuilder.analyze();
// Filter violations by criticality if specified
if (criticality && criticality.length > 0) {
results.violations = results.violations.filter(violation =>
violation.impact && criticality.includes(violation.impact)
);
}
const screenshotPath = await this.saveScreenshot(page);
console.log(`Screenshot saved to ${screenshotPath}`);
return results;
} finally {
await page.close();
await context.close();
}
}
private async saveScreenshot(page: Page): Promise<string> {
const screenshotPath = this.fileOutputManager.getScreenshotPath();
await page.screenshot({ path: screenshotPath, fullPage: true });
return screenshotPath;
}
public async cleanup() {
if (this.browser) {
await this.browser.close();
this.browser = null;
}
}
}