@reqvire-org/ads 0.3.51 → 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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/dist/assets.mjs +15 -1
  3. package/dist/browser-audit/axe-run.mjs +17 -0
  4. package/dist/browser-audit/first-render.mjs +22 -0
  5. package/dist/browser-audit/image-shape.mjs +36 -0
  6. package/dist/browser-audit/layout-overflow.mjs +11 -5
  7. package/dist/browser-audit/non-text-contrast.mjs +12 -7
  8. package/dist/browser-audit/render-states.mjs +208 -0
  9. package/dist/browser-audit/worker.mjs +60 -22
  10. package/dist/browser-audit.mjs +72 -12
  11. package/dist/bun-compiler.mjs +9 -1
  12. package/dist/check.mjs +4 -1
  13. package/dist/cli.mjs +9 -4
  14. package/dist/config.mjs +3 -1
  15. package/dist/finding-rules.mjs +14 -1
  16. package/dist/font-rules.mjs +103 -0
  17. package/dist/fonts-generated.mjs +30 -12
  18. package/dist/layout-widths.mjs +17 -8
  19. package/dist/mcp/preview-watch.mjs +2 -2
  20. package/dist/mcp/preview-widget.bundle.js +50 -47
  21. package/dist/mcp/project-widget.bundle.js +45 -42
  22. package/dist/mcp/server.mjs +4 -4
  23. package/dist/mcp/widget.bundle.js +49 -46
  24. package/dist/preview-resources.mjs +4 -1
  25. package/dist/scenarios-compiler.mjs +2 -2
  26. package/dist/showcase/client.bundle.js +27 -27
  27. package/dist/skills/ads-break-ui/references/design-data.md +8 -1
  28. package/dist/skills/ads-designer/SKILL.md +5 -3
  29. package/dist/skills/ads-designer/references/branding.md +2 -2
  30. package/dist/skills/ads-designer/references/design-data.md +8 -1
  31. package/dist/skills/ads-designer/references/performance.md +54 -4
  32. package/dist/skills/ads-import/references/design-data.md +8 -1
  33. package/dist/skills/ads-motion/references/design-data.md +8 -1
  34. package/dist/skills/ads-port/references/design-data.md +8 -1
  35. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +1 -1
  36. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +2 -2
  37. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
  38. package/docs/ARCHITECTURE.md +26 -2
  39. package/docs/CHANGELOG.md +92 -12
  40. package/docs/GUIDE.md +65 -9
  41. package/package.json +7 -7
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
@@ -0,0 +1,17 @@
1
+ /**
2
+ * One axe-core run inside the scenario document, cut down to what a report keeps. `include` is the
3
+ * selector to audit, `rules` narrows it to named rules. It must stay self-contained: Playwright
4
+ * serializes the function into the page.
5
+ */
6
+ export async function axeRun({ tags, nodeLimit, include = "#root", rules }) {
7
+ // Asking for a group is what keeps its nodes: axe cuts every other group to one.
8
+ const runOnly = rules ? { type: "rule", values: rules } : { type: "tag", values: tags };
9
+ const outcome = await window.axe.run({ include: [[include]], exclude: [["#ads-preview-status"]] }, { runOnly, resultTypes: ["violations", "incomplete"], elementRef: false, ancestry: false });
10
+ const clip = (text, size) => typeof text === "string" ? text.replace(/\s+/g, " ").trim().slice(0, size) : "";
11
+ const selector = node => clip(node.target.flat().join(" "), 300), html = node => clip(node.html, 200);
12
+ const group = item => ({ id: item.id, impact: item.impact, tags: item.tags, help: clip(item.help, 300), helpUrl: clip(item.helpUrl, 300), nodeCount: item.nodes.length });
13
+ // axe's own key for why it could not decide, such as bgGradient or pseudoContent.
14
+ const reason = node => { const check = [...node.any, ...node.all, ...node.none].find(item => item.data?.messageKey) ?? [...node.any, ...node.all, ...node.none][0]; return clip(check?.data?.messageKey ?? check?.id ?? "", 80); };
15
+ return { violations: outcome.violations.map(violation => ({ ...group(violation), nodes: violation.nodes.slice(0, nodeLimit).map(node => ({ selector: selector(node), html: html(node), summary: clip(node.failureSummary, 500) })) })),
16
+ incomplete: outcome.incomplete.map(item => ({ ...group(item), nodes: item.nodes.slice(0, nodeLimit).map(node => ({ selector: selector(node), html: html(node), reason: reason(node) })) })) };
17
+ }
@@ -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
+ }
@@ -11,8 +11,8 @@
11
11
  * a small part's limit. A row of buttons that is simply too long for a pane is not reported.
