-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathrun-axe.ts
More file actions
88 lines (73 loc) · 2.06 KB
/
run-axe.ts
File metadata and controls
88 lines (73 loc) · 2.06 KB
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
import AxeBuilder from '@axe-core/playwright';
import { type Browser, chromium } from 'playwright-core';
import type { AuditOutputs } from '@code-pushup/models';
import {
executeProcess,
logger,
pluralizeToken,
stringifyError,
} from '@code-pushup/utils';
import { toAuditOutputs } from './transform.js';
let browser: Browser | undefined;
let browserChecked = false;
export async function runAxeForUrl(
url: string,
ruleIds: string[],
timeout: number,
): Promise<AuditOutputs> {
try {
if (!browser) {
await ensureBrowserInstalled();
logger.debug('Launching Chromium browser...');
browser = await chromium.launch({ headless: true });
}
const context = await browser.newContext();
try {
const page = await context.newPage();
try {
await page.goto(url, {
waitUntil: 'networkidle',
timeout,
});
const axeBuilder = new AxeBuilder({ page });
// Use withRules() to include experimental/deprecated rules
if (ruleIds.length > 0) {
axeBuilder.withRules(ruleIds);
}
const results = await axeBuilder.analyze();
const incompleteCount = results.incomplete.length;
if (incompleteCount > 0) {
logger.warn(
`Axe returned ${pluralizeToken('incomplete result', incompleteCount)} for ${url}`,
);
}
return toAuditOutputs(results, url);
} finally {
await page.close();
}
} finally {
await context.close();
}
} catch (error) {
logger.error(`Axe execution failed for ${url}: ${stringifyError(error)}`);
throw error;
}
}
export async function closeBrowser(): Promise<void> {
if (browser) {
await browser.close();
browser = undefined;
}
}
async function ensureBrowserInstalled(): Promise<void> {
if (browserChecked) {
return;
}
logger.debug('Checking Chromium browser installation...');
await executeProcess({
command: 'npx',
args: ['playwright-core', 'install', 'chromium'],
silent: true,
});
browserChecked = true;
}