@reqvire-org/ads 0.3.52 → 0.3.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,7 +79,7 @@ There is no warning level.
79
79
  | **Static accessibility** | Focus styles, icon-only labels, image alt text, reduced motion, target size, text resize and text spacing are checked from source and tokens, without a browser. |
80
80
  | **Contrast** | `token-contrast` checks the role pairs that meet on screen (text on surfaces, fills with their foreground, status text on tints, focus indicators and control borders) in every theme and brand. `component-contrast` checks the pairs components and patterns make themselves: a style block (including a nested state such as `&:hover` or `&[aria-selected="true"]`) that sets both `color` and `background` to tokens, such as a status color as text on its own tint. Both resolve every CSS color syntax, including `oklch()` and `color-mix()`, and composite translucent fills over the canvas. Text needs 4.5:1; focus indicators and control borders need 3:1; disabled states are exempt. |
81
81
  | **Layout** | Widths are fluid on the grid. `layout-fixed-width` fails a width, `flex-basis` or grid track that cannot shrink below 96 px, in any unit, whether raw, from a token or by arithmetic; small parts use plain sizes, `min(100%, 280px)` and `%` shrink, a maximum is not read, and widths declared in `layout.widthTokens` pass and are listed for review. `layout-overflow` renders every UI scenario at 390, 768 and 1280 px and fails on horizontal page overflow and clipped content, and renders components and patterns in a 240 px container, where a set width above 96 px must fit; scrollers and ellipsis are exempt. |
82
- | **Web performance** | `img-attributes` fails a raw `<img>` without dimensions or a `loading` choice, and a `srcset` with width descriptors and no `sizes`; `asset-image-budget` fails oversized images in `assets/` (SVG 100 KB, WebP and AVIF 300 KB, JPEG 400 KB, PNG and GIF 500 KB, or `assets.imageBudgetKb`); `layout-shift` fails a rendered scenario above 0.1. `ads assets` generates preloads for the fonts the first text uses, on the URLs the stylesheet requests. Page metadata, sitemaps, hosting and Lighthouse stay with the application. |
82
+ | **Web performance** | `img-attributes` fails a raw `<img>` without dimensions or a `loading` choice, and a `srcset` with width descriptors and no `sizes`; `asset-image-budget` fails oversized images in `assets/` (SVG 100 KB, WebP and AVIF 300 KB, JPEG 400 KB, PNG and GIF 500 KB, or `assets.imageBudgetKb`); `layout-shift` fails a rendered scenario above 0.1; `img-shape` fails an image rendered at another shape than it declares; `font-weight-missing` and `asset-font-budget` hold fonts to what is declared and a size. `ads assets` generates preloads for the fonts the first text uses, on the URLs the stylesheet requests. Page metadata, sitemaps, hosting and Lighthouse stay with the application. |
83
83
  | **Themes and brands** | One mechanism: per-theme halves (`--x-light`, `--x-dark`) and brands on `[data-brand]`. `ads assets` generates `themes.generated.css` and `.ts`; missing or conflicting halves, empty themes, stale generated files, `light-dark()` and ancestor theme selectors are errors. |
84
84
  | **Tokens** | Ownership, naming, rhythm, missing and scenario references; equal values in different roles are flagged for review. |
85
85
  | **Architecture** | Data, UX and Skin ownership, project structure, unit and paint contracts, binding and variable ownership; Linaria atomic composition risks are flagged for review. |