12
12
  * - "clipped": an element with overflow-x hidden or clip whose content is more than 4 px wider
13
13
  * than its box, so content is cut off (a small negative margin cuts nothing).
14
- * Intended scrollers (overflow-x auto or scroll) and their content, text-overflow: ellipsis,
15
- * carousels (aria-roledescription="carousel"),
14
+ * Intended scrollers (overflow-x auto or scroll, other than the outermost window-tall one) and their content, text-overflow: ellipsis,
15
+ * carousels (aria-roledescription="carousel"), pannable widgets (role="application"),
16
16
  * native text fields, visually hidden content (a box of 1 px or less, clip or clip-path) and
17
17
  * fixed-position layers are exempt.
18
18
  *
@@ -68,8 +68,14 @@ export async function layoutOverflow({ nodeLimit, width: expected, container, sm
68
68
  return element.getBoundingClientRect().width > smallPart && element.checkVisibility() && (wide("width") || wide("min-width") || wide("flex-basis") && getComputedStyle(element).flexShrink === "0");
69
69
  }
70
70
  const forced = element => !container || setWide(element) || [...element.querySelectorAll("*")].some(inner => !excluded(inner.parentElement) && setWide(inner));
71
- // In the narrowed render, a box as tall as the window is the project's preview frame, not the scenario's own scroller or clip.
72
- const frame = element => !!container && Math.abs(element.getBoundingClientRect().height - window.innerHeight) <= 1;
71
+ // The outermost box as tall as the window is the page or the project's preview frame, not an
72
+ // intended scroller or clip: overflow-y: auto computes overflow-x to auto, and a page that scrolls
73
+ // sideways is what this check is for. A scroller inside it is a real one.
74
+ const frame = element => {
75
+ if (Math.abs(element.getBoundingClientRect().height - window.innerHeight) > 1) return false;
76
+ for (let node = element.parentElement; node && node !== root; node = node.parentElement) if (/^(?:auto|scroll)$/.test(getComputedStyle(node).overflowX)) return false;
77
+ return true;
78
+ };
73
79
  /** Whether an element is inside an intended scroller, a fixed layer or hidden content. */
74
80
  function excluded(element) {
75
81
  if (!element || element === root) return false;
@@ -90,7 +96,7 @@ export async function layoutOverflow({ nodeLimit, width: expected, container, sm
90
96
  const contained = () => { for (let node = element.parentElement; node && node !== root; node = node.parentElement) if (/^(?:hidden|clip)$/.test(getComputedStyle(node).overflowX) && !frame(node)) return true; return false; };
91
97
  const parent = element.parentElement === root ? pane : element.parentElement.getBoundingClientRect();
92
98
  if ((box.right > pane.right + 1 || box.left < pane.left - 1) && !(parent.right > pane.right + 1 || parent.left < pane.left - 1) && !contained() && forced(element)) report(edge, element, { overflow: Math.round(Math.max(box.right - pane.right, pane.left - box.left)) });
93
- if (/^(?:hidden|clip)$/.test(style.overflowX) && element.scrollWidth > element.clientWidth + 4 && style.textOverflow !== "ellipsis" && !element.closest('[aria-roledescription="carousel"]') && !/^(?:input|textarea|select)$/.test(element.localName) && style.clip === "auto" && style.clipPath === "none" && forced(element))
99
+ if (/^(?:hidden|clip)$/.test(style.overflowX) && element.scrollWidth > element.clientWidth + 4 && style.textOverflow !== "ellipsis" && !element.closest('[aria-roledescription="carousel"], [role="application"]') && !/^(?:input|textarea|select)$/.test(element.localName) && style.clip === "auto" && style.clipPath === "none" && forced(element))
94
100
  report("clipped", element, { overflow: element.scrollWidth - element.clientWidth });
95
101
  }
96
102
  return { issues, counts };
@@ -10,14 +10,16 @@
10
10
  * surrounding background ("border"). A button, link or tab with text or an icon is exempt: WCAG
11
11
  * 1.4.11 needs no boundary when that content identifies the control.
12
12
  * An icon-only control (an svg and no text) needs its icon's paint at 3:1 against the control's
13
- * effective background ("icon").
13
+ * effective background ("icon"). A busy control (aria-busy="true") is checked even when disabled,
14
+ * and its icon even when it has text: the spinner is the state it reports.
14
15
  * A control whose background contrasts 3:1 with its surroundings is identified by its background;
15
16
  * an icon-only one is still checked against that background. Disabled controls are exempt.
16
17
  * Browser-drawn native checkboxes, radios and ranges and backgrounds under an image or gradient
17
18
  * are skipped. Colors are read through a 1×1 canvas, so every CSS color syntax resolves to sRGB.
19
+ * `scope` measures one element and what is in it instead of #root.
18
20
  */
19
- export function nonTextContrast({ nodeLimit }) {
20
- const root = document.querySelector("#root");
21
+ export function nonTextContrast({ nodeLimit, scope }) {
22
+ const root = document.querySelector(scope ?? "#root");
21
23
  if (!root) return { issues: [], counts: {} };
22
24
  const canvas = document.createElement("canvas"); canvas.width = canvas.height = 1;
23
25
  const context = canvas.getContext("2d", { willReadFrequently: true }), cache = new Map();
@@ -48,12 +50,15 @@ export function nonTextContrast({ nodeLimit }) {
48
50
  const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
49
51
  parts.unshift(`${node.localName}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(node) + 1})` : ""}`);
50
52
  }
51
- return ["#root", ...parts].join(" > ");
53
+ return [scope ? root.localName : "#root", ...parts].join(" > ");
52
54
  };
53
55
  const native = /^(?:checkbox|radio|range|color|file|hidden)$/;
54
56
  const issues = [], counts = { border: 0, icon: 0 };
55
- for (const element of root.querySelectorAll('button, input, select, textarea, a[href], [role="switch"], [role="checkbox"], [role="radio"], [role="slider"], [role="tab"]')) {
56
- if (element.closest("#ads-preview-status") || element.matches(":disabled") || element.closest('[aria-disabled="true"], [inert]')) continue;
57
+ const controls = 'button, input, select, textarea, a[href], [role="switch"], [role="checkbox"], [role="radio"], [role="slider"], [role="tab"]';
58
+ for (const element of [...(scope && root.matches(controls) ? [root] : []), ...root.querySelectorAll(controls)]) {
59
+ // A busy control is disabled while it works, and its spinner still has to be seen.
60
+ const busy = element.getAttribute("aria-busy") === "true";
61
+ if (element.closest("#ads-preview-status") || !busy && element.matches(":disabled") || !busy && element.closest('[aria-disabled="true"]') || element.closest("[inert]")) continue;
57
62
  if (!element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
58
63
  const box = element.getBoundingClientRect();
59
64
  if (box.width < 1 || box.height < 1) continue;
@@ -72,7 +77,7 @@ export function nonTextContrast({ nodeLimit }) {
72
77
  if (best[0] + 1e-9 < 3) report("border", best[0], over(best[1], around), around);
73
78
  }
74
79
  }
75
- const icon = !text(element) && [...element.querySelectorAll("svg")].find(svg => svg.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }));
80
+ const icon = (busy || !text(element)) && [...element.querySelectorAll("svg")].find(svg => svg.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }));
76
81
  if (icon) {
77
82
  const shape = [...icon.querySelectorAll("path, circle, rect, ellipse, line, polyline, polygon, use, text")].find(node => { const paint = getComputedStyle(node); return paint.stroke !== "none" && rgba(paint.stroke)[3] > 0 || paint.fill !== "none" && !paint.fill.startsWith("url(") && rgba(paint.fill)[3] > 0; });
78
83
  if (shape) {
@@ -0,0 +1,208 @@
1
+ import { axeRun } from "./axe-run.mjs";
2
+ import { nonTextContrast } from "./non-text-contrast.mjs";
3
+
4
+ /**
5
+ * Renders what a scenario shows only after someone acts on it, and measures it with the same checks.
6
+ *
7
+ * Overlays: each control marked aria-haspopup that this render was assigned is clicked, and what
8
+ * opens is audited by axe and non-text contrast, then held to the phone viewport. Fixed layers are
9
+ * exempt from the overflow check of the page, so this is the only place their width is measured. An
10
+ * overlay a scenario renders open is measured the same way. Accessibility trees are read through
11
+ * ARIA, not names: a trigger with no aria-haspopup is not found, and its scenario can render it open.
12
+ *
13
+ * Hover and keyboard focus: each control this render was assigned is hovered with the real mouse and
14
+ * focused as the keyboard would, for contrast only: axe color-contrast when a quick reading looks
15
+ * wrong, non-text contrast in that state, and the focus outline against what is around it. What
16
+ * already fails at rest is not repeated.
17
+ *
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.
21
+ */
22
+ const overlays = '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], dialog[open], [popover]:popover-open';
23
+
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 = [];
27
+ for (const element of document.querySelector("#root").querySelectorAll(selector)) {
28
+ const box = element.getBoundingClientRect();
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;
30
+ const name = (element.getAttribute("aria-label") ?? element.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60) || element.localName;
31
+ const key = `${signature.map(item => element.getAttribute(item) ?? "").join("|")}|${element.localName}|${trigger ? name : getComputedStyle(element.parentElement).backgroundColor}`;
32
+ if (seen.has(key)) continue;
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 });
37
+ }
38
+ return targets;
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) });
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); }));
45
+
46
+ /** A quick reading of a hovered control's text against its background, so axe, which sets up the whole
47
+ * document on every run, only confirms what looks wrong. Unreadable backgrounds go to axe too. */
48
+ function hoverTextSuspect(selector) {
49
+ const element = document.querySelector(selector);
50
+ const canvas = document.createElement("canvas"); canvas.width = canvas.height = 1;
51
+ const context = canvas.getContext("2d", { willReadFrequently: true });
52
+ const rgba = value => { context.clearRect(0, 0, 1, 1); context.fillStyle = "#000"; context.fillStyle = value; context.fillRect(0, 0, 1, 1); const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data; return [r, g, b, a / 255]; };
53
+ const over = (top, bottom) => [0, 1, 2].map(index => top[index] * top[3] + bottom[index] * (1 - top[3])).concat(1);
54
+ const lum = ([r, g, b]) => { const channel = value => { value /= 255; return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; }; return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); };
55
+ const behind = node => { if (!node) return [255, 255, 255, 1]; const style = getComputedStyle(node); if (style.backgroundImage !== "none") return null; const below = behind(node.parentElement); return below && over(rgba(style.backgroundColor), below); };
56
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
57
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
58
+ if (!node.data.trim() || !node.parentElement.checkVisibility()) continue;
59
+ const back = behind(node.parentElement);
60
+ if (!back) return true;
61
+ const [a, b] = [lum(over(rgba(getComputedStyle(node.parentElement).color), back)), lum(back)];
62
+ if ((Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05) < 4.5) return true;
63
+ }
64
+ return false;
65
+ }
66
+
67
+ /** Marks the overlay that is open and was not known before; true when there is one. */
68
+ function markOpened({ overlays, known }) {
69
+ for (const element of document.querySelectorAll(overlays)) {
70
+ if (element.closest("#ads-preview-status") || known && element.hasAttribute("data-ads-audit-known") || !element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
71
+ const box = element.getBoundingClientRect();
72
+ if (box.width < 1 || box.height < 1) continue;
73
+ element.setAttribute("data-ads-audit-overlay", "");
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+ function overlayPastViewport() {
79
+ const element = document.querySelector("[data-ads-audit-overlay]");
80
+ if (!element) return null;
81
+ const box = element.getBoundingClientRect(), width = document.documentElement.clientWidth, past = Math.round(Math.max(box.right - width, -box.left));
82
+ return past > 1 ? { overflow: past, html: element.outerHTML.replace(/\s+/g, " ").slice(0, 200) } : null;
83
+ }
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() {
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
+ }
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); }));
97
+ if (document.activeElement !== element || !element.matches(":focus-visible")) return null;
98
+ const style = getComputedStyle(element);
99
+ // A ring drawn with box-shadow is not read, so an outline beside one is not taken for the only indicator.
100
+ if (style.outlineStyle === "none" || parseFloat(style.outlineWidth) <= 0 || style.boxShadow !== "none") return null;
101
+ const canvas = document.createElement("canvas"); canvas.width = canvas.height = 1;
102
+ const context = canvas.getContext("2d", { willReadFrequently: true });
103
+ const rgba = value => { context.clearRect(0, 0, 1, 1); context.fillStyle = "#000"; context.fillStyle = value; context.fillRect(0, 0, 1, 1); const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data; return [r, g, b, a / 255]; };
104
+ const over = (top, bottom) => [0, 1, 2].map(index => top[index] * top[3] + bottom[index] * (1 - top[3])).concat(1);
105
+ const lum = ([r, g, b]) => { const channel = value => { value /= 255; return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; }; return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); };
106
+ const around = element => { if (!element) return [255, 255, 255, 1]; const parent = getComputedStyle(element); if (parent.backgroundImage !== "none") return null; const below = around(element.parentElement); return below && over(rgba(parent.backgroundColor), below); };
107
+ const back = around(element.parentElement);
108
+ if (!back) return null;
109
+ const color = over(rgba(style.outlineColor), back), [a, b] = [lum(color), lum(back)], ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
110
+ const hex = value => `#${value.slice(0, 3).map(part => Math.round(part).toString(16).padStart(2, "0")).join("")}`;
111
+ return ratio + 1e-9 < 3 ? { ratio: Math.round(ratio * 100) / 100, foreground: hex(color), background: hex(back), html: element.outerHTML.replace(/\s+/g, " ").slice(0, 200) } : null;
112
+ }
113
+
114
+ const unmarked = text => text?.replace(/\[?data-ads-audit-[a-z.]+(?:="[^"]*")?\]?/g, "").replace(/\s+>/g, " >").trim();
115
+ const named = (nodes, label) => nodes.map(node => ({ ...node, selector: `${label}: ${unmarked(node.selector)}`.slice(0, 300), ...(node.html ? { html: unmarked(node.html) } : {}) }));
116
+ const labelled = (groups, label) => groups.map(group => ({ ...group, nodes: named(group.nodes, label) }));
117
+
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 });
126
+ const isClosed = () => frame.waitForFunction(() => { const element = document.querySelector("[data-ads-audit-overlay]"); return !element || !element.checkVisibility(); }, undefined, { timeout: 1000 }).then(() => true, () => false);
127
+ const unmark = () => frame.evaluate(() => { for (const element of document.querySelectorAll("[data-ads-audit-overlay]")) element.removeAttribute("data-ads-audit-overlay"); });
128
+ const measureOverlay = async (label, reopen) => {
129
+ await frame.evaluate(settle);
130
+ const found = await frame.evaluate(axeRun, { tags, nodeLimit, include: "[data-ads-audit-overlay]" });
131
+ result.violations.push(...labelled(found.violations, label)); result.incomplete.push(...labelled(found.incomplete, label));
132
+ const nonText = await frame.evaluate(nonTextContrast, { nodeLimit, scope: "[data-ads-audit-overlay]" });
133
+ result.nonText.issues.push(...named(nonText.issues, label));
134
+ for (const [kind, count] of Object.entries(nonText.counts)) result.nonText.counts[kind] = (result.nonText.counts[kind] ?? 0) + count;
135
+ await page.setViewportSize({ width: phoneWidth, height: desktop.height });
136
+ await frame.evaluate(settle);
137
+ let past = await frame.evaluate(overlayPastViewport);
138
+ // A menu is placed when it opens, so one opened on the desktop may be stale: open it here to be sure.
139
+ if (past && reopen) {
140
+ await page.keyboard.press("Escape");
141
+ if (await isClosed()) { await unmark(); past = await reopen() ? await frame.evaluate(settle).then(() => frame.evaluate(overlayPastViewport)) : null; }
142
+ }
143
+ if (past) result.layout.push({ width: phoneWidth, issues: [{ kind: "viewport", selector: label, ...past }], counts: { viewport: 1 } });
144
+ await page.setViewportSize(desktop);
145
+ await frame.evaluate(settle);
146
+ coverage.overlays++;
147
+ };
148
+ // Already open: nothing to click, and nothing to close.
149
+ if (await frame.evaluate(markOpened, { overlays, known: false })) {
150
+ await measureOverlay("open overlay");
151
+ await unmark();
152
+ }
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()) {
156
+ try {
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);
159
+ const open = async () => {
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;
167
+ };
168
+ if (!await open()) { skip("overlay-did-not-open", name); continue; }
169
+ await measureOverlay(`open overlay "${name}"`, open);
170
+ await page.keyboard.press("Escape");
171
+ const closed = await isClosed();
172
+ await unmark();
173
+ // One that stays open covers the page, so the next trigger cannot be reached.
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); }
176
+ }
177
+ // What already fails at rest: axe names elements the same way each run, and non-text findings are the same colors.
178
+ const pair = issue => JSON.stringify([issue.kind, issue.foreground, issue.background]);
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))]);
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()) {
183
+ const target = `[data-ads-audit-control="${index}"]`;
184
+ try {
185
+ await frame.locator(target).hover({ timeout: 3000, force: true });
186
+ await frame.evaluate(target => document.querySelector(target).setAttribute("data-ads-audit-state", ""), target);
187
+ await frame.evaluate(settle);
188
+ if (await frame.evaluate(hoverTextSuspect, target)) {
189
+ const found = await frame.evaluate(axeRun, { tags, nodeLimit, include: target, rules: ["color-contrast"] });
190
+ const fresh = group => ({ ...group, nodes: group.nodes.filter(node => !rest.has(node.selector)) });
191
+ result.violations.push(...labelled(found.violations.map(fresh).filter(group => group.nodes.length), "hover"));
192
+ }
193
+ const nonText = await frame.evaluate(nonTextContrast, { nodeLimit, scope: target });
194
+ const issues = nonText.issues.filter(issue => !rest.has(pair(issue)));
195
+ result.nonText.issues.push(...named(issues, "hover"));
196
+ for (const issue of issues) result.nonText.counts[issue.kind] = (result.nonText.counts[issue.kind] ?? 0) + 1;
197
+ const outline = await frame.evaluate(focusOutline);
198
+ if (outline?.unreachable) skip("focus-not-reachable", name);
199
+ else if (outline) {
200
+ result.nonText.issues.push({ kind: "focus", selector: `focus: ${await frame.locator(target).evaluate(element => element.localName)}`, ...outline });
201
+ result.nonText.counts.focus = (result.nonText.counts.focus ?? 0) + 1;
202
+ }
203
+ await frame.evaluate(target => { const element = document.querySelector(target); element.removeAttribute("data-ads-audit-state"); element.blur(); }, target);
204
+ coverage.controls++;
205
+ } catch (error) { skip(`control-${failure(error)}`, name); }
206
+ }
207
+ await page.mouse.move(desktop.width - 1, desktop.height - 1);
208
+ }
@@ -2,20 +2,23 @@ import { readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { openPreviewScenario } from "../verification/browser.mjs";
5
- import { firstRender } from "./first-render.mjs";
5
+ import { axeRun } from "./axe-run.mjs";
6
+ import { contentQuiet, firstRender } from "./first-render.mjs";
6
7
  import { nonTextContrast } from "./non-text-contrast.mjs";
7
8
  import { layoutOverflow } from "./layout-overflow.mjs";
8
9
  import { layoutShift } from "./layout-shift.mjs";
10
+ import { imageShape } from "./image-shape.mjs";
11
+ import { auditRenderStates, listTargets } from "./render-states.mjs";
9
12
 
10
13
  // Runs only as an owned child, using the receiving project's browser dependency.
11
14
  const request = JSON.parse(readFileSync(process.argv[2], "utf8"));
12
15
  const playwright = createRequire(import.meta.url)(request.playwright);
13
16
  const axe = readFileSync(request.axe, "utf8");
14
- const runs = [];
17
+ const runs = [], capped = new Map(), claimed = new Set(request.claimed ?? []);
15
18
  /** Atomic, so a worker that dies leaves the renders it finished readable. */
16
19
  function publish() {
17
20
  const file = path.join(request.output, "report.json"), temporary = `${file}.tmp`;
18
- writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, runId: request.runId, runs }));
21
+ writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, runId: request.runId, runs, capped: [...capped.values()] }));
19
22
  renameSync(temporary, file);
