@reqvire-org/ads 0.3.50 → 0.3.52

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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/browser-audit/axe-run.mjs +17 -0
  3. package/dist/browser-audit/first-render.mjs +18 -0
  4. package/dist/browser-audit/layout-overflow.mjs +88 -41
  5. package/dist/browser-audit/non-text-contrast.mjs +12 -7
  6. package/dist/browser-audit/render-states.mjs +182 -0
  7. package/dist/browser-audit/worker.mjs +23 -12
  8. package/dist/browser-audit.mjs +56 -13
  9. package/dist/bun-compiler.mjs +9 -1
  10. package/dist/capture/worker.mjs +2 -5
  11. package/dist/check.mjs +5 -3
  12. package/dist/cli.mjs +11 -5
  13. package/dist/config.mjs +2 -2
  14. package/dist/finding-rules.mjs +11 -0
  15. package/dist/layout-widths.mjs +132 -79
  16. package/dist/mcp/preview-watch.mjs +2 -2
  17. package/dist/mcp/server.mjs +2 -2
  18. package/dist/preview-resources.mjs +4 -1
  19. package/dist/scenarios-compiler.mjs +2 -2
  20. package/dist/skills/ads-break-ui/SKILL.md +2 -1
  21. package/dist/skills/ads-break-ui/references/design-data.md +34 -14
  22. package/dist/skills/ads-break-ui/references/validation.md +1 -1
  23. package/dist/skills/ads-designer/SKILL.md +6 -4
  24. package/dist/skills/ads-designer/references/design-data.md +34 -14
  25. package/dist/skills/ads-designer/references/validation.md +1 -1
  26. package/dist/skills/ads-import/references/design-data.md +34 -14
  27. package/dist/skills/ads-import/references/validation.md +1 -1
  28. package/dist/skills/ads-motion/references/design-data.md +34 -14
  29. package/dist/skills/ads-motion/references/validation.md +1 -1
  30. package/dist/skills/ads-port/references/design-data.md +34 -14
  31. package/dist/skills/ads-port/references/validation.md +1 -1
  32. package/dist/starters/preact/ds.config.json +0 -1
  33. package/dist/starters/react/README.md +6 -4
  34. package/dist/starters/react/design-system/components/Content/Image/Image.tsx +7 -4
  35. package/dist/starters/react/design-system/components/Content/Image/README.md +2 -2
  36. package/dist/starters/react/design-system/tokens/spacing.css +1 -1
  37. package/dist/starters/react/ds.config.json +0 -1
  38. package/docs/ADS.md +2 -2
  39. package/docs/ARCHITECTURE.md +9 -6
  40. package/docs/CHANGELOG.md +81 -12
  41. package/docs/GUIDE.md +77 -23
  42. package/package.json +1 -1
@@ -9,6 +9,7 @@ import { executeDevelopmentCommand } from "./verification.mjs";
9
9
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
10
10
  import { inspectScenarios } from "./scenarios.mjs";
11
11
  import { inspectUnits } from "./units.mjs";
12
+ import { globMatcher, smallPartLimitPx } from "./layout-widths.mjs";
12
13
  import { affectedScenarios } from "./verification.mjs";
13
14
 
14
15
  // Browser accessibility audit: axe-core (Deque, MPL-2.0, an unmodified ADS dependency
@@ -19,10 +20,13 @@ import { affectedScenarios } from "./verification.mjs";
19
20
  // which audit by default (browserAudit: false turns a policy's audit off). Automated rules catch a subset of WCAG failures; passing proves nothing more.
20
21
 
21
22
  export const AUDIT_RULE = "a11y-axe";
23
+ /** What axe could not decide on its own, such as contrast over a gradient: to check by hand. */
24
+ export const INCOMPLETE_RULE = "a11y-incomplete";
22
25
  /** ADS's own rendered check: WCAG 1.4.11 non-text contrast of control boundaries and icons (axe does not check it). */
23
26
  export const NON_TEXT_RULE = "a11y-non-text-contrast";
24
27
  /** ADS's own rendered layout check: horizontal overflow at each of overflowWidths. */
25
28
  export const OVERFLOW_RULE = "layout-overflow";
