Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions code-pushup.preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import type {
CoreConfig,
PluginUrls,
} from './packages/models/src/index.js';
import axePlugin, { axeCategories } from './packages/plugin-axe/src/index.js';
import axePlugin, {
type AxePluginOptions,
axeCategories,
} from './packages/plugin-axe/src/index.js';
import coveragePlugin, {
type CoveragePluginConfig,
getNxCoveragePaths,
Expand Down Expand Up @@ -226,8 +229,11 @@ export async function configureLighthousePlugin(
};
}

export function configureAxePlugin(urls: PluginUrls): CoreConfig {
const axe = axePlugin(urls);
export function configureAxePlugin(
urls: PluginUrls,
options?: AxePluginOptions,
): CoreConfig {
const axe = axePlugin(urls, options);
return {
plugins: [axe],
categories: axeCategories(axe),
Expand Down
11 changes: 6 additions & 5 deletions e2e/plugin-axe-e2e/tests/collect.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
E2E_ENVIRONMENTS_DIR,
TEST_OUTPUT_DIR,
omitVariableReportData,
restoreNxIgnoredFiles,
teardownTestFolder,
} from '@code-pushup/test-utils';
import { executeProcess, readJsonFile } from '@code-pushup/utils';
Expand All @@ -22,17 +23,17 @@ function sanitizeReportPaths(report: Report): Report {
}

describe('PLUGIN collect report with axe-plugin NPM package', () => {
const fixturesDir = path.join('e2e', nxTargetProject(), 'mocks', 'fixtures');
const testFileDir = path.join(
E2E_ENVIRONMENTS_DIR,
nxTargetProject(),
TEST_OUTPUT_DIR,
'collect',
);
const defaultSetupDir = path.join(testFileDir, 'default-setup');
const fixturesDir = path.join('e2e', nxTargetProject(), 'mocks', 'fixtures');

beforeAll(async () => {
await cp(fixturesDir, testFileDir, { recursive: true });
await restoreNxIgnoredFiles(testFileDir);
});

afterAll(async () => {
Expand All @@ -43,13 +44,13 @@ describe('PLUGIN collect report with axe-plugin NPM package', () => {
const { code } = await executeProcess({
command: 'npx',
args: ['@code-pushup/cli', 'collect'],
cwd: defaultSetupDir,
cwd: testFileDir,
});

expect(code).toBe(0);

const report: Report = await readJsonFile(
path.join(defaultSetupDir, '.code-pushup', 'report.json'),
const report = await readJsonFile<Report>(
path.join(testFileDir, '.code-pushup', 'report.json'),
);

expect(() => reportSchema.parse(report)).not.toThrow();
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"wrap-ansi": "^9.0.2",
"yaml": "^2.5.1",
"yargs": "^17.7.2",
"zod": "^4.0.5"
"zod": "^4.2.1"
},
"devDependencies": {
"@actions/core": "^1.11.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/ci/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"glob": "^11.0.1",
"simple-git": "^3.20.0",
"yaml": "^2.5.1",
"zod": "^4.0.5"
"zod": "^4.2.1"
},
"files": [
"src",
Expand Down
34 changes: 17 additions & 17 deletions packages/models/docs/models-reference.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/models/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"dependencies": {
"ansis": "^3.3.2",
"vscode-material-icons": "^0.1.0",
"zod": "^4.0.5"
"zod": "^4.2.1"
},
"files": [
"src",
Expand Down
1 change: 1 addition & 0 deletions packages/models/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,4 @@ export {
type Tree,
} from './lib/tree.js';
export { uploadConfigSchema, type UploadConfig } from './lib/upload-config.js';
export { convertAsyncZodFunctionToSchema } from './lib/implementation/function.js';
43 changes: 16 additions & 27 deletions packages/models/src/lib/implementation/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { MATERIAL_ICONS } from 'vscode-material-icons';
import {
ZodError,
type ZodIssue,
type ZodObject,
type ZodOptional,
type ZodString,
z,
} from 'zod';
import { type ZodObject, type ZodOptional, type ZodString, z } from 'zod';
import {
MAX_DESCRIPTION_LENGTH,
MAX_SLUG_LENGTH,
Expand Down Expand Up @@ -65,28 +58,24 @@ export const descriptionSchema = z
.optional();

/* Schema for a URL */
export const urlSchema = z.string().url().meta({ title: 'URL' });
export const urlSchema = z.url().meta({ title: 'URL' });

/** Schema for a docsUrl */
export const docsUrlSchema = urlSchema
export const docsUrlSchema = z
.union([
z.literal(''), // allow empty string (no URL validation)
// eslint-disable-next-line unicorn/prefer-top-level-await, unicorn/catch-error-name
urlSchema.optional().catch(ctx => {
const issue = ctx.issues[0];
if (issue?.code === 'invalid_format' && issue?.format === 'url') {
console.warn(`Ignoring invalid docsUrl: ${ctx.value}`);
return '';
}
// re-parse to throw formatted error for non-URL issues
return urlSchema.parse(ctx.value);
}),
])
.optional()
.or(z.literal('')) // allow empty string (no URL validation)
// eslint-disable-next-line unicorn/prefer-top-level-await, unicorn/catch-error-name
.catch(ctx => {
// if only URL validation fails, supress error since this metadata is optional anyway
if (
ctx.issues.length === 1 &&
(ctx.issues[0]?.errors as ZodIssue[][])
.flat()
.some(
error => error.code === 'invalid_format' && error.format === 'url',
)
) {
console.warn(`Ignoring invalid docsUrl: ${ctx.value}`);
return '';
}
throw new ZodError(ctx.error.issues);
})
.meta({ title: 'DocsUrl', description: 'Documentation site' });

/** Schema for a title of a plugin, category and audit */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import {
type TableCellValue,
docsUrlSchema,
Expand Down
53 changes: 52 additions & 1 deletion packages/plugin-axe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,10 @@ axePlugin(urls: PluginUrls, options?: AxePluginOptions)
| Property | Type | Default | Description |
| -------------- | ----------- | ------------ | ----------------------------------------- |
| `preset` | `AxePreset` | `'wcag21aa'` | Accessibility ruleset preset |
| `setupScript` | `string` | `undefined` | Path to authentication setup script |
| `scoreTargets` | `object` | `undefined` | Pass/fail thresholds for audits or groups |

See [Presets](#presets) for the list of available presets and [Preset details](#preset-details) for what each preset includes.
See [Presets](#presets) and [Authentication](#authentication) sections below.

## Multiple URLs

Expand All @@ -92,6 +93,56 @@ axePlugin({

URLs with higher weights contribute more to overall scores. For example, a URL with weight 3 has three times the influence of a URL with weight 1.

## Authentication

To test login-protected pages, provide a `setupScript` that authenticates before analysis:

```ts
axePlugin('https://example.com/dashboard', {
setupScript: './axe-setup.ts',
});
```

The setup script must export a default async function that receives a Playwright `Page` instance:

```ts
// axe-setup.ts
import type { Page } from 'playwright-core';

export default async function (page: Page): Promise<void> {
await page.goto('https://example.com/login');
await page.fill('#username', process.env.USERNAME);
await page.fill('#password', process.env.PASSWORD);
await page.click('button[type="submit"]');
await page.waitForURL('**/dashboard');
}
```

The script runs once before analyzing URLs. Authentication state (cookies, localStorage) is automatically shared across all URL analyses.

<details>
<summary>Alternative: Cookie-based authentication</summary>

If you have a session token, you can inject it directly via cookies:

```ts
// axe-setup.ts
import type { Page } from 'playwright-core';

export default async function (page: Page): Promise<void> {
await page.context().addCookies([
{
name: 'session_token',
value: process.env.SESSION_TOKEN,
domain: 'example.com',
path: '/',
},
]);
}
```

</details>

## Presets

Choose which accessibility ruleset to test against using the `preset` option:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Page } from 'playwright-core';

export async function setup(page: Page): Promise<void> {
await page.goto('about:blank');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 'not a function';
5 changes: 5 additions & 0 deletions packages/plugin-axe/mocks/fixtures/valid-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Page } from 'playwright-core';

export default async function setup(page: Page): Promise<void> {
await page.goto('about:blank');
}
2 changes: 1 addition & 1 deletion packages/plugin-axe/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"@code-pushup/utils": "0.100.1",
"axe-core": "^4.11.0",
"playwright-core": "^1.56.1",
"zod": "^4.1.12"
"zod": "^4.2.1"
},
"files": [
"src",
Expand Down
4 changes: 2 additions & 2 deletions packages/plugin-axe/src/lib/axe-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function axePlugin(
urls: PluginUrls,
options: AxePluginOptions = {},
): PluginConfig {
const { preset, scoreTargets, timeout } = validate(
const { preset, scoreTargets, timeout, setupScript } = validate(
axePluginOptionsSchema,
options,
);
Expand All @@ -49,7 +49,7 @@ export function axePlugin(
version: packageJson.version,
audits,
groups,
runner: createRunnerFunction(normalizedUrls, ruleIds, timeout),
runner: createRunnerFunction(normalizedUrls, ruleIds, timeout, setupScript),
context,
...(scoreTargets && { scoreTargets }),
};
Expand Down
3 changes: 3 additions & 0 deletions packages/plugin-axe/src/lib/categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ function expandCategories(
);
}

/** Creates an aggregated accessibility category from Axe groups. */
export function createAggregatedCategory(
groups: Group[],
context: PluginUrlContext,
Expand All @@ -72,6 +73,7 @@ export function createAggregatedCategory(
};
}

/** Expands category refs for multiple URLs. */
export function expandAggregatedCategory(
category: CategoryConfig,
context: PluginUrlContext,
Expand All @@ -84,6 +86,7 @@ export function expandAggregatedCategory(
};
}

/** Extracts unique group slugs from Axe groups. */
export function extractGroupSlugs(groups: Group[]): AxeCategoryGroupSlug[] {
const slugs = groups.map(({ slug }) => removeIndex(slug));
return [...new Set(slugs)].filter(isAxeGroupSlug);
Expand Down
2 changes: 2 additions & 0 deletions packages/plugin-axe/src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { z } from 'zod';
import {
filePathSchema,
pluginScoreTargetsSchema,
positiveIntSchema,
} from '@code-pushup/models';
Expand All @@ -21,6 +22,7 @@ export const axePluginOptionsSchema = z
description:
'Accessibility ruleset preset (default: wcag21aa for WCAG 2.1 Level AA compliance)',
}),
setupScript: filePathSchema.optional(),
scoreTargets: pluginScoreTargetsSchema.optional(),
timeout: positiveIntSchema.default(DEFAULT_TIMEOUT_MS).meta({
description:
Expand Down
6 changes: 6 additions & 0 deletions packages/plugin-axe/src/lib/config.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ describe('axePluginOptionsSchema', () => {
},
);

it('should accept setupScript as a file path', () => {
expect(() =>
axePluginOptionsSchema.parse({ setupScript: 'src/axe-setup.js' }),
).not.toThrow();
});

it('should accept scoreTargets as a number between 0 and 1', () => {
expect(() =>
axePluginOptionsSchema.parse({ scoreTargets: 0.99 }),
Expand Down
6 changes: 6 additions & 0 deletions packages/plugin-axe/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import type { AxePreset } from './config.js';

/** Unique identifier for the Axe plugin. */
export const AXE_PLUGIN_SLUG = 'axe';

/** Display title for the Axe plugin. */
export const AXE_PLUGIN_TITLE = 'Axe';

/** Default WCAG preset used when none is specified. */
export const AXE_DEFAULT_PRESET = 'wcag21aa';

/** Default timeout in milliseconds for page operations. */
export const DEFAULT_TIMEOUT_MS = 30_000;

/** Human-readable names for each Axe preset. */
export const AXE_PRESET_NAMES: Record<AxePreset, string> = {
wcag21aa: 'WCAG 2.1 AA',
wcag22aa: 'WCAG 2.2 AA',
Expand Down
3 changes: 3 additions & 0 deletions packages/plugin-axe/src/lib/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const WCAG_PRESET_TAGS: Record<AxeWcagPreset, AxeWcagTag[]> = {
wcag22aa: ['wcag2a', 'wcag21a', 'wcag2aa', 'wcag21aa', 'wcag22aa'],
};

/** Returns the WCAG tags for a given preset. */
export function getWcagPresetTags(preset: AxeWcagPreset): AxeWcagTag[] {
return WCAG_PRESET_TAGS[preset];
}
Expand Down Expand Up @@ -54,6 +55,7 @@ export const axeCategoryGroupSlugSchema = z

export type AxeCategoryGroupSlug = z.infer<typeof axeCategoryGroupSlugSchema>;

/** Maps category group slugs to human-readable titles. */
export const CATEGORY_GROUPS: Record<AxeCategoryGroupSlug, string> = {
aria: 'ARIA',
color: 'Color & Contrast',
Expand All @@ -70,6 +72,7 @@ export const CATEGORY_GROUPS: Record<AxeCategoryGroupSlug, string> = {
'time-and-media': 'Media',
};

/** Type guard for valid Axe group slugs. */
export function isAxeGroupSlug(slug: unknown): slug is AxeCategoryGroupSlug {
return axeCategoryGroupSlugSchema.safeParse(slug).success;
}
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-axe/src/lib/meta/format.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { pluginMetaLogFormatter } from '@code-pushup/utils';
import { AXE_PLUGIN_TITLE } from '../constants.js';

/** Formats log messages with the Axe plugin prefix. */
export const formatMetaLog = pluginMetaLogFormatter(AXE_PLUGIN_TITLE);
Loading