20
23
  }
21
24
  let browser;
@@ -26,57 +29,92 @@ try {
26
29
  const apps = request.apps.filter(app => app.theme === theme);
27
30
  // The audit injects its own script; bypassCSP keeps project CSP from blocking it.
28
31
  const context = await browser.newContext({ viewport: request.viewport, deviceScaleFactor: 1, colorScheme: apps[0].scheme, bypassCSP: true, reducedMotion: "reduce" });
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) })); });
29
43
  try {
30
44
  // A bounded number of pages render at once; results keep request order.
31
45
  const results = [];
32
46
  let next = 0;
33
- 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(); } }
34
48
  await Promise.all(Array.from({ length: Math.min(apps.length, request.concurrency ?? 1) }, lane));
35
49
  // One render failing is that render's result; what it found before failing is kept.
36
- async function attempt(app) {
50
+ async function attempt(app, index) {
37
51
  const partial = {};
38
- try { return await audit(app, partial); }
52
+ try { return await audit(app, partial, index); }
39
53
  catch (error) {
54
+ lists[index].resolve({ triggers: [], controls: [] });
40
55
  const code = error.failure?.code;
41
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 };
42
57
  }
43
58
  }
44
- async function audit(app, partial) {
59
+ async function audit(app, partial, index) {
45
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;
46
77
  try {
47
- const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
78
+ frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
48
79
  await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
49
80
  if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
81
+ // Nothing is hovered at rest: the mouse starts over whatever sits at the page's corner.
82
+ await page.mouse.move(request.viewport.width - 1, request.viewport.height - 1);
50
83
  await frame.evaluate(firstRender);
84
+ const contentSettled = await settled();
85
+ lists[index].resolve(await listTargets(frame));
51
86
  // Before the audit touches the page: resizing below would shift it.
52
87
  partial.layoutShift = await frame.evaluate(layoutShift, { nodeLimit: request.nodeLimit });
53
88
  if (!await frame.evaluate(() => !!window.axe)) await frame.addScriptTag({ content: axe });
54
- const result = await frame.evaluate(async ({ tags, nodeLimit }) => {
55
- // Scenario content only: the preview status aside and document-level chrome are ADS-owned.
56
- // Asking for a group is what keeps its nodes: axe cuts every other group to one.
57
- const outcome = await window.axe.run({ include: [["#root"]], exclude: [["#ads-preview-status"]] }, { runOnly: { type: "tag", values: tags }, resultTypes: ["violations", "incomplete"], elementRef: false, ancestry: false });
58
- const clip = (text, size) => typeof text === "string" ? text.replace(/\s+/g, " ").trim().slice(0, size) : "";
59
- const selector = node => clip(node.target.flat().join(" "), 300), html = node => clip(node.html, 200);
60
- const group = item => ({ id: item.id, impact: item.impact, tags: item.tags, help: clip(item.help, 300), helpUrl: clip(item.helpUrl, 300), nodeCount: item.nodes.length });
61
- // axe's own key for why it could not decide, such as bgGradient or pseudoContent.
62
- const reason = node => { const check = [...node.any, ...node.all, ...node.none].find(item => item.data?.messageKey) ?? [...node.any, ...node.all, ...node.none][0]; return clip(check?.data?.messageKey ?? check?.id ?? "", 80); };
63
- return { violations: outcome.violations.map(violation => ({ ...group(violation), nodes: violation.nodes.slice(0, nodeLimit).map(node => ({ selector: selector(node), html: html(node), summary: clip(node.failureSummary, 500) })) })),
64
- incomplete: outcome.incomplete.map(item => ({ ...group(item), nodes: item.nodes.slice(0, nodeLimit).map(node => ({ selector: selector(node), html: html(node), reason: reason(node) })) })) };
65
- }, { tags: request.tags, nodeLimit: request.nodeLimit });
89
+ const result = await frame.evaluate(axeRun, { tags: request.tags, nodeLimit: request.nodeLimit });
66
90
  result.layoutShift = partial.layoutShift;
67
91
  Object.assign(partial, result);
68
92
  result.nonText = await frame.evaluate(nonTextContrast, { nodeLimit: request.nodeLimit });
69
93
  // The same page is resized: one evaluate per width, no new render.
70
- result.layout = [];
94
+ result.layout = []; result.imageShape = new Map();
71
95
  for (const width of request.overflowWidths) {
72
96
  await page.setViewportSize({ width, height: request.viewport.height });
73
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 });
74
99
  }
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()];
75
105
  // Last: it narrows #root for good, at the widest viewport, as a pane in a window would be.
