File size: 28,388 Bytes
8b99f6f | 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | // Generates synthetic accessibility-fix fixtures (MIT).
// Usage: node scripts/gen-tasks.mjs [--seed N] [--split public|hidden] [--out path] [--count N]
// Public split defaults to data/tasks.jsonl with seed 20261015.
// Hidden split defaults to artifacts/tasks.hidden.jsonl (gitignored, never published)
// and uses its own a11yh- id prefix so hidden ids never collide with public ones.
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { createHash } from "node:crypto";
const args = process.argv.slice(2);
const get = (name, fallback) => {
const index = args.indexOf(name);
return index === -1 ? fallback : args[index + 1];
};
if (args.includes("--help")) {
console.log("Usage: node scripts/gen-tasks.mjs [--seed N] [--split public|hidden] [--out path] [--count N]");
process.exit(0);
}
const seed = Number(get("--seed", "20261015"));
const split = get("--split", "public");
const count = Number(get("--count", "40"));
const out = get("--out", split === "hidden" ? "artifacts/tasks.hidden.jsonl" : "data/tasks.jsonl");
if (!Number.isInteger(seed) || !Number.isInteger(count) || count < 1) throw new Error("seed and count must be positive integers");
if (split !== "public" && split !== "hidden") throw new Error("--split must be public or hidden");
function mulberry32(start) {
let state = start >>> 0;
return () => {
state += 1831565813;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
const pick = (rng, list) => list[Math.floor(rng() * list.length)];
const pickN = (rng, list, n) => {
const copy = [...list];
const out = [];
while (out.length < Math.min(n, copy.length)) out.push(copy.splice(Math.floor(rng() * copy.length), 1)[0]);
return out;
};
const shuffle = (rng, list) => {
const a = [...list];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
// WCAG relative luminance for #rrggbb.
function luminance(hex) {
const h = hex.replace("#", "");
const [r, g, b] = [0, 2, 4].map((i) => {
const c = parseInt(h.slice(i, i + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
const ratio = (a, b) => {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m);
return (x + 0.05) / (y + 0.05);
};
const hex = (rng, lo, hi) => "#" + [0, 1, 2].map(() => (lo + Math.floor(rng() * (hi - lo + 1))).toString(16).padStart(2, "0")).join("");
// A passing foreground/background pair at >= minRatio. The default
// carries margin over the 4.5:1 rule so equivalent color spellings
// (hsl() with rounded channels, 8-digit hex) cannot dip a reference
// page under the threshold.
function goodPair(rng, minRatio = 4.75) {
for (let tries = 0; tries < 200; tries++) {
const bg = hex(rng, 200, 255);
const fg = hex(rng, 0, 120);
if (ratio(fg, bg) >= minRatio) return { fg, bg };
}
throw new Error("no good pair found");
}
// A failing pair against a fixed background (text lands in the 3.5-4.4 band
// so the defect is visible but not blatant).
function badFg(rng, bg) {
for (let tries = 0; tries < 400; tries++) {
const fg = hex(rng, 120, 190);
const r = ratio(fg, bg);
if (r < 4.5 && r > 2.5) return fg;
}
return "#8a8a8a";
}
// A passing foreground on a FIXED background: the inline span inherits
// the body background, so it must be drawn against it, not against a
// throwaway pair bg.
function goodFg(rng, bg, minRatio = 4.75) {
for (let tries = 0; tries < 400; tries++) {
const fg = hex(rng, 0, 130);
if (ratio(fg, bg) >= minRatio) return fg;
}
throw new Error("no good foreground found");
}
// A large-text pair in the passing 3:1-4.5 band (valid fix, tests the
// large-text threshold). The 3.3 floor leaves room for color-format
// rounding noise, same margin idea as goodPair.
function largePair(rng) {
for (let tries = 0; tries < 300; tries++) {
const bg = hex(rng, 200, 255);
const fg = hex(rng, 60, 160);
const r = ratio(fg, bg);
if (r >= 3.3 && r < 4.5) return { fg, bg };
}
throw new Error("no large pair found");
}
const CHECKS = [
["missing-alt", "1.1.1"], ["unlabeled-input", "3.3.2"], ["low-contrast", "1.4.3"],
["heading-order", "1.3.1"], ["tabindex-positive", "2.4.3"], ["div-button", "4.1.2"],
["missing-lang", "3.1.1"], ["no-focus-style", "2.4.7"], ["empty-link", "2.4.4"],
["table-headers", "1.3.1"],
];
const WCAG = Object.fromEntries(CHECKS);
const ADJ = ["Harbor", "Kestrel", "Northern", "River", "Garden", "Amber", "Cedar", "Juniper", "Misty", "Copper", "Silver", "Quiet", "Bright", "Willow", "Frost", "Ember", "Sage", "Coral", "Atlas", "Meadow"];
const NOUN = ["Lights", "Ridge", "Valley", "Crossing", "Mills", "Works", "Foundry", "Collective", "Cooperative", "Observatory", "Pantry", "Workshop", "Ledger", "Orchard", "Depot", "Exchange", "Studio", "Clinic", "Archive", "Guild"];
const KIND = ["newsletter", "field guide", "status report", "release notes", "handbook", "bulletin", "weekly digest", "product sheet", "setup guide", "survey results", "booking page", "service page"];
const TOPICS = [
["ferry sailings", "harbor notes", "crossing times"],
["grind settings", "care notes", "brew ratios"],
["sleeper bookings", "reading list", "departure board"],
["volunteer shifts", "meeting point", "supply list"],
["api keys", "rate limits", "endpoint status"],
["survey findings", "next steps", "member quotes"],
["trail conditions", "permit windows", "ranger notes"],
["menu changes", "supplier list", "order cutoffs"],
["rehearsal dates", "set list", "venue notes"],
["seed inventory", "planting calendar", "pest watch"],
["loan rates", "branch hours", "member news"],
["build artifacts", "test matrix", "deploy log"],
];
const NOTES = [
"New routes post every Sunday evening.", "Burrs carry a five year warranty.",
"Berths sell out around holidays.", "Gloves and bags are provided.",
"Keys rotate every ninety days.", "Two hundred members answered.",
"Permits open on the first Monday.", "Orders close at noon on Fridays.",
"Rehearsals move indoors in winter.", "Seed counts refresh monthly.",
"Rates lock for sixty days.", "Artifacts prune after thirty days.",
];
const SPANS = [
"Ferries run hourly on holidays.", "Free returns within thirty days.",
"Bring a lock for the cabin door.", "All ages welcome with an adult.",
"Sandbox data refreshes hourly.", "Evening hours were the top ask.",
"Boots are required past the gate.", "Late orders ship the next day.",
"Guests may watch the last set.", "Cover beds before a frost.",
"Statements arrive by post.", "Flaky tests quarantine on retry.",
];
const ALTS = [
"Ferry crossing the harbor at dusk", "Steel burr coffee grinder on a counter",
"Sleeper train under northern lights", "Volunteers clearing a riverbank",
"Soil sensor beside tomato plants", "Reading room with tall shelves",
"Trail marker above the treeline", "Stacked crates at the loading dock",
"String section tuning on stage", "Seed packets on a potting bench",
"Teller counter at the main branch", "Build monitor showing green jobs",
];
const CTA = ["Subscribe", "Add to basket", "Save article", "Join us", "Get a key", "Download PDF", "Book now", "Reserve a spot", "Notify me", "Start trial"];
const NAV2 = ["About", "FAQ", "Pricing", "News", "Docs", "Team", "Contact", "Archive"];
const FIELD_POOL = [
["name", "Full name", "text"], ["email", "Email address", "email"],
["phone", "Phone number", "tel"], ["org", "Organization", "text"],
["city", "City", "text"], ["note", "Delivery note", "text"],
];
const CLASS_A = ["note", "hint", "aside", "fine", "meta", "muted"];
const CLASS_B = ["cta", "btn-primary", "action", "primary-btn", "main-action", "go"];
const CAPTIONS = ["Crossing times", "Grind guide", "Departure board", "Cleanup shifts", "Endpoint limits", "Survey results", "Permit windows", "Order ledger", "Rehearsal slots", "Seed counts", "Rate sheet", "Build history"];
const COLHEADS = [["Option", "Detail", "Status"], ["Name", "Owner", "State"], ["Step", "Input", "Output"], ["Item", "Count", "Flag"]];
const CELLS = [["Standard", "Weekly", "Open"], ["Plus", "Daily", "Open"], ["Rush", "Hourly", "Full"], ["Basic", "Monthly", "Closed"], ["Trial", "Once", "Open"], ["Custom", "On call", "Open"]];
// One randomized but fully accessible page. Returns the HTML plus a hooks
// object with the exact strings defect breakers can target.
function buildFixed(rng) {
const title = `${pick(rng, ADJ)} ${pick(rng, NOUN)} ${pick(rng, KIND)}`;
const topics = pick(rng, TOPICS);
const [h2a, h2b, caption] = [topics[0], topics[1], pick(rng, CAPTIONS)];
const noteClass = pick(rng, CLASS_A);
const ctaClass = pick(rng, CLASS_B);
const noteText = pick(rng, NOTES);
const spanText = pick(rng, SPANS);
const heroAlt = pick(rng, ALTS);
const img = `https://example.com/${title.toLowerCase().replace(/[^a-z]+/g, "-")}.jpg`;
const ctaText = pick(rng, CTA);
const nav2 = pick(rng, NAV2);
const fields = pickN(rng, FIELD_POOL, 2 + Math.floor(rng() * 2));
const colheads = pick(rng, COLHEADS);
const rows = pickN(rng, CELLS, 2 + Math.floor(rng() * 2));
// Colors: every pair is generated to pass.
const body = goodPair(rng);
const note = goodPair(rng);
const spanFg = goodFg(rng, body.bg);
const cta = goodPair(rng);
const focusColor = goodPair(rng).fg;
// A large-text heading pair in the legal 3:1-4.5 band keeps the
// large-text path exercised without tripping the defect check.
const large = rng() < 0.5 ? largePair(rng) : null;
const largeRule = large ? `\n.big-head{color:${large.fg};background-color:${large.bg};font-size:26px;font-weight:700}` : "";
const bigHead = large ? `<h2 class="big-head">${h2a}</h2>` : `<h2>${h2a}</h2>`;
const styleBlock = `<style>
body{color:${body.fg};background-color:${body.bg};font-family:system-ui,sans-serif;line-height:1.5}
.${noteClass}{color:${note.fg};background-color:${note.bg}}
.${ctaClass}{color:${cta.fg};background-color:${cta.bg};padding:.6rem 1rem;border:0;border-radius:.4rem}
a:focus-visible,.${ctaClass}:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}${largeRule}
</style>`;
const skip = `<a href="#main">Skip to content</a>`;
const formFields = fields.map(([id, label, type]) =>
`<label for="${id}">${label}</label>\n<input id="${id}" name="${id}" type="${type}" autocomplete="${id}">`).join("\n");
const tableRows = rows.map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("\n");
const table = `<table>\n<caption>${caption}</caption>\n<tr>${colheads.map((c) => `<th scope="col">${c}</th>`).join("")}</tr>\n${tableRows}\n</table>`;
const sections = shuffle(rng, [
`<img src="${img}" alt="${heroAlt}">`,
`<p class="${noteClass}">${noteText}</p>`,
`<p><span style="color:${spanFg}">${spanText}</span></p>`,
table,
]);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${title}</title>
${styleBlock}
</head>
<body>
<header>
<nav>${skip} <a href="/${nav2.toLowerCase()}">${nav2}</a></nav>
<h1>${title}</h1>
</header>
<main id="main">
${bigHead}
${sections[0]}
${sections[1]}
<h3>${h2b}</h3>
<form action="/signup" method="post">
${formFields}
<button type="submit">Sign up</button>
</form>
${sections[2]}
<p><button class="${ctaClass}" type="button">${ctaText}</button></p>
${sections[3]}
</main>
<footer>
<p><a href="/archive">Archive</a> <a href="/contact">Contact</a></p>
</footer>
</body>
</html>`;
return {
html,
hooks: {
heroAlt: ` alt="${heroAlt}"`,
label: fields[1] ? `<label for="${fields[1][0]}">${fields[1][1]}</label>\n` : `<label for="${fields[0][0]}">${fields[0][1]}</label>\n`,
noteRule: `.${noteClass}{color:${note.fg};`,
noteBad: `.${noteClass}{color:${badFg(rng, note.bg)};`,
spanRule: `<span style="color:${spanFg}">`,
spanBad: `<span style="color:${badFg(rng, body.bg)}">`,
ctaButton: `<button class="${ctaClass}" type="button">${ctaText}</button>`,
ctaText,
focusRule: `\na:focus-visible,.${ctaClass}:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}`,
skip,
archive: `<a href="/archive">Archive</a>`,
},
};
}
const TABS = ["Overview", "History", "Members", "Billing", "Usage", "Alerts", "Archive", "Notes"];
// Hard tier: a different page skeleton, not the easy page with extra
// defects. Grouped fields carry names through an aria-labelledby chain,
// a tab widget holds role/tabindex/handler parts, and the table spans
// headers across columns and rows - so a fixer tuned to the easy template
// leaves real barriers behind.
function buildHard(rng) {
const title = `${pick(rng, ADJ)} ${pick(rng, NOUN)} ${pick(rng, KIND)}`;
const topics = pick(rng, TOPICS);
const [h2a, h2b, h3c] = topics;
const caption = pick(rng, CAPTIONS);
const noteClass = pick(rng, CLASS_A);
const ctaClass = pick(rng, CLASS_B);
const noteText = pick(rng, NOTES);
const spanText = pick(rng, SPANS);
const heroAlt = pick(rng, ALTS);
const img = `https://example.com/${title.toLowerCase().replace(/[^a-z]+/g, "-")}.jpg`;
const ctaText = pick(rng, CTA);
const nav2 = pick(rng, NAV2);
const cardText = pick(rng, CTA.filter((c) => c !== ctaText));
const tabs = pickN(rng, TABS, 2);
const [f0, f1, f2] = pickN(rng, FIELD_POOL, 3);
const colheads = pick(rng, COLHEADS);
const cells = pickN(rng, CELLS, 4);
const body = goodPair(rng);
const note = goodPair(rng);
const spanFg = goodFg(rng, body.bg);
const cta = goodPair(rng);
const tabPair = goodPair(rng);
const focusColor = goodPair(rng).fg;
const large = rng() < 0.5 ? largePair(rng) : null;
const largeRule = large ? `\n.big-head{color:${large.fg};background-color:${large.bg};font-size:26px;font-weight:700}` : "";
const bigHead = large ? `<h2 class="big-head" id="deck">${h2a}</h2>` : `<h2 id="deck">${h2a}</h2>`;
const styleBlock = `<style>
body{color:${body.fg};background-color:${body.bg};font-family:system-ui,sans-serif;line-height:1.5}
.${noteClass}{color:${note.fg};background-color:${note.bg}}
.tab{color:${tabPair.fg};background-color:${tabPair.bg};padding:.4rem .8rem;display:inline-block}
.${ctaClass}{color:${cta.fg};background-color:${cta.bg};padding:.6rem 1rem;border:0;border-radius:.4rem}
a:focus-visible,.${ctaClass}:focus-visible,[role=tab]:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}${largeRule}
</style>`;
const skip = `<a href="#main">Skip to content</a>`;
const labelParts = f0[1].split(" ");
const labSpanA = `<span id="l-a">${labelParts[0]}</span>`;
const labSpanB = `<span id="l-b">${labelParts.slice(1).join(" ") || pick(rng, topics)}</span>`;
const tabA = `<div role="tab" tabindex="0" onkeydown="pickTab('a')" aria-selected="true">${tabs[0]}</div>`;
const tabB = `<div role="tab" tabindex="0" onkeydown="pickTab('b')" aria-selected="false">${tabs[1]}</div>`;
const tabsOpen = `<div class="tabs" role="tablist" aria-labelledby="tabs-title">`;
const label = `<label for="hf2">${f1[1]}</label>`;
const cardHref = `/${cardText.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
const cardLink = `<a href="${cardHref}">${cardText}</a>`;
const table = `<table>
<caption>${caption}</caption>
<tr><th scope="col">${colheads[0]}</th><th colspan="2" scope="colgroup">${colheads[1]}</th></tr>
<tr><th scope="row">${cells[0][0]}</th><td>${cells[0][1]}</td><td>${cells[0][2]}</td></tr>
<tr><th scope="row">${cells[1][0]}</th><td>${cells[1][1]}</td><td>${cells[1][2]}</td></tr>
<tr><th scope="row">${cells[2][0]}</th><td>${cells[2][1]}</td><td>${cells[2][2]}</td></tr>
</table>`;
const sections = shuffle(rng, [
`<img src="${img}" alt="${heroAlt}">`,
`<p class="${noteClass}">${noteText}</p>`,
`<p><span style="color:${spanFg}">${spanText}</span></p>`,
table,
]);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${title}</title>
${styleBlock}
</head>
<body>
<header>
<nav>${skip} <a href="/${nav2.toLowerCase()}">${nav2}</a></nav>
<h1>${title}</h1>
</header>
<main id="main">
${bigHead}
<section aria-labelledby="deck">
${sections[0]}
${sections[1]}
</section>
<h3 id="tabs-title">${h2b}</h3>
${tabsOpen}
${tabA}
${tabB}
</div>
<h4>${h3c}</h4>
<fieldset>
<legend>${h3c}</legend>
${labSpanA} ${labSpanB}
<input id="hf1" name="hf1" type="${f0[2]}" autocomplete="off" aria-labelledby="l-a l-b">
${label}
<input id="hf2" name="hf2" type="${f1[2]}" autocomplete="${f1[0]}">
<input id="hf3" name="hf3" type="${f2[2]}" autocomplete="${f2[0]}" aria-label="${f2[1]}">
</fieldset>
${sections[2]}
<p>${cardLink} <button class="${ctaClass}" type="button">${ctaText}</button></p>
${sections[3]}
</main>
<footer>
<p><a href="/archive">Archive</a> <a href="/contact">Contact</a></p>
</footer>
</body>
</html>`;
return {
html,
hooks: {
heroAlt: ` alt="${heroAlt}"`,
label: `${label}\n`,
labSpanA,
labSpanB,
labelledby: `aria-labelledby="l-a l-b"`,
noteRule: `.${noteClass}{color:${note.fg};`,
noteBad: `.${noteClass}{color:${badFg(rng, note.bg)};`,
spanRule: `<span style="color:${spanFg}">`,
spanBad: `<span style="color:${badFg(rng, body.bg)}">`,
tabA,
tabsOpen,
ctaButton: `<button class="${ctaClass}" type="button">${ctaText}</button>`,
ctaText,
focusRule: `\na:focus-visible,.${ctaClass}:focus-visible,[role=tab]:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}`,
skip,
archive: `<a href="/archive">Archive</a>`,
cardLink,
cardHref,
cardText,
heading3: `<h3 id="tabs-title">${h2b}</h3>`,
},
};
}
// Each breaker rewrites one hook in the fixed page. Variants make the same
// defect appear in different disguises (role-button lookalikes, multi-step
// tab order, empty-label silences) so a template-aware regex fixer misses.
const BREAKERS = {
"missing-alt": (h) => [(p) => p.replace(h.hooks.heroAlt, ""), "alt removed"],
"unlabeled-input": (h, rng) => {
const variant = rng();
if (variant < 0.5) return [(p) => p.replace(h.hooks.label, ""), "label removed"];
if (variant < 0.8) return [(p) => p.replace(/<label for="(\w+)">/, '<label for="missing-$1">'), "label for broken"];
return [(p) => p.replace(h.hooks.label.trimEnd(), h.hooks.label.trimEnd().replace(/>([^<]+)</, "><")), "label emptied"];
},
"low-contrast": (h) => [(p) => p.replace(h.hooks.noteRule, h.hooks.noteBad).replace(h.hooks.spanRule, h.hooks.spanBad), "colors dimmed"],
"heading-order": (h, rng) => [(p) => (rng() < 0.5
? p.replace("<h3>", "<h5>").replace("</h3>", "</h5>")
: p.replace("<h1>", "<h2>").replace("</h1>", "</h2>")), "headings shuffled"],
"tabindex-positive": (h, rng) => [(p) => {
// Multi-step order: sprinkle 1-3 positive tabindices across the page.
let out = p.replace('<a href="#main">', '<a tabindex="3" href="#main">');
if (rng() < 0.6) out = out.replace('<a href="/archive">', '<a tabindex="1" href="/archive">');
if (rng() < 0.4) out = out.replace('type="submit"', 'tabindex="7" type="submit"');
return out;
}, "tabindex added"],
"div-button": (h, rng) => {
const v = rng();
const repl = v < 0.4
? `<div class="cta-div" onclick="go()">${h.hooks.ctaText}</div>`
: v < 0.7
? `<div role="button">${h.hooks.ctaText}</div>`
: `<span class="cta-div" onclick="go()">${h.hooks.ctaText}</span>`;
return [(p) => p.replace(h.hooks.ctaButton, repl), "button divved"];
},
"missing-lang": () => [(p) => p.replace('<html lang="en">', "<html>"), "lang removed"],
"no-focus-style": (h) => [(p) => p.replace(h.hooks.focusRule, ""), "focus rule removed"],
"empty-link": (h, rng) => {
const v = rng();
if (v < 0.5) return [(p) => p.replace(h.hooks.archive, '<a href="/archive"></a>'), "link emptied"];
if (v < 0.8) return [(p) => p.replace(h.hooks.archive, '<a href="/archive" aria-label=""></a>'), "link label emptied"];
return [(p) => p.replace(h.hooks.archive, '<a href="/archive"><span class="icon"></span></a>'), "link icon unlabeled"];
},
"table-headers": () => [(p) => p.replaceAll("<th scope=\"col\">", "<td>").replaceAll("</th>", "</td>"), "headers demoted"],
};
// Hard-tier breakers hit the widget skeleton: dangling name chains, a Tab
// trap, a control nested in a link, a widget hidden from AT, and spanning
// headers demoted. Each leaves the page looking close to fixed, so a
// template-aware repair still fails the check.
const HARD_BREAKERS = {
"missing-alt": (h) => [(p) => p.replace(h.hooks.heroAlt, ""), "alt removed"],
"unlabeled-input": (h, rng) => {
const v = rng();
if (v < 0.35) return [(p) => p.replace(h.hooks.labSpanB, h.hooks.labSpanB.replace('id="l-b"', 'id="l-gone"')), "labelledby link cut"];
if (v < 0.6) return [(p) => p.replace(h.hooks.labSpanA, h.hooks.labSpanA.replace(/>([^<]+)</, "><")).replace(h.hooks.labSpanB, h.hooks.labSpanB.replace(/>([^<]+)</, "><")), "labelledby emptied"];
if (v < 0.8) return [(p) => p.replace(h.hooks.labelledby, 'aria-labelledby="l-a l-missing"'), "labelledby dangled"];
return [(p) => p.replace(h.hooks.label, ""), "label removed"];
},
"low-contrast": (h) => [(p) => p.replace(h.hooks.noteRule, h.hooks.noteBad).replace(h.hooks.spanRule, h.hooks.spanBad), "colors dimmed"],
"heading-order": (h, rng) => [(p) => (rng() < 0.5
? p.replace("<h3", "<h5").replace("</h3>", "</h5>")
: p.replace("<h1>", "<h2>").replace("</h1>", "</h2>")), "headings shuffled"],
"tabindex-positive": (h, rng) => [(p) => {
// Two disguises: a focus trap on the first tab (Tab swallowed), and
// a bent multi-step order across nav and footer.
let out = p;
if (rng() < 0.6) out = out.replace('onkeydown="pickTab(\'a\')"', "onkeydown=\"if(event.key==='Tab')event.preventDefault()\"");
out = out.replace('<a href="#main">', '<a tabindex="2" href="#main">');
if (rng() < 0.5) out = out.replace('<a href="/archive">', '<a tabindex="1" href="/archive">');
return out;
}, "tab order bent"],
"div-button": (h, rng) => {
const v = rng();
if (v < 0.4) return [(p) => p.replace(`<p>${h.hooks.cardLink} ${h.hooks.ctaButton}</p>`, `<p><a href="${h.hooks.cardHref}">${h.hooks.cardText}<div class="cta-div" onclick="go()">${h.hooks.ctaText}</div></a></p>`), "control nested in link"];
if (v < 0.7) return [(p) => p.replace(h.hooks.tabA, h.hooks.tabA.replace(' tabindex="0" onkeydown="pickTab(\'a\')"', "")), "tab lost keyboard support"];
return [(p) => p.replace(h.hooks.tabsOpen, h.hooks.tabsOpen.replace(/>$/, ' aria-hidden="true">')), "widget hidden from AT"];
},
"missing-lang": () => [(p) => p.replace('<html lang="en">', "<html>"), "lang removed"],
"no-focus-style": (h) => [(p) => p.replace(h.hooks.focusRule, ""), "focus rule removed"],
"empty-link": (h, rng) => {
const v = rng();
// The div-button breaker can consume the card link first; the footer
// archive link is always there as a fallback target.
return [(p) => {
const target = p.includes(h.hooks.cardLink) ? h.hooks.cardLink : h.hooks.archive;
if (v < 0.4 && target === h.hooks.cardLink) return p.replace(target, target.replace(">", ' aria-labelledby="ghost">'));
if (v < 0.7) return p.replace(target, target.replace(/>([^<]+)</, "><"));
return p.replace(target, target.replace(/>([^<]+)</, '><span class="icon"></span><'));
}, "link name removed"];
},
"table-headers": () => [(p) => p.replaceAll("<th ", "<td ").replaceAll("</th>", "</td>"), "headers demoted"],
};
function pickDefects(rng, taskIndex, tier) {
const ids = CHECKS.map(([id]) => id);
const defects = new Set([ids[taskIndex % ids.length]]);
const target = tier === "hard" ? 4 + Math.floor(rng() * 2) : 2 + Math.floor(rng() * 2);
while (defects.size < target) defects.add(ids[Math.floor(rng() * ids.length)]);
return [...defects];
}
const PROMPT_HEAD = `Fix the broken HTML page below so keyboard, screen-reader, and contrast checks pass.
Repair every defect you find: image text alternatives, input labels, text contrast (4.5:1 or better, or 3:1 for large text), heading order, tab order, native buttons, page language, visible focus styles, link names, and table headers. Keep all visible text and elements; do not delete or hide content to silence a check.
Return the complete fixed HTML document.`;
// Verification imports the real grader from the built package: an
// expected page is only a valid reference when it scores exactly 1.
const { benchmark } = await import(new URL("../dist/index.js", import.meta.url).href).catch(() => {
throw new Error("dist/index.js not found - run `npm run build` before generating tasks");
});
// Tokens that mean a template leak: a breaker or builder read a field
// that does not exist and strung the result into the page.
const JUNK = /\bundefined\b|\bNaN\b|\[object Object\]|\bnull\b/;
const assertNoJunk = (where, text) => {
if (JUNK.test(text)) throw new Error(`generated ${where} contains a template-leak token`);
};
// Grade the fixed page as if every check were an injected defect: the
// score is exactly 1 iff all ten checks pass with real targets. A page
// that fails any check gets re-drawn; a reference that caps its own
// task below 1 must never ship.
const ALL_DEFECTS = CHECKS.map(([id]) => id);
async function expectedScoresOne(html) {
const probe = { id: "a11y-probe", kind: "single", prompt: `\`\`\`html\n${html}\n\`\`\``, expected: html, metadata: { defects: ALL_DEFECTS } };
const result = await benchmark.score(probe, { answer: html });
return result.score === 1;
}
const rng = mulberry32(seed);
const tasks = [];
const fingerprints = new Set();
for (let i = 0; i < count; i++) {
const tier = i % 3 === 2 ? "hard" : "easy";
const build = tier === "hard" ? buildHard : buildFixed;
const breakers = tier === "hard" ? HARD_BREAKERS : BREAKERS;
let built;
for (let attempt = 0; ; attempt += 1) {
built = build(rng);
assertNoJunk(`page ${i + 1}`, built.html);
if (await expectedScoresOne(built.html)) break;
if (attempt >= 199) throw new Error(`task ${i + 1}: no clean reference page after 200 draws`);
}
const defects = pickDefects(rng, i, tier).sort();
let broken = built.html;
for (const id of defects) {
const [breakPage] = breakers[id](built, rng);
const next = breakPage(broken);
if (next === broken) throw new Error(`breaker ${id} changed nothing on task ${i + 1}`);
broken = next;
}
if (broken === built.html) throw new Error(`task ${i + 1} has no visible break`);
assertNoJunk(`task ${i + 1}`, broken);
fingerprints.add(createHash("sha1").update(built.html.replace(/>\s*</g, "><").replace(/[\w.-]+(?=\.jpg|"[a-z-]+")/g, "#")).digest("hex").slice(0, 12));
const idNum = String(i + 1).padStart(2, "0");
tasks.push({
id: `${split === "hidden" ? "a11yh" : "a11y"}-${idNum}`,
kind: "single",
prompt: `${PROMPT_HEAD}\n\n\`\`\`html\n${broken}\n\`\`\``,
expected: built.html,
metadata: {
defects, wcag: defects.map((d) => WCAG[d]), tier, seed, split, taskSeed: seed + i,
},
});
assertNoJunk(`task ${i + 1} prompt`, tasks[tasks.length - 1].prompt);
}
const coverage = new Map(CHECKS.map(([id]) => [id, 0]));
for (const task of tasks) for (const id of task.metadata.defects) coverage.set(id, coverage.get(id) + 1);
for (const [id, n] of coverage) {
if (n < Math.floor(count / CHECKS.length)) throw new Error(`check ${id} appears in only ${n} tasks`);
}
// Distinct pages, not six fixed themes: the hidden split cannot reuse a
// public reference page. Require well above the old six-theme ceiling.
if (fingerprints.size < Math.min(30, count)) {
throw new Error(`only ${fingerprints.size} distinct page fingerprints (need >= ${Math.min(30, count)})`);
}
await mkdir(dirname(out), { recursive: true });
await writeFile(out, `${tasks.map((task) => JSON.stringify(task)).join("\n")}\n`);
console.log(`generated ${tasks.length} ${split} tasks (seed ${seed}) -> ${out}`);
console.log(`fingerprints: ${fingerprints.size} distinct pages`);
console.log(`coverage: ${[...coverage].map(([id, n]) => `${id}=${n}`).join(" ")}`);
|