/**
* Manual WCAG 2.2 AA checks for the BEAT site, run in a real browser.
*
* The script drives the built site over HTTP and records, for every route:
*
* 1. Keyboard operability: every interactive element is reachable with
* Tab, the focus order follows the visual order, and the focused
* element shows a visible focus indicator (outline, box-shadow or a
* border colour change against the un-focused state).
* 2. Landmarks and heading order: one banner, one main, one contentinfo,
* at most one navigation landmark per group, exactly one h1, and no
* skipped heading level.
* 3. Meaningful link text: every link has an accessible name that
* describes its destination, and no link is named "click here",
* "read more", "here", "link" or a bare URL.
* 4. Alt text: every image carries an alt attribute; an informative image
* has text, a decorative image has an empty alt.
* 5. Measured contrast: the computed foreground and background colours of
* every text node, its size and weight, compared against the WCAG
* thresholds (4.5:1 for body text, 3:1 for large text).
*
* The script prints the raw measurements and writes a JSON file. It does
* not change any application code.
*
* Usage:
* node scripts/check-a11y-manual.mjs [--dist
] [--browser ]
* [--json ] [--help]
*
* Exit codes: 0 = every check passed, 1 = at least one check failed,
* 2 = usage or I/O error.
*/
import { createServer } from 'node:http'
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, extname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import vm from 'node:vm'
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
const REPO_ROOT = resolve(SCRIPT_DIR, '..')
const DEFAULT_DIST = join(REPO_ROOT, 'public', 'dist')
const DEFAULT_ROUTER = join(REPO_ROOT, 'public', 'src', 'router', 'index.js')
const SITE_REQUIRE = createRequire(join(REPO_ROOT, 'public', 'package.json'))
const THEME_STORAGE_KEY = 'beat-theme'
/** Viewports to check: the mobile width and the desktop width of the brief. */
const WIDTHS = [
{ name: '360', width: 360, height: 800 },
{ name: '1440', width: 1440, height: 900 },
]
/** The two themes. */
const THEMES = ['light', 'dark']
/** Link names that describe nothing about the destination. */
const MEANINGLESS_LINK_NAMES = [
'click here', 'here', 'read more', 'more', 'link', 'this', 'this page',
'learn more', 'continue', 'details', 'see more', 'read this',
]
const usage = `Usage: node scripts/check-a11y-manual.mjs [options]
--dist built site to check (default: public/dist)
--router router config to read the route list from
--browser Chromium executable to drive
--json write the measurements to this file
--help print this text
Exit codes: 0 = every check passed, 1 = a check failed, 2 = usage or I/O error.`
/* ------------------------------------------------------------------ options */
function readOptions (argv) {
const flags = new Map([['--help', 'help'], ['-h', 'help']])
const takesValue = new Map([['--dist', 'dist'], ['--router', 'router'], ['--browser', 'browser'], ['--json', 'json']])
const options = { dist: DEFAULT_DIST, router: DEFAULT_ROUTER, browser: null, json: null, help: false }
for (let index = 0; index < argv.length; index++) {
const argument = argv[index]
if (argument.startsWith('-')) {
const flag = flags.get(argument)
if (flag !== undefined) {
options[flag] = true
continue
}
const key = takesValue.get(argument)
if (key === undefined) throw new Error(`unknown option: ${argument}`)
const value = argv[index + 1]
if (value === undefined) throw new Error(`option ${argument} needs a value`)
options[key] = resolve(value)
index += 1
continue
}
throw new Error(`unexpected argument: ${argument}`)
}
return options
}
/* -------------------------------------------------------------- route table */
function matchingBracket (source, start) {
const pairs = { '[': ']', '{': '}', '(': ')' }
const open = source[start]
const close = pairs[open]
if (close === undefined) return -1
let depth = 0
let index = start
let state = 'code'
while (index < source.length) {
const character = source[index]
const next = source[index + 1]
if (state === 'code') {
if (character === '/' && next === '/') { state = 'line'; index += 2; continue }
if (character === '/' && next === '*') { state = 'block'; index += 2; continue }
if (character === '"') { state = 'double'; index += 1; continue }
if (character === "'") { state = 'single'; index += 1; continue }
if (character === '`') { state = 'template'; index += 1; continue }
if (character === open) depth += 1
else if (character === close) {
depth -= 1
if (depth === 0) return index
}
index += 1
continue
}
if (state === 'line') {
if (character === '\n') state = 'code'
index += 1
continue
}
if (state === 'block') {
if (character === '*' && next === '/') state = 'code'
index += 1
continue
}
if (character === '\\') { index += 2; continue }
if ((state === 'single' && character === "'") ||
(state === 'double' && character === '"') ||
(state === 'template' && character === '`')) state = 'code'
index += 1
}
return -1
}
function normalizePath (value) {
if (typeof value !== 'string') return null
let path = value.trim()
if (path === '') return null
if (!path.startsWith('/')) path = `/${path}`
const cut = path.search(/[?#]/)
if (cut !== -1) path = path.slice(0, cut)
if (path.length > 1) path = path.replace(/\/+$/, '')
return path
}
function readRouterRoutes (routerPath) {
const source = readFileSync(routerPath, 'utf8')
const declaration = /(?:export\s+)?const\s+routes\s*=\s*/.exec(source)
if (declaration === null) throw new Error(`no "const routes = ..." in ${routerPath}`)
const start = source.indexOf('[', declaration.index + declaration[0].length)
if (start === -1) throw new Error(`the routes export in ${routerPath} is not an array literal`)
const end = matchingBracket(source, start)
if (end === -1) throw new Error(`the routes array in ${routerPath} is not closed`)
const literal = source.slice(start, end + 1)
const routes = vm.runInNewContext(`(${literal})`, Object.create(null), {
importModuleDynamically: (specifier) => {
throw new Error(`the router file must not be executed, but it imports ${specifier}`)
}
})
if (!Array.isArray(routes)) throw new Error(`the routes export in ${routerPath} is not an array`)
const entries = []
for (const route of routes) {
const path = normalizePath(route.path)
if (path === null) continue
entries.push({
path,
name: typeof route.name === 'string' ? route.name : null,
title: route.meta && typeof route.meta.title === 'string' ? route.meta.title : null,
isCatchAll: path.includes('*'),
})
}
return entries
}
/* ----------------------------------------------------------- static server */
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.json': 'application/json; charset=utf-8',
'.woff2': 'font/woff2',
}
function startServer (distDir) {
const server = createServer((request, response) => {
const requested = decodeURIComponent((request.url ?? '/').split('?')[0].split('#')[0])
const relative = requested.replace(/^\/+/, '')
const candidate = relative === '' ? 'index.html' : relative
let filePath = join(distDir, candidate)
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
const fallback = join(distDir, '404.html')
filePath = existsSync(fallback) ? fallback : join(distDir, 'index.html')
}
const type = MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream'
const body = readFileSync(filePath)
response.writeHead(200, { 'Content-Type': type, 'Content-Length': body.length })
response.end(body)
})
return new Promise((resolveServer, rejectServer) => {
server.on('error', rejectServer)
server.listen(0, '127.0.0.1', () => {
const address = server.address()
resolveServer({ server, origin: `http://127.0.0.1:${address.port}` })
})
})
}
/* ------------------------------------------------------- in-page check code */
/**
* The checks that run inside the page.
*
* They are injected as a string, so they cannot use the outer scope; every
* helper they need is defined inside the function.
*/
const PAGE_CHECKS = `(() => {
const results = {}
/* ---------------------------------------------------------- colour maths */
const parseColor = (value) => {
const match = /rgba?\\(([^)]+)\\)/.exec(value)
if (match === null) return null
const parts = match[1].split(',').map((part) => Number.parseFloat(part.trim()))
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) return null
return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 ? parts[3] : 1 }
}
const channelLuminance = (channel) => {
const value = channel / 255
return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
}
const relativeLuminance = (color) => (
0.2126 * channelLuminance(color.r) +
0.7152 * channelLuminance(color.g) +
0.0722 * channelLuminance(color.b)
)
const contrastRatio = (foreground, background) => {
const a = relativeLuminance(foreground)
const b = relativeLuminance(background)
const lighter = Math.max(a, b)
const darker = Math.min(a, b)
return (lighter + 0.05) / (darker + 0.05)
}
/** The opaque background behind an element, walking up the tree. */
const effectiveBackground = (element) => {
let node = element
while (node !== null && node.nodeType === 1) {
const color = parseColor(getComputedStyle(node).backgroundColor)
if (color !== null && color.a > 0) {
if (color.a === 1) return color
// A translucent background is composited over its own backdrop.
const parent = effectiveBackground(node.parentElement)
if (parent === null) return color
return {
r: color.r * color.a + parent.r * (1 - color.a),
g: color.g * color.a + parent.g * (1 - color.a),
b: color.b * color.a + parent.b * (1 - color.a),
a: 1
}
}
node = node.parentElement
}
return { r: 255, g: 255, b: 255, a: 1 }
}
/* ------------------------------------------------------------- landmarks */
// The landmark role of an element follows the HTML-AAM rules: a header or
// footer is a banner or a contentinfo only at the top level of the
// document. A header inside main, article, aside, nav or section is a
// plain section heading and carries no landmark role.
const sectioningAncestor = 'article, aside, main, nav, section'
const landmarkRole = (element) => {
const explicit = element.getAttribute('role')
if (explicit !== null && explicit !== '') return explicit
const tag = element.tagName.toLowerCase()
if (tag === 'main') return 'main'
if (tag === 'nav') return 'navigation'
if (tag === 'aside') return 'complementary'
if (tag === 'header') return element.closest(sectioningAncestor) === null ? 'banner' : 'generic'
if (tag === 'footer') return element.closest(sectioningAncestor) === null ? 'contentinfo' : 'generic'
return null
}
const landmarks = []
for (const element of document.querySelectorAll('header, nav, main, aside, footer, [role="banner"], [role="navigation"], [role="main"], [role="contentinfo"], [role="complementary"], [role="search"]')) {
const role = landmarkRole(element)
if (role === null) continue
landmarks.push({
role,
label: element.getAttribute('aria-label') ?? '',
heading: (element.querySelector('a, button, [class*="text-"]')?.textContent ?? '').trim().slice(0, 60)
})
}
results.landmarks = landmarks
const count = (role) => landmarks.filter((landmark) => landmark.role === role).length
results.landmarkCounts = {
banner: count('banner'),
navigation: count('navigation'),
main: count('main'),
contentinfo: count('contentinfo'),
complementary: count('complementary'),
search: count('search')
}
/* -------------------------------------------------------- heading order */
const headings = []
for (const element of document.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
if (element.closest('[aria-hidden="true"]')) continue
const style = getComputedStyle(element)
if (style.display === 'none' || style.visibility === 'hidden') continue
headings.push({
level: Number.parseInt(element.tagName.slice(1), 10),
text: element.textContent.trim().replace(/\\s+/g, ' ').slice(0, 80),
target: element.id === '' ? element.tagName.toLowerCase() : '#' + element.id
})
}
results.headings = headings
results.h1Count = headings.filter((heading) => heading.level === 1).length
results.headingSkips = []
let previous = null
for (const heading of headings) {
if (previous !== null && heading.level > previous + 1) {
results.headingSkips.push({ from: previous, to: heading.level, text: heading.text })
}
previous = heading.level
}
/* -------------------------------------------------------------- link text */
const links = []
for (const anchor of document.querySelectorAll('a[href]')) {
const style = getComputedStyle(anchor)
if (style.display === 'none' || style.visibility === 'hidden') continue
const name = (anchor.getAttribute('aria-label') ?? anchor.textContent ?? '').trim().replace(/\\s+/g, ' ')
// A link whose text is its own URL is only acceptable inside a reference
// entry: the entry itself carries the citation id and the label, so the
// link is not the only way to find out what it points at.
const entry = anchor.closest('li')
let labelledEntry = false
if (entry !== null) {
labelledEntry = Array.from(entry.querySelectorAll('p, h2, h3, h4, dt, dd')).some((node) => {
const text = node.textContent.trim().replace(/\\s+/g, ' ')
return text.length > 0 && text !== name
})
}
links.push({
href: anchor.getAttribute('href'),
name,
text: anchor.textContent.trim().replace(/\\s+/g, ' ').slice(0, 80),
title: anchor.getAttribute('title') ?? '',
bareUrl: /^https?:\\/\\//.test(name),
labelledEntry
})
}
results.links = links
/* -------------------------------------------------------------- alt text */
const images = []
for (const image of document.querySelectorAll('img')) {
images.push({
src: image.getAttribute('src'),
alt: image.getAttribute('alt'),
hasAlt: image.hasAttribute('alt'),
ariaHidden: image.getAttribute('aria-hidden') === 'true'
})
}
for (const svg of document.querySelectorAll('svg')) {
images.push({
src: 'inline