29
+ export const NARROW_RULE = "layout-overflow-narrow";
26
30
  /** ADS's own rendered check: a scenario's layout shift above the Core Web Vitals 0.1 threshold. */
27
31
  export const SHIFT_RULE = "layout-shift";
28
32
  const shiftLimit = 0.1;
@@ -32,9 +36,15 @@ const viewport = { width: 1280, height: 800 };
32
36
  /** Viewport widths layout-overflow renders every scenario at: phone, tablet and desktop. */
33
37
  export const overflowWidths = Object.freeze([390, 768, 1280]);
34
38
  export const auditedKinds = Object.freeze(["components", "patterns", "composition"]);
39
+ /** The width layout-overflow also renders scenarios of these kinds at, inside the widest viewport
40
+ * and in the first theme, since layout does not follow color: a narrow side pane. A composition is
41
+ * a whole screen, and is never hosted in one. */
42
+ export const containerWidth = 240;
43
+ export const containerKinds = Object.freeze(["components", "patterns"]);
35
44
  /** Attempts for one render, against a dropped preview connection or a slow preview. */
36
45
  export const auditAttempts = 3;
37
- const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4 };
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 };
38
48
 
39
49
  /** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
40
50
  export function wcagCriteria(tags) {
@@ -64,9 +74,29 @@ export function auditFindings(runs, scenarios) {
64
74
  });
65
75
  }
66
76
 
77
+ /** One info item per scenario, axe rule and element set, across brands and themes. */
78
+ export function incompleteFindings(runs, scenarios) {
79
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
80
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
81
+ for (const run of runs) for (const item of run.incomplete ?? []) {
82
+ const key = JSON.stringify([run.scenario, item.id, item.nodes.map(node => node.selector).sort()]);
83
+ const group = groups.get(key) ?? { scenario: run.scenario, themes: [], brands: [], item };
84
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
85
+ }
86
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, themes, brands, item }) => {
87
+ const where = item.nodes.slice(0, 3).map(node => `${node.selector}${node.reason ? ` (${node.reason})` : ""}`).join(", ") + (item.nodeCount > 3 ? ` and ${item.nodeCount - 3} more` : "");
88
+ return {
89
+ rule: INCOMPLETE_RULE, severity: findingSeverity(INCOMPLETE_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "axe-core", axeRule: item.id, impact: item.impact ?? null, scenario, themes, ...(brands.length ? { brands } : {}),
90
+ nodes: item.nodes, nodeCount: item.nodeCount, helpUrl: item.helpUrl, guidanceUri: "ads://guides/accessibility",
91
+ message: `axe could not decide ${item.id} in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: check it by hand. ${item.help}. ${item.nodeCount} element${item.nodeCount === 1 ? "" : "s"}: ${where}. ${item.helpUrl}`,
92
+ };
93
+ });
94
+ }
95
+
67
96
  const nonTextKinds = {
68
97
  border: { what: count => count === 1 ? "control's border is its only boundary and has" : "controls' borders are their only boundary and have", against: "the background around it", fix: "Give the boundary a border token with 3:1 against the surface it sits on, such as --border-strong, or a background with 3:1 against it." },
69
98
  icon: { what: count => count === 1 ? "icon-only control's icon has" : "icon-only controls' icons have", against: "its control's background", fix: "Paint the icon with a text or foreground token that has 3:1 against the control's background." },
99
+ focus: { what: count => count === 1 ? "control's focus outline has" : "controls' focus outlines have", against: "the background around it", fix: "Paint the focus outline with --border-focus or a token with 3:1 against the surface it sits on." },
70
100
  };
71
101
 