package/dist/assets.mjs CHANGED
@@ -69,6 +69,20 @@ export function inspectGlyphs({ root, dsRoot, config }) {
69
69
  * PNG and GIF are for flat art and icons, where a 1024 px master fits in 500; an SVG over 100 is
70
70
  * usually an embedded bitmap or unoptimized paths. assets.imageBudgetKb replaces them all. */
71
71
  export const imageBudgets = Object.freeze({ ".svg": 100, ".webp": 300, ".avif": 300, ".jpg": 400, ".jpeg": 400, ".png": 500, ".gif": 500 });
72
+ /** A font file above this is rarely one Latin subset: the largest of a set of real projects' fonts, a
73
+ * variable font covering two scripts, is 108 KB. assets.fontBudgetKb replaces it. */
74
+ export const fontBudgetKb = 150;
75
+ function inspectFontBudget({ root, dsRoot, config }) {
76
+ const directory = path.join(dsRoot, "assets"), findings = [];
77
+ for (const relative of assetFiles(directory)) {
78
+ if (!/\.(?:woff2?|ttf|otf)$/i.test(relative)) continue;
79
+ const limit = config.assets.fontBudgetKb ?? fontBudgetKb, file = path.join(directory, relative), kb = Math.ceil(lstatSync(file).size / 1024);
80
+ if (kb <= limit) continue;
81
+ findings.push({ rule: "asset-font-budget", severity: findingSeverity("asset-font-budget"), file: path.relative(root, file).replaceAll("\\", "/"), line: 1, column: 1, guidanceUri: "ads://guides/performance",
82
+ message: `${path.basename(file)} is ${kb} KB; a font file stays within ${limit} KB. Use WOFF2, subset it to the script the page uses, and put other scripts in their own unicode-range files. assets.fontBudgetKb in ds.config.json changes the limit.` });
83
+ }
84
+ return findings;
85
+ }
72
86
  function inspectImageBudget({ root, dsRoot, config }) {
73
87
  const directory = path.join(dsRoot, "assets"), findings = [];
74
88
  for (const relative of assetFiles(directory)) {
@@ -113,7 +127,7 @@ export function inspectAssets({ root, dsRoot, config, trackingRoot = root }) {
113
127
  const diagnostics = [];
114
128
  const sourceDiagnostic = brandSourceDiagnostic({ root, dsRoot, config });
115
129
  if (sourceDiagnostic) diagnostics.push(sourceDiagnostic);
116
- diagnostics.push(...inspectBrand({ root, dsRoot, config }), ...inspectGlyphs({ root, dsRoot, config }), ...inspectImageBudget({ root, dsRoot, config }));
130
+ diagnostics.push(...inspectBrand({ root, dsRoot, config }), ...inspectGlyphs({ root, dsRoot, config }), ...inspectImageBudget({ root, dsRoot, config }), ...inspectFontBudget({ root, dsRoot, config }));
117
131
  function report(rule, file, message) { diagnostics.push({ rule, file: path.relative(root, file).replaceAll("\\", "/") || ".", line: 1, column: 1, message }); }
118
132
  const assetRoot = path.join(dsRoot, "assets");
119
133
  // Every mount is compared with the canonical ADS assets. Public mounts are
@@ -16,3 +16,25 @@ export async function firstRender() {
16
16
  await Promise.race([ready, new Promise(resolve => setTimeout(resolve, 5000))]);
17
17
  await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
18
18
  }
19
+
20
+ /**
21
+ * Waits until the page has stopped changing: no mutation in the scenario for `quietMs` and no finite
22
+ * animation running, up to `limitMs`. Content that arrives after first render, such as syntax colours
23
+ * from a grammar loaded late, is otherwise measured in some runs and missed in others. Nothing here
24
+ * knows a project's signals. Returns whether it got quiet. Self-contained, like firstRender.
25
+ */
26
+ export async function contentQuiet({ quietMs, limitMs }) {
27
+ const started = performance.now();
28
+ let last = started;
29
+ const observer = new MutationObserver(records => { if (records.some(record => !record.target.closest?.("#ads-preview-status") && !record.target.parentElement?.closest("#ads-preview-status"))) last = performance.now(); });
30
+ observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
31
+ const moving = () => document.getAnimations().some(animation => animation.playState === "running" && animation.effect?.getComputedTiming().iterations !== Infinity);
32
+ try {
33
+ while (performance.now() - started < limitMs) {
34
+ if (moving()) last = performance.now();
35
+ else if (performance.now() - last >= quietMs) return true;
36
+ await new Promise(resolve => setTimeout(resolve, 50));
37
+ }
38
+ return false;
39
+ } finally { observer.disconnect(); }
40
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Images rendered at a shape other than the one they declare. Self-contained: Playwright serializes
3
+ * it into the page. The declared shape is the CSS aspect-ratio or, without one, the width and height
4
+ * attributes. A height attribute beats aspect-ratio unless the CSS says height: auto, so an image can
5
+ * reserve its space, pass layout-shift, and still be cropped to the wrong shape. With no aspect-ratio,
6
+ * object-fit: cover, contain or none is a deliberate crop in a box of its own; only a fill stretches.
7
+ */
8
+ export function imageShape({ nodeLimit }) {
9
+ const root = document.querySelector("#root");
10
+ if (!root) return { issues: [], counts: {} };
11
+ const selector = element => {
12
+ const parts = [];
13
+ for (let node = element; node && node !== root; node = node.parentElement) {
14
+ const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
15
+ parts.unshift(`${node.localName}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(node) + 1})` : ""}`);
16
+ }
17
+ return ["#root", ...parts].join(" > ").slice(0, 300);
18
+ };
19
+ const issues = [], counts = { shape: 0 };
20
+ for (const image of root.querySelectorAll("img")) {
21
+ if (!image.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) || (image.complete && !image.naturalWidth)) continue;
22
+ const box = image.getBoundingClientRect();
23
+ if (box.width < 8 || box.height < 8) continue;
24
+ const style = getComputedStyle(image), authored = /^(?:auto\s+)?([\d.]+)\s*\/\s*([\d.]+)$/.exec(style.aspectRatio);
25
+ // The browser reports the attributes' ratio as "auto W / H"; only a value without auto is the author's.
26
+ const explicit = authored && !style.aspectRatio.startsWith("auto") ? Number(authored[1]) / Number(authored[2]) : undefined;
27
+ const width = Number(image.getAttribute("width")), height = Number(image.getAttribute("height"));
28
+ const attributes = width > 0 && height > 0 ? width / height : undefined;
29
+ if (explicit === undefined && (attributes === undefined || style.objectFit !== "fill")) continue;
30
+ const declared = explicit ?? attributes, rendered = box.width / box.height;
31
+ // Rounding moves a small box by a pixel or so; 3% and 2 px of height is not rounding.
32
+ if (Math.abs(rendered / declared - 1) <= 0.03 || Math.abs(box.width / declared - box.height) <= 2) continue;
33
+ if (counts.shape++ < nodeLimit) issues.push({ kind: "shape", selector: selector(image), html: image.outerHTML.replace(/\s+/g, " ").slice(0, 200), rendered: `${Math.round(box.width)}x${Math.round(box.height)}`, declared: explicit !== undefined ? `aspect-ratio ${style.aspectRatio}` : `width and height ${width}x${height}` });
34
+ }
35
+ return { issues, counts };
36
+ }
@@ -4,36 +4,43 @@ import { nonTextContrast } from "./non-text-contrast.mjs";
4
4
  /**
5
5
  * Renders what a scenario shows only after someone acts on it, and measures it with the same checks.
6
6
  *
7
- * Overlays: each control marked aria-haspopup is clicked, up to `overlayLimit` not yet opened, and what
7
+ * Overlays: each control marked aria-haspopup that this render was assigned is clicked, and what
8
8
  * opens is audited by axe and non-text contrast, then held to the phone viewport. Fixed layers are
9
9
  * exempt from the overflow check of the page, so this is the only place their width is measured. An
10
10
  * overlay a scenario renders open is measured the same way. Accessibility trees are read through
11
11
  * ARIA, not names: a trigger with no aria-haspopup is not found, and its scenario can render it open.
12
12
  *
13
- * Hover and keyboard focus: up to `stateLimit` controls not yet measured in this theme are hovered with the real mouse and
13
+ * Hover and keyboard focus: each control this render was assigned is hovered with the real mouse and
14
14
  * focused as the keyboard would, for contrast only: axe color-contrast when a quick reading looks
15
15
  * wrong, non-text contrast in that state, and the focus outline against what is around it. What
16
16
  * already fails at rest is not repeated.
17
17
  *
18
- * Results join the render's own, with selectors that say which state they were found in.
18
+ * The worker assigns targets in request order, so which render measures what does not depend on
19
+ * which page got there first. Results join the render's own, with selectors that say which state they
20
+ * were found in, and `result.coverage` says what was measured and what was skipped and why.
19
21
  */
20
22
  const overlays = '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], dialog[open], [popover]:popover-open';
21
23
 
22
- function markTargets({ selector, attribute, limit, signature, known = [] }) {
23
- const seen = new Set(known), targets = [], keys = [];
24
+ /** Lists what could be measured, in document order, each distinct one once; with `only`, marks those. */
25
+ function findTargets({ selector, attribute, signature, trigger, only }) {
26
+ const seen = new Set(), targets = [];
24
27
  for (const element of document.querySelector("#root").querySelectorAll(selector)) {
25
- if (targets.length >= limit) break;
26
28
  const box = element.getBoundingClientRect();
27
29
  if (box.width < 1 || box.height < 1 || element.closest('#ads-preview-status, [inert], [aria-disabled="true"]') || element.matches(":disabled") || !element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
28
30
  const name = (element.getAttribute("aria-label") ?? element.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60) || element.localName;
29
- const key = `${signature.map(name => element.getAttribute(name) ?? "").join("|")}|${element.localName}|${attribute === "data-ads-audit-trigger" ? name : getComputedStyle(element.parentElement).backgroundColor}`;
31
+ const key = `${signature.map(item => element.getAttribute(item) ?? "").join("|")}|${element.localName}|${trigger ? name : getComputedStyle(element.parentElement).backgroundColor}`;
30
32
  if (seen.has(key)) continue;
31
- seen.add(key); keys.push(key);
32
- element.setAttribute(attribute, String(targets.length));
33
- targets.push(name);
33
+ seen.add(key);
34
+ if (only && !only.includes(key)) continue;
35
+ if (only) element.setAttribute(attribute, String(targets.length));
36
+ targets.push({ key, name });
34
37
  }
35
- return { targets, keys };
38
+ return targets;
36
39
  }
40
+ export const triggerTargets = { selector: '[aria-haspopup]:not([aria-haspopup="false"])', attribute: "data-ads-audit-trigger", signature: ["aria-haspopup", "class"], trigger: true };
41
+ export const controlTargets = { selector: 'button, a[href], input:not([type="hidden"]), select, textarea, [role="switch"], [role="checkbox"], [role="radio"], [role="slider"], [role="tab"]', attribute: "data-ads-audit-control", signature: ["class", "role", "type"] };
42
+ /** What this render could measure, read before anything acts on the page. */
43
+ export const listTargets = async frame => ({ triggers: await frame.evaluate(findTargets, triggerTargets), controls: await frame.evaluate(findTargets, controlTargets) });
37
44
  const settle = () => new Promise(resolve => requestAnimationFrame(() => { for (const animation of document.getAnimations()) { try { animation.finish(); } catch { /* An endless one has no end to reach. */ } } requestAnimationFrame(resolve); }));
38
45
 
39
46
  /** A quick reading of a hovered control's text against its background, so axe, which sets up the whole
@@ -74,10 +81,19 @@ function overlayPastViewport() {
74
81
  const box = element.getBoundingClientRect(), width = document.documentElement.clientWidth, past = Math.round(Math.max(box.right - width, -box.left));
75
82
  return past > 1 ? { overflow: past, html: element.outerHTML.replace(/\s+/g, " ").slice(0, 200) } : null;
76
83
  }
77
- /** The focus outline's contrast with what is around it, when the focus shows as an outline. */
78
- function focusOutline() {
84
+ /** The focus outline's contrast with what is around it, when the focus shows as an outline, and only
85
+ * where a keyboard can bring it. A negative tabindex is reachable only as an item of a composite widget
86
+ * that holds the roving tab stop, which arrow keys move through. */
87
+ async function focusOutline() {
79
88
  const element = document.querySelector("[data-ads-audit-state]");
89
+ if (element.closest('[aria-hidden="true"], [inert]')) return { unreachable: true };
90
+ if (element.tabIndex < 0) {
91
+ const widget = element.closest('[role="group"], [role="tablist"], [role="menu"], [role="menubar"], [role="radiogroup"], [role="toolbar"], [role="listbox"], [role="tree"], [role="grid"]');
92
+ if (!widget?.querySelector('[tabindex="0"]')) return { unreachable: true };
93
+ }
80
94
  element.focus({ focusVisible: true });
95
+ // An outline that transitions in is read where it ends, the same every run.
96
+ await new Promise(resolve => requestAnimationFrame(() => { for (const animation of document.getAnimations()) { try { animation.finish(); } catch { /* An endless one has no end to reach. */ } } requestAnimationFrame(resolve); }));
81
97
  if (document.activeElement !== element || !element.matches(":focus-visible")) return null;
82
98
  const style = getComputedStyle(element);
83
99
  // A ring drawn with box-shadow is not read, so an outline beside one is not taken for the only indicator.
@@ -99,9 +115,14 @@ const unmarked = text => text?.replace(/\[?data-ads-audit-[a-z.]+(?:="[^"]*")?\]
99
115
  const named = (nodes, label) => nodes.map(node => ({ ...node, selector: `${label}: ${unmarked(node.selector)}`.slice(0, 300), ...(node.html ? { html: unmarked(node.html) } : {}) }));
100
116
  const labelled = (groups, label) => groups.map(group => ({ ...group, nodes: named(group.nodes, label) }));
101
117
 
102
- /** Runs both, adding what it finds to `result`. One failing control ends only its own part. */
103
- export async function auditRenderStates({ page, frame, result, request, phoneWidth, measuredControls }) {
104
- const { nodeLimit, tags, overlayLimit, stateLimit } = request, desktop = page.viewportSize();
118
+ const failure = error => /detached|not attached|intercept/i.test(error.message) ? "detached" : /timeout/i.test(error.message) ? "timeout" : "failed";
119
+
120
+ /** Runs both on what this render was assigned, adding what it finds to `result`. One failing target
121
+ * ends only its own part, and is recorded in `result.coverage`. */
122
+ export async function auditRenderStates({ page, frame, result, request, phoneWidth, assigned }) {
123
+ const { nodeLimit, tags } = request, desktop = page.viewportSize();
124
+ const coverage = result.coverage = { overlays: 0, controls: 0, skipped: [] };
125
+ const skip = (reason, name) => coverage.skipped.push({ reason, name });
105
126
  const isClosed = () => frame.waitForFunction(() => { const element = document.querySelector("[data-ads-audit-overlay]"); return !element || !element.checkVisibility(); }, undefined, { timeout: 1000 }).then(() => true, () => false);
106
127
  const unmark = () => frame.evaluate(() => { for (const element of document.querySelectorAll("[data-ads-audit-overlay]")) element.removeAttribute("data-ads-audit-overlay"); });
107
128
  const measureOverlay = async (label, reopen) => {
@@ -122,42 +143,46 @@ export async function auditRenderStates({ page, frame, result, request, phoneWid
122
143
  if (past) result.layout.push({ width: phoneWidth, issues: [{ kind: "viewport", selector: label, ...past }], counts: { viewport: 1 } });
123
144
  await page.setViewportSize(desktop);
124
145
  await frame.evaluate(settle);
125
- result.overlays = (result.overlays ?? 0) + 1;
146
+ coverage.overlays++;
126
147
  };
127
148
  // Already open: nothing to click, and nothing to close.
128
149
  if (await frame.evaluate(markOpened, { overlays, known: false })) {
129
150
  await measureOverlay("open overlay");
130
151
  await unmark();
131
152
  }
132
- // A shell repeated across scenarios opens the same menu in each: one audit measures it once per theme and brand.
133
- const { targets: triggers, keys: triggerKeys } = await frame.evaluate(markTargets, { selector: '[aria-haspopup]:not([aria-haspopup="false"])', attribute: "data-ads-audit-trigger", limit: overlayLimit, signature: ["aria-haspopup", "class"], known: [...measuredControls] });
134
- for (const key of triggerKeys) measuredControls.add(key);
135
- for (const [index, name] of triggers.entries()) {
153
+ const triggers = await frame.evaluate(findTargets, { ...triggerTargets, only: assigned.triggers.map(item => item.key) });
154
+ for (const { key, name } of assigned.triggers) if (!triggers.some(item => item.key === key)) skip("overlay-trigger-gone", name);
155
+ for (const [index, { name }] of triggers.entries()) {
136
156
  try {
137
- await frame.evaluate(overlays => { for (const element of document.querySelectorAll(overlays)) element.setAttribute("data-ads-audit-known", ""); }, overlays);
157
+ // Only what is open now is known: a closed overlay's element is often reused by the next one.
158
+ await frame.evaluate(overlays => { for (const element of document.querySelectorAll(overlays)) element.toggleAttribute("data-ads-audit-known", element.checkVisibility()); }, overlays);
138
159
  const open = async () => {
139
- await frame.locator(`[data-ads-audit-trigger="${index}"]`).click({ timeout: 2000 });
140
- return frame.waitForFunction(markOpened, { overlays, known: true }, { timeout: 1500 }).then(() => true, () => false);
160
+ // A click while the last overlay is still going away only dismisses it, so a second one opens.
161
+ for (const wait of [3000, 1500]) {
162
+ await frame.locator(`[data-ads-audit-trigger="${index}"]`).click({ timeout: 5000 });
163
+ if (await frame.waitForFunction(markOpened, { overlays, known: true }, { timeout: wait }).then(() => true, () => false)) return true;
164
+ await frame.evaluate(settle);
165
+ }
166
+ return false;
141
167
  };
142
- if (!await open()) continue;
168
+ if (!await open()) { skip("overlay-did-not-open", name); continue; }
143
169
  await measureOverlay(`open overlay "${name}"`, open);
144
170
  await page.keyboard.press("Escape");
145
171
  const closed = await isClosed();
146
172
  await unmark();
147
173
  // One that stays open covers the page, so the next trigger cannot be reached.
148
- if (!closed) break;
149
- } catch { /* A trigger that cannot be used says nothing about what it opens. */ }
174
+ if (!closed) { for (const { name: next } of triggers.slice(index + 1)) skip("overlay-left-open", next); break; }
175
+ } catch (error) { skip(`overlay-${failure(error)}`, name); }
150
176
  }
151
177
  // What already fails at rest: axe names elements the same way each run, and non-text findings are the same colors.
152
178
  const pair = issue => JSON.stringify([issue.kind, issue.foreground, issue.background]);
153
179
  const rest = new Set([...result.nonText.issues.map(pair), ...result.violations.filter(item => item.id === "color-contrast").flatMap(item => item.nodes.map(node => node.selector))]);
154
- // The same control on the same surface measures the same everywhere, so one audit measures it once per theme and brand.
155
- const { targets, keys } = await frame.evaluate(markTargets, { selector: 'button, a[href], input:not([type="hidden"]), select, textarea, [role="switch"], [role="checkbox"], [role="radio"], [role="slider"], [role="tab"]', attribute: "data-ads-audit-control", limit: stateLimit, signature: ["class", "role", "type"], known: [...measuredControls] });
156
- for (const key of keys) measuredControls.add(key);
157
- for (const [index] of targets.entries()) {
180
+ const targets = await frame.evaluate(findTargets, { ...controlTargets, only: assigned.controls.map(item => item.key) });
181
+ for (const { key, name } of assigned.controls) if (!targets.some(item => item.key === key)) skip("control-gone", name);
182
+ for (const [index, { name }] of targets.entries()) {
158
183
  const target = `[data-ads-audit-control="${index}"]`;
159
184
  try {
160
- await frame.locator(target).hover({ timeout: 1000, force: true });
185
+ await frame.locator(target).hover({ timeout: 3000, force: true });
161
186
  await frame.evaluate(target => document.querySelector(target).setAttribute("data-ads-audit-state", ""), target);
162
187
  await frame.evaluate(settle);
163
188
  if (await frame.evaluate(hoverTextSuspect, target)) {
@@ -170,13 +195,14 @@ export async function auditRenderStates({ page, frame, result, request, phoneWid
170
195
  result.nonText.issues.push(...named(issues, "hover"));
171
196
  for (const issue of issues) result.nonText.counts[issue.kind] = (result.nonText.counts[issue.kind] ?? 0) + 1;
172
197
  const outline = await frame.evaluate(focusOutline);
173
- if (outline) {
198
+ if (outline?.unreachable) skip("focus-not-reachable", name);
199
+ else if (outline) {
174
200
  result.nonText.issues.push({ kind: "focus", selector: `focus: ${await frame.locator(target).evaluate(element => element.localName)}`, ...outline });
175
201
  result.nonText.counts.focus = (result.nonText.counts.focus ?? 0) + 1;
176
202
  }
177
203
  await frame.evaluate(target => { const element = document.querySelector(target); element.removeAttribute("data-ads-audit-state"); element.blur(); }, target);
178
- } catch { /* A control that cannot be reached has no state to measure. */ }
204
+ coverage.controls++;
205
+ } catch (error) { skip(`control-${failure(error)}`, name); }
179
206
  }
180
207
  await page.mouse.move(desktop.width - 1, desktop.height - 1);
181
- result.controls = (result.controls ?? 0) + targets.length;
182
208
  }
@@ -3,21 +3,22 @@ import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { openPreviewScenario } from "../verification/browser.mjs";
5
5
  import { axeRun } from "./axe-run.mjs";
6
- import { firstRender } from "./first-render.mjs";
6
+ import { contentQuiet, firstRender } from "./first-render.mjs";
7
7
  import { nonTextContrast } from "./non-text-contrast.mjs";
8
8
  import { layoutOverflow } from "./layout-overflow.mjs";
9
9
  import { layoutShift } from "./layout-shift.mjs";
10
- import { auditRenderStates } from "./render-states.mjs";
10
+ import { imageShape } from "./image-shape.mjs";
11
+ import { auditRenderStates, listTargets } from "./render-states.mjs";
11
12
 
12
13
  // Runs only as an owned child, using the receiving project's browser dependency.
13
14
  const request = JSON.parse(readFileSync(process.argv[2], "utf8"));
14
15
  const playwright = createRequire(import.meta.url)(request.playwright);
15
16
  const axe = readFileSync(request.axe, "utf8");
16
- const runs = [];
17
+ const runs = [], capped = new Map(), claimed = new Set(request.claimed ?? []);
17
18
  /** Atomic, so a worker that dies leaves the renders it finished readable. */
18
19
  function publish() {
19
20
  const file = path.join(request.output, "report.json"), temporary = `${file}.tmp`;
20
- writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, runId: request.runId, runs }));
21
+ writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, runId: request.runId, runs, capped: [...capped.values()] }));
21
22
  renameSync(temporary, file);
22
23
  }
23
24
  let browser;
@@ -28,31 +29,60 @@ try {
28
29
  const apps = request.apps.filter(app => app.theme === theme);
29
30
  // The audit injects its own script; bypassCSP keeps project CSP from blocking it.
30
31
  const context = await browser.newContext({ viewport: request.viewport, deviceScaleFactor: 1, colorScheme: apps[0].scheme, bypassCSP: true, reducedMotion: "reduce" });
31
- const measuredControls = new Set();
32
+ // Each render lists what it could measure, then takes its turn in request order: a shared control is
33
+ // measured by the first scenario that has it, however fast the pages load. A cap leaves the rest for later renders.
34
+ const lists = apps.map(() => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; });
35
+ const assign = (kind, { scenario, theme, brand }, items, limit) => {
36
+ const scope = JSON.stringify([theme, brand ?? null]), fresh = items.map(item => ({ ...item, claim: `${scope}${kind}${item.key}` })).filter(item => !claimed.has(item.claim));
37
+ for (const item of fresh.slice(0, limit)) { claimed.add(item.claim); capped.delete(item.claim); }
38
+ for (const item of fresh.slice(limit)) if (!capped.has(item.claim)) capped.set(item.claim, { claim: item.claim, reason: `${kind}-cap`, name: item.name, scenario, theme, ...(brand ? { brand } : {}) });
39
+ return fresh.slice(0, limit);
40
+ };
41
+ const turns = [];
42
+ apps.forEach((app, index) => { turns[index] = (turns[index - 1] ?? Promise.resolve()).then(() => lists[index].promise).then(({ triggers, controls }) => ({ triggers: assign("overlay", app, triggers, request.overlayLimit), controls: assign("control", app, controls, request.stateLimit) })); });
32
43
  try {
33
44
  // A bounded number of pages render at once; results keep request order.
34
45
  const results = [];
35
46
  let next = 0;
36
- async function lane() { while (next < apps.length) { const index = next++; results[index] = await attempt(apps[index]); runs.push(results[index]); publish(); } }
47
+ async function lane() { while (next < apps.length) { const index = next++; results[index] = await attempt(apps[index], index); runs.push(results[index]); publish(); } }
37
48
  await Promise.all(Array.from({ length: Math.min(apps.length, request.concurrency ?? 1) }, lane));
38
49
  // One render failing is that render's result; what it found before failing is kept.
39
- async function attempt(app) {
50
+ async function attempt(app, index) {
40
51
  const partial = {};
41
- try { return await audit(app, partial); }
52
+ try { return await audit(app, partial, index); }
42
53
  catch (error) {
54
+ lists[index].resolve({ triggers: [], controls: [] });
43
55
  const code = error.failure?.code;
44
56
  return { scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), failed: true, cause: `${String(error.message).replace(/\s+/g, " ").trim().slice(0, 460)}${code ? ` (${code})` : ""}`, ...partial };
45
57
  }
46
58
  }
47
- async function audit(app, partial) {
59
+ async function audit(app, partial, index) {
48
60
  const page = await context.newPage();
61
+ // What the page is still loading: its files, also through the preview's asset reads. Streams and the host's status polling never end, so they do not count.
62
+ const loading = new Set(), loads = request => ["script", "stylesheet", "image", "font"].includes(request.resourceType()) || /resources\/read.*ads:\/\/assets\//.test(request.postData() ?? "");
63
+ page.on("request", request => { if (loads(request)) loading.add(request); });
64
+ for (const event of ["requestfinished", "requestfailed"]) page.on(event, request => loading.delete(request));
65
+ /** Quiet in the page and nothing loading, up to the limit: an async grammar shows up as both. */
66
+ const settled = async () => {
67
+ const end = Date.now() + request.contentLimitMs;
68
+ while (Date.now() < end) {
69
+ const quiet = await frame.evaluate(contentQuiet, { quietMs: request.contentQuietMs, limitMs: Math.max(end - Date.now(), 1) });
70
+ if (quiet && !loading.size) return true;
71
+ if (!quiet) return false;
72
+ await new Promise(resolve => setTimeout(resolve, 50));
73
+ }
74
+ return false;
75
+ };
76
+ let frame;
49
77
  try {
50
- const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
78
+ frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
51
79
  await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
52
80
  if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
53
81
  // Nothing is hovered at rest: the mouse starts over whatever sits at the page's corner.
54
82
  await page.mouse.move(request.viewport.width - 1, request.viewport.height - 1);
55
83
  await frame.evaluate(firstRender);
84
+ const contentSettled = await settled();
85
+ lists[index].resolve(await listTargets(frame));
56
86
  // Before the audit touches the page: resizing below would shift it.
57
87
  partial.layoutShift = await frame.evaluate(layoutShift, { nodeLimit: request.nodeLimit });
58
88
  if (!await frame.evaluate(() => !!window.axe)) await frame.addScriptTag({ content: axe });
@@ -61,12 +91,17 @@ try {
61
91
  Object.assign(partial, result);
62
92
  result.nonText = await frame.evaluate(nonTextContrast, { nodeLimit: request.nodeLimit });
63
93
  // The same page is resized: one evaluate per width, no new render.
64
- result.layout = [];
94
+ result.layout = []; result.imageShape = new Map();
65
95
  for (const width of request.overflowWidths) {
66
96
  await page.setViewportSize({ width, height: request.viewport.height });
67
97
  result.layout.push({ width, ...await frame.evaluate(layoutOverflow, { nodeLimit: request.nodeLimit, width }) });
98
+ for (const issue of (await frame.evaluate(imageShape, { nodeLimit: request.nodeLimit })).issues) result.imageShape.set(issue.selector, { ...issue, width });
68
99
  }
69
- await auditRenderStates({ page, frame, result, request, phoneWidth: request.overflowWidths[0], measuredControls });
100
+ const assigned = await turns[index];
101
+ await auditRenderStates({ page, frame, result, request, phoneWidth: request.overflowWidths[0], assigned });
102
+ if (!contentSettled) result.coverage.skipped.push({ reason: "content-still-changing", name: "the page" });
103
+ result.coverage.claimed = [...assigned.triggers, ...assigned.controls].map(item => item.claim);
104
+ result.imageShape = [...result.imageShape.values()];
70
105
  // Last: it narrows #root for good, at the widest viewport, as a pane in a window would be.
71
106
  // A scenario with the main landmark is a whole page, which no pane hosts.
72
107
  if (app.container && !await frame.evaluate(() => !!document.querySelector('main, [role="main"]'))) {
@@ -44,7 +44,7 @@ export const containerKinds = Object.freeze(["components", "patterns"]);
44
44
  /** Attempts for one render, against a dropped preview connection or a slow preview. */
45
45
  export const auditAttempts = 3;
46
46
  /** overlays and controls bound what each render opens and hovers: distinct ones, in document order. */
47
- const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4, overlays: 3, controls: 6 };
47
+ const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4, overlays: 3, controls: 6, contentQuietMs: 500, contentLimitMs: 5000 };
48
48
 
49
49
  /** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
50
50
  export function wcagCriteria(tags) {
@@ -127,6 +127,23 @@ export function nonTextContrastFindings(runs, scenarios) {
127
127
  });
128
128
  }
129
129
 
130
+ const skipReasons = {
131
+ "overlay-did-not-open": "a control with aria-haspopup opened nothing with a dialog, menu or listbox role",
132
+ "overlay-trigger-gone": "a trigger left the page before its turn",
133
+ "overlay-left-open": "an overlay did not close on Escape, so later triggers could not be reached",
134
+ "overlay-timeout": "a trigger could not be clicked in time",
135
+ "overlay-detached": "a trigger left the page or was covered while it was being clicked",
136
+ "overlay-failed": "opening an overlay failed",
137
+ "overlay-cap": "the limit of 3 triggers per render was reached and no other scenario has them",
138
+ "control-gone": "a control left the page before its turn",
139
+ "control-timeout": "a control could not be hovered in time",
140
+ "control-detached": "a control left the page while it was being measured",
141
+ "control-failed": "measuring a control failed",
142
+ "control-cap": "the limit of 6 controls per render was reached and no other scenario has them",
143
+ "content-still-changing": "the page kept changing past 5 s, so what it measured may be mid-change",
144
+ "focus-not-reachable": "a control a keyboard cannot reach (aria-hidden, inert, or tabindex -1 outside a roving widget): hover measured, focus not",
145
+ };
146
+
130
147
  const overflowKinds = {
131
148
  document: { what: "the page scrolls horizontally", fix: "Find the element wider than its container; use fluid widths, min-width: 0 on flex and grid children, and let long text wrap." },
132
149
  viewport: { what: "content reaches past the viewport", fix: "Make the element fluid (%, fr, a --grid-span-N token in a container query), wrap it, or put it in an overflow-x: auto scroller." },
@@ -159,6 +176,45 @@ export function layoutOverflowFindings(runs, scenarios) {
159
176
  });
160
177
  }
161
178
 
179
+ /** One error per scenario and image rendered at a shape other than the one it declares. */
180
+ export function imageShapeFindings(runs, scenarios) {
181
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
182
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
183
+ for (const run of runs) for (const issue of run.imageShape ?? []) {
184
+ const key = JSON.stringify([run.scenario, issue.selector]);
185
+ const group = groups.get(key) ?? { scenario: run.scenario, issue, themes: [], brands: [] };
186
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
187
+ }
188
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, issue, themes, brands }) => ({
189
+ rule: "img-shape", severity: findingSeverity("img-shape"), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", scenario, themes, ...(brands.length ? { brands } : {}), nodes: [issue], rendered: issue.rendered, declared: issue.declared, guidanceUri: "ads://guides/performance",
190
+ message: `Image shape in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${issue.selector} renders at ${issue.rendered} at the ${issue.width} px viewport but declares ${issue.declared}, so it is cropped or stretched. A height attribute beats aspect-ratio: add height: auto. For a deliberate crop in a box of its own, set object-fit and no aspect-ratio.`,
191
+ }));
192
+ }
193
+
194
+ /** What a run measured, and what it skipped and why: per reason, with a few examples. An info finding
195
+ * for each reason, and a review item for a render assigned targets that measured none of them. */
196
+ export function auditCoverage(runs, capped, scenarios) {
197
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), reasons = new Map();
198
+ const claimedNow = new Set(runs.flatMap(run => run.coverage?.claimed ?? []));
199
+ const note = (reason, example) => { const entry = reasons.get(reason) ?? { count: 0, examples: [] }; reasons.set(reason, entry); entry.count++; if (entry.examples.length < limits.nodes) entry.examples.push(example); };
200
+ for (const run of runs) for (const { reason, name } of run.coverage?.skipped ?? []) note(reason, { scenario: run.scenario, theme: run.theme, ...(run.brand ? { brand: run.brand } : {}), name });
201
+ for (const { claim, reason, ...example } of capped) if (!claimedNow.has(claim)) note(reason, example);
202
+ const coverage = { renders: runs.length, overlaysOpened: 0, controlsMeasured: 0, skipped: Object.fromEntries([...reasons].sort(([a], [b]) => a.localeCompare(b))) };
203
+ const empty = [];
204
+ for (const run of runs) if (run.coverage) {
205
+ coverage.overlaysOpened += run.coverage.overlays; coverage.controlsMeasured += run.coverage.controls;
206
+ // A trigger that opened nothing is not a failure to measure: that is a skip, and the rest of the render stands.
207
+ const failed = run.coverage.skipped.filter(item => /^(?:overlay|control)-(?:gone|timeout|detached|failed)$/.test(item.reason)).length;
208
+ if (failed && !run.coverage.overlays && !run.coverage.controls) empty.push(run);
209
+ }
210
+ const findings = [...reasons].map(([reason, { count, examples }]) => ({
211
+ rule: "browser-audit-skipped", severity: findingSeverity("browser-audit-skipped"), file: files.get(examples[0].scenario) ?? examples[0].scenario, line: 1, column: 1, source: "ads", reason, count, examples, guidanceUri: "ads://guides/accessibility",
212
+ message: `The audit skipped ${count} target${count === 1 ? "" : "s"}: ${skipReasons[reason] ?? reason}. ${examples.slice(0, 3).map(item => `"${item.name}" in ${item.scenario} [${item.theme}]`).join(", ")}${count > 3 ? ` and ${count - 3} more` : ""}.`,
213
+ }));
214
+ for (const run of empty) findings.push({ rule: "browser-audit-nothing-measured", severity: findingSeverity("browser-audit-nothing-measured"), file: files.get(run.scenario) ?? run.scenario, line: 1, column: 1, source: "ads", scenario: run.scenario, themes: [run.theme], message: `Nothing the audit tried to open or hover in ${run.scenario} [${run.theme}] could be measured: ${[...new Set(run.coverage.skipped.map(item => item.reason))].join(", ")}.` });
215
+ return { coverage, findings };
216
+ }
217
+
162
218
  /** One error per scenario above the threshold, with its worst score, themes, brands and elements. */
163
219
  export function layoutShiftFindings(runs, scenarios) {
164
220
  const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
@@ -200,7 +256,7 @@ export function auditScenarioSelection(options, changedFiles) {
200
256
  export function auditCheck(audit, extra = {}) {
201
257
  const routed = routeFindings([], audit.findings);
202
258
  return { routed, check: { name: "browser-accessibility-audit", passed: !routed.diagnostics.length, engine: audit.engine, scenarios: audit.scenarios, themes: audit.themes, ...(audit.brands ? { brands: audit.brands } : {}),
203
- renders: audit.runs, ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
259
+ renders: audit.runs, ...(audit.coverage ? { coverage: audit.coverage } : {}), ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
204
260
  }
205
261
 
206
262
  function projectPlaywright(root) {
@@ -245,10 +301,10 @@ async function warmScenariosApart(host, ids, signal) {
245
301
 
246
302
  /** One browser process over the given renders. Its report grows as they finish, so a worker that
247
303
  * dies keeps what it finished. A browser that is not installed stops the audit. */
248
- async function runAuditWorker({ root, temporary, playwright, settings, apps, signal }) {
304
+ async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed }) {
249
305
  const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
250
306
  rmSync(report, { force: true });
251
- writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
307
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, contentQuietMs: limits.contentQuietMs, contentLimitMs: limits.contentLimitMs, claimed, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
252
308
  const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
253
309
  let cause;
254
310
  try {
@@ -259,10 +315,10 @@ async function runAuditWorker({ root, temporary, playwright, settings, apps, sig
259
315
  if (signal.aborted || error.code === "ADS_AUDIT_UNAVAILABLE") throw error;
260
316
  cause = clipCause(error.message);
261
317
  }
262
- if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], cause: cause ?? "Accessibility audit produced no bounded report." };
318
+ if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], capped: [], cause: cause ?? "Accessibility audit produced no bounded report." };
263
319
  const value = JSON.parse(readFileSync(report, "utf8"));
264
- if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
265
- return { runs: value.runs, cause };
320
+ if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], capped: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
321
+ return { runs: value.runs, capped: value.capped ?? [], cause };
266
322
  }
267
323
 
268
324
  /** A scenario that could not be audited is an error naming it and its last cause, never a pass. */
@@ -320,7 +376,7 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
320
376
  const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
321
377
  const floating = floatingScenarios(options, scenarios);
322
378
  const wanted = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => ({ scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, ...(theme === themes[0] && containerKinds.includes(scenario.kind) && !floating.has(scenario.id) ? { container: containerWidth } : {}) }))));
323
- const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }]));
379
+ const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }])), capped = new Map();
324
380
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${wanted.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
325
381
  for (let attempt = 1; attempt <= auditAttempts; attempt++) {
326
382
  const pending = [...renders.values()].filter(render => !render.result);
@@ -338,7 +394,8 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
338
394
  if (app.brand) url.searchParams.set("brand", app.brand);
339
395
  return { ...app, url: url.href };
340
396
  });
341
- const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal }) : { runs: [] };
397
+ const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed: [...renders.values()].flatMap(render => render.result?.coverage?.claimed ?? []) }) : { runs: [], capped: [] };
398
+ for (const item of reached.capped ?? []) capped.set(item.claim, item);
342
399
  for (const run of reached.runs) {
343
400
  const render = renders.get(renderKey(run));
344
401
  if (!render) continue;
@@ -354,9 +411,10 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
354
411
  }
355
412
  const all = [...renders.values()], runs = all.map(render => render.result ?? render.partial).filter(Boolean);
356
413
  const retries = all.filter(render => render.result && render.attempts > 1).map(({ app, attempts, causes }) => ({ scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), attempts, causes }));
357
- const findings = [...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
414
+ const { coverage, findings: coverageItems } = auditCoverage(all.map(render => render.result).filter(Boolean), [...capped.values()], scenarios);
415
+ const findings = [...coverageItems, ...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...imageShapeFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
358
416
  const shifts = runs.filter(run => run.layoutShift).sort((a, b) => b.layoutShift.value - a.layoutShift.value);
359
- return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, overlaysOpened: runs.reduce((sum, run) => sum + (run.overlays ?? 0), 0), controlsMeasured: runs.reduce((sum, run) => sum + (run.controls ?? 0), 0), findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
417
+ return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, overlaysOpened: coverage.overlaysOpened, controlsMeasured: coverage.controlsMeasured, coverage, findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
360
418
  } finally {
361
419
  try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
362
420
  }
package/dist/check.mjs CHANGED
@@ -40,6 +40,7 @@ import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
40
40
  import { inspectUsage } from "./usage.mjs";
41
41
  import { controlPaddingAdvisories } from "./control-padding.mjs";
42
42
  import { createComponentContrast } from "./component-contrast.mjs";
43
+ import { createFontRules } from "./font-rules.mjs";
43
44
  import { createLayoutWidths, globMatcher } from "./layout-widths.mjs";
44
45
  import { imageAttributeFindings } from "./image-attributes.mjs";
45
46
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
@@ -113,6 +114,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
113
114
  for (const glob of config.layout.widthTokens) if (!tokenInventory.tokens.some(token => globMatcher([glob])(token.name))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.widthTokens entry ${glob} matches no declared token. Remove it or declare the token.` });
114
115
  for (const glob of config.layout.fixedWidthUnits) if (!units.units.some(unit => globMatcher([glob])(unit.id) || unit.files.some(file => globMatcher([glob])(file)))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.fixedWidthUnits entry ${glob} matches no unit or owned file. Remove it or correct the path.` });
115
116
  const ownerFixedWidths = [];
117
+ const fontRules = createFontRules(options, tokenInventory.tokens);
116
118
  function checkRegistrations(file,css,offset={line:1}){
117
119
  css.walkAtRules(/^property$/i,rule=>{
118
120
  const line=offset.line+(rule.source?.start.line??1)-1;
@@ -148,6 +150,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
148
150
  catch (error) { report(file, "css-syntax", error.reason ?? error.message, offset.line + (error.line ?? 1) - 1); return; }
149
151
  layers.collectComponentStyles(file, css);
150
152
  layerStyles.push({ file, css, offset });
153
+ if (foundation || !isDevelopmentFile(file, options)) fontRules.collect(css, file, offset);
151
154
  checkRegistrations(file,css,offset);
152
155
  if (!foundation && !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) componentContrast.collect(path.relative(root, file).replaceAll("\\", "/"), css, offset);
153
156
  if (!foundation && (isInside(path.join(dsRoot, "composition"), file) || !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)))) {
@@ -383,7 +386,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
383
386
  }
384
387
  inspectDesignAliases(layerStyles,options,report);
385
388
  for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
386
- advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths));
389
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths), ...fontRules.findings());
387
390
  // Errors block by class; bounded clients see review items before informational limits.
388
391
  const routed=routeFindings(diagnostics,advisories);
389
392
  const uniqueDiagnostics=[...new Map(routed.diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];