76
106
  // A scenario with the main landmark is a whole page, which no pane hosts.
77
107
  if (app.container && !await frame.evaluate(() => !!document.querySelector('main, [role="main"]'))) {
78
108
  await frame.addStyleTag({ content: `#root { inline-size: ${app.container}px; }` });
79
- result.layout.push({ width: app.container, container: true, ...await frame.evaluate(layoutOverflow, { nodeLimit: request.nodeLimit, width: request.overflowWidths.at(-1), container: app.container, smallPart: request.smallPart }) });
109
+ const options = { nodeLimit: request.nodeLimit, container: app.container, smallPart: request.smallPart };
110
+ let narrowed = await frame.evaluate(layoutOverflow, { ...options, width: request.overflowWidths.at(-1) });
111
+ // What clears at the phone viewport folds on a media query, as full-width site chrome does.
112
+ if (narrowed.issues.length) {
113
+ await page.setViewportSize({ width: request.overflowWidths[0], height: request.viewport.height });
114
+ const folded = await frame.evaluate(layoutOverflow, { ...options, width: request.overflowWidths[0] });
115
+ if (!folded.issues.length) narrowed = folded;
116
+ }
117
+ result.layout.push({ width: app.container, container: true, ...narrowed });
80
118
  }
81
119
  if (await frame.locator("html").getAttribute("data-ads-preview-state") !== "ready") throw new Error(`Scenario ${app.scenario} stopped being ready during the audit.`);
82
120
  return { scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), ...result };