72
102
  /** Collapse per-brand, per-theme non-text contrast issues into ADS errors: one per scenario, kind
@@ -100,6 +130,7 @@ export function nonTextContrastFindings(runs, scenarios) {
100
130
  const overflowKinds = {
101
131
  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." },
102
132
  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." },
133
+ container: { what: "content reaches past its container", fix: "Make the element fluid (%, fr, min(100%, ...)), wrap it, or put it in an overflow-x: auto scroller. A width that truly stays this wide only fits an overlay: list its owner in layout.fixedWidthUnits." },
103
134
  clipped: { what: "content is cut off by overflow hidden or clip", fix: "Make the content fit, truncate it with text-overflow: ellipsis, or use overflow-x: auto if it should scroll." },
104
135
  };
105
136
 
@@ -108,22 +139,22 @@ const overflowKinds = {
108
139
  export function layoutOverflowFindings(runs, scenarios) {
109
140
  const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
110
141
  const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
111
- for (const run of runs) for (const { width, issues = [], counts = {} } of run.layout ?? []) for (const kind of Object.keys(overflowKinds)) {
142
+ for (const run of runs) for (const { width, container = false, issues = [], counts = {} } of run.layout ?? []) for (const kind of Object.keys(overflowKinds)) {
112
143
  const found = issues.filter(issue => issue.kind === kind);
113
144
  if (!found.length) continue;
114
- const key = JSON.stringify([run.scenario, kind, found.map(issue => issue.selector).sort()]);
115
- const group = groups.get(key) ?? { scenario: run.scenario, kind, widths: [], themes: [], brands: [], nodes: new Map(), nodeCount: 0 };
145
+ const key = JSON.stringify([run.scenario, kind, container, found.map(issue => issue.selector).sort()]);
146
+ const group = groups.get(key) ?? { scenario: run.scenario, kind, container, widths: [], themes: [], brands: [], nodes: new Map(), nodeCount: 0 };
116
147
  groups.set(key, group); add(group.widths, width); add(group.themes, run.theme); add(group.brands, run.brand);
117
148
  group.nodeCount = Math.max(group.nodeCount, counts[kind] ?? found.length);
118
149
  for (const issue of found) if (!(group.nodes.get(issue.selector)?.overflow >= issue.overflow)) group.nodes.set(issue.selector, { ...issue, width });
119
150
  }
120
- return [...groups.values()].slice(0, limits.findings).map(({ scenario, kind, widths, themes, brands, nodes, nodeCount }) => {
151
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, kind, container, widths, themes, brands, nodes, nodeCount }) => {
121
152
  const list = [...nodes.values()], sorted = [...widths].sort((a, b) => a - b);
122
153
  const where = list.slice(0, 3).map(node => `${node.selector} (${node.overflow}px at ${node.width}px)`).join(", ") + (nodeCount > 3 ? ` and ${nodeCount - 3} more` : "");
123
154
  return {
124
- rule: OVERFLOW_RULE, severity: findingSeverity(OVERFLOW_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", kind, scenario, widths: sorted, themes, ...(brands.length ? { brands } : {}),
155
+ rule: container ? NARROW_RULE : OVERFLOW_RULE, severity: findingSeverity(container ? NARROW_RULE : OVERFLOW_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", kind, ...(container ? { container: sorted[0] } : { widths: sorted }), scenario, themes, ...(brands.length ? { brands } : {}),
125
156
  nodes: list, nodeCount, guidanceUri: "ads://guides/tokens",
126
- message: `Layout overflow in ${scenario} at ${sorted.join(", ")} px wide [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${overflowKinds[kind].what}: ${where}. ${overflowKinds[kind].fix}`,
157
+ message: `Layout overflow in ${scenario} ${container ? `in a ${sorted[0]} px container` : `at ${sorted.join(", ")} px wide`} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${overflowKinds[kind].what}: ${where}. ${overflowKinds[kind].fix}`,
127
158
  };
128
159
  });
129
160
  }
@@ -169,7 +200,7 @@ export function auditScenarioSelection(options, changedFiles) {
169
200
  export function auditCheck(audit, extra = {}) {
170
201
  const routed = routeFindings([], audit.findings);
171
202
  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 } : {}),
172
- renders: audit.runs, ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.length, elapsedMs: audit.elapsedMs, ...extra } };
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 } };
173
204
  }
174
205
 
175
206
  function projectPlaywright(root) {
@@ -183,6 +214,17 @@ const installHint = "`npm install -D @playwright/test` and `npx playwright insta
183
214
  /** Whether the project can run the audit: project-local Playwright, as for captures. */
184
215
  export const browserAuditAvailable = root => !!projectPlaywright(path.resolve(root));
185
216
 
