@reqvire-org/ads 0.3.46 → 0.3.47
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 +21 -11
- package/dist/a11y.mjs +4 -2
- package/dist/assets.mjs +20 -15
- package/dist/atomic-composition.mjs +3 -2
- package/dist/brand-assets.mjs +48 -11
- package/dist/brands.mjs +82 -0
- package/dist/browser-audit/worker.mjs +45 -0
- package/dist/browser-audit.mjs +117 -0
- package/dist/capture/worker.mjs +1 -0
- package/dist/capture-store.mjs +2 -0
- package/dist/capture.mjs +7 -4
- package/dist/check.mjs +38 -8
- package/dist/cli.mjs +45 -10
- package/dist/color-values.mjs +325 -0
- package/dist/config.mjs +16 -2
- package/dist/control-padding.mjs +93 -0
- package/dist/design-values.mjs +3 -2
- package/dist/finding-rules.mjs +61 -0
- package/dist/foundation.mjs +17 -4
- package/dist/icons.mjs +107 -0
- package/dist/init.mjs +3 -0
- package/dist/mcp/apps.mjs +9 -6
- package/dist/mcp/drafts.mjs +3 -0
- package/dist/mcp/mutations.mjs +17 -1
- package/dist/mcp/preview-widget.bundle.js +36 -36
- package/dist/mcp/project-widget.bundle.js +12 -12
- package/dist/mcp/server.mjs +21 -9
- package/dist/mcp/widget.bundle.js +17 -17
- package/dist/palette-generated.mjs +180 -0
- package/dist/preview-resources.mjs +12 -3
- package/dist/render-color-probe.mjs +148 -0
- package/dist/runtime-contracts.mjs +14 -4
- package/dist/scenarios.mjs +1 -1
- package/dist/showcase/client.bundle.js +28 -28
- package/dist/showcase/icons.js +146 -0
- package/dist/showcase/index.html +2 -1
- package/dist/showcase/style.css +19 -2
- package/dist/skills/README.md +2 -1
- package/dist/skills/ads-break-ui/SKILL.md +6 -5
- package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
- package/dist/skills/ads-break-ui/references/contracts.md +13 -10
- package/dist/skills/ads-break-ui/references/design-data.md +137 -29
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-designer/SKILL.md +23 -16
- package/dist/skills/ads-designer/references/accessibility.md +39 -5
- package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
- package/dist/skills/ads-designer/references/branding.md +37 -10
- package/dist/skills/ads-designer/references/cli.md +8 -2
- package/dist/skills/ads-designer/references/contracts.md +13 -10
- package/dist/skills/ads-designer/references/design-data.md +137 -29
- package/dist/skills/ads-designer/references/validation.md +8 -4
- package/dist/skills/ads-import/SKILL.md +9 -8
- package/dist/skills/ads-import/references/atomic-styles.md +12 -12
- package/dist/skills/ads-import/references/cli.md +8 -2
- package/dist/skills/ads-import/references/contracts.md +13 -10
- package/dist/skills/ads-import/references/design-data.md +137 -29
- package/dist/skills/ads-import/references/tokens.md +7 -3
- package/dist/skills/ads-import/references/validation.md +8 -4
- package/dist/skills/ads-motion/SKILL.md +6 -5
- package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
- package/dist/skills/ads-motion/references/contracts.md +13 -10
- package/dist/skills/ads-motion/references/design-data.md +137 -29
- package/dist/skills/ads-motion/references/validation.md +8 -4
- package/dist/skills/ads-port/SKILL.md +6 -5
- package/dist/skills/ads-port/references/atomic-styles.md +12 -12
- package/dist/skills/ads-port/references/cli.md +8 -2
- package/dist/skills/ads-port/references/contracts.md +13 -10
- package/dist/skills/ads-port/references/design-data.md +137 -29
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +11 -2
- package/dist/starters/react/ADS.md +43 -10
- package/dist/starters/react/README.md +14 -9
- package/dist/starters/react/design-system/assets/brand/README.md +8 -3
- package/dist/starters/react/design-system/assets/glyphs/README.md +4 -1
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -1
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +3 -2
- package/dist/starters/react/design-system/components/Content/Icon/README.md +2 -1
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
- package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
- package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
- package/dist/starters/react/design-system/index.ts +3 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +11 -2
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/design-system/tokens/base.css +8 -5
- package/dist/starters/react/design-system/tokens/colors.css +167 -175
- package/dist/starters/react/design-system/tokens/elevation.css +14 -21
- package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
- package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
- package/dist/style-boundaries.mjs +2 -1
- package/dist/themes-generated.mjs +150 -0
- package/dist/themes-watch.mjs +42 -0
- package/dist/themes.mjs +214 -63
- package/dist/token-export.mjs +22 -11
- package/dist/token-policy.mjs +2 -1
- package/dist/token-quality.mjs +28 -25
- package/dist/tokens.mjs +27 -32
- package/dist/validation.mjs +18 -1
- package/dist/verification/browser.mjs +14 -3
- package/docs/ADS.md +41 -27
- package/docs/ARCHITECTURE.md +49 -22
- package/docs/CACHING.md +2 -3
- package/docs/CHANGELOG.md +97 -13
- package/docs/CONTRACTS.md +13 -10
- package/docs/GUIDE.md +89 -21
- package/docs/MCP.md +35 -25
- package/docs/benchmarks/bun-previews.md +5 -5
- package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
- package/docs/benchmarks/turbo-poc.md +24 -6
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -107,9 +107,9 @@ bun --bun run build
|
|
|
107
107
|
`init` detects npm or Bun from your project. It adds ADS as a development dependency, sets up an empty local ADS if needed, and adds ADS checks before your
|
|
108
108
|
existing build. The default layout is root `design-system/`, alongside `src/`.
|
|
109
109
|
It keeps your app, token values, scripts, and lockfile. Each build runs native ADS gates for tokens, styles, imports, renderer
|
|
110
|
-
boundaries and asset ownership, then
|
|
111
|
-
|
|
112
|
-
|
|
110
|
+
boundaries and asset ownership, then runs `ads assets` (configured brand icons, the
|
|
111
|
+
glyph module and the generated theme files). Commit the updated lockfile and the
|
|
112
|
+
generated theme files; generated `.ds/` files are ignored. Init does not install or configure
|
|
113
113
|
Linaria; integrate its extraction with your build as described in the
|
|
114
114
|
[guide](docs/GUIDE.md#linaria-integration).
|
|
115
115
|
|
|
@@ -118,14 +118,15 @@ Linaria; integrate its extraction with your build as described in the
|
|
|
118
118
|
| Command | Use |
|
|
119
119
|
|---------|-----|
|
|
120
120
|
| `ads init --framework react` | Set up ADS in the current project; also accepts `preact`; saved choices can omit the flag |
|
|
121
|
-
| `ads check` | Check tokens, styles, imports, and ADS ownership |
|
|
121
|
+
| `ads check` | Check tokens, styles, imports, and ADS ownership; errors fail, review items are listed |
|
|
122
122
|
| `ads validate` | Run the configured validation policy and current-preview audit |
|
|
123
123
|
| `ads validate --policy acceptance` | Check the acceptance policy against direct source edits without applying changes |
|
|
124
124
|
| `ads compile` | Compile all previews with Bun; `--watch` rebuilds on edits |
|
|
125
125
|
| `ads tokens` | Inspect token values and themes |
|
|
126
126
|
| `ads behaviors` | Inspect registered behavior guarantees and current evidence |
|
|
127
127
|
| `ads verify --unit <id>` | Run an owner's registered behavior checks |
|
|
128
|
-
| `ads
|
|
128
|
+
| `ads audit` | Run axe-core in every rendered UI scenario, once per brand and theme; findings are errors |
|
|
129
|
+
| `ads assets` | Generate web icons, the glyph module, `themes.generated.css` and the renderer palette `themes.generated.ts` |
|
|
129
130
|
| `ads lint-config` | Optional integration with an explicitly configured project linter |
|
|
130
131
|
| `ads mcp` | Start the stdio MCP server and its local showcase |
|
|
131
132
|
| `ads showcase` | Start the same MCP runtime for browser-only inspection |
|
|
@@ -203,8 +204,9 @@ Clients without Apps can inspect text/resources and use the regular showcase.
|
|
|
203
204
|
## Showcase
|
|
204
205
|
|
|
205
206
|
The showcase is **a minimal shell plus an MCP client and Apps host**. It ships
|
|
206
|
-
with ADS tooling. Tokens, Components, Patterns and Composition share its header,
|
|
207
|
-
collapsible left menu, theme
|
|
207
|
+
with ADS tooling. Brand, Tokens, Components, Patterns and Composition share its header,
|
|
208
|
+
collapsible left menu, theme and brand switches and preview area; an Icons tab shows the
|
|
209
|
+
glyph set. Lists come from MCP results;
|
|
208
210
|
selecting an entry renders its real scenario inside one reusable MCP App. The
|
|
209
211
|
App loads shared runtime, CSS, fonts and selected modules through MCP resources.
|
|
210
212
|
All project code and styles stay inside its sandbox; the shell stays neutral.
|
|
@@ -263,13 +265,21 @@ of production. Full-app harnesses belong in application tests. See the
|
|
|
263
265
|
|
|
264
266
|
Change values in `design-system/tokens/`, keeping the
|
|
265
267
|
[shared token names](docs/ADS.md#shared-token-contract), such as `--accent` and
|
|
266
|
-
`--font-sans`.
|
|
268
|
+
`--font-sans`. A value that differs per theme is written as one half per theme on `:root`
|
|
269
|
+
(`--color-accent-9-light`, `--color-accent-9-dark`), and a second brand re-sets halves on
|
|
270
|
+
`[data-brand="<name>"]`; ADS generates `tokens/themes.generated.css` and
|
|
271
|
+
`tokens/themes.generated.ts` from them. See
|
|
272
|
+
[themes](docs/GUIDE.md#tokens-grid-icons-and-accessibility).
|
|
267
273
|
|
|
268
274
|
Keep original artwork, with its use, credits and license in a README, in
|
|
269
|
-
`design-system/assets/brand/`; `ads check`
|
|
270
|
-
unpreviewed
|
|
275
|
+
`design-system/assets/brand/`; `ads check` fails on undescribed, unlicensed or
|
|
276
|
+
unpreviewed artwork and lists unused artwork for review. Name dark-theme variants `<name>.dark.svg`.
|
|
271
277
|
Committed native and export icons (`assets.targets`: SVG, PNG, ICO, ICNS) and UI
|
|
272
278
|
icon sets (`assets.glyphs`) are generated by `ads assets` and checked for freshness.
|
|
279
|
+
Other products' logos are not brand artwork or glyphs: keep them, in their own
|
|
280
|
+
colors and under their owners' trademark and usage terms, in `assets/logos/` and
|
|
281
|
+
show them as images (a CSS mask over `currentColor` for a muted use); ADS generates
|
|
282
|
+
and checks nothing there.
|
|
273
283
|
To generate web icons, add this to `ds.config.json`:
|
|
274
284
|
|
|
275
285
|
```json
|
|
@@ -360,7 +370,7 @@ There are two different starting points in this checkout:
|
|
|
360
370
|
[starters/preact/](starters/preact/) the files that replace it for Preact:
|
|
361
371
|
a token foundation in six groups (AA contrast in both themes, a 2 px
|
|
362
372
|
rhythm), light and dark themes declared in `ds.config.json` that apply to the page or one
|
|
363
|
-
section, a column grid, an icon set, a brand preview with placeholder artwork, build
|
|
373
|
+
section at any depth, a column grid, an icon set, a brand preview with placeholder artwork, build
|
|
364
374
|
setup, example components, a pattern and a composition, development-only review
|
|
365
375
|
renderers, and a project preview compiler adapter. They ship in the npm package;
|
|
366
376
|
`ads create` copies them into a new project, and `ads init` uses their foundation
|
package/dist/a11y.mjs
CHANGED
|
@@ -4,12 +4,14 @@ import ts from "typescript";
|
|
|
4
4
|
import { isDevelopmentFile, isInside, sourceFiles } from "./config.mjs";
|
|
5
5
|
import { parseColor } from "./token-quality.mjs";
|
|
6
6
|
import { baseDefinition } from "./themes.mjs";
|
|
7
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
7
8
|
|
|
8
9
|
// Accessibility guards ADS can check without a browser: token values (WCAG target size,
|
|
9
10
|
// focus, text resize, reduced motion, text spacing) and runtime component source (text
|
|
10
|
-
// alternatives, keyboard reach, autoplaying motion)
|
|
11
|
+
// alternatives, keyboard reach, autoplaying motion), each with its WCAG reference. Keyboard reach
|
|
12
|
+
// is a review item (a delegated control may handle it); the rest are errors.
|
|
11
13
|
|
|
12
|
-
const advisory = (rule, { file, line = 1, column = 1 }, message, tokens) => ({ rule, severity:
|
|
14
|
+
const advisory = (rule, { file, line = 1, column = 1 }, message, tokens) => ({ rule, severity: findingSeverity(rule), file, line, column, ...(tokens ? { tokens } : {}), guidanceUri: "ads://guides/accessibility", message });
|
|
13
15
|
/** Pixels of a px/rem length, or null. */
|
|
14
16
|
const pixels = value => {
|
|
15
17
|
const match = value.trim().match(/^(\d*\.?\d+)(px|rem)$/);
|
package/dist/assets.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { brandFormats, isInside } from "./config.mjs";
|
|
5
|
-
import { brandFiles, brandSourceDiagnostic, staleBrandOutputs } from "./brand-assets.mjs";
|
|
5
|
+
import { brandFiles, brandSourceDiagnostic, glyphAliases, staleBrandOutputs } from "./brand-assets.mjs";
|
|
6
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
6
7
|
|
|
7
8
|
function assetFiles(directory, prefix = "") {
|
|
8
9
|
const stat = lstatSync(directory, { throwIfNoEntry: false });
|
|
@@ -35,26 +36,30 @@ function sourceTexts(directories, skipped) {
|
|
|
35
36
|
return texts;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
/** A glyph
|
|
39
|
-
|
|
39
|
+
/** A glyph's normalized viewBox, or null without one. */
|
|
40
|
+
export const glyphViewBox = text => text.match(/<svg\b[^>]*\bviewBox\s*=\s*["']([^"']+)["']/)?.[1]?.trim().replace(/\s+/g, " ") ?? null;
|
|
41
|
+
|
|
42
|
+
/** A glyph set draws in currentColor on one shared viewBox, so icons follow text color and size. Its aliases name existing glyphs. */
|
|
43
|
+
export function inspectGlyphs({ root, dsRoot, config }) {
|
|
40
44
|
const glyphs = config.assets.glyphs;
|
|
41
45
|
if (!glyphs) return [];
|
|
42
46
|
const directory = path.join(dsRoot, glyphs.source);
|
|
43
47
|
const files = assetFiles(directory).filter(file => file.toLowerCase().endsWith(".svg"));
|
|
44
48
|
const read = files.map(file => ({ file: path.join(directory, file), text: readFileSync(path.join(directory, file), "utf8") }));
|
|
45
|
-
const
|
|
46
|
-
const viewBox =
|
|
49
|
+
const finding = (rule, file, message, line = 1, column = 1) => ({ rule, severity: findingSeverity(rule), file: path.relative(root, file).replaceAll("\\", "/"), line, column, guidanceUri: "ads://guides/branding", message });
|
|
50
|
+
const viewBox = glyphViewBox;
|
|
47
51
|
const counts = new Map();
|
|
48
52
|
for (const { text } of read) { const box = viewBox(text); if (box) counts.set(box, (counts.get(box) ?? 0) + 1); }
|
|
49
53
|
const shared = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
50
|
-
const
|
|
54
|
+
const aliases = glyphAliases(directory, files.filter(file => !file.includes("/")).map(file => file.slice(0, -4)));
|
|
55
|
+
const findings = aliases.problems.map(({ line, column, message }) => finding("glyph-aliases", aliases.file, message, line, column));
|
|
51
56
|
for (const { file, text } of read) {
|
|
52
57
|
const base = path.basename(file), box = viewBox(text);
|
|
53
|
-
if (!box) findings.push(
|
|
54
|
-
else if (shared && box !== shared) findings.push(
|
|
58
|
+
if (!box) findings.push(finding("glyph-viewbox", file, `${base} has no viewBox; glyphs need one shared viewBox to draw at the same size.`));
|
|
59
|
+
else if (shared && box !== shared) findings.push(finding("glyph-viewbox", file, `${base} uses viewBox "${box}"; the set uses "${shared}", so it would draw at a different size.`));
|
|
55
60
|
// Any fill or stroke other than none or currentColor fixes the icon's color.
|
|
56
61
|
const colors = [...text.matchAll(/\b(fill|stroke)\s*[=:]\s*["']?\s*([^"';\s>]+)/g)].map(match => match[2]).filter(value => !/^(?:none|currentcolor|inherit)$/i.test(value) && !/^url\(/i.test(value));
|
|
57
|
-
if (colors.length) findings.push(
|
|
62
|
+
if (colors.length) findings.push(finding("glyph-color", file, `${base} sets ${[...new Set(colors)].join(", ")}; draw glyphs in currentColor so they follow the text color and theme. Another product's logo that keeps its own colors belongs in assets/logos/, shown as an image; the project's own colored artwork belongs in assets/brand/.`));
|
|
58
63
|
}
|
|
59
64
|
return findings;
|
|
60
65
|
}
|
|
@@ -67,21 +72,21 @@ function inspectBrand({ root, dsRoot, config }) {
|
|
|
67
72
|
const brand = path.join(dsRoot, "assets/brand");
|
|
68
73
|
const artwork = assetFiles(brand).filter(file => brandFormats.includes(path.extname(file).toLowerCase()));
|
|
69
74
|
if (!artwork.length) return diagnostics;
|
|
70
|
-
const
|
|
75
|
+
const finding = (rule, file, message) => diagnostics.push({ rule, severity: findingSeverity(rule), file: relative(file), line: 1, column: 1, guidanceUri: "ads://guides/branding", message });
|
|
71
76
|
const readmeFile = path.join(brand, "README.md");
|
|
72
77
|
const readme = existsSync(readmeFile) ? readFileSync(readmeFile, "utf8") : null;
|
|
73
|
-
if (readme === null)
|
|
74
|
-
else if (!/licen[cs]e/i.test(readme))
|
|
78
|
+
if (readme === null) finding("brand-readme", brand, "Describe each artwork in assets/brand/README.md: its use, suitable backgrounds, credits and license.");
|
|
79
|
+
else if (!/licen[cs]e/i.test(readme)) finding("brand-license", readmeFile, "State the license (or ownership) of the brand artwork in assets/brand/README.md.");
|
|
75
80
|
const generated = [...config.assets.generatedPaths.map(entry => path.resolve(root, entry)), path.join(root, ".ds")];
|
|
76
81
|
const sources = sourceTexts([dsRoot, path.join(root, config.sourceDir ?? "src")], [path.join(dsRoot, "assets"), ...generated]);
|
|
77
82
|
const configured = new Set([config.assets.iconSource, ...config.assets.targets.map(target => target.from)].filter(Boolean).map(file => path.join(dsRoot, file)));
|
|
78
83
|
const previews = path.join(dsRoot, "brand");
|
|
79
84
|
for (const name of artwork) {
|
|
80
85
|
const file = path.join(brand, name), base = path.basename(name);
|
|
81
|
-
if (readme !== null && !readme.includes(base))
|
|
86
|
+
if (readme !== null && !readme.includes(base)) finding("brand-readme", file, `Describe ${base} in assets/brand/README.md: its use, suitable backgrounds, credits and license.`);
|
|
82
87
|
const referencing = sources.filter(source => source.text.includes(base));
|
|
83
|
-
if (!referencing.some(source => isInside(previews, source.file) && previewFile.test(source.file)))
|
|
84
|
-
if (!configured.has(file) && !referencing.some(source => !previewFile.test(source.file)))
|
|
88
|
+
if (!referencing.some(source => isInside(previews, source.file) && previewFile.test(source.file))) finding("brand-preview", file, `Show ${base} in a brand/ scenario, so it can be reviewed in the showcase's Brand section.`);
|
|
89
|
+
if (!configured.has(file) && !referencing.some(source => !previewFile.test(source.file))) finding("brand-unused", file, `${base} is not used by any component, assets.iconSource or assets.targets. Use it or remove it.`);
|
|
85
90
|
}
|
|
86
91
|
return diagnostics;
|
|
87
92
|
}
|
|
@@ -5,6 +5,7 @@ import valueParser from "postcss-value-parser";
|
|
|
5
5
|
import { isInside } from "./config.mjs";
|
|
6
6
|
import { createAtomicTrace } from "./atomic-trace.mjs";
|
|
7
7
|
import { sourceSymbol } from "./source-symbols.mjs";
|
|
8
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
8
9
|
|
|
9
10
|
export const atomicStyleGuide = "ads://guides/atomic-styles";
|
|
10
11
|
|
|
@@ -189,7 +190,7 @@ export function createAtomicCompositionReview(program, options) {
|
|
|
189
190
|
if (previous && (previous.target || !context.target) && previous.composition.length >= composition.length) continue;
|
|
190
191
|
const position = source.getLineAndCharacterOfPosition(location.getStart(source));
|
|
191
192
|
const dependent = writingModeDependent(a.property, b.property) || valueModeDependent(a, b);
|
|
192
|
-
warnings.set(key, { rule: "atomic-composition-review", severity: "
|
|
193
|
+
warnings.set(key, { rule: "atomic-composition-review", severity: findingSeverity("atomic-composition-review"), line: position.line + 1, column: position.character + 1,
|
|
193
194
|
message: `Atomic declarations ${a.property}: ${previewValue(a.value)} and ${b.property}: ${previewValue(b.value)} may overlap without matching cx merge keys.${context.target ? ` Source tracing reaches the same <${context.target.name}> className.` : " This is a source composition risk, not a confirmed rendered conflict."}${dependent ? " The overlap depends on writing mode or direction." : ""} Their winner can depend on extraction order, specificity or writing mode. Use consistent property names/granularity across the base and variants, compose with Linaria cx, and verify computed styles in the built preview. Review all affected variants; valid tokens do not establish cascade correctness. See ${atomicStyleGuide}.`,
|
|
194
195
|
guidanceUri: atomicStyleGuide, writingModeDependent: dependent, composition, ...(context.target ? { target: relative(context.target) } : {}), ...(context.limits?.length ? { analysisLimits: [...new Set(context.limits)].slice(0, 5) } : {}),
|
|
195
196
|
related: [a, b].map(({ selectors: _selectors, conditions: _conditions, important: _important, via: _via, ...entry }) => ({...entry,value:previewValue(entry.value)})) });
|
|
@@ -199,7 +200,7 @@ export function createAtomicCompositionReview(program, options) {
|
|
|
199
200
|
const key = reasons.join("\n");
|
|
200
201
|
if (limits.has(key) || limits.size >= 5) return;
|
|
201
202
|
const position = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
202
|
-
limits.set(key, { rule: "atomic-composition-limit", severity: "
|
|
203
|
+
limits.set(key, { rule: "atomic-composition-limit", severity: findingSeverity("atomic-composition-limit"), line: position.line + 1, column: position.character + 1,
|
|
203
204
|
message: `Atomic source review is incomplete: ${[...new Set(reasons)].slice(0, 3).join(" ")} Review the actual DOM classes and computed styles in a built scenario. An unresolved path is not evidence that composition is safe. See ${atomicStyleGuide}.`, guidanceUri: atomicStyleGuide, composition: composition.slice(0, 16).map(relative) });
|
|
204
205
|
}
|
|
205
206
|
function visit(node) {
|
package/dist/brand-assets.mjs
CHANGED
|
@@ -120,26 +120,63 @@ async function renderTarget(sharp, source, target) {
|
|
|
120
120
|
return format === ".ico" ? ico(entries.map(entry => ({ ...entry, size: entry.size === 256 ? 0 : entry.size }))) : icns(entries);
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
/** One glyph as the generated module stores it: the configured default attributes fill what the SVG leaves unset. */
|
|
124
|
+
export function glyphMarkup(text, attributes = {}) {
|
|
125
|
+
return text.replace(/<\?xml[\s\S]*?\?>/g, "").trim()
|
|
126
|
+
.replace(/<svg\b([^>]*)>/, (_match, own) => {
|
|
127
|
+
const missing = Object.entries(attributes).filter(([key]) => !new RegExp(`(?:^|\\s)${key}=`).test(own)).map(([key, value]) => ` ${key}="${value}"`).join("");
|
|
128
|
+
return `<svg${missing}${own}>`;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function jsonErrorPosition(text, error) {
|
|
133
|
+
const lineColumn = error.message.match(/line (\d+) column (\d+)/);
|
|
134
|
+
if (lineColumn) return { line: Number(lineColumn[1]), column: Number(lineColumn[2]) };
|
|
135
|
+
const position = error.message.match(/position (\d+)/);
|
|
136
|
+
return position ? textPosition(text, Number(position[1])) : { line: 1, column: 1 };
|
|
137
|
+
}
|
|
138
|
+
function textPosition(text, index) {
|
|
139
|
+
const before = text.slice(0, index).split("\n");
|
|
140
|
+
return { line: before.length, column: before.at(-1).length + 1 };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A glyph set's aliases.json: the alias map and its problems, each with its line.
|
|
145
|
+
* `names` are the set's SVG names; a file named like an alias is not a glyph.
|
|
146
|
+
* The problems are what `ads check`, the Icons view and `ads assets` report.
|
|
147
|
+
*/
|
|
148
|
+
export function glyphAliases(directory, names) {
|
|
149
|
+
const file = path.join(directory, "aliases.json");
|
|
150
|
+
if (!existsSync(file)) return { file, aliases: {}, problems: [] };
|
|
151
|
+
const text = readFileSync(file, "utf8");
|
|
152
|
+
let value;
|
|
153
|
+
try { value = JSON.parse(text); }
|
|
154
|
+
catch (error) { return { file, aliases: {}, problems: [{ ...jsonErrorPosition(text, error), message: `aliases.json is not valid JSON: ${error.message}` }] }; }
|
|
155
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some(target => typeof target !== "string")) {
|
|
156
|
+
return { file, aliases: {}, problems: [{ line: 1, column: 1, message: "aliases.json maps alias names to glyph names." }] };
|
|
157
|
+
}
|
|
158
|
+
const glyphs = new Set(names.filter(name => !Object.hasOwn(value, name)));
|
|
159
|
+
const problems = Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).filter(([, target]) => !glyphs.has(target)).map(([alias, target]) => {
|
|
160
|
+
const key = text.search(new RegExp(`${JSON.stringify(alias).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*:`));
|
|
161
|
+
return { ...(key >= 0 ? textPosition(text, key) : { line: 1, column: 1 }), message: `${alias} names a missing glyph ${target}.` };
|
|
162
|
+
});
|
|
163
|
+
return { file, aliases: value, problems };
|
|
164
|
+
}
|
|
165
|
+
|
|
123
166
|
/** The glyph set as its generated module, or null without one. */
|
|
124
167
|
export function glyphModule({ dsRoot, config }) {
|
|
125
168
|
const glyphs = config.assets.glyphs;
|
|
126
169
|
if (!glyphs) return null;
|
|
127
170
|
const directory = path.join(dsRoot, glyphs.source);
|
|
128
|
-
const
|
|
129
|
-
const aliases
|
|
171
|
+
const names = readdirSync(directory).filter(name => name.endsWith(".svg")).sort().map(name => name.slice(0, -4));
|
|
172
|
+
const { aliases, problems: [problem] } = glyphAliases(directory, names);
|
|
173
|
+
if (problem) throw new Error(`${path.join(glyphs.source, "aliases.json")}:${problem.line}: ${problem.message}`);
|
|
130
174
|
const attributes = glyphs.attributes ?? {};
|
|
131
175
|
const map = {};
|
|
132
|
-
for (const
|
|
133
|
-
const id = name.slice(0, -4);
|
|
176
|
+
for (const id of names) {
|
|
134
177
|
if (Object.hasOwn(aliases, id)) continue;
|
|
135
|
-
|
|
136
|
-
.replace(/<svg\b([^>]*)>/, (_match, own) => {
|
|
137
|
-
const missing = Object.entries(attributes).filter(([key]) => !new RegExp(`(?:^|\\s)${key}=`).test(own)).map(([key, value]) => ` ${key}="${value}"`).join("");
|
|
138
|
-
return `<svg${missing}${own}>`;
|
|
139
|
-
});
|
|
140
|
-
map[id] = svg;
|
|
178
|
+
map[id] = glyphMarkup(readFileSync(path.join(directory, `${id}.svg`), "utf8"), attributes);
|
|
141
179
|
}
|
|
142
|
-
for (const [alias, target] of Object.entries(aliases)) if (!Object.hasOwn(map, target)) throw new Error(`${path.join(glyphs.source, "aliases.json")}: ${alias} names a missing glyph ${target}.`);
|
|
143
180
|
return `// Generated by \`ads assets\` from ${glyphs.source}/. Edit the SVGs, not this file.\n`
|
|
144
181
|
+ `export const glyphs = ${JSON.stringify(map, null, 2)} as const;\n`
|
|
145
182
|
+ `export const glyphAliases = ${JSON.stringify(aliases, null, 2)} as const;\n`;
|
package/dist/brands.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { baseDefinition, nameList, themeDependents } from "./themes.mjs";
|
|
2
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
3
|
+
|
|
4
|
+
// A brand is a named set of token values beside the theme: a theme changes the color mode, a
|
|
5
|
+
// brand changes identity (an accent ramp, a font, a logo choice). Brands are optional; the first
|
|
6
|
+
// declared brand is the default and lives on :root. Every other brand re-values existing tokens
|
|
7
|
+
// on [data-brand="<name>"] only, giving every per-theme half of a themed token it changes. The
|
|
8
|
+
// generated themes.generated.css re-applies them, so a brand section works on the page or on
|
|
9
|
+
// any element, inside any theme, and a default-brand section inside another brand restores the
|
|
10
|
+
// defaults.
|
|
11
|
+
|
|
12
|
+
export function validateBrands(brands) {
|
|
13
|
+
if (!Array.isArray(brands) || brands.length > 8) throw new Error("brands must list up to 8 brands; the first is the default. An empty list (or none) means a single brand.");
|
|
14
|
+
const names = new Set();
|
|
15
|
+
for (const [index, brand] of brands.entries()) {
|
|
16
|
+
const field = `brands[${index}]`;
|
|
17
|
+
if (!brand || typeof brand !== "object" || Array.isArray(brand)) throw new Error(`${field} must be an object with a name.`);
|
|
18
|
+
const unknown = Object.keys(brand).filter(key => key !== "name");
|
|
19
|
+
if (unknown.length) throw new Error(`${field} has unknown keys: ${unknown.join(", ")}.`);
|
|
20
|
+
if (typeof brand.name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(brand.name)) throw new Error(`${field}.name must be a lowercase name such as "acme" or "partner-co".`);
|
|
21
|
+
if (names.has(brand.name)) throw new Error(`Brand "${brand.name}" is declared twice.`);
|
|
22
|
+
names.add(brand.name);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const colorLiteral = /^(?:#[\da-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\()/i;
|
|
27
|
+
const ascending = (a, b) => Number(a.match(/\d+$/)[0]) - Number(b.match(/\d+$/)[0]);
|
|
28
|
+
const brandOwn = (token, brand) => token.definitions.filter(definition => !definition.conditional && definition.brand === brand);
|
|
29
|
+
|
|
30
|
+
/** Brands are declared, re-value only existing tokens, give every half of a themed token they
|
|
31
|
+
* change, re-value tokens that follow the theme only through halves, and re-value whole ramps. */
|
|
32
|
+
export function brandFindings(tokens, brands, themes, { dsDir } = {}) {
|
|
33
|
+
const declared = new Set(brands.map(brand => brand.name));
|
|
34
|
+
const diagnostics = [], advisories = [];
|
|
35
|
+
const finding = (rule, at, message, names) => (findingSeverity(rule) === "error" ? diagnostics : advisories).push({ rule, severity: findingSeverity(rule), file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), guidanceUri: "ads://guides/tokens", message });
|
|
36
|
+
const reported = new Set();
|
|
37
|
+
for (const token of tokens) for (const definition of token.definitions) {
|
|
38
|
+
if (definition.brand === null || declared.has(definition.brand) || reported.has(`${definition.file}:${definition.line}:${definition.brand}`)) continue;
|
|
39
|
+
reported.add(`${definition.file}:${definition.line}:${definition.brand}`);
|
|
40
|
+
diagnostics.push({ rule: "brand-undeclared", file: definition.file, line: definition.line, column: definition.column, message: `${token.name} is set for brand "${definition.brand}", which ds.config.json does not declare (${declared.size ? `brands: ${[...declared].join(", ")}` : "no brands"}). Declare it or fix the name.` });
|
|
41
|
+
}
|
|
42
|
+
if (!brands.length) return { diagnostics, advisories };
|
|
43
|
+
for (const token of tokens) {
|
|
44
|
+
if (baseDefinition(token)) continue;
|
|
45
|
+
const branded = token.definitions.find(definition => !definition.conditional && definition.brand !== null);
|
|
46
|
+
if (branded) finding("brand-new-token", branded, `${token.name} exists only in a brand; brands re-value the default brand's tokens, so define it on :root and change only its value per brand.`, [token.name]);
|
|
47
|
+
}
|
|
48
|
+
const dependent = themeDependents(tokens);
|
|
49
|
+
const ramps = new Map();
|
|
50
|
+
for (const token of tokens) {
|
|
51
|
+
const match = token.name.match(/^(--[\w-]+?)-(\d+)$/), base = baseDefinition(token);
|
|
52
|
+
if (!match || !base || !colorLiteral.test(base.value.trim())) continue;
|
|
53
|
+
if (!ramps.has(match[1])) ramps.set(match[1], []);
|
|
54
|
+
ramps.get(match[1]).push(token);
|
|
55
|
+
}
|
|
56
|
+
for (const brand of brands.slice(1)) {
|
|
57
|
+
const own = token => brandOwn(token, brand.name).length > 0;
|
|
58
|
+
if (!tokens.some(own)) {
|
|
59
|
+
if (dsDir) finding("brand-empty", { file: dsDir, line: 1, column: 1 }, `Brand "${brand.name}" is declared but sets no token values; give it values under [data-brand="${brand.name}"] or remove it from ds.config.json.`);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
// The generated resolver re-resolves tokens that follow the theme on every brand element, over one brand value.
|
|
63
|
+
for (const token of tokens.filter(token => dependent.has(token.name))) {
|
|
64
|
+
const single = brandOwn(token, brand.name).find(definition => definition.theme === null);
|
|
65
|
+
if (single) diagnostics.push({ rule: "brand-theme-value", file: single.file, line: single.line, column: single.column, tokens: [token.name],
|
|
66
|
+
message: `Brand "${brand.name}" sets ${token.name} to one value, but ${token.name} follows the theme; give it per-theme halves (${themes.map(theme => `${token.name}-${theme.name}`).join(", ")}) on :root and under [data-brand="${brand.name}"].` });
|
|
67
|
+
}
|
|
68
|
+
const partial = tokens.filter(token => token.themed && brandOwn(token, brand.name).some(definition => definition.theme !== null)
|
|
69
|
+
&& themes.some(theme => !brandOwn(token, brand.name).some(definition => definition.theme === theme.name)));
|
|
70
|
+
if (partial.length) {
|
|
71
|
+
const names = partial.map(token => token.name), missing = themes.filter(theme => partial.some(token => !brandOwn(token, brand.name).some(definition => definition.theme === theme.name))).map(theme => theme.name);
|
|
72
|
+
finding("brand-coverage", brandOwn(partial[0], brand.name)[0], `Brand "${brand.name}" gives ${nameList(names)} only some of their halves (missing for ${missing.join(", ")}); a brand gives every half of a token it changes, or those themes mix ${brand.name}'s values with the default brand's.`, names);
|
|
73
|
+
}
|
|
74
|
+
for (const [ramp, steps] of ramps) {
|
|
75
|
+
const set = steps.filter(own);
|
|
76
|
+
if (!set.length || set.length === steps.length) continue;
|
|
77
|
+
const missing = steps.filter(step => !own(step)).map(step => step.name).sort(ascending);
|
|
78
|
+
finding("brand-coverage", brandOwn(set[0], brand.name)[0], `Brand "${brand.name}" sets ${set.length} of ${steps.length} ${ramp}-* steps; it also needs ${missing.join(", ")}, or the ramp mixes two brands.`, missing);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { diagnostics, advisories };
|
|
82
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { openPreviewScenario } from "../verification/browser.mjs";
|
|
5
|
+
|
|
6
|
+
// Runs only as an owned child, using the receiving project's browser dependency.
|
|
7
|
+
const request = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
8
|
+
const playwright = createRequire(import.meta.url)(request.playwright);
|
|
9
|
+
const axe = readFileSync(request.axe, "utf8");
|
|
10
|
+
let browser;
|
|
11
|
+
try {
|
|
12
|
+
browser = await playwright[request.settings.browser].launch({ headless: true, ...(request.settings.channel ? { channel: request.settings.channel } : {}) });
|
|
13
|
+
const runs = [], timeout = request.settings.timeoutMs;
|
|
14
|
+
for (const theme of new Set(request.apps.map(app => app.theme))) {
|
|
15
|
+
const apps = request.apps.filter(app => app.theme === theme);
|
|
16
|
+
// The audit injects its own script; bypassCSP keeps project CSP from blocking it.
|
|
17
|
+
const context = await browser.newContext({ viewport: request.viewport, deviceScaleFactor: 1, colorScheme: apps[0].scheme, bypassCSP: true, reducedMotion: "reduce" });
|
|
18
|
+
try {
|
|
19
|
+
for (const app of apps) {
|
|
20
|
+
const page = await context.newPage();
|
|
21
|
+
try {
|
|
22
|
+
const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
|
|
23
|
+
await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
|
|
24
|
+
if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
|
|
25
|
+
await frame.evaluate(async () => {
|
|
26
|
+
await document.fonts.ready;
|
|
27
|
+
await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
|
|
28
|
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
29
|
+
});
|
|
30
|
+
if (!await frame.evaluate(() => !!window.axe)) await frame.addScriptTag({ content: axe });
|
|
31
|
+
const result = await frame.evaluate(async ({ tags, nodeLimit }) => {
|
|
32
|
+
// Scenario content only: the preview status aside and document-level chrome are ADS-owned.
|
|
33
|
+
const outcome = await window.axe.run({ include: [["#root"]], exclude: [["#ads-preview-status"]] }, { runOnly: { type: "tag", values: tags }, resultTypes: ["violations"], elementRef: false, ancestry: false });
|
|
34
|
+
const clip = (text, size) => typeof text === "string" ? text.replace(/\s+/g, " ").trim().slice(0, size) : "";
|
|
35
|
+
return { violations: outcome.violations.map(violation => ({ id: violation.id, impact: violation.impact, tags: violation.tags, help: clip(violation.help, 300), helpUrl: clip(violation.helpUrl, 300), nodeCount: violation.nodes.length,
|
|
36
|
+
nodes: violation.nodes.slice(0, nodeLimit).map(node => ({ selector: clip(node.target.flat().join(" "), 300), html: clip(node.html, 200), summary: clip(node.failureSummary, 500) })) })), incomplete: outcome.incomplete.length };
|
|
37
|
+
}, { tags: request.tags, nodeLimit: request.nodeLimit });
|
|
38
|
+
if (await frame.locator("html").getAttribute("data-ads-preview-state") !== "ready") throw new Error(`Scenario ${app.scenario} stopped being ready during the audit.`);
|
|
39
|
+
runs.push({ scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), ...result });
|
|
40
|
+
} finally { await page.close(); }
|
|
41
|
+
}
|
|
42
|
+
} finally { await context.close(); }
|
|
43
|
+
}
|
|
44
|
+
writeFileSync(path.join(request.output, "report.json"), JSON.stringify({ schemaVersion: 1, runId: request.runId, runs }));
|
|
45
|
+
} finally { await browser?.close(); }
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { loadConfig } from "./config.mjs";
|
|
7
|
+
import { discoverScenarioRegistry } from "./scenario-registry.mjs";
|
|
8
|
+
import { executeDevelopmentCommand } from "./verification.mjs";
|
|
9
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
10
|
+
|
|
11
|
+
// Browser accessibility audit: axe-core (Deque, MPL-2.0, an unmodified ADS dependency
|
|
12
|
+
// injected at run time, never bundled) runs inside each rendered scenario document, once per
|
|
13
|
+
// declared brand and theme. Only the scenario's #root is audited; the preview status chrome is excluded.
|
|
14
|
+
// Findings are errors: they fail `ads audit` and any validation/acceptance policy with
|
|
15
|
+
// browserAudit. Automated rules catch a subset of WCAG failures; passing proves nothing more.
|
|
16
|
+
|
|
17
|
+
export const AUDIT_RULE = "a11y-axe";
|
|
18
|
+
/** WCAG A/AA rule tags. Best-practice and page-level rules (landmarks, one h1) don't fit isolated scenarios. */
|
|
19
|
+
export const auditTags = Object.freeze(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]);
|
|
20
|
+
const viewport = { width: 1280, height: 800 };
|
|
21
|
+
export const auditedKinds = Object.freeze(["components", "patterns", "composition"]);
|
|
22
|
+
const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024 };
|
|
23
|
+
|
|
24
|
+
/** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
|
|
25
|
+
export function wcagCriteria(tags) {
|
|
26
|
+
return [...new Set(tags.map(tag => tag.match(/^wcag(\d)(\d)(\d{1,2})$/)).filter(Boolean).map(([, a, b, c]) => `${a}.${b}.${c}`))];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Collapse per-brand, per-theme axe violations into ADS errors: one per scenario, rule and failing element set. */
|
|
30
|
+
export function auditFindings(runs, scenarios) {
|
|
31
|
+
const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
|
|
32
|
+
const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
|
|
33
|
+
for (const run of runs) for (const violation of run.violations) {
|
|
34
|
+
const selectors = violation.nodes.map(node => node.selector);
|
|
35
|
+
const key = JSON.stringify([run.scenario, violation.id, [...selectors].sort()]);
|
|
36
|
+
const group = groups.get(key) ?? { scenario: run.scenario, themes: [], brands: [], violation };
|
|
37
|
+
groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
|
|
38
|
+
}
|
|
39
|
+
return [...groups.values()].slice(0, limits.findings).map(({ scenario, themes, brands, violation }) => {
|
|
40
|
+
const wcag = wcagCriteria(violation.tags), contrast = violation.id === "color-contrast";
|
|
41
|
+
const where = violation.nodes.map(node => node.selector).slice(0, 3).join(", ") + (violation.nodeCount > 3 ? ` and ${violation.nodeCount - 3} more` : "");
|
|
42
|
+
return {
|
|
43
|
+
rule: AUDIT_RULE, severity: findingSeverity(AUDIT_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "axe-core",
|
|
44
|
+
axeRule: violation.id, impact: violation.impact ?? null, wcag, tags: violation.tags, scenario, themes, ...(brands.length ? { brands } : {}),
|
|
45
|
+
nodes: violation.nodes, nodeCount: violation.nodeCount, helpUrl: violation.helpUrl, guidanceUri: "ads://guides/accessibility",
|
|
46
|
+
...(contrast ? { overlaps: "token-contrast" } : {}),
|
|
47
|
+
message: `${contrast ? "Rendered contrast (browser audit; token-contrast checks declared token pairs statically): " : ""}axe ${violation.id}${violation.impact ? ` (${violation.impact})` : ""}${wcag.length ? `, WCAG ${wcag.join("/")}` : ""} in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${violation.help}. ${violation.nodeCount} element${violation.nodeCount === 1 ? "" : "s"}: ${where}. ${violation.helpUrl}`,
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function projectPlaywright(root) {
|
|
53
|
+
const require = createRequire(path.join(root, "package.json"));
|
|
54
|
+
for (const name of ["@playwright/test", "playwright"]) { try { return require.resolve(name); } catch { /* Try the other supported project-installed entry. */ } }
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Whether the project can run the audit: project-local Playwright, as for captures. */
|
|
59
|
+
export const browserAuditAvailable = root => !!projectPlaywright(path.resolve(root));
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Render every selected scenario in every declared brand and theme and run axe-core on it.
|
|
63
|
+
* Without declared brands it renders the single default brand.
|
|
64
|
+
* Reuses a showcase-serving preview host when given one; otherwise starts and closes its own.
|
|
65
|
+
*/
|
|
66
|
+
export async function runBrowserAudit(root, { scenarios: selected, themes: selectedThemes, brands: selectedBrands, previewHost, signal = new AbortController().signal, onProgress } = {}) {
|
|
67
|
+
root = path.resolve(root);
|
|
68
|
+
const startedAt = Date.now(), options = loadConfig(root);
|
|
69
|
+
const playwright = projectPlaywright(root);
|
|
70
|
+
if (!playwright) throw Object.assign(new Error("The browser accessibility audit requires project-local @playwright/test or playwright and its installed browser. ADS installs neither; mcp.capture selects browser/channel/timeoutMs."), { code: "ADS_AUDIT_UNAVAILABLE" });
|
|
71
|
+
const registry = discoverScenarioRegistry(options);
|
|
72
|
+
if (registry.diagnostics.length) throw new Error(`Scenario registration failed: ${registry.diagnostics[0].message}`);
|
|
73
|
+
const unknown = (selected ?? []).filter(id => !registry.scenarios.some(scenario => scenario.id === id));
|
|
74
|
+
if (unknown.length) throw new Error(`Unknown scenario ${unknown[0]}. Discover exact IDs with ads_scenarios.`);
|
|
75
|
+
// Token and brand scenarios display raw values (token-contrast reviews those pairs); UI scenarios are audited.
|
|
76
|
+
// An explicit selection may still name one.
|
|
77
|
+
const scenarios = registry.scenarios.filter(scenario => selected?.length ? selected.includes(scenario.id) : auditedKinds.includes(scenario.kind)).slice(0, limits.scenarios);
|
|
78
|
+
const themes = options.config.themes.filter(theme => !selectedThemes?.length || selectedThemes.includes(theme.name));
|
|
79
|
+
if (selectedThemes?.length && themes.length !== new Set(selectedThemes).size) throw new Error(`Unknown theme; the project declares ${options.config.themes.map(theme => theme.name).join(", ")}.`);
|
|
80
|
+
const declaredBrands = options.config.brands ?? [];
|
|
81
|
+
if (selectedBrands?.length && !declaredBrands.length) throw new Error("Unknown brand; the project declares no brands.");
|
|
82
|
+
const brands = declaredBrands.filter(brand => !selectedBrands?.length || selectedBrands.includes(brand.name));
|
|
83
|
+
if (selectedBrands?.length && brands.length !== new Set(selectedBrands).size) throw new Error(`Unknown brand; the project declares ${declaredBrands.map(brand => brand.name).join(", ")}.`);
|
|
84
|
+
const summary = { scenarios: scenarios.length, themes: themes.map(theme => theme.name), ...(brands.length ? { brands: brands.map(brand => brand.name) } : {}), tags: auditTags, engine: `axe-core ${axeVersion()}` };
|
|
85
|
+
if (!scenarios.length) return { ...summary, runs: 0, findings: [], elapsedMs: Date.now() - startedAt };
|
|
86
|
+
const outputRoot = path.join(root, ".ds");
|
|
87
|
+
mkdirSync(outputRoot, { recursive: true });
|
|
88
|
+
if (realpathSync(outputRoot) !== outputRoot) throw new Error("Audit work output cannot resolve through a symlink.");
|
|
89
|
+
const temporary = mkdtempSync(path.join(outputRoot, "audit-work-"));
|
|
90
|
+
let host = previewHost;
|
|
91
|
+
try {
|
|
92
|
+
onProgress?.({ stage: "browser-audit", message: `Accessibility audit: building ${scenarios.length} scenario previews.`, elapsedMs: Date.now() - startedAt });
|
|
93
|
+
if (!host?.url) { const { startAdsMcp } = await import("./mcp/server.mjs"); host = await startAdsMcp(root, { stdio: false, showcase: true }); }
|
|
94
|
+
await host.warmScenarios?.(scenarios.map(scenario => scenario.id), signal);
|
|
95
|
+
const apps = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => {
|
|
96
|
+
const url = new URL(host.url); url.searchParams.set("scenario", scenario.id); url.searchParams.set("capture", "1"); url.searchParams.set("theme", theme.name);
|
|
97
|
+
if (brand) url.searchParams.set("brand", brand.name);
|
|
98
|
+
return { scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, url: url.href };
|
|
99
|
+
})));
|
|
100
|
+
const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
|
|
101
|
+
const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
|
|
102
|
+
writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, tags: auditTags, nodeLimit: limits.nodes, apps, output: temporary }));
|
|
103
|
+
onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${apps.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
|
|
104
|
+
const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
|
|
105
|
+
const run = await executeDevelopmentCommand({ command: "runtime", timeoutMs, label: "Accessibility audit" }, [fileURLToPath(new URL("./browser-audit/worker.mjs", import.meta.url)), request], root, {}, signal);
|
|
106
|
+
if (run.code !== 0) throw new Error(`Accessibility audit browser failed (${run.code}): ${run.output.slice(-3000)}`);
|
|
107
|
+
if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) throw new Error("Accessibility audit produced no bounded report.");
|
|
108
|
+
const value = JSON.parse(readFileSync(report, "utf8"));
|
|
109
|
+
if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs) || value.runs.length !== apps.length) throw new Error("Accessibility audit returned the wrong run identity or render count.");
|
|
110
|
+
return { ...summary, runs: value.runs.length, incomplete: value.runs.reduce((sum, item) => sum + item.incomplete, 0), findings: auditFindings(value.runs, scenarios), elapsedMs: Date.now() - startedAt };
|
|
111
|
+
} finally {
|
|
112
|
+
try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const requireTool = createRequire(import.meta.url);
|
|
117
|
+
function axeVersion() { return JSON.parse(readFileSync(requireTool.resolve("axe-core/package.json"), "utf8")).version; }
|
package/dist/capture/worker.mjs
CHANGED
|
@@ -17,6 +17,7 @@ try {
|
|
|
17
17
|
const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
|
|
18
18
|
await frame.locator("html").waitFor({ state: "visible", timeout });
|
|
19
19
|
await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
|
|
20
|
+
if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
|
|
20
21
|
await frame.evaluate(async () => {
|
|
21
22
|
await document.fonts.ready;
|
|
22
23
|
await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
|
package/dist/capture-store.mjs
CHANGED
|
@@ -9,6 +9,8 @@ export const captureSpec = z.object({
|
|
|
9
9
|
scenario: z.string().min(1).max(256), target: z.string().regex(/^[a-zA-Z0-9][\w.-]{0,79}$/).optional(),
|
|
10
10
|
// A declared theme's name; the project's default theme when omitted.
|
|
11
11
|
theme: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/).optional(),
|
|
12
|
+
// A declared brand's name; the project's default brand when omitted. Only with declared brands.
|
|
13
|
+
brand: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/).optional(),
|
|
12
14
|
viewport: z.object({ width: z.number().int().min(100).max(4096), height: z.number().int().min(100).max(4096) }).strict().default({ width: 1280, height: 800 }),
|
|
13
15
|
animations: z.enum(["disabled", "allow"]).default("disabled"),
|
|
14
16
|
}).strict().refine(value => value.viewport.width * value.viewport.height <= captureLimits.pixels, "Capture viewport exceeds 8 megapixels.");
|
package/dist/capture.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { executeDevelopmentCommand } from "./verification.mjs";
|
|
|
11
11
|
import { captureKey, captureSpec, captureLimits, createCaptureStore } from "./capture-store.mjs";
|
|
12
12
|
|
|
13
13
|
export function captureSelections(values) {
|
|
14
|
-
if (!Array.isArray(values) || !values.length || values.length > captureLimits.selections) throw new Error("Select 1–8 exact scenarios/targets with captures:[{scenario,target?,theme?,viewport?}]. Discover IDs with ads_scenarios.");
|
|
14
|
+
if (!Array.isArray(values) || !values.length || values.length > captureLimits.selections) throw new Error("Select 1–8 exact scenarios/targets with captures:[{scenario,target?,theme?,brand?,viewport?}]. Discover IDs with ads_scenarios.");
|
|
15
15
|
const selections = values.map(value => captureSpec.parse(value));
|
|
16
16
|
if (new Set(selections.map(captureKey)).size !== selections.length) throw new Error("Select each scenario/target once; settings replace that target's slots rather than creating extra history.");
|
|
17
17
|
return selections;
|
|
@@ -80,12 +80,15 @@ export function createCaptureController(root) {
|
|
|
80
80
|
const host = previewHosts[projectIndex] ?? await startAdsMcp(project.options.root, { stdio: false, showcase: true });
|
|
81
81
|
if(!previewHosts[projectIndex])ownedHosts.push(host);
|
|
82
82
|
hosts.push(host);
|
|
83
|
-
const themes = project.options.config.themes;
|
|
83
|
+
const themes = project.options.config.themes, brands = project.options.config.brands;
|
|
84
84
|
for (const selection of project.apps) {
|
|
85
85
|
const theme = themes.find(item => item.name === (selection.theme ?? themes[0].name));
|
|
86
86
|
if (!theme) throw new Error(`Unknown theme "${selection.theme}"; the project declares ${themes.map(item => item.name).join(", ")}.`);
|
|
87
|
+
const brand = selection.brand === undefined ? brands[0] : brands.find(item => item.name === selection.brand);
|
|
88
|
+
if (!brand && selection.brand !== undefined) throw new Error(`Unknown brand "${selection.brand}"; ${brands.length ? `the project declares ${brands.map(item => item.name).join(", ")}` : "the project declares no brands"}.`);
|
|
87
89
|
const url = new URL(host.url); url.searchParams.set("scenario", selection.scenario); url.searchParams.set("capture", "1"); url.searchParams.set("theme", theme.name);
|
|
88
|
-
|
|
90
|
+
if (brand) url.searchParams.set("brand", brand.name);
|
|
91
|
+
apps.push({ ...selection, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, projectIndex, url: url.href });
|
|
89
92
|
}
|
|
90
93
|
}
|
|
91
94
|
const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
|
|
@@ -104,7 +107,7 @@ export function createCaptureController(root) {
|
|
|
104
107
|
const bytes = readFileSync(file), metadata = await sharp(bytes).metadata();
|
|
105
108
|
if (metadata.format !== "png" || !metadata.width || !metadata.height || metadata.width * metadata.height > captureLimits.pixels) throw new Error("Screenshot output exceeds 8 megapixels or is not PNG.");
|
|
106
109
|
const project = projects[app.projectIndex];
|
|
107
|
-
images.set(`${app.projectIndex}:${app.selectionIndex}`, { mimeType: "image/png", blob: bytes.toString("base64"), digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, width: metadata.width, height: metadata.height, bytes: bytes.length, capturedAt: value.images[index].capturedAt, sourceRevision: project.revision, buildRevision: hosts[app.projectIndex].previewRevision(), settings: { theme: app.theme, viewport: app.viewport, animations: app.animations, browser: settings.browser, ...(settings.channel ? { channel: settings.channel } : {}), scale: "css" }, scenarioFile: app.scenarioFile, fixtureFile: app.fixtureFile });
|
|
110
|
+
images.set(`${app.projectIndex}:${app.selectionIndex}`, { mimeType: "image/png", blob: bytes.toString("base64"), digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, width: metadata.width, height: metadata.height, bytes: bytes.length, capturedAt: value.images[index].capturedAt, sourceRevision: project.revision, buildRevision: hosts[app.projectIndex].previewRevision(), settings: { theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), viewport: app.viewport, animations: app.animations, browser: settings.browser, ...(settings.channel ? { channel: settings.channel } : {}), scale: "css" }, scenarioFile: app.scenarioFile, fixtureFile: app.fixtureFile });
|
|
108
111
|
}
|
|
109
112
|
for (const project of projects) if (previewSourceRevision(loadConfig(project.options.root)) !== project.revision) throw new Error("Project inputs changed while capturing. No capture slots were replaced; retry against current source.");
|
|
110
113
|
if (signal.aborted) throw new Error("Screenshot capture cancelled before publication.");
|