217
+ /** Scenarios of an owner in layout.fixedWidthUnits float above the layout, and have no container to fit. */
218
+ function floatingScenarios(options, scenarios) {
219
+ const globs = options.config.layout.fixedWidthUnits, floating = globMatcher(globs);
220
+ if (!globs.length) return new Set();
221
+ const inventory = inspectUnits(options);
222
+ return new Set(scenarios.filter(scenario => {
223
+ const owner = inventory.owner(inventory.relative(scenario.file));
224
+ return owner && (floating(owner) || inventory.units.find(unit => unit.id === owner)?.files.some(floating));
225
+ }).map(scenario => scenario.id));
226
+ }
227
+
186
228
  const renderKey = ({ scenario, theme, brand }) => JSON.stringify([scenario, theme, brand ?? null]);
187
229
  const clipCause = text => String(text).replace(/\s+/g, " ").trim().slice(0, 500);
188
230
 
@@ -206,7 +248,7 @@ async function warmScenariosApart(host, ids, signal) {
206
248
  async function runAuditWorker({ root, temporary, playwright, settings, apps, signal }) {
207
249
  const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
208
250
  rmSync(report, { force: true });
209
- writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
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 }));
210
252
  const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
211
253
  let cause;
212
254
  try {
@@ -273,10 +315,11 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
273
315
  let host = previewHost;
274
316
  try {
275
317
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: building ${scenarios.length} scenario previews.`, elapsedMs: Date.now() - startedAt });
276
- const startHost = async () => { const { startAdsMcp } = await import("./mcp/server.mjs"); return startAdsMcp(root, { stdio: false, showcase: true }); };
318
+ const startHost = async () => { const { startAdsMcp } = await import("./mcp/server.mjs"); return startAdsMcp(root, { stdio: false, showcase: true, despitePolicy: true }); };
277
319
  if (!host?.url) host = await startHost();
278
320
  const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
279
- 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 }))));
321
+ const floating = floatingScenarios(options, scenarios);
322
+ 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 } : {}) }))));
280
323
  const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }]));
281
324
  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 });
282
325
  for (let attempt = 1; attempt <= auditAttempts; attempt++) {
@@ -311,9 +354,9 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
311
354
  }
312
355
  const all = [...renders.values()], runs = all.map(render => render.result ?? render.partial).filter(Boolean);
313
356
  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 }));
314
- const findings = [...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios)];
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)];
315
358
  const shifts = runs.filter(run => run.layoutShift).sort((a, b) => b.layoutShift.value - a.layoutShift.value);
316
- return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: runs.reduce((sum, item) => sum + (item.incomplete ?? 0), 0), findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
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 };
317
360
  } finally {
318
361
  try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
319
362
  }
@@ -5,12 +5,20 @@ import { loadConfig } from "./config.mjs";
5
5
  import { withPreviewSession } from "./preview-scope.mjs";
6
6
  import { createBunPreviewBuilder } from "./preview-bun.mjs";
7
7
  import { checkCandidate } from "./validation-checks.mjs";
8
+ import { renderStoppingRules } from "./finding-rules.mjs";
8
9
 
9
10
  /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
10
11
  export async function compilePreviews(directory=process.cwd(),{watched=false}={}) {
11
12
  const root=path.resolve(directory);
12
13
  const compilerFiles=[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))];
13
- async function validate(){const result=await checkCandidate(root);if(!result.ok)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:result.diagnostics});}
14
+ async function validate(){
15
+ const result=await checkCandidate(root);
16
+ if(result.ok)return true;
17
+ // A session the audit started renders despite policy errors and reports them; it records no pass.
18
+ const stopping=process.env.ADS_PREVIEW_DESPITE_POLICY==="1"?result.diagnostics.filter(item=>renderStoppingRules.has(item.rule)):result.diagnostics;
19
+ if(stopping.length)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:stopping});
20
+ return false;
21
+ }
14
22
  if(!watched){const restored=await restoreCompiledPreviews(withPreviewSession(loadConfig(root),process.env.ADS_MCP_BUILD_SESSION),compilerFiles);if(restored)return restored;}
15
23
  return runScenarioCompiler(root,{watched,compilerFiles,validate,buildGraph:createBunPreviewBuilder()});
16
24
  }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, writeFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
+ import { firstRender } from "../browser-audit/first-render.mjs";
4
5
  import { openPreviewScenario } from "../verification/browser.mjs";
5
6
 
6
7
  // Runs only as an owned child, using the receiving project's browser dependency.
@@ -18,11 +19,7 @@ try {
18
19
  await frame.locator("html").waitFor({ state: "visible", timeout });
19
20
  await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
20
21
  if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
21
- await frame.evaluate(async () => {
22
- await document.fonts.ready;
23
- await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
24
- await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
25
- });
22
+ await frame.evaluate(firstRender);
26
23
  const actualViewport = await frame.evaluate(() => ({ width: innerWidth, height: innerHeight }));
27
24
  if (actualViewport.width !== app.viewport.width || actualViewport.height !== app.viewport.height) throw new Error(`App viewport differs from requested capture settings: ${JSON.stringify(actualViewport)}`);
28
25
  const target = frame.locator(app.selector);
package/dist/check.mjs CHANGED
@@ -112,7 +112,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
112
112
  const layoutWidths = createLayoutWidths(tokenInventory.tokens, config), fixedWidthOwner = globMatcher(config.layout.fixedWidthUnits);
113
113
  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
114
  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
- advisories.push(...layoutWidths.tokenFindings());
115
+ const ownerFixedWidths = [];
116
116
  function checkRegistrations(file,css,offset={line:1}){
117
117
  css.walkAtRules(/^property$/i,rule=>{
118
118
  const line=offset.line+(rule.source?.start.line??1)-1;
@@ -152,7 +152,9 @@ export function checkProject(directory, { trackingRoot } = {}) {
152
152
  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
153
  if (!foundation && (isInside(path.join(dsRoot, "composition"), file) || !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)))) {
154
154
  const relative = path.relative(root, file).replaceAll("\\", "/"), owner = units.owner(units.relative(path.relative(root, file)));
155
- if (!fixedWidthOwner(relative) && !(owner && fixedWidthOwner(owner))) advisories.push(...layoutWidths.inspect(css, relative, offset));
155
+ const widths = layoutWidths.inspect(css, relative, offset);
156
+ if (!fixedWidthOwner(relative) && !(owner && fixedWidthOwner(owner))) advisories.push(...widths);
157
+ else ownerFixedWidths.push(...widths.filter(finding => finding.rule === "layout-fixed-width"));
156
158
  }
157
159
  // Linaria templates are checked once per resolved interpolation variant.
158
160
  if (!foundation) for (const finding of controlPaddingAdvisories(css, { tokens: declaredTokens, file: path.relative(root, file).replaceAll("\\", "/"), offset })) {
@@ -381,7 +383,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
381
383
  }
382
384
  inspectDesignAliases(layerStyles,options,report);
383
385
  for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
384
- advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings());
386
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths));
385
387
  // Errors block by class; bounded clients see review items before informational limits.
386
388
  const routed=routeFindings(diagnostics,advisories);
387
389
  const uniqueDiagnostics=[...new Map(routed.diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];
package/dist/cli.mjs CHANGED
@@ -171,11 +171,16 @@ async function main(args) {
171
171
  const controller = new AbortController(), abort = () => controller.abort();
172
172
  process.once("SIGINT", abort); process.once("SIGTERM", abort);
173
173
  try {
174
- const { routeFindings } = await import("./finding-rules.mjs");
174
+ const { renderStoppingRules, routeFindings } = await import("./finding-rules.mjs");
175
+ // Policy errors do not stop the render: they are reported with the audit's and fail it the same.
176
+ const { checkCandidate } = await import("./validation-checks.mjs");
177
+ const core = await checkCandidate(target, controller.signal);
178
+ const stopping = core.diagnostics.filter(item => renderStoppingRules.has(item.rule));
179
+ if (stopping.length) throw new Error(`Project validation failed; nothing can be rendered. ${stopping.slice(0, 5).map(item => `${item.file ?? ""}:${item.line ?? 1}: ${item.rule}: ${item.message}`).join(" ")}`);
175
180
  const audit = await runBrowserAudit(target, { scenarios: selectedScenarios, themes: theme ? [theme] : undefined, brands: brand ? [brand] : undefined, signal: controller.signal });
176
181
  // a11y-axe findings are errors, as in validation; any review-class finding stays nonblocking.
177
- const routed = routeFindings([], audit.findings);
178
- result = { ...audit, ok: !routed.diagnostics.length, findings: routed.advisories, diagnostics: routed.diagnostics };
182
+ const routed = routeFindings(core.diagnostics, audit.findings);
183
+ result = { ...audit, ok: !routed.diagnostics.length, staticErrors: core.diagnostics.length, findings: routed.advisories, diagnostics: routed.diagnostics };
179
184
  }
180
185
  finally { process.removeListener("SIGINT", abort); process.removeListener("SIGTERM", abort); }
181
186
  }
@@ -184,7 +189,8 @@ async function main(args) {
184
189
  else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
185
190
  else if (command === "lint-config") result = generateLintConfig(target);
186
191
  else throw new Error(`Unknown command: ${command}. Run ads --help.`);
187
- if (json) console.log(JSON.stringify(result, null, 2));
192
+ // Bun ends a piped stdout at its buffer unless the write is awaited.
193
+ if (json) await new Promise(resolve => process.stdout.write(`${JSON.stringify(result, null, 2)}\n`, resolve));
188
194
  else if (command === "create") console.log(`Created ${result.name} in ${target}\nFramework: ${result.framework}\nNext: cd ${((folder) => /[\s'"$`\\]/.test(folder) ? JSON.stringify(folder) : folder)(path.relative(process.cwd(), target) || ".")} && ${result.packageManager} install && ${result.packageManager === "bun" ? "bunx" : "npx"} playwright install chromium && ${result.packageManager} run build && ${result.packageManager} run dev:showcase`);
189
195
  else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build runs ADS checks and generates configured brand assets automatically.`);
190
196
  else if (command === "assets") {
@@ -196,7 +202,7 @@ async function main(args) {
196
202
  }
197
203
  else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
198
204
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
199
- else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.length)} across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); if (result.retries) console.log(`Retried ${result.retries.length} render${result.retries.length === 1 ? "" : "s"} that then passed: ${result.retries.map(retry => `${retry.scenario} [${[retry.theme, retry.brand].filter(Boolean).join(", ")}] in ${retry.attempts} attempts`).join("; ")}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
205
+ else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.filter(finding => finding.severity === "review").length)}, ${result.incomplete ?? 0} that axe could not decide across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); if (result.retries) console.log(`Retried ${result.retries.length} render${result.retries.length === 1 ? "" : "s"} that then passed: ${result.retries.map(retry => `${retry.scenario} [${[retry.theme, retry.brand].filter(Boolean).join(", ")}] in ${retry.attempts} attempts`).join("; ")}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
200
206
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
201
207
  else if (command === "validate") {console.log(`ADS ${result.policy} ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
202
208
  else if (command === "tokens") {
package/dist/config.mjs CHANGED
@@ -131,8 +131,8 @@ export function loadConfig(directory = process.cwd()) {
131
131
  for (const brand of config.brands) if (config.themes.some(theme => theme.name === `brand-${brand.name}`)) throw new Error(`Theme "brand-${brand.name}" and brand "${brand.name}" would share the display switch --display-brand-${brand.name}; rename one.`);
132
132
  if(config.resources.memoryLimitMb!==null&&(!Number.isInteger(config.resources.memoryLimitMb)||config.resources.memoryLimitMb<64||config.resources.memoryLimitMb>1048576))throw new Error("resources.memoryLimitMb must be null (automatic) or an integer from 64 to 1048576 MiB.");
133
133
  if (config.assets.imageBudgetKb !== null && (!Number.isInteger(config.assets.imageBudgetKb) || config.assets.imageBudgetKb < 1 || config.assets.imageBudgetKb > 1048576)) throw new Error("assets.imageBudgetKb must be null (a limit per format) or a positive whole number of KB for every format.");
134
- if (!Array.isArray(config.layout.widthTokens) || config.layout.widthTokens.length > 200 || new Set(config.layout.widthTokens).size !== config.layout.widthTokens.length || config.layout.widthTokens.some(name => typeof name !== "string" || !/^--[\w*-]+$/.test(name))) throw new Error("layout.widthTokens must contain distinct token names or globs such as --grid-span-*.");
135
- if (!Array.isArray(config.layout.fixedWidthUnits) || config.layout.fixedWidthUnits.length > 200 || new Set(config.layout.fixedWidthUnits).size !== config.layout.fixedWidthUnits.length || config.layout.fixedWidthUnits.some(glob => typeof glob !== "string" || !glob || glob.includes("\\") || glob.startsWith("/") || glob.split("/").includes(".."))) throw new Error("layout.fixedWidthUnits must contain distinct unit ids or project-relative globs such as components/Overlay/*.");
134
+ if (!Array.isArray(config.layout.widthTokens) || config.layout.widthTokens.length > 200 || new Set(config.layout.widthTokens).size !== config.layout.widthTokens.length || config.layout.widthTokens.some(name => typeof name !== "string" || !/^--[\w-][\w*-]*$/.test(name))) throw new Error("layout.widthTokens must contain distinct token names or globs such as --panel-*, and cannot name every token.");
135
+ if (!Array.isArray(config.layout.fixedWidthUnits) || config.layout.fixedWidthUnits.length > 200 || new Set(config.layout.fixedWidthUnits).size !== config.layout.fixedWidthUnits.length || config.layout.fixedWidthUnits.some(glob => typeof glob !== "string" || !glob || glob.includes("\\") || glob.startsWith("/") || glob.split("/").includes("..") || !/[^*/]/.test(glob))) throw new Error("layout.fixedWidthUnits must contain distinct unit ids or project-relative globs such as components/Overlay/*, and cannot name every unit.");
136
136
  if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
137
137
  const notificationNames = new Set();
138
138
  for (const entry of config.usage.notifications) {
@@ -11,6 +11,8 @@ export const findingRules = Object.freeze({
11
11
  "a11y-non-text-contrast": "error", "a11y-target-size": "error", "a11y-text-resize": "error", "a11y-text-spacing": "error",
12
12
  // A click handler on a non-control may be reachable through a delegated or wrapping control.
13
13
  "a11y-keyboard": "review",
14
+ // What axe reports it could not decide: nothing fails, and someone checks it by hand.
15
+ "a11y-incomplete": "info",
14
16
  // Atomic styles: the composition analysis is heuristic; its limits are informational.
15
17
  "atomic-composition-review": "review", "atomic-composition-limit": "info",
16
18
  // Text and background a component style block pairs itself; a side that names no color token is informational.
@@ -22,6 +24,9 @@ export const findingRules = Object.freeze({
22
24
  "control-padding": "error",
23
25
  // Widths are fluid on the grid: fixed widths from source, and overflow where the audit renders.
24
26
  "layout-fixed-width": "error", "layout-overflow": "error",
27
+ // Whether a declared width must stay fixed, a fluid wrapper does anything, or a part ever sits in
28
+ // a narrow pane takes judgement.
29
+ "layout-declared-width": "review", "layout-width-noop": "review", "layout-overflow-narrow": "review",
25
30
  // Images reserve their space and choose how they load; a spread or foreign class cannot be read.
26
31
  "img-attributes": "error", "img-attributes-unresolved": "info",
27
32
  "asset-image-budget": "error",
@@ -43,6 +48,12 @@ export const findingRules = Object.freeze({
43
48
  "token-overlap-review": "review",
44
49
  });
45
50
 
51
+ /** Static errors that stop a preview from rendering: a file that does not parse, a project that is
52
+ * not laid out, a scenario that cannot be registered. Everything else is policy: it fails ads check,
53
+ * validation and the audit's exit code, but the audit still renders and reports it. A broken import
54
+ * stops only the builds that reach it, which then fail as unaudited scenarios. */
55
+ export const renderStoppingRules = Object.freeze(new Set(["css-syntax", "project-structure", "scenario-contract", "source-syntax", "styles-entry"]));
56
+
46
57
  const severities = new Set(["error", "review", "info"]);
47
58
 
48
59
  /** A classified finding's severity; throws for an id missing from the registry. */